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
10b25f25008e003b9cc0d427ffc276d04b43baa1
3dd1b66af77106badae6edb1c4dea91a146ead30
/tests/lean/run/cody2.lean
ac356b33d440751344a012d6be5de0a316c67b68
[ "Apache-2.0" ]
permissive
silky/lean
79c20c15c93feef47bb659a2cc139b26f3614642
df8b88dca2f8da1a422cb618cd476ef5be730546
refs/heads/master
1,610,737,587,697
1,406,574,534,000
1,406,574,534,000
22,362,176
1
0
null
null
null
null
UTF-8
Lean
false
false
425
lean
import logic abbreviation subsets (P : Type) := P → Prop. section hypothesis A : Type. hypothesis r : A → subsets A. hypothesis i : subsets A → A. hypothesis retract {P : subsets A} {a : A} : r (i P) a = P a. definition delta (a:A) : Prop := ¬ (r a a). notation `δ` := delta. theorem delta_aux : ¬ (δ (i delta)) := assume H : δ (i delta), H (subst (symm retract) H). check delta_aux.
c3cca82c9867ea6b322d80fc8080164adc9748ca
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebra/ring/ulift.lean
e39ea0479ab0aa38fb4f60a9072761073c658ff8
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
5,151
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 algebra.group.ulift import algebra.ring.equiv /-! # `ulift` instances for ring This file defines instances for ring, semiring and related structures on `ulift` types. (Recall `ulift α` is just a "copy" of a type `α` in a higher universe.) We also provide `ulift.ring_equiv : ulift R ≃+* R`. -/ universes u v variables {α : Type u} {x y : ulift.{v} α} namespace ulift instance mul_zero_class [mul_zero_class α] : mul_zero_class (ulift α) := by refine_struct { zero := (0 : ulift α), mul := (*), .. }; tactic.pi_instance_derive_field instance distrib [distrib α] : distrib (ulift α) := by refine_struct { add := (+), mul := (*), .. }; tactic.pi_instance_derive_field instance non_unital_non_assoc_semiring [non_unital_non_assoc_semiring α] : non_unital_non_assoc_semiring (ulift α) := by refine_struct { zero := (0 : ulift α), add := (+), mul := (*), nsmul := add_monoid.nsmul, }; tactic.pi_instance_derive_field instance non_assoc_semiring [non_assoc_semiring α] : non_assoc_semiring (ulift α) := by refine_struct { zero := (0 : ulift α), one := 1, add := (+), mul := (*), nsmul := add_monoid.nsmul, .. ulift.add_monoid_with_one }; tactic.pi_instance_derive_field instance non_unital_semiring [non_unital_semiring α] : non_unital_semiring (ulift α) := by refine_struct { zero := (0 : ulift α), add := (+), mul := (*), nsmul := add_monoid.nsmul, }; tactic.pi_instance_derive_field instance semiring [semiring α] : semiring (ulift α) := by refine_struct { zero := (0 : ulift α), one := 1, add := (+), mul := (*), nsmul := add_monoid.nsmul, npow := monoid.npow, .. ulift.add_monoid_with_one }; tactic.pi_instance_derive_field /-- The ring equivalence between `ulift α` and `α`. -/ def ring_equiv [non_unital_non_assoc_semiring α] : ulift α ≃+* α := { to_fun := ulift.down, inv_fun := ulift.up, map_mul' := λ x y, rfl, map_add' := λ x y, rfl, left_inv := by tidy, right_inv := by tidy, } instance non_unital_comm_semiring [non_unital_comm_semiring α] : non_unital_comm_semiring (ulift α) := by refine_struct { zero := (0 : ulift α), add := (+), mul := (*), nsmul := add_monoid.nsmul }; tactic.pi_instance_derive_field instance comm_semiring [comm_semiring α] : comm_semiring (ulift α) := by refine_struct { zero := (0 : ulift α), one := 1, add := (+), mul := (*), nsmul := add_monoid.nsmul, npow := monoid.npow, .. ulift.semiring }; tactic.pi_instance_derive_field instance non_unital_non_assoc_ring [non_unital_non_assoc_ring α] : non_unital_non_assoc_ring (ulift α) := by refine_struct { zero := (0 : ulift α), add := (+), mul := (*), sub := has_sub.sub, neg := has_neg.neg, nsmul := add_monoid.nsmul, zsmul := sub_neg_monoid.zsmul }; tactic.pi_instance_derive_field instance non_unital_ring [non_unital_ring α] : non_unital_ring (ulift α) := by refine_struct { zero := (0 : ulift α), add := (+), mul := (*), sub := has_sub.sub, neg := has_neg.neg, nsmul := add_monoid.nsmul, zsmul := sub_neg_monoid.zsmul }; tactic.pi_instance_derive_field instance non_assoc_ring [non_assoc_ring α] : non_assoc_ring (ulift α) := by refine_struct { zero := (0 : ulift α), one := 1, add := (+), mul := (*), sub := has_sub.sub, neg := has_neg.neg, nsmul := add_monoid.nsmul, zsmul := sub_neg_monoid.zsmul, .. ulift.add_group_with_one }; tactic.pi_instance_derive_field instance ring [ring α] : ring (ulift α) := by refine_struct { zero := (0 : ulift α), one := 1, add := (+), mul := (*), sub := has_sub.sub, neg := has_neg.neg, nsmul := add_monoid.nsmul, npow := monoid.npow, zsmul := sub_neg_monoid.zsmul, .. ulift.semiring, .. ulift.add_group_with_one }; tactic.pi_instance_derive_field instance non_unital_comm_ring [non_unital_comm_ring α] : non_unital_comm_ring (ulift α) := by refine_struct { zero := (0 : ulift α), add := (+), mul := (*), sub := has_sub.sub, neg := has_neg.neg, nsmul := add_monoid.nsmul, zsmul := sub_neg_monoid.zsmul }; tactic.pi_instance_derive_field instance comm_ring [comm_ring α] : comm_ring (ulift α) := by refine_struct { .. ulift.ring }; tactic.pi_instance_derive_field instance [has_rat_cast α] : has_rat_cast (ulift α) := ⟨λ a, ulift.up (coe a)⟩ @[simp] lemma rat_cast_down [has_rat_cast α] (n : ℚ) : ulift.down (n : ulift α) = n := rfl instance field [field α] : field (ulift α) := begin have of_rat_mk : ∀ a b h1 h2, ((⟨a, b, h1, h2⟩ : ℚ) : ulift α) = ↑a * (↑b)⁻¹, { intros a b h1 h2, ext, rw [rat_cast_down, mul_down, inv_down, nat_cast_down, int_cast_down], exact field.rat_cast_mk a b h1 h2 }, refine_struct { zero := (0 : ulift α), inv := has_inv.inv, div := has_div.div, zpow := λ n a, ulift.up (a.down ^ n), rat_cast := coe, rat_cast_mk := of_rat_mk, qsmul := (•), .. @ulift.nontrivial α _, .. ulift.comm_ring }; tactic.pi_instance_derive_field, -- `mul_inv_cancel` requires special attention: it leaves the goal `∀ {a}, a ≠ 0 → a * a⁻¹ = 1`. cases a, tauto end end ulift
31e2571e34123fc17bc118a2405b08b44854dbed
63abd62053d479eae5abf4951554e1064a4c45b4
/src/topology/local_homeomorph.lean
0b98b81626be8b9589a8da93fd9d931e66ceea6a
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
37,806
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import data.equiv.local_equiv import topology.opens /-! # Local homeomorphisms This file defines homeomorphisms between open subsets of topological spaces. An element `e` of `local_homeomorph α β` is an extension of `local_equiv α β`, i.e., it is a pair of functions `e.to_fun` and `e.inv_fun`, inverse of each other on the sets `e.source` and `e.target`. Additionally, we require that these sets are open, and that the functions are continuous on them. Equivalently, they are homeomorphisms there. As in equivs, we register a coercion to functions, and we use `e x` and `e.symm x` throughout instead of `e.to_fun x` and `e.inv_fun x`. ## Main definitions `homeomorph.to_local_homeomorph`: associating a local homeomorphism to a homeomorphism, with source = target = univ `local_homeomorph.symm` : the inverse of a local homeomorphism `local_homeomorph.trans` : the composition of two local homeomorphisms `local_homeomorph.refl` : the identity local homeomorphism `local_homeomorph.of_set`: the identity on a set `s` `eq_on_source` : equivalence relation describing the "right" notion of equality for local homeomorphisms ## Implementation notes Most statements are copied from their local_equiv versions, although some care is required especially when restricting to subsets, as these should be open subsets. For design notes, see `local_equiv.lean`. -/ open function set open_locale topological_space variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] /-- local homeomorphisms, defined on open subsets of the space -/ @[nolint has_inhabited_instance] structure local_homeomorph (α : Type*) (β : Type*) [topological_space α] [topological_space β] extends local_equiv α β := (open_source : is_open source) (open_target : is_open target) (continuous_to_fun : continuous_on to_fun source) (continuous_inv_fun : continuous_on inv_fun target) /-- A homeomorphism induces a local homeomorphism on the whole space -/ def homeomorph.to_local_homeomorph (e : homeomorph α β) : local_homeomorph α β := { open_source := is_open_univ, open_target := is_open_univ, continuous_to_fun := by { erw ← continuous_iff_continuous_on_univ, exact e.continuous_to_fun }, continuous_inv_fun := by { erw ← continuous_iff_continuous_on_univ, exact e.continuous_inv_fun }, ..e.to_equiv.to_local_equiv } namespace local_homeomorph variables (e : local_homeomorph α β) (e' : local_homeomorph β γ) instance : has_coe_to_fun (local_homeomorph α β) := ⟨_, λ e, e.to_local_equiv.to_fun⟩ /-- The inverse of a local homeomorphism -/ protected def symm : local_homeomorph β α := { open_source := e.open_target, open_target := e.open_source, continuous_to_fun := e.continuous_inv_fun, continuous_inv_fun := e.continuous_to_fun, ..e.to_local_equiv.symm } protected lemma continuous_on : continuous_on e e.source := e.continuous_to_fun lemma continuous_on_symm : continuous_on e.symm e.target := e.continuous_inv_fun @[simp, mfld_simps] lemma mk_coe (e : local_equiv α β) (a b c d) : (local_homeomorph.mk e a b c d : α → β) = e := rfl @[simp, mfld_simps] lemma mk_coe_symm (e : local_equiv α β) (a b c d) : ((local_homeomorph.mk e a b c d).symm : β → α) = e.symm := rfl /- Register a few simp lemmas to make sure that `simp` puts the application of a local homeomorphism in its normal form, i.e., in terms of its coercion to a function. -/ @[simp, mfld_simps] lemma to_fun_eq_coe (e : local_homeomorph α β) : e.to_fun = e := rfl @[simp, mfld_simps] lemma inv_fun_eq_coe (e : local_homeomorph α β) : e.inv_fun = e.symm := rfl @[simp, mfld_simps] lemma coe_coe : (e.to_local_equiv : α → β) = e := rfl @[simp, mfld_simps] lemma coe_coe_symm : (e.to_local_equiv.symm : β → α) = e.symm := rfl @[simp, mfld_simps] lemma map_source {x : α} (h : x ∈ e.source) : e x ∈ e.target := e.map_source' h @[simp, mfld_simps] lemma map_target {x : β} (h : x ∈ e.target) : e.symm x ∈ e.source := e.map_target' h @[simp, mfld_simps] lemma left_inv {x : α} (h : x ∈ e.source) : e.symm (e x) = x := e.left_inv' h @[simp, mfld_simps] lemma right_inv {x : β} (h : x ∈ e.target) : e (e.symm x) = x := e.right_inv' h lemma source_preimage_target : e.source ⊆ e ⁻¹' e.target := λ _ h, map_source e h lemma eq_of_local_equiv_eq {e e' : local_homeomorph α β} (h : e.to_local_equiv = e'.to_local_equiv) : e = e' := begin cases e, cases e', dsimp at *, induction h, refl end lemma eventually_left_inverse (e : local_homeomorph α β) {x} (hx : x ∈ e.source) : ∀ᶠ y in 𝓝 x, e.symm (e y) = y := filter.eventually.mono (mem_nhds_sets e.open_source hx) e.left_inv' lemma eventually_left_inverse' (e : local_homeomorph α β) {x} (hx : x ∈ e.target) : ∀ᶠ y in 𝓝 (e.symm x), e.symm (e y) = y := e.eventually_left_inverse (e.map_target hx) lemma eventually_right_inverse (e : local_homeomorph α β) {x} (hx : x ∈ e.target) : ∀ᶠ y in 𝓝 x, e (e.symm y) = y := filter.eventually.mono (mem_nhds_sets e.open_target hx) e.right_inv' lemma eventually_right_inverse' (e : local_homeomorph α β) {x} (hx : x ∈ e.source) : ∀ᶠ y in 𝓝 (e x), e (e.symm y) = y := e.eventually_right_inverse (e.map_source hx) lemma image_eq_target_inter_inv_preimage {s : set α} (h : s ⊆ e.source) : e '' s = e.target ∩ e.symm ⁻¹' s := e.to_local_equiv.image_eq_target_inter_inv_preimage h lemma image_inter_source_eq (s : set α) : e '' (s ∩ e.source) = e.target ∩ e.symm ⁻¹' (s ∩ e.source) := e.image_eq_target_inter_inv_preimage (inter_subset_right _ _) lemma symm_image_eq_source_inter_preimage {s : set β} (h : s ⊆ e.target) : e.symm '' s = e.source ∩ e ⁻¹' s := e.symm.image_eq_target_inter_inv_preimage h lemma symm_image_inter_target_eq (s : set β) : e.symm '' (s ∩ e.target) = e.source ∩ e ⁻¹' (s ∩ e.target) := e.symm.image_inter_source_eq _ /-- Two local homeomorphisms are equal when they have equal `to_fun`, `inv_fun` and `source`. It is not sufficient to have equal `to_fun` and `source`, as this only determines `inv_fun` on the target. This would only be true for a weaker notion of equality, arguably the right one, called `eq_on_source`. -/ @[ext] protected lemma ext (e' : local_homeomorph α β) (h : ∀x, e x = e' x) (hinv : ∀x, e.symm x = e'.symm x) (hs : e.source = e'.source) : e = e' := eq_of_local_equiv_eq (local_equiv.ext h hinv hs) @[simp, mfld_simps] lemma symm_to_local_equiv : e.symm.to_local_equiv = e.to_local_equiv.symm := rfl -- The following lemmas are already simp via local_equiv lemma symm_source : e.symm.source = e.target := rfl lemma symm_target : e.symm.target = e.source := rfl @[simp, mfld_simps] lemma symm_symm : e.symm.symm = e := eq_of_local_equiv_eq $ by simp /-- A local homeomorphism is continuous at any point of its source -/ protected lemma continuous_at {x : α} (h : x ∈ e.source) : continuous_at e x := (e.continuous_on x h).continuous_at (mem_nhds_sets e.open_source h) /-- A local homeomorphism inverse is continuous at any point of its target -/ lemma continuous_at_symm {x : β} (h : x ∈ e.target) : continuous_at e.symm x := e.symm.continuous_at h lemma tendsto_symm (e : local_homeomorph α β) {x} (hx : x ∈ e.source) : filter.tendsto e.symm (𝓝 (e x)) (𝓝 x) := by simpa only [continuous_at, e.left_inv hx] using e.continuous_at_symm (e.map_source hx) /-- Preimage of interior or interior of preimage coincide for local homeomorphisms, when restricted to the source. -/ lemma preimage_interior (s : set β) : e.source ∩ e ⁻¹' (interior s) = e.source ∩ interior (e ⁻¹' s) := begin apply subset.antisymm, { exact e.continuous_on.preimage_interior_subset_interior_preimage e.open_source }, { calc e.source ∩ interior (e ⁻¹' s) = (e.source ∩ interior (e ⁻¹' s)) ∩ (e ⁻¹' e.target) : by mfld_set_tac ... = (e.source ∩ e ⁻¹' (e.symm ⁻¹' (interior (e ⁻¹' s)))) ∩ (e ⁻¹' e.target) : begin have := e.to_local_equiv.source_inter_preimage_inv_preimage _, simp only [coe_coe_symm, coe_coe] at this, rw this end ... = e.source ∩ e ⁻¹' (e.target ∩ e.symm ⁻¹' (interior (e ⁻¹' s))) : by rw [inter_comm e.target, preimage_inter, inter_assoc] ... ⊆ e.source ∩ e ⁻¹' (e.target ∩ interior (e.symm ⁻¹' (e ⁻¹' s))) : begin apply inter_subset_inter (subset.refl _) (preimage_mono _), exact e.continuous_on_symm.preimage_interior_subset_interior_preimage e.open_target end ... = e.source ∩ e ⁻¹' (interior (e.target ∩ e.symm ⁻¹' (e ⁻¹' s))) : by rw [interior_inter, e.open_target.interior_eq] ... = e.source ∩ e ⁻¹' (interior (e.target ∩ s)) : begin have := e.to_local_equiv.target_inter_inv_preimage_preimage, simp only [coe_coe_symm, coe_coe] at this, rw this end ... = e.source ∩ e ⁻¹' e.target ∩ e ⁻¹' (interior s) : by rw [interior_inter, preimage_inter, e.open_target.interior_eq, inter_assoc] ... = e.source ∩ e ⁻¹' (interior s) : by mfld_set_tac } end lemma preimage_open_of_open {s : set β} (hs : is_open s) : is_open (e.source ∩ e ⁻¹' s) := e.continuous_on.preimage_open_of_open e.open_source hs lemma preimage_open_of_open_symm {s : set α} (hs : is_open s) : is_open (e.target ∩ e.symm ⁻¹' s) := e.symm.continuous_on.preimage_open_of_open e.open_target hs /-- The image of an open set in the source is open. -/ lemma image_open_of_open {s : set α} (hs : is_open s) (h : s ⊆ e.source) : is_open (e '' s) := begin have : e '' s = e.target ∩ e.symm ⁻¹' s := e.to_local_equiv.image_eq_target_inter_inv_preimage h, rw this, exact e.continuous_on_symm.preimage_open_of_open e.open_target hs end /-- The image of the restriction of an open set to the source is open. -/ lemma image_open_of_open' {s : set α} (hs : is_open s) : is_open (e '' (s ∩ e.source)) := begin refine image_open_of_open _ (is_open_inter hs e.open_source) _, simp, end /-- Restricting a local homeomorphism `e` to `e.source ∩ s` when `s` is open. This is sometimes hard to use because of the openness assumption, but it has the advantage that when it can be used then its local_equiv is defeq to local_equiv.restr -/ protected def restr_open (s : set α) (hs : is_open s) : local_homeomorph α β := { open_source := is_open_inter e.open_source hs, open_target := (continuous_on_open_iff e.open_target).1 e.continuous_inv_fun s hs, continuous_to_fun := e.continuous_to_fun.mono (inter_subset_left _ _), continuous_inv_fun := e.continuous_inv_fun.mono (inter_subset_left _ _), ..e.to_local_equiv.restr s} @[simp, mfld_simps] lemma restr_open_to_local_equiv (s : set α) (hs : is_open s) : (e.restr_open s hs).to_local_equiv = e.to_local_equiv.restr s := rfl -- Already simp via local_equiv lemma restr_open_source (s : set α) (hs : is_open s) : (e.restr_open s hs).source = e.source ∩ s := rfl /-- Restricting a local homeomorphism `e` to `e.source ∩ interior s`. We use the interior to make sure that the restriction is well defined whatever the set s, since local homeomorphisms are by definition defined on open sets. In applications where `s` is open, this coincides with the restriction of local equivalences -/ protected def restr (s : set α) : local_homeomorph α β := e.restr_open (interior s) is_open_interior @[simp, mfld_simps] lemma restr_to_local_equiv (s : set α) : (e.restr s).to_local_equiv = (e.to_local_equiv).restr (interior s) := rfl @[simp, mfld_simps] lemma restr_coe (s : set α) : (e.restr s : α → β) = e := rfl @[simp, mfld_simps] lemma restr_coe_symm (s : set α) : ((e.restr s).symm : β → α) = e.symm := rfl lemma restr_source (s : set α) : (e.restr s).source = e.source ∩ interior s := rfl lemma restr_target (s : set α) : (e.restr s).target = e.target ∩ e.symm ⁻¹' (interior s) := rfl lemma restr_source' (s : set α) (hs : is_open s) : (e.restr s).source = e.source ∩ s := by rw [e.restr_source, hs.interior_eq] lemma restr_to_local_equiv' (s : set α) (hs : is_open s): (e.restr s).to_local_equiv = e.to_local_equiv.restr s := by rw [e.restr_to_local_equiv, hs.interior_eq] lemma restr_eq_of_source_subset {e : local_homeomorph α β} {s : set α} (h : e.source ⊆ s) : e.restr s = e := begin apply eq_of_local_equiv_eq, rw restr_to_local_equiv, apply local_equiv.restr_eq_of_source_subset, have := interior_mono h, rwa e.open_source.interior_eq at this end @[simp, mfld_simps] lemma restr_univ {e : local_homeomorph α β} : e.restr univ = e := restr_eq_of_source_subset (subset_univ _) lemma restr_source_inter (s : set α) : e.restr (e.source ∩ s) = e.restr s := begin refine local_homeomorph.ext _ _ (λx, rfl) (λx, rfl) _, simp [e.open_source.interior_eq], rw [← inter_assoc, inter_self] end /-- The identity on the whole space as a local homeomorphism. -/ protected def refl (α : Type*) [topological_space α] : local_homeomorph α α := (homeomorph.refl α).to_local_homeomorph @[simp, mfld_simps] lemma refl_local_equiv : (local_homeomorph.refl α).to_local_equiv = local_equiv.refl α := rfl lemma refl_source : (local_homeomorph.refl α).source = univ := rfl lemma refl_target : (local_homeomorph.refl α).target = univ := rfl @[simp, mfld_simps] lemma refl_symm : (local_homeomorph.refl α).symm = local_homeomorph.refl α := rfl @[simp, mfld_simps] lemma refl_coe : (local_homeomorph.refl α : α → α) = id := rfl section variables {s : set α} (hs : is_open s) /-- The identity local equiv on a set `s` -/ def of_set (s : set α) (hs : is_open s) : local_homeomorph α α := { open_source := hs, open_target := hs, continuous_to_fun := continuous_id.continuous_on, continuous_inv_fun := continuous_id.continuous_on, ..local_equiv.of_set s } @[simp, mfld_simps] lemma of_set_to_local_equiv : (of_set s hs).to_local_equiv = local_equiv.of_set s := rfl lemma of_set_source : (of_set s hs).source = s := rfl lemma of_set_target : (of_set s hs).target = s := rfl @[simp, mfld_simps] lemma of_set_coe : (of_set s hs : α → α) = id := rfl @[simp, mfld_simps] lemma of_set_symm : (of_set s hs).symm = of_set s hs := rfl @[simp, mfld_simps] lemma of_set_univ_eq_refl : of_set univ is_open_univ = local_homeomorph.refl α := by ext; simp end /-- Composition of two local homeomorphisms when the target of the first and the source of the second coincide. -/ protected def trans' (h : e.target = e'.source) : local_homeomorph α γ := { open_source := e.open_source, open_target := e'.open_target, continuous_to_fun := begin apply continuous_on.comp e'.continuous_to_fun e.continuous_to_fun, rw ← h, exact e.to_local_equiv.source_subset_preimage_target end, continuous_inv_fun := begin apply continuous_on.comp e.continuous_inv_fun e'.continuous_inv_fun, rw h, exact e'.to_local_equiv.target_subset_preimage_source end, ..local_equiv.trans' e.to_local_equiv e'.to_local_equiv h } /-- Composing two local homeomorphisms, by restricting to the maximal domain where their composition is well defined. -/ protected def trans : local_homeomorph α γ := local_homeomorph.trans' (e.symm.restr_open e'.source e'.open_source).symm (e'.restr_open e.target e.open_target) (by simp [inter_comm]) @[simp, mfld_simps] lemma trans_to_local_equiv : (e.trans e').to_local_equiv = e.to_local_equiv.trans e'.to_local_equiv := rfl @[simp, mfld_simps] lemma coe_trans : (e.trans e' : α → γ) = e' ∘ e := rfl @[simp, mfld_simps] lemma coe_trans_symm : ((e.trans e').symm : γ → α) = e.symm ∘ e'.symm := rfl lemma trans_symm_eq_symm_trans_symm : (e.trans e').symm = e'.symm.trans e.symm := by cases e; cases e'; refl /- This could be considered as a simp lemma, but there are many situations where it makes something simple into something more complicated. -/ lemma trans_source : (e.trans e').source = e.source ∩ e ⁻¹' e'.source := local_equiv.trans_source e.to_local_equiv e'.to_local_equiv lemma trans_source' : (e.trans e').source = e.source ∩ e ⁻¹' (e.target ∩ e'.source) := local_equiv.trans_source' e.to_local_equiv e'.to_local_equiv lemma trans_source'' : (e.trans e').source = e.symm '' (e.target ∩ e'.source) := local_equiv.trans_source'' e.to_local_equiv e'.to_local_equiv lemma image_trans_source : e '' (e.trans e').source = e.target ∩ e'.source := local_equiv.image_trans_source e.to_local_equiv e'.to_local_equiv lemma trans_target : (e.trans e').target = e'.target ∩ e'.symm ⁻¹' e.target := rfl lemma trans_target' : (e.trans e').target = e'.target ∩ e'.symm ⁻¹' (e'.source ∩ e.target) := trans_source' e'.symm e.symm lemma trans_target'' : (e.trans e').target = e' '' (e'.source ∩ e.target) := trans_source'' e'.symm e.symm lemma inv_image_trans_target : e'.symm '' (e.trans e').target = e'.source ∩ e.target := image_trans_source e'.symm e.symm lemma trans_assoc (e'' : local_homeomorph γ δ) : (e.trans e').trans e'' = e.trans (e'.trans e'') := eq_of_local_equiv_eq $ local_equiv.trans_assoc e.to_local_equiv e'.to_local_equiv e''.to_local_equiv @[simp, mfld_simps] lemma trans_refl : e.trans (local_homeomorph.refl β) = e := eq_of_local_equiv_eq $ local_equiv.trans_refl e.to_local_equiv @[simp, mfld_simps] lemma refl_trans : (local_homeomorph.refl α).trans e = e := eq_of_local_equiv_eq $ local_equiv.refl_trans e.to_local_equiv lemma trans_of_set {s : set β} (hs : is_open s) : e.trans (of_set s hs) = e.restr (e ⁻¹' s) := local_homeomorph.ext _ _ (λx, rfl) (λx, rfl) $ by simp [local_equiv.trans_source, (e.preimage_interior _).symm, hs.interior_eq] lemma trans_of_set' {s : set β} (hs : is_open s) : e.trans (of_set s hs) = e.restr (e.source ∩ e ⁻¹' s) := by rw [trans_of_set, restr_source_inter] lemma of_set_trans {s : set α} (hs : is_open s) : (of_set s hs).trans e = e.restr s := local_homeomorph.ext _ _ (λx, rfl) (λx, rfl) $ by simp [local_equiv.trans_source, hs.interior_eq, inter_comm] lemma of_set_trans' {s : set α} (hs : is_open s) : (of_set s hs).trans e = e.restr (e.source ∩ s) := by rw [of_set_trans, restr_source_inter] @[simp, mfld_simps] lemma of_set_trans_of_set {s : set α} (hs : is_open s) {s' : set α} (hs' : is_open s') : (of_set s hs).trans (of_set s' hs') = of_set (s ∩ s') (is_open_inter hs hs') := begin rw (of_set s hs).trans_of_set hs', ext; simp [hs'.interior_eq] end lemma restr_trans (s : set α) : (e.restr s).trans e' = (e.trans e').restr s := eq_of_local_equiv_eq $ local_equiv.restr_trans e.to_local_equiv e'.to_local_equiv (interior s) /-- `eq_on_source e e'` means that `e` and `e'` have the same source, and coincide there. They should really be considered the same local equiv. -/ def eq_on_source (e e' : local_homeomorph α β) : Prop := e.source = e'.source ∧ (eq_on e e' e.source) lemma eq_on_source_iff (e e' : local_homeomorph α β) : eq_on_source e e' ↔ local_equiv.eq_on_source e.to_local_equiv e'.to_local_equiv := iff.rfl /-- `eq_on_source` is an equivalence relation -/ instance : setoid (local_homeomorph α β) := { r := eq_on_source, iseqv := ⟨ λe, (@local_equiv.eq_on_source_setoid α β).iseqv.1 e.to_local_equiv, λe e' h, (@local_equiv.eq_on_source_setoid α β).iseqv.2.1 ((eq_on_source_iff e e').1 h), λe e' e'' h h', (@local_equiv.eq_on_source_setoid α β).iseqv.2.2 ((eq_on_source_iff e e').1 h) ((eq_on_source_iff e' e'').1 h')⟩ } lemma eq_on_source_refl : e ≈ e := setoid.refl _ /-- If two local homeomorphisms are equivalent, so are their inverses -/ lemma eq_on_source.symm' {e e' : local_homeomorph α β} (h : e ≈ e') : e.symm ≈ e'.symm := local_equiv.eq_on_source.symm' h /-- Two equivalent local homeomorphisms have the same source -/ lemma eq_on_source.source_eq {e e' : local_homeomorph α β} (h : e ≈ e') : e.source = e'.source := h.1 /-- Two equivalent local homeomorphisms have the same target -/ lemma eq_on_source.target_eq {e e' : local_homeomorph α β} (h : e ≈ e') : e.target = e'.target := h.symm'.1 /-- Two equivalent local homeomorphisms have coinciding `to_fun` on the source -/ lemma eq_on_source.eq_on {e e' : local_homeomorph α β} (h : e ≈ e') : eq_on e e' e.source := h.2 /-- Two equivalent local homeomorphisms have coinciding `inv_fun` on the target -/ lemma eq_on_source.symm_eq_on_target {e e' : local_homeomorph α β} (h : e ≈ e') : eq_on e.symm e'.symm e.target := h.symm'.2 /-- Composition of local homeomorphisms respects equivalence -/ lemma eq_on_source.trans' {e e' : local_homeomorph α β} {f f' : local_homeomorph β γ} (he : e ≈ e') (hf : f ≈ f') : e.trans f ≈ e'.trans f' := local_equiv.eq_on_source.trans' he hf /-- Restriction of local homeomorphisms respects equivalence -/ lemma eq_on_source.restr {e e' : local_homeomorph α β} (he : e ≈ e') (s : set α) : e.restr s ≈ e'.restr s := local_equiv.eq_on_source.restr he _ /-- Composition of a local homeomorphism and its inverse is equivalent to the restriction of the identity to the source -/ lemma trans_self_symm : e.trans e.symm ≈ local_homeomorph.of_set e.source e.open_source := local_equiv.trans_self_symm _ lemma trans_symm_self : e.symm.trans e ≈ local_homeomorph.of_set e.target e.open_target := e.symm.trans_self_symm lemma eq_of_eq_on_source_univ {e e' : local_homeomorph α β} (h : e ≈ e') (s : e.source = univ) (t : e.target = univ) : e = e' := eq_of_local_equiv_eq $ local_equiv.eq_of_eq_on_source_univ _ _ h s t section prod /-- The product of two local homeomorphisms, as a local homeomorphism on the product space. -/ def prod (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : local_homeomorph (α × γ) (β × δ) := { open_source := e.open_source.prod e'.open_source, open_target := e.open_target.prod e'.open_target, continuous_to_fun := continuous_on.prod (e.continuous_to_fun.comp continuous_fst.continuous_on (prod_subset_preimage_fst _ _)) (e'.continuous_to_fun.comp continuous_snd.continuous_on (prod_subset_preimage_snd _ _)), continuous_inv_fun := continuous_on.prod (e.continuous_inv_fun.comp continuous_fst.continuous_on (prod_subset_preimage_fst _ _)) (e'.continuous_inv_fun.comp continuous_snd.continuous_on (prod_subset_preimage_snd _ _)), ..e.to_local_equiv.prod e'.to_local_equiv } @[simp, mfld_simps] lemma prod_to_local_equiv (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : (e.prod e').to_local_equiv = e.to_local_equiv.prod e'.to_local_equiv := rfl lemma prod_source (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : (e.prod e').source = set.prod e.source e'.source := rfl lemma prod_target (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : (e.prod e').target = set.prod e.target e'.target := rfl @[simp, mfld_simps] lemma prod_coe (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : (e.prod e' : α × γ → β × δ) = λp, (e p.1, e' p.2) := rfl lemma prod_coe_symm (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : ((e.prod e').symm : β × δ → α × γ) = λp, (e.symm p.1, e'.symm p.2) := rfl @[simp, mfld_simps] lemma prod_symm (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : (e.prod e').symm = (e.symm.prod e'.symm) := by ext x; simp [prod_coe_symm] @[simp, mfld_simps] lemma prod_trans {η : Type*} {ε : Type*} [topological_space η] [topological_space ε] (e : local_homeomorph α β) (f : local_homeomorph β γ) (e' : local_homeomorph δ η) (f' : local_homeomorph η ε) : (e.prod e').trans (f.prod f') = (e.trans f).prod (e'.trans f') := by ext x; simp [ext_iff]; tauto end prod section continuity /-- Continuity within a set at a point can be read under right composition with a local homeomorphism, if the point is in its target -/ lemma continuous_within_at_iff_continuous_within_at_comp_right {f : β → γ} {s : set β} {x : β} (h : x ∈ e.target) : continuous_within_at f s x ↔ continuous_within_at (f ∘ e) (e ⁻¹' s) (e.symm x) := begin split, { assume f_cont, have : e (e.symm x) = x := e.right_inv h, rw ← this at f_cont, have : e.source ∈ 𝓝 (e.symm x) := mem_nhds_sets e.open_source (e.map_target h), rw [← continuous_within_at_inter this, inter_comm], exact continuous_within_at.comp f_cont ((e.continuous_at (e.map_target h)).continuous_within_at) (inter_subset_right _ _) }, { assume fe_cont, have : continuous_within_at ((f ∘ e) ∘ e.symm) (s ∩ e.target) x, { apply continuous_within_at.comp fe_cont, apply (e.continuous_at_symm h).continuous_within_at, assume x hx, simp [hx.1, hx.2, e.map_target] }, have : continuous_within_at f (s ∩ e.target) x := continuous_within_at.congr this (λy hy, by simp [hy.2]) (by simp [h]), rwa continuous_within_at_inter at this, exact mem_nhds_sets e.open_target h } end /-- Continuity at a point can be read under right composition with a local homeomorphism, if the point is in its target -/ lemma continuous_at_iff_continuous_at_comp_right {f : β → γ} {x : β} (h : x ∈ e.target) : continuous_at f x ↔ continuous_at (f ∘ e) (e.symm x) := by rw [← continuous_within_at_univ, e.continuous_within_at_iff_continuous_within_at_comp_right h, preimage_univ, continuous_within_at_univ] /-- A function is continuous on a set if and only if its composition with a local homeomorphism on the right is continuous on the corresponding set. -/ lemma continuous_on_iff_continuous_on_comp_right {f : β → γ} {s : set β} (h : s ⊆ e.target) : continuous_on f s ↔ continuous_on (f ∘ e) (e.source ∩ e ⁻¹' s) := begin split, { assume f_cont x hx, have := e.continuous_within_at_iff_continuous_within_at_comp_right (e.map_source hx.1), rw e.left_inv hx.1 at this, have A := f_cont _ hx.2, rw this at A, exact A.mono (inter_subset_right _ _), }, { assume fe_cont x hx, have := e.continuous_within_at_iff_continuous_within_at_comp_right (h hx), rw this, have : e.source ∈ 𝓝 (e.symm x) := mem_nhds_sets e.open_source (e.map_target (h hx)), rw [← continuous_within_at_inter this, inter_comm], exact fe_cont _ (by simp [hx, h hx, e.map_target (h hx)]) } end /-- Continuity within a set at a point can be read under left composition with a local homeomorphism if a neighborhood of the initial point is sent to the source of the local homeomorphism-/ lemma continuous_within_at_iff_continuous_within_at_comp_left {f : γ → α} {s : set γ} {x : γ} (hx : f x ∈ e.source) (h : f ⁻¹' e.source ∈ 𝓝[s] x) : continuous_within_at f s x ↔ continuous_within_at (e ∘ f) s x := begin rw [← continuous_within_at_inter' h, ← continuous_within_at_inter' h], split, { assume f_cont, have : e.source ∈ 𝓝 (f x) := mem_nhds_sets e.open_source hx, apply continuous_within_at.comp (e.continuous_on (f x) hx) f_cont (inter_subset_right _ _) }, { assume fe_cont, have : continuous_within_at (e.symm ∘ (e ∘ f)) (s ∩ f ⁻¹' e.source) x, { have : continuous_within_at e.symm univ (e (f x)) := (e.continuous_at_symm (e.map_source hx)).continuous_within_at, exact continuous_within_at.comp this fe_cont (subset_univ _) }, exact this.congr (λy hy, by simp [e.left_inv hy.2]) (by simp [e.left_inv hx]) } end /-- Continuity at a point can be read under left composition with a local homeomorphism if a neighborhood of the initial point is sent to the source of the local homeomorphism-/ lemma continuous_at_iff_continuous_at_comp_left {f : γ → α} {x : γ} (h : f ⁻¹' e.source ∈ 𝓝 x) : continuous_at f x ↔ continuous_at (e ∘ f) x := begin have hx : f x ∈ e.source := (mem_of_nhds h : _), have h' : f ⁻¹' e.source ∈ 𝓝[univ] x, by rwa nhds_within_univ, rw [← continuous_within_at_univ, ← continuous_within_at_univ, e.continuous_within_at_iff_continuous_within_at_comp_left hx h'] end /-- A function is continuous on a set if and only if its composition with a local homeomorphism on the left is continuous on the corresponding set. -/ lemma continuous_on_iff_continuous_on_comp_left {f : γ → α} {s : set γ} (h : s ⊆ f ⁻¹' e.source) : continuous_on f s ↔ continuous_on (e ∘ f) s := begin split, { assume f_cont, exact e.continuous_on.comp f_cont h }, { assume fe_cont, have : continuous_on (e.symm ∘ e ∘ f) s, { apply continuous_on.comp e.continuous_on_symm fe_cont, assume x hx, have : f x ∈ e.source := h hx, simp [this] }, refine continuous_on.congr_mono this (λx hx, _) (subset.refl _), have : f x ∈ e.source := h hx, simp [this] } end end continuity /-- If a local homeomorphism has source and target equal to univ, then it induces a homeomorphism between the whole spaces, expressed in this definition. -/ def to_homeomorph_of_source_eq_univ_target_eq_univ (h : e.source = (univ : set α)) (h' : e.target = univ) : homeomorph α β := { to_fun := e, inv_fun := e.symm, left_inv := λx, e.left_inv $ by { rw h, exact mem_univ _ }, right_inv := λx, e.right_inv $ by { rw h', exact mem_univ _ }, continuous_to_fun := begin rw [continuous_iff_continuous_on_univ], convert e.continuous_to_fun, rw h end, continuous_inv_fun := begin rw [continuous_iff_continuous_on_univ], convert e.continuous_inv_fun, rw h' end } @[simp, mfld_simps] lemma to_homeomorph_coe (h : e.source = (univ : set α)) (h' : e.target = univ) : (e.to_homeomorph_of_source_eq_univ_target_eq_univ h h' : α → β) = e := rfl @[simp, mfld_simps] lemma to_homeomorph_symm_coe (h : e.source = (univ : set α)) (h' : e.target = univ) : ((e.to_homeomorph_of_source_eq_univ_target_eq_univ h h').symm : β → α) = e.symm := rfl /-- A local homeomorphism whose source is all of `α` defines an open embedding of `α` into `β`. The converse is also true; see `open_embedding.to_local_homeomorph`. -/ lemma to_open_embedding (h : e.source = set.univ) : open_embedding e.to_fun := begin apply open_embedding_of_continuous_injective_open, { apply continuous_iff_continuous_on_univ.mpr, rw ← h, exact e.continuous_to_fun }, { apply set.injective_iff_inj_on_univ.mpr, rw ← h, exact e.to_local_equiv.bij_on_source.inj_on }, { intros U hU, simpa only [h, subset_univ] with mfld_simps using e.image_open_of_open hU} end end local_homeomorph namespace homeomorph variables (e : homeomorph α β) (e' : homeomorph β γ) /- Register as simp lemmas that the fields of a local homeomorphism built from a homeomorphism correspond to the fields of the original homeomorphism. -/ @[simp, mfld_simps] lemma to_local_homeomorph_source : e.to_local_homeomorph.source = univ := rfl @[simp, mfld_simps] lemma to_local_homeomorph_target : e.to_local_homeomorph.target = univ := rfl @[simp, mfld_simps] lemma to_local_homeomorph_coe : (e.to_local_homeomorph : α → β) = e := rfl @[simp, mfld_simps] lemma to_local_homeomorph_coe_symm : (e.to_local_homeomorph.symm : β → α) = e.symm := rfl @[simp, mfld_simps] lemma refl_to_local_homeomorph : (homeomorph.refl α).to_local_homeomorph = local_homeomorph.refl α := rfl @[simp, mfld_simps] lemma symm_to_local_homeomorph : e.symm.to_local_homeomorph = e.to_local_homeomorph.symm := rfl @[simp, mfld_simps] lemma trans_to_local_homeomorph : (e.trans e').to_local_homeomorph = e.to_local_homeomorph.trans e'.to_local_homeomorph := local_homeomorph.eq_of_local_equiv_eq $ equiv.trans_to_local_equiv _ _ end homeomorph namespace open_embedding variables [nonempty α] variables {f : α → β} (h : open_embedding f) include f h /-- An open embedding of `α` into `β`, with `α` nonempty, defines a local equivalence whose source is all of `α`. This is mainly an auxiliary lemma for the stronger result `to_local_homeomorph`. -/ noncomputable def to_local_equiv : local_equiv α β := set.inj_on.to_local_equiv f set.univ (set.injective_iff_inj_on_univ.mp h.to_embedding.inj) @[simp, mfld_simps] lemma to_local_equiv_coe : (h.to_local_equiv : α → β) = f := rfl @[simp, mfld_simps] lemma to_local_equiv_source : h.to_local_equiv.source = set.univ := rfl @[simp, mfld_simps] lemma to_local_equiv_target : h.to_local_equiv.target = set.range f := begin rw ←local_equiv.image_source_eq_target, ext, split, { exact λ ⟨a, _, h'⟩, ⟨a, h'⟩ }, { exact λ ⟨a, h'⟩, ⟨a, by trivial, h'⟩ } end lemma open_target : is_open h.to_local_equiv.target := by simpa only with mfld_simps using h.open_range lemma continuous_inv_fun : continuous_on h.to_local_equiv.inv_fun h.to_local_equiv.target := begin apply (continuous_on_open_iff h.open_target).mpr, intros t ht, simp only with mfld_simps, convert h.open_iff_image_open.mp ht, ext y, have hinv : ∀ x : α, (f x = y) → h.to_local_equiv.symm y = x := λ x hxy, by { simpa only [hxy.symm] with mfld_simps using h.to_local_equiv.left_inv }, simp only [mem_image, mem_range] with mfld_simps, split, { rintros ⟨⟨x, hxy⟩, hy⟩, refine ⟨x, _, hxy⟩, rwa (hinv x hxy) at hy }, { rintros ⟨x, hx, hxy⟩, refine ⟨⟨x, hxy⟩, _⟩, rwa ← (hinv x hxy) at hx } end /-- An open embedding of `α` into `β`, with `α` nonempty, defines a local homeomorphism whose source is all of `α`. The converse is also true; see `local_homeomorph.to_open_embedding`. -/ noncomputable def to_local_homeomorph : local_homeomorph α β := { to_local_equiv := h.to_local_equiv, open_source := is_open_univ, open_target := h.open_target, continuous_to_fun := by simpa only with mfld_simps using h.continuous.continuous_on, continuous_inv_fun := h.continuous_inv_fun } @[simp, mfld_simps] lemma to_local_homeomorph_coe : (h.to_local_homeomorph : α → β) = f := rfl @[simp, mfld_simps] lemma source : h.to_local_homeomorph.source = set.univ := rfl @[simp, mfld_simps] lemma target : h.to_local_homeomorph.target = set.range f := h.to_local_equiv_target end open_embedding -- We close and reopen the namespace to avoid -- picking up the unnecessary `[nonempty α]` typeclass argument namespace open_embedding lemma continuous_at_iff {f : α → β} {g : β → γ} (hf : open_embedding f) {x : α} : continuous_at (g ∘ f) x ↔ continuous_at g (f x) := begin haveI : nonempty α := ⟨x⟩, convert ((hf.to_local_homeomorph.continuous_at_iff_continuous_at_comp_right) _).symm, { apply (local_homeomorph.left_inv _ _).symm, simp, }, { simp, }, end end open_embedding namespace topological_space.opens open topological_space variables (s : opens α) [nonempty s] /-- The inclusion of an open subset `s` of a space `α` into `α` is a local homeomorphism from the subtype `s` to `α`. -/ noncomputable def local_homeomorph_subtype_coe : local_homeomorph s α := open_embedding.to_local_homeomorph (s.2.open_embedding_subtype_coe) @[simp, mfld_simps] lemma local_homeomorph_subtype_coe_coe : (s.local_homeomorph_subtype_coe : s → α) = coe := rfl @[simp, mfld_simps] lemma local_homeomorph_subtype_coe_source : s.local_homeomorph_subtype_coe.source = set.univ := rfl @[simp, mfld_simps] lemma local_homeomorph_subtype_coe_target : s.local_homeomorph_subtype_coe.target = s := by { simp only [local_homeomorph_subtype_coe, subtype.range_coe_subtype] with mfld_simps, refl } end topological_space.opens namespace local_homeomorph open topological_space variables (e : local_homeomorph α β) variables (s : opens α) [nonempty s] /-- The restriction of a local homeomorphism `e` to an open subset `s` of the domain type produces a local homeomorphism whose domain is the subtype `s`.-/ noncomputable def subtype_restr : local_homeomorph s β := s.local_homeomorph_subtype_coe.trans e lemma subtype_restr_def : e.subtype_restr s = s.local_homeomorph_subtype_coe.trans e := rfl @[simp, mfld_simps] lemma subtype_restr_coe : ((e.subtype_restr s : local_homeomorph s β) : s → β) = set.restrict (e : α → β) s := rfl @[simp, mfld_simps] lemma subtype_restr_source : (e.subtype_restr s).source = coe ⁻¹' e.source := by simp only [subtype_restr_def] with mfld_simps /- This lemma characterizes the transition functions of an open subset in terms of the transition functions of the original space. -/ lemma subtype_restr_symm_trans_subtype_restr (f f' : local_homeomorph α β) : (f.subtype_restr s).symm.trans (f'.subtype_restr s) ≈ (f.symm.trans f').restr (f.target ∩ (f.symm) ⁻¹' s) := begin simp only [subtype_restr_def, trans_symm_eq_symm_trans_symm], have openness₁ : is_open (f.target ∩ f.symm ⁻¹' s) := f.preimage_open_of_open_symm s.2, rw [← of_set_trans _ openness₁, ← trans_assoc, ← trans_assoc], refine eq_on_source.trans' _ (eq_on_source_refl _), -- f' has been eliminated !!! have sets_identity : f.symm.source ∩ (f.target ∩ (f.symm) ⁻¹' s) = f.symm.source ∩ f.symm ⁻¹' s, { mfld_set_tac }, have openness₂ : is_open (s : set α) := s.2, rw [of_set_trans', sets_identity, ← trans_of_set' _ openness₂, trans_assoc], refine eq_on_source.trans' (eq_on_source_refl _) _, -- f has been eliminated !!! refine setoid.trans (trans_symm_self s.local_homeomorph_subtype_coe) _, simp only with mfld_simps, end end local_homeomorph
47ed808ea6a6cdccfa247fcc6f42e513e013f5fe
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/11_Tactic-Style_Proofs.org.7.lean
d6bbc1785a896e31ec0e8e73c00b2967d808cd0e
[]
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
128
lean
import standard theorem test (p q : Prop) (Hp : p) (Hq : q) : p ∧ q ∧ p := by apply (and.intro Hp); exact (and.intro Hq Hp)
e466c187c1666929209fb362950f22c0df9beb7c
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/858.lean
43aeb6ad597bfadb672af5a57583289b70391d29
[ "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
39
lean
section parameter (n : Πa, nat) end
f8d92ed660ebbb3fb892f7374460661cccbf890d
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/probability/cond_count.lean
3145180686d02199472b3c9d4f64b52677c8cc71
[ "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,870
lean
/- Copyright (c) 2022 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying, Bhavik Mehta -/ import probability.conditional_probability /-! # Classical probability > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The classical formulation of probability states that the probability of an event occurring in a finite probability space is the ratio of that event to all possible events. This notion can be expressed with measure theory using the counting measure. In particular, given the sets `s` and `t`, we define the probability of `t` occuring in `s` to be `|s|⁻¹ * |s ∩ t|`. With this definition, we recover the the probability over the entire sample space when `s = set.univ`. Classical probability is often used in combinatorics and we prove some useful lemmas in this file for that purpose. ## Main definition * `probability_theory.cond_count`: given a set `s`, `cond_count s` is the counting measure conditioned on `s`. This is a probability measure when `s` is finite and nonempty. ## Notes The original aim of this file is to provide a measure theoretic method of describing the probability an element of a set `s` satisfies some predicate `P`. Our current formulation still allow us to describe this by abusing the definitional equality of sets and predicates by simply writing `cond_count s P`. We should avoid this however as none of the lemmas are written for predicates. -/ noncomputable theory open_locale probability_theory open measure_theory measurable_space namespace probability_theory variables {Ω : Type*} [measurable_space Ω] /-- Given a set `s`, `cond_count s` is the counting measure conditioned on `s`. In particular, `cond_count s t` is the proportion of `s` that is contained in `t`. This is a probability measure when `s` is finite and nonempty and is given by `probability_theory.cond_count_is_probability_measure`. -/ def cond_count (s : set Ω) : measure Ω := measure.count[|s] @[simp] lemma cond_count_empty_meas : (cond_count ∅ : measure Ω) = 0 := by simp [cond_count] lemma cond_count_empty {s : set Ω} : cond_count s ∅ = 0 := by simp lemma finite_of_cond_count_ne_zero {s t : set Ω} (h : cond_count s t ≠ 0) : s.finite := begin by_contra hs', simpa [cond_count, cond, measure.count_apply_infinite hs'] using h, end lemma cond_count_univ [fintype Ω] {s : set Ω} : cond_count set.univ s = measure.count s / fintype.card Ω := begin rw [cond_count, cond_apply _ measurable_set.univ, ←ennreal.div_eq_inv_mul, set.univ_inter], congr', rw [←finset.coe_univ, measure.count_apply, finset.univ.tsum_subtype' (λ _, (1 : ennreal))], { simp [finset.card_univ] }, { exact (@finset.coe_univ Ω _).symm ▸ measurable_set.univ } end variables [measurable_singleton_class Ω] lemma cond_count_is_probability_measure {s : set Ω} (hs : s.finite) (hs' : s.nonempty) : is_probability_measure (cond_count s) := { measure_univ := begin rw [cond_count, cond_apply _ hs.measurable_set, set.inter_univ, ennreal.inv_mul_cancel], { exact λ h, hs'.ne_empty $ measure.empty_of_count_eq_zero h }, { exact (measure.count_apply_lt_top.2 hs).ne } end } lemma cond_count_singleton (ω : Ω) (t : set Ω) [decidable (ω ∈ t)] : cond_count {ω} t = if ω ∈ t then 1 else 0 := begin rw [cond_count, cond_apply _ (measurable_set_singleton ω), measure.count_singleton, inv_one, one_mul], split_ifs, { rw [(by simpa : ({ω} : set Ω) ∩ t = {ω}), measure.count_singleton] }, { rw [(by simpa : ({ω} : set Ω) ∩ t = ∅), measure.count_empty] }, end variables {s t u : set Ω} lemma cond_count_inter_self (hs : s.finite): cond_count s (s ∩ t) = cond_count s t := by rw [cond_count, cond_inter_self _ hs.measurable_set] lemma cond_count_self (hs : s.finite) (hs' : s.nonempty) : cond_count s s = 1 := begin rw [cond_count, cond_apply _ hs.measurable_set, set.inter_self, ennreal.inv_mul_cancel], { exact λ h, hs'.ne_empty $ measure.empty_of_count_eq_zero h }, { exact (measure.count_apply_lt_top.2 hs).ne } end lemma cond_count_eq_one_of (hs : s.finite) (hs' : s.nonempty) (ht : s ⊆ t) : cond_count s t = 1 := begin haveI := cond_count_is_probability_measure hs hs', refine eq_of_le_of_not_lt prob_le_one _, rw [not_lt, ← cond_count_self hs hs'], exact measure_mono ht, end lemma pred_true_of_cond_count_eq_one (h : cond_count s t = 1) : s ⊆ t := begin have hsf := finite_of_cond_count_ne_zero (by { rw h, exact one_ne_zero }), rw [cond_count, cond_apply _ hsf.measurable_set, mul_comm] at h, replace h := ennreal.eq_inv_of_mul_eq_one_left h, rw [inv_inv, measure.count_apply_finite _ hsf, measure.count_apply_finite _ (hsf.inter_of_left _), nat.cast_inj] at h, suffices : s ∩ t = s, { exact this ▸ λ x hx, hx.2 }, rw ← @set.finite.to_finset_inj _ _ _ (hsf.inter_of_left _) hsf, exact finset.eq_of_subset_of_card_le (set.finite.to_finset_mono $ s.inter_subset_left t) h.ge, end lemma cond_count_eq_zero_iff (hs : s.finite) : cond_count s t = 0 ↔ s ∩ t = ∅ := by simp [cond_count, cond_apply _ hs.measurable_set, measure.count_apply_eq_top, set.not_infinite.2 hs, measure.count_apply_finite _ (hs.inter_of_left _)] lemma cond_count_of_univ (hs : s.finite) (hs' : s.nonempty) : cond_count s set.univ = 1 := cond_count_eq_one_of hs hs' s.subset_univ lemma cond_count_inter (hs : s.finite) : cond_count s (t ∩ u) = cond_count (s ∩ t) u * cond_count s t := begin by_cases hst : s ∩ t = ∅, { rw [hst, cond_count_empty_meas, measure.coe_zero, pi.zero_apply, zero_mul, cond_count_eq_zero_iff hs, ← set.inter_assoc, hst, set.empty_inter] }, rw [cond_count, cond_count, cond_apply _ hs.measurable_set, cond_apply _ hs.measurable_set, cond_apply _ (hs.inter_of_left _).measurable_set, mul_comm _ (measure.count (s ∩ t)), ← mul_assoc, mul_comm _ (measure.count (s ∩ t)), ← mul_assoc, ennreal.mul_inv_cancel, one_mul, mul_comm, set.inter_assoc], { rwa ← measure.count_eq_zero_iff at hst }, { exact (measure.count_apply_lt_top.2 $ hs.inter_of_left _).ne } end lemma cond_count_inter' (hs : s.finite) : cond_count s (t ∩ u) = cond_count (s ∩ u) t * cond_count s u := begin rw ← set.inter_comm, exact cond_count_inter hs, end lemma cond_count_union (hs : s.finite) (htu : disjoint t u) : cond_count s (t ∪ u) = cond_count s t + cond_count s u := begin rw [cond_count, cond_apply _ hs.measurable_set, cond_apply _ hs.measurable_set, cond_apply _ hs.measurable_set, set.inter_union_distrib_left, measure_union, mul_add], exacts [htu.mono inf_le_right inf_le_right, (hs.inter_of_left _).measurable_set], end lemma cond_count_compl (t : set Ω) (hs : s.finite) (hs' : s.nonempty) : cond_count s t + cond_count s tᶜ = 1 := begin rw [← cond_count_union hs disjoint_compl_right, set.union_compl_self, (cond_count_is_probability_measure hs hs').measure_univ], end lemma cond_count_disjoint_union (hs : s.finite) (ht : t.finite) (hst : disjoint s t) : cond_count s u * cond_count (s ∪ t) s + cond_count t u * cond_count (s ∪ t) t = cond_count (s ∪ t) u := begin rcases s.eq_empty_or_nonempty with (rfl | hs'); rcases t.eq_empty_or_nonempty with (rfl | ht'), { simp }, { simp [cond_count_self ht ht'] }, { simp [cond_count_self hs hs'] }, rw [cond_count, cond_count, cond_count, cond_apply _ hs.measurable_set, cond_apply _ ht.measurable_set, cond_apply _ (hs.union ht).measurable_set, cond_apply _ (hs.union ht).measurable_set, cond_apply _ (hs.union ht).measurable_set], conv_lhs { rw [set.union_inter_cancel_left, set.union_inter_cancel_right, mul_comm (measure.count (s ∪ t))⁻¹, mul_comm (measure.count (s ∪ t))⁻¹, ← mul_assoc, ← mul_assoc, mul_comm _ (measure.count s), mul_comm _ (measure.count t), ← mul_assoc, ← mul_assoc] }, rw [ennreal.mul_inv_cancel, ennreal.mul_inv_cancel, one_mul, one_mul, ← add_mul, ← measure_union, set.union_inter_distrib_right, mul_comm], exacts [hst.mono inf_le_left inf_le_left, (ht.inter_of_left _).measurable_set, measure.count_ne_zero ht', (measure.count_apply_lt_top.2 ht).ne, measure.count_ne_zero hs', (measure.count_apply_lt_top.2 hs).ne], end /-- A version of the law of total probability for counting probabilites. -/ lemma cond_count_add_compl_eq (u t : set Ω) (hs : s.finite) : cond_count (s ∩ u) t * cond_count s u + cond_count (s ∩ uᶜ) t * cond_count s uᶜ = cond_count s t := begin conv_rhs { rw [(by simp : s = s ∩ u ∪ s ∩ uᶜ), ← cond_count_disjoint_union (hs.inter_of_left _) (hs.inter_of_left _) (disjoint_compl_right.mono inf_le_right inf_le_right)] }, simp [cond_count_inter_self hs], end end probability_theory
c4bcbc6f4ff61e2db8263745bd6830521a1639af
f3849be5d845a1cb97680f0bbbe03b85518312f0
/library/init/algebra/ring.lean
fb470746e5f31c3a08925d2f07ad3fee50273c85
[ "Apache-2.0" ]
permissive
bjoeris/lean
0ed95125d762b17bfcb54dad1f9721f953f92eeb
4e496b78d5e73545fa4f9a807155113d8e6b0561
refs/heads/master
1,611,251,218,281
1,495,337,658,000
1,495,337,658,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,036
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura -/ prelude import init.algebra.group /- Make sure instances defined in this file have lower priority than the ones defined for concrete structures -/ set_option default_priority 100 set_option old_structure_cmd true universe u class distrib (α : Type u) extends has_mul α, has_add α := (left_distrib : ∀ a b c : α, a * (b + c) = (a * b) + (a * c)) (right_distrib : ∀ a b c : α, (a + b) * c = (a * c) + (b * c)) variable {α : Type u} lemma left_distrib [distrib α] (a b c : α) : a * (b + c) = a * b + a * c := distrib.left_distrib a b c def mul_add := @left_distrib lemma right_distrib [distrib α] (a b c : α) : (a + b) * c = a * c + b * c := distrib.right_distrib a b c def add_mul := @right_distrib class mul_zero_class (α : Type u) extends has_mul α, has_zero α := (zero_mul : ∀ a : α, 0 * a = 0) (mul_zero : ∀ a : α, a * 0 = 0) @[simp] lemma zero_mul [mul_zero_class α] (a : α) : 0 * a = 0 := mul_zero_class.zero_mul a @[simp] lemma mul_zero [mul_zero_class α] (a : α) : a * 0 = 0 := mul_zero_class.mul_zero a class zero_ne_one_class (α : Type u) extends has_zero α, has_one α := (zero_ne_one : 0 ≠ (1:α)) @[simp] lemma zero_ne_one [s: zero_ne_one_class α] : 0 ≠ (1:α) := @zero_ne_one_class.zero_ne_one α s @[simp] lemma one_ne_zero [s: zero_ne_one_class α] : (1:α) ≠ 0 := take h, @zero_ne_one_class.zero_ne_one α s h.symm /- semiring -/ class semiring (α : Type u) extends add_comm_monoid α, monoid α, distrib α, mul_zero_class α section semiring variables [semiring α] lemma one_add_one_eq_two : 1 + 1 = (2 : α) := begin unfold bit0, reflexivity end lemma ne_zero_of_mul_ne_zero_right {a b : α} (h : a * b ≠ 0) : a ≠ 0 := suppose a = 0, have a * b = 0, by rw [this, zero_mul], h this lemma ne_zero_of_mul_ne_zero_left {a b : α} (h : a * b ≠ 0) : b ≠ 0 := suppose b = 0, have a * b = 0, by rw [this, mul_zero], h this lemma distrib_three_right (a b c d : α) : (a + b + c) * d = a * d + b * d + c * d := by simp [right_distrib] end semiring class comm_semiring (α : Type u) extends semiring α, comm_monoid α /- ring -/ class ring (α : Type u) extends add_comm_group α, monoid α, distrib α lemma ring.mul_zero [ring α] (a : α) : a * 0 = 0 := have a * 0 + 0 = a * 0 + a * 0, from calc a * 0 + 0 = a * (0 + 0) : by simp ... = a * 0 + a * 0 : by rw left_distrib, show a * 0 = 0, from (add_left_cancel this).symm lemma ring.zero_mul [ring α] (a : α) : 0 * a = 0 := have 0 * a + 0 = 0 * a + 0 * a, from calc 0 * a + 0 = (0 + 0) * a : by simp ... = 0 * a + 0 * a : by rewrite right_distrib, show 0 * a = 0, from (add_left_cancel this).symm instance ring.to_semiring [s : ring α] : semiring α := { s with mul_zero := ring.mul_zero, zero_mul := ring.zero_mul } lemma neg_mul_eq_neg_mul [s : ring α] (a b : α) : -(a * b) = -a * b := neg_eq_of_add_eq_zero begin rw [-right_distrib, add_right_neg, zero_mul] end lemma neg_mul_eq_mul_neg [s : ring α] (a b : α) : -(a * b) = a * -b := neg_eq_of_add_eq_zero begin rw [-left_distrib, add_right_neg, mul_zero] end @[simp] lemma neg_mul_eq_neg_mul_symm [s : ring α] (a b : α) : - a * b = - (a * b) := eq.symm (neg_mul_eq_neg_mul a b) @[simp] lemma mul_neg_eq_neg_mul_symm [s : ring α] (a b : α) : a * - b = - (a * b) := eq.symm (neg_mul_eq_mul_neg a b) lemma neg_mul_neg [s : ring α] (a b : α) : -a * -b = a * b := by simp lemma neg_mul_comm [s : ring α] (a b : α) : -a * b = a * -b := by simp theorem neg_eq_neg_one_mul [s : ring α] (a : α) : -a = -1 * a := by simp lemma mul_sub_left_distrib [s : ring α] (a b c : α) : a * (b - c) = a * b - a * c := calc a * (b - c) = a * b + a * -c : left_distrib a b (-c) ... = a * b - a * c : by simp def mul_sub := @mul_sub_left_distrib lemma mul_sub_right_distrib [s : ring α] (a b c : α) : (a - b) * c = a * c - b * c := calc (a - b) * c = a * c + -b * c : right_distrib a (-b) c ... = a * c - b * c : by simp def sub_mul := @mul_sub_right_distrib class comm_ring (α : Type u) extends ring α, comm_semigroup α instance comm_ring.to_comm_semiring [s : comm_ring α] : comm_semiring α := { s with mul_zero := mul_zero, zero_mul := zero_mul } section comm_ring variable [comm_ring α] lemma mul_self_sub_mul_self_eq (a b : α) : a * a - b * b = (a + b) * (a - b) := by simp [right_distrib, left_distrib] lemma mul_self_sub_one_eq (a : α) : a * a - 1 = (a + 1) * (a - 1) := by simp [right_distrib, left_distrib] lemma add_mul_self_eq (a b : α) : (a + b) * (a + b) = a*a + 2*a*b + b*b := calc (a + b)*(a + b) = a*a + (1+1)*a*b + b*b : by simp [right_distrib, left_distrib] ... = a*a + 2*a*b + b*b : by rw one_add_one_eq_two end comm_ring class no_zero_divisors (α : Type u) extends has_mul α, has_zero α := (eq_zero_or_eq_zero_of_mul_eq_zero : ∀ a b : α, a * b = 0 → a = 0 ∨ b = 0) lemma eq_zero_or_eq_zero_of_mul_eq_zero [no_zero_divisors α] {a b : α} (h : a * b = 0) : a = 0 ∨ b = 0 := no_zero_divisors.eq_zero_or_eq_zero_of_mul_eq_zero a b h lemma eq_zero_of_mul_self_eq_zero [no_zero_divisors α] {a : α} (h : a * a = 0) : a = 0 := or.elim (eq_zero_or_eq_zero_of_mul_eq_zero h) (assume h', h') (assume h', h') class integral_domain (α : Type u) extends comm_ring α, no_zero_divisors α, zero_ne_one_class α section integral_domain variable [integral_domain α] lemma mul_ne_zero {a b : α} (h₁ : a ≠ 0) (h₂ : b ≠ 0) : a * b ≠ 0 := λ h, or.elim (eq_zero_or_eq_zero_of_mul_eq_zero h) (assume h₃, h₁ h₃) (assume h₄, h₂ h₄) lemma eq_of_mul_eq_mul_right {a b c : α} (ha : a ≠ 0) (h : b * a = c * a) : b = c := have b * a - c * a = 0, from sub_eq_zero_of_eq h, have (b - c) * a = 0, by rw [mul_sub_right_distrib, this], have b - c = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right ha, eq_of_sub_eq_zero this lemma eq_of_mul_eq_mul_left {a b c : α} (ha : a ≠ 0) (h : a * b = a * c) : b = c := have a * b - a * c = 0, from sub_eq_zero_of_eq h, have a * (b - c) = 0, by rw [mul_sub_left_distrib, this], have b - c = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_left ha, eq_of_sub_eq_zero this lemma eq_zero_of_mul_eq_self_right {a b : α} (h₁ : b ≠ 1) (h₂ : a * b = a) : a = 0 := have hb : b - 1 ≠ 0, from suppose b - 1 = 0, have b = 0 + 1, from eq_add_of_sub_eq this, have b = 1, by rwa zero_add at this, h₁ this, have a * b - a = 0, by simp [h₂], have a * (b - 1) = 0, by rwa [mul_sub_left_distrib, mul_one], show a = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right hb lemma eq_zero_of_mul_eq_self_left {a b : α} (h₁ : b ≠ 1) (h₂ : b * a = a) : a = 0 := eq_zero_of_mul_eq_self_right h₁ (by rwa mul_comm at h₂) lemma mul_self_eq_mul_self_iff (a b : α) : a * a = b * b ↔ a = b ∨ a = -b := iff.intro (suppose a * a = b * b, have (a - b) * (a + b) = 0, by rewrite [mul_comm, -mul_self_sub_mul_self_eq, this, sub_self], have a - b = 0 ∨ a + b = 0, from eq_zero_or_eq_zero_of_mul_eq_zero this, or.elim this (suppose a - b = 0, or.inl (eq_of_sub_eq_zero this)) (suppose a + b = 0, or.inr (eq_neg_of_add_eq_zero this))) (suppose a = b ∨ a = -b, or.elim this (suppose a = b, by rewrite this) (suppose a = -b, by rewrite [this, neg_mul_neg])) lemma mul_self_eq_one_iff (a : α) : a * a = 1 ↔ a = 1 ∨ a = -1 := have a * a = 1 * 1 ↔ a = 1 ∨ a = -1, from mul_self_eq_mul_self_iff a 1, by rwa mul_one at this end integral_domain /- TODO(Leo): remove the following annotations as soon as we have support for arithmetic in the SMT tactic framework -/ attribute [ematch] add_zero zero_add mul_one one_mul mul_zero zero_mul
428a1d396e347d9224de5a40df8dcce81dcede38
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebra/order/monoid_lemmas.lean
dede9ac014afc29891947dd70874623b62a3f5f4
[ "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
45,376
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes Hölzl, Damiano Testa, Yuyang Zhao -/ import algebra.covariant_and_contravariant import order.monotone /-! # Ordered monoids This file develops the basics of ordered monoids. ## Implementation details Unfortunately, the number of `'` appended to lemmas in this file may differ between the multiplicative and the additive version of a lemma. The reason is that we did not want to change existing names in the library. ## Remark Almost no monoid is actually present in this file: most assumptions have been generalized to `has_mul` or `mul_one_class`. -/ -- TODO: If possible, uniformize lemma names, taking special care of `'`, -- after the `ordered`-refactor is done. open function variables {α β : Type*} section has_mul variables [has_mul α] section has_le variables [has_le α] /- The prime on this lemma is present only on the multiplicative version. The unprimed version is taken by the analogous lemma for semiring, with an extra non-negativity assumption. -/ @[to_additive add_le_add_left] lemma mul_le_mul_left' [covariant_class α α (*) (≤)] {b c : α} (bc : b ≤ c) (a : α) : a * b ≤ a * c := covariant_class.elim _ bc @[to_additive le_of_add_le_add_left] lemma le_of_mul_le_mul_left' [contravariant_class α α (*) (≤)] {a b c : α} (bc : a * b ≤ a * c) : b ≤ c := contravariant_class.elim _ bc /- The prime on this lemma is present only on the multiplicative version. The unprimed version is taken by the analogous lemma for semiring, with an extra non-negativity assumption. -/ @[to_additive add_le_add_right] lemma mul_le_mul_right' [covariant_class α α (swap (*)) (≤)] {b c : α} (bc : b ≤ c) (a : α) : b * a ≤ c * a := covariant_class.elim a bc @[to_additive le_of_add_le_add_right] lemma le_of_mul_le_mul_right' [contravariant_class α α (swap (*)) (≤)] {a b c : α} (bc : b * a ≤ c * a) : b ≤ c := contravariant_class.elim a bc @[simp, to_additive] lemma mul_le_mul_iff_left [covariant_class α α (*) (≤)] [contravariant_class α α (*) (≤)] (a : α) {b c : α} : a * b ≤ a * c ↔ b ≤ c := rel_iff_cov α α (*) (≤) a @[simp, to_additive] lemma mul_le_mul_iff_right [covariant_class α α (swap (*)) (≤)] [contravariant_class α α (swap (*)) (≤)] (a : α) {b c : α} : b * a ≤ c * a ↔ b ≤ c := rel_iff_cov α α (swap (*)) (≤) a end has_le section has_lt variables [has_lt α] @[simp, to_additive] lemma mul_lt_mul_iff_left [covariant_class α α (*) (<)] [contravariant_class α α (*) (<)] (a : α) {b c : α} : a * b < a * c ↔ b < c := rel_iff_cov α α (*) (<) a @[simp, to_additive] lemma mul_lt_mul_iff_right [covariant_class α α (swap (*)) (<)] [contravariant_class α α (swap (*)) (<)] (a : α) {b c : α} : b * a < c * a ↔ b < c := rel_iff_cov α α (swap (*)) (<) a @[to_additive add_lt_add_left] lemma mul_lt_mul_left' [covariant_class α α (*) (<)] {b c : α} (bc : b < c) (a : α) : a * b < a * c := covariant_class.elim _ bc @[to_additive lt_of_add_lt_add_left] lemma lt_of_mul_lt_mul_left' [contravariant_class α α (*) (<)] {a b c : α} (bc : a * b < a * c) : b < c := contravariant_class.elim _ bc @[to_additive add_lt_add_right] lemma mul_lt_mul_right' [covariant_class α α (swap (*)) (<)] {b c : α} (bc : b < c) (a : α) : b * a < c * a := covariant_class.elim a bc @[to_additive lt_of_add_lt_add_right] lemma lt_of_mul_lt_mul_right' [contravariant_class α α (swap (*)) (<)] {a b c : α} (bc : b * a < c * a) : b < c := contravariant_class.elim a bc end has_lt section preorder variables [preorder α] @[to_additive] lemma mul_lt_mul_of_lt_of_lt [covariant_class α α (*) (<)] [covariant_class α α (swap (*)) (<)] {a b c d : α} (h₁ : a < b) (h₂ : c < d) : a * c < b * d := calc a * c < a * d : mul_lt_mul_left' h₂ a ... < b * d : mul_lt_mul_right' h₁ d alias add_lt_add_of_lt_of_lt ← add_lt_add @[to_additive] lemma mul_lt_mul_of_le_of_lt [covariant_class α α (*) (<)] [covariant_class α α (swap (*)) (≤)] {a b c d : α} (h₁ : a ≤ b) (h₂ : c < d) : a * c < b * d := (mul_le_mul_right' h₁ _).trans_lt (mul_lt_mul_left' h₂ b) @[to_additive] lemma mul_lt_mul_of_lt_of_le [covariant_class α α (*) (≤)] [covariant_class α α (swap (*)) (<)] {a b c d : α} (h₁ : a < b) (h₂ : c ≤ d) : a * c < b * d := (mul_le_mul_left' h₂ _).trans_lt (mul_lt_mul_right' h₁ d) /-- Only assumes left strict covariance. -/ @[to_additive "Only assumes left strict covariance"] lemma left.mul_lt_mul [covariant_class α α (*) (<)] [covariant_class α α (swap (*)) (≤)] {a b c d : α} (h₁ : a < b) (h₂ : c < d) : a * c < b * d := mul_lt_mul_of_le_of_lt h₁.le h₂ /-- Only assumes right strict covariance. -/ @[to_additive "Only assumes right strict covariance"] lemma right.mul_lt_mul [covariant_class α α (*) (≤)] [covariant_class α α (swap (*)) (<)] {a b c d : α} (h₁ : a < b) (h₂ : c < d) : a * c < b * d := mul_lt_mul_of_lt_of_le h₁ h₂.le @[to_additive add_le_add] lemma mul_le_mul' [covariant_class α α (*) (≤)] [covariant_class α α (swap (*)) (≤)] {a b c d : α} (h₁ : a ≤ b) (h₂ : c ≤ d) : a * c ≤ b * d := (mul_le_mul_left' h₂ _).trans (mul_le_mul_right' h₁ d) @[to_additive] lemma mul_le_mul_three [covariant_class α α (*) (≤)] [covariant_class α α (swap (*)) (≤)] {a b c d e f : α} (h₁ : a ≤ d) (h₂ : b ≤ e) (h₃ : c ≤ f) : a * b * c ≤ d * e * f := mul_le_mul' (mul_le_mul' h₁ h₂) h₃ @[to_additive] lemma mul_lt_of_mul_lt_left [covariant_class α α (*) (≤)] {a b c d : α} (h : a * b < c) (hle : d ≤ b) : a * d < c := (mul_le_mul_left' hle a).trans_lt h @[to_additive] lemma mul_le_of_mul_le_left [covariant_class α α (*) (≤)] {a b c d : α} (h : a * b ≤ c) (hle : d ≤ b) : a * d ≤ c := @act_rel_of_rel_of_act_rel _ _ _ (≤) _ ⟨λ _ _ _, le_trans⟩ a _ _ _ hle h @[to_additive] lemma mul_lt_of_mul_lt_right [covariant_class α α (swap (*)) (≤)] {a b c d : α} (h : a * b < c) (hle : d ≤ a) : d * b < c := (mul_le_mul_right' hle b).trans_lt h @[to_additive] lemma mul_le_of_mul_le_right [covariant_class α α (swap (*)) (≤)] {a b c d : α} (h : a * b ≤ c) (hle : d ≤ a) : d * b ≤ c := (mul_le_mul_right' hle b).trans h @[to_additive] lemma lt_mul_of_lt_mul_left [covariant_class α α (*) (≤)] {a b c d : α} (h : a < b * c) (hle : c ≤ d) : a < b * d := h.trans_le (mul_le_mul_left' hle b) @[to_additive] lemma le_mul_of_le_mul_left [covariant_class α α (*) (≤)] {a b c d : α} (h : a ≤ b * c) (hle : c ≤ d) : a ≤ b * d := @rel_act_of_rel_of_rel_act _ _ _ (≤) _ ⟨λ _ _ _, le_trans⟩ b _ _ _ hle h @[to_additive] lemma lt_mul_of_lt_mul_right [covariant_class α α (swap (*)) (≤)] {a b c d : α} (h : a < b * c) (hle : b ≤ d) : a < d * c := h.trans_le (mul_le_mul_right' hle c) @[to_additive] lemma le_mul_of_le_mul_right [covariant_class α α (swap (*)) (≤)] {a b c d : α} (h : a ≤ b * c) (hle : b ≤ d) : a ≤ d * c := h.trans (mul_le_mul_right' hle c) end preorder section partial_order variables [partial_order α] @[to_additive] lemma mul_left_cancel'' [contravariant_class α α (*) (≤)] {a b c : α} (h : a * b = a * c) : b = c := (le_of_mul_le_mul_left' h.le).antisymm (le_of_mul_le_mul_left' h.ge) @[to_additive] lemma mul_right_cancel'' [contravariant_class α α (swap (*)) (≤)] {a b c : α} (h : a * b = c * b) : a = c := le_antisymm (le_of_mul_le_mul_right' h.le) (le_of_mul_le_mul_right' h.ge) end partial_order end has_mul -- using one section mul_one_class variables [mul_one_class α] section has_le variables [has_le α] @[to_additive le_add_of_nonneg_right] lemma le_mul_of_one_le_right' [covariant_class α α (*) (≤)] {a b : α} (h : 1 ≤ b) : a ≤ a * b := calc a = a * 1 : (mul_one a).symm ... ≤ a * b : mul_le_mul_left' h a @[to_additive add_le_of_nonpos_right] lemma mul_le_of_le_one_right' [covariant_class α α (*) (≤)] {a b : α} (h : b ≤ 1) : a * b ≤ a := calc a * b ≤ a * 1 : mul_le_mul_left' h a ... = a : mul_one a @[to_additive le_add_of_nonneg_left] lemma le_mul_of_one_le_left' [covariant_class α α (swap (*)) (≤)] {a b : α} (h : 1 ≤ b) : a ≤ b * a := calc a = 1 * a : (one_mul a).symm ... ≤ b * a : mul_le_mul_right' h a @[to_additive add_le_of_nonpos_left] lemma mul_le_of_le_one_left' [covariant_class α α (swap (*)) (≤)] {a b : α} (h : b ≤ 1) : b * a ≤ a := calc b * a ≤ 1 * a : mul_le_mul_right' h a ... = a : one_mul a @[simp, to_additive le_add_iff_nonneg_right] lemma le_mul_iff_one_le_right' [covariant_class α α (*) (≤)] [contravariant_class α α (*) (≤)] (a : α) {b : α} : a ≤ a * b ↔ 1 ≤ b := iff.trans (by rw [mul_one]) (mul_le_mul_iff_left a) @[simp, to_additive le_add_iff_nonneg_left] lemma le_mul_iff_one_le_left' [covariant_class α α (swap (*)) (≤)] [contravariant_class α α (swap (*)) (≤)] (a : α) {b : α} : a ≤ b * a ↔ 1 ≤ b := iff.trans (by rw one_mul) (mul_le_mul_iff_right a) @[simp, to_additive add_le_iff_nonpos_right] lemma mul_le_iff_le_one_right' [covariant_class α α (*) (≤)] [contravariant_class α α (*) (≤)] (a : α) {b : α} : a * b ≤ a ↔ b ≤ 1 := iff.trans (by rw [mul_one]) (mul_le_mul_iff_left a) @[simp, to_additive add_le_iff_nonpos_left] lemma mul_le_iff_le_one_left' [covariant_class α α (swap (*)) (≤)] [contravariant_class α α (swap (*)) (≤)] {a b : α} : a * b ≤ b ↔ a ≤ 1 := iff.trans (by rw one_mul) (mul_le_mul_iff_right b) end has_le section has_lt variable [has_lt α] @[to_additive lt_add_of_pos_right] lemma lt_mul_of_one_lt_right' [covariant_class α α (*) (<)] (a : α) {b : α} (h : 1 < b) : a < a * b := calc a = a * 1 : (mul_one a).symm ... < a * b : mul_lt_mul_left' h a @[to_additive add_lt_of_neg_right] lemma mul_lt_of_lt_one_right' [covariant_class α α (*) (<)] (a : α) {b : α} (h : b < 1) : a * b < a := calc a * b < a * 1 : mul_lt_mul_left' h a ... = a : mul_one a @[to_additive lt_add_of_pos_left] lemma lt_mul_of_one_lt_left' [covariant_class α α (swap (*)) (<)] (a : α) {b : α} (h : 1 < b) : a < b * a := calc a = 1 * a : (one_mul a).symm ... < b * a : mul_lt_mul_right' h a @[to_additive add_lt_of_neg_left] lemma mul_lt_of_lt_one_left' [covariant_class α α (swap (*)) (<)] (a : α) {b : α} (h : b < 1) : b * a < a := calc b * a < 1 * a : mul_lt_mul_right' h a ... = a : one_mul a @[simp, to_additive lt_add_iff_pos_right] lemma lt_mul_iff_one_lt_right' [covariant_class α α (*) (<)] [contravariant_class α α (*) (<)] (a : α) {b : α} : a < a * b ↔ 1 < b := iff.trans (by rw mul_one) (mul_lt_mul_iff_left a) @[simp, to_additive lt_add_iff_pos_left] lemma lt_mul_iff_one_lt_left' [covariant_class α α (swap (*)) (<)] [contravariant_class α α (swap (*)) (<)] (a : α) {b : α} : a < b * a ↔ 1 < b := iff.trans (by rw one_mul) (mul_lt_mul_iff_right a) @[simp, to_additive add_lt_iff_neg_left] lemma mul_lt_iff_lt_one_left' [covariant_class α α (*) (<)] [contravariant_class α α (*) (<)] {a b : α} : a * b < a ↔ b < 1 := iff.trans (by rw mul_one) (mul_lt_mul_iff_left a) @[simp, to_additive add_lt_iff_neg_right] lemma mul_lt_iff_lt_one_right' [covariant_class α α (swap (*)) (<)] [contravariant_class α α (swap (*)) (<)] {a : α} (b : α) : a * b < b ↔ a < 1 := iff.trans (by rw one_mul) (mul_lt_mul_iff_right b) end has_lt section preorder variable [preorder α] /-! Lemmas of the form `b ≤ c → a ≤ 1 → b * a ≤ c`, which assume left covariance. -/ @[to_additive] lemma mul_le_of_le_of_le_one [covariant_class α α (*) (≤)] {a b c : α} (hbc : b ≤ c) (ha : a ≤ 1) : b * a ≤ c := calc b * a ≤ b * 1 : mul_le_mul_left' ha b ... = b : mul_one b ... ≤ c : hbc @[to_additive] lemma mul_lt_of_le_of_lt_one [covariant_class α α (*) (<)] {a b c : α} (hbc : b ≤ c) (ha : a < 1) : b * a < c := calc b * a < b * 1 : mul_lt_mul_left' ha b ... = b : mul_one b ... ≤ c : hbc @[to_additive] lemma mul_lt_of_lt_of_le_one [covariant_class α α (*) (≤)] {a b c : α} (hbc : b < c) (ha : a ≤ 1) : b * a < c := calc b * a ≤ b * 1 : mul_le_mul_left' ha b ... = b : mul_one b ... < c : hbc @[to_additive] lemma mul_lt_of_lt_of_lt_one [covariant_class α α (*) (<)] {a b c : α} (hbc : b < c) (ha : a < 1) : b * a < c := calc b * a < b * 1 : mul_lt_mul_left' ha b ... = b : mul_one b ... < c : hbc @[to_additive] lemma mul_lt_of_lt_of_lt_one' [covariant_class α α (*) (≤)] {a b c : α} (hbc : b < c) (ha : a < 1) : b * a < c := mul_lt_of_lt_of_le_one hbc ha.le /-- Assumes left covariance. The lemma assuming right covariance is `right.mul_le_one`. -/ @[to_additive "Assumes left covariance. The lemma assuming right covariance is `right.add_nonpos`."] lemma left.mul_le_one [covariant_class α α (*) (≤)] {a b : α} (ha : a ≤ 1) (hb : b ≤ 1) : a * b ≤ 1 := mul_le_of_le_of_le_one ha hb /-- Assumes left covariance. The lemma assuming right covariance is `right.mul_lt_one_of_le_of_lt`. -/ @[to_additive left.add_neg_of_nonpos_of_neg "Assumes left covariance. The lemma assuming right covariance is `right.add_neg_of_nonpos_of_neg`."] lemma left.mul_lt_one_of_le_of_lt [covariant_class α α (*) (<)] {a b : α} (ha : a ≤ 1) (hb : b < 1) : a * b < 1 := mul_lt_of_le_of_lt_one ha hb /-- Assumes left covariance. The lemma assuming right covariance is `right.mul_lt_one_of_lt_of_le`. -/ @[to_additive left.add_neg_of_neg_of_nonpos "Assumes left covariance. The lemma assuming right covariance is `right.add_neg_of_neg_of_nonpos`."] lemma left.mul_lt_one_of_lt_of_le [covariant_class α α (*) (≤)] {a b : α} (ha : a < 1) (hb : b ≤ 1) : a * b < 1 := mul_lt_of_lt_of_le_one ha hb /-- Assumes left covariance. The lemma assuming right covariance is `right.mul_lt_one`. -/ @[to_additive "Assumes left covariance. The lemma assuming right covariance is `right.add_neg`."] lemma left.mul_lt_one [covariant_class α α (*) (<)] {a b : α} (ha : a < 1) (hb : b < 1) : a * b < 1 := mul_lt_of_lt_of_lt_one ha hb /-- Assumes left covariance. The lemma assuming right covariance is `right.mul_lt_one'`. -/ @[to_additive "Assumes left covariance. The lemma assuming right covariance is `right.add_neg'`."] lemma left.mul_lt_one' [covariant_class α α (*) (≤)] {a b : α} (ha : a < 1) (hb : b < 1) : a * b < 1 := mul_lt_of_lt_of_lt_one' ha hb /-! Lemmas of the form `b ≤ c → 1 ≤ a → b ≤ c * a`, which assume left covariance. -/ @[to_additive] lemma le_mul_of_le_of_one_le [covariant_class α α (*) (≤)] {a b c : α} (hbc : b ≤ c) (ha : 1 ≤ a) : b ≤ c * a := calc b ≤ c : hbc ... = c * 1 : (mul_one c).symm ... ≤ c * a : mul_le_mul_left' ha c @[to_additive] lemma lt_mul_of_le_of_one_lt [covariant_class α α (*) (<)] {a b c : α} (hbc : b ≤ c) (ha : 1 < a) : b < c * a := calc b ≤ c : hbc ... = c * 1 : (mul_one c).symm ... < c * a : mul_lt_mul_left' ha c @[to_additive] lemma lt_mul_of_lt_of_one_le [covariant_class α α (*) (≤)] {a b c : α} (hbc : b < c) (ha : 1 ≤ a) : b < c * a := calc b < c : hbc ... = c * 1 : (mul_one c).symm ... ≤ c * a : mul_le_mul_left' ha c @[to_additive] lemma lt_mul_of_lt_of_one_lt [covariant_class α α (*) (<)] {a b c : α} (hbc : b < c) (ha : 1 < a) : b < c * a := calc b < c : hbc ... = c * 1 : (mul_one c).symm ... < c * a : mul_lt_mul_left' ha c @[to_additive] lemma lt_mul_of_lt_of_one_lt' [covariant_class α α (*) (≤)] {a b c : α} (hbc : b < c) (ha : 1 < a) : b < c * a := lt_mul_of_lt_of_one_le hbc ha.le /-- Assumes left covariance. The lemma assuming right covariance is `right.one_le_mul`. -/ @[to_additive left.add_nonneg "Assumes left covariance. The lemma assuming right covariance is `right.add_nonneg`."] lemma left.one_le_mul [covariant_class α α (*) (≤)] {a b : α} (ha : 1 ≤ a) (hb : 1 ≤ b) : 1 ≤ a * b := le_mul_of_le_of_one_le ha hb /-- Assumes left covariance. The lemma assuming right covariance is `right.one_lt_mul_of_le_of_lt`. -/ @[to_additive left.add_pos_of_nonneg_of_pos "Assumes left covariance. The lemma assuming right covariance is `right.add_pos_of_nonneg_of_pos`."] lemma left.one_lt_mul_of_le_of_lt [covariant_class α α (*) (<)] {a b : α} (ha : 1 ≤ a) (hb : 1 < b) : 1 < a * b := lt_mul_of_le_of_one_lt ha hb /-- Assumes left covariance. The lemma assuming right covariance is `right.one_lt_mul_of_lt_of_le`. -/ @[to_additive left.add_pos_of_pos_of_nonneg "Assumes left covariance. The lemma assuming right covariance is `right.add_pos_of_pos_of_nonneg`."] lemma left.one_lt_mul_of_lt_of_le [covariant_class α α (*) (≤)] {a b : α} (ha : 1 < a) (hb : 1 ≤ b) : 1 < a * b := lt_mul_of_lt_of_one_le ha hb /-- Assumes left covariance. The lemma assuming right covariance is `right.one_lt_mul`. -/ @[to_additive left.add_pos "Assumes left covariance. The lemma assuming right covariance is `right.add_pos`."] lemma left.one_lt_mul [covariant_class α α (*) (<)] {a b : α} (ha : 1 < a) (hb : 1 < b) : 1 < a * b := lt_mul_of_lt_of_one_lt ha hb /-- Assumes left covariance. The lemma assuming right covariance is `right.one_lt_mul'`. -/ @[to_additive left.add_pos' "Assumes left covariance. The lemma assuming right covariance is `right.add_pos'`."] lemma left.one_lt_mul' [covariant_class α α (*) (≤)] {a b : α} (ha : 1 < a) (hb : 1 < b) : 1 < a * b := lt_mul_of_lt_of_one_lt' ha hb /-! Lemmas of the form `a ≤ 1 → b ≤ c → a * b ≤ c`, which assume right covariance. -/ @[to_additive] lemma mul_le_of_le_one_of_le [covariant_class α α (swap (*)) (≤)] {a b c : α} (ha : a ≤ 1) (hbc : b ≤ c) : a * b ≤ c := calc a * b ≤ 1 * b : mul_le_mul_right' ha b ... = b : one_mul b ... ≤ c : hbc @[to_additive] lemma mul_lt_of_lt_one_of_le [covariant_class α α (swap (*)) (<)] {a b c : α} (ha : a < 1) (hbc : b ≤ c) : a * b < c := calc a * b < 1 * b : mul_lt_mul_right' ha b ... = b : one_mul b ... ≤ c : hbc @[to_additive] lemma mul_lt_of_le_one_of_lt [covariant_class α α (swap (*)) (≤)] {a b c : α} (ha : a ≤ 1) (hb : b < c) : a * b < c := calc a * b ≤ 1 * b : mul_le_mul_right' ha b ... = b : one_mul b ... < c : hb @[to_additive] lemma mul_lt_of_lt_one_of_lt [covariant_class α α (swap (*)) (<)] {a b c : α} (ha : a < 1) (hb : b < c) : a * b < c := calc a * b < 1 * b : mul_lt_mul_right' ha b ... = b : one_mul b ... < c : hb @[to_additive] lemma mul_lt_of_lt_one_of_lt' [covariant_class α α (swap (*)) (≤)] {a b c : α} (ha : a < 1) (hbc : b < c) : a * b < c := mul_lt_of_le_one_of_lt ha.le hbc /-- Assumes right covariance. The lemma assuming left covariance is `left.mul_le_one`. -/ @[to_additive "Assumes right covariance. The lemma assuming left covariance is `left.add_nonpos`."] lemma right.mul_le_one [covariant_class α α (swap (*)) (≤)] {a b : α} (ha : a ≤ 1) (hb : b ≤ 1) : a * b ≤ 1 := mul_le_of_le_one_of_le ha hb /-- Assumes right covariance. The lemma assuming left covariance is `left.mul_lt_one_of_lt_of_le`. -/ @[to_additive right.add_neg_of_neg_of_nonpos "Assumes right covariance. The lemma assuming left covariance is `left.add_neg_of_neg_of_nonpos`."] lemma right.mul_lt_one_of_lt_of_le [covariant_class α α (swap (*)) (<)] {a b : α} (ha : a < 1) (hb : b ≤ 1) : a * b < 1 := mul_lt_of_lt_one_of_le ha hb /-- Assumes right covariance. The lemma assuming left covariance is `left.mul_lt_one_of_le_of_lt`. -/ @[to_additive right.add_neg_of_nonpos_of_neg "Assumes right covariance. The lemma assuming left covariance is `left.add_neg_of_nonpos_of_neg`."] lemma right.mul_lt_one_of_le_of_lt [covariant_class α α (swap (*)) (≤)] {a b : α} (ha : a ≤ 1) (hb : b < 1) : a * b < 1 := mul_lt_of_le_one_of_lt ha hb /-- Assumes right covariance. The lemma assuming left covariance is `left.mul_lt_one`. -/ @[to_additive "Assumes right covariance. The lemma assuming left covariance is `left.add_neg`."] lemma right.mul_lt_one [covariant_class α α (swap (*)) (<)] {a b : α} (ha : a < 1) (hb : b < 1) : a * b < 1 := mul_lt_of_lt_one_of_lt ha hb /-- Assumes right covariance. The lemma assuming left covariance is `left.mul_lt_one'`. -/ @[to_additive "Assumes right covariance. The lemma assuming left covariance is `left.add_neg'`."] lemma right.mul_lt_one' [covariant_class α α (swap (*)) (≤)] {a b : α} (ha : a < 1) (hb : b < 1) : a * b < 1 := mul_lt_of_lt_one_of_lt' ha hb /-! Lemmas of the form `1 ≤ a → b ≤ c → b ≤ a * c`, which assume right covariance. -/ @[to_additive] lemma le_mul_of_one_le_of_le [covariant_class α α (swap (*)) (≤)] {a b c : α} (ha : 1 ≤ a) (hbc : b ≤ c) : b ≤ a * c := calc b ≤ c : hbc ... = 1 * c : (one_mul c).symm ... ≤ a * c : mul_le_mul_right' ha c @[to_additive] lemma lt_mul_of_one_lt_of_le [covariant_class α α (swap (*)) (<)] {a b c : α} (ha : 1 < a) (hbc : b ≤ c) : b < a * c := calc b ≤ c : hbc ... = 1 * c : (one_mul c).symm ... < a * c : mul_lt_mul_right' ha c @[to_additive] lemma lt_mul_of_one_le_of_lt [covariant_class α α (swap (*)) (≤)] {a b c : α} (ha : 1 ≤ a) (hbc : b < c) : b < a * c := calc b < c : hbc ... = 1 * c : (one_mul c).symm ... ≤ a * c : mul_le_mul_right' ha c @[to_additive] lemma lt_mul_of_one_lt_of_lt [covariant_class α α (swap (*)) (<)] {a b c : α} (ha : 1 < a) (hbc : b < c) : b < a * c := calc b < c : hbc ... = 1 * c : (one_mul c).symm ... < a * c : mul_lt_mul_right' ha c @[to_additive] lemma lt_mul_of_one_lt_of_lt' [covariant_class α α (swap (*)) (≤)] {a b c : α} (ha : 1 < a) (hbc : b < c) : b < a * c := lt_mul_of_one_le_of_lt ha.le hbc /-- Assumes right covariance. The lemma assuming left covariance is `left.one_le_mul`. -/ @[to_additive right.add_nonneg "Assumes right covariance. The lemma assuming left covariance is `left.add_nonneg`."] lemma right.one_le_mul [covariant_class α α (swap (*)) (≤)] {a b : α} (ha : 1 ≤ a) (hb : 1 ≤ b) : 1 ≤ a * b := le_mul_of_one_le_of_le ha hb /-- Assumes right covariance. The lemma assuming left covariance is `left.one_lt_mul_of_lt_of_le`. -/ @[to_additive right.add_pos_of_pos_of_nonneg "Assumes right covariance. The lemma assuming left covariance is `left.add_pos_of_pos_of_nonneg`."] lemma right.one_lt_mul_of_lt_of_le [covariant_class α α (swap (*)) (<)] {a b : α} (ha : 1 < a) (hb : 1 ≤ b) : 1 < a * b := lt_mul_of_one_lt_of_le ha hb /-- Assumes right covariance. The lemma assuming left covariance is `left.one_lt_mul_of_le_of_lt`. -/ @[to_additive right.add_pos_of_nonneg_of_pos "Assumes right covariance. The lemma assuming left covariance is `left.add_pos_of_nonneg_of_pos`."] lemma right.one_lt_mul_of_le_of_lt [covariant_class α α (swap (*)) (≤)] {a b : α} (ha : 1 ≤ a) (hb : 1 < b) : 1 < a * b := lt_mul_of_one_le_of_lt ha hb /-- Assumes right covariance. The lemma assuming left covariance is `left.one_lt_mul`. -/ @[to_additive right.add_pos "Assumes right covariance. The lemma assuming left covariance is `left.add_pos`."] lemma right.one_lt_mul [covariant_class α α (swap (*)) (<)] {a b : α} (ha : 1 < a) (hb : 1 < b) : 1 < a * b := lt_mul_of_one_lt_of_lt ha hb /-- Assumes right covariance. The lemma assuming left covariance is `left.one_lt_mul'`. -/ @[to_additive right.add_pos' "Assumes right covariance. The lemma assuming left covariance is `left.add_pos'`."] lemma right.one_lt_mul' [covariant_class α α (swap (*)) (≤)] {a b : α} (ha : 1 < a) (hb : 1 < b) : 1 < a * b := lt_mul_of_one_lt_of_lt' ha hb alias left.mul_le_one ← mul_le_one' alias left.mul_lt_one_of_le_of_lt ← mul_lt_one_of_le_of_lt alias left.mul_lt_one_of_lt_of_le ← mul_lt_one_of_lt_of_le alias left.mul_lt_one ← mul_lt_one alias left.mul_lt_one' ← mul_lt_one' attribute [to_additive add_nonpos "**Alias** of `left.add_nonpos`."] mul_le_one' attribute [to_additive add_neg_of_nonpos_of_neg "**Alias** of `left.add_neg_of_nonpos_of_neg`."] mul_lt_one_of_le_of_lt attribute [to_additive add_neg_of_neg_of_nonpos "**Alias** of `left.add_neg_of_neg_of_nonpos`."] mul_lt_one_of_lt_of_le attribute [to_additive "**Alias** of `left.add_neg`."] mul_lt_one attribute [to_additive "**Alias** of `left.add_neg'`."] mul_lt_one' alias left.one_le_mul ← one_le_mul alias left.one_lt_mul_of_le_of_lt ← one_lt_mul_of_le_of_lt' alias left.one_lt_mul_of_lt_of_le ← one_lt_mul_of_lt_of_le' alias left.one_lt_mul ← one_lt_mul' alias left.one_lt_mul' ← one_lt_mul'' attribute [to_additive add_nonneg "**Alias** of `left.add_nonneg`."] one_le_mul attribute [to_additive add_pos_of_nonneg_of_pos "**Alias** of `left.add_pos_of_nonneg_of_pos`."] one_lt_mul_of_le_of_lt' attribute [to_additive add_pos_of_pos_of_nonneg "**Alias** of `left.add_pos_of_pos_of_nonneg`."] one_lt_mul_of_lt_of_le' attribute [to_additive add_pos "**Alias** of `left.add_pos`."] one_lt_mul' attribute [to_additive add_pos' "**Alias** of `left.add_pos'`."] one_lt_mul'' @[to_additive] lemma lt_of_mul_lt_of_one_le_left [covariant_class α α (*) (≤)] {a b c : α} (h : a * b < c) (hle : 1 ≤ b) : a < c := (le_mul_of_one_le_right' hle).trans_lt h @[to_additive] lemma le_of_mul_le_of_one_le_left [covariant_class α α (*) (≤)] {a b c : α} (h : a * b ≤ c) (hle : 1 ≤ b) : a ≤ c := (le_mul_of_one_le_right' hle).trans h @[to_additive] lemma lt_of_lt_mul_of_le_one_left [covariant_class α α (*) (≤)] {a b c : α} (h : a < b * c) (hle : c ≤ 1) : a < b := h.trans_le (mul_le_of_le_one_right' hle) @[to_additive] lemma le_of_le_mul_of_le_one_left [covariant_class α α (*) (≤)] {a b c : α} (h : a ≤ b * c) (hle : c ≤ 1) : a ≤ b := h.trans (mul_le_of_le_one_right' hle) @[to_additive] lemma lt_of_mul_lt_of_one_le_right [covariant_class α α (swap (*)) (≤)] {a b c : α} (h : a * b < c) (hle : 1 ≤ a) : b < c := (le_mul_of_one_le_left' hle).trans_lt h @[to_additive] lemma le_of_mul_le_of_one_le_right [covariant_class α α (swap (*)) (≤)] {a b c : α} (h : a * b ≤ c) (hle : 1 ≤ a) : b ≤ c := (le_mul_of_one_le_left' hle).trans h @[to_additive] lemma lt_of_lt_mul_of_le_one_right [covariant_class α α (swap (*)) (≤)] {a b c : α} (h : a < b * c) (hle : b ≤ 1) : a < c := h.trans_le (mul_le_of_le_one_left' hle) @[to_additive] lemma le_of_le_mul_of_le_one_right [covariant_class α α (swap (*)) (≤)] {a b c : α} (h : a ≤ b * c) (hle : b ≤ 1) : a ≤ c := h.trans (mul_le_of_le_one_left' hle) end preorder section partial_order variables [partial_order α] @[to_additive] lemma mul_eq_one_iff' [covariant_class α α (*) (≤)] [covariant_class α α (swap (*)) (≤)] {a b : α} (ha : 1 ≤ a) (hb : 1 ≤ b) : a * b = 1 ↔ a = 1 ∧ b = 1 := iff.intro (assume hab : a * b = 1, have a ≤ 1, from hab ▸ le_mul_of_le_of_one_le le_rfl hb, have a = 1, from le_antisymm this ha, have b ≤ 1, from hab ▸ le_mul_of_one_le_of_le ha le_rfl, have b = 1, from le_antisymm this hb, and.intro ‹a = 1› ‹b = 1›) (assume ⟨ha', hb'⟩, by rw [ha', hb', mul_one]) section left variables [covariant_class α α (*) (≤)] {a b : α} @[to_additive eq_zero_of_add_nonneg_left] lemma eq_one_of_one_le_mul_left (ha : a ≤ 1) (hb : b ≤ 1) (hab : 1 ≤ a * b) : a = 1 := ha.eq_of_not_lt $ λ h, hab.not_lt $ mul_lt_one_of_lt_of_le h hb @[to_additive] lemma eq_one_of_mul_le_one_left (ha : 1 ≤ a) (hb : 1 ≤ b) (hab : a * b ≤ 1) : a = 1 := ha.eq_of_not_gt $ λ h, hab.not_lt $ one_lt_mul_of_lt_of_le' h hb end left section right variables [covariant_class α α (swap (*)) (≤)] {a b : α} @[to_additive eq_zero_of_add_nonneg_right] lemma eq_one_of_one_le_mul_right (ha : a ≤ 1) (hb : b ≤ 1) (hab : 1 ≤ a * b) : b = 1 := hb.eq_of_not_lt $ λ h, hab.not_lt $ right.mul_lt_one_of_le_of_lt ha h @[to_additive] lemma eq_one_of_mul_le_one_right (ha : 1 ≤ a) (hb : 1 ≤ b) (hab : a * b ≤ 1) : b = 1 := hb.eq_of_not_gt $ λ h, hab.not_lt $ right.one_lt_mul_of_le_of_lt ha h end right end partial_order section linear_order variables [linear_order α] lemma exists_square_le [covariant_class α α (*) (<)] (a : α) : ∃ (b : α), b * b ≤ a := begin by_cases h : a < 1, { use a, have : a*a < a*1, exact mul_lt_mul_left' h a, rw mul_one at this, exact le_of_lt this }, { use 1, push_neg at h, rwa mul_one } end end linear_order end mul_one_class section semigroup variables [semigroup α] section partial_order variables [partial_order α] /- This is not instance, since we want to have an instance from `left_cancel_semigroup`s to the appropriate `covariant_class`. -/ /-- A semigroup with a partial order and satisfying `left_cancel_semigroup` (i.e. `a * c < b * c → a < b`) is a `left_cancel semigroup`. -/ @[to_additive "An additive semigroup with a partial order and satisfying `left_cancel_add_semigroup` (i.e. `c + a < c + b → a < b`) is a `left_cancel add_semigroup`."] def contravariant.to_left_cancel_semigroup [contravariant_class α α (*) (≤)] : left_cancel_semigroup α := { mul_left_cancel := λ a b c, mul_left_cancel'' ..‹semigroup α› } /- This is not instance, since we want to have an instance from `right_cancel_semigroup`s to the appropriate `covariant_class`. -/ /-- A semigroup with a partial order and satisfying `right_cancel_semigroup` (i.e. `a * c < b * c → a < b`) is a `right_cancel semigroup`. -/ @[to_additive "An additive semigroup with a partial order and satisfying `right_cancel_add_semigroup` (`a + c < b + c → a < b`) is a `right_cancel add_semigroup`."] def contravariant.to_right_cancel_semigroup [contravariant_class α α (swap (*)) (≤)] : right_cancel_semigroup α := { mul_right_cancel := λ a b c, mul_right_cancel'' ..‹semigroup α› } @[to_additive] lemma left.mul_eq_mul_iff_eq_and_eq [covariant_class α α (*) (<)] [covariant_class α α (swap (*)) (≤)] [contravariant_class α α (*) (≤)] [contravariant_class α α (swap (*)) (≤)] {a b c d : α} (hac : a ≤ c) (hbd : b ≤ d) : a * b = c * d ↔ a = c ∧ b = d := begin refine ⟨λ h, _, λ h, congr_arg2 (*) h.1 h.2⟩, rcases hac.eq_or_lt with rfl | hac, { exact ⟨rfl, mul_left_cancel'' h⟩ }, rcases eq_or_lt_of_le hbd with rfl | hbd, { exact ⟨mul_right_cancel'' h, rfl⟩ }, exact ((left.mul_lt_mul hac hbd).ne h).elim, end @[to_additive] lemma right.mul_eq_mul_iff_eq_and_eq [covariant_class α α (*) (≤)] [contravariant_class α α (*) (≤)] [covariant_class α α (swap (*)) (<)] [contravariant_class α α (swap (*)) (≤)] {a b c d : α} (hac : a ≤ c) (hbd : b ≤ d) : a * b = c * d ↔ a = c ∧ b = d := begin refine ⟨λ h, _, λ h, congr_arg2 (*) h.1 h.2⟩, rcases hac.eq_or_lt with rfl | hac, { exact ⟨rfl, mul_left_cancel'' h⟩ }, rcases eq_or_lt_of_le hbd with rfl | hbd, { exact ⟨mul_right_cancel'' h, rfl⟩ }, exact ((right.mul_lt_mul hac hbd).ne h).elim, end alias left.mul_eq_mul_iff_eq_and_eq ← mul_eq_mul_iff_eq_and_eq attribute [to_additive] mul_eq_mul_iff_eq_and_eq end partial_order end semigroup section mono variables [has_mul α] [preorder α] [preorder β] {f g : β → α} {s : set β} @[to_additive const_add] lemma monotone.const_mul' [covariant_class α α (*) (≤)] (hf : monotone f) (a : α) : monotone (λ x, a * f x) := λ x y h, mul_le_mul_left' (hf h) a @[to_additive const_add] lemma monotone_on.const_mul' [covariant_class α α (*) (≤)] (hf : monotone_on f s) (a : α) : monotone_on (λ x, a * f x) s := λ x hx y hy h, mul_le_mul_left' (hf hx hy h) a @[to_additive const_add] lemma antitone.const_mul' [covariant_class α α (*) (≤)] (hf : antitone f) (a : α) : antitone (λ x, a * f x) := λ x y h, mul_le_mul_left' (hf h) a @[to_additive const_add] lemma antitone_on.const_mul' [covariant_class α α (*) (≤)] (hf : antitone_on f s) (a : α) : antitone_on (λ x, a * f x) s := λ x hx y hy h, mul_le_mul_left' (hf hx hy h) a @[to_additive add_const] lemma monotone.mul_const' [covariant_class α α (swap (*)) (≤)] (hf : monotone f) (a : α) : monotone (λ x, f x * a) := λ x y h, mul_le_mul_right' (hf h) a @[to_additive add_const] lemma monotone_on.mul_const' [covariant_class α α (swap (*)) (≤)] (hf : monotone_on f s) (a : α) : monotone_on (λ x, f x * a) s := λ x hx y hy h, mul_le_mul_right' (hf hx hy h) a @[to_additive add_const] lemma antitone.mul_const' [covariant_class α α (swap (*)) (≤)] (hf : antitone f) (a : α) : antitone (λ x, f x * a) := λ x y h, mul_le_mul_right' (hf h) a @[to_additive add_const] lemma antitone_on.mul_const' [covariant_class α α (swap (*)) (≤)] (hf : antitone_on f s) (a : α) : antitone_on (λ x, f x * a) s := λ x hx y hy h, mul_le_mul_right' (hf hx hy h) a /-- The product of two monotone functions is monotone. -/ @[to_additive add "The sum of two monotone functions is monotone."] lemma monotone.mul' [covariant_class α α (*) (≤)] [covariant_class α α (swap (*)) (≤)] (hf : monotone f) (hg : monotone g) : monotone (λ x, f x * g x) := λ x y h, mul_le_mul' (hf h) (hg h) /-- The product of two monotone functions is monotone. -/ @[to_additive add "The sum of two monotone functions is monotone."] lemma monotone_on.mul' [covariant_class α α (*) (≤)] [covariant_class α α (swap (*)) (≤)] (hf : monotone_on f s) (hg : monotone_on g s) : monotone_on (λ x, f x * g x) s := λ x hx y hy h, mul_le_mul' (hf hx hy h) (hg hx hy h) /-- The product of two antitone functions is antitone. -/ @[to_additive add "The sum of two antitone functions is antitone."] lemma antitone.mul' [covariant_class α α (*) (≤)] [covariant_class α α (swap (*)) (≤)] (hf : antitone f) (hg : antitone g) : antitone (λ x, f x * g x) := λ x y h, mul_le_mul' (hf h) (hg h) /-- The product of two antitone functions is antitone. -/ @[to_additive add "The sum of two antitone functions is antitone."] lemma antitone_on.mul' [covariant_class α α (*) (≤)] [covariant_class α α (swap (*)) (≤)] (hf : antitone_on f s) (hg : antitone_on g s) : antitone_on (λ x, f x * g x) s := λ x hx y hy h, mul_le_mul' (hf hx hy h) (hg hx hy h) section left variables [covariant_class α α (*) (<)] @[to_additive const_add] lemma strict_mono.const_mul' (hf : strict_mono f) (c : α) : strict_mono (λ x, c * f x) := λ a b ab, mul_lt_mul_left' (hf ab) c @[to_additive const_add] lemma strict_mono_on.const_mul' (hf : strict_mono_on f s) (c : α) : strict_mono_on (λ x, c * f x) s := λ a ha b hb ab, mul_lt_mul_left' (hf ha hb ab) c @[to_additive const_add] lemma strict_anti.const_mul' (hf : strict_anti f) (c : α) : strict_anti (λ x, c * f x) := λ a b ab, mul_lt_mul_left' (hf ab) c @[to_additive const_add] lemma strict_anti_on.const_mul' (hf : strict_anti_on f s) (c : α) : strict_anti_on (λ x, c * f x) s := λ a ha b hb ab, mul_lt_mul_left' (hf ha hb ab) c end left section right variables [covariant_class α α (swap (*)) (<)] @[to_additive add_const] lemma strict_mono.mul_const' (hf : strict_mono f) (c : α) : strict_mono (λ x, f x * c) := λ a b ab, mul_lt_mul_right' (hf ab) c @[to_additive add_const] lemma strict_mono_on.mul_const' (hf : strict_mono_on f s) (c : α) : strict_mono_on (λ x, f x * c) s := λ a ha b hb ab, mul_lt_mul_right' (hf ha hb ab) c @[to_additive add_const] lemma strict_anti.mul_const' (hf : strict_anti f) (c : α) : strict_anti (λ x, f x * c) := λ a b ab, mul_lt_mul_right' (hf ab) c @[to_additive add_const] lemma strict_anti_on.mul_const' (hf : strict_anti_on f s) (c : α) : strict_anti_on (λ x, f x * c) s := λ a ha b hb ab, mul_lt_mul_right' (hf ha hb ab) c end right /-- The product of two strictly monotone functions is strictly monotone. -/ @[to_additive add "The sum of two strictly monotone functions is strictly monotone."] lemma strict_mono.mul' [covariant_class α α (*) (<)] [covariant_class α α (swap (*)) (<)] (hf : strict_mono f) (hg : strict_mono g) : strict_mono (λ x, f x * g x) := λ a b ab, mul_lt_mul_of_lt_of_lt (hf ab) (hg ab) /-- The product of two strictly monotone functions is strictly monotone. -/ @[to_additive add "The sum of two strictly monotone functions is strictly monotone."] lemma strict_mono_on.mul' [covariant_class α α (*) (<)] [covariant_class α α (swap (*)) (<)] (hf : strict_mono_on f s) (hg : strict_mono_on g s) : strict_mono_on (λ x, f x * g x) s := λ a ha b hb ab, mul_lt_mul_of_lt_of_lt (hf ha hb ab) (hg ha hb ab) /-- The product of two strictly antitone functions is strictly antitone. -/ @[to_additive add "The sum of two strictly antitone functions is strictly antitone."] lemma strict_anti.mul' [covariant_class α α (*) (<)] [covariant_class α α (swap (*)) (<)] (hf : strict_anti f) (hg : strict_anti g) : strict_anti (λ x, f x * g x) := λ a b ab, mul_lt_mul_of_lt_of_lt (hf ab) (hg ab) /-- The product of two strictly antitone functions is strictly antitone. -/ @[to_additive add "The sum of two strictly antitone functions is strictly antitone."] lemma strict_anti_on.mul' [covariant_class α α (*) (<)] [covariant_class α α (swap (*)) (<)] (hf : strict_anti_on f s) (hg : strict_anti_on g s) : strict_anti_on (λ x, f x * g x) s := λ a ha b hb ab, mul_lt_mul_of_lt_of_lt (hf ha hb ab) (hg ha hb ab) /-- The product of a monotone function and a strictly monotone function is strictly monotone. -/ @[to_additive add_strict_mono "The sum of a monotone function and a strictly monotone function is strictly monotone."] lemma monotone.mul_strict_mono' [covariant_class α α (*) (<)] [covariant_class α α (swap (*)) (≤)] {f g : β → α} (hf : monotone f) (hg : strict_mono g) : strict_mono (λ x, f x * g x) := λ x y h, mul_lt_mul_of_le_of_lt (hf h.le) (hg h) /-- The product of a monotone function and a strictly monotone function is strictly monotone. -/ @[to_additive add_strict_mono "The sum of a monotone function and a strictly monotone function is strictly monotone."] lemma monotone_on.mul_strict_mono' [covariant_class α α (*) (<)] [covariant_class α α (swap (*)) (≤)] {f g : β → α} (hf : monotone_on f s) (hg : strict_mono_on g s) : strict_mono_on (λ x, f x * g x) s := λ x hx y hy h, mul_lt_mul_of_le_of_lt (hf hx hy h.le) (hg hx hy h) /-- The product of a antitone function and a strictly antitone function is strictly antitone. -/ @[to_additive add_strict_anti "The sum of a antitone function and a strictly antitone function is strictly antitone."] lemma antitone.mul_strict_anti' [covariant_class α α (*) (<)] [covariant_class α α (swap (*)) (≤)] {f g : β → α} (hf : antitone f) (hg : strict_anti g) : strict_anti (λ x, f x * g x) := λ x y h, mul_lt_mul_of_le_of_lt (hf h.le) (hg h) /-- The product of a antitone function and a strictly antitone function is strictly antitone. -/ @[to_additive add_strict_anti "The sum of a antitone function and a strictly antitone function is strictly antitone."] lemma antitone_on.mul_strict_anti' [covariant_class α α (*) (<)] [covariant_class α α (swap (*)) (≤)] {f g : β → α} (hf : antitone_on f s) (hg : strict_anti_on g s) : strict_anti_on (λ x, f x * g x) s := λ x hx y hy h, mul_lt_mul_of_le_of_lt (hf hx hy h.le) (hg hx hy h) variables [covariant_class α α (*) (≤)] [covariant_class α α (swap (*)) (<)] /-- The product of a strictly monotone function and a monotone function is strictly monotone. -/ @[to_additive add_monotone "The sum of a strictly monotone function and a monotone function is strictly monotone."] lemma strict_mono.mul_monotone' (hf : strict_mono f) (hg : monotone g) : strict_mono (λ x, f x * g x) := λ x y h, mul_lt_mul_of_lt_of_le (hf h) (hg h.le) /-- The product of a strictly monotone function and a monotone function is strictly monotone. -/ @[to_additive add_monotone "The sum of a strictly monotone function and a monotone function is strictly monotone."] lemma strict_mono_on.mul_monotone' (hf : strict_mono_on f s) (hg : monotone_on g s) : strict_mono_on (λ x, f x * g x) s := λ x hx y hy h, mul_lt_mul_of_lt_of_le (hf hx hy h) (hg hx hy h.le) /-- The product of a strictly antitone function and a antitone function is strictly antitone. -/ @[to_additive add_antitone "The sum of a strictly antitone function and a antitone function is strictly antitone."] lemma strict_anti.mul_antitone' (hf : strict_anti f) (hg : antitone g) : strict_anti (λ x, f x * g x) := λ x y h, mul_lt_mul_of_lt_of_le (hf h) (hg h.le) /-- The product of a strictly antitone function and a antitone function is strictly antitone. -/ @[to_additive add_antitone "The sum of a strictly antitone function and a antitone function is strictly antitone."] lemma strict_anti_on.mul_antitone' (hf : strict_anti_on f s) (hg : antitone_on g s) : strict_anti_on (λ x, f x * g x) s := λ x hx y hy h, mul_lt_mul_of_lt_of_le (hf hx hy h) (hg hx hy h.le) @[simp, to_additive cmp_add_left] lemma cmp_mul_left' {α : Type*} [has_mul α] [linear_order α] [covariant_class α α (*) (<)] (a b c : α) : cmp (a * b) (a * c) = cmp b c := (strict_mono_id.const_mul' a).cmp_map_eq b c @[simp, to_additive cmp_add_right] lemma cmp_mul_right' {α : Type*} [has_mul α] [linear_order α] [covariant_class α α (swap (*)) (<)] (a b c : α) : cmp (a * c) (b * c) = cmp a b := (strict_mono_id.mul_const' c).cmp_map_eq a b end mono /-- An element `a : α` is `mul_le_cancellable` if `x ↦ a * x` is order-reflecting. We will make a separate version of many lemmas that require `[contravariant_class α α (*) (≤)]` with `mul_le_cancellable` assumptions instead. These lemmas can then be instantiated to specific types, like `ennreal`, where we can replace the assumption `add_le_cancellable x` by `x ≠ ∞`. -/ @[to_additive /-" An element `a : α` is `add_le_cancellable` if `x ↦ a + x` is order-reflecting. We will make a separate version of many lemmas that require `[contravariant_class α α (+) (≤)]` with `mul_le_cancellable` assumptions instead. These lemmas can then be instantiated to specific types, like `ennreal`, where we can replace the assumption `add_le_cancellable x` by `x ≠ ∞`. "-/ ] def mul_le_cancellable [has_mul α] [has_le α] (a : α) : Prop := ∀ ⦃b c⦄, a * b ≤ a * c → b ≤ c @[to_additive] lemma contravariant.mul_le_cancellable [has_mul α] [has_le α] [contravariant_class α α (*) (≤)] {a : α} : mul_le_cancellable a := λ b c, le_of_mul_le_mul_left' @[to_additive] lemma mul_le_cancellable_one [monoid α] [has_le α] : mul_le_cancellable (1 : α) := λ a b, by simpa only [one_mul] using id namespace mul_le_cancellable @[to_additive] protected lemma injective [has_mul α] [partial_order α] {a : α} (ha : mul_le_cancellable a) : injective ((*) a) := λ b c h, le_antisymm (ha h.le) (ha h.ge) @[to_additive] protected lemma inj [has_mul α] [partial_order α] {a b c : α} (ha : mul_le_cancellable a) : a * b = a * c ↔ b = c := ha.injective.eq_iff @[to_additive] protected lemma injective_left [comm_semigroup α] [partial_order α] {a : α} (ha : mul_le_cancellable a) : injective (* a) := λ b c h, ha.injective $ by rwa [mul_comm a, mul_comm a] @[to_additive] protected lemma inj_left [comm_semigroup α] [partial_order α] {a b c : α} (hc : mul_le_cancellable c) : a * c = b * c ↔ a = b := hc.injective_left.eq_iff variable [has_le α] @[to_additive] protected lemma mul_le_mul_iff_left [has_mul α] [covariant_class α α (*) (≤)] {a b c : α} (ha : mul_le_cancellable a) : a * b ≤ a * c ↔ b ≤ c := ⟨λ h, ha h, λ h, mul_le_mul_left' h a⟩ @[to_additive] protected lemma mul_le_mul_iff_right [comm_semigroup α] [covariant_class α α (*) (≤)] {a b c : α} (ha : mul_le_cancellable a) : b * a ≤ c * a ↔ b ≤ c := by rw [mul_comm b, mul_comm c, ha.mul_le_mul_iff_left] @[to_additive] protected lemma le_mul_iff_one_le_right [mul_one_class α] [covariant_class α α (*) (≤)] {a b : α} (ha : mul_le_cancellable a) : a ≤ a * b ↔ 1 ≤ b := iff.trans (by rw [mul_one]) ha.mul_le_mul_iff_left @[to_additive] protected lemma mul_le_iff_le_one_right [mul_one_class α] [covariant_class α α (*) (≤)] {a b : α} (ha : mul_le_cancellable a) : a * b ≤ a ↔ b ≤ 1 := iff.trans (by rw [mul_one]) ha.mul_le_mul_iff_left @[to_additive] protected lemma le_mul_iff_one_le_left [comm_monoid α] [covariant_class α α (*) (≤)] {a b : α} (ha : mul_le_cancellable a) : a ≤ b * a ↔ 1 ≤ b := by rw [mul_comm, ha.le_mul_iff_one_le_right] @[to_additive] protected lemma mul_le_iff_le_one_left [comm_monoid α] [covariant_class α α (*) (≤)] {a b : α} (ha : mul_le_cancellable a) : b * a ≤ a ↔ b ≤ 1 := by rw [mul_comm, ha.mul_le_iff_le_one_right] end mul_le_cancellable
483e9d9caf74a2dc2a48df21750884e1cf575e82
968e2f50b755d3048175f176376eff7139e9df70
/examples/prop_logic_lean_summary/unnamed_138.lean
b594add11f36fd8ee2b7ae8f4e47bf8d57f21234
[]
no_license
gihanmarasingha/mth1001_sphinx
190a003269ba5e54717b448302a27ca26e31d491
05126586cbf5786e521be1ea2ef5b4ba3c44e74a
refs/heads/master
1,672,913,933,677
1,604,516,583,000
1,604,516,583,000
309,245,750
1
0
null
null
null
null
UTF-8
Lean
false
false
158
lean
variables p q : Prop -- BEGIN example (h : p ∧ q) : q := begin have hq : q, from h.right, -- Term-style right and elimination. exact hq, end -- END
2a179711b390bc60c5ac5356f56e42f4f5c4f614
4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d
/src/Lean/Elab/PreDefinition/WF/PackDomain.lean
b90a119f972688cda14d8d15dbdf285f46a02e48
[ "Apache-2.0" ]
permissive
subfish-zhou/leanprover-zh_CN.github.io
30b9fba9bd790720bd95764e61ae796697d2f603
8b2985d4a3d458ceda9361ac454c28168d920d3f
refs/heads/master
1,689,709,967,820
1,632,503,056,000
1,632,503,056,000
409,962,097
1
0
null
null
null
null
UTF-8
Lean
false
false
4,462
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.PreDefinition.Basic namespace Lean.Elab.WF open Meta /-- Given a (dependent) tuple `t` (using `PSigma`) of the given arity. Return an array containing its "elements". Example: `mkTupleElems a 4` returns `#[a.1, a.2.1, a.2.2.1, a.2.2.2]`. -/ private def mkTupleElems (t : Expr) (arity : Nat) : Array Expr := do let mut result := #[] let mut t := t for i in [:arity - 1] do result := result.push (mkProj ``PSigma 0 t) t := mkProj ``PSigma 1 t result.push t /-- Create a unary application by packing the given arguments using `PSigma.mk` -/ private partial def mkUnaryApp (unaryFn : Expr) (args : Array Expr) : MetaM Expr := do let Expr.forallE _ d .. ← inferType unaryFn | unreachable! go 0 d where go (i : Nat) (type : Expr) : MetaM Expr := do if i < args.size - 1 then let arg := args[i] assert! type.isAppOfArity ``PSigma 2 let us := type.getAppFn.constLevels! let α := type.appFn!.appArg! let β := type.appArg! assert! β.isLambda let type := β.bindingBody!.instantiate1 arg let rest ← go (i+1) type return mkApp4 (mkConst ``PSigma.mk us) α β arg rest else return args[i] /-- Convert the given pre-definitions into unary functions. We "pack" the arguments using `PSigma`. -/ def packDomain (preDefs : Array PreDefinition) : MetaM (Array PreDefinition) := do let mut preDefsNew := #[] let mut arities := #[] let mut modified := false for preDef in preDefs do let (preDefNew, arity, modifiedCurr) ← lambdaTelescope preDef.value fun xs body => do if xs.size > 1 then let bodyType ← instantiateForall preDef.type xs let mut d ← inferType xs.back for x in xs.pop.reverse do d ← mkAppOptM ``PSigma #[some (← inferType x), some (← mkLambdaFVars #[x] d)] withLocalDeclD (← mkFreshUserName `_x) d fun tuple => do let elems := mkTupleElems tuple xs.size let codomain := bodyType.replaceFVars xs elems let preDefNew:= { preDef with declName := preDef.declName ++ `_unary type := (← mkForallFVars #[tuple] codomain) } addAsAxiom preDefNew return (preDefNew, xs.size, true) else return (preDef, 1, false) modified := modified || modifiedCurr arities := arities.push arity preDefsNew := preDefsNew.push preDefNew if !modified then return preDefs /- Return `some i` if `e` is a `preDefs[i]` application -/ let isAppOfPreDef? (e : Expr) : OptionM Nat := do let f := e.getAppFn guard f.isConst preDefs.findIdx? (·.declName == f.constName!) /- Return `some i` if `e` is a `preDefs[i]` application with `arities[i]` arguments. -/ let isTargetApp? (e : Expr) : OptionM Nat := do let i ← isAppOfPreDef? e guard (e.getAppNumArgs == arities[i]) return i -- Update values for i in [:preDefs.size] do let preDef := preDefs[i] let preDefNew := preDefsNew[i] let arity := arities[i] let valueNew ← lambdaTelescope preDef.value fun xs body => do if arity > 1 then forallBoundedTelescope preDefNew.type (some 1) fun y _ => do let newBody := body.replaceFVars xs (mkTupleElems y[0] xs.size) trace[Elab.definition.wf] "newBody: {newBody}" let visit (e : Expr) : MetaM TransformStep := do if let some idx := isTargetApp? e |>.run then let f := e.getAppFn let fNew := mkConst preDefsNew[idx].declName f.constLevels! let argNew ← mkUnaryApp fNew e.getAppArgs return TransformStep.done <| mkApp fNew argNew else return TransformStep.done e mkLambdaFVars y (← transform newBody (post := visit)) else preDef.value if let some bad := valueNew.find? fun e => isAppOfPreDef? e |>.isSome then if let some i := isAppOfPreDef? bad then throwErrorAt preDef.ref "well-founded recursion cannot be used, function '{preDef.declName}' contains application of function '{preDefs[i].declName}' with #{bad.getAppNumArgs} argument(s), but function has arity {arities[i]}" preDefsNew := preDefsNew.set! i { preDefNew with value := valueNew } return preDefsNew end Lean.Elab.WF
414d58952027b89cc82ae1c96498053e94f2dff7
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/algebra/nonarchimedean/basic.lean
627036977fa6faf1a389c0109d9b864f27c8187f
[ "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
6,303
lean
/- Copyright (c) 2021 Ashwin Iyengar. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Johan Commelin, Ashwin Iyengar, Patrick Massot -/ import group_theory.subgroup.basic import topology.algebra.open_subgroup import topology.algebra.ring /-! # Nonarchimedean Topology In this file we set up the theory of nonarchimedean topological groups and rings. A nonarchimedean group is a topological group whose topology admits a basis of open neighborhoods of the identity element in the group consisting of open subgroups. A nonarchimedean ring is a topological ring whose underlying topological (additive) group is nonarchimedean. ## Definitions - `nonarchimedean_add_group`: nonarchimedean additive group. - `nonarchimedean_group`: nonarchimedean multiplicative group. - `nonarchimedean_ring`: nonarchimedean ring. -/ open_locale pointwise /-- An topological additive group is nonarchimedean if every neighborhood of 0 contains an open subgroup. -/ class nonarchimedean_add_group (G : Type*) [add_group G] [topological_space G] extends topological_add_group G : Prop := (is_nonarchimedean : ∀ U ∈ nhds (0 : G), ∃ V : open_add_subgroup G, (V : set G) ⊆ U) /-- A topological group is nonarchimedean if every neighborhood of 1 contains an open subgroup. -/ @[to_additive] class nonarchimedean_group (G : Type*) [group G] [topological_space G] extends topological_group G : Prop := (is_nonarchimedean : ∀ U ∈ nhds (1 : G), ∃ V : open_subgroup G, (V : set G) ⊆ U) /-- An topological ring is nonarchimedean if its underlying topological additive group is nonarchimedean. -/ class nonarchimedean_ring (R : Type*) [ring R] [topological_space R] extends topological_ring R : Prop := (is_nonarchimedean : ∀ U ∈ nhds (0 : R), ∃ V : open_add_subgroup R, (V : set R) ⊆ U) /-- Every nonarchimedean ring is naturally a nonarchimedean additive group. -/ @[priority 100] -- see Note [lower instance priority] instance nonarchimedean_ring.to_nonarchimedean_add_group (R : Type*) [ring R] [topological_space R] [t: nonarchimedean_ring R] : nonarchimedean_add_group R := {..t} namespace nonarchimedean_group variables {G : Type*} [group G] [topological_space G] [nonarchimedean_group G] variables {H : Type*} [group H] [topological_space H] [topological_group H] variables {K : Type*} [group K] [topological_space K] [nonarchimedean_group K] /-- If a topological group embeds into a nonarchimedean group, then it is nonarchimedean. -/ @[to_additive nonarchimedean_add_group.nonarchimedean_of_emb "If a topological group embeds into a nonarchimedean group, then it is nonarchimedean."] lemma nonarchimedean_of_emb (f : G →* H) (emb : open_embedding f) : nonarchimedean_group H := { is_nonarchimedean := λ U hU, have h₁ : (f ⁻¹' U) ∈ nhds (1 : G), from by {apply emb.continuous.tendsto, rwa f.map_one}, let ⟨V, hV⟩ := is_nonarchimedean (f ⁻¹' U) h₁ in ⟨{is_open' := emb.is_open_map _ V.is_open, ..subgroup.map f V}, set.image_subset_iff.2 hV⟩ } /-- An open neighborhood of the identity in the cartesian product of two nonarchimedean groups contains the cartesian product of an open neighborhood in each group. -/ @[to_additive nonarchimedean_add_group.prod_subset "An open neighborhood of the identity in the cartesian product of two nonarchimedean groups contains the cartesian product of an open neighborhood in each group."] lemma prod_subset {U} (hU : U ∈ nhds (1 : G × K)) : ∃ (V : open_subgroup G) (W : open_subgroup K), (V : set G) ×ˢ (W : set K) ⊆ U := begin erw [nhds_prod_eq, filter.mem_prod_iff] at hU, rcases hU with ⟨U₁, hU₁, U₂, hU₂, h⟩, cases is_nonarchimedean _ hU₁ with V hV, cases is_nonarchimedean _ hU₂ with W hW, use V, use W, rw set.prod_subset_iff, intros x hX y hY, exact set.subset.trans (set.prod_mono hV hW) h (set.mem_sep hX hY), end /-- An open neighborhood of the identity in the cartesian square of a nonarchimedean group contains the cartesian square of an open neighborhood in the group. -/ @[to_additive nonarchimedean_add_group.prod_self_subset "An open neighborhood of the identity in the cartesian square of a nonarchimedean group contains the cartesian square of an open neighborhood in the group."] lemma prod_self_subset {U} (hU : U ∈ nhds (1 : G × G)) : ∃ (V : open_subgroup G), (V : set G) ×ˢ (V : set G) ⊆ U := let ⟨V, W, h⟩ := prod_subset hU in ⟨V ⊓ W, by {refine set.subset.trans (set.prod_mono _ _) ‹_›; simp}⟩ /-- The cartesian product of two nonarchimedean groups is nonarchimedean. -/ @[to_additive "The cartesian product of two nonarchimedean groups is nonarchimedean."] instance : nonarchimedean_group (G × K) := { is_nonarchimedean := λ U hU, let ⟨V, W, h⟩ := prod_subset hU in ⟨V.prod W, ‹_›⟩ } end nonarchimedean_group namespace nonarchimedean_ring open nonarchimedean_ring open nonarchimedean_add_group variables {R S : Type*} variables [ring R] [topological_space R] [nonarchimedean_ring R] variables [ring S] [topological_space S] [nonarchimedean_ring S] /-- The cartesian product of two nonarchimedean rings is nonarchimedean. -/ instance : nonarchimedean_ring (R × S) := { is_nonarchimedean := nonarchimedean_add_group.is_nonarchimedean } /-- Given an open subgroup `U` and an element `r` of a nonarchimedean ring, there is an open subgroup `V` such that `r • V` is contained in `U`. -/ lemma left_mul_subset (U : open_add_subgroup R) (r : R) : ∃ V : open_add_subgroup R, r • (V : set R) ⊆ U := ⟨U.comap (add_monoid_hom.mul_left r) (continuous_mul_left r), (U : set R).image_preimage_subset _⟩ /-- An open subgroup of a nonarchimedean ring contains the square of another one. -/ lemma mul_subset (U : open_add_subgroup R) : ∃ V : open_add_subgroup R, (V : set R) * V ⊆ U := let ⟨V, H⟩ := prod_self_subset (is_open.mem_nhds (is_open.preimage continuous_mul U.is_open) begin simpa only [set.mem_preimage, open_add_subgroup.mem_coe, prod.snd_zero, mul_zero] using U.zero_mem, end) in begin use V, rintros v ⟨a, b, ha, hb, hv⟩, have hy := H (set.mk_mem_prod ha hb), simp only [set.mem_preimage, open_add_subgroup.mem_coe] at hy, rwa hv at hy end end nonarchimedean_ring
48c553ad84b0d6e333597491d0c9092269b7510d
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/analysis/normed_space/pi_Lp.lean
63a5c0410403f11947c62465d573d47fe43191ef
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,300
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.mean_inequalities /-! # `L^p` distance on finite products of metric spaces Given finitely many metric spaces, one can put the max distance on their product, but there is also a whole family of natural distances, indexed by a real parameter `p ∈ [1, ∞)`, that also induce the product topology. We define them in this file. The distance on `Π i, α i` is given by $$ d(x, y) = \left(\sum d(x_i, y_i)^p\right)^{1/p}. $$ We give instances of this construction for emetric spaces, metric spaces, normed groups and normed spaces. To avoid conflicting instances, all these are defined on a copy of the original Pi type, named `pi_Lp p hp α`, where `hp : 1 ≤ p`. This assumption is included in the definition of the type to make sure that it is always available to typeclass inference to construct the instances. We ensure that the topology and uniform structure on `pi_Lp p hp α` are (defeq to) the product topology and product uniformity, to be able to use freely continuity statements for the coordinate functions, for instance. ## Implementation notes We only deal with the `L^p` distance on a product of finitely many metric spaces, which may be distinct. A closely related construction is the `L^p` norm on the space of functions from a measure space to a normed space, where the norm is $$ \left(\int ∥f (x)∥^p dμ\right)^{1/p}. $$ However, the topology induced by this construction is not the product topology, this only defines a seminorm (as almost everywhere zero functions have zero `L^p` norm), and some functions have infinite `L^p` norm. All these subtleties are not present in the case of finitely many metric spaces (which corresponds to the basis which is a finite space with the counting measure), hence it is worth devoting a file to this specific case which is particularly well behaved. The general case is not yet formalized in mathlib. To prove that the topology (and the uniform structure) on a finite product with the `L^p` distance are the same as those coming from the `L^∞` distance, we could argue that the `L^p` and `L^∞` norms are equivalent on `ℝ^n` for abstract (norm equivalence) reasons. Instead, we give a more explicit (easy) proof which provides a comparison between these two norms with explicit constants. We also set up the theory for `pseudo_emetric_space` and `pseudo_metric_space`. -/ open real set filter is_R_or_C open_locale big_operators uniformity topological_space nnreal ennreal noncomputable theory variables {ι : Type*} /-- A copy of a Pi type, on which we will put the `L^p` distance. Since the Pi type itself is already endowed with the `L^∞` distance, we need the type synonym to avoid confusing typeclass resolution. Also, we let it depend on `p`, to get a whole family of type on which we can put different distances, and we provide the assumption `hp` in the definition, to make it available to typeclass resolution when it looks for a distance on `pi_Lp p hp α`. -/ @[nolint unused_arguments] def pi_Lp {ι : Type*} (p : ℝ) (hp : 1 ≤ p) (α : ι → Type*) : Type* := Π (i : ι), α i instance {ι : Type*} (p : ℝ) (hp : 1 ≤ p) (α : ι → Type*) [∀ i, inhabited (α i)] : inhabited (pi_Lp p hp α) := ⟨λ i, default (α i)⟩ namespace pi_Lp variables (p : ℝ) (hp : 1 ≤ p) (α : ι → Type*) (β : ι → Type*) /-- Canonical bijection between `pi_Lp p hp α` and the original Pi type. We introduce it to be able to compare the `L^p` and `L^∞` distances through it. -/ protected def equiv : pi_Lp p hp α ≃ Π (i : ι), α i := equiv.refl _ section /-! ### The uniformity on finite `L^p` products is the product uniformity In this section, we put the `L^p` edistance on `pi_Lp p hp α`, and we check that the uniformity coming from this edistance coincides with the product uniformity, by showing that the canonical map to the Pi type (with the `L^∞` distance) is a uniform embedding, as it is both Lipschitz and antiLipschitz. We only register this emetric space structure as a temporary instance, as the true instance (to be registered later) will have as uniformity exactly the product uniformity, instead of the one coming from the edistance (which is equal to it, but not defeq). See Note [forgetful inheritance] explaining why having definitionally the right uniformity is often important. -/ variables [∀ i, emetric_space (α i)] [∀ i, pseudo_emetric_space (β i)] [fintype ι] /-- Endowing the space `pi_Lp p hp β` with the `L^p` pseudoedistance. This definition is not satisfactory, as it does not register the fact that the topology and the uniform structure coincide with the product one. Therefore, we do not register it as an instance. Using this as a temporary pseudoemetric space instance, we will show that the uniform structure is equal (but not defeq) to the product one, and then register an instance in which we replace the uniform structure by the product one using this pseudoemetric space and `pseudo_emetric_space.replace_uniformity`. -/ def pseudo_emetric_aux : pseudo_emetric_space (pi_Lp p hp β) := have pos : 0 < p := lt_of_lt_of_le zero_lt_one hp, { edist := λ f g, (∑ (i : ι), (edist (f i) (g i)) ^ p) ^ (1/p), edist_self := λ f, by simp [edist, ennreal.zero_rpow_of_pos pos, ennreal.zero_rpow_of_pos (inv_pos.2 pos)], edist_comm := λ f g, by simp [edist, edist_comm], edist_triangle := λ f g h, calc (∑ (i : ι), edist (f i) (h i) ^ p) ^ (1 / p) ≤ (∑ (i : ι), (edist (f i) (g i) + edist (g i) (h i)) ^ p) ^ (1 / p) : begin apply ennreal.rpow_le_rpow _ (one_div_nonneg.2 $ le_of_lt pos), refine finset.sum_le_sum (λ i hi, _), exact ennreal.rpow_le_rpow (edist_triangle _ _ _) (le_trans zero_le_one hp) end ... ≤ (∑ (i : ι), edist (f i) (g i) ^ p) ^ (1 / p) + (∑ (i : ι), edist (g i) (h i) ^ p) ^ (1 / p) : ennreal.Lp_add_le _ _ _ hp } /-- Endowing the space `pi_Lp p hp α` with the `L^p` edistance. This definition is not satisfactory, as it does not register the fact that the topology and the uniform structure coincide with the product one. Therefore, we do not register it as an instance. Using this as a temporary emetric space instance, we will show that the uniform structure is equal (but not defeq) to the product one, and then register an instance in which we replace the uniform structure by the product one using this emetric space and `emetric_space.replace_uniformity`. -/ def emetric_aux : emetric_space (pi_Lp p hp α) := { eq_of_edist_eq_zero := λ f g hfg, begin have pos : 0 < p := lt_of_lt_of_le zero_lt_one hp, letI h := pseudo_emetric_aux p hp α, have h : edist f g = (∑ (i : ι), (edist (f i) (g i)) ^ p) ^ (1/p) := rfl, simp [h, ennreal.rpow_eq_zero_iff, pos, asymm pos, finset.sum_eq_zero_iff_of_nonneg] at hfg, exact funext hfg end, ..pseudo_emetric_aux p hp α } local attribute [instance] pi_Lp.emetric_aux pi_Lp.pseudo_emetric_aux lemma lipschitz_with_equiv : lipschitz_with 1 (pi_Lp.equiv p hp β) := begin have pos : 0 < p := lt_of_lt_of_le zero_lt_one hp, have cancel : p * (1/p) = 1 := mul_div_cancel' 1 (ne_of_gt pos), assume x y, simp only [edist, forall_prop_of_true, one_mul, finset.mem_univ, finset.sup_le_iff, ennreal.coe_one], assume i, calc edist (x i) (y i) = (edist (x i) (y i) ^ p) ^ (1/p) : by simp [← ennreal.rpow_mul, cancel, -one_div] ... ≤ (∑ (i : ι), edist (x i) (y i) ^ p) ^ (1 / p) : begin apply ennreal.rpow_le_rpow _ (one_div_nonneg.2 $ le_of_lt pos), exact finset.single_le_sum (λ i hi, (bot_le : (0 : ℝ≥0∞) ≤ _)) (finset.mem_univ i) end end lemma antilipschitz_with_equiv : antilipschitz_with ((fintype.card ι : ℝ≥0) ^ (1/p)) (pi_Lp.equiv p hp β) := begin have pos : 0 < p := lt_of_lt_of_le zero_lt_one hp, have nonneg : 0 ≤ 1 / p := one_div_nonneg.2 (le_of_lt pos), have cancel : p * (1/p) = 1 := mul_div_cancel' 1 (ne_of_gt pos), assume x y, simp [edist, -one_div], calc (∑ (i : ι), edist (x i) (y i) ^ p) ^ (1 / p) ≤ (∑ (i : ι), edist (pi_Lp.equiv p hp β x) (pi_Lp.equiv p hp β y) ^ p) ^ (1 / p) : begin apply ennreal.rpow_le_rpow _ nonneg, apply finset.sum_le_sum (λ i hi, _), apply ennreal.rpow_le_rpow _ (le_of_lt pos), exact finset.le_sup (finset.mem_univ i) end ... = (((fintype.card ι : ℝ≥0)) ^ (1/p) : ℝ≥0) * edist (pi_Lp.equiv p hp β x) (pi_Lp.equiv p hp β y) : begin simp only [nsmul_eq_mul, finset.card_univ, ennreal.rpow_one, finset.sum_const, ennreal.mul_rpow_of_nonneg _ _ nonneg, ←ennreal.rpow_mul, cancel], have : (fintype.card ι : ℝ≥0∞) = (fintype.card ι : ℝ≥0) := (ennreal.coe_nat (fintype.card ι)).symm, rw [this, ennreal.coe_rpow_of_nonneg _ nonneg] end end lemma aux_uniformity_eq : 𝓤 (pi_Lp p hp β) = @uniformity _ (Pi.uniform_space _) := begin have A : uniform_inducing (pi_Lp.equiv p hp β) := (antilipschitz_with_equiv p hp β).uniform_inducing (lipschitz_with_equiv p hp β).uniform_continuous, have : (λ (x : pi_Lp p hp β × pi_Lp p hp β), ((pi_Lp.equiv p hp β) x.fst, (pi_Lp.equiv p hp β) x.snd)) = id, by ext i; refl, rw [← A.comap_uniformity, this, comap_id] end end /-! ### Instances on finite `L^p` products -/ instance uniform_space [∀ i, uniform_space (β i)] : uniform_space (pi_Lp p hp β) := Pi.uniform_space _ variable [fintype ι] /-- pseudoemetric space instance on the product of finitely many pseudoemetric spaces, using the `L^p` pseudoedistance, and having as uniformity the product uniformity. -/ instance [∀ i, pseudo_emetric_space (β i)] : pseudo_emetric_space (pi_Lp p hp β) := (pseudo_emetric_aux p hp β).replace_uniformity (aux_uniformity_eq p hp β).symm /-- emetric space instance on the product of finitely many emetric spaces, using the `L^p` edistance, and having as uniformity the product uniformity. -/ instance [∀ i, emetric_space (α i)] : emetric_space (pi_Lp p hp α) := (emetric_aux p hp α).replace_uniformity (aux_uniformity_eq p hp α).symm protected lemma edist {p : ℝ} {hp : 1 ≤ p} {β : ι → Type*} [∀ i, pseudo_emetric_space (β i)] (x y : pi_Lp p hp β) : edist x y = (∑ (i : ι), (edist (x i) (y i)) ^ p) ^ (1/p) := rfl /-- pseudometric space instance on the product of finitely many psuedometric spaces, using the `L^p` distance, and having as uniformity the product uniformity. -/ instance [∀ i, pseudo_metric_space (β i)] : pseudo_metric_space (pi_Lp p hp β) := begin /- we construct the instance from the pseudo emetric space instance to avoid checking again that the uniformity is the same as the product uniformity, but we register nevertheless a nice formula for the distance -/ have pos : 0 < p := lt_of_lt_of_le zero_lt_one hp, refine pseudo_emetric_space.to_pseudo_metric_space_of_dist (λf g, (∑ (i : ι), (dist (f i) (g i)) ^ p) ^ (1/p)) (λ f g, _) (λ f g, _), { simp [pi_Lp.edist, ennreal.rpow_eq_top_iff, asymm pos, pos, ennreal.sum_eq_top_iff, edist_ne_top] }, { have A : ∀ (i : ι), i ∈ (finset.univ : finset ι) → edist (f i) (g i) ^ p ≠ ⊤ := λ i hi, by simp [lt_top_iff_ne_top, edist_ne_top, le_of_lt pos], simp [dist, -one_div, pi_Lp.edist, ← ennreal.to_real_rpow, ennreal.to_real_sum A, dist_edist] } end /-- metric space instance on the product of finitely many metric spaces, using the `L^p` distance, and having as uniformity the product uniformity. -/ instance [∀ i, metric_space (α i)] : metric_space (pi_Lp p hp α) := begin /- we construct the instance from the emetric space instance to avoid checking again that the uniformity is the same as the product uniformity, but we register nevertheless a nice formula for the distance -/ have pos : 0 < p := lt_of_lt_of_le zero_lt_one hp, refine emetric_space.to_metric_space_of_dist (λf g, (∑ (i : ι), (dist (f i) (g i)) ^ p) ^ (1/p)) (λ f g, _) (λ f g, _), { simp [pi_Lp.edist, ennreal.rpow_eq_top_iff, asymm pos, pos, ennreal.sum_eq_top_iff, edist_ne_top] }, { have A : ∀ (i : ι), i ∈ (finset.univ : finset ι) → edist (f i) (g i) ^ p ≠ ⊤ := λ i hi, by simp [edist_ne_top, pos.le], simp [dist, -one_div, pi_Lp.edist, ← ennreal.to_real_rpow, ennreal.to_real_sum A, dist_edist] } end protected lemma dist {p : ℝ} {hp : 1 ≤ p} {β : ι → Type*} [∀ i, pseudo_metric_space (β i)] (x y : pi_Lp p hp β) : dist x y = (∑ (i : ι), (dist (x i) (y i)) ^ p) ^ (1/p) := rfl /-- seminormed group instance on the product of finitely many normed groups, using the `L^p` norm. -/ instance semi_normed_group [∀i, semi_normed_group (β i)] : semi_normed_group (pi_Lp p hp β) := { norm := λf, (∑ (i : ι), norm (f i) ^ p) ^ (1/p), dist_eq := λ x y, by { simp [pi_Lp.dist, dist_eq_norm, sub_eq_add_neg] }, .. pi.add_comm_group } /-- normed group instance on the product of finitely many normed groups, using the `L^p` norm. -/ instance normed_group [∀i, normed_group (α i)] : normed_group (pi_Lp p hp α) := { ..pi_Lp.semi_normed_group p hp α } lemma norm_eq {p : ℝ} {hp : 1 ≤ p} {β : ι → Type*} [∀i, semi_normed_group (β i)] (f : pi_Lp p hp β) : ∥f∥ = (∑ (i : ι), ∥f i∥ ^ p) ^ (1/p) := rfl lemma norm_eq_of_nat {p : ℝ} {hp : 1 ≤ p} {β : ι → Type*} [∀i, semi_normed_group (β i)] (n : ℕ) (h : p = n) (f : pi_Lp p hp β) : ∥f∥ = (∑ (i : ι), ∥f i∥ ^ n) ^ (1/(n : ℝ)) := by simp [norm_eq, h, real.sqrt_eq_rpow, ←real.rpow_nat_cast] variables (𝕜 : Type*) [normed_field 𝕜] /-- The product of finitely many seminormed spaces is a seminormed space, with the `L^p` norm. -/ instance semi_normed_space [∀i, semi_normed_group (β i)] [∀i, semi_normed_space 𝕜 (β i)] : semi_normed_space 𝕜 (pi_Lp p hp β) := { norm_smul_le := begin assume c f, have : p * (1 / p) = 1 := mul_div_cancel' 1 (ne_of_gt (lt_of_lt_of_le zero_lt_one hp)), simp only [pi_Lp.norm_eq, norm_smul, mul_rpow, norm_nonneg, ←finset.mul_sum, pi.smul_apply], rw [mul_rpow (rpow_nonneg_of_nonneg (norm_nonneg _) _), ← rpow_mul (norm_nonneg _), this, rpow_one], exact finset.sum_nonneg (λ i hi, rpow_nonneg_of_nonneg (norm_nonneg _) _) end, .. pi.module ι β 𝕜 } /-- The product of finitely many normed spaces is a normed space, with the `L^p` norm. -/ instance normed_space [∀i, normed_group (α i)] [∀i, normed_space 𝕜 (α i)] : normed_space 𝕜 (pi_Lp p hp α) := { ..pi_Lp.semi_normed_space p hp α 𝕜 } /- Register simplification lemmas for the applications of `pi_Lp` elements, as the usual lemmas for Pi types will not trigger. -/ variables {𝕜 p hp α} [∀i, semi_normed_group (β i)] [∀i, semi_normed_space 𝕜 (β i)] (c : 𝕜) (x y : pi_Lp p hp β) (i : ι) @[simp] lemma add_apply : (x + y) i = x i + y i := rfl @[simp] lemma sub_apply : (x - y) i = x i - y i := rfl @[simp] lemma smul_apply : (c • x) i = c • x i := rfl @[simp] lemma neg_apply : (-x) i = - (x i) := rfl end pi_Lp
6473dcf95fa458b2e8510ad1d6556881434e2c19
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/category_theory/fully_faithful.lean
c0e398a7e5599bc68a64aba37dd5ce9f0802fcb2
[ "Apache-2.0" ]
permissive
JLimperg/aesop3
306cc6570c556568897ed2e508c8869667252e8a
a4a116f650cc7403428e72bd2e2c4cda300fe03f
refs/heads/master
1,682,884,916,368
1,620,320,033,000
1,620,320,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,134
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.natural_isomorphism import data.equiv.basic -- declare the `v`'s first; see `category_theory.category` for an explanation universes v₁ v₂ v₃ u₁ u₂ u₃ namespace category_theory variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] /-- A functor `F : C ⥤ D` is full if for each `X Y : C`, `F.map` is surjective. In fact, we use a constructive definition, so the `full F` typeclass contains data, specifying a particular preimage of each `f : F.obj X ⟶ F.obj Y`. See https://stacks.math.columbia.edu/tag/001C. -/ class full (F : C ⥤ D) := (preimage : ∀ {X Y : C} (f : (F.obj X) ⟶ (F.obj Y)), X ⟶ Y) (witness' : ∀ {X Y : C} (f : (F.obj X) ⟶ (F.obj Y)), F.map (preimage f) = f . obviously) restate_axiom full.witness' attribute [simp] full.witness /-- A functor `F : C ⥤ D` is faithful if for each `X Y : C`, `F.map` is injective. See https://stacks.math.columbia.edu/tag/001C. -/ class faithful (F : C ⥤ D) : Prop := (map_injective' [] : ∀ {X Y : C}, function.injective (@functor.map _ _ _ _ F X Y) . obviously) restate_axiom faithful.map_injective' namespace functor lemma map_injective (F : C ⥤ D) [faithful F] {X Y : C} : function.injective $ @functor.map _ _ _ _ F X Y := faithful.map_injective F /-- The specified preimage of a morphism under a full functor. -/ def preimage (F : C ⥤ D) [full F] {X Y : C} (f : F.obj X ⟶ F.obj Y) : X ⟶ Y := full.preimage.{v₁ v₂} f @[simp] lemma image_preimage (F : C ⥤ D) [full F] {X Y : C} (f : F.obj X ⟶ F.obj Y) : F.map (preimage F f) = f := by unfold preimage; obviously end functor variables {F : C ⥤ D} [full F] [faithful F] {X Y Z : C} @[simp] lemma preimage_id : F.preimage (𝟙 (F.obj X)) = 𝟙 X := F.map_injective (by simp) @[simp] lemma preimage_comp (f : F.obj X ⟶ F.obj Y) (g : F.obj Y ⟶ F.obj Z) : F.preimage (f ≫ g) = F.preimage f ≫ F.preimage g := F.map_injective (by simp) @[simp] lemma preimage_map (f : X ⟶ Y) : F.preimage (F.map f) = f := F.map_injective (by simp) /-- If `F : C ⥤ D` is fully faithful, every isomorphism `F.obj X ≅ F.obj Y` has a preimage. -/ def preimage_iso (f : (F.obj X) ≅ (F.obj Y)) : X ≅ Y := { hom := F.preimage f.hom, inv := F.preimage f.inv, hom_inv_id' := F.map_injective (by simp), inv_hom_id' := F.map_injective (by simp), } @[simp] lemma preimage_iso_hom (f : (F.obj X) ≅ (F.obj Y)) : (preimage_iso f).hom = F.preimage f.hom := rfl @[simp] lemma preimage_iso_inv (f : (F.obj X) ≅ (F.obj Y)) : (preimage_iso f).inv = F.preimage (f.inv) := rfl @[simp] lemma preimage_iso_map_iso (f : X ≅ Y) : preimage_iso (F.map_iso f) = f := by tidy variables (F) /-- If the image of a morphism under a fully faithful functor in an isomorphism, then the original morphisms is also an isomorphism. -/ lemma is_iso_of_fully_faithful (f : X ⟶ Y) [is_iso (F.map f)] : is_iso f := ⟨⟨F.preimage (inv (F.map f)), ⟨F.map_injective (by simp), F.map_injective (by simp)⟩⟩⟩ /-- If `F` is fully faithful, we have an equivalence of hom-sets `X ⟶ Y` and `F X ⟶ F Y`. -/ def equiv_of_fully_faithful {X Y} : (X ⟶ Y) ≃ (F.obj X ⟶ F.obj Y) := { to_fun := λ f, F.map f, inv_fun := λ f, F.preimage f, left_inv := λ f, by simp, right_inv := λ f, by simp } @[simp] lemma equiv_of_fully_faithful_apply {X Y : C} (f : X ⟶ Y) : equiv_of_fully_faithful F f = F.map f := rfl @[simp] lemma equiv_of_fully_faithful_symm_apply {X Y} (f : F.obj X ⟶ F.obj Y) : (equiv_of_fully_faithful F).symm f = F.preimage f := rfl end category_theory namespace category_theory variables {C : Type u₁} [category.{v₁} C] instance full.id : full (𝟭 C) := { preimage := λ _ _ f, f } instance faithful.id : faithful (𝟭 C) := by obviously variables {D : Type u₂} [category.{v₂} D] {E : Type u₃} [category.{v₃} E] variables (F F' : C ⥤ D) (G : D ⥤ E) instance faithful.comp [faithful F] [faithful G] : faithful (F ⋙ G) := { map_injective' := λ _ _ _ _ p, F.map_injective (G.map_injective p) } lemma faithful.of_comp [faithful $ F ⋙ G] : faithful F := { map_injective' := λ X Y, (F ⋙ G).map_injective.of_comp } section variables {F F'} lemma faithful.of_iso [faithful F] (α : F ≅ F') : faithful F' := { map_injective' := λ X Y f f' h, F.map_injective (by rw [←nat_iso.naturality_1 α.symm, h, nat_iso.naturality_1 α.symm]) } end variables {F G} lemma faithful.of_comp_iso {H : C ⥤ E} [ℋ : faithful H] (h : F ⋙ G ≅ H) : faithful F := @faithful.of_comp _ _ _ _ _ _ F G (faithful.of_iso h.symm) alias faithful.of_comp_iso ← category_theory.iso.faithful_of_comp -- We could prove this from `faithful.of_comp_iso` using `eq_to_iso`, -- but that would introduce a cyclic import. lemma faithful.of_comp_eq {H : C ⥤ E} [ℋ : faithful H] (h : F ⋙ G = H) : faithful F := @faithful.of_comp _ _ _ _ _ _ F G (h.symm ▸ ℋ) alias faithful.of_comp_eq ← eq.faithful_of_comp variables (F G) /-- “Divide” a functor by a faithful functor. -/ protected def faithful.div (F : C ⥤ E) (G : D ⥤ E) [faithful G] (obj : C → D) (h_obj : ∀ X, G.obj (obj X) = F.obj X) (map : Π {X Y}, (X ⟶ Y) → (obj X ⟶ obj Y)) (h_map : ∀ {X Y} {f : X ⟶ Y}, G.map (map f) == F.map f) : C ⥤ D := { obj := obj, map := @map, map_id' := begin assume X, apply G.map_injective, apply eq_of_heq, transitivity F.map (𝟙 X), from h_map, rw [F.map_id, G.map_id, h_obj X] end, map_comp' := begin assume X Y Z f g, apply G.map_injective, apply eq_of_heq, transitivity F.map (f ≫ g), from h_map, rw [F.map_comp, G.map_comp], congr' 1; try { exact (h_obj _).symm }; exact h_map.symm end } -- This follows immediately from `functor.hext` (`functor.hext h_obj @h_map`), -- but importing `category_theory.eq_to_hom` causes an import loop: -- category_theory.eq_to_hom → category_theory.opposites → -- category_theory.equivalence → category_theory.fully_faithful lemma faithful.div_comp (F : C ⥤ E) [faithful F] (G : D ⥤ E) [faithful G] (obj : C → D) (h_obj : ∀ X, G.obj (obj X) = F.obj X) (map : Π {X Y}, (X ⟶ Y) → (obj X ⟶ obj Y)) (h_map : ∀ {X Y} {f : X ⟶ Y}, G.map (map f) == F.map f) : (faithful.div F G obj @h_obj @map @h_map) ⋙ G = F := begin casesI F with F_obj _ _ _, casesI G with G_obj _ _ _, unfold faithful.div functor.comp, unfold_projs at h_obj, have: F_obj = G_obj ∘ obj := (funext h_obj).symm, substI this, congr, funext, exact eq_of_heq h_map end lemma faithful.div_faithful (F : C ⥤ E) [faithful F] (G : D ⥤ E) [faithful G] (obj : C → D) (h_obj : ∀ X, G.obj (obj X) = F.obj X) (map : Π {X Y}, (X ⟶ Y) → (obj X ⟶ obj Y)) (h_map : ∀ {X Y} {f : X ⟶ Y}, G.map (map f) == F.map f) : faithful (faithful.div F G obj @h_obj @map @h_map) := (faithful.div_comp F G _ h_obj _ @h_map).faithful_of_comp instance full.comp [full F] [full G] : full (F ⋙ G) := { preimage := λ _ _ f, F.preimage (G.preimage f) } /-- Given a natural isomorphism between `F ⋙ H` and `G ⋙ H` for a fully faithful functor `H`, we can 'cancel' it to give a natural iso between `F` and `G`. -/ def fully_faithful_cancel_right {F G : C ⥤ D} (H : D ⥤ E) [full H] [faithful H] (comp_iso: F ⋙ H ≅ G ⋙ H) : F ≅ G := nat_iso.of_components (λ X, preimage_iso (comp_iso.app X)) (λ X Y f, H.map_injective (by simpa using comp_iso.hom.naturality f)) @[simp] lemma fully_faithful_cancel_right_hom_app {F G : C ⥤ D} {H : D ⥤ E} [full H] [faithful H] (comp_iso: F ⋙ H ≅ G ⋙ H) (X : C) : (fully_faithful_cancel_right H comp_iso).hom.app X = H.preimage (comp_iso.hom.app X) := rfl @[simp] lemma fully_faithful_cancel_right_inv_app {F G : C ⥤ D} {H : D ⥤ E} [full H] [faithful H] (comp_iso: F ⋙ H ≅ G ⋙ H) (X : C) : (fully_faithful_cancel_right H comp_iso).inv.app X = H.preimage (comp_iso.inv.app X) := rfl end category_theory
838ec553105e574b35447527245c1a1f47810b7b
3994e03e14a3cbe3858c1098d0ab9ed1113d6666
/06-formalizacija-dokazov/dokazi.lean
dd5ecd9a8f31d94c9ffccffc8f815ee88b222dab
[]
no_license
tadejpetric/tpj-coq
15f2548ba8f012d9a5b5e0bfb78ab0860d048e96
dda9fb2e635f9a1302739e34d8692a4252066b76
refs/heads/master
1,629,182,614,649
1,600,449,570,000
1,600,449,570,000
222,798,649
1
0
null
null
null
null
UTF-8
Lean
false
false
2,342
lean
inductive naravno : Type | nic : naravno | nasl : naravno -> naravno inductive seznam_naravnih_stevil : Type | prazen : seznam_naravnih_stevil | sestavljen : naravno -> seznam_naravnih_stevil -> seznam_naravnih_stevil inductive seznam_dolzine : naravno -> Type | prazen : seznam_dolzine naravno.nic | sestavljen : ∀ n, naravno -> seznam_dolzine n -> seznam_dolzine (naravno.nasl n) inductive ali : Prop -> Prop -> Prop | inl : ∀ p q, p -> ali p q | inr : ∀ p q, q -> ali p q #check ali.rec #check or.rec #check or.inl -- P \/ Q => Q \/ P def or_comm' : ∀ p q, p ∨ q -> q ∨ p := λ p q h_p_q, or.rec or.inr or.inl h_p_q theorem or_comm'' : ∀ p q, p ∨ q -> q ∨ p := begin intro p, intro q, intro h, cases h, case or.inl { apply or.inr, exact h, }, case or.inr { left, assumption, } end #print or_comm'' theorem or_comm''' : forall p q, p ∨ q -> q ∨ p := begin intros, cases a, case or.inl { apply or.inr, exact a }, case or.inr { apply (or.inl a) } end -- (P => Q) /\ P => Q -- P /\ Q => Q /\ P theorem t2: forall p q, p ∧ q -> q ∧ p := begin intros, cases a, show q ∧ p, from and.intro a_right a_left, --and.intro (and.right a_left) (and.left a_right), end theorem orintroleft : forall p q: Prop, p -> (p ∨ q) := begin intros, show p ∨ q, from or.intro_left q a, end theorem orintroright : forall p q: Prop, p -> (q ∨ p) := begin intros, show q ∨ p, from or.intro_right q a, end -- (P \/ Q) /\ R => (P /\ R) \/ (Q /\ R) theorem t3 : forall p q r, (p ∨ q) ∧ r -> (p ∧ r) ∨ (q ∧ r) := begin intros, cases a, cases a_left, case or.inl { apply orintroleft, show p ∧ r, from and.intro a_left a_right, }, case or.inr { apply orintroright, exact and.intro a_left a_right, } end -- (P /\ Q) \/ R => (P \/ R) /\ (Q \/ R) -- (P => R) => (Q => R) <=> ((P \/ Q) => R) -- r = ⊥ p = ⊤ q = ⊤ -- a : ⊥ → (q → r), -- a_1 : p theorem t5 : forall p q r : Prop, (p -> r) -> ((q -> r) ↔ ((p ∨ q) -> r)) := begin intros, apply iff.intro, { intros, cases a_2, case or.inl { apply a, assumption, }, case or.inr { apply a_1, assumption, }, }, { intros, apply a_1, apply orintroright, assumption, } end -- P \/ Q => P /\ Q
b59d7c19b5d9987b388afbe851e84e9b40f85882
8e6cad62ec62c6c348e5faaa3c3f2079012bdd69
/src/data/polynomial/degree/trailing_degree.lean
3708c028eb98355f21465f673b05018b5b009e4b
[ "Apache-2.0" ]
permissive
benjamindavidson/mathlib
8cc81c865aa8e7cf4462245f58d35ae9a56b150d
fad44b9f670670d87c8e25ff9cdf63af87ad731e
refs/heads/master
1,679,545,578,362
1,615,343,014,000
1,615,343,014,000
312,926,983
0
0
Apache-2.0
1,615,360,301,000
1,605,399,418,000
Lean
UTF-8
Lean
false
false
13,180
lean
/- Copyright (c) 2020 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa -/ import data.polynomial.degree.definitions /-! # Trailing degree of univariate polynomials ## Main definitions * `trailing_degree p`: the multiplicity of `X` in the polynomial `p` * `nat_trailing_degree`: a variant of `trailing_degree` that takes values in the natural numbers * `trailing_coeff`: the coefficient at index `nat_trailing_degree p` Converts most results about `degree`, `nat_degree` and `leading_coeff` to results about the bottom end of a polynomial -/ noncomputable theory local attribute [instance, priority 100] classical.prop_decidable open function polynomial finsupp finset open_locale big_operators namespace polynomial universes u v variables {R : Type u} {S : Type v} {a b : R} {n m : ℕ} section semiring variables [semiring R] {p q r : polynomial R} /-- `trailing_degree p` is the multiplicity of `x` in the polynomial `p`, i.e. the smallest `X`-exponent in `p`. `trailing_degree p = some n` when `p ≠ 0` and `n` is the smallest power of `X` that appears in `p`, otherwise `trailing_degree 0 = ⊤`. -/ def trailing_degree (p : polynomial R) : with_top ℕ := p.support.inf some lemma trailing_degree_lt_wf : well_founded (λp q : polynomial R, trailing_degree p < trailing_degree q) := inv_image.wf trailing_degree (with_top.well_founded_lt nat.lt_wf) /-- `nat_trailing_degree p` forces `trailing_degree p` to `ℕ`, by defining `nat_trailing_degree ⊤ = 0`. -/ def nat_trailing_degree (p : polynomial R) : ℕ := (trailing_degree p).get_or_else 0 /-- `trailing_coeff p` gives the coefficient of the smallest power of `X` in `p`-/ def trailing_coeff (p : polynomial R) : R := coeff p (nat_trailing_degree p) /-- a polynomial is `monic_at` if its trailing coefficient is 1 -/ def trailing_monic (p : polynomial R) := trailing_coeff p = (1 : R) lemma trailing_monic.def : trailing_monic p ↔ trailing_coeff p = 1 := iff.rfl instance trailing_monic.decidable [decidable_eq R] : decidable (trailing_monic p) := by unfold trailing_monic; apply_instance @[simp] lemma trailing_monic.trailing_coeff {p : polynomial R} (hp : p.trailing_monic) : trailing_coeff p = 1 := hp @[simp] lemma trailing_degree_zero : trailing_degree (0 : polynomial R) = ⊤ := rfl @[simp] lemma nat_trailing_degree_zero : nat_trailing_degree (0 : polynomial R) = 0 := rfl lemma trailing_degree_eq_top : trailing_degree p = ⊤ ↔ p = 0 := ⟨λ h, by rw [trailing_degree, ← min_eq_inf_with_top] at h; exact support_eq_empty.1 (min_eq_none.1 h), λ h, h.symm ▸ rfl⟩ lemma trailing_degree_eq_nat_trailing_degree (hp : p ≠ 0) : trailing_degree p = (nat_trailing_degree p : with_top ℕ) := let ⟨n, hn⟩ := not_forall.1 (mt option.eq_none_iff_forall_not_mem.2 (mt trailing_degree_eq_top.1 hp)) in have hn : trailing_degree p = some n := not_not.1 hn, by rw [nat_trailing_degree, hn]; refl lemma trailing_degree_eq_iff_nat_trailing_degree_eq {p : polynomial R} {n : ℕ} (hp : p ≠ 0) : p.trailing_degree = n ↔ p.nat_trailing_degree = n := by rw [trailing_degree_eq_nat_trailing_degree hp, with_top.coe_eq_coe] lemma trailing_degree_eq_iff_nat_trailing_degree_eq_of_pos {p : polynomial R} {n : ℕ} (hn : 0 < n) : p.trailing_degree = n ↔ p.nat_trailing_degree = n := begin split, { intro H, rwa ← trailing_degree_eq_iff_nat_trailing_degree_eq, rintro rfl, rw trailing_degree_zero at H, exact option.no_confusion H }, { intro H, rwa trailing_degree_eq_iff_nat_trailing_degree_eq, rintro rfl, rw nat_trailing_degree_zero at H, rw H at hn, exact lt_irrefl _ hn } end lemma nat_trailing_degree_eq_of_trailing_degree_eq_some {p : polynomial R} {n : ℕ} (h : trailing_degree p = n) : nat_trailing_degree p = n := have hp0 : p ≠ 0, from λ hp0, by rw hp0 at h; exact option.no_confusion h, option.some_inj.1 $ show (nat_trailing_degree p : with_top ℕ) = n, by rwa [← trailing_degree_eq_nat_trailing_degree hp0] @[simp] lemma nat_trailing_degree_le_trailing_degree : ↑(nat_trailing_degree p) ≤ trailing_degree p := begin by_cases hp : p = 0, { rw hp, exact le_top }, rw [trailing_degree_eq_nat_trailing_degree hp], exact le_refl _ end lemma nat_trailing_degree_eq_of_trailing_degree_eq [semiring S] {q : polynomial S} (h : trailing_degree p = trailing_degree q) : nat_trailing_degree p = nat_trailing_degree q := by unfold nat_trailing_degree; rw h lemma le_trailing_degree_of_ne_zero (h : coeff p n ≠ 0) : trailing_degree p ≤ n := show @has_le.le (with_top ℕ) _ (p.support.inf some : with_top ℕ) (some n : with_top ℕ), from finset.inf_le (finsupp.mem_support_iff.2 h) lemma nat_trailing_degree_le_of_ne_zero (h : coeff p n ≠ 0) : nat_trailing_degree p ≤ n := begin rw [← with_top.coe_le_coe, ← trailing_degree_eq_nat_trailing_degree], { exact le_trailing_degree_of_ne_zero h, }, { assume h, subst h, exact h rfl } end lemma trailing_degree_le_trailing_degree (h : coeff q (nat_trailing_degree p) ≠ 0) : trailing_degree q ≤ trailing_degree p := begin by_cases hp : p = 0, { rw hp, exact le_top }, { rw trailing_degree_eq_nat_trailing_degree hp, exact le_trailing_degree_of_ne_zero h } end lemma trailing_degree_ne_of_nat_trailing_degree_ne {n : ℕ} : p.nat_trailing_degree ≠ n → trailing_degree p ≠ n := mt $ λ h, by rw [nat_trailing_degree, h, option.get_or_else_coe] theorem nat_trailing_degree_le_of_trailing_degree_le {n : ℕ} {hp : p ≠ 0} (H : (n : with_top ℕ) ≤ trailing_degree p) : n ≤ nat_trailing_degree p := begin rw trailing_degree_eq_nat_trailing_degree hp at H, exact with_top.coe_le_coe.mp H, end lemma nat_trailing_degree_le_nat_trailing_degree {hq : q ≠ 0} (hpq : p.trailing_degree ≤ q.trailing_degree) : p.nat_trailing_degree ≤ q.nat_trailing_degree := begin by_cases hp : p = 0, { rw [hp, nat_trailing_degree_zero], exact zero_le _ }, rwa [trailing_degree_eq_nat_trailing_degree hp, trailing_degree_eq_nat_trailing_degree hq, with_top.coe_le_coe] at hpq end @[simp] lemma trailing_degree_monomial (ha : a ≠ 0) : trailing_degree (monomial n a) = n := by rw [trailing_degree, support_monomial _ _ ha, inf_singleton, with_top.some_eq_coe] lemma nat_trailing_degree_monomial (ha : a ≠ 0) : nat_trailing_degree (monomial n a) = n := by rw [nat_trailing_degree, trailing_degree_monomial ha]; refl lemma nat_trailing_degree_monomial_le : nat_trailing_degree (monomial n a) ≤ n := if ha : a = 0 then by simp [ha] else (nat_trailing_degree_monomial ha).le lemma le_trailing_degree_monomial : ↑n ≤ trailing_degree (monomial n a) := if ha : a = 0 then by simp [ha] else (trailing_degree_monomial ha).ge @[simp] lemma trailing_degree_C (ha : a ≠ 0) : trailing_degree (C a) = (0 : with_top ℕ) := trailing_degree_monomial ha lemma le_trailing_degree_C : (0 : with_top ℕ) ≤ trailing_degree (C a) := le_trailing_degree_monomial lemma trailing_degree_one_le : (0 : with_top ℕ) ≤ trailing_degree (1 : polynomial R) := by rw [← C_1]; exact le_trailing_degree_C @[simp] lemma nat_trailing_degree_C (a : R) : nat_trailing_degree (C a) = 0 := nonpos_iff_eq_zero.1 nat_trailing_degree_monomial_le @[simp] lemma nat_trailing_degree_one : nat_trailing_degree (1 : polynomial R) = 0 := nat_trailing_degree_C 1 @[simp] lemma nat_trailing_degree_nat_cast (n : ℕ) : nat_trailing_degree (n : polynomial R) = 0 := by simp only [←C_eq_nat_cast, nat_trailing_degree_C] @[simp] lemma trailing_degree_C_mul_X_pow (n : ℕ) (ha : a ≠ 0) : trailing_degree (C a * X ^ n) = n := by rw [C_mul_X_pow_eq_monomial, trailing_degree_monomial ha] lemma le_trailing_degree_C_mul_X_pow (n : ℕ) (a : R) : (n : with_top ℕ) ≤ trailing_degree (C a * X ^ n) := by { rw C_mul_X_pow_eq_monomial, exact le_trailing_degree_monomial } lemma coeff_eq_zero_of_trailing_degree_lt (h : (n : with_top ℕ) < trailing_degree p) : coeff p n = 0 := not_not.1 (mt le_trailing_degree_of_ne_zero (not_le_of_gt h)) lemma coeff_eq_zero_of_lt_nat_trailing_degree {p : polynomial R} {n : ℕ} (h : n < p.nat_trailing_degree) : p.coeff n = 0 := begin apply coeff_eq_zero_of_trailing_degree_lt, by_cases hp : p = 0, { subst hp, exact with_top.coe_lt_top n, }, { rwa [trailing_degree_eq_nat_trailing_degree hp, with_top.coe_lt_coe] }, end @[simp] lemma coeff_nat_trailing_degree_pred_eq_zero {p : polynomial R} {hp : (0 : with_top ℕ) < nat_trailing_degree p} : p.coeff (p.nat_trailing_degree - 1) = 0 := coeff_eq_zero_of_lt_nat_trailing_degree $ nat.sub_lt ((with_top.zero_lt_coe (nat_trailing_degree p)).mp hp) nat.one_pos theorem le_trailing_degree_X_pow (n : ℕ) : (n : with_top ℕ) ≤ trailing_degree (X^n : polynomial R) := by simpa only [C_1, one_mul] using le_trailing_degree_C_mul_X_pow n (1:R) theorem le_trailing_degree_X : (1 : with_top ℕ) ≤ trailing_degree (X : polynomial R) := le_trailing_degree_monomial lemma nat_trailing_degree_X_le : (X : polynomial R).nat_trailing_degree ≤ 1 := nat_trailing_degree_monomial_le @[simp] lemma trailing_coeff_eq_zero : trailing_coeff p = 0 ↔ p = 0 := ⟨λ h, by_contradiction $ λ hp, mt mem_support_iff.1 (not_not.2 h) (mem_of_min (trailing_degree_eq_nat_trailing_degree hp)), λ h, h.symm ▸ leading_coeff_zero⟩ lemma trailing_coeff_nonzero_iff_nonzero : trailing_coeff p ≠ 0 ↔ p ≠ 0 := not_congr trailing_coeff_eq_zero lemma nat_trailing_degree_mem_support_of_nonzero : p ≠ 0 → nat_trailing_degree p ∈ p.support := (mem_support_iff_coeff_ne_zero.mpr ∘ trailing_coeff_nonzero_iff_nonzero.mpr) lemma nat_trailing_degree_le_of_mem_supp (a : ℕ) : a ∈ p.support → nat_trailing_degree p ≤ a:= nat_trailing_degree_le_of_ne_zero ∘ mem_support_iff_coeff_ne_zero.mp lemma nat_trailing_degree_eq_support_min' (h : p ≠ 0) : nat_trailing_degree p = p.support.min' (nonempty_support_iff.mpr h) := begin apply le_antisymm, { apply le_min', intros y hy, exact nat_trailing_degree_le_of_mem_supp y hy }, { apply finset.min'_le, exact mem_support_iff_coeff_ne_zero.mpr (trailing_coeff_nonzero_iff_nonzero.mpr h), }, end lemma nat_trailing_degree_le_nat_degree (p : polynomial R) : p.nat_trailing_degree ≤ p.nat_degree := begin by_cases hp : p = 0, { rw [hp, nat_degree_zero, nat_trailing_degree_zero] }, { exact le_nat_degree_of_ne_zero (mt trailing_coeff_eq_zero.mp hp) }, end lemma nat_trailing_degree_mul_X_pow {p : polynomial R} (hp : p ≠ 0) (n : ℕ) : (p * X ^ n).nat_trailing_degree = p.nat_trailing_degree + n := begin apply le_antisymm, { refine nat_trailing_degree_le_of_ne_zero (λ h, mt trailing_coeff_eq_zero.mp hp _), rwa [trailing_coeff, ←coeff_mul_X_pow] }, { rw [nat_trailing_degree_eq_support_min' (λ h, hp (mul_X_pow_eq_zero h)), finset.le_min'_iff], intros y hy, have key : n ≤ y, { rw [mem_support_iff_coeff_ne_zero, coeff_mul_X_pow'] at hy, exact by_contra (λ h, hy (if_neg h)) }, rw [mem_support_iff_coeff_ne_zero, coeff_mul_X_pow', if_pos key] at hy, exact (nat.add_le_to_le_sub _ key).mpr (nat_trailing_degree_le_of_ne_zero hy) }, end end semiring section nonzero_semiring variables [semiring R] [nontrivial R] {p q : polynomial R} @[simp] lemma trailing_degree_one : trailing_degree (1 : polynomial R) = (0 : with_top ℕ) := trailing_degree_C one_ne_zero @[simp] lemma trailing_degree_X : trailing_degree (X : polynomial R) = 1 := trailing_degree_monomial one_ne_zero @[simp] lemma nat_trailing_degree_X : (X : polynomial R).nat_trailing_degree = 1 := nat_trailing_degree_monomial one_ne_zero end nonzero_semiring section ring variables [ring R] @[simp] lemma trailing_degree_neg (p : polynomial R) : trailing_degree (-p) = trailing_degree p := by unfold trailing_degree; rw finsupp.support_neg @[simp] lemma nat_trailing_degree_neg (p : polynomial R) : nat_trailing_degree (-p) = nat_trailing_degree p := by simp [nat_trailing_degree] @[simp] lemma nat_trailing_degree_int_cast (n : ℤ) : nat_trailing_degree (n : polynomial R) = 0 := by simp only [←C_eq_int_cast, nat_trailing_degree_C] end ring section semiring variables [semiring R] /-- The second-lowest coefficient, or 0 for constants -/ def next_coeff_up (p : polynomial R) : R := if p.nat_trailing_degree = 0 then 0 else p.coeff (p.nat_trailing_degree + 1) @[simp] lemma next_coeff_up_C_eq_zero (c : R) : next_coeff_up (C c) = 0 := by { rw next_coeff_up, simp } lemma next_coeff_up_of_pos_nat_trailing_degree (p : polynomial R) (hp : 0 < p.nat_trailing_degree) : next_coeff_up p = p.coeff (p.nat_trailing_degree + 1) := by { rw [next_coeff_up, if_neg], contrapose! hp, simpa } end semiring section semiring variables [semiring R] {p q : polynomial R} {ι : Type*} lemma coeff_nat_trailing_degree_eq_zero_of_trailing_degree_lt (h : trailing_degree p < trailing_degree q) : coeff q (nat_trailing_degree p) = 0 := coeff_eq_zero_of_trailing_degree_lt $ nat_trailing_degree_le_trailing_degree.trans_lt h lemma ne_zero_of_trailing_degree_lt {n : with_top ℕ} (h : trailing_degree p < n) : p ≠ 0 := λ h₀, h.not_le (by simp [h₀]) end semiring end polynomial
bae5e1f3a8cdcc3d39e306d1e39145e980775c3f
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/data/complex/exponential.lean
b03711502d10f67f9850b79b91bd6ede1d4e86ed
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
63,332
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir -/ import algebra.geom_sum import data.complex.basic import data.nat.choose.sum /-! # Exponential, trigonometric and hyperbolic trigonometric functions This file contains the definitions of the real and complex exponential, sine, cosine, tangent, hyperbolic sine, hyperbolic cosine, and hyperbolic tangent functions. -/ local notation `abs'` := has_abs.abs open is_absolute_value open_locale classical big_operators nat complex_conjugate section open real is_absolute_value finset section variables {α : Type*} {β : Type*} [ring β] [linear_ordered_field α] [archimedean α] {abv : β → α} [is_absolute_value abv] lemma is_cau_of_decreasing_bounded (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, |f n| ≤ a) (hnm : ∀ n ≥ m, f n.succ ≤ f n) : is_cau_seq abs f := λ ε ε0, let ⟨k, hk⟩ := archimedean.arch a ε0 in have h : ∃ l, ∀ n ≥ m, a - l • ε < f n := ⟨k + k + 1, λ n hnm, lt_of_lt_of_le (show a - (k + (k + 1)) • ε < -|f n|, from lt_neg.1 $ lt_of_le_of_lt (ham n hnm) (begin rw [neg_sub, lt_sub_iff_add_lt, add_nsmul, add_nsmul, one_nsmul], exact add_lt_add_of_le_of_lt hk (lt_of_le_of_lt hk (lt_add_of_pos_right _ ε0)), end)) (neg_le.2 $ (abs_neg (f n)) ▸ le_abs_self _)⟩, let l := nat.find h in have hl : ∀ (n : ℕ), n ≥ m → f n > a - l • ε := nat.find_spec h, have hl0 : l ≠ 0 := λ hl0, not_lt_of_ge (ham m (le_refl _)) (lt_of_lt_of_le (by have := hl m (le_refl m); simpa [hl0] using this) (le_abs_self (f m))), begin cases not_forall.1 (nat.find_min h (nat.pred_lt hl0)) with i hi, rw [not_imp, not_lt] at hi, existsi i, assume j hj, have hfij : f j ≤ f i := forall_ge_le_of_forall_le_succ f hnm hi.1 hj, rw [abs_of_nonpos (sub_nonpos.2 hfij), neg_sub, sub_lt_iff_lt_add'], exact calc f i ≤ a - (nat.pred l) • ε : hi.2 ... = a - l • ε + ε : by conv {to_rhs, rw [← nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero hl0), succ_nsmul', sub_add, add_sub_cancel] } ... < f j + ε : add_lt_add_right (hl j (le_trans hi.1 hj)) _ end lemma is_cau_of_mono_bounded (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, |f n| ≤ a) (hnm : ∀ n ≥ m, f n ≤ f n.succ) : is_cau_seq abs f := begin refine @eq.rec_on (ℕ → α) _ (is_cau_seq abs) _ _ (-⟨_, @is_cau_of_decreasing_bounded _ _ _ (λ n, -f n) a m (by simpa) (by simpa)⟩ : cau_seq α abs).2, ext, exact neg_neg _ end end section no_archimedean variables {α : Type*} {β : Type*} [ring β] [linear_ordered_field α] {abv : β → α} [is_absolute_value abv] lemma is_cau_series_of_abv_le_cau {f : ℕ → β} {g : ℕ → α} (n : ℕ) : (∀ m, n ≤ m → abv (f m) ≤ g m) → is_cau_seq abs (λ n, ∑ i in range n, g i) → is_cau_seq abv (λ n, ∑ i in range n, f i) := begin assume hm hg ε ε0, cases hg (ε / 2) (div_pos ε0 (by norm_num)) with i hi, existsi max n i, assume j ji, have hi₁ := hi j (le_trans (le_max_right n i) ji), have hi₂ := hi (max n i) (le_max_right n i), have sub_le := abs_sub_le (∑ k in range j, g k) (∑ k in range i, g k) (∑ k in range (max n i), g k), have := add_lt_add hi₁ hi₂, rw [abs_sub_comm (∑ k in range (max n i), g k), add_halves ε] at this, refine lt_of_le_of_lt (le_trans (le_trans _ (le_abs_self _)) sub_le) this, generalize hk : j - max n i = k, clear this hi₂ hi₁ hi ε0 ε hg sub_le, rw tsub_eq_iff_eq_add_of_le ji at hk, rw hk, clear hk ji j, induction k with k' hi, { simp [abv_zero abv] }, { simp only [nat.succ_add, sum_range_succ_comm, sub_eq_add_neg, add_assoc], refine le_trans (abv_add _ _ _) _, simp only [sub_eq_add_neg] at hi, exact add_le_add (hm _ (le_add_of_nonneg_of_le (nat.zero_le _) (le_max_left _ _))) hi }, end lemma is_cau_series_of_abv_cau {f : ℕ → β} : is_cau_seq abs (λ m, ∑ n in range m, abv (f n)) → is_cau_seq abv (λ m, ∑ n in range m, f n) := is_cau_series_of_abv_le_cau 0 (λ n h, le_refl _) end no_archimedean section variables {α : Type*} {β : Type*} [ring β] [linear_ordered_field α] [archimedean α] {abv : β → α} [is_absolute_value abv] lemma is_cau_geo_series {β : Type*} [field β] {abv : β → α} [is_absolute_value abv] (x : β) (hx1 : abv x < 1) : is_cau_seq abv (λ n, ∑ m in range n, x ^ m) := have hx1' : abv x ≠ 1 := λ h, by simpa [h, lt_irrefl] using hx1, is_cau_series_of_abv_cau begin simp only [abv_pow abv] {eta := ff}, have : (λ (m : ℕ), ∑ n in range m, (abv x) ^ n) = λ m, geom_sum (abv x) m := rfl, simp only [this, geom_sum_eq hx1'] {eta := ff}, conv in (_ / _) { rw [← neg_div_neg_eq, neg_sub, neg_sub] }, refine @is_cau_of_mono_bounded _ _ _ _ ((1 : α) / (1 - abv x)) 0 _ _, { assume n hn, rw abs_of_nonneg, refine div_le_div_of_le (le_of_lt $ sub_pos.2 hx1) (sub_le_self _ (abv_pow abv x n ▸ abv_nonneg _ _)), refine div_nonneg (sub_nonneg.2 _) (sub_nonneg.2 $ le_of_lt hx1), clear hn, induction n with n ih, { simp }, { rw [pow_succ, ← one_mul (1 : α)], refine mul_le_mul (le_of_lt hx1) ih (abv_pow abv x n ▸ abv_nonneg _ _) (by norm_num) } }, { assume n hn, refine div_le_div_of_le (le_of_lt $ sub_pos.2 hx1) (sub_le_sub_left _ _), rw [← one_mul (_ ^ n), pow_succ], exact mul_le_mul_of_nonneg_right (le_of_lt hx1) (pow_nonneg (abv_nonneg _ _) _) } end lemma is_cau_geo_series_const (a : α) {x : α} (hx1 : |x| < 1) : is_cau_seq abs (λ m, ∑ n in range m, a * x ^ n) := have is_cau_seq abs (λ m, a * ∑ n in range m, x ^ n) := (cau_seq.const abs a * ⟨_, is_cau_geo_series x hx1⟩).2, by simpa only [mul_sum] lemma series_ratio_test {f : ℕ → β} (n : ℕ) (r : α) (hr0 : 0 ≤ r) (hr1 : r < 1) (h : ∀ m, n ≤ m → abv (f m.succ) ≤ r * abv (f m)) : is_cau_seq abv (λ m, ∑ n in range m, f n) := have har1 : |r| < 1, by rwa abs_of_nonneg hr0, begin refine is_cau_series_of_abv_le_cau n.succ _ (is_cau_geo_series_const (abv (f n.succ) * r⁻¹ ^ n.succ) har1), assume m hmn, cases classical.em (r = 0) with r_zero r_ne_zero, { have m_pos := lt_of_lt_of_le (nat.succ_pos n) hmn, have := h m.pred (nat.le_of_succ_le_succ (by rwa [nat.succ_pred_eq_of_pos m_pos])), simpa [r_zero, nat.succ_pred_eq_of_pos m_pos, pow_succ] }, generalize hk : m - n.succ = k, have r_pos : 0 < r := lt_of_le_of_ne hr0 (ne.symm r_ne_zero), replace hk : m = k + n.succ := (tsub_eq_iff_eq_add_of_le hmn).1 hk, induction k with k ih generalizing m n, { rw [hk, zero_add, mul_right_comm, inv_pow₀ _ _, ← div_eq_mul_inv, mul_div_cancel], exact (ne_of_lt (pow_pos r_pos _)).symm }, { have kn : k + n.succ ≥ n.succ, by rw ← zero_add n.succ; exact add_le_add (zero_le _) (by simp), rw [hk, nat.succ_add, pow_succ' r, ← mul_assoc], exact le_trans (by rw mul_comm; exact h _ (nat.le_of_succ_le kn)) (mul_le_mul_of_nonneg_right (ih (k + n.succ) n h kn rfl) hr0) } end lemma sum_range_diag_flip {α : Type*} [add_comm_monoid α] (n : ℕ) (f : ℕ → ℕ → α) : ∑ m in range n, ∑ k in range (m + 1), f k (m - k) = ∑ m in range n, ∑ k in range (n - m), f m k := by rw [sum_sigma', sum_sigma']; exact sum_bij (λ a _, ⟨a.2, a.1 - a.2⟩) (λ a ha, have h₁ : a.1 < n := mem_range.1 (mem_sigma.1 ha).1, have h₂ : a.2 < nat.succ a.1 := mem_range.1 (mem_sigma.1 ha).2, mem_sigma.2 ⟨mem_range.2 (lt_of_lt_of_le h₂ h₁), mem_range.2 ((tsub_lt_tsub_iff_right (nat.le_of_lt_succ h₂)).2 h₁)⟩) (λ _ _, rfl) (λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩ ha hb h, have ha : a₁ < n ∧ a₂ ≤ a₁ := ⟨mem_range.1 (mem_sigma.1 ha).1, nat.le_of_lt_succ (mem_range.1 (mem_sigma.1 ha).2)⟩, have hb : b₁ < n ∧ b₂ ≤ b₁ := ⟨mem_range.1 (mem_sigma.1 hb).1, nat.le_of_lt_succ (mem_range.1 (mem_sigma.1 hb).2)⟩, have h : a₂ = b₂ ∧ _ := sigma.mk.inj h, have h' : a₁ = b₁ - b₂ + a₂ := (tsub_eq_iff_eq_add_of_le ha.2).1 (eq_of_heq h.2), sigma.mk.inj_iff.2 ⟨tsub_add_cancel_of_le hb.2 ▸ h'.symm ▸ h.1 ▸ rfl, (heq_of_eq h.1)⟩) (λ ⟨a₁, a₂⟩ ha, have ha : a₁ < n ∧ a₂ < n - a₁ := ⟨mem_range.1 (mem_sigma.1 ha).1, (mem_range.1 (mem_sigma.1 ha).2)⟩, ⟨⟨a₂ + a₁, a₁⟩, ⟨mem_sigma.2 ⟨mem_range.2 (lt_tsub_iff_right.1 ha.2), mem_range.2 (nat.lt_succ_of_le (nat.le_add_left _ _))⟩, sigma.mk.inj_iff.2 ⟨rfl, heq_of_eq (add_tsub_cancel_right _ _).symm⟩⟩⟩) -- TODO move to src/algebra/big_operators/basic.lean, rewrite with comm_group, and make to_additive lemma sum_range_sub_sum_range {α : Type*} [add_comm_group α] {f : ℕ → α} {n m : ℕ} (hnm : n ≤ m) : ∑ k in range m, f k - ∑ k in range n, f k = ∑ k in (range m).filter (λ k, n ≤ k), f k := begin rw [← sum_sdiff (@filter_subset _ (λ k, n ≤ k) _ (range m)), sub_eq_iff_eq_add, ← eq_sub_iff_add_eq, add_sub_cancel'], refine finset.sum_congr (finset.ext $ λ a, ⟨λ h, by simp at *; finish, λ h, have ham : a < m := lt_of_lt_of_le (mem_range.1 h) hnm, by simp * at *⟩) (λ _ _, rfl), end end section no_archimedean variables {α : Type*} {β : Type*} [ring β] [linear_ordered_field α] {abv : β → α} [is_absolute_value abv] lemma abv_sum_le_sum_abv {γ : Type*} (f : γ → β) (s : finset γ) : abv (∑ k in s, f k) ≤ ∑ k in s, abv (f k) := by haveI := classical.dec_eq γ; exact finset.induction_on s (by simp [abv_zero abv]) (λ a s has ih, by rw [sum_insert has, sum_insert has]; exact le_trans (abv_add abv _ _) (add_le_add_left ih _)) lemma cauchy_product {a b : ℕ → β} (ha : is_cau_seq abs (λ m, ∑ n in range m, abv (a n))) (hb : is_cau_seq abv (λ m, ∑ n in range m, b n)) (ε : α) (ε0 : 0 < ε) : ∃ i : ℕ, ∀ j ≥ i, abv ((∑ k in range j, a k) * (∑ k in range j, b k) - ∑ n in range j, ∑ m in range (n + 1), a m * b (n - m)) < ε := let ⟨Q, hQ⟩ := cau_seq.bounded ⟨_, hb⟩ in let ⟨P, hP⟩ := cau_seq.bounded ⟨_, ha⟩ in have hP0 : 0 < P, from lt_of_le_of_lt (abs_nonneg _) (hP 0), have hPε0 : 0 < ε / (2 * P), from div_pos ε0 (mul_pos (show (2 : α) > 0, from by norm_num) hP0), let ⟨N, hN⟩ := cau_seq.cauchy₂ ⟨_, hb⟩ hPε0 in have hQε0 : 0 < ε / (4 * Q), from div_pos ε0 (mul_pos (show (0 : α) < 4, by norm_num) (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))), let ⟨M, hM⟩ := cau_seq.cauchy₂ ⟨_, ha⟩ hQε0 in ⟨2 * (max N M + 1), λ K hK, have h₁ : ∑ m in range K, ∑ k in range (m + 1), a k * b (m - k) = ∑ m in range K, ∑ n in range (K - m), a m * b n, by simpa using sum_range_diag_flip K (λ m n, a m * b n), have h₂ : (λ i, ∑ k in range (K - i), a i * b k) = (λ i, a i * ∑ k in range (K - i), b k), by simp [finset.mul_sum], have h₃ : ∑ i in range K, a i * ∑ k in range (K - i), b k = ∑ i in range K, a i * (∑ k in range (K - i), b k - ∑ k in range K, b k) + ∑ i in range K, a i * ∑ k in range K, b k, by rw ← sum_add_distrib; simp [(mul_add _ _ _).symm], have two_mul_two : (4 : α) = 2 * 2, by norm_num, have hQ0 : Q ≠ 0, from λ h, by simpa [h, lt_irrefl] using hQε0, have h2Q0 : 2 * Q ≠ 0, from mul_ne_zero two_ne_zero hQ0, have hε : ε / (2 * P) * P + ε / (4 * Q) * (2 * Q) = ε, by rw [← div_div_eq_div_mul, div_mul_cancel _ (ne.symm (ne_of_lt hP0)), two_mul_two, mul_assoc, ← div_div_eq_div_mul, div_mul_cancel _ h2Q0, add_halves], have hNMK : max N M + 1 < K, from lt_of_lt_of_le (by rw two_mul; exact lt_add_of_pos_left _ (nat.succ_pos _)) hK, have hKN : N < K, from calc N ≤ max N M : le_max_left _ _ ... < max N M + 1 : nat.lt_succ_self _ ... < K : hNMK, have hsumlesum : ∑ i in range (max N M + 1), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) ≤ ∑ i in range (max N M + 1), abv (a i) * (ε / (2 * P)), from sum_le_sum (λ m hmJ, mul_le_mul_of_nonneg_left (le_of_lt (hN (K - m) K (le_tsub_of_add_le_left (le_trans (by rw two_mul; exact add_le_add (le_of_lt (mem_range.1 hmJ)) (le_trans (le_max_left _ _) (le_of_lt (lt_add_one _)))) hK)) (le_of_lt hKN))) (abv_nonneg abv _)), have hsumltP : ∑ n in range (max N M + 1), abv (a n) < P := calc ∑ n in range (max N M + 1), abv (a n) = |∑ n in range (max N M + 1), abv (a n)| : eq.symm (abs_of_nonneg (sum_nonneg (λ x h, abv_nonneg abv (a x)))) ... < P : hP (max N M + 1), begin rw [h₁, h₂, h₃, sum_mul, ← sub_sub, sub_right_comm, sub_self, zero_sub, abv_neg abv], refine lt_of_le_of_lt (abv_sum_le_sum_abv _ _) _, suffices : ∑ i in range (max N M + 1), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) + (∑ i in range K, abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) - ∑ i in range (max N M + 1), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k)) < ε / (2 * P) * P + ε / (4 * Q) * (2 * Q), { rw hε at this, simpa [abv_mul abv] }, refine add_lt_add (lt_of_le_of_lt hsumlesum (by rw [← sum_mul, mul_comm]; exact (mul_lt_mul_left hPε0).mpr hsumltP)) _, rw sum_range_sub_sum_range (le_of_lt hNMK), exact calc ∑ i in (range K).filter (λ k, max N M + 1 ≤ k), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) ≤ ∑ i in (range K).filter (λ k, max N M + 1 ≤ k), abv (a i) * (2 * Q) : sum_le_sum (λ n hn, begin refine mul_le_mul_of_nonneg_left _ (abv_nonneg _ _), rw sub_eq_add_neg, refine le_trans (abv_add _ _ _) _, rw [two_mul, abv_neg abv], exact add_le_add (le_of_lt (hQ _)) (le_of_lt (hQ _)), end) ... < ε / (4 * Q) * (2 * Q) : by rw [← sum_mul, ← sum_range_sub_sum_range (le_of_lt hNMK)]; refine (mul_lt_mul_right $ by rw two_mul; exact add_pos (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0)) (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))).2 (lt_of_le_of_lt (le_abs_self _) (hM _ _ (le_trans (nat.le_succ_of_le (le_max_right _ _)) (le_of_lt hNMK)) (nat.le_succ_of_le (le_max_right _ _)))) end⟩ end no_archimedean end open finset open cau_seq namespace complex lemma is_cau_abs_exp (z : ℂ) : is_cau_seq has_abs.abs (λ n, ∑ m in range n, abs (z ^ m / m!)) := let ⟨n, hn⟩ := exists_nat_gt (abs z) in have hn0 : (0 : ℝ) < n, from lt_of_le_of_lt (abs_nonneg _) hn, series_ratio_test n (complex.abs z / n) (div_nonneg (complex.abs_nonneg _) (le_of_lt hn0)) (by rwa [div_lt_iff hn0, one_mul]) (λ m hm, by rw [abs_abs, abs_abs, nat.factorial_succ, pow_succ, mul_comm m.succ, nat.cast_mul, ← div_div_eq_div_mul, mul_div_assoc, mul_div_right_comm, abs_mul, abs_div, abs_cast_nat]; exact mul_le_mul_of_nonneg_right (div_le_div_of_le_left (abs_nonneg _) hn0 (nat.cast_le.2 (le_trans hm (nat.le_succ _)))) (abs_nonneg _)) noncomputable theory lemma is_cau_exp (z : ℂ) : is_cau_seq abs (λ n, ∑ m in range n, z ^ m / m!) := is_cau_series_of_abv_cau (is_cau_abs_exp z) /-- The Cauchy sequence consisting of partial sums of the Taylor series of the complex exponential function -/ @[pp_nodot] def exp' (z : ℂ) : cau_seq ℂ complex.abs := ⟨λ n, ∑ m in range n, z ^ m / m!, is_cau_exp z⟩ /-- The complex exponential function, defined via its Taylor series -/ @[pp_nodot] def exp (z : ℂ) : ℂ := lim (exp' z) /-- The complex sine function, defined via `exp` -/ @[pp_nodot] def sin (z : ℂ) : ℂ := ((exp (-z * I) - exp (z * I)) * I) / 2 /-- The complex cosine function, defined via `exp` -/ @[pp_nodot] def cos (z : ℂ) : ℂ := (exp (z * I) + exp (-z * I)) / 2 /-- The complex tangent function, defined as `sin z / cos z` -/ @[pp_nodot] def tan (z : ℂ) : ℂ := sin z / cos z /-- The complex hyperbolic sine function, defined via `exp` -/ @[pp_nodot] def sinh (z : ℂ) : ℂ := (exp z - exp (-z)) / 2 /-- The complex hyperbolic cosine function, defined via `exp` -/ @[pp_nodot] def cosh (z : ℂ) : ℂ := (exp z + exp (-z)) / 2 /-- The complex hyperbolic tangent function, defined as `sinh z / cosh z` -/ @[pp_nodot] def tanh (z : ℂ) : ℂ := sinh z / cosh z end complex namespace real open complex /-- The real exponential function, defined as the real part of the complex exponential -/ @[pp_nodot] def exp (x : ℝ) : ℝ := (exp x).re /-- The real sine function, defined as the real part of the complex sine -/ @[pp_nodot] def sin (x : ℝ) : ℝ := (sin x).re /-- The real cosine function, defined as the real part of the complex cosine -/ @[pp_nodot] def cos (x : ℝ) : ℝ := (cos x).re /-- The real tangent function, defined as the real part of the complex tangent -/ @[pp_nodot] def tan (x : ℝ) : ℝ := (tan x).re /-- The real hypebolic sine function, defined as the real part of the complex hyperbolic sine -/ @[pp_nodot] def sinh (x : ℝ) : ℝ := (sinh x).re /-- The real hypebolic cosine function, defined as the real part of the complex hyperbolic cosine -/ @[pp_nodot] def cosh (x : ℝ) : ℝ := (cosh x).re /-- The real hypebolic tangent function, defined as the real part of the complex hyperbolic tangent -/ @[pp_nodot] def tanh (x : ℝ) : ℝ := (tanh x).re end real namespace complex variables (x y : ℂ) @[simp] lemma exp_zero : exp 0 = 1 := lim_eq_of_equiv_const $ λ ε ε0, ⟨1, λ j hj, begin convert ε0, cases j, { exact absurd hj (not_le_of_gt zero_lt_one) }, { dsimp [exp'], induction j with j ih, { dsimp [exp']; simp }, { rw ← ih dec_trivial, simp only [sum_range_succ, pow_succ], simp } } end⟩ lemma exp_add : exp (x + y) = exp x * exp y := show lim (⟨_, is_cau_exp (x + y)⟩ : cau_seq ℂ abs) = lim (show cau_seq ℂ abs, from ⟨_, is_cau_exp x⟩) * lim (show cau_seq ℂ abs, from ⟨_, is_cau_exp y⟩), from have hj : ∀ j : ℕ, ∑ m in range j, (x + y) ^ m / m! = ∑ i in range j, ∑ k in range (i + 1), x ^ k / k! * (y ^ (i - k) / (i - k)!), from assume j, finset.sum_congr rfl (λ m hm, begin rw [add_pow, div_eq_mul_inv, sum_mul], refine finset.sum_congr rfl (λ i hi, _), have h₁ : (m.choose i : ℂ) ≠ 0 := nat.cast_ne_zero.2 (pos_iff_ne_zero.1 (nat.choose_pos (nat.le_of_lt_succ (mem_range.1 hi)))), have h₂ := nat.choose_mul_factorial_mul_factorial (nat.le_of_lt_succ $ finset.mem_range.1 hi), rw [← h₂, nat.cast_mul, nat.cast_mul, mul_inv₀, mul_inv₀], simp only [mul_left_comm (m.choose i : ℂ), mul_assoc, mul_left_comm (m.choose i : ℂ)⁻¹, mul_comm (m.choose i : ℂ)], rw inv_mul_cancel h₁, simp [div_eq_mul_inv, mul_comm, mul_assoc, mul_left_comm] end), by rw lim_mul_lim; exact eq.symm (lim_eq_lim_of_equiv (by dsimp; simp only [hj]; exact cauchy_product (is_cau_abs_exp x) (is_cau_exp y))) attribute [irreducible] complex.exp lemma exp_list_sum (l : list ℂ) : exp l.sum = (l.map exp).prod := @monoid_hom.map_list_prod (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ l lemma exp_multiset_sum (s : multiset ℂ) : exp s.sum = (s.map exp).prod := @monoid_hom.map_multiset_prod (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ s lemma exp_sum {α : Type*} (s : finset α) (f : α → ℂ) : exp (∑ x in s, f x) = ∏ x in s, exp (f x) := @monoid_hom.map_prod (multiplicative ℂ) α ℂ _ _ ⟨exp, exp_zero, exp_add⟩ f s lemma exp_nat_mul (x : ℂ) : ∀ n : ℕ, exp(n*x) = (exp x)^n | 0 := by rw [nat.cast_zero, zero_mul, exp_zero, pow_zero] | (nat.succ n) := by rw [pow_succ', nat.cast_add_one, add_mul, exp_add, ←exp_nat_mul, one_mul] lemma exp_ne_zero : exp x ≠ 0 := λ h, zero_ne_one $ by rw [← exp_zero, ← add_neg_self x, exp_add, h]; simp lemma exp_neg : exp (-x) = (exp x)⁻¹ := by rw [← mul_right_inj' (exp_ne_zero x), ← exp_add]; simp [mul_inv_cancel (exp_ne_zero x)] lemma exp_sub : exp (x - y) = exp x / exp y := by simp [sub_eq_add_neg, exp_add, exp_neg, div_eq_mul_inv] lemma exp_int_mul (z : ℂ) (n : ℤ) : complex.exp (n * z) = (complex.exp z) ^ n := begin cases n, { apply complex.exp_nat_mul }, { simpa [complex.exp_neg, add_comm, ← neg_mul_eq_neg_mul_symm] using complex.exp_nat_mul (-z) (1 + n) }, end @[simp] lemma exp_conj : exp (conj x) = conj (exp x) := begin dsimp [exp], rw [← lim_conj], refine congr_arg lim (cau_seq.ext (λ _, _)), dsimp [exp', function.comp, cau_seq_conj], rw star_ring_aut.map_sum, refine sum_congr rfl (λ n hn, _), rw [ring_equiv.map_div, ring_equiv.map_pow, ← of_real_nat_cast, conj_of_real] end @[simp] lemma of_real_exp_of_real_re (x : ℝ) : ((exp x).re : ℂ) = exp x := eq_conj_iff_re.1 $ by rw [← exp_conj, conj_of_real] @[simp, norm_cast] lemma of_real_exp (x : ℝ) : (real.exp x : ℂ) = exp x := of_real_exp_of_real_re _ @[simp] lemma exp_of_real_im (x : ℝ) : (exp x).im = 0 := by rw [← of_real_exp_of_real_re, of_real_im] lemma exp_of_real_re (x : ℝ) : (exp x).re = real.exp x := rfl lemma two_sinh : 2 * sinh x = exp x - exp (-x) := mul_div_cancel' _ two_ne_zero' lemma two_cosh : 2 * cosh x = exp x + exp (-x) := mul_div_cancel' _ two_ne_zero' @[simp] lemma sinh_zero : sinh 0 = 0 := by simp [sinh] @[simp] lemma sinh_neg : sinh (-x) = -sinh x := by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul] private lemma sinh_add_aux {a b c d : ℂ} : (a - b) * (c + d) + (a + b) * (c - d) = 2 * (a * c - b * d) := by ring lemma sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y := begin rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), two_sinh, exp_add, neg_add, exp_add, eq_comm, mul_add, ← mul_assoc, two_sinh, mul_left_comm, two_sinh, ← mul_right_inj' (@two_ne_zero' ℂ _ _ _), mul_add, mul_left_comm, two_cosh, ← mul_assoc, two_cosh], exact sinh_add_aux end @[simp] lemma cosh_zero : cosh 0 = 1 := by simp [cosh] @[simp] lemma cosh_neg : cosh (-x) = cosh x := by simp [add_comm, cosh, exp_neg] private lemma cosh_add_aux {a b c d : ℂ} : (a + b) * (c + d) + (a - b) * (c - d) = 2 * (a * c + b * d) := by ring lemma cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y := begin rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), two_cosh, exp_add, neg_add, exp_add, eq_comm, mul_add, ← mul_assoc, two_cosh, ← mul_assoc, two_sinh, ← mul_right_inj' (@two_ne_zero' ℂ _ _ _), mul_add, mul_left_comm, two_cosh, mul_left_comm, two_sinh], exact cosh_add_aux end lemma sinh_sub : sinh (x - y) = sinh x * cosh y - cosh x * sinh y := by simp [sub_eq_add_neg, sinh_add, sinh_neg, cosh_neg] lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y := by simp [sub_eq_add_neg, cosh_add, sinh_neg, cosh_neg] lemma sinh_conj : sinh (conj x) = conj (sinh x) := by rw [sinh, ← ring_equiv.map_neg, exp_conj, exp_conj, ← ring_equiv.map_sub, sinh, ring_equiv.map_div, conj_bit0, ring_equiv.map_one] @[simp] lemma of_real_sinh_of_real_re (x : ℝ) : ((sinh x).re : ℂ) = sinh x := eq_conj_iff_re.1 $ by rw [← sinh_conj, conj_of_real] @[simp, norm_cast] lemma of_real_sinh (x : ℝ) : (real.sinh x : ℂ) = sinh x := of_real_sinh_of_real_re _ @[simp] lemma sinh_of_real_im (x : ℝ) : (sinh x).im = 0 := by rw [← of_real_sinh_of_real_re, of_real_im] lemma sinh_of_real_re (x : ℝ) : (sinh x).re = real.sinh x := rfl lemma cosh_conj : cosh (conj x) = conj (cosh x) := begin rw [cosh, ← ring_equiv.map_neg, exp_conj, exp_conj, ← ring_equiv.map_add, cosh, ring_equiv.map_div, conj_bit0, ring_equiv.map_one] end @[simp] lemma of_real_cosh_of_real_re (x : ℝ) : ((cosh x).re : ℂ) = cosh x := eq_conj_iff_re.1 $ by rw [← cosh_conj, conj_of_real] @[simp, norm_cast] lemma of_real_cosh (x : ℝ) : (real.cosh x : ℂ) = cosh x := of_real_cosh_of_real_re _ @[simp] lemma cosh_of_real_im (x : ℝ) : (cosh x).im = 0 := by rw [← of_real_cosh_of_real_re, of_real_im] lemma cosh_of_real_re (x : ℝ) : (cosh x).re = real.cosh x := rfl lemma tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x := rfl @[simp] lemma tanh_zero : tanh 0 = 0 := by simp [tanh] @[simp] lemma tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div] lemma tanh_conj : tanh (conj x) = conj (tanh x) := by rw [tanh, sinh_conj, cosh_conj, ← ring_equiv.map_div, tanh] @[simp] lemma of_real_tanh_of_real_re (x : ℝ) : ((tanh x).re : ℂ) = tanh x := eq_conj_iff_re.1 $ by rw [← tanh_conj, conj_of_real] @[simp, norm_cast] lemma of_real_tanh (x : ℝ) : (real.tanh x : ℂ) = tanh x := of_real_tanh_of_real_re _ @[simp] lemma tanh_of_real_im (x : ℝ) : (tanh x).im = 0 := by rw [← of_real_tanh_of_real_re, of_real_im] lemma tanh_of_real_re (x : ℝ) : (tanh x).re = real.tanh x := rfl lemma cosh_add_sinh : cosh x + sinh x = exp x := by rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), mul_add, two_cosh, two_sinh, add_add_sub_cancel, two_mul] lemma sinh_add_cosh : sinh x + cosh x = exp x := by rw [add_comm, cosh_add_sinh] lemma cosh_sub_sinh : cosh x - sinh x = exp (-x) := by rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), mul_sub, two_cosh, two_sinh, add_sub_sub_cancel, two_mul] lemma cosh_sq_sub_sinh_sq : cosh x ^ 2 - sinh x ^ 2 = 1 := by rw [sq_sub_sq, cosh_add_sinh, cosh_sub_sinh, ← exp_add, add_neg_self, exp_zero] lemma cosh_sq : cosh x ^ 2 = sinh x ^ 2 + 1 := begin rw ← cosh_sq_sub_sinh_sq x, ring end lemma sinh_sq : sinh x ^ 2 = cosh x ^ 2 - 1 := begin rw ← cosh_sq_sub_sinh_sq x, ring end lemma cosh_two_mul : cosh (2 * x) = cosh x ^ 2 + sinh x ^ 2 := by rw [two_mul, cosh_add, sq, sq] lemma sinh_two_mul : sinh (2 * x) = 2 * sinh x * cosh x := begin rw [two_mul, sinh_add], ring end lemma cosh_three_mul : cosh (3 * x) = 4 * cosh x ^ 3 - 3 * cosh x := begin have h1 : x + 2 * x = 3 * x, by ring, rw [← h1, cosh_add x (2 * x)], simp only [cosh_two_mul, sinh_two_mul], have h2 : sinh x * (2 * sinh x * cosh x) = 2 * cosh x * sinh x ^ 2, by ring, rw [h2, sinh_sq], ring end lemma sinh_three_mul : sinh (3 * x) = 4 * sinh x ^ 3 + 3 * sinh x := begin have h1 : x + 2 * x = 3 * x, by ring, rw [← h1, sinh_add x (2 * x)], simp only [cosh_two_mul, sinh_two_mul], have h2 : cosh x * (2 * sinh x * cosh x) = 2 * sinh x * cosh x ^ 2, by ring, rw [h2, cosh_sq], ring, end @[simp] lemma sin_zero : sin 0 = 0 := by simp [sin] @[simp] lemma sin_neg : sin (-x) = -sin x := by simp [sin, sub_eq_add_neg, exp_neg, (neg_div _ _).symm, add_mul] lemma two_sin : 2 * sin x = (exp (-x * I) - exp (x * I)) * I := mul_div_cancel' _ two_ne_zero' lemma two_cos : 2 * cos x = exp (x * I) + exp (-x * I) := mul_div_cancel' _ two_ne_zero' lemma sinh_mul_I : sinh (x * I) = sin x * I := by rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), two_sinh, ← mul_assoc, two_sin, mul_assoc, I_mul_I, mul_neg_one, neg_sub, neg_mul_eq_neg_mul] lemma cosh_mul_I : cosh (x * I) = cos x := by rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), two_cosh, two_cos, neg_mul_eq_neg_mul] lemma tanh_mul_I : tanh (x * I) = tan x * I := by rw [tanh_eq_sinh_div_cosh, cosh_mul_I, sinh_mul_I, mul_div_right_comm, tan] lemma cos_mul_I : cos (x * I) = cosh x := by rw ← cosh_mul_I; ring_nf; simp lemma sin_mul_I : sin (x * I) = sinh x * I := have h : I * sin (x * I) = -sinh x := by { rw [mul_comm, ← sinh_mul_I], ring_nf, simp }, by simpa only [neg_mul_eq_neg_mul_symm, div_I, neg_neg] using cancel_factors.cancel_factors_eq_div h I_ne_zero lemma tan_mul_I : tan (x * I) = tanh x * I := by rw [tan, sin_mul_I, cos_mul_I, mul_div_right_comm, tanh_eq_sinh_div_cosh] lemma sin_add : sin (x + y) = sin x * cos y + cos x * sin y := by rw [← mul_left_inj' I_ne_zero, ← sinh_mul_I, add_mul, add_mul, mul_right_comm, ← sinh_mul_I, mul_assoc, ← sinh_mul_I, ← cosh_mul_I, ← cosh_mul_I, sinh_add] @[simp] lemma cos_zero : cos 0 = 1 := by simp [cos] @[simp] lemma cos_neg : cos (-x) = cos x := by simp [cos, sub_eq_add_neg, exp_neg, add_comm] private lemma cos_add_aux {a b c d : ℂ} : (a + b) * (c + d) - (b - a) * (d - c) * (-1) = 2 * (a * c + b * d) := by ring lemma cos_add : cos (x + y) = cos x * cos y - sin x * sin y := by rw [← cosh_mul_I, add_mul, cosh_add, cosh_mul_I, cosh_mul_I, sinh_mul_I, sinh_mul_I, mul_mul_mul_comm, I_mul_I, mul_neg_one, sub_eq_add_neg] lemma sin_sub : sin (x - y) = sin x * cos y - cos x * sin y := by simp [sub_eq_add_neg, sin_add, sin_neg, cos_neg] lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y := by simp [sub_eq_add_neg, cos_add, sin_neg, cos_neg] lemma sin_add_mul_I (x y : ℂ) : sin (x + y*I) = sin x * cosh y + cos x * sinh y * I := by rw [sin_add, cos_mul_I, sin_mul_I, mul_assoc] lemma sin_eq (z : ℂ) : sin z = sin z.re * cosh z.im + cos z.re * sinh z.im * I := by convert sin_add_mul_I z.re z.im; exact (re_add_im z).symm lemma cos_add_mul_I (x y : ℂ) : cos (x + y*I) = cos x * cosh y - sin x * sinh y * I := by rw [cos_add, cos_mul_I, sin_mul_I, mul_assoc] lemma cos_eq (z : ℂ) : cos z = cos z.re * cosh z.im - sin z.re * sinh z.im * I := by convert cos_add_mul_I z.re z.im; exact (re_add_im z).symm theorem sin_sub_sin : sin x - sin y = 2 * sin((x - y)/2) * cos((x + y)/2) := begin have s1 := sin_add ((x + y) / 2) ((x - y) / 2), have s2 := sin_sub ((x + y) / 2) ((x - y) / 2), rw [div_add_div_same, add_sub, add_right_comm, add_sub_cancel, half_add_self] at s1, rw [div_sub_div_same, ←sub_add, add_sub_cancel', half_add_self] at s2, rw [s1, s2], ring end theorem cos_sub_cos : cos x - cos y = -2 * sin((x + y)/2) * sin((x - y)/2) := begin have s1 := cos_add ((x + y) / 2) ((x - y) / 2), have s2 := cos_sub ((x + y) / 2) ((x - y) / 2), rw [div_add_div_same, add_sub, add_right_comm, add_sub_cancel, half_add_self] at s1, rw [div_sub_div_same, ←sub_add, add_sub_cancel', half_add_self] at s2, rw [s1, s2], ring, end lemma cos_add_cos : cos x + cos y = 2 * cos ((x + y) / 2) * cos ((x - y) / 2) := begin have h2 : (2:ℂ) ≠ 0 := by norm_num, calc cos x + cos y = cos ((x + y) / 2 + (x - y) / 2) + cos ((x + y) / 2 - (x - y) / 2) : _ ... = (cos ((x + y) / 2) * cos ((x - y) / 2) - sin ((x + y) / 2) * sin ((x - y) / 2)) + (cos ((x + y) / 2) * cos ((x - y) / 2) + sin ((x + y) / 2) * sin ((x - y) / 2)) : _ ... = 2 * cos ((x + y) / 2) * cos ((x - y) / 2) : _, { congr; field_simp [h2]; ring }, { rw [cos_add, cos_sub] }, ring, end lemma sin_conj : sin (conj x) = conj (sin x) := by rw [← mul_left_inj' I_ne_zero, ← sinh_mul_I, ← conj_neg_I, ← ring_equiv.map_mul, ← ring_equiv.map_mul, sinh_conj, mul_neg_eq_neg_mul_symm, sinh_neg, sinh_mul_I, mul_neg_eq_neg_mul_symm] @[simp] lemma of_real_sin_of_real_re (x : ℝ) : ((sin x).re : ℂ) = sin x := eq_conj_iff_re.1 $ by rw [← sin_conj, conj_of_real] @[simp, norm_cast] lemma of_real_sin (x : ℝ) : (real.sin x : ℂ) = sin x := of_real_sin_of_real_re _ @[simp] lemma sin_of_real_im (x : ℝ) : (sin x).im = 0 := by rw [← of_real_sin_of_real_re, of_real_im] lemma sin_of_real_re (x : ℝ) : (sin x).re = real.sin x := rfl lemma cos_conj : cos (conj x) = conj (cos x) := by rw [← cosh_mul_I, ← conj_neg_I, ← ring_equiv.map_mul, ← cosh_mul_I, cosh_conj, mul_neg_eq_neg_mul_symm, cosh_neg] @[simp] lemma of_real_cos_of_real_re (x : ℝ) : ((cos x).re : ℂ) = cos x := eq_conj_iff_re.1 $ by rw [← cos_conj, conj_of_real] @[simp, norm_cast] lemma of_real_cos (x : ℝ) : (real.cos x : ℂ) = cos x := of_real_cos_of_real_re _ @[simp] lemma cos_of_real_im (x : ℝ) : (cos x).im = 0 := by rw [← of_real_cos_of_real_re, of_real_im] lemma cos_of_real_re (x : ℝ) : (cos x).re = real.cos x := rfl @[simp] lemma tan_zero : tan 0 = 0 := by simp [tan] lemma tan_eq_sin_div_cos : tan x = sin x / cos x := rfl lemma tan_mul_cos {x : ℂ} (hx : cos x ≠ 0) : tan x * cos x = sin x := by rw [tan_eq_sin_div_cos, div_mul_cancel _ hx] @[simp] lemma tan_neg : tan (-x) = -tan x := by simp [tan, neg_div] lemma tan_conj : tan (conj x) = conj (tan x) := by rw [tan, sin_conj, cos_conj, ← ring_equiv.map_div, tan] @[simp] lemma of_real_tan_of_real_re (x : ℝ) : ((tan x).re : ℂ) = tan x := eq_conj_iff_re.1 $ by rw [← tan_conj, conj_of_real] @[simp, norm_cast] lemma of_real_tan (x : ℝ) : (real.tan x : ℂ) = tan x := of_real_tan_of_real_re _ @[simp] lemma tan_of_real_im (x : ℝ) : (tan x).im = 0 := by rw [← of_real_tan_of_real_re, of_real_im] lemma tan_of_real_re (x : ℝ) : (tan x).re = real.tan x := rfl lemma cos_add_sin_I : cos x + sin x * I = exp (x * I) := by rw [← cosh_add_sinh, sinh_mul_I, cosh_mul_I] lemma cos_sub_sin_I : cos x - sin x * I = exp (-x * I) := by rw [← neg_mul_eq_neg_mul, ← cosh_sub_sinh, sinh_mul_I, cosh_mul_I] @[simp] lemma sin_sq_add_cos_sq : sin x ^ 2 + cos x ^ 2 = 1 := eq.trans (by rw [cosh_mul_I, sinh_mul_I, mul_pow, I_sq, mul_neg_one, sub_neg_eq_add, add_comm]) (cosh_sq_sub_sinh_sq (x * I)) @[simp] lemma cos_sq_add_sin_sq : cos x ^ 2 + sin x ^ 2 = 1 := by rw [add_comm, sin_sq_add_cos_sq] lemma cos_two_mul' : cos (2 * x) = cos x ^ 2 - sin x ^ 2 := by rw [two_mul, cos_add, ← sq, ← sq] lemma cos_two_mul : cos (2 * x) = 2 * cos x ^ 2 - 1 := by rw [cos_two_mul', eq_sub_iff_add_eq.2 (sin_sq_add_cos_sq x), ← sub_add, sub_add_eq_add_sub, two_mul] lemma sin_two_mul : sin (2 * x) = 2 * sin x * cos x := by rw [two_mul, sin_add, two_mul, add_mul, mul_comm] lemma cos_sq : cos x ^ 2 = 1 / 2 + cos (2 * x) / 2 := by simp [cos_two_mul, div_add_div_same, mul_div_cancel_left, two_ne_zero', -one_div] lemma cos_sq' : cos x ^ 2 = 1 - sin x ^ 2 := by rw [←sin_sq_add_cos_sq x, add_sub_cancel'] lemma sin_sq : sin x ^ 2 = 1 - cos x ^ 2 := by rw [←sin_sq_add_cos_sq x, add_sub_cancel] lemma inv_one_add_tan_sq {x : ℂ} (hx : cos x ≠ 0) : (1 + tan x ^ 2)⁻¹ = cos x ^ 2 := have cos x ^ 2 ≠ 0, from pow_ne_zero 2 hx, by { rw [tan_eq_sin_div_cos, div_pow], field_simp [this] } lemma tan_sq_div_one_add_tan_sq {x : ℂ} (hx : cos x ≠ 0) : tan x ^ 2 / (1 + tan x ^ 2) = sin x ^ 2 := by simp only [← tan_mul_cos hx, mul_pow, ← inv_one_add_tan_sq hx, div_eq_mul_inv, one_mul] lemma cos_three_mul : cos (3 * x) = 4 * cos x ^ 3 - 3 * cos x := begin have h1 : x + 2 * x = 3 * x, by ring, rw [← h1, cos_add x (2 * x)], simp only [cos_two_mul, sin_two_mul, mul_add, mul_sub, mul_one, sq], have h2 : 4 * cos x ^ 3 = 2 * cos x * cos x * cos x + 2 * cos x * cos x ^ 2, by ring, rw [h2, cos_sq'], ring end lemma sin_three_mul : sin (3 * x) = 3 * sin x - 4 * sin x ^ 3 := begin have h1 : x + 2 * x = 3 * x, by ring, rw [← h1, sin_add x (2 * x)], simp only [cos_two_mul, sin_two_mul, cos_sq'], have h2 : cos x * (2 * sin x * cos x) = 2 * sin x * cos x ^ 2, by ring, rw [h2, cos_sq'], ring end lemma exp_mul_I : exp (x * I) = cos x + sin x * I := (cos_add_sin_I _).symm lemma exp_add_mul_I : exp (x + y * I) = exp x * (cos y + sin y * I) := by rw [exp_add, exp_mul_I] lemma exp_eq_exp_re_mul_sin_add_cos : exp x = exp x.re * (cos x.im + sin x.im * I) := by rw [← exp_add_mul_I, re_add_im] lemma exp_re : (exp x).re = real.exp x.re * real.cos x.im := by { rw [exp_eq_exp_re_mul_sin_add_cos], simp [exp_of_real_re, cos_of_real_re] } lemma exp_im : (exp x).im = real.exp x.re * real.sin x.im := by { rw [exp_eq_exp_re_mul_sin_add_cos], simp [exp_of_real_re, sin_of_real_re] } /-- **De Moivre's formula** -/ theorem cos_add_sin_mul_I_pow (n : ℕ) (z : ℂ) : (cos z + sin z * I) ^ n = cos (↑n * z) + sin (↑n * z) * I := begin rw [← exp_mul_I, ← exp_mul_I], induction n with n ih, { rw [pow_zero, nat.cast_zero, zero_mul, zero_mul, exp_zero] }, { rw [pow_succ', ih, nat.cast_succ, add_mul, add_mul, one_mul, exp_add] } end end complex namespace real open complex variables (x y : ℝ) @[simp] lemma exp_zero : exp 0 = 1 := by simp [real.exp] lemma exp_add : exp (x + y) = exp x * exp y := by simp [exp_add, exp] lemma exp_list_sum (l : list ℝ) : exp l.sum = (l.map exp).prod := @monoid_hom.map_list_prod (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ l lemma exp_multiset_sum (s : multiset ℝ) : exp s.sum = (s.map exp).prod := @monoid_hom.map_multiset_prod (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ s lemma exp_sum {α : Type*} (s : finset α) (f : α → ℝ) : exp (∑ x in s, f x) = ∏ x in s, exp (f x) := @monoid_hom.map_prod (multiplicative ℝ) α ℝ _ _ ⟨exp, exp_zero, exp_add⟩ f s lemma exp_nat_mul (x : ℝ) : ∀ n : ℕ, exp(n*x) = (exp x)^n | 0 := by rw [nat.cast_zero, zero_mul, exp_zero, pow_zero] | (nat.succ n) := by rw [pow_succ', nat.cast_add_one, add_mul, exp_add, ←exp_nat_mul, one_mul] lemma exp_ne_zero : exp x ≠ 0 := λ h, exp_ne_zero x $ by rw [exp, ← of_real_inj] at h; simp * at * lemma exp_neg : exp (-x) = (exp x)⁻¹ := by rw [← of_real_inj, exp, of_real_exp_of_real_re, of_real_neg, exp_neg, of_real_inv, of_real_exp] lemma exp_sub : exp (x - y) = exp x / exp y := by simp [sub_eq_add_neg, exp_add, exp_neg, div_eq_mul_inv] @[simp] lemma sin_zero : sin 0 = 0 := by simp [sin] @[simp] lemma sin_neg : sin (-x) = -sin x := by simp [sin, exp_neg, (neg_div _ _).symm, add_mul] lemma sin_add : sin (x + y) = sin x * cos y + cos x * sin y := by rw [← of_real_inj]; simp [sin, sin_add] @[simp] lemma cos_zero : cos 0 = 1 := by simp [cos] @[simp] lemma cos_neg : cos (-x) = cos x := by simp [cos, exp_neg] lemma cos_add : cos (x + y) = cos x * cos y - sin x * sin y := by rw ← of_real_inj; simp [cos, cos_add] lemma sin_sub : sin (x - y) = sin x * cos y - cos x * sin y := by simp [sub_eq_add_neg, sin_add, sin_neg, cos_neg] lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y := by simp [sub_eq_add_neg, cos_add, sin_neg, cos_neg] lemma sin_sub_sin : sin x - sin y = 2 * sin((x - y)/2) * cos((x + y)/2) := begin rw ← of_real_inj, simp only [sin, cos, of_real_sin_of_real_re, of_real_sub, of_real_add, of_real_div, of_real_mul, of_real_one, of_real_bit0], convert sin_sub_sin _ _; norm_cast end theorem cos_sub_cos : cos x - cos y = -2 * sin((x + y)/2) * sin((x - y)/2) := begin rw ← of_real_inj, simp only [cos, neg_mul_eq_neg_mul_symm, of_real_sin, of_real_sub, of_real_add, of_real_cos_of_real_re, of_real_div, of_real_mul, of_real_one, of_real_neg, of_real_bit0], convert cos_sub_cos _ _, ring, end lemma cos_add_cos : cos x + cos y = 2 * cos ((x + y) / 2) * cos ((x - y) / 2) := begin rw ← of_real_inj, simp only [cos, of_real_sub, of_real_add, of_real_cos_of_real_re, of_real_div, of_real_mul, of_real_one, of_real_bit0], convert cos_add_cos _ _; norm_cast, end lemma tan_eq_sin_div_cos : tan x = sin x / cos x := by rw [← of_real_inj, of_real_tan, tan_eq_sin_div_cos, of_real_div, of_real_sin, of_real_cos] lemma tan_mul_cos {x : ℝ} (hx : cos x ≠ 0) : tan x * cos x = sin x := by rw [tan_eq_sin_div_cos, div_mul_cancel _ hx] @[simp] lemma tan_zero : tan 0 = 0 := by simp [tan] @[simp] lemma tan_neg : tan (-x) = -tan x := by simp [tan, neg_div] @[simp] lemma sin_sq_add_cos_sq : sin x ^ 2 + cos x ^ 2 = 1 := of_real_inj.1 $ by simp @[simp] lemma cos_sq_add_sin_sq : cos x ^ 2 + sin x ^ 2 = 1 := by rw [add_comm, sin_sq_add_cos_sq] lemma sin_sq_le_one : sin x ^ 2 ≤ 1 := by rw ← sin_sq_add_cos_sq x; exact le_add_of_nonneg_right (sq_nonneg _) lemma cos_sq_le_one : cos x ^ 2 ≤ 1 := by rw ← sin_sq_add_cos_sq x; exact le_add_of_nonneg_left (sq_nonneg _) lemma abs_sin_le_one : |sin x| ≤ 1 := abs_le_one_iff_mul_self_le_one.2 $ by simp only [← sq, sin_sq_le_one] lemma abs_cos_le_one : |cos x| ≤ 1 := abs_le_one_iff_mul_self_le_one.2 $ by simp only [← sq, cos_sq_le_one] lemma sin_le_one : sin x ≤ 1 := (abs_le.1 (abs_sin_le_one _)).2 lemma cos_le_one : cos x ≤ 1 := (abs_le.1 (abs_cos_le_one _)).2 lemma neg_one_le_sin : -1 ≤ sin x := (abs_le.1 (abs_sin_le_one _)).1 lemma neg_one_le_cos : -1 ≤ cos x := (abs_le.1 (abs_cos_le_one _)).1 lemma cos_two_mul : cos (2 * x) = 2 * cos x ^ 2 - 1 := by rw ← of_real_inj; simp [cos_two_mul] lemma cos_two_mul' : cos (2 * x) = cos x ^ 2 - sin x ^ 2 := by rw ← of_real_inj; simp [cos_two_mul'] lemma sin_two_mul : sin (2 * x) = 2 * sin x * cos x := by rw ← of_real_inj; simp [sin_two_mul] lemma cos_sq : cos x ^ 2 = 1 / 2 + cos (2 * x) / 2 := of_real_inj.1 $ by simpa using cos_sq x lemma cos_sq' : cos x ^ 2 = 1 - sin x ^ 2 := by rw [←sin_sq_add_cos_sq x, add_sub_cancel'] lemma sin_sq : sin x ^ 2 = 1 - cos x ^ 2 := eq_sub_iff_add_eq.2 $ sin_sq_add_cos_sq _ lemma abs_sin_eq_sqrt_one_sub_cos_sq (x : ℝ) : |sin x| = sqrt (1 - cos x ^ 2) := by rw [← sin_sq, sqrt_sq_eq_abs] lemma abs_cos_eq_sqrt_one_sub_sin_sq (x : ℝ) : |cos x| = sqrt (1 - sin x ^ 2) := by rw [← cos_sq', sqrt_sq_eq_abs] lemma inv_one_add_tan_sq {x : ℝ} (hx : cos x ≠ 0) : (1 + tan x ^ 2)⁻¹ = cos x ^ 2 := have complex.cos x ≠ 0, from mt (congr_arg re) hx, of_real_inj.1 $ by simpa using complex.inv_one_add_tan_sq this lemma tan_sq_div_one_add_tan_sq {x : ℝ} (hx : cos x ≠ 0) : tan x ^ 2 / (1 + tan x ^ 2) = sin x ^ 2 := by simp only [← tan_mul_cos hx, mul_pow, ← inv_one_add_tan_sq hx, div_eq_mul_inv, one_mul] lemma inv_sqrt_one_add_tan_sq {x : ℝ} (hx : 0 < cos x) : (sqrt (1 + tan x ^ 2))⁻¹ = cos x := by rw [← sqrt_sq hx.le, ← sqrt_inv, inv_one_add_tan_sq hx.ne'] lemma tan_div_sqrt_one_add_tan_sq {x : ℝ} (hx : 0 < cos x) : tan x / sqrt (1 + tan x ^ 2) = sin x := by rw [← tan_mul_cos hx.ne', ← inv_sqrt_one_add_tan_sq hx, div_eq_mul_inv] lemma cos_three_mul : cos (3 * x) = 4 * cos x ^ 3 - 3 * cos x := by rw ← of_real_inj; simp [cos_three_mul] lemma sin_three_mul : sin (3 * x) = 3 * sin x - 4 * sin x ^ 3 := by rw ← of_real_inj; simp [sin_three_mul] /-- The definition of `sinh` in terms of `exp`. -/ lemma sinh_eq (x : ℝ) : sinh x = (exp x - exp (-x)) / 2 := eq_div_of_mul_eq two_ne_zero $ by rw [sinh, exp, exp, complex.of_real_neg, complex.sinh, mul_two, ← complex.add_re, ← mul_two, div_mul_cancel _ (two_ne_zero' : (2 : ℂ) ≠ 0), complex.sub_re] @[simp] lemma sinh_zero : sinh 0 = 0 := by simp [sinh] @[simp] lemma sinh_neg : sinh (-x) = -sinh x := by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul] lemma sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y := by rw ← of_real_inj; simp [sinh_add] /-- The definition of `cosh` in terms of `exp`. -/ lemma cosh_eq (x : ℝ) : cosh x = (exp x + exp (-x)) / 2 := eq_div_of_mul_eq two_ne_zero $ by rw [cosh, exp, exp, complex.of_real_neg, complex.cosh, mul_two, ← complex.add_re, ← mul_two, div_mul_cancel _ (two_ne_zero' : (2 : ℂ) ≠ 0), complex.add_re] @[simp] lemma cosh_zero : cosh 0 = 1 := by simp [cosh] @[simp] lemma cosh_neg : cosh (-x) = cosh x := by simp [cosh, exp_neg] lemma cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y := by rw ← of_real_inj; simp [cosh, cosh_add] lemma sinh_sub : sinh (x - y) = sinh x * cosh y - cosh x * sinh y := by simp [sub_eq_add_neg, sinh_add, sinh_neg, cosh_neg] lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y := by simp [sub_eq_add_neg, cosh_add, sinh_neg, cosh_neg] lemma tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x := of_real_inj.1 $ by simp [tanh_eq_sinh_div_cosh] @[simp] lemma tanh_zero : tanh 0 = 0 := by simp [tanh] @[simp] lemma tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div] lemma cosh_add_sinh : cosh x + sinh x = exp x := by rw ← of_real_inj; simp [cosh_add_sinh] lemma sinh_add_cosh : sinh x + cosh x = exp x := by rw ← of_real_inj; simp [sinh_add_cosh] lemma cosh_sq_sub_sinh_sq (x : ℝ) : cosh x ^ 2 - sinh x ^ 2 = 1 := by rw ← of_real_inj; simp [cosh_sq_sub_sinh_sq] lemma cosh_sq : cosh x ^ 2 = sinh x ^ 2 + 1 := by rw ← of_real_inj; simp [cosh_sq] lemma sinh_sq : sinh x ^ 2 = cosh x ^ 2 - 1 := by rw ← of_real_inj; simp [sinh_sq] lemma cosh_two_mul : cosh (2 * x) = cosh x ^ 2 + sinh x ^ 2 := by rw ← of_real_inj; simp [cosh_two_mul] lemma sinh_two_mul : sinh (2 * x) = 2 * sinh x * cosh x := by rw ← of_real_inj; simp [sinh_two_mul] lemma cosh_three_mul : cosh (3 * x) = 4 * cosh x ^ 3 - 3 * cosh x := by rw ← of_real_inj; simp [cosh_three_mul] lemma sinh_three_mul : sinh (3 * x) = 4 * sinh x ^ 3 + 3 * sinh x := by rw ← of_real_inj; simp [sinh_three_mul] open is_absolute_value /- TODO make this private and prove ∀ x -/ lemma add_one_le_exp_of_nonneg {x : ℝ} (hx : 0 ≤ x) : x + 1 ≤ exp x := calc x + 1 ≤ lim (⟨(λ n : ℕ, ((exp' x) n).re), is_cau_seq_re (exp' x)⟩ : cau_seq ℝ has_abs.abs) : le_lim (cau_seq.le_of_exists ⟨2, λ j hj, show x + (1 : ℝ) ≤ (∑ m in range j, (x ^ m / m! : ℂ)).re, from have h₁ : (((λ m : ℕ, (x ^ m / m! : ℂ)) ∘ nat.succ) 0).re = x, by simp, have h₂ : ((x : ℂ) ^ 0 / 0!).re = 1, by simp, begin rw [← tsub_add_cancel_of_le hj, sum_range_succ', sum_range_succ', add_re, add_re, h₁, h₂, add_assoc, ← coe_re_add_group_hom, (re_add_group_hom).map_sum, coe_re_add_group_hom ], refine le_add_of_nonneg_of_le (sum_nonneg (λ m hm, _)) (le_refl _), rw [← of_real_pow, ← of_real_nat_cast, ← of_real_div, of_real_re], exact div_nonneg (pow_nonneg hx _) (nat.cast_nonneg _), end⟩) ... = exp x : by rw [exp, complex.exp, ← cau_seq_re, lim_re] lemma one_le_exp {x : ℝ} (hx : 0 ≤ x) : 1 ≤ exp x := by linarith [add_one_le_exp_of_nonneg hx] lemma exp_pos (x : ℝ) : 0 < exp x := (le_total 0 x).elim (lt_of_lt_of_le zero_lt_one ∘ one_le_exp) (λ h, by rw [← neg_neg x, real.exp_neg]; exact inv_pos.2 (lt_of_lt_of_le zero_lt_one (one_le_exp (neg_nonneg.2 h)))) @[simp] lemma abs_exp (x : ℝ) : |exp x| = exp x := abs_of_pos (exp_pos _) lemma exp_strict_mono : strict_mono exp := λ x y h, by rw [← sub_add_cancel y x, real.exp_add]; exact (lt_mul_iff_one_lt_left (exp_pos _)).2 (lt_of_lt_of_le (by linarith) (add_one_le_exp_of_nonneg (by linarith))) @[mono] lemma exp_monotone : ∀ {x y : ℝ}, x ≤ y → exp x ≤ exp y := exp_strict_mono.monotone @[simp] lemma exp_lt_exp {x y : ℝ} : exp x < exp y ↔ x < y := exp_strict_mono.lt_iff_lt @[simp] lemma exp_le_exp {x y : ℝ} : exp x ≤ exp y ↔ x ≤ y := exp_strict_mono.le_iff_le lemma exp_injective : function.injective exp := exp_strict_mono.injective @[simp] lemma exp_eq_exp {x y : ℝ} : exp x = exp y ↔ x = y := exp_injective.eq_iff @[simp] lemma exp_eq_one_iff : exp x = 1 ↔ x = 0 := by rw [← exp_zero, exp_injective.eq_iff] @[simp] lemma one_lt_exp_iff {x : ℝ} : 1 < exp x ↔ 0 < x := by rw [← exp_zero, exp_lt_exp] @[simp] lemma exp_lt_one_iff {x : ℝ} : exp x < 1 ↔ x < 0 := by rw [← exp_zero, exp_lt_exp] @[simp] lemma exp_le_one_iff {x : ℝ} : exp x ≤ 1 ↔ x ≤ 0 := exp_zero ▸ exp_le_exp @[simp] lemma one_le_exp_iff {x : ℝ} : 1 ≤ exp x ↔ 0 ≤ x := exp_zero ▸ exp_le_exp /-- `real.cosh` is always positive -/ lemma cosh_pos (x : ℝ) : 0 < real.cosh x := (cosh_eq x).symm ▸ half_pos (add_pos (exp_pos x) (exp_pos (-x))) end real namespace complex lemma sum_div_factorial_le {α : Type*} [linear_ordered_field α] (n j : ℕ) (hn : 0 < n) : ∑ m in filter (λ k, n ≤ k) (range j), (1 / m! : α) ≤ n.succ / (n! * n) := calc ∑ m in filter (λ k, n ≤ k) (range j), (1 / m! : α) = ∑ m in range (j - n), 1 / (m + n)! : sum_bij (λ m _, m - n) (λ m hm, mem_range.2 $ (tsub_lt_tsub_iff_right (by simp at hm; tauto)).2 (by simp at hm; tauto)) (λ m hm, by rw tsub_add_cancel_of_le; simp at *; tauto) (λ a₁ a₂ ha₁ ha₂ h, by rwa [tsub_eq_iff_eq_add_of_le, tsub_add_eq_add_tsub, eq_comm, tsub_eq_iff_eq_add_of_le, add_left_inj, eq_comm] at h; simp at *; tauto) (λ b hb, ⟨b + n, mem_filter.2 ⟨mem_range.2 $ lt_tsub_iff_right.mp (mem_range.1 hb), nat.le_add_left _ _⟩, by rw add_tsub_cancel_right⟩) ... ≤ ∑ m in range (j - n), (n! * n.succ ^ m)⁻¹ : begin refine sum_le_sum (assume m n, _), rw [one_div, inv_le_inv], { rw [← nat.cast_pow, ← nat.cast_mul, nat.cast_le, add_comm], exact nat.factorial_mul_pow_le_factorial }, { exact nat.cast_pos.2 (nat.factorial_pos _) }, { exact mul_pos (nat.cast_pos.2 (nat.factorial_pos _)) (pow_pos (nat.cast_pos.2 (nat.succ_pos _)) _) }, end ... = n!⁻¹ * ∑ m in range (j - n), n.succ⁻¹ ^ m : by simp [mul_inv₀, mul_sum.symm, sum_mul.symm, -nat.factorial_succ, mul_comm, inv_pow₀] ... = (n.succ - n.succ * n.succ⁻¹ ^ (j - n)) / (n! * n) : have h₁ : (n.succ : α) ≠ 1, from @nat.cast_one α _ _ ▸ mt nat.cast_inj.1 (mt nat.succ.inj (pos_iff_ne_zero.1 hn)), have h₂ : (n.succ : α) ≠ 0, from nat.cast_ne_zero.2 (nat.succ_ne_zero _), have h₃ : (n! * n : α) ≠ 0, from mul_ne_zero (nat.cast_ne_zero.2 (pos_iff_ne_zero.1 (nat.factorial_pos _))) (nat.cast_ne_zero.2 (pos_iff_ne_zero.1 hn)), have h₄ : (n.succ - 1 : α) = n, by simp, by rw [← geom_sum_def, geom_sum_inv h₁ h₂, eq_div_iff_mul_eq h₃, mul_comm _ (n! * n : α), ← mul_assoc (n!⁻¹ : α), ← mul_inv_rev₀, h₄, ← mul_assoc (n! * n : α), mul_comm (n : α) n!, mul_inv_cancel h₃]; simp [mul_add, add_mul, mul_assoc, mul_comm] ... ≤ n.succ / (n! * n) : begin refine iff.mpr (div_le_div_right (mul_pos _ _)) _, exact nat.cast_pos.2 (nat.factorial_pos _), exact nat.cast_pos.2 hn, exact sub_le_self _ (mul_nonneg (nat.cast_nonneg _) (pow_nonneg (inv_nonneg.2 (nat.cast_nonneg _)) _)) end lemma exp_bound {x : ℂ} (hx : abs x ≤ 1) {n : ℕ} (hn : 0 < n) : abs (exp x - ∑ m in range n, x ^ m / m!) ≤ abs x ^ n * (n.succ * (n! * n)⁻¹) := begin rw [← lim_const (∑ m in range n, _), exp, sub_eq_add_neg, ← lim_neg, lim_add, ← lim_abs], refine lim_le (cau_seq.le_of_exists ⟨n, λ j hj, _⟩), simp_rw ← sub_eq_add_neg, show abs (∑ m in range j, x ^ m / m! - ∑ m in range n, x ^ m / m!) ≤ abs x ^ n * (n.succ * (n! * n)⁻¹), rw sum_range_sub_sum_range hj, exact calc abs (∑ m in (range j).filter (λ k, n ≤ k), (x ^ m / m! : ℂ)) = abs (∑ m in (range j).filter (λ k, n ≤ k), (x ^ n * (x ^ (m - n) / m!) : ℂ)) : begin refine congr_arg abs (sum_congr rfl (λ m hm, _)), rw [mem_filter, mem_range] at hm, rw [← mul_div_assoc, ← pow_add, add_tsub_cancel_of_le hm.2] end ... ≤ ∑ m in filter (λ k, n ≤ k) (range j), abs (x ^ n * (_ / m!)) : abv_sum_le_sum_abv _ _ ... ≤ ∑ m in filter (λ k, n ≤ k) (range j), abs x ^ n * (1 / m!) : begin refine sum_le_sum (λ m hm, _), rw [abs_mul, abv_pow abs, abs_div, abs_cast_nat], refine mul_le_mul_of_nonneg_left ((div_le_div_right _).2 _) _, { exact nat.cast_pos.2 (nat.factorial_pos _), }, { rw abv_pow abs, exact (pow_le_one _ (abs_nonneg _) hx), }, { exact pow_nonneg (abs_nonneg _) _ }, end ... = abs x ^ n * (∑ m in (range j).filter (λ k, n ≤ k), (1 / m! : ℝ)) : by simp [abs_mul, abv_pow abs, abs_div, mul_sum.symm] ... ≤ abs x ^ n * (n.succ * (n! * n)⁻¹) : mul_le_mul_of_nonneg_left (sum_div_factorial_le _ _ hn) (pow_nonneg (abs_nonneg _) _) end lemma exp_bound' {x : ℂ} {n : ℕ} (hx : abs x / (n.succ) ≤ 1 / 2) : abs (exp x - ∑ m in range n, x ^ m / m!) ≤ abs x ^ n / (n!) * 2 := begin rw [← lim_const (∑ m in range n, _), exp, sub_eq_add_neg, ← lim_neg, lim_add, ← lim_abs], refine lim_le (cau_seq.le_of_exists ⟨n, λ j hj, _⟩), simp_rw [←sub_eq_add_neg], show abs (∑ m in range j, x ^ m / m! - ∑ m in range n, x ^ m / m!) ≤ abs x ^ n / (n!) * 2, let k := j - n, have hj : j = n + k := (add_tsub_cancel_of_le hj).symm, rw [hj, sum_range_add_sub_sum_range], calc abs (∑ (i : ℕ) in range k, x ^ (n + i) / ((n + i)! : ℂ)) ≤ ∑ (i : ℕ) in range k, abs (x ^ (n + i) / ((n + i)! : ℂ)) : abv_sum_le_sum_abv _ _ ... ≤ ∑ (i : ℕ) in range k, (abs x) ^ (n + i) / (n + i)! : by simp only [complex.abs_cast_nat, complex.abs_div, abv_pow abs] ... ≤ ∑ (i : ℕ) in range k, (abs x) ^ (n + i) / (n! * n.succ ^ i) : _ ... = ∑ (i : ℕ) in range k, (abs x) ^ (n) / (n!) * ((abs x)^i / n.succ ^ i) : _ ... ≤ abs x ^ n / (↑n!) * 2 : _, { refine sum_le_sum (λ m hm, div_le_div (pow_nonneg (abs_nonneg x) (n + m)) (le_refl _) _ _), { exact_mod_cast mul_pos n.factorial_pos (pow_pos n.succ_pos _), }, { exact_mod_cast (nat.factorial_mul_pow_le_factorial), }, }, { refine finset.sum_congr rfl (λ _ _, _), simp only [pow_add, div_eq_inv_mul, mul_inv₀, mul_left_comm, mul_assoc], }, { rw [←mul_sum], apply mul_le_mul_of_nonneg_left, { simp_rw [←div_pow], rw [←geom_sum_def, geom_sum_eq, div_le_iff_of_neg], { transitivity (-1 : ℝ), { linarith }, { simp only [neg_le_sub_iff_le_add, div_pow, nat.cast_succ, le_add_iff_nonneg_left], exact div_nonneg (pow_nonneg (abs_nonneg x) k) (pow_nonneg (n+1).cast_nonneg k) } }, { linarith }, { linarith }, }, { exact div_nonneg (pow_nonneg (abs_nonneg x) n) (nat.cast_nonneg (n!)), }, }, end lemma abs_exp_sub_one_le {x : ℂ} (hx : abs x ≤ 1) : abs (exp x - 1) ≤ 2 * abs x := calc abs (exp x - 1) = abs (exp x - ∑ m in range 1, x ^ m / m!) : by simp [sum_range_succ] ... ≤ abs x ^ 1 * ((nat.succ 1) * (1! * (1 : ℕ))⁻¹) : exp_bound hx dec_trivial ... = 2 * abs x : by simp [two_mul, mul_two, mul_add, mul_comm] lemma abs_exp_sub_one_sub_id_le {x : ℂ} (hx : abs x ≤ 1) : abs (exp x - 1 - x) ≤ (abs x)^2 := calc abs (exp x - 1 - x) = abs (exp x - ∑ m in range 2, x ^ m / m!) : by simp [sub_eq_add_neg, sum_range_succ_comm, add_assoc] ... ≤ (abs x)^2 * (nat.succ 2 * (2! * (2 : ℕ))⁻¹) : exp_bound hx dec_trivial ... ≤ (abs x)^2 * 1 : mul_le_mul_of_nonneg_left (by norm_num) (sq_nonneg (abs x)) ... = (abs x)^2 : by rw [mul_one] end complex namespace real open complex finset lemma exp_bound {x : ℝ} (hx : |x| ≤ 1) {n : ℕ} (hn : 0 < n) : |exp x - ∑ m in range n, x ^ m / m!|≤ |x| ^ n * (n.succ / (n! * n)) := begin have hxc : complex.abs x ≤ 1, by exact_mod_cast hx, convert exp_bound hxc hn; norm_cast end /-- A finite initial segment of the exponential series, followed by an arbitrary tail. For fixed `n` this is just a linear map wrt `r`, and each map is a simple linear function of the previous (see `exp_near_succ`), with `exp_near n x r ⟶ exp x` as `n ⟶ ∞`, for any `r`. -/ def exp_near (n : ℕ) (x r : ℝ) : ℝ := ∑ m in range n, x ^ m / m! + x ^ n / n! * r @[simp] theorem exp_near_zero (x r) : exp_near 0 x r = r := by simp [exp_near] @[simp] theorem exp_near_succ (n x r) : exp_near (n + 1) x r = exp_near n x (1 + x / (n+1) * r) := by simp [exp_near, range_succ, mul_add, add_left_comm, add_assoc, pow_succ, div_eq_mul_inv, mul_inv₀]; ac_refl theorem exp_near_sub (n x r₁ r₂) : exp_near n x r₁ - exp_near n x r₂ = x ^ n / n! * (r₁ - r₂) := by simp [exp_near, mul_sub] lemma exp_approx_end (n m : ℕ) (x : ℝ) (e₁ : n + 1 = m) (h : |x| ≤ 1) : |exp x - exp_near m x 0| ≤ |x| ^ m / m! * ((m+1)/m) := by { simp [exp_near], convert exp_bound h _ using 1, field_simp [mul_comm], linarith } lemma exp_approx_succ {n} {x a₁ b₁ : ℝ} (m : ℕ) (e₁ : n + 1 = m) (a₂ b₂ : ℝ) (e : |1 + x / m * a₂ - a₁| ≤ b₁ - |x| / m * b₂) (h : |exp x - exp_near m x a₂| ≤ |x| ^ m / m! * b₂) : |exp x - exp_near n x a₁| ≤ |x| ^ n / n! * b₁ := begin refine (_root_.abs_sub_le _ _ _).trans ((add_le_add_right h _).trans _), subst e₁, rw [exp_near_succ, exp_near_sub, _root_.abs_mul], convert mul_le_mul_of_nonneg_left (le_sub_iff_add_le'.1 e) _, { simp [mul_add, pow_succ', div_eq_mul_inv, _root_.abs_mul, _root_.abs_inv, ← pow_abs, mul_inv₀], ac_refl }, { simp [_root_.div_nonneg, _root_.abs_nonneg] } end lemma exp_approx_end' {n} {x a b : ℝ} (m : ℕ) (e₁ : n + 1 = m) (rm : ℝ) (er : ↑m = rm) (h : |x| ≤ 1) (e : |1 - a| ≤ b - |x| / rm * ((rm+1)/rm)) : |exp x - exp_near n x a| ≤ |x| ^ n / n! * b := by subst er; exact exp_approx_succ _ e₁ _ _ (by simpa using e) (exp_approx_end _ _ _ e₁ h) lemma exp_1_approx_succ_eq {n} {a₁ b₁ : ℝ} {m : ℕ} (en : n + 1 = m) {rm : ℝ} (er : ↑m = rm) (h : |exp 1 - exp_near m 1 ((a₁ - 1) * rm)| ≤ |1| ^ m / m! * (b₁ * rm)) : |exp 1 - exp_near n 1 a₁| ≤ |1| ^ n / n! * b₁ := begin subst er, refine exp_approx_succ _ en _ _ _ h, field_simp [show (m : ℝ) ≠ 0, by norm_cast; linarith], end lemma exp_approx_start (x a b : ℝ) (h : |exp x - exp_near 0 x a| ≤ |x| ^ 0 / 0! * b) : |exp x - a| ≤ b := by simpa using h lemma cos_bound {x : ℝ} (hx : |x| ≤ 1) : |cos x - (1 - x ^ 2 / 2)| ≤ |x| ^ 4 * (5 / 96) := calc |cos x - (1 - x ^ 2 / 2)| = abs (complex.cos x - (1 - x ^ 2 / 2)) : by rw ← abs_of_real; simp [of_real_bit0, of_real_one, of_real_inv] ... = abs ((complex.exp (x * I) + complex.exp (-x * I) - (2 - x ^ 2)) / 2) : by simp [complex.cos, sub_div, add_div, neg_div, div_self (@two_ne_zero' ℂ _ _ _)] ... = abs (((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!) + ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!))) / 2) : congr_arg abs (congr_arg (λ x : ℂ, x / 2) begin simp only [sum_range_succ], simp [pow_succ], apply complex.ext; simp [div_eq_mul_inv, norm_sq]; ring end) ... ≤ abs ((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!) / 2) + abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!) / 2) : by rw add_div; exact abs_add _ _ ... = (abs ((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!)) / 2 + abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!)) / 2) : by simp [complex.abs_div] ... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2 + (complex.abs (-x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2) : add_le_add ((div_le_div_right (by norm_num)).2 (complex.exp_bound (by simpa) dec_trivial)) ((div_le_div_right (by norm_num)).2 (complex.exp_bound (by simpa) dec_trivial)) ... ≤ |x| ^ 4 * (5 / 96) : by norm_num; simp [mul_assoc, mul_comm, mul_left_comm, mul_div_assoc] lemma sin_bound {x : ℝ} (hx : |x| ≤ 1) : |sin x - (x - x ^ 3 / 6)| ≤ |x| ^ 4 * (5 / 96) := calc |sin x - (x - x ^ 3 / 6)| = abs (complex.sin x - (x - x ^ 3 / 6)) : by rw ← abs_of_real; simp [of_real_bit0, of_real_one, of_real_inv] ... = abs (((complex.exp (-x * I) - complex.exp (x * I)) * I - (2 * x - x ^ 3 / 3)) / 2) : by simp [complex.sin, sub_div, add_div, neg_div, mul_div_cancel_left _ (@two_ne_zero' ℂ _ _ _), div_div_eq_div_mul, show (3 : ℂ) * 2 = 6, by norm_num] ... = abs ((((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!) - (complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!)) * I) / 2) : congr_arg abs (congr_arg (λ x : ℂ, x / 2) begin simp only [sum_range_succ], simp [pow_succ], apply complex.ext; simp [div_eq_mul_inv, norm_sq]; ring end) ... ≤ abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!) * I / 2) + abs (-((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!) * I) / 2) : by rw [sub_mul, sub_eq_add_neg, add_div]; exact abs_add _ _ ... = (abs ((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!)) / 2 + abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!)) / 2) : by simp [add_comm, complex.abs_div, complex.abs_mul] ... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2 + (complex.abs (-x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2) : add_le_add ((div_le_div_right (by norm_num)).2 (complex.exp_bound (by simpa) dec_trivial)) ((div_le_div_right (by norm_num)).2 (complex.exp_bound (by simpa) dec_trivial)) ... ≤ |x| ^ 4 * (5 / 96) : by norm_num; simp [mul_assoc, mul_comm, mul_left_comm, mul_div_assoc] lemma cos_pos_of_le_one {x : ℝ} (hx : |x| ≤ 1) : 0 < cos x := calc 0 < (1 - x ^ 2 / 2) - |x| ^ 4 * (5 / 96) : sub_pos.2 $ lt_sub_iff_add_lt.2 (calc |x| ^ 4 * (5 / 96) + x ^ 2 / 2 ≤ 1 * (5 / 96) + 1 / 2 : add_le_add (mul_le_mul_of_nonneg_right (pow_le_one _ (abs_nonneg _) hx) (by norm_num)) ((div_le_div_right (by norm_num)).2 (by rw [sq, ← abs_mul_self, _root_.abs_mul]; exact mul_le_one hx (abs_nonneg _) hx)) ... < 1 : by norm_num) ... ≤ cos x : sub_le.1 (abs_sub_le_iff.1 (cos_bound hx)).2 lemma sin_pos_of_pos_of_le_one {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 1) : 0 < sin x := calc 0 < x - x ^ 3 / 6 - |x| ^ 4 * (5 / 96) : sub_pos.2 $ lt_sub_iff_add_lt.2 (calc |x| ^ 4 * (5 / 96) + x ^ 3 / 6 ≤ x * (5 / 96) + x / 6 : add_le_add (mul_le_mul_of_nonneg_right (calc |x| ^ 4 ≤ |x| ^ 1 : pow_le_pow_of_le_one (abs_nonneg _) (by rwa _root_.abs_of_nonneg (le_of_lt hx0)) dec_trivial ... = x : by simp [_root_.abs_of_nonneg (le_of_lt (hx0))]) (by norm_num)) ((div_le_div_right (by norm_num)).2 (calc x ^ 3 ≤ x ^ 1 : pow_le_pow_of_le_one (le_of_lt hx0) hx dec_trivial ... = x : pow_one _)) ... < x : by linarith) ... ≤ sin x : sub_le.1 (abs_sub_le_iff.1 (sin_bound (by rwa [_root_.abs_of_nonneg (le_of_lt hx0)]))).2 lemma sin_pos_of_pos_of_le_two {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 2) : 0 < sin x := have x / 2 ≤ 1, from (div_le_iff (by norm_num)).mpr (by simpa), calc 0 < 2 * sin (x / 2) * cos (x / 2) : mul_pos (mul_pos (by norm_num) (sin_pos_of_pos_of_le_one (half_pos hx0) this)) (cos_pos_of_le_one (by rwa [_root_.abs_of_nonneg (le_of_lt (half_pos hx0))])) ... = sin x : by rw [← sin_two_mul, two_mul, add_halves] lemma cos_one_le : cos 1 ≤ 2 / 3 := calc cos 1 ≤ |(1 : ℝ)| ^ 4 * (5 / 96) + (1 - 1 ^ 2 / 2) : sub_le_iff_le_add.1 (abs_sub_le_iff.1 (cos_bound (by simp))).1 ... ≤ 2 / 3 : by norm_num lemma cos_one_pos : 0 < cos 1 := cos_pos_of_le_one (le_of_eq abs_one) lemma cos_two_neg : cos 2 < 0 := calc cos 2 = cos (2 * 1) : congr_arg cos (mul_one _).symm ... = _ : real.cos_two_mul 1 ... ≤ 2 * (2 / 3) ^ 2 - 1 : sub_le_sub_right (mul_le_mul_of_nonneg_left (by { rw [sq, sq], exact mul_self_le_mul_self (le_of_lt cos_one_pos) cos_one_le }) zero_le_two) _ ... < 0 : by norm_num end real namespace complex lemma abs_cos_add_sin_mul_I (x : ℝ) : abs (cos x + sin x * I) = 1 := have _ := real.sin_sq_add_cos_sq x, by simp [add_comm, abs, norm_sq, sq, *, sin_of_real_re, cos_of_real_re, mul_re] at * @[simp] lemma abs_exp_of_real (x : ℝ) : abs (exp x) = real.exp x := by rw [← of_real_exp]; exact abs_of_nonneg (le_of_lt (real.exp_pos _)) lemma abs_exp (z : ℂ) : abs (exp z) = real.exp (z.re) := by rw [exp_eq_exp_re_mul_sin_add_cos, abs_mul, abs_exp_of_real, abs_cos_add_sin_mul_I, mul_one] lemma abs_exp_eq_iff_re_eq {x y : ℂ} : abs (exp x) = abs (exp y) ↔ x.re = y.re := by rw [abs_exp, abs_exp, real.exp_eq_exp] end complex
43eb1b81624a96511ae428dcabadbba258ba16f3
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/lift2.lean
508242ab3f51803c988882ab997df5cea5527c9e
[ "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
267
lean
import logic inductive lift.{l₁ l₂} (A : Type.{l₁}) : Type.{(max 1 l₁ l₂)} := inj : A → lift A set_option pp.universes true variables (A : Type.{3}) (B : Type.{1}) check A = lift B universe u variables (C : Type.{u+2}) (D : Type.{u}) check C = lift D
ace42ad1d934dee915310b7f25347c9353429231
4727251e0cd73359b15b664c3170e5d754078599
/src/data/finmap.lean
7b064236817dcafd32f9e9f1ca610e7495b08e1d
[ "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
19,047
lean
/- Copyright (c) 2018 Sean Leather. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sean Leather, Mario Carneiro -/ import data.list.alist import data.finset.basic import data.part /-! # Finite maps over `multiset` -/ universes u v w open list variables {α : Type u} {β : α → Type v} /-! ### multisets of sigma types-/ namespace multiset /-- Multiset of keys of an association multiset. -/ def keys (s : multiset (sigma β)) : multiset α := s.map sigma.fst @[simp] theorem coe_keys {l : list (sigma β)} : keys (l : multiset (sigma β)) = (l.keys : multiset α) := rfl /-- `nodupkeys s` means that `s` has no duplicate keys. -/ def nodupkeys (s : multiset (sigma β)) : Prop := quot.lift_on s list.nodupkeys (λ s t p, propext $ perm_nodupkeys p) @[simp] theorem coe_nodupkeys {l : list (sigma β)} : @nodupkeys α β l ↔ l.nodupkeys := iff.rfl end multiset /-! ### finmap -/ /-- `finmap β` is the type of finite maps over a multiset. It is effectively a quotient of `alist β` by permutation of the underlying list. -/ structure finmap (β : α → Type v) : Type (max u v) := (entries : multiset (sigma β)) (nodupkeys : entries.nodupkeys) /-- The quotient map from `alist` to `finmap`. -/ def alist.to_finmap (s : alist β) : finmap β := ⟨s.entries, s.nodupkeys⟩ local notation `⟦`:max a `⟧`:0 := alist.to_finmap a theorem alist.to_finmap_eq {s₁ s₂ : alist β} : ⟦s₁⟧ = ⟦s₂⟧ ↔ s₁.entries ~ s₂.entries := by cases s₁; cases s₂; simp [alist.to_finmap] @[simp] theorem alist.to_finmap_entries (s : alist β) : ⟦s⟧.entries = s.entries := rfl /-- Given `l : list (sigma β)`, create a term of type `finmap β` by removing entries with duplicate keys. -/ def list.to_finmap [decidable_eq α] (s : list (sigma β)) : finmap β := s.to_alist.to_finmap namespace finmap open alist /-! ### lifting from alist -/ /-- Lift a permutation-respecting function on `alist` to `finmap`. -/ @[elab_as_eliminator] def lift_on {γ} (s : finmap β) (f : alist β → γ) (H : ∀ a b : alist β, a.entries ~ b.entries → f a = f b) : γ := begin refine (quotient.lift_on s.1 (λ l, (⟨_, λ nd, f ⟨l, nd⟩⟩ : part γ)) (λ l₁ l₂ p, part.ext' (perm_nodupkeys p) _) : part γ).get _, { exact λ h₁ h₂, H _ _ (by exact p) }, { have := s.nodupkeys, rcases s.entries with ⟨l⟩, exact id } end @[simp] theorem lift_on_to_finmap {γ} (s : alist β) (f : alist β → γ) (H) : lift_on ⟦s⟧ f H = f s := by cases s; refl /-- Lift a permutation-respecting function on 2 `alist`s to 2 `finmap`s. -/ @[elab_as_eliminator] def lift_on₂ {γ} (s₁ s₂ : finmap β) (f : alist β → alist β → γ) (H : ∀ a₁ b₁ a₂ b₂ : alist β, a₁.entries ~ a₂.entries → b₁.entries ~ b₂.entries → f a₁ b₁ = f a₂ b₂) : γ := lift_on s₁ (λ l₁, lift_on s₂ (f l₁) (λ b₁ b₂ p, H _ _ _ _ (perm.refl _) p)) (λ a₁ a₂ p, have H' : f a₁ = f a₂ := funext (λ _, H _ _ _ _ p (perm.refl _)), by simp only [H']) @[simp] theorem lift_on₂_to_finmap {γ} (s₁ s₂ : alist β) (f : alist β → alist β → γ) (H) : lift_on₂ ⟦s₁⟧ ⟦s₂⟧ f H = f s₁ s₂ := by cases s₁; cases s₂; refl /-! ### induction -/ @[elab_as_eliminator] theorem induction_on {C : finmap β → Prop} (s : finmap β) (H : ∀ (a : alist β), C ⟦a⟧) : C s := by rcases s with ⟨⟨a⟩, h⟩; exact H ⟨a, h⟩ @[elab_as_eliminator] theorem induction_on₂ {C : finmap β → finmap β → Prop} (s₁ s₂ : finmap β) (H : ∀ (a₁ a₂ : alist β), C ⟦a₁⟧ ⟦a₂⟧) : C s₁ s₂ := induction_on s₁ $ λ l₁, induction_on s₂ $ λ l₂, H l₁ l₂ @[elab_as_eliminator] theorem induction_on₃ {C : finmap β → finmap β → finmap β → Prop} (s₁ s₂ s₃ : finmap β) (H : ∀ (a₁ a₂ a₃ : alist β), C ⟦a₁⟧ ⟦a₂⟧ ⟦a₃⟧) : C s₁ s₂ s₃ := induction_on₂ s₁ s₂ $ λ l₁ l₂, induction_on s₃ $ λ l₃, H l₁ l₂ l₃ /-! ### extensionality -/ @[ext] theorem ext : ∀ {s t : finmap β}, s.entries = t.entries → s = t | ⟨l₁, h₁⟩ ⟨l₂, h₂⟩ H := by congr' @[simp] theorem ext_iff {s t : finmap β} : s.entries = t.entries ↔ s = t := ⟨ext, congr_arg _⟩ /-! ### mem -/ /-- The predicate `a ∈ s` means that `s` has a value associated to the key `a`. -/ instance : has_mem α (finmap β) := ⟨λ a s, a ∈ s.entries.keys⟩ theorem mem_def {a : α} {s : finmap β} : a ∈ s ↔ a ∈ s.entries.keys := iff.rfl @[simp] theorem mem_to_finmap {a : α} {s : alist β} : a ∈ ⟦s⟧ ↔ a ∈ s := iff.rfl /-! ### keys -/ /-- The set of keys of a finite map. -/ def keys (s : finmap β) : finset α := ⟨s.entries.keys, induction_on s keys_nodup⟩ @[simp] theorem keys_val (s : alist β) : (keys ⟦s⟧).val = s.keys := rfl @[simp] theorem keys_ext {s₁ s₂ : alist β} : keys ⟦s₁⟧ = keys ⟦s₂⟧ ↔ s₁.keys ~ s₂.keys := by simp [keys, alist.keys] theorem mem_keys {a : α} {s : finmap β} : a ∈ s.keys ↔ a ∈ s := induction_on s $ λ s, alist.mem_keys /-! ### empty -/ /-- The empty map. -/ instance : has_emptyc (finmap β) := ⟨⟨0, nodupkeys_nil⟩⟩ instance : inhabited (finmap β) := ⟨∅⟩ @[simp] theorem empty_to_finmap : (⟦∅⟧ : finmap β) = ∅ := rfl @[simp] theorem to_finmap_nil [decidable_eq α] : ([].to_finmap : finmap β) = ∅ := rfl theorem not_mem_empty {a : α} : a ∉ (∅ : finmap β) := multiset.not_mem_zero a @[simp] theorem keys_empty : (∅ : finmap β).keys = ∅ := rfl /-! ### singleton -/ /-- The singleton map. -/ def singleton (a : α) (b : β a) : finmap β := ⟦alist.singleton a b⟧ @[simp] theorem keys_singleton (a : α) (b : β a) : (singleton a b).keys = {a} := rfl @[simp] lemma mem_singleton (x y : α) (b : β y) : x ∈ singleton y b ↔ x = y := by simp only [singleton]; erw [mem_cons_eq, mem_nil_iff, or_false] section variables [decidable_eq α] instance has_decidable_eq [∀ a, decidable_eq (β a)] : decidable_eq (finmap β) | s₁ s₂ := decidable_of_iff _ ext_iff /-! ### lookup -/ /-- Look up the value associated to a key in a map. -/ def lookup (a : α) (s : finmap β) : option (β a) := lift_on s (lookup a) (λ s t, perm_lookup) @[simp] theorem lookup_to_finmap (a : α) (s : alist β) : lookup a ⟦s⟧ = s.lookup a := rfl @[simp] theorem lookup_list_to_finmap (a : α) (s : list (sigma β)) : lookup a s.to_finmap = s.lookup a := by rw [list.to_finmap, lookup_to_finmap, lookup_to_alist] @[simp] theorem lookup_empty (a) : lookup a (∅ : finmap β) = none := rfl theorem lookup_is_some {a : α} {s : finmap β} : (s.lookup a).is_some ↔ a ∈ s := induction_on s $ λ s, alist.lookup_is_some theorem lookup_eq_none {a} {s : finmap β} : lookup a s = none ↔ a ∉ s := induction_on s $ λ s, alist.lookup_eq_none @[simp] lemma lookup_singleton_eq {a : α} {b : β a} : (singleton a b).lookup a = some b := by rw [singleton, lookup_to_finmap, alist.singleton, alist.lookup, lookup_cons_eq] instance (a : α) (s : finmap β) : decidable (a ∈ s) := decidable_of_iff _ lookup_is_some lemma mem_iff {a : α} {s : finmap β} : a ∈ s ↔ ∃ b, s.lookup a = some b := induction_on s $ λ s, iff.trans list.mem_keys $ exists_congr $ λ b, (mem_lookup_iff s.nodupkeys).symm lemma mem_of_lookup_eq_some {a : α} {b : β a} {s : finmap β} (h : s.lookup a = some b) : a ∈ s := mem_iff.mpr ⟨_, h⟩ theorem ext_lookup {s₁ s₂ : finmap β} : (∀ x, s₁.lookup x = s₂.lookup x) → s₁ = s₂ := induction_on₂ s₁ s₂ $ λ s₁ s₂ h, begin simp only [alist.lookup, lookup_to_finmap] at h, rw [alist.to_finmap_eq], apply lookup_ext s₁.nodupkeys s₂.nodupkeys, intros x y, rw h, end /-! ### replace -/ /-- Replace a key with a given value in a finite map. If the key is not present it does nothing. -/ def replace (a : α) (b : β a) (s : finmap β) : finmap β := lift_on s (λ t, ⟦replace a b t⟧) $ λ s₁ s₂ p, to_finmap_eq.2 $ perm_replace p @[simp] theorem replace_to_finmap (a : α) (b : β a) (s : alist β) : replace a b ⟦s⟧ = ⟦s.replace a b⟧ := by simp [replace] @[simp] theorem keys_replace (a : α) (b : β a) (s : finmap β) : (replace a b s).keys = s.keys := induction_on s $ λ s, by simp @[simp] theorem mem_replace {a a' : α} {b : β a} {s : finmap β} : a' ∈ replace a b s ↔ a' ∈ s := induction_on s $ λ s, by simp end /-! ### foldl -/ /-- Fold a commutative function over the key-value pairs in the map -/ def foldl {δ : Type w} (f : δ → Π a, β a → δ) (H : ∀ d a₁ b₁ a₂ b₂, f (f d a₁ b₁) a₂ b₂ = f (f d a₂ b₂) a₁ b₁) (d : δ) (m : finmap β) : δ := m.entries.foldl (λ d s, f d s.1 s.2) (λ d s t, H _ _ _ _ _) d /-- `any f s` returns `tt` iff there exists a value `v` in `s` such that `f v = tt`. -/ def any (f : Π x, β x → bool) (s : finmap β) : bool := s.foldl (λ x y z, x ∨ f y z) (by { intros, simp [or.right_comm] }) ff /-- `all f s` returns `tt` iff `f v = tt` for all values `v` in `s`. -/ def all (f : Π x, β x → bool) (s : finmap β) : bool := s.foldl (λ x y z, x ∧ f y z) (by { intros, simp [and.right_comm] }) ff /-! ### erase -/ section variables [decidable_eq α] /-- Erase a key from the map. If the key is not present it does nothing. -/ def erase (a : α) (s : finmap β) : finmap β := lift_on s (λ t, ⟦erase a t⟧) $ λ s₁ s₂ p, to_finmap_eq.2 $ perm_erase p @[simp] theorem erase_to_finmap (a : α) (s : alist β) : erase a ⟦s⟧ = ⟦s.erase a⟧ := by simp [erase] @[simp] theorem keys_erase_to_finset (a : α) (s : alist β) : keys ⟦s.erase a⟧ = (keys ⟦s⟧).erase a := by simp [finset.erase, keys, alist.erase, keys_kerase] @[simp] theorem keys_erase (a : α) (s : finmap β) : (erase a s).keys = s.keys.erase a := induction_on s $ λ s, by simp @[simp] theorem mem_erase {a a' : α} {s : finmap β} : a' ∈ erase a s ↔ a' ≠ a ∧ a' ∈ s := induction_on s $ λ s, by simp theorem not_mem_erase_self {a : α} {s : finmap β} : ¬ a ∈ erase a s := by rw [mem_erase, not_and_distrib, not_not]; left; refl @[simp] theorem lookup_erase (a) (s : finmap β) : lookup a (erase a s) = none := induction_on s $ lookup_erase a @[simp] theorem lookup_erase_ne {a a'} {s : finmap β} (h : a ≠ a') : lookup a (erase a' s) = lookup a s := induction_on s $ λ s, lookup_erase_ne h theorem erase_erase {a a' : α} {s : finmap β} : erase a (erase a' s) = erase a' (erase a s) := induction_on s $ λ s, ext (by simp only [erase_erase, erase_to_finmap]) /-! ### sdiff -/ /-- `sdiff s s'` consists of all key-value pairs from `s` and `s'` where the keys are in `s` or `s'` but not both. -/ def sdiff (s s' : finmap β) : finmap β := s'.foldl (λ s x _, s.erase x) (λ a₀ a₁ _ a₂ _, erase_erase) s instance : has_sdiff (finmap β) := ⟨sdiff⟩ /-! ### insert -/ /-- Insert a key-value pair into a finite map, replacing any existing pair with the same key. -/ def insert (a : α) (b : β a) (s : finmap β) : finmap β := lift_on s (λ t, ⟦insert a b t⟧) $ λ s₁ s₂ p, to_finmap_eq.2 $ perm_insert p @[simp] theorem insert_to_finmap (a : α) (b : β a) (s : alist β) : insert a b ⟦s⟧ = ⟦s.insert a b⟧ := by simp [insert] theorem insert_entries_of_neg {a : α} {b : β a} {s : finmap β} : a ∉ s → (insert a b s).entries = ⟨a, b⟩ ::ₘ s.entries := induction_on s $ λ s h, by simp [insert_entries_of_neg (mt mem_to_finmap.1 h)] @[simp] theorem mem_insert {a a' : α} {b' : β a'} {s : finmap β} : a ∈ insert a' b' s ↔ a = a' ∨ a ∈ s := induction_on s mem_insert @[simp] theorem lookup_insert {a} {b : β a} (s : finmap β) : lookup a (insert a b s) = some b := induction_on s $ λ s, by simp only [insert_to_finmap, lookup_to_finmap, lookup_insert] @[simp] theorem lookup_insert_of_ne {a a'} {b : β a} (s : finmap β) (h : a' ≠ a) : lookup a' (insert a b s) = lookup a' s := induction_on s $ λ s, by simp only [insert_to_finmap, lookup_to_finmap, lookup_insert_ne h] @[simp] theorem insert_insert {a} {b b' : β a} (s : finmap β) : (s.insert a b).insert a b' = s.insert a b' := induction_on s $ λ s, by simp only [insert_to_finmap, insert_insert] theorem insert_insert_of_ne {a a'} {b : β a} {b' : β a'} (s : finmap β) (h : a ≠ a') : (s.insert a b).insert a' b' = (s.insert a' b').insert a b := induction_on s $ λ s, by simp only [insert_to_finmap, alist.to_finmap_eq, insert_insert_of_ne _ h] theorem to_finmap_cons (a : α) (b : β a) (xs : list (sigma β)) : list.to_finmap (⟨a,b⟩ :: xs) = insert a b xs.to_finmap := rfl theorem mem_list_to_finmap (a : α) (xs : list (sigma β)) : a ∈ xs.to_finmap ↔ (∃ b : β a, sigma.mk a b ∈ xs) := by { induction xs with x xs; [skip, cases x]; simp only [to_finmap_cons, *, not_mem_empty, exists_or_distrib, not_mem_nil, to_finmap_nil, exists_false, mem_cons_iff, mem_insert, exists_and_distrib_left]; apply or_congr _ iff.rfl, conv { to_lhs, rw ← and_true (a = x_fst) }, apply and_congr_right, rintro ⟨⟩, simp only [exists_eq, iff_self, heq_iff_eq] } @[simp] theorem insert_singleton_eq {a : α} {b b' : β a} : insert a b (singleton a b') = singleton a b := by simp only [singleton, finmap.insert_to_finmap, alist.insert_singleton_eq] /-! ### extract -/ /-- Erase a key from the map, and return the corresponding value, if found. -/ def extract (a : α) (s : finmap β) : option (β a) × finmap β := lift_on s (λ t, prod.map id to_finmap (extract a t)) $ λ s₁ s₂ p, by simp [perm_lookup p, to_finmap_eq, perm_erase p] @[simp] theorem extract_eq_lookup_erase (a : α) (s : finmap β) : extract a s = (lookup a s, erase a s) := induction_on s $ λ s, by simp [extract] /-! ### union -/ /-- `s₁ ∪ s₂` is the key-based union of two finite maps. It is left-biased: if there exists an `a ∈ s₁`, `lookup a (s₁ ∪ s₂) = lookup a s₁`. -/ def union (s₁ s₂ : finmap β) : finmap β := lift_on₂ s₁ s₂ (λ s₁ s₂, ⟦s₁ ∪ s₂⟧) $ λ s₁ s₂ s₃ s₄ p₁₃ p₂₄, to_finmap_eq.mpr $ perm_union p₁₃ p₂₄ instance : has_union (finmap β) := ⟨union⟩ @[simp] theorem mem_union {a} {s₁ s₂ : finmap β} : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ := induction_on₂ s₁ s₂ $ λ _ _, mem_union @[simp] theorem union_to_finmap (s₁ s₂ : alist β) : ⟦s₁⟧ ∪ ⟦s₂⟧ = ⟦s₁ ∪ s₂⟧ := by simp [(∪), union] theorem keys_union {s₁ s₂ : finmap β} : (s₁ ∪ s₂).keys = s₁.keys ∪ s₂.keys := induction_on₂ s₁ s₂ $ λ s₁ s₂, finset.ext $ by simp [keys] @[simp] theorem lookup_union_left {a} {s₁ s₂ : finmap β} : a ∈ s₁ → lookup a (s₁ ∪ s₂) = lookup a s₁ := induction_on₂ s₁ s₂ $ λ s₁ s₂, lookup_union_left @[simp] theorem lookup_union_right {a} {s₁ s₂ : finmap β} : a ∉ s₁ → lookup a (s₁ ∪ s₂) = lookup a s₂ := induction_on₂ s₁ s₂ $ λ s₁ s₂, lookup_union_right theorem lookup_union_left_of_not_in {a} {s₁ s₂ : finmap β} (h : a ∉ s₂) : lookup a (s₁ ∪ s₂) = lookup a s₁ := begin by_cases h' : a ∈ s₁, { rw lookup_union_left h' }, { rw [lookup_union_right h', lookup_eq_none.mpr h, lookup_eq_none.mpr h'] } end @[simp] theorem mem_lookup_union {a} {b : β a} {s₁ s₂ : finmap β} : b ∈ lookup a (s₁ ∪ s₂) ↔ b ∈ lookup a s₁ ∨ a ∉ s₁ ∧ b ∈ lookup a s₂ := induction_on₂ s₁ s₂ $ λ s₁ s₂, mem_lookup_union theorem mem_lookup_union_middle {a} {b : β a} {s₁ s₂ s₃ : finmap β} : b ∈ lookup a (s₁ ∪ s₃) → a ∉ s₂ → b ∈ lookup a (s₁ ∪ s₂ ∪ s₃) := induction_on₃ s₁ s₂ s₃ $ λ s₁ s₂ s₃, mem_lookup_union_middle theorem insert_union {a} {b : β a} {s₁ s₂ : finmap β} : insert a b (s₁ ∪ s₂) = insert a b s₁ ∪ s₂ := induction_on₂ s₁ s₂ $ λ a₁ a₂, by simp [insert_union] theorem union_assoc {s₁ s₂ s₃ : finmap β} : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) := induction_on₃ s₁ s₂ s₃ $ λ s₁ s₂ s₃, by simp only [alist.to_finmap_eq, union_to_finmap, alist.union_assoc] @[simp] theorem empty_union {s₁ : finmap β} : ∅ ∪ s₁ = s₁ := induction_on s₁ $ λ s₁, by rw ← empty_to_finmap; simp [- empty_to_finmap, alist.to_finmap_eq, union_to_finmap, alist.union_assoc] @[simp] theorem union_empty {s₁ : finmap β} : s₁ ∪ ∅ = s₁ := induction_on s₁ $ λ s₁, by rw ← empty_to_finmap; simp [- empty_to_finmap, alist.to_finmap_eq, union_to_finmap, alist.union_assoc] theorem erase_union_singleton (a : α) (b : β a) (s : finmap β) (h : s.lookup a = some b) : s.erase a ∪ singleton a b = s := ext_lookup (λ x, by { by_cases h' : x = a, { subst a, rw [lookup_union_right not_mem_erase_self, lookup_singleton_eq, h], }, { have : x ∉ singleton a b, { rwa mem_singleton }, rw [lookup_union_left_of_not_in this, lookup_erase_ne h'] } } ) end /-! ### disjoint -/ /-- `disjoint s₁ s₂` holds if `s₁` and `s₂` have no keys in common. -/ def disjoint (s₁ s₂ : finmap β) : Prop := ∀ x ∈ s₁, ¬ x ∈ s₂ lemma disjoint_empty (x : finmap β) : disjoint ∅ x . @[symm] lemma disjoint.symm (x y : finmap β) (h : disjoint x y) : disjoint y x := λ p hy hx, h p hx hy lemma disjoint.symm_iff (x y : finmap β) : disjoint x y ↔ disjoint y x := ⟨disjoint.symm x y, disjoint.symm y x⟩ section variables [decidable_eq α] instance : decidable_rel (@disjoint α β) := λ x y, by dsimp only [disjoint]; apply_instance lemma disjoint_union_left (x y z : finmap β) : disjoint (x ∪ y) z ↔ disjoint x z ∧ disjoint y z := by simp [disjoint, finmap.mem_union, or_imp_distrib, forall_and_distrib] lemma disjoint_union_right (x y z : finmap β) : disjoint x (y ∪ z) ↔ disjoint x y ∧ disjoint x z := by rw [disjoint.symm_iff, disjoint_union_left, disjoint.symm_iff _ x, disjoint.symm_iff _ x] theorem union_comm_of_disjoint {s₁ s₂ : finmap β} : disjoint s₁ s₂ → s₁ ∪ s₂ = s₂ ∪ s₁ := induction_on₂ s₁ s₂ $ λ s₁ s₂, by { intros h, simp only [alist.to_finmap_eq, union_to_finmap, alist.union_comm_of_disjoint h] } theorem union_cancel {s₁ s₂ s₃ : finmap β} (h : disjoint s₁ s₃) (h' : disjoint s₂ s₃) : s₁ ∪ s₃ = s₂ ∪ s₃ ↔ s₁ = s₂ := ⟨λ h'', begin apply ext_lookup, intro x, have : (s₁ ∪ s₃).lookup x = (s₂ ∪ s₃).lookup x, from h'' ▸ rfl, by_cases hs₁ : x ∈ s₁, { rwa [lookup_union_left hs₁, lookup_union_left_of_not_in (h _ hs₁)] at this, }, { by_cases hs₂ : x ∈ s₂, { rwa [lookup_union_left_of_not_in (h' _ hs₂), lookup_union_left hs₂] at this, }, { rw [lookup_eq_none.mpr hs₁, lookup_eq_none.mpr hs₂] } } end, λ h, h ▸ rfl⟩ end end finmap
c350d5d552d8f4b6996691861cbfb9e85be11b20
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/category_theory/triangulated/pretriangulated.lean
ef43bdbc4177f8e505adf9bdb77bb5e7160aaec0
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
8,532
lean
/- Copyright (c) 2021 Luke Kershaw. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Luke Kershaw -/ import category_theory.preadditive.additive_functor import category_theory.shift import category_theory.triangulated.rotate /-! # Pretriangulated Categories This file contains the definition of pretriangulated categories and triangulated functors between them. ## Implementation Notes We work under the assumption that pretriangulated categories are preadditive categories, but not necessarily additive categories, as is assumed in some sources. TODO: generalise this to n-angulated categories as in https://arxiv.org/abs/1006.4592 -/ noncomputable theory open category_theory open category_theory.preadditive open category_theory.limits universes v v₀ v₁ v₂ u u₀ u₁ u₂ namespace category_theory.triangulated open category_theory.category /- We work in a preadditive category `C` equipped with an additive shift. -/ variables (C : Type u) [category.{v} C] [has_zero_object C] [has_shift C ℤ] [preadditive C] [∀ n : ℤ, functor.additive (shift_functor C n)] /-- A preadditive category `C` with an additive shift, and a class of "distinguished triangles" relative to that shift is called pretriangulated if the following hold: * Any triangle that is isomorphic to a distinguished triangle is also distinguished. * Any triangle of the form `(X,X,0,id,0,0)` is distinguished. * For any morphism `f : X ⟶ Y` there exists a distinguished triangle of the form `(X,Y,Z,f,g,h)`. * The triangle `(X,Y,Z,f,g,h)` is distinguished if and only if `(Y,Z,X⟦1⟧,g,h,-f⟦1⟧)` is. * Given a diagram: ``` f g h X ───> Y ───> Z ───> X⟦1⟧ │ │ │ │a │b │a⟦1⟧' V V V X' ───> Y' ───> Z' ───> X'⟦1⟧ f' g' h' ``` where the left square commutes, and whose rows are distinguished triangles, there exists a morphism `c : Z ⟶ Z'` such that `(a,b,c)` is a triangle morphism. See https://stacks.math.columbia.edu/tag/0145 -/ class pretriangulated := (distinguished_triangles [] : set (triangle C)) (isomorphic_distinguished : Π (T₁ ∈ distinguished_triangles) (T₂ ≅ T₁), T₂ ∈ distinguished_triangles) (contractible_distinguished : Π (X : C), (contractible_triangle C X) ∈ distinguished_triangles) (distinguished_cocone_triangle : Π (X Y : C) (f : X ⟶ Y), (∃ (Z : C) (g : Y ⟶ Z) (h : Z ⟶ X⟦(1:ℤ)⟧), triangle.mk _ f g h ∈ distinguished_triangles)) (rotate_distinguished_triangle : Π (T : triangle C), T ∈ distinguished_triangles ↔ T.rotate ∈ distinguished_triangles) (complete_distinguished_triangle_morphism : Π (T₁ T₂ : triangle C) (h₁ : T₁ ∈ distinguished_triangles) (h₂ : T₂ ∈ distinguished_triangles) (a : T₁.obj₁ ⟶ T₂.obj₁) (b : T₁.obj₂ ⟶ T₂.obj₂) (comm₁ : T₁.mor₁ ≫ b = a ≫ T₂.mor₁), (∃ (c : T₁.obj₃ ⟶ T₂.obj₃), (T₁.mor₂ ≫ c = b ≫ T₂.mor₂) ∧ (T₁.mor₃ ≫ a⟦1⟧' = c ≫ T₂.mor₃) )) namespace pretriangulated variables [pretriangulated C] notation `dist_triang`:20 C := distinguished_triangles C /-- Given any distinguished triangle `T`, then we know `T.rotate` is also distinguished. -/ lemma rot_of_dist_triangle (T ∈ dist_triang C) : (T.rotate ∈ dist_triang C) := (rotate_distinguished_triangle T).mp H /-- Given any distinguished triangle `T`, then we know `T.inv_rotate` is also distinguished. -/ lemma inv_rot_of_dist_triangle (T ∈ dist_triang C) : (T.inv_rotate ∈ dist_triang C) := (rotate_distinguished_triangle (T.inv_rotate)).mpr (isomorphic_distinguished T H T.inv_rotate.rotate (inv_rot_comp_rot.app T)) /-- Given any distinguished triangle ``` f g h X ───> Y ───> Z ───> X⟦1⟧ ``` the composition `f ≫ g = 0`. See https://stacks.math.columbia.edu/tag/0146 -/ lemma comp_dist_triangle_mor_zero₁₂ (T ∈ dist_triang C) : T.mor₁ ≫ T.mor₂ = 0 := begin have h := contractible_distinguished T.obj₁, have f := complete_distinguished_triangle_morphism, specialize f (contractible_triangle C T.obj₁) T h H (𝟙 T.obj₁) T.mor₁, have t : (contractible_triangle C T.obj₁).mor₁ ≫ T.mor₁ = 𝟙 T.obj₁ ≫ T.mor₁, by refl, specialize f t, cases f with c f, rw ← f.left, simp only [limits.zero_comp, contractible_triangle_mor₂], end -- TODO : tidy this proof up /-- Given any distinguished triangle ``` f g h X ───> Y ───> Z ───> X⟦1⟧ ``` the composition `g ≫ h = 0`. See https://stacks.math.columbia.edu/tag/0146 -/ lemma comp_dist_triangle_mor_zero₂₃ (T ∈ dist_triang C) : T.mor₂ ≫ T.mor₃ = 0 := comp_dist_triangle_mor_zero₁₂ C T.rotate (rot_of_dist_triangle C T H) /-- Given any distinguished triangle ``` f g h X ───> Y ───> Z ───> X⟦1⟧ ``` the composition `h ≫ f⟦1⟧ = 0`. See https://stacks.math.columbia.edu/tag/0146 -/ lemma comp_dist_triangle_mor_zero₃₁ (T ∈ dist_triang C) : T.mor₃ ≫ ((shift_equiv C 1).functor.map T.mor₁) = 0 := have H₂ : _ := rot_of_dist_triangle C T.rotate (rot_of_dist_triangle C T H), by simpa using comp_dist_triangle_mor_zero₁₂ C (T.rotate.rotate) H₂ /- TODO: If `C` is pretriangulated with respect to a shift, then `Cᵒᵖ` is pretriangulated with respect to the inverse shift. -/ end pretriangulated end category_theory.triangulated namespace category_theory.triangulated namespace pretriangulated variables (C : Type u₁) [category.{v₁} C] [has_zero_object C] [has_shift C ℤ] [preadditive C] [∀ n : ℤ, functor.additive (shift_functor C n)] variables (D : Type u₂) [category.{v₂} D] [has_zero_object D] [has_shift D ℤ] [preadditive D] [∀ n : ℤ, functor.additive (shift_functor D n)] /-- The underlying structure of a triangulated functor between pretriangulated categories `C` and `D` is a functor `F : C ⥤ D` together with given functorial isomorphisms `ξ X : F(X⟦1⟧) ⟶ F(X)⟦1⟧`. -/ structure triangulated_functor_struct extends (C ⥤ D) := (comm_shift : shift_functor C (1 : ℤ) ⋙ to_functor ≅ to_functor ⋙ shift_functor D (1 : ℤ)) instance : inhabited (triangulated_functor_struct C C) := ⟨{ obj := λ X, X, map := λ _ _ f, f, comm_shift := by refl }⟩ variables {C D} /-- Given a `triangulated_functor_struct` we can define a function from triangles of `C` to triangles of `D`. -/ @[simp] def triangulated_functor_struct.map_triangle (F : triangulated_functor_struct C D) (T : triangle C) : triangle D := triangle.mk _ (F.map T.mor₁) (F.map T.mor₂) (F.map T.mor₃ ≫ F.comm_shift.hom.app T.obj₁) variables (C D) /-- A triangulated functor between pretriangulated categories `C` and `D` is a functor `F : C ⥤ D` together with given functorial isomorphisms `ξ X : F(X⟦1⟧) ⟶ F(X)⟦1⟧` such that for every distinguished triangle `(X,Y,Z,f,g,h)` of `C`, the triangle `(F(X), F(Y), F(Z), F(f), F(g), F(h) ≫ (ξ X))` is a distinguished triangle of `D`. See https://stacks.math.columbia.edu/tag/014V -/ structure triangulated_functor [pretriangulated C] [pretriangulated D] extends triangulated_functor_struct C D := (map_distinguished' : Π (T: triangle C), (T ∈ dist_triang C) → (to_triangulated_functor_struct.map_triangle T ∈ dist_triang D) ) instance [pretriangulated C] : inhabited (triangulated_functor C C) := ⟨{obj := λ X, X, map := λ _ _ f, f, comm_shift := by refl , map_distinguished' := begin rintros ⟨_,_,_,_⟩ Tdt, dsimp at *, rwa category.comp_id, end }⟩ variables {C D} [pretriangulated C] [pretriangulated D] /-- Given a `triangulated_functor` we can define a function from triangles of `C` to triangles of `D`. -/ @[simp] def triangulated_functor.map_triangle (F : triangulated_functor C D) (T : triangle C) : triangle D := triangle.mk _ (F.map T.mor₁) (F.map T.mor₂) (F.map T.mor₃ ≫ F.comm_shift.hom.app T.obj₁) /-- Given a `triangulated_functor` and a distinguished triangle `T` of `C`, then the triangle it maps onto in `D` is also distinguished. -/ lemma triangulated_functor.map_distinguished (F : triangulated_functor C D) (T : triangle C) (h : T ∈ dist_triang C) : (F.map_triangle T) ∈ dist_triang D := F.map_distinguished' T h end pretriangulated end category_theory.triangulated
289deed1733c36144aed2046d5672821b15c12eb
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/functor/const.lean
e1b08fce78845c97cb3e7a653d359e9947ab7e95
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
2,932
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Bhavik Mehta -/ import category_theory.opposites /-! # The constant functor `const J : C ⥤ (J ⥤ C)` is the functor that sends an object `X : C` to the functor `J ⥤ C` sending every object in `J` to `X`, and every morphism to `𝟙 X`. When `J` is nonempty, `const` is faithful. We have `(const J).obj X ⋙ F ≅ (const J).obj (F.obj X)` for any `F : C ⥤ D`. -/ -- declare the `v`'s first; see `category_theory.category` for an explanation universes v₁ v₂ v₃ u₁ u₂ u₃ open category_theory namespace category_theory.functor variables (J : Type u₁) [category.{v₁} J] variables {C : Type u₂} [category.{v₂} C] /-- The functor sending `X : C` to the constant functor `J ⥤ C` sending everything to `X`. -/ @[simps] def const : C ⥤ (J ⥤ C) := { obj := λ X, { obj := λ j, X, map := λ j j' f, 𝟙 X }, map := λ X Y f, { app := λ j, f } } namespace const open opposite variables {J} /-- The contant functor `Jᵒᵖ ⥤ Cᵒᵖ` sending everything to `op X` is (naturally isomorphic to) the opposite of the constant functor `J ⥤ C` sending everything to `X`. -/ @[simps] def op_obj_op (X : C) : (const Jᵒᵖ).obj (op X) ≅ ((const J).obj X).op := { hom := { app := λ j, 𝟙 _ }, inv := { app := λ j, 𝟙 _ } } /-- The contant functor `Jᵒᵖ ⥤ C` sending everything to `unop X` is (naturally isomorphic to) the opposite of the constant functor `J ⥤ Cᵒᵖ` sending everything to `X`. -/ def op_obj_unop (X : Cᵒᵖ) : (const Jᵒᵖ).obj (unop X) ≅ ((const J).obj X).left_op := { hom := { app := λ j, 𝟙 _ }, inv := { app := λ j, 𝟙 _ } } -- Lean needs some help with universes here. @[simp] lemma op_obj_unop_hom_app (X : Cᵒᵖ) (j : Jᵒᵖ) : (op_obj_unop.{v₁ v₂} X).hom.app j = 𝟙 _ := rfl @[simp] lemma op_obj_unop_inv_app (X : Cᵒᵖ) (j : Jᵒᵖ) : (op_obj_unop.{v₁ v₂} X).inv.app j = 𝟙 _ := rfl @[simp] lemma unop_functor_op_obj_map (X : Cᵒᵖ) {j₁ j₂ : J} (f : j₁ ⟶ j₂) : (unop ((functor.op (const J)).obj X)).map f = 𝟙 (unop X) := rfl end const section variables {D : Type u₃} [category.{v₃} D] /-- These are actually equal, of course, but not definitionally equal (the equality requires F.map (𝟙 _) = 𝟙 _). A natural isomorphism is more convenient than an equality between functors (compare id_to_iso). -/ @[simps] def const_comp (X : C) (F : C ⥤ D) : (const J).obj X ⋙ F ≅ (const J).obj (F.obj X) := { hom := { app := λ _, 𝟙 _ }, inv := { app := λ _, 𝟙 _ } } /-- If `J` is nonempty, then the constant functor over `J` is faithful. -/ instance [nonempty J] : faithful (const J : C ⥤ J ⥤ C) := { map_injective' := λ X Y f g e, nat_trans.congr_app e (classical.arbitrary J) } end end category_theory.functor
65f2320c8635fc82a226087f4a5dac52732ef644
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/set/lattice.lean
a620fca369967f4fe66068653bfff4ec0619b4cf
[ "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
74,850
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Johannes Hölzl, Mario Carneiro -/ import order.complete_boolean_algebra import order.directed import order.galois_connection /-! # The set lattice This file provides usual set notation for unions and intersections, a `complete_lattice` instance for `set α`, and some more set constructions. ## Main declarations * `set.Union`: Union of an indexed family of sets. * `set.Inter`: Intersection of an indexed family of sets. * `set.sInter`: **s**et **Inter**. Intersection of sets belonging to a set of sets. * `set.sUnion`: **s**et **Union**. Union of sets belonging to a set of sets. This is actually defined in core Lean. * `set.sInter_eq_bInter`, `set.sUnion_eq_bInter`: Shows that `⋂₀ s = ⋂ x ∈ s, x` and `⋃₀ s = ⋃ x ∈ s, x`. * `set.complete_boolean_algebra`: `set α` is a `complete_boolean_algebra` with `≤ = ⊆`, `< = ⊂`, `⊓ = ∩`, `⊔ = ∪`, `⨅ = ⋂`, `⨆ = ⋃` and `\` as the set difference. See `set.boolean_algebra`. * `set.kern_image`: For a function `f : α → β`, `s.kern_image f` is the set of `y` such that `f ⁻¹ y ⊆ s`. * `set.seq`: Union of the image of a set under a **seq**uence of functions. `seq s t` is the union of `f '' t` over all `f ∈ s`, where `t : set α` and `s : set (α → β)`. * `set.Union_eq_sigma_of_disjoint`: Equivalence between `⋃ i, t i` and `Σ i, t i`, where `t` is an indexed family of disjoint sets. ## Naming convention In lemma names, * `⋃ i, s i` is called `Union` * `⋂ i, s i` is called `Inter` * `⋃ i j, s i j` is called `Union₂`. This is a `Union` inside a `Union`. * `⋂ i j, s i j` is called `Inter₂`. This is an `Inter` inside an `Inter`. * `⋃ i ∈ s, t i` is called `bUnion` for "bounded `Union`". This is the special case of `Union₂` where `j : i ∈ s`. * `⋂ i ∈ s, t i` is called `bInter` for "bounded `Inter`". This is the special case of `Inter₂` where `j : i ∈ s`. ## Notation * `⋃`: `set.Union` * `⋂`: `set.Inter` * `⋃₀`: `set.sUnion` * `⋂₀`: `set.sInter` -/ open function tactic set universes u variables {α β γ : Type*} {ι ι' ι₂ : Sort*} {κ κ₁ κ₂ : ι → Sort*} {κ' : ι' → Sort*} namespace set /-! ### Complete lattice and complete Boolean algebra instances -/ instance : has_Inf (set α) := ⟨λ s, {a | ∀ t ∈ s, a ∈ t}⟩ instance : has_Sup (set α) := ⟨λ s, {a | ∃ t ∈ s, a ∈ t}⟩ /-- Intersection of a set of sets. -/ def sInter (S : set (set α)) : set α := Inf S /-- Union of a set of sets. -/ def sUnion (S : set (set α)) : set α := Sup S prefix `⋂₀ `:110 := sInter prefix `⋃₀ `:110 := sUnion @[simp] theorem mem_sInter {x : α} {S : set (set α)} : x ∈ ⋂₀ S ↔ ∀ t ∈ S, x ∈ t := iff.rfl @[simp] theorem mem_sUnion {x : α} {S : set (set α)} : x ∈ ⋃₀ S ↔ ∃ t ∈ S, x ∈ t := iff.rfl /-- Indexed union of a family of sets -/ def Union (s : ι → set β) : set β := supr s /-- Indexed intersection of a family of sets -/ def Inter (s : ι → set β) : set β := infi s notation `⋃` binders `, ` r:(scoped f, Union f) := r notation `⋂` binders `, ` r:(scoped f, Inter f) := r @[simp] lemma Sup_eq_sUnion (S : set (set α)) : Sup S = ⋃₀ S := rfl @[simp] lemma Inf_eq_sInter (S : set (set α)) : Inf S = ⋂₀ S := rfl @[simp] lemma supr_eq_Union (s : ι → set α) : supr s = Union s := rfl @[simp] lemma infi_eq_Inter (s : ι → set α) : infi s = Inter s := rfl @[simp] lemma mem_Union {x : α} {s : ι → set α} : x ∈ (⋃ i, s i) ↔ ∃ i, x ∈ s i := ⟨λ ⟨t, ⟨⟨a, (t_eq : s a = t)⟩, (h : x ∈ t)⟩⟩, ⟨a, t_eq.symm ▸ h⟩, λ ⟨a, h⟩, ⟨s a, ⟨⟨a, rfl⟩, h⟩⟩⟩ @[simp] lemma mem_Inter {x : α} {s : ι → set α} : x ∈ (⋂ i, s i) ↔ ∀ i, x ∈ s i := ⟨λ (h : ∀ a ∈ {a : set α | ∃ i, s i = a}, x ∈ a) a, h (s a) ⟨a, rfl⟩, λ h t ⟨a, (eq : s a = t)⟩, eq ▸ h a⟩ lemma mem_Union₂ {x : γ} {s : Π i, κ i → set γ} : x ∈ (⋃ i j, s i j) ↔ ∃ i j, x ∈ s i j := by simp_rw mem_Union lemma mem_Inter₂ {x : γ} {s : Π i, κ i → set γ} : x ∈ (⋂ i j, s i j) ↔ ∀ i j, x ∈ s i j := by simp_rw mem_Inter lemma mem_Union_of_mem {s : ι → set α} {a : α} (i : ι) (ha : a ∈ s i) : a ∈ ⋃ i, s i := mem_Union.2 ⟨i, ha⟩ lemma mem_Union₂_of_mem {s : Π i, κ i → set α} {a : α} {i : ι} (j : κ i) (ha : a ∈ s i j) : a ∈ ⋃ i j, s i j := mem_Union₂.2 ⟨i, j, ha⟩ lemma mem_Inter_of_mem {s : ι → set α} {a : α} (h : ∀ i, a ∈ s i) : a ∈ ⋂ i, s i := mem_Inter.2 h lemma mem_Inter₂_of_mem {s : Π i, κ i → set α} {a : α} (h : ∀ i j, a ∈ s i j) : a ∈ ⋂ i j, s i j := mem_Inter₂.2 h instance : complete_boolean_algebra (set α) := { Sup := Sup, Inf := Inf, le_Sup := λ s t t_in a a_in, ⟨t, ⟨t_in, a_in⟩⟩, Sup_le := λ s t h a ⟨t', ⟨t'_in, a_in⟩⟩, h t' t'_in a_in, le_Inf := λ s t h a a_in t' t'_in, h t' t'_in a_in, Inf_le := λ s t t_in a h, h _ t_in, infi_sup_le_sup_Inf := λ s S x, iff.mp $ by simp [forall_or_distrib_left], inf_Sup_le_supr_inf := λ s S x, iff.mp $ by simp [exists_and_distrib_left], .. set.boolean_algebra } /-- `set.image` is monotone. See `set.image_image` for the statement in terms of `⊆`. -/ lemma monotone_image {f : α → β} : monotone (image f) := λ s t, image_subset _ theorem _root_.monotone.inter [preorder β] {f g : β → set α} (hf : monotone f) (hg : monotone g) : monotone (λ x, f x ∩ g x) := hf.inf hg theorem _root_.monotone_on.inter [preorder β] {f g : β → set α} {s : set β} (hf : monotone_on f s) (hg : monotone_on g s) : monotone_on (λ x, f x ∩ g x) s := hf.inf hg theorem _root_.antitone.inter [preorder β] {f g : β → set α} (hf : antitone f) (hg : antitone g) : antitone (λ x, f x ∩ g x) := hf.inf hg theorem _root_.antitone_on.inter [preorder β] {f g : β → set α} {s : set β} (hf : antitone_on f s) (hg : antitone_on g s) : antitone_on (λ x, f x ∩ g x) s := hf.inf hg theorem _root_.monotone.union [preorder β] {f g : β → set α} (hf : monotone f) (hg : monotone g) : monotone (λ x, f x ∪ g x) := hf.sup hg theorem _root_.monotone_on.union [preorder β] {f g : β → set α} {s : set β} (hf : monotone_on f s) (hg : monotone_on g s) : monotone_on (λ x, f x ∪ g x) s := hf.sup hg theorem _root_.antitone.union [preorder β] {f g : β → set α} (hf : antitone f) (hg : antitone g) : antitone (λ x, f x ∪ g x) := hf.sup hg theorem _root_.antitone_on.union [preorder β] {f g : β → set α} {s : set β} (hf : antitone_on f s) (hg : antitone_on g s) : antitone_on (λ x, f x ∪ g x) s := hf.sup hg theorem monotone_set_of [preorder α] {p : α → β → Prop} (hp : ∀ b, monotone (λ a, p a b)) : monotone (λ a, {b | p a b}) := λ a a' h b, hp b h theorem antitone_set_of [preorder α] {p : α → β → Prop} (hp : ∀ b, antitone (λ a, p a b)) : antitone (λ a, {b | p a b}) := λ a a' h b, hp b h /-- Quantifying over a set is antitone in the set -/ lemma antitone_bforall {P : α → Prop} : antitone (λ s : set α, ∀ x ∈ s, P x) := λ s t hst h x hx, h x $ hst hx section galois_connection variables {f : α → β} protected lemma image_preimage : galois_connection (image f) (preimage f) := λ a b, image_subset_iff /-- `kern_image f s` is the set of `y` such that `f ⁻¹ y ⊆ s`. -/ def kern_image (f : α → β) (s : set α) : set β := {y | ∀ ⦃x⦄, f x = y → x ∈ s} protected lemma preimage_kern_image : galois_connection (preimage f) (kern_image f) := λ a b, ⟨ λ h x hx y hy, have f y ∈ a, from hy.symm ▸ hx, h this, λ h x (hx : f x ∈ a), h hx rfl⟩ end galois_connection /-! ### Union and intersection over an indexed family of sets -/ instance : order_top (set α) := { top := univ, le_top := by simp } @[congr] theorem Union_congr_Prop {p q : Prop} {f₁ : p → set α} {f₂ : q → set α} (pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : Union f₁ = Union f₂ := supr_congr_Prop pq f @[congr] theorem Inter_congr_Prop {p q : Prop} {f₁ : p → set α} {f₂ : q → set α} (pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : Inter f₁ = Inter f₂ := infi_congr_Prop pq f lemma Union_plift_up (f : plift ι → set α) : (⋃ i, f (plift.up i)) = ⋃ i, f i := supr_plift_up _ lemma Union_plift_down (f : ι → set α) : (⋃ i, f (plift.down i)) = ⋃ i, f i := supr_plift_down _ lemma Inter_plift_up (f : plift ι → set α) : (⋂ i, f (plift.up i)) = ⋂ i, f i := infi_plift_up _ lemma Inter_plift_down (f : ι → set α) : (⋂ i, f (plift.down i)) = ⋂ i, f i := infi_plift_down _ lemma Union_eq_if {p : Prop} [decidable p] (s : set α) : (⋃ h : p, s) = if p then s else ∅ := supr_eq_if _ lemma Union_eq_dif {p : Prop} [decidable p] (s : p → set α) : (⋃ (h : p), s h) = if h : p then s h else ∅ := supr_eq_dif _ lemma Inter_eq_if {p : Prop} [decidable p] (s : set α) : (⋂ h : p, s) = if p then s else univ := infi_eq_if _ lemma Infi_eq_dif {p : Prop} [decidable p] (s : p → set α) : (⋂ (h : p), s h) = if h : p then s h else univ := infi_eq_dif _ lemma exists_set_mem_of_union_eq_top {ι : Type*} (t : set ι) (s : ι → set β) (w : (⋃ i ∈ t, s i) = ⊤) (x : β) : ∃ (i ∈ t), x ∈ s i := begin have p : x ∈ ⊤ := set.mem_univ x, simpa only [←w, set.mem_Union] using p, end lemma nonempty_of_union_eq_top_of_nonempty {ι : Type*} (t : set ι) (s : ι → set α) (H : nonempty α) (w : (⋃ i ∈ t, s i) = ⊤) : t.nonempty := begin obtain ⟨x, m, -⟩ := exists_set_mem_of_union_eq_top t s w H.some, exact ⟨x, m⟩, end theorem set_of_exists (p : ι → β → Prop) : {x | ∃ i, p i x} = ⋃ i, {x | p i x} := ext $ λ i, mem_Union.symm theorem set_of_forall (p : ι → β → Prop) : {x | ∀ i, p i x} = ⋂ i, {x | p i x} := ext $ λ i, mem_Inter.symm lemma Union_subset {s : ι → set α} {t : set α} (h : ∀ i, s i ⊆ t) : (⋃ i, s i) ⊆ t := @supr_le (set α) _ _ _ _ h lemma Union₂_subset {s : Π i, κ i → set α} {t : set α} (h : ∀ i j, s i j ⊆ t) : (⋃ i j, s i j) ⊆ t := Union_subset $ λ x, Union_subset (h x) theorem subset_Inter {t : set β} {s : ι → set β} (h : ∀ i, t ⊆ s i) : t ⊆ ⋂ i, s i := @le_infi (set β) _ _ _ _ h lemma subset_Inter₂ {s : set α} {t : Π i, κ i → set α} (h : ∀ i j, s ⊆ t i j) : s ⊆ ⋂ i j, t i j := subset_Inter $ λ x, subset_Inter $ h x @[simp] lemma Union_subset_iff {s : ι → set α} {t : set α} : (⋃ i, s i) ⊆ t ↔ ∀ i, s i ⊆ t := ⟨λ h i, subset.trans (le_supr s _) h, Union_subset⟩ lemma Union₂_subset_iff {s : Π i, κ i → set α} {t : set α} : (⋃ i j, s i j) ⊆ t ↔ ∀ i j, s i j ⊆ t := by simp_rw Union_subset_iff @[simp] lemma subset_Inter_iff {s : set α} {t : ι → set α} : s ⊆ (⋂ i, t i) ↔ ∀ i, s ⊆ t i := @le_infi_iff (set α) _ _ _ _ @[simp] lemma subset_Inter₂_iff {s : set α} {t : Π i, κ i → set α} : s ⊆ (⋂ i j, t i j) ↔ ∀ i j, s ⊆ t i j := by simp_rw subset_Inter_iff lemma subset_Union : ∀ (s : ι → set β) (i : ι), s i ⊆ ⋃ i, s i := le_supr lemma Inter_subset : ∀ (s : ι → set β) (i : ι), (⋂ i, s i) ⊆ s i := infi_le lemma subset_Union₂ {s : Π i, κ i → set α} (i : ι) (j : κ i) : s i j ⊆ ⋃ i j, s i j := @le_supr₂ (set α) _ _ _ _ i j lemma Inter₂_subset {s : Π i, κ i → set α} (i : ι) (j : κ i) : (⋂ i j, s i j) ⊆ s i j := @infi₂_le (set α) _ _ _ _ i j /-- This rather trivial consequence of `subset_Union`is convenient with `apply`, and has `i` explicit for this purpose. -/ lemma subset_Union_of_subset {s : set α} {t : ι → set α} (i : ι) (h : s ⊆ t i) : s ⊆ ⋃ i, t i := @le_supr_of_le (set α) _ _ _ _ i h /-- This rather trivial consequence of `Inter_subset`is convenient with `apply`, and has `i` explicit for this purpose. -/ lemma Inter_subset_of_subset {s : ι → set α} {t : set α} (i : ι) (h : s i ⊆ t) : (⋂ i, s i) ⊆ t := @infi_le_of_le (set α) _ _ _ _ i h /-- This rather trivial consequence of `subset_Union₂` is convenient with `apply`, and has `i` and `j` explicit for this purpose. -/ lemma subset_Union₂_of_subset {s : set α} {t : Π i, κ i → set α} (i : ι) (j : κ i) (h : s ⊆ t i j) : s ⊆ ⋃ i j, t i j := @le_supr₂_of_le (set α) _ _ _ _ _ i j h /-- This rather trivial consequence of `Inter₂_subset` is convenient with `apply`, and has `i` and `j` explicit for this purpose. -/ lemma Inter₂_subset_of_subset {s : Π i, κ i → set α} {t : set α} (i : ι) (j : κ i) (h : s i j ⊆ t) : (⋂ i j, s i j) ⊆ t := @infi₂_le_of_le (set α) _ _ _ _ _ i j h lemma Union_mono {s t : ι → set α} (h : ∀ i, s i ⊆ t i) : (⋃ i, s i) ⊆ ⋃ i, t i := @supr_mono (set α) _ _ s t h lemma Union₂_mono {s t : Π i, κ i → set α} (h : ∀ i j, s i j ⊆ t i j) : (⋃ i j, s i j) ⊆ ⋃ i j, t i j := @supr₂_mono (set α) _ _ _ s t h lemma Inter_mono {s t : ι → set α} (h : ∀ i, s i ⊆ t i) : (⋂ i, s i) ⊆ ⋂ i, t i := @infi_mono (set α) _ _ s t h lemma Inter₂_mono {s t : Π i, κ i → set α} (h : ∀ i j, s i j ⊆ t i j) : (⋂ i j, s i j) ⊆ ⋂ i j, t i j := @infi₂_mono (set α) _ _ _ s t h lemma Union_mono' {s : ι → set α} {t : ι₂ → set α} (h : ∀ i, ∃ j, s i ⊆ t j) : (⋃ i, s i) ⊆ ⋃ i, t i := @supr_mono' (set α) _ _ _ s t h lemma Union₂_mono' {s : Π i, κ i → set α} {t : Π i', κ' i' → set α} (h : ∀ i j, ∃ i' j', s i j ⊆ t i' j') : (⋃ i j, s i j) ⊆ ⋃ i' j', t i' j' := @supr₂_mono' (set α) _ _ _ _ _ s t h lemma Inter_mono' {s : ι → set α} {t : ι' → set α} (h : ∀ j, ∃ i, s i ⊆ t j) : (⋂ i, s i) ⊆ (⋂ j, t j) := set.subset_Inter $ λ j, let ⟨i, hi⟩ := h j in Inter_subset_of_subset i hi lemma Inter₂_mono' {s : Π i, κ i → set α} {t : Π i', κ' i' → set α} (h : ∀ i' j', ∃ i j, s i j ⊆ t i' j') : (⋂ i j, s i j) ⊆ ⋂ i' j', t i' j' := subset_Inter₂_iff.2 $ λ i' j', let ⟨i, j, hst⟩ := h i' j' in (Inter₂_subset _ _).trans hst lemma Union₂_subset_Union (κ : ι → Sort*) (s : ι → set α) : (⋃ i (j : κ i), s i) ⊆ ⋃ i, s i := Union_mono $ λ i, Union_subset $ λ h, subset.rfl lemma Inter_subset_Inter₂ (κ : ι → Sort*) (s : ι → set α) : (⋂ i, s i) ⊆ ⋂ i (j : κ i), s i := Inter_mono $ λ i, subset_Inter $ λ h, subset.rfl lemma Union_set_of (P : ι → α → Prop) : (⋃ i, {x : α | P i x}) = {x : α | ∃ i, P i x} := by { ext, exact mem_Union } lemma Inter_set_of (P : ι → α → Prop) : (⋂ i, {x : α | P i x}) = {x : α | ∀ i, P i x} := by { ext, exact mem_Inter } lemma Union_congr_of_surjective {f : ι → set α} {g : ι₂ → set α} (h : ι → ι₂) (h1 : surjective h) (h2 : ∀ x, g (h x) = f x) : (⋃ x, f x) = ⋃ y, g y := h1.supr_congr h h2 lemma Inter_congr_of_surjective {f : ι → set α} {g : ι₂ → set α} (h : ι → ι₂) (h1 : surjective h) (h2 : ∀ x, g (h x) = f x) : (⋂ x, f x) = ⋂ y, g y := h1.infi_congr h h2 theorem Union_const [nonempty ι] (s : set β) : (⋃ i : ι, s) = s := supr_const theorem Inter_const [nonempty ι] (s : set β) : (⋂ i : ι, s) = s := infi_const @[simp] theorem compl_Union (s : ι → set β) : (⋃ i, s i)ᶜ = (⋂ i, (s i)ᶜ) := compl_supr lemma compl_Union₂ (s : Π i, κ i → set α) : (⋃ i j, s i j)ᶜ = ⋂ i j, (s i j)ᶜ := by simp_rw compl_Union @[simp] theorem compl_Inter (s : ι → set β) : (⋂ i, s i)ᶜ = (⋃ i, (s i)ᶜ) := compl_infi lemma compl_Inter₂ (s : Π i, κ i → set α) : (⋂ i j, s i j)ᶜ = ⋃ i j, (s i j)ᶜ := by simp_rw compl_Inter -- classical -- complete_boolean_algebra theorem Union_eq_compl_Inter_compl (s : ι → set β) : (⋃ i, s i) = (⋂ i, (s i)ᶜ)ᶜ := by simp only [compl_Inter, compl_compl] -- classical -- complete_boolean_algebra theorem Inter_eq_compl_Union_compl (s : ι → set β) : (⋂ i, s i) = (⋃ i, (s i)ᶜ)ᶜ := by simp only [compl_Union, compl_compl] theorem inter_Union (s : set β) (t : ι → set β) : s ∩ (⋃ i, t i) = ⋃ i, s ∩ t i := inf_supr_eq _ _ theorem Union_inter (s : set β) (t : ι → set β) : (⋃ i, t i) ∩ s = ⋃ i, t i ∩ s := supr_inf_eq _ _ theorem Union_union_distrib (s : ι → set β) (t : ι → set β) : (⋃ i, s i ∪ t i) = (⋃ i, s i) ∪ (⋃ i, t i) := supr_sup_eq theorem Inter_inter_distrib (s : ι → set β) (t : ι → set β) : (⋂ i, s i ∩ t i) = (⋂ i, s i) ∩ (⋂ i, t i) := infi_inf_eq theorem union_Union [nonempty ι] (s : set β) (t : ι → set β) : s ∪ (⋃ i, t i) = ⋃ i, s ∪ t i := sup_supr theorem Union_union [nonempty ι] (s : set β) (t : ι → set β) : (⋃ i, t i) ∪ s = ⋃ i, t i ∪ s := supr_sup theorem inter_Inter [nonempty ι] (s : set β) (t : ι → set β) : s ∩ (⋂ i, t i) = ⋂ i, s ∩ t i := inf_infi theorem Inter_inter [nonempty ι] (s : set β) (t : ι → set β) : (⋂ i, t i) ∩ s = ⋂ i, t i ∩ s := infi_inf -- classical theorem union_Inter (s : set β) (t : ι → set β) : s ∪ (⋂ i, t i) = ⋂ i, s ∪ t i := sup_infi_eq _ _ theorem Inter_union (s : ι → set β) (t : set β) : (⋂ i, s i) ∪ t = ⋂ i, s i ∪ t := infi_sup_eq _ _ theorem Union_diff (s : set β) (t : ι → set β) : (⋃ i, t i) \ s = ⋃ i, t i \ s := Union_inter _ _ theorem diff_Union [nonempty ι] (s : set β) (t : ι → set β) : s \ (⋃ i, t i) = ⋂ i, s \ t i := by rw [diff_eq, compl_Union, inter_Inter]; refl theorem diff_Inter (s : set β) (t : ι → set β) : s \ (⋂ i, t i) = ⋃ i, s \ t i := by rw [diff_eq, compl_Inter, inter_Union]; refl lemma directed_on_Union {r} {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 λ 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₂⟩ lemma Union_inter_subset {ι α} {s t : ι → set α} : (⋃ i, s i ∩ t i) ⊆ (⋃ i, s i) ∩ (⋃ i, t i) := le_supr_inf_supr s t lemma Union_inter_of_monotone {ι α} [preorder ι] [is_directed ι (≤)] {s t : ι → set α} (hs : monotone s) (ht : monotone t) : (⋃ i, s i ∩ t i) = (⋃ i, s i) ∩ (⋃ i, t i) := supr_inf_of_monotone hs ht lemma Union_inter_of_antitone {ι α} [preorder ι] [is_directed ι (swap (≤))] {s t : ι → set α} (hs : antitone s) (ht : antitone t) : (⋃ i, s i ∩ t i) = (⋃ i, s i) ∩ (⋃ i, t i) := supr_inf_of_antitone hs ht lemma Inter_union_of_monotone {ι α} [preorder ι] [is_directed ι (swap (≤))] {s t : ι → set α} (hs : monotone s) (ht : monotone t) : (⋂ i, s i ∪ t i) = (⋂ i, s i) ∪ (⋂ i, t i) := infi_sup_of_monotone hs ht lemma Inter_union_of_antitone {ι α} [preorder ι] [is_directed ι (≤)] {s t : ι → set α} (hs : antitone s) (ht : antitone t) : (⋂ i, s i ∪ t i) = (⋂ i, s i) ∪ (⋂ i, t i) := infi_sup_of_antitone hs ht /-- An equality version of this lemma is `Union_Inter_of_monotone` in `data.set.finite`. -/ lemma Union_Inter_subset {s : ι → ι' → set α} : (⋃ j, ⋂ i, s i j) ⊆ ⋂ i, ⋃ j, s i j := supr_infi_le_infi_supr (flip s) lemma Union_option {ι} (s : option ι → set α) : (⋃ o, s o) = s none ∪ ⋃ i, s (some i) := supr_option s lemma Inter_option {ι} (s : option ι → set α) : (⋂ o, s o) = s none ∩ ⋂ i, s (some i) := infi_option s section variables (p : ι → Prop) [decidable_pred p] lemma Union_dite (f : Π i, p i → set α) (g : Π i, ¬p i → set α) : (⋃ i, if h : p i then f i h else g i h) = (⋃ i (h : p i), f i h) ∪ (⋃ i (h : ¬ p i), g i h) := supr_dite _ _ _ lemma Union_ite (f g : ι → set α) : (⋃ i, if p i then f i else g i) = (⋃ i (h : p i), f i) ∪ (⋃ i (h : ¬ p i), g i) := Union_dite _ _ _ lemma Inter_dite (f : Π i, p i → set α) (g : Π i, ¬p i → set α) : (⋂ i, if h : p i then f i h else g i h) = (⋂ i (h : p i), f i h) ∩ (⋂ i (h : ¬ p i), g i h) := infi_dite _ _ _ lemma Inter_ite (f g : ι → set α) : (⋂ i, if p i then f i else g i) = (⋂ i (h : p i), f i) ∩ (⋂ i (h : ¬ p i), g i) := Inter_dite _ _ _ end lemma image_projection_prod {ι : Type*} {α : ι → Type*} {v : Π (i : ι), set (α i)} (hv : (pi univ v).nonempty) (i : ι) : (λ (x : Π (i : ι), α i), x i) '' (⋂ k, (λ (x : Π (j : ι), α j), x k) ⁻¹' v k) = v i:= begin classical, apply subset.antisymm, { simp [Inter_subset] }, { intros y y_in, simp only [mem_image, mem_Inter, mem_preimage], rcases hv with ⟨z, hz⟩, refine ⟨function.update z i y, _, update_same i y z⟩, rw @forall_update_iff ι α _ z i y (λ i t, t ∈ v i), exact ⟨y_in, λ j hj, by simpa using hz j⟩ }, end /-! ### Unions and intersections indexed by `Prop` -/ theorem Inter_false {s : false → set α} : Inter s = univ := infi_false theorem Union_false {s : false → set α} : Union s = ∅ := supr_false @[simp] theorem Inter_true {s : true → set α} : Inter s = s trivial := infi_true @[simp] theorem Union_true {s : true → set α} : Union s = s trivial := supr_true @[simp] theorem Inter_exists {p : ι → Prop} {f : Exists p → set α} : (⋂ x, f x) = (⋂ i (h : p i), f ⟨i, h⟩) := infi_exists @[simp] theorem Union_exists {p : ι → Prop} {f : Exists p → set α} : (⋃ x, f x) = (⋃ i (h : p i), f ⟨i, h⟩) := supr_exists @[simp] lemma Union_empty : (⋃ i : ι, ∅ : set α) = ∅ := supr_bot @[simp] lemma Inter_univ : (⋂ i : ι, univ : set α) = univ := infi_top section variables {s : ι → set α} @[simp] lemma Union_eq_empty : (⋃ i, s i) = ∅ ↔ ∀ i, s i = ∅ := supr_eq_bot @[simp] lemma Inter_eq_univ : (⋂ i, s i) = univ ↔ ∀ i, s i = univ := infi_eq_top @[simp] lemma nonempty_Union : (⋃ i, s i).nonempty ↔ ∃ i, (s i).nonempty := by simp [← ne_empty_iff_nonempty] @[simp] lemma nonempty_bUnion {t : set α} {s : α → set β} : (⋃ i ∈ t, s i).nonempty ↔ ∃ i ∈ t, (s i).nonempty := by simp [← ne_empty_iff_nonempty] lemma Union_nonempty_index (s : set α) (t : s.nonempty → set β) : (⋃ h, t h) = ⋃ x ∈ s, t ⟨x, ‹_›⟩ := supr_exists end @[simp] theorem Inter_Inter_eq_left {b : β} {s : Π x : β, x = b → set α} : (⋂ x (h : x = b), s x h) = s b rfl := infi_infi_eq_left @[simp] theorem Inter_Inter_eq_right {b : β} {s : Π x : β, b = x → set α} : (⋂ x (h : b = x), s x h) = s b rfl := infi_infi_eq_right @[simp] theorem Union_Union_eq_left {b : β} {s : Π x : β, x = b → set α} : (⋃ x (h : x = b), s x h) = s b rfl := supr_supr_eq_left @[simp] theorem Union_Union_eq_right {b : β} {s : Π x : β, b = x → set α} : (⋃ x (h : b = x), s x h) = s b rfl := supr_supr_eq_right theorem Inter_or {p q : Prop} (s : p ∨ q → set α) : (⋂ h, s h) = (⋂ h : p, s (or.inl h)) ∩ (⋂ h : q, s (or.inr h)) := infi_or theorem Union_or {p q : Prop} (s : p ∨ q → set α) : (⋃ h, s h) = (⋃ i, s (or.inl i)) ∪ (⋃ j, s (or.inr j)) := supr_or theorem Union_and {p q : Prop} (s : p ∧ q → set α) : (⋃ h, s h) = ⋃ hp hq, s ⟨hp, hq⟩ := supr_and theorem Inter_and {p q : Prop} (s : p ∧ q → set α) : (⋂ h, s h) = ⋂ hp hq, s ⟨hp, hq⟩ := infi_and lemma Union_comm (s : ι → ι' → set α) : (⋃ i i', s i i') = ⋃ i' i, s i i' := supr_comm lemma Inter_comm (s : ι → ι' → set α) : (⋂ i i', s i i') = ⋂ i' i, s i i' := infi_comm lemma Union₂_comm (s : Π i₁, κ₁ i₁ → Π i₂, κ₂ i₂ → set α) : (⋃ i₁ j₁ i₂ j₂, s i₁ j₁ i₂ j₂) = ⋃ i₂ j₂ i₁ j₁, s i₁ j₁ i₂ j₂ := supr₂_comm _ lemma Inter₂_comm (s : Π i₁, κ₁ i₁ → Π i₂, κ₂ i₂ → set α) : (⋂ i₁ j₁ i₂ j₂, s i₁ j₁ i₂ j₂) = ⋂ i₂ j₂ i₁ j₁, s i₁ j₁ i₂ j₂ := infi₂_comm _ @[simp] theorem bUnion_and (p : ι → Prop) (q : ι → ι' → Prop) (s : Π x y, p x ∧ q x y → set α) : (⋃ (x : ι) (y : ι') (h : p x ∧ q x y), s x y h) = ⋃ (x : ι) (hx : p x) (y : ι') (hy : q x y), s x y ⟨hx, hy⟩ := by simp only [Union_and, @Union_comm _ ι'] @[simp] theorem bUnion_and' (p : ι' → Prop) (q : ι → ι' → Prop) (s : Π x y, p y ∧ q x y → set α) : (⋃ (x : ι) (y : ι') (h : p y ∧ q x y), s x y h) = ⋃ (y : ι') (hy : p y) (x : ι) (hx : q x y), s x y ⟨hy, hx⟩ := by simp only [Union_and, @Union_comm _ ι] @[simp] theorem bInter_and (p : ι → Prop) (q : ι → ι' → Prop) (s : Π x y, p x ∧ q x y → set α) : (⋂ (x : ι) (y : ι') (h : p x ∧ q x y), s x y h) = ⋂ (x : ι) (hx : p x) (y : ι') (hy : q x y), s x y ⟨hx, hy⟩ := by simp only [Inter_and, @Inter_comm _ ι'] @[simp] theorem bInter_and' (p : ι' → Prop) (q : ι → ι' → Prop) (s : Π x y, p y ∧ q x y → set α) : (⋂ (x : ι) (y : ι') (h : p y ∧ q x y), s x y h) = ⋂ (y : ι') (hy : p y) (x : ι) (hx : q x y), s x y ⟨hy, hx⟩ := by simp only [Inter_and, @Inter_comm _ ι] @[simp] theorem Union_Union_eq_or_left {b : β} {p : β → Prop} {s : Π x : β, (x = b ∨ p x) → set α} : (⋃ x h, s x h) = s b (or.inl rfl) ∪ ⋃ x (h : p x), s x (or.inr h) := by simp only [Union_or, Union_union_distrib, Union_Union_eq_left] @[simp] theorem Inter_Inter_eq_or_left {b : β} {p : β → Prop} {s : Π x : β, (x = b ∨ p x) → set α} : (⋂ x h, s x h) = s b (or.inl rfl) ∩ ⋂ x (h : p x), s x (or.inr h) := by simp only [Inter_or, Inter_inter_distrib, Inter_Inter_eq_left] /-! ### Bounded unions and intersections -/ /-- A specialization of `mem_Union₂`. -/ theorem mem_bUnion {s : set α} {t : α → set β} {x : α} {y : β} (xs : x ∈ s) (ytx : y ∈ t x) : y ∈ ⋃ x ∈ s, t x := mem_Union₂_of_mem xs ytx /-- A specialization of `mem_Inter₂`. -/ theorem mem_bInter {s : set α} {t : α → set β} {y : β} (h : ∀ x ∈ s, y ∈ t x) : y ∈ ⋂ x ∈ s, t x := mem_Inter₂_of_mem h /-- A specialization of `subset_Union₂`. -/ theorem subset_bUnion_of_mem {s : set α} {u : α → set β} {x : α} (xs : x ∈ s) : u x ⊆ (⋃ x ∈ s, u x) := subset_Union₂ x xs /-- A specialization of `Inter₂_subset`. -/ theorem bInter_subset_of_mem {s : set α} {t : α → set β} {x : α} (xs : x ∈ s) : (⋂ x ∈ s, t x) ⊆ t x := Inter₂_subset x xs theorem bUnion_subset_bUnion_left {s s' : set α} {t : α → set β} (h : s ⊆ s') : (⋃ x ∈ s, t x) ⊆ (⋃ x ∈ s', t x) := Union₂_subset $ λ x hx, subset_bUnion_of_mem $ h hx theorem bInter_subset_bInter_left {s s' : set α} {t : α → set β} (h : s' ⊆ s) : (⋂ x ∈ s, t x) ⊆ (⋂ x ∈ s', t x) := subset_Inter₂ $ λ x hx, bInter_subset_of_mem $ h hx lemma bUnion_mono {s s' : set α} {t t' : α → set β} (hs : s' ⊆ s) (h : ∀ x ∈ s, t x ⊆ t' x) : (⋃ x ∈ s', t x) ⊆ ⋃ x ∈ s, t' x := (bUnion_subset_bUnion_left hs).trans $ Union₂_mono h lemma bInter_mono {s s' : set α} {t t' : α → set β} (hs : s ⊆ s') (h : ∀ x ∈ s, t x ⊆ t' x) : (⋂ x ∈ s', t x) ⊆ (⋂ x ∈ s, t' x) := (bInter_subset_bInter_left hs).trans $ Inter₂_mono h lemma Union_congr {s t : ι → set α} (h : ∀ i, s i = t i) : (⋃ i, s i) = ⋃ i, t i := supr_congr h lemma Inter_congr {s t : ι → set α} (h : ∀ i, s i = t i) : (⋂ i, s i) = ⋂ i, t i := infi_congr h lemma Union₂_congr {s t : Π i, κ i → set α} (h : ∀ i j, s i j = t i j) : (⋃ i j, s i j) = ⋃ i j, t i j := Union_congr $ λ i, Union_congr $ h i lemma Inter₂_congr {s t : Π i, κ i → set α} (h : ∀ i j, s i j = t i j) : (⋂ i j, s i j) = ⋂ i j, t i j := Inter_congr $ λ i, Inter_congr $ h i theorem bUnion_eq_Union (s : set α) (t : Π x ∈ s, set β) : (⋃ x ∈ s, t x ‹_›) = (⋃ x : s, t x x.2) := supr_subtype' theorem bInter_eq_Inter (s : set α) (t : Π x ∈ s, set β) : (⋂ x ∈ s, t x ‹_›) = (⋂ x : s, t x x.2) := infi_subtype' theorem Union_subtype (p : α → Prop) (s : {x // p x} → set β) : (⋃ x : {x // p x}, s x) = ⋃ x (hx : p x), s ⟨x, hx⟩ := supr_subtype theorem Inter_subtype (p : α → Prop) (s : {x // p x} → set β) : (⋂ x : {x // p x}, s x) = ⋂ x (hx : p x), s ⟨x, hx⟩ := infi_subtype theorem bInter_empty (u : α → set β) : (⋂ x ∈ (∅ : set α), u x) = univ := infi_emptyset theorem bInter_univ (u : α → set β) : (⋂ x ∈ @univ α, u x) = ⋂ x, u x := infi_univ @[simp] lemma bUnion_self (s : set α) : (⋃ x ∈ s, s) = s := subset.antisymm (Union₂_subset $ λ x hx, subset.refl s) (λ x hx, mem_bUnion hx hx) @[simp] lemma Union_nonempty_self (s : set α) : (⋃ h : s.nonempty, s) = s := by rw [Union_nonempty_index, bUnion_self] -- TODO(Jeremy): here is an artifact of the encoding of bounded intersection: -- without dsimp, the next theorem fails to type check, because there is a lambda -- in a type that needs to be contracted. Using simp [eq_of_mem_singleton xa] also works. theorem bInter_singleton (a : α) (s : α → set β) : (⋂ x ∈ ({a} : set α), s x) = s a := infi_singleton theorem bInter_union (s t : set α) (u : α → set β) : (⋂ x ∈ s ∪ t, u x) = (⋂ x ∈ s, u x) ∩ (⋂ x ∈ t, u x) := infi_union theorem bInter_insert (a : α) (s : set α) (t : α → set β) : (⋂ x ∈ insert a s, t x) = t a ∩ (⋂ x ∈ s, t x) := by simp -- TODO(Jeremy): another example of where an annotation is needed theorem bInter_pair (a b : α) (s : α → set β) : (⋂ x ∈ ({a, b} : set α), s x) = s a ∩ s b := by rw [bInter_insert, bInter_singleton] lemma bInter_inter {ι α : Type*} {s : set ι} (hs : s.nonempty) (f : ι → set α) (t : set α) : (⋂ i ∈ s, f i ∩ t) = (⋂ i ∈ s, f i) ∩ t := begin haveI : nonempty s := hs.to_subtype, simp [bInter_eq_Inter, ← Inter_inter] end lemma inter_bInter {ι α : Type*} {s : set ι} (hs : s.nonempty) (f : ι → set α) (t : set α) : (⋂ i ∈ s, t ∩ f i) = t ∩ ⋂ i ∈ s, f i := begin rw [inter_comm, ← bInter_inter hs], simp [inter_comm] end theorem bUnion_empty (s : α → set β) : (⋃ x ∈ (∅ : set α), s x) = ∅ := supr_emptyset theorem bUnion_univ (s : α → set β) : (⋃ x ∈ @univ α, s x) = ⋃ x, s x := supr_univ theorem bUnion_singleton (a : α) (s : α → set β) : (⋃ x ∈ ({a} : set α), s x) = s a := supr_singleton @[simp] theorem bUnion_of_singleton (s : set α) : (⋃ x ∈ s, {x}) = s := ext $ by simp theorem bUnion_union (s t : set α) (u : α → set β) : (⋃ x ∈ s ∪ t, u x) = (⋃ x ∈ s, u x) ∪ (⋃ x ∈ t, u x) := supr_union @[simp] lemma Union_coe_set {α β : Type*} (s : set α) (f : s → set β) : (⋃ i, f i) = ⋃ i ∈ s, f ⟨i, ‹i ∈ s›⟩ := Union_subtype _ _ @[simp] lemma Inter_coe_set {α β : Type*} (s : set α) (f : s → set β) : (⋂ i, f i) = ⋂ i ∈ s, f ⟨i, ‹i ∈ s›⟩ := Inter_subtype _ _ theorem bUnion_insert (a : α) (s : set α) (t : α → set β) : (⋃ x ∈ insert a s, t x) = t a ∪ (⋃ x ∈ s, t x) := by simp theorem bUnion_pair (a b : α) (s : α → set β) : (⋃ x ∈ ({a, b} : set α), s x) = s a ∪ s b := by simp lemma inter_Union₂ (s : set α) (t : Π i, κ i → set α) : s ∩ (⋃ i j, t i j) = ⋃ i j, s ∩ t i j := by simp only [inter_Union] lemma Union₂_inter (s : Π i, κ i → set α) (t : set α) : (⋃ i j, s i j) ∩ t = ⋃ i j, s i j ∩ t := by simp_rw Union_inter lemma union_Inter₂ (s : set α) (t : Π i, κ i → set α) : s ∪ (⋂ i j, t i j) = ⋂ i j, s ∪ t i j := by simp_rw union_Inter lemma Inter₂_union (s : Π i, κ i → set α) (t : set α) : (⋂ i j, s i j) ∪ t = ⋂ i j, s i j ∪ t := by simp_rw Inter_union theorem mem_sUnion_of_mem {x : α} {t : set α} {S : set (set α)} (hx : x ∈ t) (ht : t ∈ S) : x ∈ ⋃₀ S := ⟨t, ht, hx⟩ -- is this theorem really necessary? theorem not_mem_of_not_mem_sUnion {x : α} {t : set α} {S : set (set α)} (hx : x ∉ ⋃₀ S) (ht : t ∈ S) : x ∉ t := λ h, hx ⟨t, ht, h⟩ theorem sInter_subset_of_mem {S : set (set α)} {t : set α} (tS : t ∈ S) : ⋂₀ S ⊆ t := Inf_le tS theorem subset_sUnion_of_mem {S : set (set α)} {t : set α} (tS : t ∈ S) : t ⊆ ⋃₀ S := le_Sup tS lemma subset_sUnion_of_subset {s : set α} (t : set (set α)) (u : set α) (h₁ : s ⊆ u) (h₂ : u ∈ t) : s ⊆ ⋃₀ t := subset.trans h₁ (subset_sUnion_of_mem h₂) theorem sUnion_subset {S : set (set α)} {t : set α} (h : ∀ t' ∈ S, t' ⊆ t) : (⋃₀ S) ⊆ t := Sup_le h @[simp] theorem sUnion_subset_iff {s : set (set α)} {t : set α} : ⋃₀ s ⊆ t ↔ ∀ t' ∈ s, t' ⊆ t := @Sup_le_iff (set α) _ _ _ theorem subset_sInter {S : set (set α)} {t : set α} (h : ∀ t' ∈ S, t ⊆ t') : t ⊆ (⋂₀ S) := le_Inf h @[simp] theorem subset_sInter_iff {S : set (set α)} {t : set α} : t ⊆ (⋂₀ S) ↔ ∀ t' ∈ S, t ⊆ t' := @le_Inf_iff (set α) _ _ _ theorem sUnion_subset_sUnion {S T : set (set α)} (h : S ⊆ T) : ⋃₀ S ⊆ ⋃₀ T := sUnion_subset $ λ s hs, subset_sUnion_of_mem (h hs) theorem sInter_subset_sInter {S T : set (set α)} (h : S ⊆ T) : ⋂₀ T ⊆ ⋂₀ S := subset_sInter $ λ s hs, sInter_subset_of_mem (h hs) @[simp] theorem sUnion_empty : ⋃₀ ∅ = (∅ : set α) := Sup_empty @[simp] theorem sInter_empty : ⋂₀ ∅ = (univ : set α) := Inf_empty @[simp] theorem sUnion_singleton (s : set α) : ⋃₀ {s} = s := Sup_singleton @[simp] theorem sInter_singleton (s : set α) : ⋂₀ {s} = s := Inf_singleton @[simp] theorem sUnion_eq_empty {S : set (set α)} : (⋃₀ S) = ∅ ↔ ∀ s ∈ S, s = ∅ := Sup_eq_bot @[simp] theorem sInter_eq_univ {S : set (set α)} : (⋂₀ S) = univ ↔ ∀ s ∈ S, s = univ := Inf_eq_top @[simp] theorem nonempty_sUnion {S : set (set α)} : (⋃₀ S).nonempty ↔ ∃ s ∈ S, set.nonempty s := by simp [← ne_empty_iff_nonempty] lemma nonempty.of_sUnion {s : set (set α)} (h : (⋃₀ s).nonempty) : s.nonempty := let ⟨s, hs, _⟩ := nonempty_sUnion.1 h in ⟨s, hs⟩ lemma nonempty.of_sUnion_eq_univ [nonempty α] {s : set (set α)} (h : ⋃₀ s = univ) : s.nonempty := nonempty.of_sUnion $ h.symm ▸ univ_nonempty theorem sUnion_union (S T : set (set α)) : ⋃₀ (S ∪ T) = ⋃₀ S ∪ ⋃₀ T := Sup_union theorem sInter_union (S T : set (set α)) : ⋂₀ (S ∪ T) = ⋂₀ S ∩ ⋂₀ T := Inf_union @[simp] theorem sUnion_insert (s : set α) (T : set (set α)) : ⋃₀ (insert s T) = s ∪ ⋃₀ T := Sup_insert @[simp] theorem sInter_insert (s : set α) (T : set (set α)) : ⋂₀ (insert s T) = s ∩ ⋂₀ T := Inf_insert @[simp] lemma sUnion_diff_singleton_empty (s : set (set α)) : ⋃₀ (s \ {∅}) = ⋃₀ s := Sup_diff_singleton_bot s @[simp] lemma sInter_diff_singleton_univ (s : set (set α)) : ⋂₀ (s \ {univ}) = ⋂₀ s := Inf_diff_singleton_top s theorem sUnion_pair (s t : set α) : ⋃₀ {s, t} = s ∪ t := Sup_pair theorem sInter_pair (s t : set α) : ⋂₀ {s, t} = s ∩ t := Inf_pair @[simp] theorem sUnion_image (f : α → set β) (s : set α) : ⋃₀ (f '' s) = ⋃ x ∈ s, f x := Sup_image @[simp] theorem sInter_image (f : α → set β) (s : set α) : ⋂₀ (f '' s) = ⋂ x ∈ s, f x := Inf_image @[simp] theorem sUnion_range (f : ι → set β) : ⋃₀ (range f) = ⋃ x, f x := rfl @[simp] theorem sInter_range (f : ι → set β) : ⋂₀ (range f) = ⋂ x, f x := rfl lemma Union_eq_univ_iff {f : ι → set α} : (⋃ i, f i) = univ ↔ ∀ x, ∃ i, x ∈ f i := by simp only [eq_univ_iff_forall, mem_Union] lemma Union₂_eq_univ_iff {s : Π i, κ i → set α} : (⋃ i j, s i j) = univ ↔ ∀ a, ∃ i j, a ∈ s i j := by simp only [Union_eq_univ_iff, mem_Union] lemma sUnion_eq_univ_iff {c : set (set α)} : ⋃₀ c = univ ↔ ∀ a, ∃ b ∈ c, a ∈ b := by simp only [eq_univ_iff_forall, mem_sUnion] -- classical lemma Inter_eq_empty_iff {f : ι → set α} : (⋂ i, f i) = ∅ ↔ ∀ x, ∃ i, x ∉ f i := by simp [set.eq_empty_iff_forall_not_mem] -- classical lemma Inter₂_eq_empty_iff {s : Π i, κ i → set α} : (⋂ i j, s i j) = ∅ ↔ ∀ a, ∃ i j, a ∉ s i j := by simp only [eq_empty_iff_forall_not_mem, mem_Inter, not_forall] -- classical lemma sInter_eq_empty_iff {c : set (set α)} : ⋂₀ c = ∅ ↔ ∀ a, ∃ b ∈ c, a ∉ b := by simp [set.eq_empty_iff_forall_not_mem] -- classical @[simp] theorem nonempty_Inter {f : ι → set α} : (⋂ i, f i).nonempty ↔ ∃ x, ∀ i, x ∈ f i := by simp [← ne_empty_iff_nonempty, Inter_eq_empty_iff] -- classical @[simp] lemma nonempty_Inter₂ {s : Π i, κ i → set α} : (⋂ i j, s i j).nonempty ↔ ∃ a, ∀ i j, a ∈ s i j := by simp [← ne_empty_iff_nonempty, Inter_eq_empty_iff] -- classical @[simp] theorem nonempty_sInter {c : set (set α)}: (⋂₀ c).nonempty ↔ ∃ a, ∀ b ∈ c, a ∈ b := by simp [← ne_empty_iff_nonempty, sInter_eq_empty_iff] -- classical theorem compl_sUnion (S : set (set α)) : (⋃₀ S)ᶜ = ⋂₀ (compl '' S) := ext $ λ x, by simp -- classical theorem sUnion_eq_compl_sInter_compl (S : set (set α)) : ⋃₀ S = (⋂₀ (compl '' S))ᶜ := by rw [←compl_compl (⋃₀ S), compl_sUnion] -- classical theorem compl_sInter (S : set (set α)) : (⋂₀ S)ᶜ = ⋃₀ (compl '' S) := by rw [sUnion_eq_compl_sInter_compl, compl_compl_image] -- classical theorem sInter_eq_compl_sUnion_compl (S : set (set α)) : ⋂₀ S = (⋃₀ (compl '' S))ᶜ := by rw [←compl_compl (⋂₀ S), compl_sInter] theorem inter_empty_of_inter_sUnion_empty {s t : set α} {S : set (set α)} (hs : t ∈ S) (h : s ∩ ⋃₀ S = ∅) : s ∩ t = ∅ := eq_empty_of_subset_empty $ by rw ← h; exact inter_subset_inter_right _ (subset_sUnion_of_mem hs) theorem range_sigma_eq_Union_range {γ : α → Type*} (f : sigma γ → β) : range f = ⋃ a, range (λ b, f ⟨a, b⟩) := set.ext $ by simp theorem Union_eq_range_sigma (s : α → set β) : (⋃ i, s i) = range (λ a : Σ i, s i, a.2) := by simp [set.ext_iff] theorem Union_eq_range_psigma (s : ι → set β) : (⋃ i, s i) = range (λ a : Σ' i, s i, a.2) := by simp [set.ext_iff] theorem Union_image_preimage_sigma_mk_eq_self {ι : Type*} {σ : ι → Type*} (s : set (sigma σ)) : (⋃ i, sigma.mk i '' (sigma.mk i ⁻¹' s)) = s := begin ext x, simp only [mem_Union, mem_image, mem_preimage], split, { rintro ⟨i, a, h, rfl⟩, exact h }, { intro h, cases x with i a, exact ⟨i, a, h, rfl⟩ } end lemma sigma.univ (X : α → Type*) : (set.univ : set (Σ a, X a)) = ⋃ a, range (sigma.mk a) := set.ext $ λ x, iff_of_true trivial ⟨range (sigma.mk x.1), set.mem_range_self _, x.2, sigma.eta x⟩ lemma sUnion_mono {s t : set (set α)} (h : s ⊆ t) : (⋃₀ s) ⊆ (⋃₀ t) := sUnion_subset $ λ t' ht', subset_sUnion_of_mem $ h ht' lemma Union_subset_Union_const {s : set α} (h : ι → ι₂) : (⋃ i : ι, s) ⊆ (⋃ j : ι₂, s) := @supr_const_mono (set α) ι ι₂ _ s h @[simp] lemma Union_singleton_eq_range {α β : Type*} (f : α → β) : (⋃ (x : α), {f x}) = range f := by { ext x, simp [@eq_comm _ x] } lemma Union_of_singleton (α : Type*) : (⋃ x, {x} : set α) = univ := by simp lemma Union_of_singleton_coe (s : set α) : (⋃ (i : s), {i} : set α) = s := by simp lemma sUnion_eq_bUnion {s : set (set α)} : (⋃₀ s) = (⋃ (i : set α) (h : i ∈ s), i) := by rw [← sUnion_image, image_id'] lemma sInter_eq_bInter {s : set (set α)} : (⋂₀ s) = (⋂ (i : set α) (h : i ∈ s), i) := by rw [← sInter_image, image_id'] lemma sUnion_eq_Union {s : set (set α)} : (⋃₀ s) = (⋃ (i : s), i) := by simp only [←sUnion_range, subtype.range_coe] lemma sInter_eq_Inter {s : set (set α)} : (⋂₀ s) = (⋂ (i : s), i) := by simp only [←sInter_range, subtype.range_coe] @[simp] lemma Union_of_empty [is_empty ι] (s : ι → set α) : (⋃ i, s i) = ∅ := supr_of_empty _ @[simp] lemma Inter_of_empty [is_empty ι] (s : ι → set α) : (⋂ i, s i) = univ := infi_of_empty _ lemma union_eq_Union {s₁ s₂ : set α} : s₁ ∪ s₂ = ⋃ b : bool, cond b s₁ s₂ := sup_eq_supr s₁ s₂ lemma inter_eq_Inter {s₁ s₂ : set α} : s₁ ∩ s₂ = ⋂ b : bool, cond b s₁ s₂ := inf_eq_infi s₁ s₂ lemma sInter_union_sInter {S T : set (set α)} : (⋂₀ S) ∪ (⋂₀ T) = (⋂ p ∈ S ×ˢ T, (p : (set α) × (set α)).1 ∪ p.2) := Inf_sup_Inf lemma sUnion_inter_sUnion {s t : set (set α)} : (⋃₀ s) ∩ (⋃₀ t) = (⋃ p ∈ s ×ˢ t, (p : (set α) × (set α )).1 ∩ p.2) := Sup_inf_Sup lemma bUnion_Union (s : ι → set α) (t : α → set β) : (⋃ x ∈ ⋃ i, s i, t x) = ⋃ i (x ∈ s i), t x := by simp [@Union_comm _ ι] lemma bInter_Union (s : ι → set α) (t : α → set β) : (⋂ x ∈ ⋃ i, s i, t x) = ⋂ i (x ∈ s i), t x := by simp [@Inter_comm _ ι] lemma sUnion_Union (s : ι → set (set α)) : ⋃₀ (⋃ i, s i) = ⋃ i, ⋃₀ (s i) := by simp only [sUnion_eq_bUnion, bUnion_Union] theorem sInter_Union (s : ι → set (set α)) : ⋂₀ (⋃ i, s i) = ⋂ i, ⋂₀ s i := by simp only [sInter_eq_bInter, bInter_Union] lemma Union_range_eq_sUnion {α β : Type*} (C : set (set α)) {f : ∀ (s : C), β → s} (hf : ∀ (s : C), surjective (f s)) : (⋃ (y : β), range (λ (s : C), (f s y).val)) = ⋃₀ C := begin ext x, split, { rintro ⟨s, ⟨y, rfl⟩, ⟨s, hs⟩, rfl⟩, refine ⟨_, hs, _⟩, exact (f ⟨s, hs⟩ y).2 }, { rintro ⟨s, hs, hx⟩, cases hf ⟨s, hs⟩ ⟨x, hx⟩ with y hy, refine ⟨_, ⟨y, rfl⟩, ⟨s, hs⟩, _⟩, exact congr_arg subtype.val hy } end lemma Union_range_eq_Union (C : ι → set α) {f : ∀ (x : ι), β → C x} (hf : ∀ (x : ι), surjective (f x)) : (⋃ (y : β), range (λ (x : ι), (f x y).val)) = ⋃ x, C x := begin ext x, rw [mem_Union, mem_Union], split, { rintro ⟨y, i, rfl⟩, exact ⟨i, (f i y).2⟩ }, { rintro ⟨i, hx⟩, cases hf i ⟨x, hx⟩ with y hy, exact ⟨y, i, congr_arg subtype.val hy⟩ } end lemma union_distrib_Inter_left (s : ι → set α) (t : set α) : t ∪ (⋂ i, s i) = (⋂ i, t ∪ s i) := sup_infi_eq _ _ lemma union_distrib_Inter₂_left (s : set α) (t : Π i, κ i → set α) : s ∪ (⋂ i j, t i j) = ⋂ i j, s ∪ t i j := by simp_rw union_distrib_Inter_left lemma union_distrib_Inter_right (s : ι → set α) (t : set α) : (⋂ i, s i) ∪ t = (⋂ i, s i ∪ t) := infi_sup_eq _ _ lemma union_distrib_Inter₂_right (s : Π i, κ i → set α) (t : set α) : (⋂ i j, s i j) ∪ t = ⋂ i j, s i j ∪ t := by simp_rw union_distrib_Inter_right section function /-! ### `maps_to` -/ lemma maps_to_sUnion {S : set (set α)} {t : set β} {f : α → β} (H : ∀ s ∈ S, maps_to f s t) : maps_to f (⋃₀ S) t := λ x ⟨s, hs, hx⟩, H s hs hx lemma maps_to_Union {s : ι → set α} {t : set β} {f : α → β} (H : ∀ i, maps_to f (s i) t) : maps_to f (⋃ i, s i) t := maps_to_sUnion $ forall_range_iff.2 H lemma maps_to_Union₂ {s : Π i, κ i → set α} {t : set β} {f : α → β} (H : ∀ i j, maps_to f (s i j) t) : maps_to f (⋃ i j, s i j) t := maps_to_Union $ λ i, maps_to_Union (H i) lemma maps_to_Union_Union {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, maps_to f (s i) (t i)) : maps_to f (⋃ i, s i) (⋃ i, t i) := maps_to_Union $ λ i, (H i).mono (subset.refl _) (subset_Union t i) lemma maps_to_Union₂_Union₂ {s : Π i, κ i → set α} {t : Π i, κ i → set β} {f : α → β} (H : ∀ i j, maps_to f (s i j) (t i j)) : maps_to f (⋃ i j, s i j) (⋃ i j, t i j) := maps_to_Union_Union $ λ i, maps_to_Union_Union (H i) lemma maps_to_sInter {s : set α} {T : set (set β)} {f : α → β} (H : ∀ t ∈ T, maps_to f s t) : maps_to f s (⋂₀ T) := λ x hx t ht, H t ht hx lemma maps_to_Inter {s : set α} {t : ι → set β} {f : α → β} (H : ∀ i, maps_to f s (t i)) : maps_to f s (⋂ i, t i) := λ x hx, mem_Inter.2 $ λ i, H i hx lemma maps_to_Inter₂ {s : set α} {t : Π i, κ i → set β} {f : α → β} (H : ∀ i j, maps_to f s (t i j)) : maps_to f s (⋂ i j, t i j) := maps_to_Inter $ λ i, maps_to_Inter (H i) lemma maps_to_Inter_Inter {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, maps_to f (s i) (t i)) : maps_to f (⋂ i, s i) (⋂ i, t i) := maps_to_Inter $ λ i, (H i).mono (Inter_subset s i) (subset.refl _) lemma maps_to_Inter₂_Inter₂ {s : Π i, κ i → set α} {t : Π i, κ i → set β} {f : α → β} (H : ∀ i j, maps_to f (s i j) (t i j)) : maps_to f (⋂ i j, s i j) (⋂ i j, t i j) := maps_to_Inter_Inter $ λ i, maps_to_Inter_Inter (H i) lemma image_Inter_subset (s : ι → set α) (f : α → β) : f '' (⋂ i, s i) ⊆ ⋂ i, f '' (s i) := (maps_to_Inter_Inter $ λ i, maps_to_image f (s i)).image_subset lemma image_Inter₂_subset (s : Π i, κ i → set α) (f : α → β) : f '' (⋂ i j, s i j) ⊆ ⋂ i j, f '' s i j := (maps_to_Inter₂_Inter₂ $ λ i hi, maps_to_image f (s i hi)).image_subset lemma image_sInter_subset (S : set (set α)) (f : α → β) : f '' (⋂₀ S) ⊆ ⋂ s ∈ S, f '' s := by { rw sInter_eq_bInter, apply image_Inter₂_subset } /-! ### `restrict_preimage` -/ section open function variables (s : set β) {f : α → β} {U : ι → set β} (hU : Union U = univ) lemma restrict_preimage_injective (hf : injective f) : injective (s.restrict_preimage f) := λ x y e, subtype.mk.inj_arrow e (λ e, subtype.coe_injective (hf e)) lemma restrict_preimage_surjective (hf : surjective f) : surjective (s.restrict_preimage f) := λ x, ⟨⟨_, (show f (hf x).some ∈ s, from (hf x).some_spec.symm ▸ x.2)⟩, subtype.ext (hf x).some_spec⟩ lemma restrict_preimage_bijective (hf : bijective f) : bijective (s.restrict_preimage f) := ⟨s.restrict_preimage_injective hf.1, s.restrict_preimage_surjective hf.2⟩ alias set.restrict_preimage_injective ← _root_.function.injective.restrict_preimage alias set.restrict_preimage_surjective ← _root_.function.surjective.restrict_preimage alias set.restrict_preimage_bijective ← _root_.function.bijective.restrict_preimage include hU lemma injective_iff_injective_of_Union_eq_univ : injective f ↔ ∀ i, injective ((U i).restrict_preimage f) := begin refine ⟨λ H i, (U i).restrict_preimage_injective H, λ H x y e, _⟩, obtain ⟨i, hi⟩ := set.mem_Union.mp (show f x ∈ set.Union U, by { rw hU, triv }), injection @H i ⟨x, hi⟩ ⟨y, show f y ∈ U i, from e ▸ hi⟩ (subtype.ext e) end lemma surjective_iff_surjective_of_Union_eq_univ : surjective f ↔ ∀ i, surjective ((U i).restrict_preimage f) := begin refine ⟨λ H i, (U i).restrict_preimage_surjective H, λ H x, _⟩, obtain ⟨i, hi⟩ := set.mem_Union.mp (show x ∈ set.Union U, by { rw hU, triv }), exact ⟨_, congr_arg subtype.val (H i ⟨x, hi⟩).some_spec⟩ end lemma bijective_iff_bijective_of_Union_eq_univ : bijective f ↔ ∀ i, bijective ((U i).restrict_preimage f) := by simp_rw [bijective, forall_and_distrib, injective_iff_injective_of_Union_eq_univ hU, surjective_iff_surjective_of_Union_eq_univ hU] end /-! ### `inj_on` -/ lemma inj_on.image_inter {f : α → β} {s t u : set α} (hf : inj_on f u) (hs : s ⊆ u) (ht : t ⊆ u) : f '' (s ∩ t) = f '' s ∩ f '' t := begin apply subset.antisymm (image_inter_subset _ _ _), rintros x ⟨⟨y, ys, hy⟩, ⟨z, zt, hz⟩⟩, have : y = z, { apply hf (hs ys) (ht zt), rwa ← hz at hy }, rw ← this at zt, exact ⟨y, ⟨ys, zt⟩, hy⟩, end lemma inj_on.image_Inter_eq [nonempty ι] {s : ι → set α} {f : α → β} (h : inj_on f (⋃ i, s i)) : f '' (⋂ i, s i) = ⋂ i, f '' (s i) := begin inhabit ι, refine subset.antisymm (image_Inter_subset s f) (λ y hy, _), simp only [mem_Inter, mem_image_iff_bex] at hy, choose x hx hy using hy, refine ⟨x default, mem_Inter.2 $ λ i, _, hy _⟩, suffices : x default = x i, { rw this, apply hx }, replace hx : ∀ i, x i ∈ ⋃ j, s j := λ i, (subset_Union _ _) (hx i), apply h (hx _) (hx _), simp only [hy] end lemma inj_on.image_bInter_eq {p : ι → Prop} {s : Π i (hi : p i), set α} (hp : ∃ i, p i) {f : α → β} (h : inj_on f (⋃ i hi, s i hi)) : f '' (⋂ i hi, s i hi) = ⋂ i hi, f '' (s i hi) := begin simp only [Inter, infi_subtype'], haveI : nonempty {i // p i} := nonempty_subtype.2 hp, apply inj_on.image_Inter_eq, simpa only [Union, supr_subtype'] using h end lemma image_Inter {f : α → β} (hf : bijective f) (s : ι → set α) : f '' (⋂ i, s i) = ⋂ i, f '' s i := begin casesI is_empty_or_nonempty ι, { simp_rw [Inter_of_empty, image_univ_of_surjective hf.surjective] }, { exact (hf.injective.inj_on _).image_Inter_eq } end lemma image_Inter₂ {f : α → β} (hf : bijective f) (s : Π i, κ i → set α) : f '' (⋂ i j, s i j) = ⋂ i j, f '' s i j := by simp_rw image_Inter hf lemma inj_on_Union_of_directed {s : ι → set α} (hs : directed (⊆) s) {f : α → β} (hf : ∀ i, inj_on f (s i)) : inj_on f (⋃ i, s i) := begin intros x hx y hy hxy, rcases mem_Union.1 hx with ⟨i, hx⟩, rcases mem_Union.1 hy with ⟨j, hy⟩, rcases hs i j with ⟨k, hi, hj⟩, exact hf k (hi hx) (hj hy) hxy end /-! ### `surj_on` -/ lemma surj_on_sUnion {s : set α} {T : set (set β)} {f : α → β} (H : ∀ t ∈ T, surj_on f s t) : surj_on f s (⋃₀ T) := λ x ⟨t, ht, hx⟩, H t ht hx lemma surj_on_Union {s : set α} {t : ι → set β} {f : α → β} (H : ∀ i, surj_on f s (t i)) : surj_on f s (⋃ i, t i) := surj_on_sUnion $ forall_range_iff.2 H lemma surj_on_Union_Union {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, surj_on f (s i) (t i)) : surj_on f (⋃ i, s i) (⋃ i, t i) := surj_on_Union $ λ i, (H i).mono (subset_Union _ _) (subset.refl _) lemma surj_on_Union₂ {s : set α} {t : Π i, κ i → set β} {f : α → β} (H : ∀ i j, surj_on f s (t i j)) : surj_on f s (⋃ i j, t i j) := surj_on_Union $ λ i, surj_on_Union (H i) lemma surj_on_Union₂_Union₂ {s : Π i, κ i → set α} {t : Π i, κ i → set β} {f : α → β} (H : ∀ i j, surj_on f (s i j) (t i j)) : surj_on f (⋃ i j, s i j) (⋃ i j, t i j) := surj_on_Union_Union $ λ i, surj_on_Union_Union (H i) lemma surj_on_Inter [hi : nonempty ι] {s : ι → set α} {t : set β} {f : α → β} (H : ∀ i, surj_on f (s i) t) (Hinj : inj_on f (⋃ i, s i)) : surj_on f (⋂ i, s i) t := begin intros y hy, rw [Hinj.image_Inter_eq, mem_Inter], exact λ i, H i hy end lemma surj_on_Inter_Inter [hi : nonempty ι] {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, surj_on f (s i) (t i)) (Hinj : inj_on f (⋃ i, s i)) : surj_on f (⋂ i, s i) (⋂ i, t i) := surj_on_Inter (λ i, (H i).mono (subset.refl _) (Inter_subset _ _)) Hinj /-! ### `bij_on` -/ lemma bij_on_Union {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, bij_on f (s i) (t i)) (Hinj : inj_on f (⋃ i, s i)) : bij_on f (⋃ i, s i) (⋃ i, t i) := ⟨maps_to_Union_Union $ λ i, (H i).maps_to, Hinj, surj_on_Union_Union $ λ i, (H i).surj_on⟩ lemma bij_on_Inter [hi :nonempty ι] {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, bij_on f (s i) (t i)) (Hinj : inj_on f (⋃ i, s i)) : bij_on f (⋂ i, s i) (⋂ i, t i) := ⟨maps_to_Inter_Inter $ λ i, (H i).maps_to, hi.elim $ λ i, (H i).inj_on.mono (Inter_subset _ _), surj_on_Inter_Inter (λ i, (H i).surj_on) Hinj⟩ lemma bij_on_Union_of_directed {s : ι → set α} (hs : directed (⊆) s) {t : ι → set β} {f : α → β} (H : ∀ i, bij_on f (s i) (t i)) : bij_on f (⋃ i, s i) (⋃ i, t i) := bij_on_Union H $ inj_on_Union_of_directed hs (λ i, (H i).inj_on) lemma bij_on_Inter_of_directed [nonempty ι] {s : ι → set α} (hs : directed (⊆) s) {t : ι → set β} {f : α → β} (H : ∀ i, bij_on f (s i) (t i)) : bij_on f (⋂ i, s i) (⋂ i, t i) := bij_on_Inter H $ inj_on_Union_of_directed hs (λ i, (H i).inj_on) end function /-! ### `image`, `preimage` -/ section image lemma image_Union {f : α → β} {s : ι → set α} : f '' (⋃ i, s i) = (⋃ i, f '' s i) := begin ext1 x, simp [image, ← exists_and_distrib_right, @exists_swap α] end lemma image_Union₂ (f : α → β) (s : Π i, κ i → set α) : f '' (⋃ i j, s i j) = ⋃ i j, f '' s i j := by simp_rw image_Union lemma univ_subtype {p : α → Prop} : (univ : set (subtype p)) = (⋃ x (h : p x), {⟨x, h⟩}) := set.ext $ λ ⟨x, h⟩, by simp [h] lemma range_eq_Union {ι} (f : ι → α) : range f = (⋃ i, {f i}) := set.ext $ λ a, by simp [@eq_comm α a] lemma image_eq_Union (f : α → β) (s : set α) : f '' s = (⋃ i ∈ s, {f i}) := set.ext $ λ b, by simp [@eq_comm β b] lemma bUnion_range {f : ι → α} {g : α → set β} : (⋃ x ∈ range f, g x) = (⋃ y, g (f y)) := supr_range @[simp] lemma Union_Union_eq' {f : ι → α} {g : α → set β} : (⋃ x y (h : f y = x), g x) = ⋃ y, g (f y) := by simpa using bUnion_range lemma bInter_range {f : ι → α} {g : α → set β} : (⋂ x ∈ range f, g x) = (⋂ y, g (f y)) := infi_range @[simp] lemma Inter_Inter_eq' {f : ι → α} {g : α → set β} : (⋂ x y (h : f y = x), g x) = ⋂ y, g (f y) := by simpa using bInter_range variables {s : set γ} {f : γ → α} {g : α → set β} lemma bUnion_image : (⋃ x ∈ f '' s, g x) = (⋃ y ∈ s, g (f y)) := supr_image lemma bInter_image : (⋂ x ∈ f '' s, g x) = (⋂ y ∈ s, g (f y)) := infi_image end image section preimage theorem monotone_preimage {f : α → β} : monotone (preimage f) := λ a b h, preimage_mono h @[simp] lemma preimage_Union {f : α → β} {s : ι → set β} : f ⁻¹' (⋃ i, s i) = (⋃ i, f ⁻¹' s i) := set.ext $ by simp [preimage] lemma preimage_Union₂ {f : α → β} {s : Π i, κ i → set β} : f ⁻¹' (⋃ i j, s i j) = ⋃ i j, f ⁻¹' s i j := by simp_rw preimage_Union @[simp] theorem preimage_sUnion {f : α → β} {s : set (set β)} : f ⁻¹' (⋃₀ s) = (⋃ t ∈ s, f ⁻¹' t) := by rw [sUnion_eq_bUnion, preimage_Union₂] lemma preimage_Inter {f : α → β} {s : ι → set β} : f ⁻¹' (⋂ i, s i) = (⋂ i, f ⁻¹' s i) := by ext; simp lemma preimage_Inter₂ {f : α → β} {s : Π i, κ i → set β} : f ⁻¹' (⋂ i j, s i j) = ⋂ i j, f ⁻¹' s i j := by simp_rw preimage_Inter @[simp] lemma preimage_sInter {f : α → β} {s : set (set β)} : f ⁻¹' (⋂₀ s) = ⋂ t ∈ s, f ⁻¹' t := by rw [sInter_eq_bInter, preimage_Inter₂] @[simp] lemma bUnion_preimage_singleton (f : α → β) (s : set β) : (⋃ y ∈ s, f ⁻¹' {y}) = f ⁻¹' s := by rw [← preimage_Union₂, bUnion_of_singleton] lemma bUnion_range_preimage_singleton (f : α → β) : (⋃ y ∈ range f, f ⁻¹' {y}) = univ := by rw [bUnion_preimage_singleton, preimage_range] end preimage section prod lemma prod_Union {s : set α} {t : ι → set β} : s ×ˢ (⋃ i, t i) = ⋃ i, s ×ˢ (t i) := by { ext, simp } lemma prod_Union₂ {s : set α} {t : Π i, κ i → set β} : s ×ˢ (⋃ i j, t i j) = ⋃ i j, s ×ˢ t i j := by simp_rw [prod_Union] lemma prod_sUnion {s : set α} {C : set (set β)} : s ×ˢ (⋃₀ C) = ⋃₀ ((λ t, s ×ˢ t) '' C) := by simp_rw [sUnion_eq_bUnion, bUnion_image, prod_Union₂] lemma Union_prod_const {s : ι → set α} {t : set β} : (⋃ i, s i) ×ˢ t = ⋃ i, s i ×ˢ t := by { ext, simp } lemma Union₂_prod_const {s : Π i, κ i → set α} {t : set β} : (⋃ i j, s i j) ×ˢ t = ⋃ i j, s i j ×ˢ t := by simp_rw [Union_prod_const] lemma sUnion_prod_const {C : set (set α)} {t : set β} : (⋃₀ C) ×ˢ t = ⋃₀ ((λ s : set α, s ×ˢ t) '' C) := by simp only [sUnion_eq_bUnion, Union₂_prod_const, bUnion_image] lemma Union_prod {ι ι' α β} (s : ι → set α) (t : ι' → set β) : (⋃ (x : ι × ι'), s x.1 ×ˢ t x.2) = (⋃ (i : ι), s i) ×ˢ (⋃ (i : ι'), t i) := by { ext, simp } lemma Union_prod_of_monotone [semilattice_sup α] {s : α → set β} {t : α → set γ} (hs : monotone s) (ht : monotone t) : (⋃ x, s x ×ˢ t x) = (⋃ x, s x) ×ˢ (⋃ x, t x) := begin ext ⟨z, w⟩, simp only [mem_prod, mem_Union, exists_imp_distrib, and_imp, iff_def], split, { intros x hz hw, exact ⟨⟨x, hz⟩, x, hw⟩ }, { intros x hz x' hw, exact ⟨x ⊔ x', hs le_sup_left hz, ht le_sup_right hw⟩ } end lemma sInter_prod_sInter_subset (S : set (set α)) (T : set (set β)) : ⋂₀ S ×ˢ ⋂₀ T ⊆ ⋂ r ∈ S ×ˢ T, r.1 ×ˢ r.2 := subset_Inter₂ (λ x hx y hy, ⟨hy.1 x.1 hx.1, hy.2 x.2 hx.2⟩) lemma sInter_prod_sInter {S : set (set α)} {T : set (set β)} (hS : S.nonempty) (hT : T.nonempty) : ⋂₀ S ×ˢ ⋂₀ T = ⋂ r ∈ S ×ˢ T, r.1 ×ˢ r.2 := begin obtain ⟨s₁, h₁⟩ := hS, obtain ⟨s₂, h₂⟩ := hT, refine set.subset.antisymm (sInter_prod_sInter_subset S T) (λ x hx, _), rw mem_Inter₂ at hx, exact ⟨λ s₀ h₀, (hx (s₀, s₂) ⟨h₀, h₂⟩).1, λ s₀ h₀, (hx (s₁, s₀) ⟨h₁, h₀⟩).2⟩, end lemma sInter_prod {S : set (set α)} (hS : S.nonempty) (t : set β) : ⋂₀ S ×ˢ t = ⋂ s ∈ S, s ×ˢ t := begin rw [←sInter_singleton t, sInter_prod_sInter hS (singleton_nonempty t), sInter_singleton], simp_rw [prod_singleton, mem_image, Inter_exists, bInter_and', Inter_Inter_eq_right], end lemma prod_sInter {T : set (set β)} (hT : T.nonempty) (s : set α) : s ×ˢ ⋂₀ T = ⋂ t ∈ T, s ×ˢ t := begin rw [←sInter_singleton s, sInter_prod_sInter (singleton_nonempty s) hT, sInter_singleton], simp_rw [singleton_prod, mem_image, Inter_exists, bInter_and', Inter_Inter_eq_right], end end prod section image2 variables (f : α → β → γ) {s : set α} {t : set β} lemma Union_image_left : (⋃ a ∈ s, f a '' t) = image2 f s t := by { ext y, split; simp only [mem_Union]; rintro ⟨a, ha, x, hx, ax⟩; exact ⟨a, x, ha, hx, ax⟩ } lemma Union_image_right : (⋃ b ∈ t, (λ a, f a b) '' s) = image2 f s t := by { ext y, split; simp only [mem_Union]; rintro ⟨a, b, c, d, e⟩, exact ⟨c, a, d, b, e⟩, exact ⟨b, d, a, c, e⟩ } lemma image2_Union_left (s : ι → set α) (t : set β) : image2 f (⋃ i, s i) t = ⋃ i, image2 f (s i) t := by simp only [← image_prod, Union_prod_const, image_Union] lemma image2_Union_right (s : set α) (t : ι → set β) : image2 f s (⋃ i, t i) = ⋃ i, image2 f s (t i) := by simp only [← image_prod, prod_Union, image_Union] lemma image2_Union₂_left (s : Π i, κ i → set α) (t : set β) : image2 f (⋃ i j, s i j) t = ⋃ i j, image2 f (s i j) t := by simp_rw image2_Union_left lemma image2_Union₂_right (s : set α) (t : Π i, κ i → set β) : image2 f s (⋃ i j, t i j) = ⋃ i j, image2 f s (t i j) := by simp_rw image2_Union_right lemma image2_Inter_subset_left (s : ι → set α) (t : set β) : image2 f (⋂ i, s i) t ⊆ ⋂ i, image2 f (s i) t := by { simp_rw [image2_subset_iff, mem_Inter], exact λ x hx y hy i, mem_image2_of_mem (hx _) hy } lemma image2_Inter_subset_right (s : set α) (t : ι → set β) : image2 f s (⋂ i, t i) ⊆ ⋂ i, image2 f s (t i) := by { simp_rw [image2_subset_iff, mem_Inter], exact λ x hx y hy i, mem_image2_of_mem hx (hy _) } lemma image2_Inter₂_subset_left (s : Π i, κ i → set α) (t : set β) : image2 f (⋂ i j, s i j) t ⊆ ⋂ i j, image2 f (s i j) t := by { simp_rw [image2_subset_iff, mem_Inter], exact λ x hx y hy i j, mem_image2_of_mem (hx _ _) hy } lemma image2_Inter₂_subset_right (s : set α) (t : Π i, κ i → set β) : image2 f s (⋂ i j, t i j) ⊆ ⋂ i j, image2 f s (t i j) := by { simp_rw [image2_subset_iff, mem_Inter], exact λ x hx y hy i j, mem_image2_of_mem hx (hy _ _) } /-- The `set.image2` version of `set.image_eq_Union` -/ lemma image2_eq_Union (s : set α) (t : set β) : image2 f s t = ⋃ (i ∈ s) (j ∈ t), {f i j} := by simp_rw [←image_eq_Union, Union_image_left] lemma prod_eq_bUnion_left : s ×ˢ t = ⋃ a ∈ s, (λ b, (a, b)) '' t := by rw [Union_image_left, image2_mk_eq_prod] lemma prod_eq_bUnion_right : s ×ˢ t = ⋃ b ∈ t, (λ a, (a, b)) '' s := by rw [Union_image_right, image2_mk_eq_prod] end image2 section seq /-- Given a set `s` of functions `α → β` and `t : set α`, `seq s t` is the union of `f '' t` over all `f ∈ s`. -/ def seq (s : set (α → β)) (t : set α) : set β := {b | ∃ f ∈ s, ∃ a ∈ t, (f : α → β) a = b} lemma seq_def {s : set (α → β)} {t : set α} : seq s t = ⋃ f ∈ s, f '' t := set.ext $ by simp [seq] @[simp] lemma mem_seq_iff {s : set (α → β)} {t : set α} {b : β} : b ∈ seq s t ↔ ∃ (f ∈ s) (a ∈ t), (f : α → β) a = b := iff.rfl lemma seq_subset {s : set (α → β)} {t : set α} {u : set β} : seq s t ⊆ u ↔ (∀ f ∈ s, ∀ a ∈ t, (f : α → β) a ∈ u) := iff.intro (λ h f hf a ha, h ⟨f, hf, a, ha, rfl⟩) (λ h b ⟨f, hf, a, ha, eq⟩, eq ▸ h f hf a ha) lemma seq_mono {s₀ s₁ : set (α → β)} {t₀ t₁ : set α} (hs : s₀ ⊆ s₁) (ht : t₀ ⊆ t₁) : seq s₀ t₀ ⊆ seq s₁ t₁ := λ b ⟨f, hf, a, ha, eq⟩, ⟨f, hs hf, a, ht ha, eq⟩ lemma singleton_seq {f : α → β} {t : set α} : set.seq {f} t = f '' t := set.ext $ by simp lemma seq_singleton {s : set (α → β)} {a : α} : set.seq s {a} = (λ f : α → β, f a) '' s := set.ext $ by simp lemma seq_seq {s : set (β → γ)} {t : set (α → β)} {u : set α} : seq s (seq t u) = seq (seq ((∘) '' s) t) u := begin refine set.ext (λ c, iff.intro _ _), { rintro ⟨f, hfs, b, ⟨g, hg, a, hau, rfl⟩, rfl⟩, exact ⟨f ∘ g, ⟨(∘) f, mem_image_of_mem _ hfs, g, hg, rfl⟩, a, hau, rfl⟩ }, { rintro ⟨fg, ⟨fc, ⟨f, hfs, rfl⟩, g, hgt, rfl⟩, a, ha, rfl⟩, exact ⟨f, hfs, g a, ⟨g, hgt, a, ha, rfl⟩, rfl⟩ } end lemma image_seq {f : β → γ} {s : set (α → β)} {t : set α} : f '' seq s t = seq ((∘) f '' s) t := by rw [← singleton_seq, ← singleton_seq, seq_seq, image_singleton] lemma prod_eq_seq {s : set α} {t : set β} : s ×ˢ t = (prod.mk '' s).seq t := begin ext ⟨a, b⟩, split, { rintro ⟨ha, hb⟩, exact ⟨prod.mk a, ⟨a, ha, rfl⟩, b, hb, rfl⟩ }, { rintro ⟨f, ⟨x, hx, rfl⟩, y, hy, eq⟩, rw ← eq, exact ⟨hx, hy⟩ } end lemma prod_image_seq_comm (s : set α) (t : set β) : (prod.mk '' s).seq t = seq ((λ b a, (a, b)) '' t) s := by rw [← prod_eq_seq, ← image_swap_prod, prod_eq_seq, image_seq, ← image_comp, prod.swap] lemma image2_eq_seq (f : α → β → γ) (s : set α) (t : set β) : image2 f s t = seq (f '' s) t := by { ext, simp } end seq section pi variables {π : α → Type*} lemma pi_def (i : set α) (s : Π a, set (π a)) : pi i s = (⋂ a ∈ i, eval a ⁻¹' s a) := by { ext, simp } lemma univ_pi_eq_Inter (t : Π i, set (π i)) : pi univ t = ⋂ i, eval i ⁻¹' t i := by simp only [pi_def, Inter_true, mem_univ] lemma pi_diff_pi_subset (i : set α) (s t : Π a, set (π a)) : pi i s \ pi i t ⊆ ⋃ a ∈ i, (eval a ⁻¹' (s a \ t a)) := begin refine diff_subset_comm.2 (λ x hx a ha, _), simp only [mem_diff, mem_pi, mem_Union, not_exists, mem_preimage, not_and, not_not, eval_apply] at hx, exact hx.2 _ ha (hx.1 _ ha) end lemma Union_univ_pi (t : Π i, ι → set (π i)) : (⋃ (x : α → ι), pi univ (λ i, t i (x i))) = pi univ (λ i, ⋃ (j : ι), t i j) := by { ext, simp [classical.skolem] } end pi end set namespace function namespace surjective lemma Union_comp {f : ι → ι₂} (hf : surjective f) (g : ι₂ → set α) : (⋃ x, g (f x)) = ⋃ y, g y := hf.supr_comp g lemma Inter_comp {f : ι → ι₂} (hf : surjective f) (g : ι₂ → set α) : (⋂ x, g (f x)) = ⋂ y, g y := hf.infi_comp g end surjective end function /-! ### Disjoint sets We define some lemmas in the `disjoint` namespace to be able to use projection notation. -/ section disjoint variables {s t u : set α} {f : α → β} namespace disjoint theorem union_left (hs : disjoint s u) (ht : disjoint t u) : disjoint (s ∪ t) u := hs.sup_left ht theorem union_right (ht : disjoint s t) (hu : disjoint s u) : disjoint s (t ∪ u) := ht.sup_right hu lemma inter_left (u : set α) (h : disjoint s t) : disjoint (s ∩ u) t := inf_left _ h lemma inter_left' (u : set α) (h : disjoint s t) : disjoint (u ∩ s) t := inf_left' _ h lemma inter_right (u : set α) (h : disjoint s t) : disjoint s (t ∩ u) := inf_right _ h lemma inter_right' (u : set α) (h : disjoint s t) : disjoint s (u ∩ t) := inf_right' _ h lemma subset_left_of_subset_union (h : s ⊆ t ∪ u) (hac : disjoint s u) : s ⊆ t := hac.left_le_of_le_sup_right h lemma subset_right_of_subset_union (h : s ⊆ t ∪ u) (hab : disjoint s t) : s ⊆ u := hab.left_le_of_le_sup_left h lemma preimage {α β} (f : α → β) {s t : set β} (h : disjoint s t) : disjoint (f ⁻¹' s) (f ⁻¹' t) := disjoint_iff_inf_le.mpr $ λ x hx, h.le_bot hx end disjoint namespace set lemma not_disjoint_iff : ¬disjoint s t ↔ ∃ x, x ∈ s ∧ x ∈ t := set.disjoint_iff.not.trans $ not_forall.trans $ exists_congr $ λ x, not_not lemma not_disjoint_iff_nonempty_inter : ¬disjoint s t ↔ (s ∩ t).nonempty := not_disjoint_iff alias not_disjoint_iff_nonempty_inter ↔ _ nonempty.not_disjoint lemma disjoint_or_nonempty_inter (s t : set α) : disjoint s t ∨ (s ∩ t).nonempty := (em _).imp_right not_disjoint_iff_nonempty_inter.mp lemma disjoint_iff_forall_ne : disjoint s t ↔ ∀ (x ∈ s) (y ∈ t), x ≠ y := by simp only [ne.def, disjoint_left, @imp_not_comm _ (_ = _), forall_eq'] lemma _root_.disjoint.ne_of_mem (h : disjoint s t) {x y} (hx : x ∈ s) (hy : y ∈ t) : x ≠ y := disjoint_iff_forall_ne.mp h x hx y hy theorem disjoint_of_subset_left (h : s ⊆ u) (d : disjoint u t) : disjoint s t := d.mono_left h theorem disjoint_of_subset_right (h : t ⊆ u) (d : disjoint s u) : disjoint s t := d.mono_right h theorem disjoint_of_subset {s t u v : set α} (h1 : s ⊆ u) (h2 : t ⊆ v) (d : disjoint u v) : disjoint s t := d.mono h1 h2 @[simp] theorem disjoint_union_left : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := disjoint_sup_left @[simp] theorem disjoint_union_right : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := disjoint_sup_right @[simp] theorem disjoint_Union_left {ι : Sort*} {s : ι → set α} : disjoint (⋃ i, s i) t ↔ ∀ i, disjoint (s i) t := supr_disjoint_iff @[simp] theorem disjoint_Union_right {ι : Sort*} {s : ι → set α} : disjoint t (⋃ i, s i) ↔ ∀ i, disjoint t (s i) := disjoint_supr_iff @[simp] lemma disjoint_Union₂_left {s : Π i, κ i → set α} {t : set α} : disjoint (⋃ i j, s i j) t ↔ ∀ i j, disjoint (s i j) t := supr₂_disjoint_iff @[simp] lemma disjoint_Union₂_right {s : set α} {t : Π i, κ i → set α} : disjoint s (⋃ i j, t i j) ↔ ∀ i j, disjoint s (t i j) := disjoint_supr₂_iff @[simp] lemma disjoint_sUnion_left {S : set (set α)} {t : set α} : disjoint (⋃₀ S) t ↔ ∀ s ∈ S, disjoint s t := Sup_disjoint_iff @[simp] lemma disjoint_sUnion_right {s : set α} {S : set (set α)} : disjoint s (⋃₀ S) ↔ ∀ t ∈ S, disjoint s t := disjoint_Sup_iff theorem disjoint_diff {a b : set α} : disjoint a (b \ a) := disjoint_iff.2 (inter_diff_self _ _) @[simp] theorem disjoint_empty (s : set α) : disjoint s ∅ := disjoint_bot_right @[simp] theorem empty_disjoint (s : set α) : disjoint ∅ s := disjoint_bot_left @[simp] lemma univ_disjoint {s : set α} : disjoint univ s ↔ s = ∅ := top_disjoint @[simp] lemma disjoint_univ {s : set α} : disjoint s univ ↔ s = ∅ := disjoint_top @[simp] theorem disjoint_singleton_left {a : α} {s : set α} : disjoint {a} s ↔ a ∉ s := by simp [set.disjoint_iff, subset_def]; exact iff.rfl @[simp] theorem disjoint_singleton_right {a : α} {s : set α} : disjoint s {a} ↔ a ∉ s := by rw [disjoint.comm]; exact disjoint_singleton_left @[simp] lemma disjoint_singleton {a b : α} : disjoint ({a} : set α) {b} ↔ a ≠ b := by rw [disjoint_singleton_left, mem_singleton_iff] theorem disjoint_image_image {f : β → α} {g : γ → α} {s : set β} {t : set γ} (h : ∀ b ∈ s, ∀ c ∈ t, f b ≠ g c) : disjoint (f '' s) (g '' t) := disjoint_iff_inf_le.mpr $ by rintro a ⟨⟨b, hb, eq⟩, c, hc, rfl⟩; exact h b hb c hc eq lemma disjoint_image_of_injective {f : α → β} (hf : injective f) {s t : set α} (hd : disjoint s t) : disjoint (f '' s) (f '' t) := disjoint_image_image $ λ x hx y hy, hf.ne $ λ H, set.disjoint_iff.1 hd ⟨hx, H.symm ▸ hy⟩ lemma _root_.disjoint.of_image (h : disjoint (f '' s) (f '' t)) : disjoint s t := disjoint_iff_inf_le.mpr $ λ x hx, disjoint_left.1 h (mem_image_of_mem _ hx.1) (mem_image_of_mem _ hx.2) lemma disjoint_image_iff (hf : injective f) : disjoint (f '' s) (f '' t) ↔ disjoint s t := ⟨disjoint.of_image, disjoint_image_of_injective hf⟩ lemma _root_.disjoint.of_preimage (hf : surjective f) {s t : set β} (h : disjoint (f ⁻¹' s) (f ⁻¹' t)) : disjoint s t := by rw [disjoint_iff_inter_eq_empty, ←image_preimage_eq (_ ∩ _) hf, preimage_inter, h.inter_eq, image_empty] lemma disjoint_preimage_iff (hf : surjective f) {s t : set β} : disjoint (f ⁻¹' s) (f ⁻¹' t) ↔ disjoint s t := ⟨disjoint.of_preimage hf, disjoint.preimage _⟩ lemma preimage_eq_empty {f : α → β} {s : set β} (h : disjoint s (range f)) : f ⁻¹' s = ∅ := by simpa using h.preimage f lemma preimage_eq_empty_iff {s : set β} : f ⁻¹' s = ∅ ↔ disjoint s (range f) := ⟨λ h, begin simp only [eq_empty_iff_forall_not_mem, disjoint_iff_inter_eq_empty, not_exists, mem_inter_iff, not_and, mem_range, mem_preimage] at h ⊢, assume y hy x hx, rw ← hx at hy, exact h x hy, end, preimage_eq_empty⟩ lemma _root_.disjoint.image {s t u : set α} {f : α → β} (h : disjoint s t) (hf : inj_on f u) (hs : s ⊆ u) (ht : t ⊆ u) : disjoint (f '' s) (f '' t) := begin rw disjoint_iff_inter_eq_empty at h ⊢, rw [← hf.image_inter hs ht, h, image_empty], end end set end disjoint /-! ### Intervals -/ namespace set variables [complete_lattice α] lemma Ici_supr (f : ι → α) : Ici (⨆ i, f i) = ⋂ i, Ici (f i) := ext $ λ _, by simp only [mem_Ici, supr_le_iff, mem_Inter] lemma Iic_infi (f : ι → α) : Iic (⨅ i, f i) = ⋂ i, Iic (f i) := ext $ λ _, by simp only [mem_Iic, le_infi_iff, mem_Inter] lemma Ici_supr₂ (f : Π i, κ i → α) : Ici (⨆ i j, f i j) = ⋂ i j, Ici (f i j) := by simp_rw Ici_supr lemma Iic_infi₂ (f : Π i, κ i → α) : Iic (⨅ i j, f i j) = ⋂ i j, Iic (f i j) := by simp_rw Iic_infi lemma Ici_Sup (s : set α) : Ici (Sup s) = ⋂ a ∈ s, Ici a := by rw [Sup_eq_supr, Ici_supr₂] lemma Iic_Inf (s : set α) : Iic (Inf s) = ⋂ a ∈ s, Iic a := by rw [Inf_eq_infi, Iic_infi₂] end set namespace set variables (t : α → set β) lemma subset_diff {s t u : set α} : s ⊆ t \ u ↔ s ⊆ t ∧ disjoint s u := ⟨λ h, ⟨λ x hxs, (h hxs).1, disjoint_iff_inf_le.mpr $ λ x ⟨hxs, hxu⟩, (h hxs).2 hxu⟩, λ ⟨h1, h2⟩ x hxs, ⟨h1 hxs, λ hxu, h2.le_bot ⟨hxs, hxu⟩⟩⟩ lemma bUnion_diff_bUnion_subset (s₁ s₂ : set α) : (⋃ x ∈ s₁, t x) \ (⋃ x ∈ s₂, t x) ⊆ (⋃ x ∈ s₁ \ s₂, t x) := begin simp only [diff_subset_iff, ← bUnion_union], apply bUnion_subset_bUnion_left, rw union_diff_self, apply subset_union_right end /-- If `t` is an indexed family of sets, then there is a natural map from `Σ i, t i` to `⋃ i, t i` sending `⟨i, x⟩` to `x`. -/ def sigma_to_Union (x : Σ i, t i) : (⋃ i, t i) := ⟨x.2, mem_Union.2 ⟨x.1, x.2.2⟩⟩ lemma sigma_to_Union_surjective : surjective (sigma_to_Union t) | ⟨b, hb⟩ := have ∃ a, b ∈ t a, by simpa using hb, let ⟨a, hb⟩ := this in ⟨⟨a, b, hb⟩, rfl⟩ lemma sigma_to_Union_injective (h : ∀ i j, i ≠ j → disjoint (t i) (t j)) : injective (sigma_to_Union t) | ⟨a₁, b₁, h₁⟩ ⟨a₂, b₂, h₂⟩ eq := have b_eq : b₁ = b₂, from congr_arg subtype.val eq, have a_eq : a₁ = a₂, from classical.by_contradiction $ λ ne, have b₁ ∈ t a₁ ∩ t a₂, from ⟨h₁, b_eq.symm ▸ h₂⟩, (h _ _ ne).le_bot this, sigma.eq a_eq $ subtype.eq $ by subst b_eq; subst a_eq lemma sigma_to_Union_bijective (h : ∀ i j, i ≠ j → disjoint (t i) (t j)) : bijective (sigma_to_Union t) := ⟨sigma_to_Union_injective t h, sigma_to_Union_surjective t⟩ /-- Equivalence between a disjoint union and a dependent sum. -/ noncomputable def Union_eq_sigma_of_disjoint {t : α → set β} (h : ∀ i j, i ≠ j → disjoint (t i) (t j)) : (⋃ i, t i) ≃ (Σ i, t i) := (equiv.of_bijective _ $ sigma_to_Union_bijective t h).symm lemma Union_ge_eq_Union_nat_add (u : ℕ → set α) (n : ℕ) : (⋃ i ≥ n, u i) = ⋃ i, u (i + n) := supr_ge_eq_supr_nat_add u n lemma Inter_ge_eq_Inter_nat_add (u : ℕ → set α) (n : ℕ) : (⋂ i ≥ n, u i) = ⋂ i, u (i + n) := infi_ge_eq_infi_nat_add u n lemma _root_.monotone.Union_nat_add {f : ℕ → set α} (hf : monotone f) (k : ℕ) : (⋃ n, f (n + k)) = ⋃ n, f n := hf.supr_nat_add k lemma _root_.antitone.Inter_nat_add {f : ℕ → set α} (hf : antitone f) (k : ℕ) : (⋂ n, f (n + k)) = ⋂ n, f n := hf.infi_nat_add k @[simp] lemma Union_Inter_ge_nat_add (f : ℕ → set α) (k : ℕ) : (⋃ n, ⋂ i ≥ n, f (i + k)) = ⋃ n, ⋂ i ≥ n, f i := supr_infi_ge_nat_add f k lemma union_Union_nat_succ (u : ℕ → set α) : u 0 ∪ (⋃ i, u (i + 1)) = ⋃ i, u i := sup_supr_nat_succ u lemma inter_Inter_nat_succ (u : ℕ → set α) : u 0 ∩ (⋂ i, u (i + 1)) = ⋂ i, u i := inf_infi_nat_succ u end set open set variables [complete_lattice β] lemma supr_Union (s : ι → set α) (f : α → β) : (⨆ a ∈ (⋃ i, s i), f a) = ⨆ i (a ∈ s i), f a := by { rw supr_comm, simp_rw [mem_Union, supr_exists] } lemma infi_Union (s : ι → set α) (f : α → β) : (⨅ a ∈ (⋃ i, s i), f a) = ⨅ i (a ∈ s i), f a := @supr_Union α βᵒᵈ _ _ s f lemma Sup_sUnion (s : set (set β)) : Sup (⋃₀ s) = ⨆ t ∈ s, Sup t := by simp only [sUnion_eq_bUnion, Sup_eq_supr, supr_Union] lemma Inf_sUnion (s : set (set β)) : Inf (⋃₀ s) = ⨅ t ∈ s, Inf t := @Sup_sUnion βᵒᵈ _ _
7e6b0aef1b63028925cbc0687a0ee6591a4497e4
46125763b4dbf50619e8846a1371029346f4c3db
/src/category_theory/natural_transformation.lean
7f773f771703ca1eb069d89fdd991a6932ab06b0
[ "Apache-2.0" ]
permissive
thjread/mathlib
a9d97612cedc2c3101060737233df15abcdb9eb1
7cffe2520a5518bba19227a107078d83fa725ddc
refs/heads/master
1,615,637,696,376
1,583,953,063,000
1,583,953,063,000
246,680,271
0
0
Apache-2.0
1,583,960,875,000
1,583,960,875,000
null
UTF-8
Lean
false
false
2,320
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tim Baumann, Stephen Morgan, Scott Morrison, Floris van Doorn Defines natural transformations between functors. Introduces notations `τ.app X` for the components of natural transformations, `F ⟶ G` for the type of natural transformations between functors `F` and `G`, `σ ≫ τ` for vertical compositions, and `σ ◫ τ` for horizontal compositions. -/ import category_theory.functor namespace category_theory universes v₁ v₂ v₃ v₄ u₁ u₂ u₃ u₄ -- declare the `v`'s first; see `category_theory.category` for an explanation variables {C : Type u₁} [𝒞 : category.{v₁} C] {D : Type u₂} [𝒟 : category.{v₂} D] include 𝒞 𝒟 /-- `nat_trans F G` represents a natural transformation between functors `F` and `G`. The field `app` provides the components of the natural transformation. Naturality is expressed by `α.naturality_lemma`. -/ @[ext] structure nat_trans (F G : C ⥤ D) : Type (max u₁ v₂) := (app : Π X : C, (F.obj X) ⟶ (G.obj X)) (naturality' : ∀ {{X Y : C}} (f : X ⟶ Y), (F.map f) ≫ (app Y) = (app X) ≫ (G.map f) . obviously) restate_axiom nat_trans.naturality' attribute [simp] nat_trans.naturality namespace nat_trans /-- `nat_trans.id F` is the identity natural transformation on a functor `F`. -/ protected def id (F : C ⥤ D) : nat_trans F F := { app := λ X, 𝟙 (F.obj X) } @[simp] lemma id_app' (F : C ⥤ D) (X : C) : (nat_trans.id F).app X = 𝟙 (F.obj X) := rfl open category open category_theory.functor section variables {F G H I : C ⥤ D} /-- `vcomp α β` is the vertical compositions of natural transformations. -/ def vcomp (α : nat_trans F G) (β : nat_trans G H) : nat_trans F H := { app := λ X, (α.app X) ≫ (β.app X), naturality' := begin /- `obviously'` says: -/ intros, simp, rw [←assoc, naturality, assoc, ←naturality], end } -- functor_category will rewrite (vcomp α β) to (α ≫ β), so this is not a -- suitable simp lemma. We will declare the variant vcomp_app' there. lemma vcomp_app (α : nat_trans F G) (β : nat_trans G H) (X : C) : (vcomp α β).app X = (α.app X) ≫ (β.app X) := rfl end end nat_trans end category_theory
447612ad2e5c9d1cd6e3c715c8e634f8d2990522
5ee26964f602030578ef0159d46145dd2e357ba5
/src/for_mathlib/sheaves/stalk.lean
9973d7b31e68d81a13616435cf1a5056349b8929
[ "Apache-2.0" ]
permissive
fpvandoorn/lean-perfectoid-spaces
569b4006fdfe491ca8b58dd817bb56138ada761f
06cec51438b168837fc6e9268945735037fd1db6
refs/heads/master
1,590,154,571,918
1,557,685,392,000
1,557,685,392,000
186,363,547
0
0
Apache-2.0
1,557,730,933,000
1,557,730,933,000
null
UTF-8
Lean
false
false
2,521
lean
/- Stalk (of types). https://stacks.math.columbia.edu/tag/0078 Author: Ramon Fernandez Mir -/ import for_mathlib.sheaves.opens import topology.basic import for_mathlib.sheaves.presheaf universe u section stalk variables {α : Type u} [topological_space α] variables (F : presheaf α) (x : α) open topological_space -- An element in the stalk is a pair (U, s) under an equivalence relation structure stalk.elem := (U : opens α) (HxU : x ∈ U) (s : F U) -- Equivalence relation on the set of pairs. (U,s) ~ (V,t) iff there exists W -- open s.t. x ∈ W ⊆ U ∩ V, and s|W = t|W. def stalk.relation : stalk.elem F x → stalk.elem F x → Prop := λ Us Vt, ∃ (W : opens α) (HxW : x ∈ W) (HWU : W ⊆ Us.U) (HWV : W ⊆ Vt.U), F.res Us.U W HWU Us.s = F.res Vt.U W HWV Vt.s lemma stalk.relation.reflexive : reflexive (stalk.relation F x) := λ ⟨U, HxU, s⟩, ⟨U, HxU, set.subset.refl _, set.subset.refl _, rfl⟩ lemma stalk.relation.symmetric : symmetric (stalk.relation F x) := λ Us Vt ⟨W, HxW, HWU, HWV, Hres⟩, ⟨W, HxW, HWV, HWU, Hres.symm⟩ lemma stalk.relation.transitive : transitive (stalk.relation F x) := λ ⟨U, HxU, sU⟩ ⟨V, HxV, sV⟩ ⟨W, HxW, sW⟩, λ ⟨R, HxR, HRU, HRV, HresR⟩ ⟨S, HxS, HSV, HSW, HresS⟩, ⟨R ∩ S, ⟨HxR, HxS⟩, λ y ⟨HyR, _⟩, HRU HyR, λ y ⟨_, HyS⟩, HSW HyS, have HURRS : _ := F.Hcomp U R (R ∩ S) (set.inter_subset_left _ _) HRU, have HVRRS : _ := F.Hcomp V R (R ∩ S) (set.inter_subset_left _ _) HRV, have HVSRS : _ := F.Hcomp V S (R ∩ S) (set.inter_subset_right _ _) HSV, have HWSRS : _ := F.Hcomp W S (R ∩ S) (set.inter_subset_right _ _) HSW, calc F.res U (R ∩ S) _ sU = F.res R (R ∩ S) _ (F.res U R _ sU) : congr_fun HURRS sU ... = F.res R (R ∩ S) _ (F.res V R _ sV) : congr_arg _ HresR ... = F.res V (R ∩ S) _ sV : congr_fun HVRRS.symm sV ... = F.res S (R ∩ S) _ (F.res V S _ sV) : congr_fun HVSRS sV ... = F.res S (R ∩ S) _ (F.res W S _ sW) : congr_arg _ HresS ... = F.res W (R ∩ S) _ sW : congr_fun HWSRS.symm sW⟩ lemma stalk.relation.equivalence : equivalence (stalk.relation F x) := ⟨stalk.relation.reflexive F x, stalk.relation.symmetric F x, stalk.relation.transitive F x⟩ instance stalk.setoid : setoid (stalk.elem F x) := { r := stalk.relation F x, iseqv := stalk.relation.equivalence F x } -- We define a stalk as the set of stalk elements under the defined relation. definition stalk := quotient (stalk.setoid F x) end stalk
b9eb40ee8cc03af063c01d43614d4904ad28e97b
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/meta/uchange.lean
b0a98ea330b5d4b321e83b1b3d81f6375c34515e
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
819
lean
/- Copyright (c) 2020 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.PostPort namespace Mathlib /-! # Changing universes of types in meta-code This file defines the meta type `uchange (α : Type v) : Type u`, which permits us to change the universe of a type analogously to `ulift`. However since `uchange` is meta, it can both lift and lower the universe. The implementation of `uchange` is efficient. Both `uchange.up` and `uchange.down` compile to no-ops. -/ /-- `unchecked_cast' a : β` performs an unchecked cast of `(a : α)` to `β`. Unlike `unchecked_cast`, it can cast across universes. The VM implementation is guaranteed to be the identity. -/
096ed563c3a3d88f7a5a735aaea376e29e3f6bfc
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/free_monoid/count.lean
ac642cb2e04ba92c0c5658600329931e3f7d9bd2
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
2,713
lean
/- Copyright (c) 2022 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import algebra.free_monoid.basic import data.list.count /-! # `list.count` as a bundled homomorphism > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we define `free_monoid.countp`, `free_monoid.count`, `free_add_monoid.countp`, and `free_add_monoid.count`. These are `list.countp` and `list.count` bundled as multiplicative and additive homomorphisms from `free_monoid` and `free_add_monoid`. We do not use `to_additive` because it can't map `multiplicative ℕ` to `ℕ`. -/ variables {α : Type*} (p : α → Prop) [decidable_pred p] namespace free_add_monoid /-- `list.countp` as a bundled additive monoid homomorphism. -/ def countp (p : α → Prop) [decidable_pred p] : free_add_monoid α →+ ℕ := ⟨list.countp p, list.countp_nil p, list.countp_append _⟩ lemma countp_of (x : α) : countp p (of x) = if p x then 1 else 0 := rfl lemma countp_apply (l : free_add_monoid α) : countp p l = list.countp p l := rfl /-- `list.count` as a bundled additive monoid homomorphism. -/ def count [decidable_eq α] (x : α) : free_add_monoid α →+ ℕ := countp (eq x) lemma count_of [decidable_eq α] (x y : α) : count x (of y) = pi.single x 1 y := by simp only [count, countp_of, pi.single_apply, eq_comm] lemma count_apply [decidable_eq α] (x : α) (l : free_add_monoid α) : count x l = list.count x l := rfl end free_add_monoid namespace free_monoid /-- `list.countp` as a bundled multiplicative monoid homomorphism. -/ def countp (p : α → Prop) [decidable_pred p] : free_monoid α →* multiplicative ℕ := (free_add_monoid.countp p).to_multiplicative lemma countp_of' (x : α) : countp p (of x) = if p x then multiplicative.of_add 1 else multiplicative.of_add 0 := rfl lemma countp_of (x : α) : countp p (of x) = if p x then multiplicative.of_add 1 else 1 := by rw [countp_of', of_add_zero] -- `rfl` is not transitive lemma countp_apply (l : free_add_monoid α) : countp p l = multiplicative.of_add (list.countp p l) := rfl /-- `list.count` as a bundled additive monoid homomorphism. -/ def count [decidable_eq α] (x : α) : free_monoid α →* multiplicative ℕ := countp (eq x) lemma count_apply [decidable_eq α] (x : α) (l : free_add_monoid α) : count x l = multiplicative.of_add (list.count x l) := rfl lemma count_of [decidable_eq α] (x y : α) : count x (of y) = @pi.mul_single α (λ _, multiplicative ℕ) _ _ x (multiplicative.of_add 1) y := by simp only [count, countp_of, pi.mul_single_apply, eq_comm] end free_monoid
ef0ca6bc6cc6ea4490c3e4b0dc311500e8452d40
856e2e1615a12f95b551ed48fa5b03b245abba44
/src/data/finsupp.lean
ea8bf0935a5f9e9c4081ad9eed5b96726f7ae196
[ "Apache-2.0" ]
permissive
pimsp/mathlib
8b77e1ccfab21703ba8fbe65988c7de7765aa0e5
913318ca9d6979686996e8d9b5ebf7e74aae1c63
refs/heads/master
1,669,812,465,182
1,597,133,610,000
1,597,133,610,000
281,890,685
1
0
null
1,595,491,577,000
1,595,491,576,000
null
UTF-8
Lean
false
false
71,941
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, Scott Morrison -/ import algebra.big_operators.order import algebra.module import data.fintype.card import data.set.finite import data.multiset.antidiagonal /-! # Type of functions with finite support For any type `α` and a type `β` with zero, we define the type `finsupp α β` of finitely supported functions from `α` to `β`, i.e. the functions which are zero everywhere on `α` except on a finite set. We write this in infix notation as `α →₀ β`. Functions with finite support provide the basis for the following concrete instances: * `ℕ →₀ α`: Polynomials (where `α` is a ring) * `(σ →₀ ℕ) →₀ α`: Multivariate Polynomials (again `α` is a ring, and `σ` are variable names) * `α →₀ ℕ`: Multisets * `α →₀ ℤ`: Abelian groups freely generated by `α` * `β →₀ α`: Linear combinations over `β` where `α` is the scalar ring Most of the theory assumes that the range is a commutative monoid. This gives us the big sum operator as a powerful way to construct `finsupp` elements. A general piece of advice is to not use `α →₀ β` directly, as the type class setup might not be a good fit. Defining a copy and selecting the instances that are best suited for the application works better. ## Implementation notes This file is a `noncomputable theory` and uses classical logic throughout. ## Notation This file defines `α →₀ β` as notation for `finsupp α β`. -/ noncomputable theory open_locale classical big_operators open finset variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Type*} {α₁ : Type*} {α₂ : Type*} {β₁ : Type*} {β₂ : Type*} /-- `finsupp α β`, denoted `α →₀ β`, is the type of functions `f : α → β` such that `f x = 0` for all but finitely many `x`. -/ structure finsupp (α : Type*) (β : Type*) [has_zero β] := (support : finset α) (to_fun : α → β) (mem_support_to_fun : ∀a, a ∈ support ↔ to_fun a ≠ 0) infixr ` →₀ `:25 := finsupp namespace finsupp /-! ### Basic declarations about `finsupp` -/ section basic variable [has_zero β] instance : has_coe_to_fun (α →₀ β) := ⟨λ_, α → β, to_fun⟩ instance : has_zero (α →₀ β) := ⟨⟨∅, (λ_, 0), λ _, ⟨false.elim, λ H, H rfl⟩⟩⟩ @[simp] lemma zero_apply {a : α} : (0 : α →₀ β) a = 0 := rfl @[simp] lemma support_zero : (0 : α →₀ β).support = ∅ := rfl instance : inhabited (α →₀ β) := ⟨0⟩ @[simp] lemma mem_support_iff {f : α →₀ β} : ∀{a:α}, a ∈ f.support ↔ f a ≠ 0 := f.mem_support_to_fun lemma not_mem_support_iff {f : α →₀ β} {a} : a ∉ f.support ↔ f a = 0 := not_iff_comm.1 mem_support_iff.symm @[ext] lemma ext : ∀{f g : α →₀ β}, (∀a, f a = g a) → f = g | ⟨s, f, hf⟩ ⟨t, g, hg⟩ h := begin have : f = g, { funext a, exact h a }, subst this, have : s = t, { ext a, exact (hf a).trans (hg a).symm }, subst this end lemma ext_iff {f g : α →₀ β} : f = g ↔ (∀a:α, f a = g a) := ⟨by rintros rfl a; refl, ext⟩ @[simp] lemma support_eq_empty {f : α →₀ β} : f.support = ∅ ↔ f = 0 := ⟨assume h, ext $ assume a, by_contradiction $ λ H, (finset.ext_iff.1 h a).1 $ mem_support_iff.2 H, by rintro rfl; refl⟩ instance finsupp.decidable_eq [decidable_eq α] [decidable_eq β] : decidable_eq (α →₀ β) := assume f g, decidable_of_iff (f.support = g.support ∧ (∀a∈f.support, f a = g a)) ⟨assume ⟨h₁, h₂⟩, ext $ assume a, if h : a ∈ f.support then h₂ a h else have hf : f a = 0, by rwa [mem_support_iff, not_not] at h, have hg : g a = 0, by rwa [h₁, mem_support_iff, not_not] at h, by rw [hf, hg], by rintro rfl; exact ⟨rfl, λ _ _, rfl⟩⟩ lemma finite_supp (f : α →₀ β) : set.finite {a | f a ≠ 0} := ⟨fintype.of_finset f.support (λ _, mem_support_iff)⟩ lemma support_subset_iff {s : set α} {f : α →₀ β} : ↑f.support ⊆ s ↔ (∀a∉s, f a = 0) := by simp only [set.subset_def, mem_coe, mem_support_iff]; exact forall_congr (assume a, @not_imp_comm _ _ (classical.dec _) (classical.dec _)) /-- Given `fintype α`, `equiv_fun_on_fintype` is the `equiv` between `α →₀ β` and `α → β`. (All functions on a finite type are finitely supported.) -/ def equiv_fun_on_fintype [fintype α] : (α →₀ β) ≃ (α → β) := ⟨λf a, f a, λf, mk (finset.univ.filter $ λa, f a ≠ 0) f (by simp only [true_and, finset.mem_univ, iff_self, finset.mem_filter, finset.filter_congr_decidable, forall_true_iff]), begin intro f, ext a, refl end, begin intro f, ext a, refl end⟩ end basic /-! ### Declarations about `single` -/ section single variables [has_zero β] {a a' : α} {b : β} /-- `single a b` is the finitely supported function which has value `b` at `a` and zero otherwise. -/ def single (a : α) (b : β) : α →₀ β := ⟨if b = 0 then ∅ else {a}, λ a', if a = a' then b else 0, λ a', begin by_cases hb : b = 0; by_cases a = a'; simp only [hb, h, if_pos, if_false, mem_singleton], { exact ⟨false.elim, λ H, H rfl⟩ }, { exact ⟨false.elim, λ H, H rfl⟩ }, { exact ⟨λ _, hb, λ _, rfl⟩ }, { exact ⟨λ H _, h H.symm, λ H, (H rfl).elim⟩ } end⟩ lemma single_apply : (single a b : α →₀ β) a' = if a = a' then b else 0 := rfl @[simp] lemma single_eq_same : (single a b : α →₀ β) a = b := if_pos rfl @[simp] lemma single_eq_of_ne (h : a ≠ a') : (single a b : α →₀ β) a' = 0 := if_neg h @[simp] lemma single_zero : (single a 0 : α →₀ β) = 0 := ext $ assume a', begin by_cases h : a = a', { rw [h, single_eq_same, zero_apply] }, { rw [single_eq_of_ne h, zero_apply] } end lemma support_single_ne_zero (hb : b ≠ 0) : (single a b).support = {a} := if_neg hb lemma support_single_subset : (single a b).support ⊆ {a} := show ite _ _ _ ⊆ _, by split_ifs; [exact empty_subset _, exact subset.refl _] lemma single_injective (a : α) : function.injective (single a : β → α →₀ β) := assume b₁ b₂ eq, have (single a b₁ : α →₀ β) a = (single a b₂ : α →₀ β) a, by rw eq, by rwa [single_eq_same, single_eq_same] at this lemma single_eq_single_iff (a₁ a₂ : α) (b₁ b₂ : β) : single a₁ b₁ = single a₂ b₂ ↔ ((a₁ = a₂ ∧ b₁ = b₂) ∨ (b₁ = 0 ∧ b₂ = 0)) := begin split, { assume eq, by_cases a₁ = a₂, { refine or.inl ⟨h, _⟩, rwa [h, (single_injective a₂).eq_iff] at eq }, { rw [ext_iff] at eq, have h₁ := eq a₁, have h₂ := eq a₂, simp only [single_eq_same, single_eq_of_ne h, single_eq_of_ne (ne.symm h)] at h₁ h₂, exact or.inr ⟨h₁, h₂.symm⟩ } }, { rintros (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩), { refl }, { rw [single_zero, single_zero] } } end lemma single_left_inj (h : b ≠ 0) : single a b = single a' b ↔ a = a' := ⟨λ H, by simpa only [h, single_eq_single_iff, and_false, or_false, eq_self_iff_true, and_true] using H, λ H, by rw [H]⟩ lemma single_eq_zero : single a b = 0 ↔ b = 0 := ⟨λ h, by { rw ext_iff at h, simpa only [single_eq_same, zero_apply] using h a }, λ h, by rw [h, single_zero]⟩ lemma single_swap {α β : Type*} [has_zero β] (a₁ a₂ : α) (b : β) : (single a₁ b : α → β) a₂ = (single a₂ b : α → β) a₁ := by simp only [single_apply]; ac_refl lemma unique_single [unique α] (x : α →₀ β) : x = single (default α) (x (default α)) := by ext i; simp only [unique.eq_default i, single_eq_same] @[simp] lemma unique_single_eq_iff [unique α] {b' : β} : single a b = single a' b' ↔ b = b' := begin rw [single_eq_single_iff], split, { rintros (⟨_, rfl⟩ | ⟨rfl, rfl⟩); refl }, { intro h, left, exact ⟨subsingleton.elim _ _, h⟩ } end end single /-! ### Declarations about `on_finset` -/ section on_finset variables [has_zero β] /-- `on_finset s f hf` is the finsupp function representing `f` restricted to the finset `s`. The function needs to be `0` outside of `s`. Use this when the set needs to be filtered anyways, otherwise a better set representation is often available. -/ def on_finset (s : finset α) (f : α → β) (hf : ∀a, f a ≠ 0 → a ∈ s) : α →₀ β := ⟨s.filter (λa, f a ≠ 0), f, assume a, classical.by_cases (assume h : f a = 0, by rw mem_filter; exact ⟨and.right, λ H, (H h).elim⟩) (assume h : f a ≠ 0, by rw mem_filter; simp only [iff_true_intro h, hf a h, true_and])⟩ @[simp] lemma on_finset_apply {s : finset α} {f : α → β} {hf a} : (on_finset s f hf : α →₀ β) a = f a := rfl @[simp] lemma support_on_finset_subset {s : finset α} {f : α → β} {hf} : (on_finset s f hf).support ⊆ s := filter_subset _ end on_finset /-! ### Declarations about `map_range` -/ section map_range variables [has_zero β₁] [has_zero β₂] /-- The composition of `f : β₁ → β₂` and `g : α →₀ β₁` is `map_range f hf g : α →₀ β₂`, well-defined when `f 0 = 0`. -/ def map_range (f : β₁ → β₂) (hf : f 0 = 0) (g : α →₀ β₁) : α →₀ β₂ := on_finset g.support (f ∘ g) $ assume a, by rw [mem_support_iff, not_imp_not]; exact λ H, (congr_arg f H).trans hf @[simp] lemma map_range_apply {f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} {a : α} : map_range f hf g a = f (g a) := rfl @[simp] lemma map_range_zero {f : β₁ → β₂} {hf : f 0 = 0} : map_range f hf (0 : α →₀ β₁) = 0 := ext $ λ a, by simp only [hf, zero_apply, map_range_apply] lemma support_map_range {f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} : (map_range f hf g).support ⊆ g.support := support_on_finset_subset @[simp] lemma map_range_single {f : β₁ → β₂} {hf : f 0 = 0} {a : α} {b : β₁} : map_range f hf (single a b) = single a (f b) := ext $ λ a', show f (ite _ _ _) = ite _ _ _, by split_ifs; [refl, exact hf] end map_range /-! ### Declarations about `emb_domain` -/ section emb_domain variables [has_zero β] /-- Given `f : α₁ ↪ α₂` and `v : α₁ →₀ β`, `emb_domain f v : α₂ →₀ β` is the finitely supported function whose value at `f a : α₂` is `v a`. For a `b : α₂` outside the range of `f`, it is zero. -/ def emb_domain (f : α₁ ↪ α₂) (v : α₁ →₀ β) : α₂ →₀ β := begin refine ⟨v.support.map f, λa₂, if h : a₂ ∈ v.support.map f then v (v.support.choose (λa₁, f a₁ = a₂) _) else 0, _⟩, { rcases finset.mem_map.1 h with ⟨a, ha, rfl⟩, exact exists_unique.intro a ⟨ha, rfl⟩ (assume b ⟨_, hb⟩, f.injective hb) }, { assume a₂, split_ifs, { simp only [h, true_iff, ne.def], rw [← not_mem_support_iff, not_not], apply finset.choose_mem }, { simp only [h, ne.def, ne_self_iff_false] } } end lemma support_emb_domain (f : α₁ ↪ α₂) (v : α₁ →₀ β) : (emb_domain f v).support = v.support.map f := rfl lemma emb_domain_zero (f : α₁ ↪ α₂) : (emb_domain f 0 : α₂ →₀ β) = 0 := rfl lemma emb_domain_apply (f : α₁ ↪ α₂) (v : α₁ →₀ β) (a : α₁) : emb_domain f v (f a) = v a := begin change dite _ _ _ = _, split_ifs; rw [finset.mem_map' f] at h, { refine congr_arg (v : α₁ → β) (f.inj' _), exact finset.choose_property (λa₁, f a₁ = f a) _ _ }, { exact (not_mem_support_iff.1 h).symm } end lemma emb_domain_notin_range (f : α₁ ↪ α₂) (v : α₁ →₀ β) (a : α₂) (h : a ∉ set.range f) : emb_domain f v a = 0 := begin refine dif_neg (mt (assume h, _) h), rcases finset.mem_map.1 h with ⟨a, h, rfl⟩, exact set.mem_range_self a end lemma emb_domain_inj {f : α₁ ↪ α₂} {l₁ l₂ : α₁ →₀ β} : emb_domain f l₁ = emb_domain f l₂ ↔ l₁ = l₂ := ⟨λ h, ext $ λ a, by simpa only [emb_domain_apply] using ext_iff.1 h (f a), λ h, by rw h⟩ lemma emb_domain_map_range {β₁ β₂ : Type*} [has_zero β₁] [has_zero β₂] (f : α₁ ↪ α₂) (g : β₁ → β₂) (p : α₁ →₀ β₁) (hg : g 0 = 0) : emb_domain f (map_range g hg p) = map_range g hg (emb_domain f p) := begin ext a, by_cases a ∈ set.range f, { rcases h with ⟨a', rfl⟩, rw [map_range_apply, emb_domain_apply, emb_domain_apply, map_range_apply] }, { rw [map_range_apply, emb_domain_notin_range, emb_domain_notin_range, ← hg]; assumption } end lemma single_of_emb_domain_single (l : α₁ →₀ β) (f : α₁ ↪ α₂) (a : α₂) (b : β) (hb : b ≠ 0) (h : l.emb_domain f = single a b) : ∃ x, l = single x b ∧ f x = a := begin have h_map_support : finset.map f (l.support) = {a}, by rw [←support_emb_domain, h, support_single_ne_zero hb]; refl, have ha : a ∈ finset.map f (l.support), by simp only [h_map_support, finset.mem_singleton], rcases finset.mem_map.1 ha with ⟨c, hc₁, hc₂⟩, use c, split, { ext d, rw [← emb_domain_apply f l, h], by_cases h_cases : c = d, { simp only [eq.symm h_cases, hc₂, single_eq_same] }, { rw [single_apply, single_apply, if_neg, if_neg h_cases], by_contra hfd, exact h_cases (f.injective (hc₂.trans hfd)) } }, { exact hc₂ } end end emb_domain /-! ### Declarations about `zip_with` -/ section zip_with variables [has_zero β] [has_zero β₁] [has_zero β₂] /-- `zip_with f hf g₁ g₂` is the finitely supported function satisfying `zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a)`, and it is well-defined when `f 0 0 = 0`. -/ def zip_with (f : β₁ → β₂ → β) (hf : f 0 0 = 0) (g₁ : α →₀ β₁) (g₂ : α →₀ β₂) : (α →₀ β) := on_finset (g₁.support ∪ g₂.support) (λa, f (g₁ a) (g₂ a)) $ λ a H, begin simp only [mem_union, mem_support_iff, ne], rw [← not_and_distrib], rintro ⟨h₁, h₂⟩, rw [h₁, h₂] at H, exact H hf end @[simp] lemma zip_with_apply {f : β₁ → β₂ → β} {hf : f 0 0 = 0} {g₁ : α →₀ β₁} {g₂ : α →₀ β₂} {a : α} : zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a) := rfl lemma support_zip_with {f : β₁ → β₂ → β} {hf : f 0 0 = 0} {g₁ : α →₀ β₁} {g₂ : α →₀ β₂} : (zip_with f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support := support_on_finset_subset end zip_with /-! ### Declarations about `erase` -/ section erase /-- `erase a f` is the finitely supported function equal to `f` except at `a` where it is equal to `0`. -/ def erase [has_zero β] (a : α) (f : α →₀ β) : α →₀ β := ⟨f.support.erase a, (λa', if a' = a then 0 else f a'), assume a', by rw [mem_erase, mem_support_iff]; split_ifs; [exact ⟨λ H _, H.1 h, λ H, (H rfl).elim⟩, exact and_iff_right h]⟩ @[simp] lemma support_erase [has_zero β] {a : α} {f : α →₀ β} : (f.erase a).support = f.support.erase a := rfl @[simp] lemma erase_same [has_zero β] {a : α} {f : α →₀ β} : (f.erase a) a = 0 := if_pos rfl @[simp] lemma erase_ne [has_zero β] {a a' : α} {f : α →₀ β} (h : a' ≠ a) : (f.erase a) a' = f a' := if_neg h @[simp] lemma erase_single [has_zero β] {a : α} {b : β} : (erase a (single a b)) = 0 := begin ext s, by_cases hs : s = a, { rw [hs, erase_same], refl }, { rw [erase_ne hs], exact single_eq_of_ne (ne.symm hs) } end lemma erase_single_ne [has_zero β] {a a' : α} {b : β} (h : a ≠ a') : (erase a (single a' b)) = single a' b := begin ext s, by_cases hs : s = a, { rw [hs, erase_same, single_eq_of_ne (h.symm)] }, { rw [erase_ne hs] } end end erase /-! ### Declarations about `sum` and `prod` In most of this section, the domain `β` is assumed to be an `add_monoid`. -/ -- [to_additive sum] for finsupp.prod doesn't work, the equation lemmas are not generated /-- `sum f g` is the sum of `g a (f a)` over the support of `f`. -/ def sum [has_zero β] [add_comm_monoid γ] (f : α →₀ β) (g : α → β → γ) : γ := ∑ a in f.support, g a (f a) /-- `prod f g` is the product of `g a (f a)` over the support of `f`. -/ @[to_additive] def prod [has_zero β] [comm_monoid γ] (f : α →₀ β) (g : α → β → γ) : γ := ∏ a in f.support, g a (f a) @[to_additive] lemma prod_fintype [fintype α] [has_zero β] [comm_monoid γ] (f : α →₀ β) (g : α → β → γ) (h : ∀ i, g i 0 = 1) : f.prod g = ∏ i, g i (f i) := begin classical, rw [finsupp.prod, ← fintype.prod_extend_by_one, finset.prod_congr rfl], intros i hi, split_ifs with hif hif, { refl }, { rw finsupp.not_mem_support_iff at hif, rw [hif, h] } end @[to_additive] lemma prod_map_range_index [has_zero β₁] [has_zero β₂] [comm_monoid γ] {f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} {h : α → β₂ → γ} (h0 : ∀a, h a 0 = 1) : (map_range f hf g).prod h = g.prod (λa b, h a (f b)) := finset.prod_subset support_map_range $ λ _ _ H, by rw [not_mem_support_iff.1 H, h0] @[to_additive] lemma prod_zero_index [add_comm_monoid β] [comm_monoid γ] {h : α → β → γ} : (0 : α →₀ β).prod h = 1 := rfl @[to_additive] lemma prod_comm {α' : Type*} [has_zero β] {β' : Type*} [has_zero β'] (f : α →₀ β) (g : α' →₀ β') [comm_monoid γ] (h : α → β → α' → β' → γ) : f.prod (λ x v, g.prod (λ x' v', h x v x' v')) = g.prod (λ x' v', f.prod (λ x v, h x v x' v')) := begin dsimp [finsupp.prod], rw finset.prod_comm, end @[simp, to_additive] lemma prod_ite_eq [has_zero β] [comm_monoid γ] (f : α →₀ β) (a : α) (b : α → β → γ) : f.prod (λ x v, ite (a = x) (b x v) 1) = ite (a ∈ f.support) (b a (f a)) 1 := by { dsimp [finsupp.prod], rw f.support.prod_ite_eq, } /-- A restatement of `prod_ite_eq` with the equality test reversed. -/ @[simp, to_additive "A restatement of `sum_ite_eq` with the equality test reversed."] lemma prod_ite_eq' [has_zero β] [comm_monoid γ] (f : α →₀ β) (a : α) (b : α → β → γ) : f.prod (λ x v, ite (x = a) (b x v) 1) = ite (a ∈ f.support) (b a (f a)) 1 := by { dsimp [finsupp.prod], rw f.support.prod_ite_eq', } @[simp] lemma prod_pow [fintype α] [comm_monoid γ] (f : α →₀ ℕ) (g : α → γ) : f.prod (λ a b, g a ^ b) = ∏ a, g a ^ (f a) := begin apply prod_subset (finset.subset_univ _), intros a _ ha, simp only [finsupp.not_mem_support_iff.mp ha, pow_zero] end /-- If `g` maps a second argument of 0 to 0, summing it over the result of `on_finset` is the same as summing it over the original `finset`. -/ lemma on_finset_sum [has_zero β] [add_comm_monoid γ] {s : finset α} {f : α → β} {g : α → β → γ} (hf : ∀a, f a ≠ 0 → a ∈ s) (hg : ∀ a, g a 0 = 0) : (on_finset s f hf).sum g = ∑ a in s, g a (f a) := begin refine finset.sum_subset support_on_finset_subset _, intros x hx hxs, rw not_mem_support_iff.1 hxs, exact hg _ end section add_monoid variables [add_monoid β] @[to_additive] lemma prod_single_index [comm_monoid γ] {a : α} {b : β} {h : α → β → γ} (h_zero : h a 0 = 1) : (single a b).prod h = h a b := begin by_cases h : b = 0, { simp only [h, h_zero, single_zero]; refl }, { simp only [finsupp.prod, support_single_ne_zero h, prod_singleton, single_eq_same] } end instance : has_add (α →₀ β) := ⟨zip_with (+) (add_zero 0)⟩ @[simp] lemma add_apply {g₁ g₂ : α →₀ β} {a : α} : (g₁ + g₂) a = g₁ a + g₂ a := rfl lemma support_add {g₁ g₂ : α →₀ β} : (g₁ + g₂).support ⊆ g₁.support ∪ g₂.support := support_zip_with lemma support_add_eq {g₁ g₂ : α →₀ β} (h : disjoint g₁.support g₂.support) : (g₁ + g₂).support = g₁.support ∪ g₂.support := le_antisymm support_zip_with $ assume a ha, (finset.mem_union.1 ha).elim (assume ha, have a ∉ g₂.support, from disjoint_left.1 h ha, by simp only [mem_support_iff, not_not] at *; simpa only [add_apply, this, add_zero]) (assume ha, have a ∉ g₁.support, from disjoint_right.1 h ha, by simp only [mem_support_iff, not_not] at *; simpa only [add_apply, this, zero_add]) @[simp] lemma single_add {a : α} {b₁ b₂ : β} : single a (b₁ + b₂) = single a b₁ + single a b₂ := ext $ assume a', begin by_cases h : a = a', { rw [h, add_apply, single_eq_same, single_eq_same, single_eq_same] }, { rw [add_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h, zero_add] } end instance : add_monoid (α →₀ β) := { add_monoid . zero := 0, add := (+), add_assoc := assume ⟨s, f, hf⟩ ⟨t, g, hg⟩ ⟨u, h, hh⟩, ext $ assume a, add_assoc _ _ _, zero_add := assume ⟨s, f, hf⟩, ext $ assume a, zero_add _, add_zero := assume ⟨s, f, hf⟩, ext $ assume a, add_zero _ } /-- Evaluation of a function `f : α →₀ β` at a point as an additive monoid homomorphism. -/ def eval_add_hom (a : α) : (α →₀ β) →+ β := ⟨λ g, g a, zero_apply, λ _ _, add_apply⟩ @[simp] lemma eval_add_hom_apply (a : α) (g : α →₀ β) : eval_add_hom a g = g a := rfl lemma single_add_erase {a : α} {f : α →₀ β} : single a (f a) + f.erase a = f := ext $ λ a', if h : a = a' then by subst h; simp only [add_apply, single_eq_same, erase_same, add_zero] else by simp only [add_apply, single_eq_of_ne h, zero_add, erase_ne (ne.symm h)] lemma erase_add_single {a : α} {f : α →₀ β} : f.erase a + single a (f a) = f := ext $ λ a', if h : a = a' then by subst h; simp only [add_apply, single_eq_same, erase_same, zero_add] else by simp only [add_apply, single_eq_of_ne h, add_zero, erase_ne (ne.symm h)] @[simp] lemma erase_add (a : α) (f f' : α →₀ β) : erase a (f + f') = erase a f + erase a f' := begin ext s, by_cases hs : s = a, { rw [hs, add_apply, erase_same, erase_same, erase_same, add_zero] }, rw [add_apply, erase_ne hs, erase_ne hs, erase_ne hs, add_apply], end @[elab_as_eliminator] protected theorem induction {p : (α →₀ β) → Prop} (f : α →₀ β) (h0 : p 0) (ha : ∀a b (f : α →₀ β), a ∉ f.support → b ≠ 0 → p f → p (single a b + f)) : p f := suffices ∀s (f : α →₀ β), f.support = s → p f, from this _ _ rfl, assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $ assume a s has ih f hf, suffices p (single a (f a) + f.erase a), by rwa [single_add_erase] at this, begin apply ha, { rw [support_erase, mem_erase], exact λ H, H.1 rfl }, { rw [← mem_support_iff, hf], exact mem_insert_self _ _ }, { apply ih _ _, rw [support_erase, hf, finset.erase_insert has] } end lemma induction₂ {p : (α →₀ β) → Prop} (f : α →₀ β) (h0 : p 0) (ha : ∀a b (f : α →₀ β), a ∉ f.support → b ≠ 0 → p f → p (f + single a b)) : p f := suffices ∀s (f : α →₀ β), f.support = s → p f, from this _ _ rfl, assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $ assume a s has ih f hf, suffices p (f.erase a + single a (f a)), by rwa [erase_add_single] at this, begin apply ha, { rw [support_erase, mem_erase], exact λ H, H.1 rfl }, { rw [← mem_support_iff, hf], exact mem_insert_self _ _ }, { apply ih _ _, rw [support_erase, hf, finset.erase_insert has] } end lemma map_range_add [add_monoid β₁] [add_monoid β₂] {f : β₁ → β₂} {hf : f 0 = 0} (hf' : ∀ x y, f (x + y) = f x + f y) (v₁ v₂ : α →₀ β₁) : map_range f hf (v₁ + v₂) = map_range f hf v₁ + map_range f hf v₂ := ext $ λ a, by simp only [hf', add_apply, map_range_apply] end add_monoid section nat_sub instance nat_sub : has_sub (α →₀ ℕ) := ⟨zip_with (λ m n, m - n) (nat.sub_zero 0)⟩ @[simp] lemma nat_sub_apply {g₁ g₂ : α →₀ ℕ} {a : α} : (g₁ - g₂) a = g₁ a - g₂ a := rfl @[simp] lemma single_sub {a : α} {n₁ n₂ : ℕ} : single a (n₁ - n₂) = single a n₁ - single a n₂ := begin ext f, by_cases h : (a = f), { rw [h, nat_sub_apply, single_eq_same, single_eq_same, single_eq_same] }, rw [nat_sub_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h] end -- These next two lemmas are used in developing -- the partial derivative on `mv_polynomial`. lemma sub_single_one_add {a : α} {u u' : α →₀ ℕ} (h : u a ≠ 0) : u - single a 1 + u' = u + u' - single a 1 := begin ext b, rw [add_apply, nat_sub_apply, nat_sub_apply, add_apply], by_cases h : a = b, { rw [←h, single_eq_same], cases (u a), { contradiction }, { simp }, }, { simp [h], } end lemma add_sub_single_one {a : α} {u u' : α →₀ ℕ} (h : u' a ≠ 0) : u + (u' - single a 1) = u + u' - single a 1 := begin ext b, rw [add_apply, nat_sub_apply, nat_sub_apply, add_apply], by_cases h : a = b, { rw [←h, single_eq_same], cases (u' a), { contradiction }, { simp }, }, { simp [h], } end end nat_sub instance [add_comm_monoid β] : add_comm_monoid (α →₀ β) := { add_comm := assume ⟨s, f, _⟩ ⟨t, g, _⟩, ext $ assume a, add_comm _ _, .. finsupp.add_monoid } instance [add_group β] : add_group (α →₀ β) := { neg := map_range (has_neg.neg) neg_zero, add_left_neg := assume ⟨s, f, _⟩, ext $ assume x, add_left_neg _, .. finsupp.add_monoid } lemma single_multiset_sum [add_comm_monoid β] (s : multiset β) (a : α) : single a s.sum = (s.map (single a)).sum := multiset.induction_on s single_zero $ λ a s ih, by rw [multiset.sum_cons, single_add, ih, multiset.map_cons, multiset.sum_cons] lemma single_finset_sum [add_comm_monoid β] (s : finset γ) (f : γ → β) (a : α) : single a (∑ b in s, f b) = ∑ b in s, single a (f b) := begin transitivity, apply single_multiset_sum, rw [multiset.map_map], refl end lemma single_sum [has_zero γ] [add_comm_monoid β] (s : δ →₀ γ) (f : δ → γ → β) (a : α) : single a (s.sum f) = s.sum (λd c, single a (f d c)) := single_finset_sum _ _ _ @[to_additive] lemma prod_neg_index [add_group β] [comm_monoid γ] {g : α →₀ β} {h : α → β → γ} (h0 : ∀a, h a 0 = 1) : (-g).prod h = g.prod (λa b, h a (- b)) := prod_map_range_index h0 @[simp] lemma neg_apply [add_group β] {g : α →₀ β} {a : α} : (- g) a = - g a := rfl @[simp] lemma sub_apply [add_group β] {g₁ g₂ : α →₀ β} {a : α} : (g₁ - g₂) a = g₁ a - g₂ a := rfl @[simp] lemma support_neg [add_group β] {f : α →₀ β} : support (-f) = support f := finset.subset.antisymm support_map_range (calc support f = support (- (- f)) : congr_arg support (neg_neg _).symm ... ⊆ support (- f) : support_map_range) instance [add_comm_group β] : add_comm_group (α →₀ β) := { add_comm := add_comm, ..finsupp.add_group } @[simp] lemma sum_apply [has_zero β₁] [add_comm_monoid β] {f : α₁ →₀ β₁} {g : α₁ → β₁ → α →₀ β} {a₂ : α} : (f.sum g) a₂ = f.sum (λa₁ b, g a₁ b a₂) := (eval_add_hom a₂ : (α →₀ β) →+ _).map_sum _ _ lemma support_sum [has_zero β₁] [add_comm_monoid β] {f : α₁ →₀ β₁} {g : α₁ → β₁ → (α →₀ β)} : (f.sum g).support ⊆ f.support.bind (λa, (g a (f a)).support) := have ∀a₁ : α, f.sum (λ (a : α₁) (b : β₁), (g a b) a₁) ≠ 0 → (∃ (a : α₁), f a ≠ 0 ∧ ¬ (g a (f a)) a₁ = 0), from assume a₁ h, let ⟨a, ha, ne⟩ := finset.exists_ne_zero_of_sum_ne_zero h in ⟨a, mem_support_iff.mp ha, ne⟩, by simpa only [finset.subset_iff, mem_support_iff, finset.mem_bind, sum_apply, exists_prop] using this @[simp] lemma sum_zero [add_comm_monoid β] [add_comm_monoid γ] {f : α →₀ β} : f.sum (λa b, (0 : γ)) = 0 := finset.sum_const_zero @[simp] lemma sum_add [add_comm_monoid β] [add_comm_monoid γ] {f : α →₀ β} {h₁ h₂ : α → β → γ} : f.sum (λa b, h₁ a b + h₂ a b) = f.sum h₁ + f.sum h₂ := finset.sum_add_distrib @[simp] lemma sum_neg [add_comm_monoid β] [add_comm_group γ] {f : α →₀ β} {h : α → β → γ} : f.sum (λa b, - h a b) = - f.sum h := f.support.sum_hom (@has_neg.neg γ _) @[simp] lemma sum_sub [add_comm_monoid β] [add_comm_group γ] {f : α →₀ β} {h₁ h₂ : α → β → γ} : f.sum (λa b, h₁ a b - h₂ a b) = f.sum h₁ - f.sum h₂ := by rw [sub_eq_add_neg, ←sum_neg, ←sum_add]; refl @[simp] lemma sum_single [add_comm_monoid β] (f : α →₀ β) : f.sum single = f := have ∀a:α, f.sum (λa' b, ite (a' = a) b 0) = ∑ a' in {a}, ite (a' = a) (f a') 0, begin intro a, by_cases h : a ∈ f.support, { have : ({a} : finset α) ⊆ f.support, { simpa only [finset.subset_iff, mem_singleton, forall_eq] }, refine (finset.sum_subset this (λ _ _ H, _)).symm, exact if_neg (mt mem_singleton.2 H) }, { transitivity (∑ a in f.support, (0 : β)), { refine (finset.sum_congr rfl $ λ a' ha', if_neg _), rintro rfl, exact h ha' }, { rw [sum_const_zero, sum_singleton, if_pos rfl, not_mem_support_iff.1 h] } } end, ext $ assume a, by simp only [sum_apply, single_apply, this, sum_singleton, if_pos] @[to_additive] lemma prod_add_index [add_comm_monoid β] [comm_monoid γ] {f g : α →₀ β} {h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : (f + g).prod h = f.prod h * g.prod h := have f_eq : ∏ a in f.support ∪ g.support, h a (f a) = f.prod h, from (finset.prod_subset (finset.subset_union_left _ _) $ by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero]).symm, have g_eq : ∏ a in f.support ∪ g.support, h a (g a) = g.prod h, from (finset.prod_subset (finset.subset_union_right _ _) $ by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero]).symm, calc ∏ a in (f + g).support, h a ((f + g) a) = ∏ a in f.support ∪ g.support, h a ((f + g) a) : finset.prod_subset support_add $ by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero] ... = (∏ a in f.support ∪ g.support, h a (f a)) * (∏ a in f.support ∪ g.support, h a (g a)) : by simp only [add_apply, h_add, finset.prod_mul_distrib] ... = _ : by rw [f_eq, g_eq] lemma sum_sub_index [add_comm_group β] [add_comm_group γ] {f g : α →₀ β} {h : α → β → γ} (h_sub : ∀a b₁ b₂, h a (b₁ - b₂) = h a b₁ - h a b₂) : (f - g).sum h = f.sum h - g.sum h := have h_zero : ∀a, h a 0 = 0, from assume a, have h a (0 - 0) = h a 0 - h a 0, from h_sub a 0 0, by simpa only [sub_self] using this, have h_neg : ∀a b, h a (- b) = - h a b, from assume a b, have h a (0 - b) = h a 0 - h a b, from h_sub a 0 b, by simpa only [h_zero, zero_sub] using this, have h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ + h a b₂, from assume a b₁ b₂, have h a (b₁ - (- b₂)) = h a b₁ - h a (- b₂), from h_sub a b₁ (-b₂), by simpa only [h_neg, sub_neg_eq_add] using this, calc (f - g).sum h = (f + - g).sum h : rfl ... = f.sum h + - g.sum h : by simp only [sum_add_index h_zero h_add, sum_neg_index h_zero, h_neg, sum_neg] ... = f.sum h - g.sum h : rfl @[to_additive] lemma prod_finset_sum_index [add_comm_monoid β] [comm_monoid γ] {s : finset ι} {g : ι → α →₀ β} {h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : ∏ i in s, (g i).prod h = (∑ i in s, g i).prod h := finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih, sum_insert has, prod_add_index h_zero h_add] @[to_additive] lemma prod_sum_index [add_comm_monoid β₁] [add_comm_monoid β] [comm_monoid γ] {f : α₁ →₀ β₁} {g : α₁ → β₁ → α →₀ β} {h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : (f.sum g).prod h = f.prod (λa b, (g a b).prod h) := (prod_finset_sum_index h_zero h_add).symm lemma multiset_sum_sum_index [add_comm_monoid β] [add_comm_monoid γ] (f : multiset (α →₀ β)) (h : α → β → γ) (h₀ : ∀a, h a 0 = 0) (h₁ : ∀ (a : α) (b₁ b₂ : β), h a (b₁ + b₂) = h a b₁ + h a b₂) : (f.sum.sum h) = (f.map $ λg:α →₀ β, g.sum h).sum := multiset.induction_on f rfl $ assume a s ih, by rw [multiset.sum_cons, multiset.map_cons, multiset.sum_cons, sum_add_index h₀ h₁, ih] lemma multiset_map_sum [has_zero β] {f : α →₀ β} {m : γ → δ} {h : α → β → multiset γ} : multiset.map m (f.sum h) = f.sum (λa b, (h a b).map m) := (f.support.sum_hom _).symm lemma multiset_sum_sum [has_zero β] [add_comm_monoid γ] {f : α →₀ β} {h : α → β → multiset γ} : multiset.sum (f.sum h) = f.sum (λa b, multiset.sum (h a b)) := (f.support.sum_hom multiset.sum).symm section map_range variables [add_comm_monoid β₁] [add_comm_monoid β₂] (f : β₁ →+ β₂) /-- Composition with a fixed additive homomorphism is itself an additive homomorphism on functions. -/ def map_range.add_monoid_hom : (α →₀ β₁) →+ (α →₀ β₂) := { to_fun := (map_range f f.map_zero : (α →₀ β₁) → (α →₀ β₂)), map_zero' := map_range_zero, map_add' := λ a b, map_range_add f.map_add _ _ } lemma map_range_multiset_sum (m : multiset (α →₀ β₁)) : map_range f f.map_zero m.sum = (m.map $ λx, map_range f f.map_zero x).sum := (m.sum_hom (map_range.add_monoid_hom f)).symm lemma map_range_finset_sum {ι : Type*} (s : finset ι) (g : ι → (α →₀ β₁)) : map_range f f.map_zero (∑ x in s, g x) = ∑ x in s, map_range f f.map_zero (g x) := by rw [finset.sum.equations._eqn_1, map_range_multiset_sum, multiset.map_map]; refl end map_range /-! ### Declarations about `map_domain` -/ section map_domain variables [add_comm_monoid β] {v v₁ v₂ : α →₀ β} /-- Given `f : α₁ → α₂` and `v : α₁ →₀ β`, `map_domain f v : α₂ →₀ β` is the finitely supported function whose value at `a : α₂` is the sum of `v x` over all `x` such that `f x = a`. -/ def map_domain (f : α₁ → α₂) (v : α₁ →₀ β) : α₂ →₀ β := v.sum $ λa, single (f a) lemma map_domain_apply {f : α₁ → α₂} (hf : function.injective f) (x : α₁ →₀ β) (a : α₁) : map_domain f x (f a) = x a := begin rw [map_domain, sum_apply, sum, finset.sum_eq_single a, single_eq_same], { assume b _ hba, exact single_eq_of_ne (hf.ne hba) }, { simp only [(∉), (≠), not_not, mem_support_iff], assume h, rw [h, single_zero], refl } end lemma map_domain_notin_range {f : α₁ → α₂} (x : α₁ →₀ β) (a : α₂) (h : a ∉ set.range f) : map_domain f x a = 0 := begin rw [map_domain, sum_apply, sum], exact finset.sum_eq_zero (assume a' h', single_eq_of_ne $ assume eq, h $ eq ▸ set.mem_range_self _) end lemma map_domain_id : map_domain id v = v := sum_single _ lemma map_domain_comp {f : α → α₁} {g : α₁ → α₂} : map_domain (g ∘ f) v = map_domain g (map_domain f v) := begin refine ((sum_sum_index _ _).trans _).symm, { intros, exact single_zero }, { intros, exact single_add }, refine sum_congr rfl (λ _ _, sum_single_index _), { exact single_zero } end lemma map_domain_single {f : α → α₁} {a : α} {b : β} : map_domain f (single a b) = single (f a) b := sum_single_index single_zero @[simp] lemma map_domain_zero {f : α → α₂} : map_domain f 0 = (0 : α₂ →₀ β) := sum_zero_index lemma map_domain_congr {f g : α → α₂} (h : ∀x∈v.support, f x = g x) : v.map_domain f = v.map_domain g := finset.sum_congr rfl $ λ _ H, by simp only [h _ H] lemma map_domain_add {f : α → α₂} : map_domain f (v₁ + v₂) = map_domain f v₁ + map_domain f v₂ := sum_add_index (λ _, single_zero) (λ _ _ _, single_add) lemma map_domain_finset_sum {f : α → α₂} {s : finset ι} {v : ι → α →₀ β} : map_domain f (∑ i in s, v i) = ∑ i in s, map_domain f (v i) := eq.symm $ sum_finset_sum_index (λ _, single_zero) (λ _ _ _, single_add) lemma map_domain_sum [has_zero β₁] {f : α → α₂} {s : α →₀ β₁} {v : α → β₁ → α →₀ β} : map_domain f (s.sum v) = s.sum (λa b, map_domain f (v a b)) := eq.symm $ sum_finset_sum_index (λ _, single_zero) (λ _ _ _, single_add) lemma map_domain_support {f : α → α₂} {s : α →₀ β} : (s.map_domain f).support ⊆ s.support.image f := finset.subset.trans support_sum $ finset.subset.trans (finset.bind_mono $ assume a ha, support_single_subset) $ by rw [finset.bind_singleton]; exact subset.refl _ @[to_additive] lemma prod_map_domain_index [comm_monoid γ] {f : α → α₂} {s : α →₀ β} {h : α₂ → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : (s.map_domain f).prod h = s.prod (λa b, h (f a) b) := (prod_sum_index h_zero h_add).trans $ prod_congr rfl $ λ _ _, prod_single_index (h_zero _) lemma emb_domain_eq_map_domain (f : α₁ ↪ α₂) (v : α₁ →₀ β) : emb_domain f v = map_domain f v := begin ext a, by_cases a ∈ set.range f, { rcases h with ⟨a, rfl⟩, rw [map_domain_apply f.injective, emb_domain_apply] }, { rw [map_domain_notin_range, emb_domain_notin_range]; assumption } end lemma map_domain_injective {f : α₁ → α₂} (hf : function.injective f) : function.injective (map_domain f : (α₁ →₀ β) → (α₂ →₀ β)) := begin assume v₁ v₂ eq, ext a, have : map_domain f v₁ (f a) = map_domain f v₂ (f a), { rw eq }, rwa [map_domain_apply hf, map_domain_apply hf] at this, end end map_domain /-! ### Declarations about `comap_domain` -/ section comap_domain /-- Given `f : α₁ → α₂`, `l : α₂ →₀ γ` and a proof `hf` that `f` is injective on the preimage of `l.support`, `comap_domain f l hf` is the finitely supported function from `α₁` to `γ` given by composing `l` with `f`. -/ def comap_domain {α₁ α₂ γ : Type*} [has_zero γ] (f : α₁ → α₂) (l : α₂ →₀ γ) (hf : set.inj_on f (f ⁻¹' ↑l.support)) : α₁ →₀ γ := { support := l.support.preimage hf, to_fun := (λ a, l (f a)), mem_support_to_fun := begin intros a, simp only [finset.mem_def.symm, finset.mem_preimage], exact l.mem_support_to_fun (f a), end } @[simp] lemma comap_domain_apply {α₁ α₂ γ : Type*} [has_zero γ] (f : α₁ → α₂) (l : α₂ →₀ γ) (hf : set.inj_on f (f ⁻¹' ↑l.support)) (a : α₁) : comap_domain f l hf a = l (f a) := rfl lemma sum_comap_domain {α₁ α₂ β γ : Type*} [has_zero β] [add_comm_monoid γ] (f : α₁ → α₂) (l : α₂ →₀ β) (g : α₂ → β → γ) (hf : set.bij_on f (f ⁻¹' ↑l.support) ↑l.support) : (comap_domain f l hf.inj_on).sum (g ∘ f) = l.sum g := begin simp [sum], simp [comap_domain, finset.sum_preimage_of_bij f _ _ (λ (x : α₂), g x (l x))] end lemma eq_zero_of_comap_domain_eq_zero {α₁ α₂ γ : Type*} [add_comm_monoid γ] (f : α₁ → α₂) (l : α₂ →₀ γ) (hf : set.bij_on f (f ⁻¹' ↑l.support) ↑l.support) : comap_domain f l hf.inj_on = 0 → l = 0 := begin rw [← support_eq_empty, ← support_eq_empty, comap_domain], simp only [finset.ext_iff, finset.not_mem_empty, iff_false, mem_preimage], assume h a ha, cases hf.2.2 ha with b hb, exact h b (hb.2.symm ▸ ha) end lemma map_domain_comap_domain {α₁ α₂ γ : Type*} [add_comm_monoid γ] (f : α₁ → α₂) (l : α₂ →₀ γ) (hf : function.injective f) (hl : ↑l.support ⊆ set.range f): map_domain f (comap_domain f l (hf.inj_on _)) = l := begin ext a, by_cases h_cases: a ∈ set.range f, { rcases set.mem_range.1 h_cases with ⟨b, hb⟩, rw [hb.symm, map_domain_apply hf, comap_domain_apply] }, { rw map_domain_notin_range _ _ h_cases, by_contra h_contr, apply h_cases (hl $ finset.mem_coe.2 $ mem_support_iff.2 $ λ h, h_contr h.symm) } end end comap_domain /-! ### Declarations about `filter` -/ section filter section has_zero variables [has_zero β] (p : α → Prop) (f : α →₀ β) /-- `filter p f` is the function which is `f a` if `p a` is true and 0 otherwise. -/ def filter (p : α → Prop) (f : α →₀ β) : α →₀ β := on_finset f.support (λa, if p a then f a else 0) $ λ a H, mem_support_iff.2 $ λ h, by rw [h, if_t_t] at H; exact H rfl @[simp] lemma filter_apply_pos {a : α} (h : p a) : f.filter p a = f a := if_pos h @[simp] lemma filter_apply_neg {a : α} (h : ¬ p a) : f.filter p a = 0 := if_neg h @[simp] lemma support_filter : (f.filter p).support = f.support.filter p := finset.ext $ assume a, if H : p a then by simp only [mem_support_iff, filter_apply_pos _ _ H, mem_filter, H, and_true] else by simp only [mem_support_iff, filter_apply_neg _ _ H, mem_filter, H, and_false, ne.def, ne_self_iff_false] lemma filter_zero : (0 : α →₀ β).filter p = 0 := by rw [← support_eq_empty, support_filter, support_zero, finset.filter_empty] @[simp] lemma filter_single_of_pos {a : α} {b : β} (h : p a) : (single a b).filter p = single a b := ext $ λ x, begin by_cases h' : p x, { simp only [h', filter_apply_pos] }, { simp only [h', filter_apply_neg, not_false_iff], rw single_eq_of_ne, rintro rfl, exact h' h } end @[simp] lemma filter_single_of_neg {a : α} {b : β} (h : ¬ p a) : (single a b).filter p = 0 := ext $ λ x, begin by_cases h' : p x, { simp only [h', filter_apply_pos, zero_apply], rw single_eq_of_ne, rintro rfl, exact h h' }, { simp only [h', finsupp.zero_apply, not_false_iff, filter_apply_neg] } end end has_zero lemma filter_pos_add_filter_neg [add_monoid β] (f : α →₀ β) (p : α → Prop) : f.filter p + f.filter (λa, ¬ p a) = f := ext $ assume a, if H : p a then by simp only [add_apply, filter_apply_pos, filter_apply_neg, H, not_not, add_zero] else by simp only [add_apply, filter_apply_pos, filter_apply_neg, H, not_false_iff, zero_add] end filter /-! ### Declarations about `frange` -/ section frange variables [has_zero β] /-- `frange f` is the image of `f` on the support of `f`. -/ def frange (f : α →₀ β) : finset β := finset.image f f.support theorem mem_frange {f : α →₀ β} {y : β} : y ∈ f.frange ↔ y ≠ 0 ∧ ∃ x, f x = y := finset.mem_image.trans ⟨λ ⟨x, hx1, hx2⟩, ⟨hx2 ▸ mem_support_iff.1 hx1, x, hx2⟩, λ ⟨hy, x, hx⟩, ⟨x, mem_support_iff.2 (hx.symm ▸ hy), hx⟩⟩ theorem zero_not_mem_frange {f : α →₀ β} : (0:β) ∉ f.frange := λ H, (mem_frange.1 H).1 rfl theorem frange_single {x : α} {y : β} : frange (single x y) ⊆ {y} := λ r hr, let ⟨t, ht1, ht2⟩ := mem_frange.1 hr in ht2 ▸ (by rw single_apply at ht2 ⊢; split_ifs at ht2 ⊢; [exact finset.mem_singleton_self _, cc]) end frange /-! ### Declarations about `subtype_domain` -/ section subtype_domain variables {α' : Type*} [has_zero δ] {p : α → Prop} section zero variables [has_zero β] {v v' : α' →₀ β} /-- `subtype_domain p f` is the restriction of the finitely supported function `f` to the subtype `p`. -/ def subtype_domain (p : α → Prop) (f : α →₀ β) : (subtype p →₀ β) := ⟨f.support.subtype p, f ∘ subtype.val, λ a, by simp only [mem_subtype, mem_support_iff]⟩ @[simp] lemma support_subtype_domain {f : α →₀ β} : (subtype_domain p f).support = f.support.subtype p := rfl @[simp] lemma subtype_domain_apply {a : subtype p} {v : α →₀ β} : (subtype_domain p v) a = v (a.val) := rfl @[simp] lemma subtype_domain_zero : subtype_domain p (0 : α →₀ β) = 0 := rfl @[to_additive] lemma prod_subtype_domain_index [comm_monoid γ] {v : α →₀ β} {h : α → β → γ} (hp : ∀x∈v.support, p x) : (v.subtype_domain p).prod (λa b, h a.1 b) = v.prod h := prod_bij (λp _, p.val) (λ _, mem_subtype.1) (λ _ _, rfl) (λ _ _ _ _, subtype.eq) (λ b hb, ⟨⟨b, hp b hb⟩, mem_subtype.2 hb, rfl⟩) end zero section monoid variables [add_monoid β] {v v' : α' →₀ β} @[simp] lemma subtype_domain_add {v v' : α →₀ β} : (v + v').subtype_domain p = v.subtype_domain p + v'.subtype_domain p := ext $ λ _, rfl instance subtype_domain.is_add_monoid_hom : is_add_monoid_hom (subtype_domain p : (α →₀ β) → subtype p →₀ β) := { map_add := λ _ _, subtype_domain_add, map_zero := subtype_domain_zero } @[simp] lemma filter_add {v v' : α →₀ β} : (v + v').filter p = v.filter p + v'.filter p := ext $ λ a, begin by_cases p a, { simp only [h, filter_apply_pos, add_apply] }, { simp only [h, add_zero, add_apply, not_false_iff, filter_apply_neg] } end instance filter.is_add_monoid_hom (p : α → Prop) : is_add_monoid_hom (filter p : (α →₀ β) → (α →₀ β)) := { map_zero := filter_zero p, map_add := λ x y, filter_add } end monoid section comm_monoid variables [add_comm_monoid β] lemma subtype_domain_sum {s : finset γ} {h : γ → α →₀ β} : (∑ c in s, h c).subtype_domain p = ∑ c in s, (h c).subtype_domain p := eq.symm (s.sum_hom _) lemma subtype_domain_finsupp_sum {s : γ →₀ δ} {h : γ → δ → α →₀ β} : (s.sum h).subtype_domain p = s.sum (λc d, (h c d).subtype_domain p) := subtype_domain_sum lemma filter_sum (s : finset γ) (f : γ → α →₀ β) : (∑ a in s, f a).filter p = ∑ a in s, filter p (f a) := (s.sum_hom (filter p)).symm end comm_monoid section group variables [add_group β] {v v' : α' →₀ β} @[simp] lemma subtype_domain_neg {v : α →₀ β} : (- v).subtype_domain p = - v.subtype_domain p := ext $ λ _, rfl @[simp] lemma subtype_domain_sub {v v' : α →₀ β} : (v - v').subtype_domain p = v.subtype_domain p - v'.subtype_domain p := ext $ λ _, rfl end group end subtype_domain /-! ### Declarations relating `finsupp` to `multiset` -/ section multiset /-- Given `f : α →₀ ℕ`, `f.to_multiset` is the multiset with multiplicities given by the values of `f` on the elements of `α`. -/ def to_multiset (f : α →₀ ℕ) : multiset α := f.sum (λa n, n •ℕ {a}) lemma to_multiset_zero : (0 : α →₀ ℕ).to_multiset = 0 := rfl lemma to_multiset_add (m n : α →₀ ℕ) : (m + n).to_multiset = m.to_multiset + n.to_multiset := sum_add_index (assume a, zero_nsmul _) (assume a b₁ b₂, add_nsmul _ _ _) lemma to_multiset_single (a : α) (n : ℕ) : to_multiset (single a n) = n •ℕ {a} := by rw [to_multiset, sum_single_index]; apply zero_nsmul instance is_add_monoid_hom.to_multiset : is_add_monoid_hom (to_multiset : _ → multiset α) := { map_zero := to_multiset_zero, map_add := to_multiset_add } lemma card_to_multiset (f : α →₀ ℕ) : f.to_multiset.card = f.sum (λa, id) := begin refine f.induction _ _, { rw [to_multiset_zero, multiset.card_zero, sum_zero_index] }, { assume a n f _ _ ih, rw [to_multiset_add, multiset.card_add, ih, sum_add_index, to_multiset_single, sum_single_index, multiset.card_smul, multiset.singleton_eq_singleton, multiset.card_singleton, mul_one]; intros; refl } end lemma to_multiset_map (f : α →₀ ℕ) (g : α → β) : f.to_multiset.map g = (f.map_domain g).to_multiset := begin refine f.induction _ _, { rw [to_multiset_zero, multiset.map_zero, map_domain_zero, to_multiset_zero] }, { assume a n f _ _ ih, rw [to_multiset_add, multiset.map_add, ih, map_domain_add, map_domain_single, to_multiset_single, to_multiset_add, to_multiset_single, is_add_monoid_hom.map_nsmul (multiset.map g)], refl } end lemma prod_to_multiset [comm_monoid α] (f : α →₀ ℕ) : f.to_multiset.prod = f.prod (λa n, a ^ n) := begin refine f.induction _ _, { rw [to_multiset_zero, multiset.prod_zero, finsupp.prod_zero_index] }, { assume a n f _ _ ih, rw [to_multiset_add, multiset.prod_add, ih, to_multiset_single, finsupp.prod_add_index, finsupp.prod_single_index, multiset.prod_smul, multiset.singleton_eq_singleton, multiset.prod_singleton], { exact pow_zero a }, { exact pow_zero }, { exact pow_add } } end lemma to_finset_to_multiset (f : α →₀ ℕ) : f.to_multiset.to_finset = f.support := begin refine f.induction _ _, { rw [to_multiset_zero, multiset.to_finset_zero, support_zero] }, { assume a n f ha hn ih, rw [to_multiset_add, multiset.to_finset_add, ih, to_multiset_single, support_add_eq, support_single_ne_zero hn, multiset.to_finset_nsmul _ _ hn, multiset.singleton_eq_singleton, multiset.to_finset_cons, multiset.to_finset_zero], refl, refine disjoint.mono_left support_single_subset _, rwa [finset.singleton_disjoint] } end @[simp] lemma count_to_multiset (f : α →₀ ℕ) (a : α) : f.to_multiset.count a = f a := calc f.to_multiset.count a = f.sum (λx n, (n •ℕ {x} : multiset α).count a) : (f.support.sum_hom $ multiset.count a).symm ... = f.sum (λx n, n * ({x} : multiset α).count a) : by simp only [multiset.count_smul] ... = f.sum (λx n, n * (x :: 0 : multiset α).count a) : rfl ... = f a * (a :: 0 : multiset α).count a : sum_eq_single _ (λ a' _ H, by simp only [multiset.count_cons_of_ne (ne.symm H), multiset.count_zero, mul_zero]) (λ H, by simp only [not_mem_support_iff.1 H, zero_mul]) ... = f a : by simp only [multiset.count_singleton, mul_one] /-- Given `m : multiset α`, `of_multiset m` is the finitely supported function from `α` to `ℕ` given by the multiplicities of the elements of `α` in `m`. -/ def of_multiset (m : multiset α) : α →₀ ℕ := on_finset m.to_finset (λa, m.count a) $ λ a H, multiset.mem_to_finset.2 $ by_contradiction (mt multiset.count_eq_zero.2 H) @[simp] lemma of_multiset_apply (m : multiset α) (a : α) : of_multiset m a = m.count a := rfl /-- `equiv_multiset` defines an `equiv` between finitely supported functions from `α` to `ℕ` and multisets on `α`. -/ def equiv_multiset : (α →₀ ℕ) ≃ (multiset α) := ⟨ to_multiset, of_multiset, assume f, finsupp.ext $ λ a, by rw [of_multiset_apply, count_to_multiset], assume m, multiset.ext.2 $ λ a, by rw [count_to_multiset, of_multiset_apply] ⟩ lemma mem_support_multiset_sum [add_comm_monoid β] {s : multiset (α →₀ β)} (a : α) : a ∈ s.sum.support → ∃f∈s, a ∈ (f : α →₀ β).support := multiset.induction_on s false.elim begin assume f s ih ha, by_cases a ∈ f.support, { exact ⟨f, multiset.mem_cons_self _ _, h⟩ }, { simp only [multiset.sum_cons, mem_support_iff, add_apply, not_mem_support_iff.1 h, zero_add] at ha, rcases ih (mem_support_iff.2 ha) with ⟨f', h₀, h₁⟩, exact ⟨f', multiset.mem_cons_of_mem h₀, h₁⟩ } end lemma mem_support_finset_sum [add_comm_monoid β] {s : finset γ} {h : γ → α →₀ β} (a : α) (ha : a ∈ (∑ c in s, h c).support) : ∃c∈s, a ∈ (h c).support := let ⟨f, hf, hfa⟩ := mem_support_multiset_sum a ha in let ⟨c, hc, eq⟩ := multiset.mem_map.1 hf in ⟨c, hc, eq.symm ▸ hfa⟩ lemma mem_support_single [has_zero β] (a a' : α) (b : β) : a ∈ (single a' b).support ↔ a = a' ∧ b ≠ 0 := ⟨λ H : (a ∈ ite _ _ _), if h : b = 0 then by rw if_pos h at H; exact H.elim else ⟨by rw if_neg h at H; exact mem_singleton.1 H, h⟩, λ ⟨h1, h2⟩, show a ∈ ite _ _ _, by rw [if_neg h2]; exact mem_singleton.2 h1⟩ end multiset /-! ### Declarations about `curry` and `uncurry` -/ section curry_uncurry /-- Given a finitely supported function `f` from a product type `α × β` to `γ`, `curry f` is the "curried" finitely supported function from `α` to the type of finitely supported functions from `β` to `γ`. -/ protected def curry [add_comm_monoid γ] (f : (α × β) →₀ γ) : α →₀ (β →₀ γ) := f.sum $ λp c, single p.1 (single p.2 c) lemma sum_curry_index [add_comm_monoid γ] [add_comm_monoid δ] (f : (α × β) →₀ γ) (g : α → β → γ → δ) (hg₀ : ∀ a b, g a b 0 = 0) (hg₁ : ∀a b c₀ c₁, g a b (c₀ + c₁) = g a b c₀ + g a b c₁) : f.curry.sum (λa f, f.sum (g a)) = f.sum (λp c, g p.1 p.2 c) := begin rw [finsupp.curry], transitivity, { exact sum_sum_index (assume a, sum_zero_index) (assume a b₀ b₁, sum_add_index (assume a, hg₀ _ _) (assume c d₀ d₁, hg₁ _ _ _ _)) }, congr, funext p c, transitivity, { exact sum_single_index sum_zero_index }, exact sum_single_index (hg₀ _ _) end /-- Given a finitely supported function `f` from `α` to the type of finitely supported functions from `β` to `γ`, `uncurry f` is the "uncurried" finitely supported function from `α × β` to `γ`. -/ protected def uncurry [add_comm_monoid γ] (f : α →₀ (β →₀ γ)) : (α × β) →₀ γ := f.sum $ λa g, g.sum $ λb c, single (a, b) c /-- `finsupp_prod_equiv` defines the `equiv` between `((α × β) →₀ γ)` and `(α →₀ (β →₀ γ))` given by currying and uncurrying. -/ def finsupp_prod_equiv [add_comm_monoid γ] : ((α × β) →₀ γ) ≃ (α →₀ (β →₀ γ)) := by refine ⟨finsupp.curry, finsupp.uncurry, λ f, _, λ f, _⟩; simp only [ finsupp.curry, finsupp.uncurry, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, prod.mk.eta, (single_sum _ _ _).symm, sum_single] lemma filter_curry [add_comm_monoid β] (f : α₁ × α₂ →₀ β) (p : α₁ → Prop) : (f.filter (λa:α₁×α₂, p a.1)).curry = f.curry.filter p := begin rw [finsupp.curry, finsupp.curry, finsupp.sum, finsupp.sum, @filter_sum _ (α₂ →₀ β) _ p _ f.support _], rw [support_filter, sum_filter], refine finset.sum_congr rfl _, rintros ⟨a₁, a₂⟩ ha, dsimp only, split_ifs, { rw [filter_apply_pos, filter_single_of_pos]; exact h }, { rwa [filter_single_of_neg] } end lemma support_curry [add_comm_monoid β] (f : α₁ × α₂ →₀ β) : f.curry.support ⊆ f.support.image prod.fst := begin rw ← finset.bind_singleton, refine finset.subset.trans support_sum _, refine finset.bind_mono (assume a _, support_single_subset) end end curry_uncurry section variables [group γ] [mul_action γ α] [add_comm_monoid β] /-- Scalar multiplication by a group element g, given by precomposition with the action of g⁻¹ on the domain. -/ def comap_has_scalar : has_scalar γ (α →₀ β) := { smul := λ g f, f.comap_domain (λ a, g⁻¹ • a) (λ a a' m m' h, by simpa [←mul_smul] using (congr_arg (λ a, g • a) h)) } local attribute [instance] comap_has_scalar /-- Scalar multiplication by a group element, given by precomposition with the action of g⁻¹ on the domain, is multiplicative in g. -/ def comap_mul_action : mul_action γ (α →₀ β) := { one_smul := λ f, by { ext, dsimp [(•)], simp, }, mul_smul := λ g g' f, by { ext, dsimp [(•)], simp [mul_smul], }, } local attribute [instance] comap_mul_action /-- Scalar multiplication by a group element, given by precomposition with the action of g⁻¹ on the domain, is additive in the second argument. -/ def comap_distrib_mul_action : distrib_mul_action γ (α →₀ β) := { smul_zero := λ g, by { ext, dsimp [(•)], simp, }, smul_add := λ g f f', by { ext, dsimp [(•)], simp, }, } /-- Scalar multiplication by a group element on finitely supported functions on a group, given by precomposition with the action of g⁻¹. -/ def comap_distrib_mul_action_self : distrib_mul_action γ (γ →₀ β) := @finsupp.comap_distrib_mul_action γ β γ _ (mul_action.regular γ) _ @[simp] lemma comap_smul_single (g : γ) (a : α) (b : β) : g • single a b = single (g • a) b := begin ext a', dsimp [(•)], by_cases h : g • a = a', { subst h, simp [←mul_smul], }, { simp [single_eq_of_ne h], rw [single_eq_of_ne], rintro rfl, simpa [←mul_smul] using h, } end @[simp] lemma comap_smul_apply (g : γ) (f : α →₀ β) (a : α) : (g • f) a = f (g⁻¹ • a) := rfl end section instance [semiring γ] [add_comm_monoid β] [semimodule γ β] : has_scalar γ (α →₀ β) := ⟨λa v, v.map_range ((•) a) (smul_zero _)⟩ variables (α β) @[simp] lemma smul_apply' {R:semiring γ} [add_comm_monoid β] [semimodule γ β] {a : α} {b : γ} {v : α →₀ β} : (b • v) a = b • (v a) := rfl instance [semiring γ] [add_comm_monoid β] [semimodule γ β] : semimodule γ (α →₀ β) := { smul := (•), smul_add := λ a x y, ext $ λ _, smul_add _ _ _, add_smul := λ a x y, ext $ λ _, add_smul _ _ _, one_smul := λ x, ext $ λ _, one_smul _ _, mul_smul := λ r s x, ext $ λ _, mul_smul _ _ _, zero_smul := λ x, ext $ λ _, zero_smul _ _, smul_zero := λ x, ext $ λ _, smul_zero _ } variables {α β} (γ) /-- Evaluation at point as a linear map. This version assumes that the codomain is a semimodule over some semiring. See also `leval`. -/ def leval' [semiring γ] [add_comm_monoid β] [semimodule γ β] (a : α) : (α →₀ β) →ₗ[γ] β := ⟨λ g, g a, λ _ _, add_apply, λ _ _, rfl⟩ @[simp] lemma coe_leval' [semiring γ] [add_comm_monoid β] [semimodule γ β] (a : α) (g : α →₀ β) : leval' γ a g = g a := rfl variable {γ} /-- Evaluation at point as a linear map. This version assumes that the codomain is a semiring. -/ def leval [semiring β] (a : α) : (α →₀ β) →ₗ[β] β := leval' β a @[simp] lemma coe_leval [semiring β] (a : α) (g : α →₀ β) : leval a g = g a := rfl lemma support_smul {R:semiring γ} [add_comm_monoid β] [semimodule γ β] {b : γ} {g : α →₀ β} : (b • g).support ⊆ g.support := λ a, by simp only [smul_apply', mem_support_iff, ne.def]; exact mt (λ h, h.symm ▸ smul_zero _) section variables {α' : Type*} [has_zero δ] {p : α → Prop} @[simp] lemma filter_smul {R : semiring γ} [add_comm_monoid β] [semimodule γ β] {b : γ} {v : α →₀ β} : (b • v).filter p = b • v.filter p := ext $ λ a, begin by_cases p a, { simp only [h, smul_apply', filter_apply_pos] }, { simp only [h, smul_apply', not_false_iff, filter_apply_neg, smul_zero] } end end lemma map_domain_smul {α'} {R : semiring γ} [add_comm_monoid β] [semimodule γ β] {f : α → α'} (b : γ) (v : α →₀ β) : map_domain f (b • v) = b • map_domain f v := begin change map_domain f (map_range _ _ _) = map_range _ _ _, apply finsupp.induction v, { simp only [map_domain_zero, map_range_zero] }, intros a b v' hv₁ hv₂ IH, rw [map_range_add, map_domain_add, IH, map_domain_add, map_range_add, map_range_single, map_domain_single, map_domain_single, map_range_single]; apply smul_add end @[simp] lemma smul_single {R : semiring γ} [add_comm_monoid β] [semimodule γ β] (c : γ) (a : α) (b : β) : c • finsupp.single a b = finsupp.single a (c • b) := ext $ λ a', by by_cases a = a'; [{ subst h, simp only [smul_apply', single_eq_same] }, simp only [h, smul_apply', ne.def, not_false_iff, single_eq_of_ne, smul_zero]] @[simp] lemma smul_single' {R : semiring γ} (c : γ) (a : α) (b : γ) : c • finsupp.single a b = finsupp.single a (c * b) := smul_single _ _ _ end @[simp] lemma smul_apply [semiring β] {a : α} {b : β} {v : α →₀ β} : (b • v) a = b • (v a) := rfl lemma sum_smul_index [semiring β] [add_comm_monoid γ] {g : α →₀ β} {b : β} {h : α → β → γ} (h0 : ∀i, h i 0 = 0) : (b • g).sum h = g.sum (λi a, h i (b * a)) := finsupp.sum_map_range_index h0 lemma sum_smul_index' [semiring β] [add_comm_monoid γ] [semimodule β γ] [add_comm_monoid δ] {g : α →₀ γ} {b : β} {h : α → γ → δ} (h0 : ∀i, h i 0 = 0) : (b • g).sum h = g.sum (λi c, h i (b • c)) := finsupp.sum_map_range_index h0 section variables [semiring β] [semiring γ] lemma sum_mul (b : γ) (s : α →₀ β) {f : α → β → γ} : (s.sum f) * b = s.sum (λ a c, (f a (s a)) * b) := by simp only [finsupp.sum, finset.sum_mul] lemma mul_sum (b : γ) (s : α →₀ β) {f : α → β → γ} : b * (s.sum f) = s.sum (λ a c, b * (f a (s a))) := by simp only [finsupp.sum, finset.mul_sum] protected lemma eq_zero_of_zero_eq_one (zero_eq_one : (0 : β) = 1) (l : α →₀ β) : l = 0 := by ext i; simp only [eq_zero_of_zero_eq_one zero_eq_one (l i), finsupp.zero_apply] end /-- Given an `add_comm_monoid β` and `s : set α`, `restrict_support_equiv s β` is the `equiv` between the subtype of finitely supported functions with support contained in `s` and the type of finitely supported functions from `s`. -/ def restrict_support_equiv (s : set α) (β : Type*) [add_comm_monoid β] : {f : α →₀ β // ↑f.support ⊆ s } ≃ (s →₀ β):= begin refine ⟨λf, subtype_domain (λx, x ∈ s) f.1, λ f, ⟨f.map_domain subtype.val, _⟩, _, _⟩, { refine set.subset.trans (finset.coe_subset.2 map_domain_support) _, rw [finset.coe_image, set.image_subset_iff], exact assume x hx, x.2 }, { rintros ⟨f, hf⟩, apply subtype.eq, ext a, dsimp only, refine classical.by_cases (assume h : a ∈ set.range (subtype.val : s → α), _) (assume h, _), { rcases h with ⟨x, rfl⟩, rw [map_domain_apply subtype.val_injective, subtype_domain_apply] }, { convert map_domain_notin_range _ _ h, rw [← not_mem_support_iff], refine mt _ h, exact assume ha, ⟨⟨a, hf ha⟩, rfl⟩ } }, { assume f, ext ⟨a, ha⟩, dsimp only, rw [subtype_domain_apply, map_domain_apply subtype.val_injective] } end /-- Given `add_comm_monoid β` and `e : α₁ ≃ α₂`, `dom_congr e` is the corresponding `equiv` between `α₁ →₀ β` and `α₂ →₀ β`. -/ protected def dom_congr [add_comm_monoid β] (e : α₁ ≃ α₂) : (α₁ →₀ β) ≃ (α₂ →₀ β) := ⟨map_domain e, map_domain e.symm, begin assume v, simp only [map_domain_comp.symm, (∘), equiv.symm_apply_apply], exact map_domain_id end, begin assume v, simp only [map_domain_comp.symm, (∘), equiv.apply_symm_apply], exact map_domain_id end⟩ /-! ### Declarations about sigma types -/ section sigma variables {αs : ι → Type*} [has_zero β] (l : (Σ i, αs i) →₀ β) /-- Given `l`, a finitely supported function from the sigma type `Σ (i : ι), αs i` to `β` and an index element `i : ι`, `split l i` is the `i`th component of `l`, a finitely supported function from `as i` to `β`. -/ def split (i : ι) : αs i →₀ β := l.comap_domain (sigma.mk i) (λ x1 x2 _ _ hx, heq_iff_eq.1 (sigma.mk.inj hx).2) lemma split_apply (i : ι) (x : αs i) : split l i x = l ⟨i, x⟩ := begin dunfold split, rw comap_domain_apply end /-- Given `l`, a finitely supported function from the sigma type `Σ (i : ι), αs i` to `β`, `split_support l` is the finset of indices in `ι` that appear in the support of `l`. -/ def split_support : finset ι := l.support.image sigma.fst lemma mem_split_support_iff_nonzero (i : ι) : i ∈ split_support l ↔ split l i ≠ 0 := begin rw [split_support, mem_image, ne.def, ← support_eq_empty, ← ne.def, ← finset.nonempty_iff_ne_empty, split, comap_domain, finset.nonempty], simp only [exists_prop, finset.mem_preimage, exists_and_distrib_right, exists_eq_right, mem_support_iff, sigma.exists, ne.def] end /-- Given `l`, a finitely supported function from the sigma type `Σ i, αs i` to `β` and an `ι`-indexed family `g` of functions from `(αs i →₀ β)` to `γ`, `split_comp` defines a finitely supported function from the index type `ι` to `γ` given by composing `g i` with `split l i`. -/ def split_comp [has_zero γ] (g : Π i, (αs i →₀ β) → γ) (hg : ∀ i x, x = 0 ↔ g i x = 0) : ι →₀ γ := { support := split_support l, to_fun := λ i, g i (split l i), mem_support_to_fun := begin intros i, rw [mem_split_support_iff_nonzero, not_iff_not, hg], end } lemma sigma_support : l.support = l.split_support.sigma (λ i, (l.split i).support) := by simp only [finset.ext_iff, split_support, split, comap_domain, mem_image, mem_preimage, sigma.forall, mem_sigma]; tauto lemma sigma_sum [add_comm_monoid γ] (f : (Σ (i : ι), αs i) → β → γ) : l.sum f = ∑ i in split_support l, (split l i).sum (λ (a : αs i) b, f ⟨i, a⟩ b) := by simp only [sum, sigma_support, sum_sigma, split_apply] end sigma end finsupp /-! ### Declarations relating `multiset` to `finsupp` -/ namespace multiset /-- Given a multiset `s`, `s.to_finsupp` returns the finitely supported function on `ℕ` given by the multiplicities of the elements of `s`. -/ def to_finsupp (s : multiset α) : α →₀ ℕ := { support := s.to_finset, to_fun := λ a, s.count a, mem_support_to_fun := λ a, begin rw mem_to_finset, convert not_iff_not_of_iff (count_eq_zero.symm), rw not_not end } @[simp] lemma to_finsupp_support (s : multiset α) : s.to_finsupp.support = s.to_finset := rfl @[simp] lemma to_finsupp_apply (s : multiset α) (a : α) : s.to_finsupp a = s.count a := rfl @[simp] lemma to_finsupp_zero : to_finsupp (0 : multiset α) = 0 := finsupp.ext $ λ a, count_zero a @[simp] lemma to_finsupp_add (s t : multiset α) : to_finsupp (s + t) = to_finsupp s + to_finsupp t := finsupp.ext $ λ a, count_add a s t lemma to_finsupp_singleton (a : α) : to_finsupp {a} = finsupp.single a 1 := finsupp.ext $ λ b, if h : a = b then by rw [to_finsupp_apply, finsupp.single_apply, h, if_pos rfl, singleton_eq_singleton, count_singleton] else begin rw [to_finsupp_apply, finsupp.single_apply, if_neg h, count_eq_zero, singleton_eq_singleton, mem_singleton], rintro rfl, exact h rfl end namespace to_finsupp instance : is_add_monoid_hom (to_finsupp : multiset α → α →₀ ℕ) := { map_zero := to_finsupp_zero, map_add := to_finsupp_add } end to_finsupp @[simp] lemma to_finsupp_to_multiset (s : multiset α) : s.to_finsupp.to_multiset = s := ext.2 $ λ a, by rw [finsupp.count_to_multiset, to_finsupp_apply] end multiset /-! ### Declarations about order(ed) instances on `finsupp` -/ namespace finsupp variables {σ : Type*} instance [preorder α] [has_zero α] : preorder (σ →₀ α) := { le := λ f g, ∀ s, f s ≤ g s, le_refl := λ f s, le_refl _, le_trans := λ f g h Hfg Hgh s, le_trans (Hfg s) (Hgh s) } instance [partial_order α] [has_zero α] : partial_order (σ →₀ α) := { le_antisymm := λ f g hfg hgf, ext $ λ s, le_antisymm (hfg s) (hgf s), .. finsupp.preorder } instance [ordered_cancel_add_comm_monoid α] : add_left_cancel_semigroup (σ →₀ α) := { add_left_cancel := λ a b c h, ext $ λ s, by { rw ext_iff at h, exact add_left_cancel (h s) }, .. finsupp.add_monoid } instance [ordered_cancel_add_comm_monoid α] : add_right_cancel_semigroup (σ →₀ α) := { add_right_cancel := λ a b c h, ext $ λ s, by { rw ext_iff at h, exact add_right_cancel (h s) }, .. finsupp.add_monoid } instance [ordered_cancel_add_comm_monoid α] : ordered_cancel_add_comm_monoid (σ →₀ α) := { add_le_add_left := λ a b h c s, add_le_add_left (h s) (c s), le_of_add_le_add_left := λ a b c h s, le_of_add_le_add_left (h s), .. finsupp.add_comm_monoid, .. finsupp.partial_order, .. finsupp.add_left_cancel_semigroup, .. finsupp.add_right_cancel_semigroup } lemma le_iff [canonically_ordered_add_monoid α] (f g : σ →₀ α) : f ≤ g ↔ ∀ s ∈ f.support, f s ≤ g s := ⟨λ h s hs, h s, λ h s, if H : s ∈ f.support then h s H else (not_mem_support_iff.1 H).symm ▸ zero_le (g s)⟩ @[simp] lemma add_eq_zero_iff [canonically_ordered_add_monoid α] (f g : σ →₀ α) : f + g = 0 ↔ f = 0 ∧ g = 0 := begin split, { assume h, split, all_goals { ext s, suffices H : f s + g s = 0, { rw add_eq_zero_iff at H, cases H, assumption }, show (f + g) s = 0, rw h, refl } }, { rintro ⟨rfl, rfl⟩, rw add_zero } end attribute [simp] to_multiset_zero to_multiset_add @[simp] lemma to_multiset_to_finsupp (f : σ →₀ ℕ) : f.to_multiset.to_finsupp = f := ext $ λ s, by rw [multiset.to_finsupp_apply, count_to_multiset] lemma to_multiset_strict_mono : strict_mono (@to_multiset σ) := λ m n h, begin rw lt_iff_le_and_ne at h ⊢, cases h with h₁ h₂, split, { rw multiset.le_iff_count, intro s, erw [count_to_multiset m s, count_to_multiset], exact h₁ s }, { intro H, apply h₂, replace H := congr_arg multiset.to_finsupp H, simpa only [to_multiset_to_finsupp] using H } end lemma sum_id_lt_of_lt (m n : σ →₀ ℕ) (h : m < n) : m.sum (λ _, id) < n.sum (λ _, id) := begin rw [← card_to_multiset, ← card_to_multiset], apply multiset.card_lt_of_lt, exact to_multiset_strict_mono h end variable (σ) /-- The order on `σ →₀ ℕ` is well-founded.-/ lemma lt_wf : well_founded (@has_lt.lt (σ →₀ ℕ) _) := subrelation.wf (sum_id_lt_of_lt) $ inv_image.wf _ nat.lt_wf instance decidable_le : decidable_rel (@has_le.le (σ →₀ ℕ) _) := λ m n, by rw le_iff; apply_instance variable {σ} /-- The `finsupp` counterpart of `multiset.antidiagonal`: the antidiagonal of `s : σ →₀ ℕ` consists of all pairs `(t₁, t₂) : (σ →₀ ℕ) × (σ →₀ ℕ)` such that `t₁ + t₂ = s`. The finitely supported function `antidiagonal s` is equal to the multiplicities of these pairs. -/ def antidiagonal (f : σ →₀ ℕ) : ((σ →₀ ℕ) × (σ →₀ ℕ)) →₀ ℕ := (f.to_multiset.antidiagonal.map (prod.map multiset.to_finsupp multiset.to_finsupp)).to_finsupp lemma mem_antidiagonal_support {f : σ →₀ ℕ} {p : (σ →₀ ℕ) × (σ →₀ ℕ)} : p ∈ (antidiagonal f).support ↔ p.1 + p.2 = f := begin erw [multiset.mem_to_finset, multiset.mem_map], split, { rintros ⟨⟨a, b⟩, h, rfl⟩, rw multiset.mem_antidiagonal at h, simpa only [to_multiset_to_finsupp, multiset.to_finsupp_add] using congr_arg multiset.to_finsupp h}, { intro h, refine ⟨⟨p.1.to_multiset, p.2.to_multiset⟩, _, _⟩, { simpa only [multiset.mem_antidiagonal, to_multiset_add] using congr_arg to_multiset h}, { rw [prod.map, to_multiset_to_finsupp, to_multiset_to_finsupp, prod.mk.eta] } } end @[simp] lemma antidiagonal_zero : antidiagonal (0 : σ →₀ ℕ) = single (0,0) 1 := by rw [← multiset.to_finsupp_singleton]; refl lemma swap_mem_antidiagonal_support {n : σ →₀ ℕ} {f} (hf : f ∈ (antidiagonal n).support) : f.swap ∈ (antidiagonal n).support := by simpa only [mem_antidiagonal_support, add_comm, prod.swap] using hf /-- Let `n : σ →₀ ℕ` be a finitely supported function. The set of `m : σ →₀ ℕ` that are coordinatewise less than or equal to `n`, is a finite set. -/ lemma finite_le_nat (n : σ →₀ ℕ) : set.finite {m | m ≤ n} := begin let I := {i // i ∈ n.support}, let k : ℕ := ∑ i in n.support, n i, let f : (σ →₀ ℕ) → (I → fin (k + 1)) := λ m i, m i, have hf : ∀ m ≤ n, ∀ i, (f m i : ℕ) = m i, { intros m hm i, apply fin.coe_coe_of_lt, calc m i ≤ n i : hm i ... < k + 1 : nat.lt_succ_iff.mpr (single_le_sum (λ _ _, nat.zero_le _) i.2) }, have f_im : set.finite (f '' {m | m ≤ n}) := set.finite.of_fintype _, suffices f_inj : set.inj_on f {m | m ≤ n}, { exact set.finite_of_finite_image f_inj f_im }, intros m₁ h₁ m₂ h₂ h, ext i, by_cases hi : i ∈ n.support, { replace h := congr_fun h ⟨i, hi⟩, rwa [fin.ext_iff, ← fin.coe_eq_val, ← fin.coe_eq_val, hf m₁ h₁, hf m₂ h₂] at h }, { rw not_mem_support_iff at hi, specialize h₁ i, specialize h₂ i, rw [hi, nat.le_zero_iff] at h₁ h₂, rw [h₁, h₂] } end /-- Let `n : σ →₀ ℕ` be a finitely supported function. The set of `m : σ →₀ ℕ` that are coordinatewise less than or equal to `n`, but not equal to `n` everywhere, is a finite set. -/ lemma finite_lt_nat (n : σ →₀ ℕ) : set.finite {m | m < n} := (finite_le_nat n).subset $ λ m, le_of_lt end finsupp
08cabe737bd636ec0af081bfceb52d38e0a932a4
37da0369b6c03e380e057bf680d81e6c9fdf9219
/hott/types/sigma.hlean
a5f52a8fcc8bb8e87d155d8967ac3fc5ed1746c9
[ "Apache-2.0" ]
permissive
kodyvajjha/lean2
72b120d95c3a1d77f54433fa90c9810e14a931a4
227fcad22ab2bc27bb7471be7911075d101ba3f9
refs/heads/master
1,627,157,512,295
1,501,855,676,000
1,504,809,427,000
109,317,326
0
0
null
1,509,839,253,000
1,509,655,713,000
C++
UTF-8
Lean
false
false
23,523
hlean
/- Copyright (c) 2014-15 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Partially ported from Coq HoTT Theorems about sigma-types (dependent sums) -/ import types.prod open eq sigma sigma.ops equiv is_equiv function is_trunc sum unit namespace sigma variables {A A' : Type} {B : A → Type} {B' : A' → Type} {C : Πa, B a → Type} {D : Πa b, C a b → Type} {a a' a'' : A} {b b₁ b₂ : B a} {b' : B a'} {b'' : B a''} {u v w : Σa, B a} definition destruct := @sigma.cases_on /- Paths in a sigma-type -/ protected definition eta [unfold 3] : Π (u : Σa, B a), ⟨u.1 , u.2⟩ = u | eta ⟨u₁, u₂⟩ := idp definition eta2 : Π (u : Σa b, C a b), ⟨u.1, u.2.1, u.2.2⟩ = u | eta2 ⟨u₁, u₂, u₃⟩ := idp definition eta3 : Π (u : Σa b c, D a b c), ⟨u.1, u.2.1, u.2.2.1, u.2.2.2⟩ = u | eta3 ⟨u₁, u₂, u₃, u₄⟩ := idp definition dpair_eq_dpair [unfold 8] (p : a = a') (q : b =[p] b') : ⟨a, b⟩ = ⟨a', b'⟩ := apd011 sigma.mk p q definition sigma_eq [unfold 5 6] (p : u.1 = v.1) (q : u.2 =[p] v.2) : u = v := by induction u; induction v; exact (dpair_eq_dpair p q) definition sigma_eq_right [unfold 6] (q : b₁ = b₂) : ⟨a, b₁⟩ = ⟨a, b₂⟩ := ap (dpair a) q definition eq_pr1 [unfold 5] (p : u = v) : u.1 = v.1 := ap pr1 p postfix `..1`:(max+1) := eq_pr1 definition eq_pr2 [unfold 5] (p : u = v) : u.2 =[p..1] v.2 := by induction p; exact idpo postfix `..2`:(max+1) := eq_pr2 definition dpair_sigma_eq (p : u.1 = v.1) (q : u.2 =[p] v.2) : ⟨(sigma_eq p q)..1, (sigma_eq p q)..2⟩ = ⟨p, q⟩ := by induction u; induction v;esimp at *;induction q;esimp definition sigma_eq_pr1 (p : u.1 = v.1) (q : u.2 =[p] v.2) : (sigma_eq p q)..1 = p := (dpair_sigma_eq p q)..1 definition sigma_eq_pr2 (p : u.1 = v.1) (q : u.2 =[p] v.2) : (sigma_eq p q)..2 =[sigma_eq_pr1 p q] q := (dpair_sigma_eq p q)..2 definition sigma_eq_eta (p : u = v) : sigma_eq (p..1) (p..2) = p := by induction p; induction u; reflexivity definition eq2_pr1 {p q : u = v} (r : p = q) : p..1 = q..1 := ap eq_pr1 r definition eq2_pr2 {p q : u = v} (r : p = q) : p..2 =[eq2_pr1 r] q..2 := !pathover_ap (apd eq_pr2 r) definition tr_pr1_sigma_eq {B' : A → Type} (p : u.1 = v.1) (q : u.2 =[p] v.2) : transport (λx, B' x.1) (sigma_eq p q) = transport B' p := by induction u; induction v; esimp at *;induction q; reflexivity protected definition ap_pr1 (p : u = v) : ap (λx : sigma B, x.1) p = p..1 := idp /- the uncurried version of sigma_eq. We will prove that this is an equivalence -/ definition sigma_eq_unc [unfold 5] : Π (pq : Σ(p : u.1 = v.1), u.2 =[p] v.2), u = v | sigma_eq_unc ⟨pq₁, pq₂⟩ := sigma_eq pq₁ pq₂ definition dpair_sigma_eq_unc : Π (pq : Σ(p : u.1 = v.1), u.2 =[p] v.2), ⟨(sigma_eq_unc pq)..1, (sigma_eq_unc pq)..2⟩ = pq | dpair_sigma_eq_unc ⟨pq₁, pq₂⟩ := dpair_sigma_eq pq₁ pq₂ definition sigma_eq_pr1_unc (pq : Σ(p : u.1 = v.1), u.2 =[p] v.2) : (sigma_eq_unc pq)..1 = pq.1 := (dpair_sigma_eq_unc pq)..1 definition sigma_eq_pr2_unc (pq : Σ(p : u.1 = v.1), u.2 =[p] v.2) : (sigma_eq_unc pq)..2 =[sigma_eq_pr1_unc pq] pq.2 := (dpair_sigma_eq_unc pq)..2 definition sigma_eq_eta_unc (p : u = v) : sigma_eq_unc ⟨p..1, p..2⟩ = p := sigma_eq_eta p definition tr_sigma_eq_pr1_unc {B' : A → Type} (pq : Σ(p : u.1 = v.1), u.2 =[p] v.2) : transport (λx, B' x.1) (@sigma_eq_unc A B u v pq) = transport B' pq.1 := destruct pq tr_pr1_sigma_eq definition is_equiv_sigma_eq [instance] [constructor] (u v : Σa, B a) : is_equiv (@sigma_eq_unc A B u v) := adjointify sigma_eq_unc (λp, ⟨p..1, p..2⟩) sigma_eq_eta_unc dpair_sigma_eq_unc definition sigma_eq_equiv [constructor] (u v : Σa, B a) : (u = v) ≃ (Σ(p : u.1 = v.1), u.2 =[p] v.2) := (equiv.mk sigma_eq_unc _)⁻¹ᵉ definition dpair_eq_dpair_con (p1 : a = a' ) (q1 : b =[p1] b' ) (p2 : a' = a'') (q2 : b' =[p2] b'') : dpair_eq_dpair (p1 ⬝ p2) (q1 ⬝o q2) = dpair_eq_dpair p1 q1 ⬝ dpair_eq_dpair p2 q2 := by induction q1; induction q2; reflexivity definition sigma_eq_con (p1 : u.1 = v.1) (q1 : u.2 =[p1] v.2) (p2 : v.1 = w.1) (q2 : v.2 =[p2] w.2) : sigma_eq (p1 ⬝ p2) (q1 ⬝o q2) = sigma_eq p1 q1 ⬝ sigma_eq p2 q2 := by induction u; induction v; induction w; apply dpair_eq_dpair_con local attribute dpair_eq_dpair [reducible] definition dpair_eq_dpair_con_idp (p : a = a') (q : b =[p] b') : dpair_eq_dpair p q = dpair_eq_dpair p !pathover_tr ⬝ dpair_eq_dpair idp (pathover_idp_of_eq (tr_eq_of_pathover q)) := by induction q; reflexivity /- eq_pr1 commutes with the groupoid structure. -/ definition eq_pr1_idp (u : Σa, B a) : (refl u) ..1 = refl (u.1) := idp definition eq_pr1_con (p : u = v) (q : v = w) : (p ⬝ q) ..1 = (p..1) ⬝ (q..1) := !ap_con definition eq_pr1_inv (p : u = v) : p⁻¹ ..1 = (p..1)⁻¹ := !ap_inv /- Applying dpair to one argument is the same as dpair_eq_dpair with reflexivity in the first place. -/ definition ap_dpair (q : b₁ = b₂) : ap (sigma.mk a) q = dpair_eq_dpair idp (pathover_idp_of_eq q) := by induction q; reflexivity /- Dependent transport is the same as transport along a sigma_eq. -/ definition transportD_eq_transport (p : a = a') (c : C a b) : p ▸D c = transport (λu, C (u.1) (u.2)) (dpair_eq_dpair p !pathover_tr) c := by induction p; reflexivity definition sigma_eq_eq_sigma_eq {p1 q1 : a = a'} {p2 : b =[p1] b'} {q2 : b =[q1] b'} (r : p1 = q1) (s : p2 =[r] q2) : sigma_eq p1 p2 = sigma_eq q1 q2 := by induction s; reflexivity /- A path between paths in a total space is commonly shown component wise. -/ definition sigma_eq2 {p q : u = v} (r : p..1 = q..1) (s : p..2 =[r] q..2) : p = q := begin induction p, induction u with u1 u2, transitivity sigma_eq q..1 q..2, apply sigma_eq_eq_sigma_eq r s, apply sigma_eq_eta, end definition sigma_eq2_unc {p q : u = v} (rs : Σ(r : p..1 = q..1), p..2 =[r] q..2) : p = q := destruct rs sigma_eq2 definition ap_dpair_eq_dpair (f : Πa, B a → A') (p : a = a') (q : b =[p] b') : ap (sigma.rec f) (dpair_eq_dpair p q) = apd011 f p q := by induction q; reflexivity /- Transport -/ /- The concrete description of transport in sigmas (and also pis) is rather trickier than in the other types. In particular, these cannot be described just in terms of transport in simpler types; they require also the dependent transport [transportD]. In particular, this indicates why `transport` alone cannot be fully defined by induction on the structure of types, although Id-elim/transportD can be (cf. Observational Type Theory). A more thorough set of lemmas, along the lines of the present ones but dealing with Id-elim rather than just transport, might be nice to have eventually? -/ definition sigma_transport (p : a = a') (bc : Σ(b : B a), C a b) : p ▸ bc = ⟨p ▸ bc.1, p ▸D bc.2⟩ := by induction p; induction bc; reflexivity /- The special case when the second variable doesn't depend on the first is simpler. -/ definition sigma_transport_nondep {B : Type} {C : A → B → Type} (p : a = a') (bc : Σ(b : B), C a b) : p ▸ bc = ⟨bc.1, p ▸ bc.2⟩ := by induction p; induction bc; reflexivity /- Or if the second variable contains a first component that doesn't depend on the first. -/ definition sigma_transport2_nondep {C : A → Type} {D : Π a:A, B a → C a → Type} (p : a = a') (bcd : Σ(b : B a) (c : C a), D a b c) : p ▸ bcd = ⟨p ▸ bcd.1, p ▸ bcd.2.1, p ▸D2 bcd.2.2⟩ := begin induction p, induction bcd with b cd, induction cd, reflexivity end /- Pathovers -/ definition etao (p : a = a') (bc : Σ(b : B a), C a b) : bc =[p] ⟨p ▸ bc.1, p ▸D bc.2⟩ := by induction p; induction bc; apply idpo -- TODO: interchange sigma_pathover and sigma_pathover' definition sigma_pathover (p : a = a') (u : Σ(b : B a), C a b) (v : Σ(b : B a'), C a' b) (r : u.1 =[p] v.1) (s : u.2 =[apd011 C p r] v.2) : u =[p] v := begin induction u, induction v, esimp at *, induction r, esimp [apd011] at s, induction s using idp_rec_on, apply idpo end definition sigma_pathover' (p : a = a') (u : Σ(b : B a), C a b) (v : Σ(b : B a'), C a' b) (r : u.1 =[p] v.1) (s : pathover (λx, C x.1 x.2) u.2 (sigma_eq p r) v.2) : u =[p] v := begin induction u, induction v, esimp at *, induction r, induction s using idp_rec_on, apply idpo end definition sigma_pathover_nondep {B : Type} {C : A → B → Type} (p : a = a') (u : Σ(b : B), C a b) (v : Σ(b : B), C a' b) (r : u.1 = v.1) (s : pathover (λx, C (prod.pr1 x) (prod.pr2 x)) u.2 (prod.prod_eq p r) v.2) : u =[p] v := begin induction p, induction u, induction v, esimp at *, induction r, induction s using idp_rec_on, apply idpo end definition pathover_pr1 [unfold 9] {A : Type} {B : A → Type} {C : Πa, B a → Type} {a a' : A} {p : a = a'} {x : Σb, C a b} {x' : Σb', C a' b'} (q : x =[p] x') : x.1 =[p] x'.1 := begin induction q, constructor end definition sigma_pathover_equiv_of_is_prop {A : Type} {B : A → Type} (C : Πa, B a → Type) {a a' : A} (p : a = a') (x : Σb, C a b) (x' : Σb', C a' b') [Πa b, is_prop (C a b)] : x =[p] x' ≃ x.1 =[p] x'.1 := begin fapply equiv.MK, { exact pathover_pr1 }, { intro q, induction x with b c, induction x' with b' c', esimp at q, induction q, apply pathover_idp_of_eq, exact sigma_eq idp !is_prop.elimo }, { intro q, induction x with b c, induction x' with b' c', esimp at q, induction q, have c = c', from !is_prop.elim, induction this, rewrite [▸*, is_prop_elimo_self (C a) c] }, { intro q, induction q, induction x with b c, rewrite [▸*, is_prop_elimo_self (C a) c] } end /- TODO: * define the projections from the type u =[p] v * show that the uncurried version of sigma_pathover is an equivalence -/ /- Squares in a sigma type are characterized in cubical.squareover (to avoid circular imports) -/ /- Functorial action -/ variables (f : A → A') (g : Πa, B a → B' (f a)) definition sigma_functor [unfold 7] (u : Σa, B a) : Σa', B' a' := ⟨f u.1, g u.1 u.2⟩ definition total [reducible] [unfold 5] {B' : A → Type} (g : Πa, B a → B' a) : (Σa, B a) → (Σa, B' a) := sigma_functor id g /- Equivalences -/ definition is_equiv_sigma_functor [constructor] [H1 : is_equiv f] [H2 : Π a, is_equiv (g a)] : is_equiv (sigma_functor f g) := adjointify (sigma_functor f g) (sigma_functor f⁻¹ (λ(a' : A') (b' : B' a'), ((g (f⁻¹ a'))⁻¹ (transport B' (right_inv f a')⁻¹ b')))) abstract begin intro u', induction u' with a' b', apply sigma_eq (right_inv f a'), rewrite [▸*,right_inv (g (f⁻¹ a')),▸*], apply tr_pathover end end abstract begin intro u, induction u with a b, apply (sigma_eq (left_inv f a)), apply pathover_of_tr_eq, rewrite [▸*,adj f,-(fn_tr_eq_tr_fn (left_inv f a) (λ a, (g a)⁻¹)), ▸*,tr_compose B' f,tr_inv_tr,left_inv] end end definition sigma_equiv_sigma_of_is_equiv [constructor] [H1 : is_equiv f] [H2 : Π a, is_equiv (g a)] : (Σa, B a) ≃ (Σa', B' a') := equiv.mk (sigma_functor f g) !is_equiv_sigma_functor definition sigma_equiv_sigma [constructor] (Hf : A ≃ A') (Hg : Π a, B a ≃ B' (to_fun Hf a)) : (Σa, B a) ≃ (Σa', B' a') := sigma_equiv_sigma_of_is_equiv (to_fun Hf) (λ a, to_fun (Hg a)) definition sigma_equiv_sigma_right [constructor] {B' : A → Type} (Hg : Π a, B a ≃ B' a) : (Σa, B a) ≃ Σa, B' a := sigma_equiv_sigma equiv.rfl Hg definition sigma_equiv_sigma_left [constructor] (Hf : A ≃ A') : (Σa, B a) ≃ (Σa', B (to_inv Hf a')) := sigma_equiv_sigma Hf (λ a, equiv_ap B !right_inv⁻¹) definition sigma_equiv_sigma_left' [constructor] (Hf : A' ≃ A) : (Σa, B (Hf a)) ≃ (Σa', B a') := sigma_equiv_sigma Hf (λa, erfl) definition ap_sigma_functor_eq_dpair (p : a = a') (q : b =[p] b') : ap (sigma_functor f g) (sigma_eq p q) = sigma_eq (ap f p) (pathover.rec_on q idpo) := by induction q; reflexivity definition sigma_ua {A B : Type} (C : A ≃ B → Type) : (Σ(p : A = B), C (equiv_of_eq p)) ≃ Σ(e : A ≃ B), C e := sigma_equiv_sigma_left' !eq_equiv_equiv -- definition ap_sigma_functor_eq (p : u.1 = v.1) (q : u.2 =[p] v.2) -- : ap (sigma_functor f g) (sigma_eq p q) = -- sigma_eq (ap f p) -- ((tr_compose B' f p (g u.1 u.2))⁻¹ ⬝ (fn_tr_eq_tr_fn p g u.2)⁻¹ ⬝ ap (g v.1) q) := -- by induction u; induction v; apply ap_sigma_functor_eq_dpair /- definition 3.11.9(i): Summing up a contractible family of types does nothing. -/ definition is_equiv_pr1 [instance] [constructor] (B : A → Type) [H : Π a, is_contr (B a)] : is_equiv (@pr1 A B) := adjointify pr1 (λa, ⟨a, !center⟩) (λa, idp) (λu, sigma_eq idp (pathover_idp_of_eq !center_eq)) definition sigma_equiv_of_is_contr_right [constructor] [H : Π a, is_contr (B a)] : (Σa, B a) ≃ A := equiv.mk pr1 _ /- definition 3.11.9(ii): Dually, summing up over a contractible type does nothing. -/ definition sigma_equiv_of_is_contr_left [constructor] (B : A → Type) [H : is_contr A] : (Σa, B a) ≃ B (center A) := equiv.MK (λu, (center_eq u.1)⁻¹ ▸ u.2) (λb, ⟨!center, b⟩) abstract (λb, ap (λx, x ▸ b) !prop_eq_of_is_contr) end abstract (λu, sigma_eq !center_eq !tr_pathover) end /- Associativity -/ --this proof is harder than in Coq because we don't have eta definitionally for sigma definition sigma_assoc_equiv [constructor] (C : (Σa, B a) → Type) : (Σa b, C ⟨a, b⟩) ≃ (Σu, C u) := equiv.mk _ (adjointify (λav, ⟨⟨av.1, av.2.1⟩, av.2.2⟩) (λuc, ⟨uc.1.1, uc.1.2, !sigma.eta⁻¹ ▸ uc.2⟩) abstract begin intro uc, induction uc with u c, induction u, reflexivity end end abstract begin intro av, induction av with a v, induction v, reflexivity end end) open prod prod.ops definition assoc_equiv_prod [constructor] (C : (A × A') → Type) : (Σa a', C (a,a')) ≃ (Σu, C u) := equiv.mk _ (adjointify (λav, ⟨(av.1, av.2.1), av.2.2⟩) (λuc, ⟨pr₁ (uc.1), pr₂ (uc.1), !prod.eta⁻¹ ▸ uc.2⟩) abstract proof (λuc, destruct uc (λu, prod.destruct u (λa b c, idp))) qed end abstract proof (λav, destruct av (λa v, destruct v (λb c, idp))) qed end) /- Symmetry -/ definition comm_equiv_unc (C : A × A' → Type) : (Σa a', C (a, a')) ≃ (Σa' a, C (a, a')) := calc (Σa a', C (a, a')) ≃ Σu, C u : assoc_equiv_prod ... ≃ Σv, C (flip v) : sigma_equiv_sigma !prod_comm_equiv (λu, prod.destruct u (λa a', equiv.rfl)) ... ≃ Σa' a, C (a, a') : assoc_equiv_prod definition sigma_comm_equiv [constructor] (C : A → A' → Type) : (Σa a', C a a') ≃ (Σa' a, C a a') := comm_equiv_unc (λu, C (prod.pr1 u) (prod.pr2 u)) definition equiv_prod [constructor] (A B : Type) : (Σ(a : A), B) ≃ A × B := equiv.mk _ (adjointify (λs, (s.1, s.2)) (λp, ⟨pr₁ p, pr₂ p⟩) proof (λp, prod.destruct p (λa b, idp)) qed proof (λs, destruct s (λa b, idp)) qed) definition comm_equiv_nondep (A B : Type) : (Σ(a : A), B) ≃ Σ(b : B), A := calc (Σ(a : A), B) ≃ A × B : equiv_prod ... ≃ B × A : prod_comm_equiv ... ≃ Σ(b : B), A : equiv_prod definition sigma_assoc_comm_equiv {A : Type} (B C : A → Type) : (Σ(v : Σa, B a), C v.1) ≃ (Σ(u : Σa, C a), B u.1) := calc (Σ(v : Σa, B a), C v.1) ≃ (Σa (b : B a), C a) : sigma_assoc_equiv ... ≃ (Σa (c : C a), B a) : sigma_equiv_sigma_right (λa, !comm_equiv_nondep) ... ≃ (Σ(u : Σa, C a), B u.1) : sigma_assoc_equiv /- Interaction with other type constructors -/ definition sigma_empty_left [constructor] (B : empty → Type) : (Σx, B x) ≃ empty := begin fapply equiv.MK, { intro v, induction v, contradiction}, { intro x, contradiction}, { intro x, contradiction}, { intro v, induction v, contradiction}, end definition sigma_empty_right [constructor] (A : Type) : (Σ(a : A), empty) ≃ empty := begin fapply equiv.MK, { intro v, induction v, contradiction}, { intro x, contradiction}, { intro x, contradiction}, { intro v, induction v, contradiction}, end definition sigma_unit_left [constructor] (B : unit → Type) : (Σx, B x) ≃ B star := !sigma_equiv_of_is_contr_left definition sigma_unit_right [constructor] (A : Type) : (Σ(a : A), unit) ≃ A := !sigma_equiv_of_is_contr_right definition sigma_sum_left [constructor] (B : A + A' → Type) : (Σp, B p) ≃ (Σa, B (inl a)) + (Σa, B (inr a)) := begin fapply equiv.MK, { intro v, induction v with p b, induction p, { apply inl, constructor, assumption }, { apply inr, constructor, assumption }}, { intro p, induction p with v v: induction v; constructor; assumption}, { intro p, induction p with v v: induction v; reflexivity}, { intro v, induction v with p b, induction p: reflexivity}, end definition sigma_sum_right [constructor] (B C : A → Type) : (Σa, B a + C a) ≃ (Σa, B a) + (Σa, C a) := begin fapply equiv.MK, { intro v, induction v with a p, induction p, { apply inl, constructor, assumption}, { apply inr, constructor, assumption}}, { intro p, induction p with v v, { induction v, constructor, apply inl, assumption }, { induction v, constructor, apply inr, assumption }}, { intro p, induction p with v v: induction v; reflexivity}, { intro v, induction v with a p, induction p: reflexivity}, end definition sigma_sigma_eq_right {A : Type} (a : A) (P : Π(b : A), a = b → Type) : (Σ(b : A) (p : a = b), P b p) ≃ P a idp := calc (Σ(b : A) (p : a = b), P b p) ≃ (Σ(v : Σ(b : A), a = b), P v.1 v.2) : sigma_assoc_equiv ... ≃ P a idp : !sigma_equiv_of_is_contr_left definition sigma_sigma_eq_left {A : Type} (a : A) (P : Π(b : A), b = a → Type) : (Σ(b : A) (p : b = a), P b p) ≃ P a idp := calc (Σ(b : A) (p : b = a), P b p) ≃ (Σ(v : Σ(b : A), b = a), P v.1 v.2) : sigma_assoc_equiv ... ≃ P a idp : !sigma_equiv_of_is_contr_left /- ** Universal mapping properties -/ /- *** The positive universal property. -/ section definition is_equiv_sigma_rec [instance] (C : (Σa, B a) → Type) : is_equiv (sigma.rec : (Πa b, C ⟨a, b⟩) → Πab, C ab) := adjointify _ (λ g a b, g ⟨a, b⟩) (λ g, proof eq_of_homotopy (λu, destruct u (λa b, idp)) qed) (λ f, refl f) definition equiv_sigma_rec (C : (Σa, B a) → Type) : (Π(a : A) (b: B a), C ⟨a, b⟩) ≃ (Πxy, C xy) := equiv.mk sigma.rec _ /- *** The negative universal property. -/ protected definition coind_unc (fg : Σ(f : Πa, B a), Πa, C a (f a)) (a : A) : Σ(b : B a), C a b := ⟨fg.1 a, fg.2 a⟩ protected definition coind (f : Π a, B a) (g : Π a, C a (f a)) (a : A) : Σ(b : B a), C a b := sigma.coind_unc ⟨f, g⟩ a --is the instance below dangerous? --in Coq this can be done without function extensionality definition is_equiv_coind [instance] (C : Πa, B a → Type) : is_equiv (@sigma.coind_unc _ _ C) := adjointify _ (λ h, ⟨λa, (h a).1, λa, (h a).2⟩) (λ h, proof eq_of_homotopy (λu, !sigma.eta) qed) (λfg, destruct fg (λ(f : Π (a : A), B a) (g : Π (x : A), C x (f x)), proof idp qed)) definition sigma_pi_equiv_pi_sigma : (Σ(f : Πa, B a), Πa, C a (f a)) ≃ (Πa, Σb, C a b) := equiv.mk sigma.coind_unc _ end /- Subtypes (sigma types whose second components are props) -/ definition subtype [reducible] {A : Type} (P : A → Type) [H : Πa, is_prop (P a)] := Σ(a : A), P a notation [parsing_only] `{` binder `|` r:(scoped:1 P, subtype P) `}` := r /- To prove equality in a subtype, we only need equality of the first component. -/ definition subtype_eq [unfold_full] [H : Πa, is_prop (B a)] {u v : {a | B a}} : u.1 = v.1 → u = v := sigma_eq_unc ∘ inv pr1 definition is_equiv_subtype_eq [constructor] [H : Πa, is_prop (B a)] (u v : {a | B a}) : is_equiv (subtype_eq : u.1 = v.1 → u = v) := !is_equiv_compose local attribute is_equiv_subtype_eq [instance] definition equiv_subtype [constructor] [H : Πa, is_prop (B a)] (u v : {a | B a}) : (u.1 = v.1) ≃ (u = v) := equiv.mk !subtype_eq _ definition subtype_eq_equiv [constructor] [H : Πa, is_prop (B a)] (u v : {a | B a}) : (u = v) ≃ (u.1 = v.1) := (equiv_subtype u v)⁻¹ᵉ definition subtype_eq_inv {A : Type} {B : A → Type} [H : Πa, is_prop (B a)] (u v : Σa, B a) : u = v → u.1 = v.1 := subtype_eq⁻¹ᶠ local attribute subtype_eq_inv [reducible] definition is_equiv_subtype_eq_inv {A : Type} {B : A → Type} [H : Πa, is_prop (B a)] (u v : Σa, B a) : is_equiv (subtype_eq_inv u v) := _ /- truncatedness -/ theorem is_trunc_sigma (B : A → Type) (n : trunc_index) [HA : is_trunc n A] [HB : Πa, is_trunc n (B a)] : is_trunc n (Σa, B a) := begin revert A B HA HB, induction n with n IH, { intro A B HA HB, fapply is_trunc_equiv_closed_rev, apply sigma_equiv_of_is_contr_left}, { intro A B HA HB, apply is_trunc_succ_intro, intro u v, apply is_trunc_equiv_closed_rev, apply sigma_eq_equiv, exact IH _ _ _ _} end theorem is_trunc_subtype (B : A → Prop) (n : trunc_index) [HA : is_trunc (n.+1) A] : is_trunc (n.+1) (Σa, B a) := @(is_trunc_sigma B (n.+1)) _ (λa, !is_trunc_succ_of_is_prop) /- if the total space is a mere proposition, you can equate two points in the base type by finding points in their fibers -/ definition eq_base_of_is_prop_sigma {A : Type} (B : A → Type) (H : is_prop (Σa, B a)) {a a' : A} (b : B a) (b' : B a') : a = a' := (is_prop.elim ⟨a, b⟩ ⟨a', b'⟩)..1 end sigma attribute sigma.is_trunc_sigma [instance] [priority 1490] attribute sigma.is_trunc_subtype [instance] [priority 1200] namespace sigma /- pointed sigma type -/ open pointed definition pointed_sigma [instance] [constructor] {A : Type} (P : A → Type) [G : pointed A] [H : pointed (P pt)] : pointed (Σx, P x) := pointed.mk ⟨pt,pt⟩ definition psigma [constructor] {A : Type*} (P : A → Type*) : Type* := pointed.mk' (Σa, P a) notation `Σ*` binders `, ` r:(scoped P, psigma P) := r definition ppr1 [constructor] {A : Type*} {B : A → Type*} : (Σ*(x : A), B x) →* A := pmap.mk pr1 idp definition ppr2 [unfold_full] {A : Type*} {B : A → Type*} (v : (Σ*(x : A), B x)) : B (ppr1 v) := pr2 v definition ptsigma [constructor] {n : ℕ₋₂} {A : n-Type*} (P : A → n-Type*) : n-Type* := ptrunctype.mk' n (Σa, P a) end sigma
687e9b0ac43b5db7d7d4d2d18b402dd548b80e3e
91b8df3b248df89472cc0b753fbe2bac750aefea
/experiments/lean/src/ddl/binary/basic.lean
3e8e115d228f2f6d1c3a0680ca575b3cdf1857b4
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
yeslogic/fathom
eabe5c4112d3b4d5ec9096a57bb502254ddbdf15
3960a9466150d392c2cb103c5cb5fcffa0200814
refs/heads/main
1,685,349,769,736
1,675,998,621,000
1,675,998,621,000
28,993,871
214
11
Apache-2.0
1,694,044,276,000
1,420,764,938,000
Rust
UTF-8
Lean
false
false
1,259
lean
import ddl.host.basic namespace ddl.binary open ddl /- Kinds of types in the binary language -/ inductive kind : Type | type : kind | arrow : kind → kind → kind notation k₁ ` ⇒ ` k₂ := kind.arrow k₁ k₂ /- The type system of the binary language -/ inductive type (ℓ α : Type) : Type | bvar {} : ℕ → type | fvar {} : α → type | bit {} : type | union_nil {} : type | union_cons : ℓ → type → type → type | struct_nil {} : type | struct_cons : ℓ → type → type → type | array : type → host.expr ℓ → type | assert : type → host.expr ℓ → type | interp : type → host.expr ℓ → host.type ℓ → type | lam : kind → type → type | app : type → type → type -- Application operator infixl ` ∙ `:50 := type.app namespace type variables {ℓ α : Type} instance has_coe_from_nat : has_coe ℕ (type ℓ α) := ⟨bvar⟩ instance has_coe_from_atom : has_coe α (type ℓ α) := ⟨fvar⟩ def lookup (l : ℓ) [decidable_eq ℓ] : type ℓ α → option (type ℓ α) | (struct_cons l' t tr) := if l = l' then some t else lookup tr | _ := none end type end ddl.binary
eb95a31295320a0fe7e19e643b081da087442148
82e44445c70db0f03e30d7be725775f122d72f3e
/src/analysis/calculus/tangent_cone.lean
cafc1429b821926d33bdfb687a0bec8ed9340358
[ "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
18,719
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.convex.basic import analysis.specific_limits /-! # Tangent cone In this file, we define two predicates `unique_diff_within_at 𝕜 s x` and `unique_diff_on 𝕜 s` ensuring that, if a function has two derivatives, then they have to coincide. As a direct definition of this fact (quantifying on all target types and all functions) would depend on universes, we use a more intrinsic definition: if all the possible tangent directions to the set `s` at the point `x` span a dense subset of the whole subset, it is easy to check that the derivative has to be unique. Therefore, we introduce the set of all tangent directions, named `tangent_cone_at`, and express `unique_diff_within_at` and `unique_diff_on` in terms of it. One should however think of this definition as an implementation detail: the only reason to introduce the predicates `unique_diff_within_at` and `unique_diff_on` is to ensure the uniqueness of the derivative. This is why their names reflect their uses, and not how they are defined. ## Implementation details Note that this file is imported by `fderiv.lean`. Hence, derivatives are not defined yet. The property of uniqueness of the derivative is therefore proved in `fderiv.lean`, but based on the properties of the tangent cone we prove here. -/ variables (𝕜 : Type*) [nondiscrete_normed_field 𝕜] open filter set open_locale topological_space section tangent_cone variables {E : Type*} [add_comm_monoid E] [module 𝕜 E] [topological_space E] /-- The set of all tangent directions to the set `s` at the point `x`. -/ def tangent_cone_at (s : set E) (x : E) : set E := {y : E | ∃(c : ℕ → 𝕜) (d : ℕ → E), (∀ᶠ n in at_top, x + d n ∈ s) ∧ (tendsto (λn, ∥c n∥) at_top at_top) ∧ (tendsto (λn, c n • d n) at_top (𝓝 y))} /-- A property ensuring that the tangent cone to `s` at `x` spans a dense subset of the whole space. The main role of this property is to ensure that the differential within `s` at `x` is unique, hence this name. The uniqueness it asserts is proved in `unique_diff_within_at.eq` in `fderiv.lean`. To avoid pathologies in dimension 0, we also require that `x` belongs to the closure of `s` (which is automatic when `E` is not `0`-dimensional). -/ @[mk_iff] structure unique_diff_within_at (s : set E) (x : E) : Prop := (dense_tangent_cone : dense ((submodule.span 𝕜 (tangent_cone_at 𝕜 s x)) : set E)) (mem_closure : x ∈ closure s) /-- A property ensuring that the tangent cone to `s` at any of its points spans a dense subset of the whole space. The main role of this property is to ensure that the differential along `s` is unique, hence this name. The uniqueness it asserts is proved in `unique_diff_on.eq` in `fderiv.lean`. -/ def unique_diff_on (s : set E) : Prop := ∀x ∈ s, unique_diff_within_at 𝕜 s x end tangent_cone variables {E : Type*} [normed_group E] [normed_space 𝕜 E] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] variables {G : Type*} [normed_group G] [normed_space ℝ G] variables {𝕜} {x y : E} {s t : set E} section tangent_cone /- This section is devoted to the properties of the tangent cone. -/ open normed_field lemma tangent_cone_univ : tangent_cone_at 𝕜 univ x = univ := begin refine univ_subset_iff.1 (λy hy, _), rcases exists_one_lt_norm 𝕜 with ⟨w, hw⟩, refine ⟨λn, w^n, λn, (w^n)⁻¹ • y, univ_mem_sets' (λn, mem_univ _), _, _⟩, { simp only [norm_pow], exact tendsto_pow_at_top_at_top_of_one_lt hw }, { convert tendsto_const_nhds, ext n, have : w ^ n * (w ^ n)⁻¹ = 1, { apply mul_inv_cancel, apply pow_ne_zero, simpa [norm_eq_zero] using (ne_of_lt (lt_trans zero_lt_one hw)).symm }, rw [smul_smul, this, one_smul] } end lemma tangent_cone_mono (h : s ⊆ t) : tangent_cone_at 𝕜 s x ⊆ tangent_cone_at 𝕜 t x := begin rintros y ⟨c, d, ds, ctop, clim⟩, exact ⟨c, d, mem_sets_of_superset ds (λn hn, h hn), ctop, clim⟩ end /-- Auxiliary lemma ensuring that, under the assumptions defining the tangent cone, the sequence `d` tends to 0 at infinity. -/ lemma tangent_cone_at.lim_zero {α : Type*} (l : filter α) {c : α → 𝕜} {d : α → E} (hc : tendsto (λn, ∥c n∥) l at_top) (hd : tendsto (λn, c n • d n) l (𝓝 y)) : tendsto d l (𝓝 0) := begin have A : tendsto (λn, ∥c n∥⁻¹) l (𝓝 0) := tendsto_inv_at_top_zero.comp hc, have B : tendsto (λn, ∥c n • d n∥) l (𝓝 ∥y∥) := (continuous_norm.tendsto _).comp hd, have C : tendsto (λn, ∥c n∥⁻¹ * ∥c n • d n∥) l (𝓝 (0 * ∥y∥)) := A.mul B, rw zero_mul at C, have : ∀ᶠ n in l, ∥c n∥⁻¹ * ∥c n • d n∥ = ∥d n∥, { apply (eventually_ne_of_tendsto_norm_at_top hc 0).mono (λn hn, _), rw [norm_smul, ← mul_assoc, inv_mul_cancel, one_mul], rwa [ne.def, norm_eq_zero] }, have D : tendsto (λ n, ∥d n∥) l (𝓝 0) := tendsto.congr' this C, rw tendsto_zero_iff_norm_tendsto_zero, exact D end lemma tangent_cone_mono_nhds (h : 𝓝[s] x ≤ 𝓝[t] x) : tangent_cone_at 𝕜 s x ⊆ tangent_cone_at 𝕜 t x := begin rintros y ⟨c, d, ds, ctop, clim⟩, refine ⟨c, d, _, ctop, clim⟩, suffices : tendsto (λ n, x + d n) at_top (𝓝[t] x), from tendsto_principal.1 (tendsto_inf.1 this).2, refine (tendsto_inf.2 ⟨_, tendsto_principal.2 ds⟩).mono_right h, simpa only [add_zero] using tendsto_const_nhds.add (tangent_cone_at.lim_zero at_top ctop clim) end /-- Tangent cone of `s` at `x` depends only on `𝓝[s] x`. -/ lemma tangent_cone_congr (h : 𝓝[s] x = 𝓝[t] x) : tangent_cone_at 𝕜 s x = tangent_cone_at 𝕜 t x := subset.antisymm (tangent_cone_mono_nhds $ le_of_eq h) (tangent_cone_mono_nhds $ le_of_eq h.symm) /-- Intersecting with a neighborhood of the point does not change the tangent cone. -/ lemma tangent_cone_inter_nhds (ht : t ∈ 𝓝 x) : tangent_cone_at 𝕜 (s ∩ t) x = tangent_cone_at 𝕜 s x := tangent_cone_congr (nhds_within_restrict' _ ht).symm /-- The tangent cone of a product contains the tangent cone of its left factor. -/ lemma subset_tangent_cone_prod_left {t : set F} {y : F} (ht : y ∈ closure t) : linear_map.inl 𝕜 E F '' (tangent_cone_at 𝕜 s x) ⊆ tangent_cone_at 𝕜 (set.prod s t) (x, y) := begin rintros _ ⟨v, ⟨c, d, hd, hc, hy⟩, rfl⟩, have : ∀n, ∃d', y + d' ∈ t ∧ ∥c n • d'∥ < ((1:ℝ)/2)^n, { assume n, rcases mem_closure_iff_nhds.1 ht _ (eventually_nhds_norm_smul_sub_lt (c n) y (pow_pos one_half_pos n)) with ⟨z, hz, hzt⟩, exact ⟨z - y, by simpa using hzt, by simpa using hz⟩ }, choose d' hd' using this, refine ⟨c, λn, (d n, d' n), _, hc, _⟩, show ∀ᶠ n in at_top, (x, y) + (d n, d' n) ∈ set.prod s t, { filter_upwards [hd], assume n hn, simp [hn, (hd' n).1] }, { apply tendsto.prod_mk_nhds hy _, refine squeeze_zero_norm (λn, (hd' n).2.le) _, exact tendsto_pow_at_top_nhds_0_of_lt_1 one_half_pos.le one_half_lt_one } end /-- The tangent cone of a product contains the tangent cone of its right factor. -/ lemma subset_tangent_cone_prod_right {t : set F} {y : F} (hs : x ∈ closure s) : linear_map.inr 𝕜 E F '' (tangent_cone_at 𝕜 t y) ⊆ tangent_cone_at 𝕜 (set.prod s t) (x, y) := begin rintros _ ⟨w, ⟨c, d, hd, hc, hy⟩, rfl⟩, have : ∀n, ∃d', x + d' ∈ s ∧ ∥c n • d'∥ < ((1:ℝ)/2)^n, { assume n, rcases mem_closure_iff_nhds.1 hs _ (eventually_nhds_norm_smul_sub_lt (c n) x (pow_pos one_half_pos n)) with ⟨z, hz, hzs⟩, exact ⟨z - x, by simpa using hzs, by simpa using hz⟩ }, choose d' hd' using this, refine ⟨c, λn, (d' n, d n), _, hc, _⟩, show ∀ᶠ n in at_top, (x, y) + (d' n, d n) ∈ set.prod s t, { filter_upwards [hd], assume n hn, simp [hn, (hd' n).1] }, { apply tendsto.prod_mk_nhds _ hy, refine squeeze_zero_norm (λn, (hd' n).2.le) _, exact tendsto_pow_at_top_nhds_0_of_lt_1 one_half_pos.le one_half_lt_one } end /-- The tangent cone of a product contains the tangent cone of each factor. -/ lemma maps_to_tangent_cone_pi {ι : Type*} [decidable_eq ι] {E : ι → Type*} [Π i, normed_group (E i)] [Π i, normed_space 𝕜 (E i)] {s : Π i, set (E i)} {x : Π i, E i} {i : ι} (hi : ∀ j ≠ i, x j ∈ closure (s j)) : maps_to (linear_map.single i : E i →ₗ[𝕜] Π j, E j) (tangent_cone_at 𝕜 (s i) (x i)) (tangent_cone_at 𝕜 (set.pi univ s) x) := begin rintros w ⟨c, d, hd, hc, hy⟩, have : ∀ n (j ≠ i), ∃ d', x j + d' ∈ s j ∧ ∥c n • d'∥ < (1 / 2 : ℝ) ^ n, { assume n j hj, rcases mem_closure_iff_nhds.1 (hi j hj) _ (eventually_nhds_norm_smul_sub_lt (c n) (x j) (pow_pos one_half_pos n)) with ⟨z, hz, hzs⟩, exact ⟨z - x j, by simpa using hzs, by simpa using hz⟩ }, choose! d' hd's hcd', refine ⟨c, λ n, function.update (d' n) i (d n), hd.mono (λ n hn j hj', _), hc, tendsto_pi.2 $ λ j, _⟩, { rcases em (j = i) with rfl|hj; simp * }, { rcases em (j = i) with rfl|hj, { simp [hy] }, { suffices : tendsto (λ n, c n • d' n j) at_top (𝓝 0), by simpa [hj], refine squeeze_zero_norm (λ n, (hcd' n j hj).le) _, exact tendsto_pow_at_top_nhds_0_of_lt_1 one_half_pos.le one_half_lt_one } } end /-- If a subset of a real vector space contains a segment, then the direction of this segment belongs to the tangent cone at its endpoints. -/ lemma mem_tangent_cone_of_segment_subset {s : set G} {x y : G} (h : segment x y ⊆ s) : y - x ∈ tangent_cone_at ℝ s x := begin let c := λn:ℕ, (2:ℝ)^n, let d := λn:ℕ, (c n)⁻¹ • (y-x), refine ⟨c, d, filter.univ_mem_sets' (λn, h _), _, _⟩, show x + d n ∈ segment x y, { rw segment_eq_image, refine ⟨(c n)⁻¹, ⟨_, _⟩, _⟩, { rw inv_nonneg, apply pow_nonneg, norm_num }, { apply inv_le_one, apply one_le_pow_of_one_le, norm_num }, { simp only [d, sub_smul, smul_sub, one_smul], abel } }, show filter.tendsto (λ (n : ℕ), ∥c n∥) filter.at_top filter.at_top, { have : (λ (n : ℕ), ∥c n∥) = c, by { ext n, exact abs_of_nonneg (pow_nonneg (by norm_num) _) }, rw this, exact tendsto_pow_at_top_at_top_of_one_lt (by norm_num) }, show filter.tendsto (λ (n : ℕ), c n • d n) filter.at_top (𝓝 (y - x)), { have : (λ (n : ℕ), c n • d n) = (λn, y - x), { ext n, simp only [d, smul_smul], rw [mul_inv_cancel, one_smul], exact pow_ne_zero _ (by norm_num) }, rw this, apply tendsto_const_nhds } end end tangent_cone section unique_diff /-! ### Properties of `unique_diff_within_at` and `unique_diff_on` This section is devoted to properties of the predicates `unique_diff_within_at` and `unique_diff_on`. -/ lemma unique_diff_on.unique_diff_within_at {s : set E} {x} (hs : unique_diff_on 𝕜 s) (h : x ∈ s) : unique_diff_within_at 𝕜 s x := hs x h lemma unique_diff_within_at_univ : unique_diff_within_at 𝕜 univ x := by { rw [unique_diff_within_at_iff, tangent_cone_univ], simp } lemma unique_diff_on_univ : unique_diff_on 𝕜 (univ : set E) := λx hx, unique_diff_within_at_univ lemma unique_diff_on_empty : unique_diff_on 𝕜 (∅ : set E) := λ x hx, hx.elim lemma unique_diff_within_at.mono_nhds (h : unique_diff_within_at 𝕜 s x) (st : 𝓝[s] x ≤ 𝓝[t] x) : unique_diff_within_at 𝕜 t x := begin simp only [unique_diff_within_at_iff] at *, rw [mem_closure_iff_nhds_within_ne_bot] at h ⊢, exact ⟨h.1.mono $ submodule.span_mono $ tangent_cone_mono_nhds st, h.2.mono st⟩ end lemma unique_diff_within_at.mono (h : unique_diff_within_at 𝕜 s x) (st : s ⊆ t) : unique_diff_within_at 𝕜 t x := h.mono_nhds $ nhds_within_mono _ st lemma unique_diff_within_at_congr (st : 𝓝[s] x = 𝓝[t] x) : unique_diff_within_at 𝕜 s x ↔ unique_diff_within_at 𝕜 t x := ⟨λ h, h.mono_nhds $ le_of_eq st, λ h, h.mono_nhds $ le_of_eq st.symm⟩ lemma unique_diff_within_at_inter (ht : t ∈ 𝓝 x) : unique_diff_within_at 𝕜 (s ∩ t) x ↔ unique_diff_within_at 𝕜 s x := unique_diff_within_at_congr $ (nhds_within_restrict' _ ht).symm lemma unique_diff_within_at.inter (hs : unique_diff_within_at 𝕜 s x) (ht : t ∈ 𝓝 x) : unique_diff_within_at 𝕜 (s ∩ t) x := (unique_diff_within_at_inter ht).2 hs lemma unique_diff_within_at_inter' (ht : t ∈ 𝓝[s] x) : unique_diff_within_at 𝕜 (s ∩ t) x ↔ unique_diff_within_at 𝕜 s x := unique_diff_within_at_congr $ (nhds_within_restrict'' _ ht).symm lemma unique_diff_within_at.inter' (hs : unique_diff_within_at 𝕜 s x) (ht : t ∈ 𝓝[s] x) : unique_diff_within_at 𝕜 (s ∩ t) x := (unique_diff_within_at_inter' ht).2 hs lemma unique_diff_within_at_of_mem_nhds (h : s ∈ 𝓝 x) : unique_diff_within_at 𝕜 s x := by simpa only [univ_inter] using unique_diff_within_at_univ.inter h lemma is_open.unique_diff_within_at (hs : is_open s) (xs : x ∈ s) : unique_diff_within_at 𝕜 s x := unique_diff_within_at_of_mem_nhds (is_open.mem_nhds hs xs) lemma unique_diff_on.inter (hs : unique_diff_on 𝕜 s) (ht : is_open t) : unique_diff_on 𝕜 (s ∩ t) := λx hx, (hs x hx.1).inter (is_open.mem_nhds ht hx.2) lemma is_open.unique_diff_on (hs : is_open s) : unique_diff_on 𝕜 s := λx hx, is_open.unique_diff_within_at hs hx /-- The product of two sets of unique differentiability at points `x` and `y` has unique differentiability at `(x, y)`. -/ lemma unique_diff_within_at.prod {t : set F} {y : F} (hs : unique_diff_within_at 𝕜 s x) (ht : unique_diff_within_at 𝕜 t y) : unique_diff_within_at 𝕜 (set.prod s t) (x, y) := begin rw [unique_diff_within_at_iff] at ⊢ hs ht, rw [closure_prod_eq], refine ⟨_, hs.2, ht.2⟩, have : _ ≤ submodule.span 𝕜 (tangent_cone_at 𝕜 (s.prod t) (x, y)) := submodule.span_mono (union_subset (subset_tangent_cone_prod_left ht.2) (subset_tangent_cone_prod_right hs.2)), rw [linear_map.span_inl_union_inr, set_like.le_def] at this, exact (hs.1.prod ht.1).mono this end lemma unique_diff_within_at.univ_pi (ι : Type*) [fintype ι] (E : ι → Type*) [Π i, normed_group (E i)] [Π i, normed_space 𝕜 (E i)] (s : Π i, set (E i)) (x : Π i, E i) (h : ∀ i, unique_diff_within_at 𝕜 (s i) (x i)) : unique_diff_within_at 𝕜 (set.pi univ s) x := begin classical, simp only [unique_diff_within_at_iff, closure_pi_set] at h ⊢, refine ⟨(dense_pi univ (λ i _, (h i).1)).mono _, λ i _, (h i).2⟩, norm_cast, simp only [← submodule.supr_map_single, supr_le_iff, linear_map.map_span, submodule.span_le, ← maps_to'], exact λ i, (maps_to_tangent_cone_pi $ λ j hj, (h j).2).mono subset.rfl submodule.subset_span end lemma unique_diff_within_at.pi (ι : Type*) [fintype ι] (E : ι → Type*) [Π i, normed_group (E i)] [Π i, normed_space 𝕜 (E i)] (s : Π i, set (E i)) (x : Π i, E i) (I : set ι) (h : ∀ i ∈ I, unique_diff_within_at 𝕜 (s i) (x i)) : unique_diff_within_at 𝕜 (set.pi I s) x := begin classical, rw [← set.univ_pi_piecewise], refine unique_diff_within_at.univ_pi _ _ _ _ (λ i, _), by_cases hi : i ∈ I; simp [*, unique_diff_within_at_univ], end /-- The product of two sets of unique differentiability is a set of unique differentiability. -/ lemma unique_diff_on.prod {t : set F} (hs : unique_diff_on 𝕜 s) (ht : unique_diff_on 𝕜 t) : unique_diff_on 𝕜 (set.prod s t) := λ ⟨x, y⟩ h, unique_diff_within_at.prod (hs x h.1) (ht y h.2) /-- The finite product of a family of sets of unique differentiability is a set of unique differentiability. -/ lemma unique_diff_on.pi (ι : Type*) [fintype ι] (E : ι → Type*) [Π i, normed_group (E i)] [Π i, normed_space 𝕜 (E i)] (s : Π i, set (E i)) (I : set ι) (h : ∀ i ∈ I, unique_diff_on 𝕜 (s i)) : unique_diff_on 𝕜 (set.pi I s) := λ x hx, unique_diff_within_at.pi _ _ _ _ _ $ λ i hi, h i hi (x i) (hx i hi) /-- The finite product of a family of sets of unique differentiability is a set of unique differentiability. -/ lemma unique_diff_on.univ_pi (ι : Type*) [fintype ι] (E : ι → Type*) [Π i, normed_group (E i)] [Π i, normed_space 𝕜 (E i)] (s : Π i, set (E i)) (h : ∀ i, unique_diff_on 𝕜 (s i)) : unique_diff_on 𝕜 (set.pi univ s) := unique_diff_on.pi _ _ _ _ $ λ i _, h i /-- In a real vector space, a convex set with nonempty interior is a set of unique differentiability. -/ theorem unique_diff_on_convex {s : set G} (conv : convex s) (hs : (interior s).nonempty) : unique_diff_on ℝ s := begin assume x xs, rcases hs with ⟨y, hy⟩, suffices : y - x ∈ interior (tangent_cone_at ℝ s x), { refine ⟨dense.of_closure _, subset_closure xs⟩, simp [(submodule.span ℝ (tangent_cone_at ℝ s x)).eq_top_of_nonempty_interior' ⟨y - x, interior_mono submodule.subset_span this⟩] }, rw [mem_interior_iff_mem_nhds] at hy ⊢, apply mem_sets_of_superset ((is_open_map_sub_right x).image_mem_nhds hy), rintros _ ⟨z, zs, rfl⟩, exact mem_tangent_cone_of_segment_subset (conv.segment_subset xs zs) end lemma unique_diff_on_Ici (a : ℝ) : unique_diff_on ℝ (Ici a) := unique_diff_on_convex (convex_Ici a) $ by simp only [interior_Ici, nonempty_Ioi] lemma unique_diff_on_Iic (a : ℝ) : unique_diff_on ℝ (Iic a) := unique_diff_on_convex (convex_Iic a) $ by simp only [interior_Iic, nonempty_Iio] lemma unique_diff_on_Ioi (a : ℝ) : unique_diff_on ℝ (Ioi a) := is_open_Ioi.unique_diff_on lemma unique_diff_on_Iio (a : ℝ) : unique_diff_on ℝ (Iio a) := is_open_Iio.unique_diff_on lemma unique_diff_on_Icc {a b : ℝ} (hab : a < b) : unique_diff_on ℝ (Icc a b) := unique_diff_on_convex (convex_Icc a b) $ by simp only [interior_Icc, nonempty_Ioo, hab] lemma unique_diff_on_Ico (a b : ℝ) : unique_diff_on ℝ (Ico a b) := if hab : a < b then unique_diff_on_convex (convex_Ico a b) $ by simp only [interior_Ico, nonempty_Ioo, hab] else by simp only [Ico_eq_empty hab, unique_diff_on_empty] lemma unique_diff_on_Ioc (a b : ℝ) : unique_diff_on ℝ (Ioc a b) := if hab : a < b then unique_diff_on_convex (convex_Ioc a b) $ by simp only [interior_Ioc, nonempty_Ioo, hab] else by simp only [Ioc_eq_empty hab, unique_diff_on_empty] lemma unique_diff_on_Ioo (a b : ℝ) : unique_diff_on ℝ (Ioo a b) := is_open_Ioo.unique_diff_on /-- The real interval `[0, 1]` is a set of unique differentiability. -/ lemma unique_diff_on_Icc_zero_one : unique_diff_on ℝ (Icc (0:ℝ) 1) := unique_diff_on_Icc zero_lt_one end unique_diff
f2aede04578d7cfa1d28d7704d6e06d137ca2159
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/tests/bench/rbmap4.lean
3c9f038d39f695be017b31e617e2dcb6a3cb9d62
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
2,844
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.coe init.data.option.basic init.system.io universes u v w w' inductive color | Red | Black inductive Tree | Leaf {} : Tree | Node (color : color) (lchild : Tree) (key : Nat) (val : Bool) (rchild : Tree) : Tree variable {σ : Type w} open color Nat Tree def fold (f : Nat → Bool → σ → σ) : Tree → σ → σ | Leaf, b => b | Node _ l k v r, b => fold r (f k v (fold l b)) @[inline] def balance1 : Nat → Bool → Tree → Tree → Tree | kv, vv, t, Node _ (Node Red l kx vx r₁) ky vy r₂ => Node Red (Node Black l kx vx r₁) ky vy (Node Black r₂ kv vv t) | kv, vv, t, Node _ l₁ ky vy (Node Red l₂ kx vx r) => Node Red (Node Black l₁ ky vy l₂) kx vx (Node Black r kv vv t) | kv, vv, t, Node _ l ky vy r => Node Black (Node Red l ky vy r) kv vv t | _, _, _, _ => Leaf @[inline] def balance2 : Tree → Nat → Bool → Tree → Tree | t, kv, vv, Node _ (Node Red l kx₁ vx₁ r₁) ky vy r₂ => Node Red (Node Black t kv vv l) kx₁ vx₁ (Node Black r₁ ky vy r₂) | t, kv, vv, Node _ l₁ ky vy (Node Red l₂ kx₂ vx₂ r₂) => Node Red (Node Black t kv vv l₁) ky vy (Node Black l₂ kx₂ vx₂ r₂) | t, kv, vv, Node _ l ky vy r => Node Black t kv vv (Node Red l ky vy r) | _, _, _, _ => Leaf def isRed : Tree → Bool | Node Red _ _ _ _ => true | _ => false def ins : Tree → Nat → Bool → Tree | Leaf, kx, vx => Node Red Leaf kx vx Leaf | Node Red a ky vy b, kx, vx => (if kx < ky then Node Red (ins a kx vx) ky vy b else if kx = ky then Node Red a kx vx b else Node Red a ky vy (ins b kx vx)) | Node Black a ky vy b, kx, vx => if kx < ky then (if isRed a then balance1 ky vy b (ins a kx vx) else Node Black (ins a kx vx) ky vy b) else if kx = ky then Node Black a kx vx b else if isRed b then balance2 a ky vy (ins b kx vx) else Node Black a ky vy (ins b kx vx) def setBlack : Tree → Tree | Node _ l k v r => Node Black l k v r | e => e def insert (t : Tree) (k : Nat) (v : Bool) : Tree := if isRed t then setBlack (ins t k v) else ins t k v def mkMapAux : Nat → Tree → Tree | 0, m => m | n+1, m => mkMapAux n (insert m n (n % 10 = 0)) def mkMap (n : Nat) := mkMapAux n Leaf def main (xs : List String) : IO UInt32 := let m := mkMap xs.head.toNat; let v := fold (fun (k : Nat) (v : Bool) (r : Nat) => if v then r + 1 else r) m 0; IO.println (toString v) *> pure 0
ec0c5453d34f1c90081c9e7a445861def4a1f2f3
0dbd5f7001f62ee8d54ed48bada66bfeaf55e550
/src/fermat.lean
9d84933c6ed6d6591caba20fae1535b091855b99
[]
no_license
rwbarton/lean-elementary-number-theory
667203b08501792eef48217759539f6c1e2da25a
fabef0737fd2486e3f24f9e04652db4c182d5425
refs/heads/master
1,670,605,651,029
1,599,565,470,000
1,599,565,470,000
293,792,043
2
0
null
null
null
null
UTF-8
Lean
false
false
19,904
lean
import data.nat.gcd import data.nat.prime import pyth open nat local attribute [simp] mul_comm mul_left_comm mul_assoc section fermat parameters x y z : ℕ parameter fmt : x^4 = y^4 + z^2 parameter pos : x > 0 ∧ y > 0 ∧ z > 0 include fmt pos lemma x_pos : x > 0 := pos.1 lemma y_pos : y > 0 := pos.2.1 lemma z_pos : z > 0 := pos.2.2 lemma y_lt_x : y < x := begin cases nat.lt_or_ge y x with _ ge, { assumption }, { have z2pos : z^2 > 0 := begin rw nat.pow_two, exact nat.mul_self_lt_mul_self_iff.mp z_pos end, have : y^4 < y^4 := calc y^4 < y^4 + z^2 : nat.lt_add_of_pos_right z2pos ... = x^4 : by rw fmt ... ≤ y^4 : pow_le_pow_of_le_left ge 4, exact absurd this (not_lt_of_ge (le_refl (y^4))) } end lemma y_le_x : y ≤ x := le_of_lt y_lt_x lemma l1 : (x^2 + y^2) * (x^2 - y^2) = z^2 := calc (x^2 + y^2) * (x^2 - y^2) = x^2 * x^2 - y^2 * y^2 : by rw ←nat.mul_self_sub_mul_self_eq ... = x^(2 + 2) - y^(2 + 2) : by simp [nat.pow_add] ... = y^4 + z^2 - y^4 : by simp [fmt] ... = z^2 : by rw nat.add_sub_cancel_left section x_y parameter x_y : coprime x y include x_y lemma x2_y2 : coprime (x^2) (y^2) := coprime.pow 2 2 x_y lemma l2 : gcd (x^2 - y^2) (x^2 + y^2) ∣ 2 := gcd.sum_difference_of_coprime (y^2) (x^2) (pow_le_pow_of_le_left y_le_x 2) (coprime.pow 2 2 x_y.symm) section case_a parameter gmp2 : gcd (x^2 - y^2) (x^2 + y^2) = 2 include gmp2 lemma x2py2_even : 2 ∣ x^2 + y^2 := begin have := (gcd_dvd (x^2 - y^2) (x^2 + y^2)).right, rwa gmp2 at this, end lemma odd_x : odd x := begin apply even_xor_odd.resolve_left.mp, intro even_x, have := not_both_even_if_coprime x_y, cases even_or_odd y with even_y odd_y, { exact this ⟨even_x, even_y⟩ }, { have x2py2_odd : odd (x^2 + y^2) := even_plus_odd_is_odd (even_square_is_even even_x) (odd_square_is_odd odd_y), exact not_even_and_odd (x^2 + y^2) ⟨even_iff_two_dvd.mpr x2py2_even, x2py2_odd⟩ } end lemma odd_y : odd y := begin apply even_xor_odd.resolve_left.mp, intro even_y, have x2py2_odd : odd (x^2 + y^2) := odd_plus_even_is_odd (odd_square_is_odd odd_x) (even_square_is_even even_y), exact not_even_and_odd (x^2 + y^2) ⟨even_iff_two_dvd.mpr x2py2_even, x2py2_odd⟩ end lemma case_a : ∃ x' y' z' : ℕ, 0 < x' ∧ 0 < y' ∧ 0 < z' ∧ x' < x ∧ x'^4 = y'^4 + z'^2 := begin have py : (y^2)^2 + z^2 = (x^2)^2 := calc (y^2)^2 + z^2 = y^4 + z^2 : by rw square_twice ... = x^4 : fmt.symm ... = (x^2)^2 : by rw square_twice, have ppos : y^2 > 0 ∧ z > 0 ∧ x^2 > 0 := ⟨ pos_pow_of_pos 2 y_pos, z_pos, pos_pow_of_pos 2 x_pos ⟩, have even_z : even z := or.resolve_right (even_or_odd z) (begin intro odd_z, have ex4 : even (x^4) := begin rw fmt, rw ←square_twice, apply odd_plus_odd_is_even, exact (odd_square_is_odd (odd_square_is_odd odd_y)), exact (odd_square_is_odd odd_z) end, have ox4 : odd (x^4) := begin rw ←square_twice, exact (odd_square_is_odd (odd_square_is_odd odd_x)) end, exact absurd (and.intro ex4 ox4) (not_even_and_odd (x^4)) end), have y2_z : coprime (y^2) z := begin have x4_y4 : coprime (x^4) (y^4) := coprime.pow 4 4 x_y, rw fmt at x4_y4, have y4_z2 : coprime (y^4) (z^2) := begin rw coprime at *, have : gcd (y^4) (z^2) = gcd (y^4) (y^4 * 1 + z^2) := gcd.gcd_row_op (y^4) (z^2) 1, rw gcd_comm at x4_y4, rewrite [nat.mul_one, x4_y4] at this, assumption end, rw ←square_twice at y4_z2, exact gcd.coprime_iff_squares_coprime.mp y4_z2, end, rcases ex (y^2) z (x^2) py y2_z even_z ppos with ⟨d,e,d_pos,e_pos,d_gt_e,_,Hy,Hz,Hx⟩, have e2_pos : e^2 > 0 := pos_pow_of_pos 2 e_pos, have d_ge_e : d ≥ e := le_of_lt d_gt_e, existsi [d, e, x*y], repeat { split }, { exact d_pos }, { exact e_pos }, { exact mul_pos x_pos y_pos }, { apply (nat.lt_or_ge d x).resolve_right, intro d_ge_x, have : x^2 < x^2 := calc x^2 = d^2 + e^2 : by rw Hx ... ≥ x^2 + e^2 : nat.add_le_add_right (pow_le_pow_of_le_left d_ge_x 2) (e^2) ... > x^2 : nat.lt_add_of_pos_right e2_pos, exact absurd this (lt_irrefl _) }, { have : d^4 - e^4 = (x * y)^2 := calc d^4 - e^4 = (d^2)^2 - (e^2)^2 : by rw [square_twice, square_twice] ... = (d^2)*(d^2) - (e^2)*(e^2) : by rw [@nat.pow_two (d^2), @nat.pow_two (e^2)] ... = (d^2 + e^2) * (d^2 - e^2) : nat.mul_self_sub_mul_self_eq (d^2) (e^2) ... = x^2 * y^2 : by rw [←Hx, ←Hy] -- Why is there no (a * b)^n = a^n * b^n ... = (x * x) * (y * y) : by simp [nat.pow_two] ... = (x * y) * (x * y) : by simp ... = (x * y)^2 : by rw ←nat.pow_two, exact calc d^4 = (d^4 - e^4) + e^4 : (nat.sub_add_cancel (pow_le_pow_of_le_left d_ge_e 4)).symm ... = (x * y)^2 + e^4 : by rw this ... = e^4 + (x * y)^2 : by simp, } end end case_a section case_b parameter g : gcd (x^2 - y^2) (x^2 + y^2) = 1 include g -- From (x^2 - y^2) * (x^2 + y^2) = z^2 parameters s t : ℕ parameter Hs : x^2 + y^2 = s^2 parameter Ht : x^2 - y^2 = t^2 include Hs Ht def s_pos : s > 0 := begin apply (eq_zero_or_pos s).resolve_left, intro s_zero, simp [s_zero] at Hs, have : 0^2 > 0^2 := calc 0^2 = x^2 + y^2 : by rw Hs ... ≥ x^2 : le_add_right _ _ ... > 0^2 : pow_lt_pow_of_lt_left x_pos dec_trivial, exact absurd this (lt_irrefl _) end def s_odd : odd s := c_odd x y s Hs x_y def t_odd : odd t := have l : s^2 + t^2 = 2 * x^2, from calc s^2 + t^2 = (x^2 - y^2) + (x^2 + y^2) : by rw [add_comm, Hs, Ht] ... = 2 * x^2 : by rw ←gcd.sum_difference_sum (pow_le_pow_of_le_left y_le_x 2), begin cases even_or_odd t with t_even _, { have : odd (s^2 + t^2) := odd_plus_even_is_odd (odd_square_is_odd s_odd) (even_square_is_even t_even), rw l at this, have e : even (2 * x^2) := even_times_any_is_even (dec_trivial : 2 ≡ 0 [MOD 2]), exact absurd (and.intro e this) (not_even_and_odd _) }, assumption end def t_lt_s : t < s := lt_of_not_ge $ begin by_contradiction h, have := calc x^2 + y^2 = s^2 : Hs ... ≤ t^2 : pow_le_pow_of_le_left h 2 ... = x^2 - y^2 : Ht.symm ... ≤ x^2 : sub_le _ _ ... < x^2 + y^2 : nat.lt_add_of_pos_right (pos_pow_of_pos 2 y_pos), exact absurd this (lt_irrefl _) -- @[irrefl]? end def t_le_s := le_of_lt t_lt_s def spt_even : even (s + t) := odd_plus_odd_is_even s_odd t_odd def smt_even : even (s - t) := odd_minus_odd_is_even t_le_s t_odd s_odd -- These definitions are in core lean :( local attribute [trans] dvd_trans local attribute [refl] dvd_refl def s_t : coprime s t := begin apply coprime_of_dvd', intros k ks kt, have x2_y2 := gcd.coprime_iff_squares_coprime.mpr x_y, have := gcd.sum_difference_of_coprime (y^2) (x^2) (pow_le_pow_of_le_left y_le_x 2) x2_y2.symm, have k2_div_sub := calc k^2 ∣ t^2 : pow_dvd_pow_of_dvd kt ... = x^2 - y^2 : Ht.symm, have k2_div_add := calc k^2 ∣ s^2 : pow_dvd_pow_of_dvd ks ... = x^2 + y^2 : Hs.symm, have k2_div_2 := dvd.trans (dvd_gcd k2_div_sub k2_div_add) this, cases (dvd_prime dec_trivial).mp (dvd.trans self_divides_square k2_div_2) with k_1 k_2, { rw k_1 }, { rw k_2 at k2_div_2, have : ¬(4 ∣ 2) := dec_trivial, contradiction } end def u := (s + t) / 2 lemma lu : 2 * u = s + t := nat.mul_div_cancel' (even_iff_two_dvd.mp spt_even) def v := (s - t) / 2 lemma lv : 2 * v = s - t := nat.mul_div_cancel' (even_iff_two_dvd.mp smt_even) lemma u_v : coprime u v := begin have g_div_two := gcd.sum_difference_of_coprime t s t_le_s s_t.symm, have two_div_g := dvd_gcd (even_iff_two_dvd.mp smt_even) (even_iff_two_dvd.mp spt_even), have g_eq_two := dvd_antisymm g_div_two two_div_g, rw [←lu, ←lv] at g_eq_two, have := calc 2 * gcd u v = gcd (2 * u) (2 * v) : by rw gcd_mul_left ... = gcd (2 * v) (2 * u) : gcd_comm _ _ ... = 2 : g_eq_two ... = 2 * 1 : by simp, exact eq_of_mul_eq_mul_left dec_trivial this end lemma y2_2uv : y^2 = 2 * u * v := begin have := calc 2 * y^2 = (x^2 + y^2) - (x^2 - y^2) : (gcd.sum_difference_difference (pow_le_pow_of_le_left y_le_x 2)).symm ... = s^2 - t^2 : by rw [Hs, Ht] ... = s*s - t*t : by repeat { rw nat.pow_two } ... = (s + t) * (s - t) : by rw nat.mul_self_sub_mul_self_eq ... = (2 * u) * (2 * v) : by rw [lu, lv] ... = 2 * (2 * u * v) : by ac_refl, exact eq_of_mul_eq_mul_left dec_trivial this end lemma u2_v2_x2 : u^2 + v^2 = x^2 := begin have := calc (2^2) * x^2 = (2 * 2) * x^2 : by reflexivity ... = 2 * (2 * x^2) : by rw [mul_assoc] ... = 2 * ((x^2 - y^2) + (x^2 + y^2)) : by rw (gcd.sum_difference_sum (pow_le_pow_of_le_left y_le_x 2)) ... = 2 * (s^2 + t^2) : by rw [Hs, Ht, add_comm] ... = (s + t)^2 + (s - t)^2 : nat.polarization t_le_s ... = (2 * u)^2 + (2 * v)^2 : by rw [lu, lv] ... = 2^2 * u^2 + 2^2 * v^2 : by rw [nat.mul_pow, nat.mul_pow] ... = 2^2 * (u^2 + v^2) : by rw mul_add, exact eq_of_mul_eq_mul_left dec_trivial this.symm end lemma y_even : even y := begin apply even_iff_square_even.mpr, rw [y2_2uv, mul_assoc], apply two_n_even end def half_y := y / 2 lemma ly : 2 * half_y = y := nat.mul_div_cancel' (even_iff_two_dvd.mp y_even) lemma u_or_v_even : even u ∨ even v := begin by_contradiction a, cases (decidable.not_or_iff_and_not (even u) (even v)).mp a with neu nev, rw [even_xor_odd.resolve_left] at neu nev, have := calc 2 * (u * v) = 2 * u * v : by ac_refl ... = y^2 : y2_2uv.symm ... = (2 * half_y)^2 : by rw ly ... = (2 * half_y) * (2 * half_y) : pow_two ... = 2 * (2 * (half_y * half_y)) : by ac_refl, have := nat.eq_of_mul_eq_mul_left dec_trivial this, have odd_uv : odd (u * v) := odd_times_odd_is_odd neu nev, have also_even : even (2 * (half_y * half_y)) := two_n_even _, rw ←this at also_even, exact not_even_and_odd _ ⟨also_even, odd_uv⟩ end lemma uvx_pos : u > 0 ∧ v > 0 ∧ x > 0 := begin repeat { split }, { apply pos_of_pos_mul, rw lu, exact calc s + t ≥ s : le_add_right _ _ ... > 0 : s_pos }, { apply pos_of_pos_mul, rw lv, exact nat.sub_pos_of_lt t_lt_s }, { exact x_pos } end -- have u_v, u^2 + v^2 = x^2, y^2 = 2 * u * v, u > 0 ∧ v > 0 -- If u is even, swap u & v section even_v parameters u' v' : ℕ parameter u'_pos : u' > 0 parameter v'_pos : v' > 0 parameter u'_v' : coprime u' v' parameter u'2_v'2_x2 : u'^2 + v'^2 = x^2 parameter y2_2u'v' : y^2 = 2 * u' * v' include u'_pos v'_pos u'_v' u'2_v'2_x2 y2_2u'v' parameter even_v' : even v' include even_v' lemma u'v'x_pos : u' > 0 ∧ v' > 0 ∧ x > 0 := ⟨u'_pos, v'_pos, x_pos⟩ lemma u'_2v' : coprime u' (2 * v') := begin refine coprime.mul_right _ u'_v', exact coprime.coprime_dvd_right (even_iff_two_dvd.mp even_v') u'_v' end lemma v'_twice_square_etc : ∃ m k, u' = m^2 ∧ v' = 2 * k^2 := begin have u'2v'_y2 : u' * (2 * v') = y^2 := calc u' * (2 * v') = 2 * u' * v' : by ac_refl ... = y^2 : y2_2u'v'.symm, rcases coprime_square_product u'2v'_y2 u'_2v' with ⟨m, k1, Hm, Hk1⟩, have even_k1 : even k1 := begin apply or.resolve_right (even_or_odd k1), intro odd_k1, have := odd_square_is_odd odd_k1, rw ←Hk1 at this, have := two_n_not_odd v', contradiction end, let k := k1 / 2, have H' := nat.mul_div_cancel' (even_iff_two_dvd.mp even_k1), existsi [m, k], split, { exact Hm }, { have := calc 2 * v' = k1^2 : Hk1 ... = (2 * k)^2 : by rw H' ... = (2*k)*(2*k) : nat.pow_two ... = 2*(2*(k*k)) : by ac_refl ... = 2*(2*k^2) : by rw ←nat.pow_two, exact nat.eq_of_mul_eq_mul_left dec_trivial this } end lemma case_b : ∃ g h k, 0 < g ∧ 0 < h ∧ 0 < k ∧ g < x ∧ g^4 = h^4 + k^2 := begin rcases ex u' v' x u'2_v'2_x2 u'_v' even_v' u'v'x_pos with ⟨d, e, dpos, epos, d_gt_e, d_e, Hu', Hv', Hx⟩, rcases v'_twice_square_etc with ⟨m, k, Hm, Hk⟩, have : k^2 = d * e := nat.eq_of_mul_eq_mul_left (dec_trivial : 2 > 0) ( calc 2 * k^2 = v' : Hk.symm ... = 2 * d * e : Hv' ... = 2 * (d * e) : by rw mul_assoc), rcases coprime_square_product this.symm d_e with ⟨g_, h, Hg, Hh⟩, -- Weird shadowing behavior if we use "g", because u depends on the -- assuption "g" defined way above. existsi [g_, h, m], repeat { split }, { exact pos_of_square_pos (Hg ▸ dpos) }, { exact pos_of_square_pos (Hh ▸ epos) }, { exact pos_of_square_pos (Hm ▸ u'v'x_pos.1) }, { exact calc g_ ≤ g_^2 : le_square ... = d : Hg.symm ... ≤ d^2 : le_square ... < d^2 + e^2 : nat.lt_add_of_pos_right (pos_pow_of_pos 2 epos) ... = x : Hx.symm }, { exact calc g_^4 = (g_^2)^2 : by rw square_twice ... = d^2 : by rw Hg ... = d^2 - e^2 + e^2 : by rw nat.sub_add_cancel (pow_le_pow_of_le_left (le_of_lt d_gt_e) 2) ... = u' + e^2 : by rw Hu' ... = m^2 + (h^2)^2 : by rw [Hm, Hh] ... = h^4 + m^2 : by rw [square_twice, add_comm] } end end even_v end case_b end x_y set_option trace.simplify.rewrite true lemma descent : ∃ x' y' z', 0 < x' ∧ 0 < y' ∧ 0 < z' ∧ x' < x ∧ x'^4 = y'^4 + z'^2 := begin let g := gcd x y, have g_pos : g > 0 := gcd_pos_of_pos_left y x_pos, cases eq_or_lt_of_le (succ_le_of_lt g_pos) with g_eq_1 g_gt_1, swap, { -- g > 1 have g_dvd_x : g ∣ x := (gcd_dvd x y).left, have g_dvd_y : g ∣ y := (gcd_dvd x y).right, let x' := x/g, have Hx' : g * x' = x := nat.mul_div_cancel' g_dvd_x, let y' := y/g, have Hy' : g * y' = y := nat.mul_div_cancel' g_dvd_y, have g2_dvd_z : g^2 ∣ z := begin -- nat.dvd_sub doesn't actually need the (H : n ≤ m) hypothesis have : g^4 ∣ z^2 := (nat.dvd_add_iff_right (pow_dvd_pow_of_dvd g_dvd_y)).mpr (fmt ▸ pow_dvd_pow_of_dvd g_dvd_x), apply dvd_of_pow_dvd_pow (dec_trivial : 2 > 0), rwa square_twice end, let z' := z/(g^2), have Hz' : g^2 * z' = z := nat.mul_div_cancel' g2_dvd_z, existsi [x', y', z'], repeat { split }, { apply pos_of_pos_mul, rw Hx', exact x_pos }, { apply pos_of_pos_mul, rw Hy', exact y_pos }, { apply pos_of_pos_mul, rw Hz', exact z_pos }, { exact div_lt_self x_pos g_gt_1 }, { have := calc g^4 * x'^4 = (g * x')^4 : by rw nat.mul_pow ... = x^4 : by rw Hx' ... = y^4 + z^2 : by rw fmt ... = (g * y')^4 + (g^2 * z')^2 : by rw [Hy', Hz'] ... = g^4 * y'^4 + g^4 * z'^2 : by rw [nat.mul_pow, nat.mul_pow, square_twice] ... = g^4 * (y'^4 + z'^2) : by rw mul_add, exact nat.eq_of_mul_eq_mul_left (pos_pow_of_pos 4 g_pos) this } }, { -- g = 1 have x_y : coprime x y := g_eq_1.symm, let gmp := gcd (x^2 - y^2) (x^2 + y^2), have : gmp ∣ 2 := l2 x_y, cases (dvd_prime dec_trivial).mp this with gmp1 gmp2, swap, { -- gmp = 2 exact case_a x_y gmp2 -- planning!! }, { -- gmp = 1 rcases coprime_square_product l1 ((gcd_comm _ _).trans gmp1) with ⟨s,t,Hs,Ht⟩, -- this got a bit out of control let u0 := u x_y gmp1 s t Hs Ht, let v0 := v x_y gmp1 s t Hs Ht, let uvx_pos0 := uvx_pos x_y gmp1 s t Hs Ht, let u_v0 := u_v x_y gmp1 s t Hs Ht, let u2_v2_x2_0 := u2_v2_x2 x_y gmp1 s t Hs Ht, let y2_2uv_0 := y2_2uv x_y gmp1 s t Hs Ht, have : even u0 ∨ even v0 := u_or_v_even x_y gmp1 s t Hs Ht, cases this with even_u0 even_v0, { have u2_v2_x2' : v0^2 + u0^2 = x^2 := calc v0^2 + u0^2 = u0^2 + v0^2 : by ac_refl ... = x^2 : u2_v2_x2_0, have y2_2uv' : y^2 = 2 * v0 * u0 := calc y^2 = 2 * u0 * v0 : y2_2uv_0 ... = 2 * v0 * u0 : by ac_refl, refine case_b x_y gmp1 s t Hs Ht v0 u0 uvx_pos0.2.1 uvx_pos0.1 (coprime.symm u_v0) u2_v2_x2' y2_2uv' even_u0 }, { exact case_b x_y gmp1 s t Hs Ht u0 v0 uvx_pos0.1 uvx_pos0.2.1 u_v0 u2_v2_x2_0 y2_2uv_0 even_v0 }, } } end end fermat lemma no_solutions' : ∀ x, ¬(∃ y z, 0 < x ∧ 0 < y ∧ 0 < z ∧ x^4 = y^4 + z^2) := begin intro x0, refine nat.strong_induction_on x0 _, intros x iH a, rcases a with ⟨y,z,x_pos,y_pos,z_pos,fmt⟩, rcases descent x y z fmt ⟨x_pos,y_pos,z_pos⟩ with ⟨x',y',z',x'_pos,y'_pos,z'_pos,x'_lt_x,fmt'⟩, exact iH x' x'_lt_x ⟨y',z',x'_pos,y'_pos,z'_pos,fmt'⟩, end theorem no_solutions : ¬(∃ x y z, 0 < x ∧ 0 < y ∧ 0 < z ∧ x^4 = y^4 + z^2) := not_exists_of_forall_not no_solutions' theorem fermat4 : ¬(∃ a b c, 0 < a ∧ 0 < b ∧ 0 < c ∧ a^4 + b^4 = c^4) := begin intros H, rcases H with ⟨a,b,c,a_pos,b_pos,c_pos,fmt⟩, have fmt' : c^4 = a^4 + (b^2)^2 := calc c^4 = a^4 + b^4 : fmt.symm ... = a^4 + (b^2)^2 : by rw square_twice, have b2_pos := pos_pow_of_pos 2 b_pos, exact no_solutions ⟨c,a,b^2,c_pos,a_pos,b2_pos,fmt'⟩ end
73571132f5c6bfb9377acab75c31681c22207db7
c8b4b578b2fe61d500fbca7480e506f6603ea698
/src/number_theory/regular_primes.lean
bce3fcd4b334581c002258c0d03f76e4e35aefb9
[]
no_license
leanprover-community/flt-regular
aa7e564f2679dfd2e86015a5a9674a6e1197f7cc
67fb3e176584bbc03616c221a7be6fa28c5ccd32
refs/heads/master
1,692,188,905,751
1,691,766,312,000
1,691,766,312,000
421,021,216
19
4
null
1,694,532,115,000
1,635,166,136,000
Lean
UTF-8
Lean
false
false
4,087
lean
import field_theory.splitting_field.construction import number_theory.bernoulli import number_theory.class_number.finite import number_theory.class_number.admissible_abs import number_theory.cyclotomic.cycl_rat import number_theory.cyclotomic.rat /-! # Regular primes ## Main definitions * `is_regular_number`: a natural number `n` is regular if `n` is coprime with the cardinal of the class group. -/ noncomputable theory open nat polynomial open number_field open_locale classical number_field section safe_instances /- The idea of `open_locale cyclotomic` is that it provides some of these instances when needed, but sadly its implementation is so unsafe that using it here creates a lot of diamonds. We instead put some safe specialised instances here, and we can maybe look at generalising them later, when this is needed. Most results from here on genuinely only work for ℚ, so this is very fine for the moment. -/ -- todo: now the diamond is fixed, `open_locale cyclotomic` may be fine. instance safe {p : ℕ+} := is_cyclotomic_extension.number_field {p} ℚ $ cyclotomic_field p ℚ instance safe' {p : ℕ+} := is_cyclotomic_extension.finite_dimensional {p} ℚ $ cyclotomic_field p ℚ instance cyclotomic_field.class_group_finite {p : ℕ+} : fintype (class_group $ 𝓞 (cyclotomic_field p ℚ)) := class_group.fintype_of_admissible_of_finite ℚ (cyclotomic_field p ℚ) absolute_value.abs_is_admissible end safe_instances variables (n p : ℕ) [fact p.prime] instance {p : ℕ} [hp : fact p.prime] : fact (0 < p) := ⟨hp.out.pos⟩ -- note that this definition can be annoying to work with whilst #14984 isn't merged. /-- A natural number `n` is regular if `n` is coprime with the cardinal of the class group -/ def is_regular_number [hn : fact (0 < n)] : Prop := n.coprime $ fintype.card $ class_group (𝓞 $ cyclotomic_field ⟨n, hn.out⟩ ℚ) /-- The definition of regular primes. -/ def is_regular_prime : Prop := is_regular_number p /-- A prime number is Bernoulli regular if it does not divide the numerator of any of the first `p - 3` (non-zero) Bernoulli numbers-/ def is_Bernoulli_regular : Prop := ∀ i ∈ finset.range((p - 3) / 2), ((bernoulli 2 * i).num : zmod p) ≠ 0 /--A prime is super regular if its regular and Bernoulli regular.-/ def is_super_regular : Prop := is_regular_number p ∧ is_Bernoulli_regular p section two_regular variables (A K : Type*) [comm_ring A] [is_domain A] [field K] [algebra A K] [is_fraction_ring A K] variables (L : Type*) [field L] [algebra K L] /-- The second cyclotomic field is equivalent to the base field. -/ def cyclotomic_field_two_equiv [is_cyclotomic_extension {2} K L] : L ≃ₐ[K] K := begin suffices : is_splitting_field K K (cyclotomic 2 K), { letI : is_splitting_field K L (cyclotomic 2 K) := is_cyclotomic_extension.splitting_field_cyclotomic 2 K L, exact (is_splitting_field.alg_equiv L (cyclotomic 2 K)).trans (is_splitting_field.alg_equiv K $ cyclotomic 2 K).symm }, exact ⟨by simpa using @splits_X_sub_C _ _ _ _ (ring_hom.id K) (-1), by simp⟩, end instance (L : Type*) [field L] [char_zero L] [is_cyclotomic_extension {2} ℚ L] : is_principal_ideal_ring (𝓞 L) := begin haveI : is_integral_closure ℤ ℤ L := { algebra_map_injective := (algebra_map ℤ L).injective_int, is_integral_iff := λ x, begin let f := (cyclotomic_field_two_equiv ℚ L), refine ⟨λ hx, ⟨is_integral_closure.mk' ℤ (f x) (map_is_integral_int f hx), f.injective _⟩, _⟩, { convert is_integral_closure.algebra_map_mk' ℤ (f x) (map_is_integral_int f hx), simp }, { rintro ⟨y, hy⟩, simpa [← hy] using is_integral_algebra_map } end }, let F : 𝓞 L ≃+* ℤ := number_field.ring_of_integers.equiv _, exact is_principal_ideal_ring.of_surjective F.symm.to_ring_hom F.symm.surjective, end lemma is_regular_number_two : is_regular_number 2 := begin rw is_regular_number, convert coprime_one_right _, dsimp, rw card_class_group_eq_one_iff, apply_instance, end end two_regular
773921b561e9690286be02718b0522897b76a8ec
453dcd7c0d1ef170b0843a81d7d8caedc9741dce
/analysis/probability_mass_function.lean
fcae29a11a1ce92739c895a2335910776c7a2012
[ "Apache-2.0" ]
permissive
amswerdlow/mathlib
9af77a1f08486d8fa059448ae2d97795bd12ec0c
27f96e30b9c9bf518341705c99d641c38638dfd0
refs/heads/master
1,585,200,953,598
1,534,275,532,000
1,534,275,532,000
144,564,700
0
0
null
1,534,156,197,000
1,534,156,197,000
null
UTF-8
Lean
false
false
4,771
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl Probability mass function -- discrete probability measures -/ import analysis.nnreal analysis.ennreal analysis.topology.infinite_sum noncomputable theory variables {α : Type*} {β : Type*} {γ : Type*} local attribute [instance] classical.prop_decidable /-- Probability mass functions, i.e. discrete probability measures -/ def {u} pmf (α : Type u) : Type u := { f : α → nnreal // is_sum f 1 } namespace pmf instance : has_coe_to_fun (pmf α) := ⟨λp, α → nnreal, λp a, p.1 a⟩ @[extensionality] protected lemma ext : ∀{p q : pmf α}, (∀a, p a = q a) → p = q | ⟨f, hf⟩ ⟨g, hg⟩ eq := subtype.eq $ funext eq lemma is_sum_coe_one (p : pmf α) : is_sum p 1 := p.2 lemma has_sum_coe (p : pmf α) : has_sum p := has_sum_spec p.is_sum_coe_one @[simp] lemma tsum_coe (p : pmf α) : (∑a, p a) = 1 := tsum_eq_is_sum p.is_sum_coe_one def support (p : pmf α) : set α := {a | p.1 a ≠ 0} def pure (a : α) : pmf α := ⟨λa', if a' = a then 1 else 0, is_sum_ite _ _⟩ @[simp] lemma pure_apply (a a' : α) : pure a a' = (if a' = a then 1 else 0) := rfl instance [inhabited α] : inhabited (pmf α) := ⟨pure (default α)⟩ lemma coe_le_one (p : pmf α) (a : α) : p a ≤ 1 := is_sum_le (by intro b; split_ifs; simp [h]; exact le_refl _) (is_sum_ite a (p a)) p.2 protected lemma bind.has_sum (p : pmf α) (f : α → pmf β) (b : β) : has_sum (λa:α, p a * f a b) := begin refine nnreal.has_sum_of_le (assume a, _) p.has_sum_coe, suffices : p a * f a b ≤ p a * 1, { simpa }, exact mul_le_mul_of_nonneg_left ((f a).coe_le_one _) (p a).2 end def bind (p : pmf α) (f : α → pmf β) : pmf β := ⟨λb, (∑a, p a * f a b), begin simp [ennreal.is_sum_coe_iff.symm, ennreal.coe_tsum (bind.has_sum p f _)], rw [is_sum_iff_of_has_sum ennreal.has_sum, ennreal.tsum_comm], simp [ennreal.mul_tsum, (ennreal.coe_tsum (f _).has_sum_coe).symm, (ennreal.coe_tsum p.has_sum_coe).symm] end⟩ @[simp] lemma bind_apply (p : pmf α) (f : α → pmf β) (b : β) : p.bind f b = (∑a, p a * f a b) := rfl lemma coe_bind_apply (p : pmf α) (f : α → pmf β) (b : β) : (p.bind f b : ennreal) = (∑a, p a * f a b) := eq.trans (ennreal.coe_tsum $ bind.has_sum p f b) $ by simp @[simp] lemma pure_bind (a : α) (f : α → pmf β) : (pure a).bind f = f a := have ∀b a', ite (a' = a) 1 0 * f a' b = ite (a' = a) (f a b) 0, from assume b a', by split_ifs; simp; subst h; simp, by ext b; simp [this] @[simp] lemma bind_pure (p : pmf α) : p.bind pure = p := have ∀a a', (p a * ite (a' = a) 1 0) = ite (a = a') (p a') 0, from assume a a', begin split_ifs; try { subst a }; try { subst a' }; simp * at * end, by ext b; simp [this] @[simp] lemma bind_bind (p : pmf α) (f : α → pmf β) (g : β → pmf γ) : (p.bind f).bind g = p.bind (λa, (f a).bind g) := begin ext b, simp only [ennreal.coe_eq_coe.symm, coe_bind_apply, ennreal.mul_tsum.symm, ennreal.tsum_mul.symm], rw [ennreal.tsum_comm], simp [mul_assoc, mul_left_comm, mul_comm] end lemma bind_comm (p : pmf α) (q : pmf β) (f : α → β → pmf γ) : p.bind (λa, q.bind (f a)) = q.bind (λb, p.bind (λa, f a b)) := begin ext b, simp only [ennreal.coe_eq_coe.symm, coe_bind_apply, ennreal.mul_tsum.symm, ennreal.tsum_mul.symm], rw [ennreal.tsum_comm], simp [mul_assoc, mul_left_comm, mul_comm] end def map (f : α → β) (p : pmf α) : pmf β := bind p (pure ∘ f) lemma bind_pure_comp (f : α → β) (p : pmf α) : bind p (pure ∘ f) = map f p := rfl lemma map_id (p : pmf α) : map id p = p := by simp [map] lemma map_comp (p : pmf α) (f : α → β) (g : β → γ) : (p.map f).map g = p.map (g ∘ f) := by simp [map] lemma pure_map (a : α) (f : α → β) : (pure a).map f = pure (f a) := by simp [map] def seq (f : pmf (α → β)) (p : pmf α) : pmf β := f.bind (λm, p.bind $ λa, pure (m a)) def of_multiset (s : multiset α) (hs : s ≠ 0) : pmf α := ⟨λa, s.count a / s.card, have s.to_finset.sum (λa, (s.count a : ℝ) / s.card) = 1, by simp [div_eq_inv_mul, finset.mul_sum.symm, (finset.sum_nat_cast _ _).symm, hs], have s.to_finset.sum (λa, (s.count a : nnreal) / s.card) = 1, by rw [← nnreal.eq_iff, nnreal.coe_one, ← this, ← nnreal.sum_coe]; simp, begin rw ← this, apply is_sum_sum_of_ne_finset_zero, simp {contextual := tt}, end⟩ def of_fintype [fintype α] (f : α → nnreal) (h : finset.univ.sum f = 1) : pmf α := ⟨f, h ▸ is_sum_sum_of_ne_finset_zero (by simp)⟩ def bernoulli (p : nnreal) (h : p ≤ 1) : pmf bool := of_fintype (λb, cond b p (1 - p)) (nnreal.eq $ by simp [h]) end pmf
c02ea1e8068621d4f97a4a5357a930a593a0d596
6db8061629f55e774dd3d03be5bf005ffb485e48
/BetterNumLits.lean
85e3caaa0c1ed571bfee38fe520a5453fdedc5e2
[]
no_license
tydeu/lean4-betterNumLits
21fd5717d1b62ecb021c73e8cfaa0e3d19005690
45e3b79214b3e1f81f8e034dd12257e993ddc578
refs/heads/master
1,683,103,070,685
1,621,717,131,000
1,621,717,131,000
369,368,844
0
0
null
null
null
null
UTF-8
Lean
false
false
200
lean
import BetterNumLits.Numerals import BetterNumLits.Notation import BetterNumLits.Nat import BetterNumLits.OfRadix import BetterNumLits.Fin import BetterNumLits.Macro import BetterNumLits.Unexpanders
16c5a311cbc7083427b8e7a7790d3f2285142197
8e31b9e0d8cec76b5aa1e60a240bbd557d01047c
/scratch/partition.lean
90a1ad65f90c60b771ecf2c3c0c184c50dfe3c80
[]
no_license
ChrisHughes24/LP
7bdd62cb648461c67246457f3ddcb9518226dd49
e3ed64c2d1f642696104584e74ae7226d8e916de
refs/heads/master
1,685,642,642,858
1,578,070,602,000
1,578,070,602,000
195,268,102
4
3
null
1,569,229,518,000
1,562,255,287,000
Lean
UTF-8
Lean
false
false
17,223
lean
import data.matrix.pequiv data.rat.basic variables {m n : ℕ} /-- The type of ordered partitions of `m + n` elements into a `m` row variables and `n` column variables -/ structure partition (m n : ℕ) : Type := ( rowp : fin m ≃. fin (m + n) ) ( colp : fin n ≃. fin (m + n) ) ( rowp_trans_rowp_symm : rowp.trans rowp.symm = pequiv.refl (fin m) ) ( colp_trans_colp_symm : colp.trans colp.symm = pequiv.refl (fin n) ) ( rowp_trans_colp_symm : rowp.trans colp.symm = ⊥ ) namespace partition open pequiv function matrix finset fintype local infix ` ⬝ `:70 := matrix.mul local postfix `ᵀ` : 1500 := transpose attribute [simp] rowp_trans_rowp_symm colp_trans_colp_symm rowp_trans_colp_symm lemma fin.coe_eq_val (a : fin n) : (a : ℕ) = a.val := rfl def default : partition m n := { rowp := { to_fun := some ∘ fin.cast_le (le_add_right (le_refl _)), inv_fun := λ j, if hm : j.1 < m then some ⟨j, hm⟩ else none, inv := begin rintros ⟨i, _⟩ ⟨j, _⟩, split_ifs; simp [fin.coe_eq_val, fin.cast_le, fin.cast_lt, eq_comm, -not_lt]; intro; simp [*, -not_lt] at *, end }, colp := { to_fun := λ i, some ⟨m + i, add_lt_add_of_le_of_lt (le_refl _) i.2⟩, inv_fun := λ j, if hm : m ≤ j.1 then some ⟨j - m, (nat.sub_lt_left_iff_lt_add hm).2 j.2⟩ else none, inv := begin rintros ⟨i, _⟩ ⟨j, _⟩, simp [pequiv.trans, pequiv.symm, fin.cast_le, fin.cast_lt, fin.coe_eq_val, fin.ext_iff], split_ifs, { simp [fin.ext_iff, nat.sub_eq_iff_eq_add h, @eq_comm _ j] at * }, { simp, intro, subst j, simp [nat.le_add_left, *] at * } end }, rowp_trans_rowp_symm := trans_symm_eq_iff_forall_is_some.2 (λ _, rfl), colp_trans_colp_symm := trans_symm_eq_iff_forall_is_some.2 (λ _, rfl), rowp_trans_colp_symm := pequiv.ext begin rintro ⟨i, hi⟩, dsimp [pequiv.trans, pequiv.symm, fin.cast_le, fin.cast_lt], rw [dif_neg (not_le_of_gt hi)] end } instance : inhabited (partition m n) := ⟨default⟩ lemma is_some_rowp (B : partition m n) : ∀ (i : fin m), (B.rowp i).is_some := by rw [← trans_symm_eq_iff_forall_is_some, rowp_trans_rowp_symm] lemma is_some_colp (B : partition m n) : ∀ (k : fin n), (B.colp k).is_some := by rw [← trans_symm_eq_iff_forall_is_some, colp_trans_colp_symm] lemma injective_rowp (B : partition m n) : injective B.rowp := injective_of_forall_is_some (is_some_rowp B) lemma injective_colp (B : partition m n) : injective B.colp := injective_of_forall_is_some (is_some_colp B) /-- given a row index, `rowg` returns the variable in that position -/ def rowg (B : partition m n) (r : fin m) : fin (m + n) := option.get (B.is_some_rowp r) /-- given a column index, `colg` returns the variable in that position -/ def colg (B : partition m n) (s : fin n) : fin (m + n) := option.get (B.is_some_colp s) lemma injective_rowg (B : partition m n) : injective B.rowg := λ x y h, by rw [rowg, rowg, ← option.some_inj, option.some_get, option.some_get] at h; exact injective_rowp B h lemma injective_colg (B : partition m n) : injective B.colg := λ x y h, by rw [colg, colg, ← option.some_inj, option.some_get, option.some_get] at h; exact injective_colp B h local infix ` ♣ `: 70 := pequiv.trans def swap (B : partition m n) (r : fin m) (s : fin n) : partition m n := { rowp := B.rowp.trans (equiv.swap (B.rowg r) (B.colg s)).to_pequiv, colp := B.colp.trans (equiv.swap (B.rowg r) (B.colg s)).to_pequiv, rowp_trans_rowp_symm := by rw [symm_trans_rev, ← trans_assoc, trans_assoc B.rowp, ← equiv.to_pequiv_symm, ← equiv.to_pequiv_trans]; simp, colp_trans_colp_symm := by rw [symm_trans_rev, ← trans_assoc, trans_assoc B.colp, ← equiv.to_pequiv_symm, ← equiv.to_pequiv_trans]; simp, rowp_trans_colp_symm := by rw [symm_trans_rev, ← trans_assoc, trans_assoc B.rowp, ← equiv.to_pequiv_symm, ← equiv.to_pequiv_trans]; simp } lemma not_is_some_colp_of_is_some_rowp (B : partition m n) (j : fin (m + n)) : (B.rowp.symm j).is_some → (B.colp.symm j).is_some → false := begin rw [option.is_some_iff_exists, option.is_some_iff_exists], rintros ⟨i, hi⟩ ⟨k, hk⟩, have : B.rowp.trans B.colp.symm i = none, { rw [B.rowp_trans_colp_symm, pequiv.bot_apply] }, rw [pequiv.trans_eq_none] at this, rw [pequiv.eq_some_iff] at hi, exact (this j k).resolve_left (not_not.2 hi) hk end @[simp] lemma rowg_mem (B : partition m n) (r : fin m) : (B.rowg r) ∈ B.rowp r := option.get_mem _ lemma rowp_eq_some_rowg (B : partition m n) (r : fin m) : B.rowp r = some (B.rowg r) := rowg_mem _ _ @[simp] lemma colg_mem (B : partition m n) (s : fin n) : (B.colg s) ∈ B.colp s := option.get_mem _ lemma colp_eq_some_colg (B : partition m n) (s : fin n) : B.colp s = some (B.colg s) := colg_mem _ _ @[simp] lemma rowp_rowg (B : partition m n) (r : fin m) : B.rowp.symm (B.rowg r) = some r := B.rowp.mem_iff_mem.2 (rowg_mem _ _) @[simp] lemma colp_colg (B : partition m n) (s : fin n) : B.colp.symm (B.colg s) = some s := B.colp.mem_iff_mem.2 (colg_mem _ _) lemma colp_ne_none_of_rowp_eq_none (B : partition m n) (v : fin (m + n)) (hb : B.rowp.symm v = none) (hnb : B.colp.symm v = none) : false := have hs : card (univ.image B.rowg) = m, by rw [card_image_of_injective _ (B.injective_rowg), card_univ, card_fin], have ht : card (univ.image B.colg) = n, by rw [card_image_of_injective _ (B.injective_colg), card_univ, card_fin], have hst : disjoint (univ.image B.rowg) (univ.image B.colg), from finset.disjoint_left.2 begin simp only [mem_image, exists_imp_distrib, not_exists], assume v i _ hi j _ hj, subst hi, exact not_is_some_colp_of_is_some_rowp B (B.rowg i) (option.is_some_iff_exists.2 ⟨i, by simp⟩) (hj ▸ option.is_some_iff_exists.2 ⟨j, by simp⟩), end, have (univ.image B.rowg) ∪ (univ.image B.colg) = univ, from eq_of_subset_of_card_le (λ _ _, mem_univ _) (by rw [card_disjoint_union hst, hs, ht, card_univ, card_fin]), begin cases mem_union.1 (eq_univ_iff_forall.1 this v); rcases mem_image.1 h with ⟨_, _, h⟩; subst h; simp * at * end lemma is_some_rowp_iff (B : partition m n) (j : fin (m + n)) : (B.rowp.symm j).is_some ↔ ¬(B.colp.symm j).is_some := ⟨not_is_some_colp_of_is_some_rowp B j, by erw [option.not_is_some_iff_eq_none, ← option.ne_none_iff_is_some, forall_swap]; exact colp_ne_none_of_rowp_eq_none B j⟩ @[simp] lemma colp_rowg_eq_none (B : partition m n) (r : fin m) : B.colp.symm (B.rowg r) = none := option.not_is_some_iff_eq_none.1 ((B.is_some_rowp_iff _).1 (is_some_symm_get _ _)) @[simp] lemma rowp_colg_eq_none (B : partition m n) (s : fin n) : B.rowp.symm (B.colg s) = none := option.not_is_some_iff_eq_none.1 (mt (B.is_some_rowp_iff _).1 $ not_not.2 (is_some_symm_get _ _)) lemma eq_rowg_or_colg (B : partition m n) (i : fin (m + n)) : (∃ j, i = B.rowg j) ∨ (∃ j, i = B.colg j) := begin dsimp only [rowg, colg], by_cases h : ↥(B.rowp.symm i).is_some, { cases option.is_some_iff_exists.1 h with j hj, exact or.inl ⟨j, by rw [B.rowp.eq_some_iff] at hj; rw [← option.some_inj, ← hj, option.some_get]⟩ }, { rw [(@not_iff_comm _ _ (classical.dec _) (classical.dec _)).1 (B.is_some_rowp_iff _).symm] at h, cases option.is_some_iff_exists.1 h with j hj, exact or.inr ⟨j, by rw [B.colp.eq_some_iff] at hj; rw [← option.some_inj, ← hj, option.some_get]⟩ } end lemma rowg_ne_colg (B : partition m n) (i : fin m) (j : fin n) : B.rowg i ≠ B.colg j := λ h, by simpa using congr_arg B.rowp.symm h @[simp] lemma option.get_inj {α : Type*} : Π {a b : option α} {ha : a.is_some} {hb : b.is_some}, option.get ha = option.get hb ↔ a = b | (some a) (some b) _ _ := by rw [option.get_some, option.get_some, option.some_inj] @[extensionality] lemma ext {B C : partition m n} (h : ∀ i, B.rowg i = C.rowg i) (h₂ : ∀ j, B.colg j = C.colg j) : B = C := begin cases B, cases C, simp [rowg, colg, function.funext_iff, pequiv.ext_iff] at *, tauto end @[simp] lemma single_rowg_mul_rowp (B : partition m n) (i : fin m) : ((single (0 : fin 1) (B.rowg i)).to_matrix : matrix _ _ ℚ) ⬝ B.rowp.to_matrixᵀ = (single (0 : fin 1) i).to_matrix := by rw [← to_matrix_symm, ← to_matrix_trans, single_trans_of_mem _ (rowp_rowg _ _)] @[simp] lemma single_rowg_mul_colp (B : partition m n) (i : fin m) : ((single (0 : fin 1) (B.rowg i)).to_matrix : matrix _ _ ℚ) ⬝ B.colp.to_matrixᵀ = 0 := by rw [← to_matrix_symm, ← to_matrix_trans, single_trans_of_eq_none _ (colp_rowg_eq_none _ _), to_matrix_bot]; apply_instance @[simp] lemma single_colg_mul_colp (B : partition m n) (k : fin n) : ((single (0 : fin 1) (B.colg k)).to_matrix : matrix _ _ ℚ) ⬝ B.colp.to_matrixᵀ = (single (0 : fin 1) k).to_matrix := by rw [← to_matrix_symm, ← to_matrix_trans, single_trans_of_mem _ (colp_colg _ _)] lemma single_colg_mul_rowp (B : partition m n) (k : fin n) : ((single (0 : fin 1) (B.colg k)).to_matrix : matrix _ _ ℚ) ⬝ B.rowp.to_matrixᵀ = 0 := by rw [← to_matrix_symm, ← to_matrix_trans, single_trans_of_eq_none _ (rowp_colg_eq_none _ _), to_matrix_bot]; apply_instance lemma colp_trans_rowp_symm (B : partition m n) : B.colp.trans B.rowp.symm = ⊥ := symm_injective $ by rw [symm_trans_rev, symm_symm, rowp_trans_colp_symm, symm_bot] @[simp] lemma colp_mul_rowp_transpose (B : partition m n) : (B.colp.to_matrix : matrix _ _ ℚ) ⬝ B.rowp.to_matrixᵀ = 0 := by rw [← to_matrix_bot, ← B.colp_trans_rowp_symm, to_matrix_trans, to_matrix_symm] @[simp] lemma rowp_mul_colp_transpose (B : partition m n) : (B.rowp.to_matrix : matrix _ _ ℚ) ⬝ B.colp.to_matrixᵀ = 0 := by rw [← to_matrix_bot, ← B.rowp_trans_colp_symm, to_matrix_trans, to_matrix_symm] @[simp] lemma colp_mul_colp_transpose (B : partition m n) : (B.colp.to_matrix : matrix _ _ ℚ) ⬝ B.colp.to_matrixᵀ = 1 := by rw [← to_matrix_refl, ← B.colp_trans_colp_symm, to_matrix_trans, to_matrix_symm] @[simp] lemma rowp_mul_rowp_transpose (B : partition m n) : (B.rowp.to_matrix : matrix _ _ ℚ) ⬝ B.rowp.to_matrixᵀ = 1 := by rw [← to_matrix_refl, ← B.rowp_trans_rowp_symm, to_matrix_trans, to_matrix_symm] lemma transpose_mul_add_transpose_mul (B : partition m n) : (B.rowp.to_matrixᵀ ⬝ B.rowp.to_matrix : matrix _ _ ℚ) + B.colp.to_matrixᵀ ⬝ B.colp.to_matrix = 1 := begin ext, repeat {rw [← to_matrix_symm, ← to_matrix_trans] }, simp only [add_val, pequiv.symm_trans, pequiv.to_matrix, one_val, pequiv.mem_of_set_iff, set.mem_set_of_eq], have := is_some_rowp_iff B j, split_ifs; tauto end lemma swap_rowp_eq (B : partition m n) (r : fin m) (s : fin n) : (B.swap r s).rowp.to_matrix = (B.rowp.to_matrix : matrix _ _ ℚ) - (single r (B.rowg r)).to_matrix + (single r (B.colg s)).to_matrix := begin dsimp [swap], rw [to_matrix_trans, to_matrix_swap], simp only [matrix.mul_add, sub_eq_add_neg, matrix.mul_one, matrix.mul_neg, (to_matrix_trans _ _).symm, trans_single_of_mem _ (rowg_mem B r), trans_single_of_eq_none _ (rowp_colg_eq_none B s), to_matrix_bot, neg_zero, add_zero] end lemma swap_colp_eq (B : partition m n) (r : fin m) (s : fin n) : (B.swap r s).colp.to_matrix = (B.colp.to_matrix : matrix _ _ ℚ) - (single s (B.colg s)).to_matrix + (single s (B.rowg r)).to_matrix := begin dsimp [swap], rw [to_matrix_trans, to_matrix_swap], simp only [matrix.mul_add, sub_eq_add_neg, matrix.mul_one, matrix.mul_neg, (to_matrix_trans _ _).symm, trans_single_of_mem _ (colg_mem B s), trans_single_of_eq_none _ (colp_rowg_eq_none B r), to_matrix_bot, neg_zero, add_zero] end @[simp] lemma rowg_swap (B : partition m n) (r : fin m) (s : fin n) : (B.swap r s).rowg r = B.colg s := option.some_inj.1 begin dsimp [swap, rowg, colg, pequiv.trans], rw [option.some_get, option.some_get], conv in (B.rowp r) { rw rowp_eq_some_rowg }, dsimp [equiv.to_pequiv, equiv.swap_apply_def, rowg], simp, end @[simp] lemma colg_swap (B : partition m n) (r : fin m) (s : fin n) : (B.swap r s).colg s = B.rowg r := option.some_inj.1 begin dsimp [swap, rowg, colg, pequiv.trans], rw [option.some_get, option.some_get], conv in (B.colp s) { rw colp_eq_some_colg }, dsimp [equiv.to_pequiv, equiv.swap_apply_def, colg], rw [if_neg, if_pos rfl, option.some_get], exact (rowg_ne_colg _ _ _).symm end lemma rowg_swap_of_ne (B : partition m n) {i r : fin m} {s : fin n} (h : i ≠ r) : (B.swap r s).rowg i = B.rowg i := option.some_inj.1 begin dsimp [swap, rowg, colg, pequiv.trans], rw [option.some_get, option.bind_eq_some'], use [B.rowg i, rowp_eq_some_rowg _ _], dsimp [equiv.to_pequiv, equiv.swap_apply_def, option.get_some], rw [← colg, ← rowg, if_neg (rowg_ne_colg B i s), if_neg (mt B.injective_rowg.eq_iff.1 h), rowg] end lemma colg_swap_of_ne (B : partition m n) {r : fin m} {j s : fin n} (h : j ≠ s) : (B.swap r s).colg j = B.colg j := option.some_inj.1 begin dsimp [swap, rowg, colg, pequiv.trans], rw [option.some_get, option.bind_eq_some'], use [B.colg j, colp_eq_some_colg _ _], dsimp [equiv.to_pequiv, equiv.swap_apply_def, option.get_some], rw [← colg, ← rowg, if_neg (rowg_ne_colg B r j).symm, if_neg (mt B.injective_colg.eq_iff.1 h), colg] end lemma rowg_swap' (B : partition m n) (i r : fin m) (s : fin n) : (B.swap r s).rowg i = if i = r then B.colg s else B.rowg i := if hir : i = r then by simp [hir] else by rw [if_neg hir, rowg_swap_of_ne _ hir] lemma colg_swap' (B : partition m n) (r : fin m) (j s : fin n) : (B.swap r s).colg j = if j = s then B.rowg r else B.colg j := if hjs : j = s then by simp [hjs] else by rw [if_neg hjs, colg_swap_of_ne _ hjs] @[simp] lemma swap_swap (B : partition m n) (r : fin m) (s : fin n) : (B.swap r s).swap r s = B := by ext; intros; simp [rowg_swap', colg_swap']; split_ifs; cc @[simp] lemma colp_trans_swap_rowp_symm (B : partition m n) (r : fin m) (s : fin n) : B.colp.trans (B.swap r s).rowp.symm = single s r := begin rw [swap, symm_trans_rev, ← equiv.to_pequiv_symm, ← equiv.perm.inv_def, equiv.swap_inv], ext i j, rw [mem_single_iff], dsimp [pequiv.trans, equiv.to_pequiv, equiv.swap_apply_def], simp only [coe, coe_mk_apply, option.mem_def, option.bind_eq_some'], rw [option.mem_def.1 (colg_mem B i)], simp [B.injective_colg.eq_iff, (B.rowg_ne_colg _ _).symm], split_ifs; simp [*, eq_comm] end @[simp] lemma colp_mul_swap_rowp_tranpose (B : partition m n) (r : fin m) (s : fin n) : (B.colp.to_matrix : matrix _ _ ℚ) ⬝ (B.swap r s).rowp.to_matrixᵀ = (single s r).to_matrix := by rw [← colp_trans_swap_rowp_symm, to_matrix_trans, to_matrix_symm] lemma rowp_trans_swap_rowp_transpose (B : partition m n) (r : fin m) (s : fin n) : B.rowp.trans (B.swap r s).rowp.symm = of_set {i | i ≠ r} := begin rw [swap, symm_trans_rev, ← equiv.to_pequiv_symm, ← equiv.perm.inv_def, equiv.swap_inv], ext i j, dsimp [pequiv.trans, equiv.to_pequiv, equiv.swap_apply_def], simp only [coe, coe_mk_apply, option.mem_def, option.bind_eq_some'], rw [option.mem_def.1 (rowg_mem B i)], simp [B.injective_rowg.eq_iff, B.rowg_ne_colg], split_ifs, { simp * }, { simp *; split; intros; simp * at * } end lemma swap_rowp_transpose_mul_single_of_ne (B : partition m n) {r : fin m} (s : fin n) {i : fin m} (hir : i ≠ r) : ((B.swap r s).rowp.to_matrixᵀ : matrix _ _ ℚ) ⬝ (single i (0 : fin 1)).to_matrix = B.rowp.to_matrixᵀ ⬝ (single i 0).to_matrix := begin simp only [swap_rowp_eq, sub_eq_add_neg, matrix.mul_add, matrix.mul_neg, matrix.mul_one, matrix.add_mul, (to_matrix_trans _ _).symm, (to_matrix_symm _).symm, transpose_add, transpose_neg, matrix.neg_mul, symm_trans_rev, trans_assoc], rw [trans_single_of_mem _ (rowp_rowg _ _), trans_single_of_eq_none, trans_single_of_eq_none, to_matrix_bot, neg_zero, add_zero, add_zero]; {dsimp [single]; simp [*, B.injective_rowg.eq_iff]} <|> apply_instance end @[simp] lemma swap_rowp_transpose_mul_single (B : partition m n) (r : fin m) (s : fin n) : ((B.swap r s).rowp.to_matrixᵀ : matrix _ _ ℚ) ⬝ (single r (0 : fin 1)).to_matrix = B.colp.to_matrixᵀ ⬝ (single s (0 : fin 1)).to_matrix := begin simp only [swap_rowp_eq, sub_eq_add_neg, matrix.mul_add, matrix.mul_neg, matrix.mul_one, matrix.add_mul, (to_matrix_trans _ _).symm, (to_matrix_symm _).symm, transpose_add, transpose_neg, matrix.neg_mul, symm_trans_rev, trans_assoc, symm_single], rw [trans_single_of_mem _ (rowp_rowg _ _), trans_single_of_mem _ (mem_single _ _), trans_single_of_mem _ (mem_single _ _), trans_single_of_mem _ (colp_colg _ _)], simp, all_goals {apply_instance} end def equiv_aux : partition m n ≃ Σ' (rowp : fin m ≃. fin (m + n)) (colp : fin n ≃. fin (m + n)) ( rowp_trans_rowp_symm : rowp.trans rowp.symm = pequiv.refl (fin m) ) ( colp_trans_colp_symm : colp.trans colp.symm = pequiv.refl (fin n) ), rowp.trans colp.symm = ⊥ := { to_fun := λ ⟨a, b, c, d, e⟩, ⟨a, b, c, d, e⟩, inv_fun := λ ⟨a, b, c, d, e⟩, ⟨a, b, c, d, e⟩, left_inv := λ ⟨_, _, _, _, _⟩, rfl, right_inv := λ ⟨_, _, _, _, _⟩, rfl } end partition
d74b7790ce1605c65b595f3c93daf8ce6fa93cad
f083c4ed5d443659f3ed9b43b1ca5bb037ddeb58
/data/analysis/filter.lean
5e25a630030d4d48f79c2e9a7c511701cdb81f33
[ "Apache-2.0" ]
permissive
semorrison/mathlib
1be6f11086e0d24180fec4b9696d3ec58b439d10
20b4143976dad48e664c4847b75a85237dca0a89
refs/heads/master
1,583,799,212,170
1,535,634,130,000
1,535,730,505,000
129,076,205
0
0
Apache-2.0
1,551,697,998,000
1,523,442,265,000
Lean
UTF-8
Lean
false
false
11,827
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Computational realization of filters (experimental). -/ import order.filter open set filter /-- A `cfilter α σ` is a realization of a filter (base) on `α`, represented by a type `σ` together with operations for the top element and the binary inf operation. -/ structure cfilter (α σ : Type*) [partial_order α] := (f : σ → α) (pt : σ) (inf : σ → σ → σ) (inf_le_left : ∀ a b : σ, f (inf a b) ≤ f a) (inf_le_right : ∀ a b : σ, f (inf a b) ≤ f b) variables {α : Type*} {β : Type*} {σ : Type*} {τ : Type*} namespace cfilter section variables [partial_order α] (F : cfilter α σ) instance : has_coe_to_fun (cfilter α σ) := ⟨_, cfilter.f⟩ @[simp] theorem coe_mk (f pt inf h₁ h₂ a) : (@cfilter.mk α σ _ f pt inf h₁ h₂) a = f a := rfl /-- Map a cfilter to an equivalent representation type. -/ def of_equiv (E : σ ≃ τ) : cfilter α σ → cfilter α τ | ⟨f, p, g, h₁, h₂⟩ := { f := λ a, f (E.symm a), pt := E p, inf := λ a b, E (g (E.symm a) (E.symm b)), inf_le_left := λ a b, by simpa using h₁ (E.symm a) (E.symm b), inf_le_right := λ a b, by simpa using h₂ (E.symm a) (E.symm b) } @[simp] theorem of_equiv_val (E : σ ≃ τ) (F : cfilter α σ) (a : τ) : F.of_equiv E a = F (E.symm a) := by cases F; refl end /-- The filter represented by a `cfilter` is the collection of supersets of elements of the filter base. -/ def to_filter (F : cfilter (set α) σ) : filter α := { sets := {a | ∃ b, F b ⊆ a}, univ_sets := ⟨F.pt, subset_univ _⟩, sets_of_superset := λ x y ⟨b, h⟩ s, ⟨b, subset.trans h s⟩, inter_sets := λ x y ⟨a, h₁⟩ ⟨b, h₂⟩, ⟨F.inf a b, subset_inter (subset.trans (F.inf_le_left _ _) h₁) (subset.trans (F.inf_le_right _ _) h₂)⟩ } @[simp] theorem mem_to_filter_sets (F : cfilter (set α) σ) {a : set α} : a ∈ F.to_filter.sets ↔ ∃ b, F b ⊆ a := iff.rfl end cfilter /-- A realizer for filter `f` is a cfilter which generates `f`. -/ structure filter.realizer (f : filter α) := (σ : Type*) (F : cfilter (set α) σ) (eq : F.to_filter = f) protected def cfilter.to_realizer (F : cfilter (set α) σ) : F.to_filter.realizer := ⟨σ, F, rfl⟩ namespace filter.realizer theorem mem_sets {f : filter α} (F : f.realizer) {a : set α} : a ∈ f.sets ↔ ∃ b, F.F b ⊆ a := by cases F; subst f; simp -- Used because it has better definitional equalities than the eq.rec proof def of_eq {f g : filter α} (e : f = g) (F : f.realizer) : g.realizer := ⟨F.σ, F.F, F.eq.trans e⟩ /-- A filter realizes itself. -/ def of_filter (f : filter α) : f.realizer := ⟨f.sets, { f := subtype.val, pt := ⟨univ, univ_mem_sets⟩, inf := λ ⟨x, h₁⟩ ⟨y, h₂⟩, ⟨_, inter_mem_sets h₁ h₂⟩, inf_le_left := λ ⟨x, h₁⟩ ⟨y, h₂⟩, inter_subset_left x y, inf_le_right := λ ⟨x, h₁⟩ ⟨y, h₂⟩, inter_subset_right x y }, filter_eq $ set.ext $ λ x, set_coe.exists.trans exists_sets_subset_iff⟩ /-- Transfer a filter realizer to another realizer on a different base type. -/ def of_equiv {f : filter α} (F : f.realizer) (E : F.σ ≃ τ) : f.realizer := ⟨τ, F.F.of_equiv E, by refine eq.trans _ F.eq; exact filter_eq (set.ext $ λ x, ⟨λ ⟨s, h⟩, ⟨E.symm s, by simpa using h⟩, λ ⟨t, h⟩, ⟨E t, by simp [h]⟩⟩)⟩ @[simp] theorem of_equiv_σ {f : filter α} (F : f.realizer) (E : F.σ ≃ τ) : (F.of_equiv E).σ = τ := rfl @[simp] theorem of_equiv_F {f : filter α} (F : f.realizer) (E : F.σ ≃ τ) (s : τ) : (F.of_equiv E).F s = F.F (E.symm s) := by delta of_equiv; simp /-- `unit` is a realizer for the principal filter -/ protected def principal (s : set α) : (principal s).realizer := ⟨unit, { f := λ _, s, pt := (), inf := λ _ _, (), inf_le_left := λ _ _, le_refl _, inf_le_right := λ _ _, le_refl _ }, filter_eq $ set.ext $ λ x, ⟨λ ⟨_, s⟩, s, λ h, ⟨(), h⟩⟩⟩ @[simp] theorem principal_σ (s : set α) : (realizer.principal s).σ = unit := rfl @[simp] theorem principal_F (s : set α) (u : unit) : (realizer.principal s).F u = s := rfl /-- `unit` is a realizer for the top filter -/ protected def top : (⊤ : filter α).realizer := (realizer.principal _).of_eq principal_univ @[simp] theorem top_σ : (@realizer.top α).σ = unit := rfl @[simp] theorem top_F (u : unit) : (@realizer.top α).F u = univ := rfl /-- `unit` is a realizer for the bottom filter -/ protected def bot : (⊥ : filter α).realizer := (realizer.principal _).of_eq principal_empty @[simp] theorem bot_σ : (@realizer.bot α).σ = unit := rfl @[simp] theorem bot_F (u : unit) : (@realizer.bot α).F u = ∅ := rfl /-- Construct a realizer for `map m f` given a realizer for `f` -/ protected def map (m : α → β) {f : filter α} (F : f.realizer) : (map m f).realizer := ⟨F.σ, { f := λ s, image m (F.F s), pt := F.F.pt, inf := F.F.inf, inf_le_left := λ a b, image_subset _ (F.F.inf_le_left _ _), inf_le_right := λ a b, image_subset _ (F.F.inf_le_right _ _) }, filter_eq $ set.ext $ λ x, by simp [cfilter.to_filter]; rw F.mem_sets; exact exists_congr (λ s, image_subset_iff)⟩ @[simp] theorem map_σ (m : α → β) {f : filter α} (F : f.realizer) : (F.map m).σ = F.σ := rfl @[simp] theorem map_F (m : α → β) {f : filter α} (F : f.realizer) (s) : (F.map m).F s = image m (F.F s) := rfl /-- Construct a realizer for `vmap m f` given a realizer for `f` -/ protected def vmap (m : α → β) {f : filter β} (F : f.realizer) : (vmap m f).realizer := ⟨F.σ, { f := λ s, preimage m (F.F s), pt := F.F.pt, inf := F.F.inf, inf_le_left := λ a b, preimage_mono (F.F.inf_le_left _ _), inf_le_right := λ a b, preimage_mono (F.F.inf_le_right _ _) }, filter_eq $ set.ext $ λ x, by cases F; subst f; simp [cfilter.to_filter, mem_vmap_sets]; exact ⟨λ ⟨s, h⟩, ⟨_, ⟨s, subset.refl _⟩, h⟩, λ ⟨y, ⟨s, h⟩, h₂⟩, ⟨s, subset.trans (preimage_mono h) h₂⟩⟩⟩ /-- Construct a realizer for the sup of two filters -/ protected def sup {f g : filter α} (F : f.realizer) (G : g.realizer) : (f ⊔ g).realizer := ⟨F.σ × G.σ, { f := λ ⟨s, t⟩, F.F s ∪ G.F t, pt := (F.F.pt, G.F.pt), inf := λ ⟨a, a'⟩ ⟨b, b'⟩, (F.F.inf a b, G.F.inf a' b'), inf_le_left := λ ⟨a, a'⟩ ⟨b, b'⟩, union_subset_union (F.F.inf_le_left _ _) (G.F.inf_le_left _ _), inf_le_right := λ ⟨a, a'⟩ ⟨b, b'⟩, union_subset_union (F.F.inf_le_right _ _) (G.F.inf_le_right _ _) }, filter_eq $ set.ext $ λ x, by cases F; cases G; substs f g; simp [cfilter.to_filter]; exact ⟨λ ⟨s, t, h⟩, ⟨⟨s, subset.trans (subset_union_left _ _) h⟩, ⟨t, subset.trans (subset_union_right _ _) h⟩⟩, λ ⟨⟨s, h₁⟩, ⟨t, h₂⟩⟩, ⟨s, t, union_subset h₁ h₂⟩⟩⟩ /-- Construct a realizer for the inf of two filters -/ protected def inf {f g : filter α} (F : f.realizer) (G : g.realizer) : (f ⊓ g).realizer := ⟨F.σ × G.σ, { f := λ ⟨s, t⟩, F.F s ∩ G.F t, pt := (F.F.pt, G.F.pt), inf := λ ⟨a, a'⟩ ⟨b, b'⟩, (F.F.inf a b, G.F.inf a' b'), inf_le_left := λ ⟨a, a'⟩ ⟨b, b'⟩, inter_subset_inter (F.F.inf_le_left _ _) (G.F.inf_le_left _ _), inf_le_right := λ ⟨a, a'⟩ ⟨b, b'⟩, inter_subset_inter (F.F.inf_le_right _ _) (G.F.inf_le_right _ _) }, filter_eq $ set.ext $ λ x, by cases F; cases G; substs f g; simp [cfilter.to_filter]; exact ⟨λ ⟨s, t, h⟩, ⟨_, ⟨s, subset.refl _⟩, _, ⟨t, subset.refl _⟩, h⟩, λ ⟨y, ⟨s, h₁⟩, z, ⟨t, h₂⟩, h⟩, ⟨s, t, subset.trans (inter_subset_inter h₁ h₂) h⟩⟩⟩ /-- Construct a realizer for the cofinite filter -/ protected def cofinite [decidable_eq α] : (@cofinite α).realizer := ⟨finset α, { f := λ s, {a | a ∉ s}, pt := ∅, inf := (∪), inf_le_left := λ s t a, mt (finset.mem_union_left _), inf_le_right := λ s t a, mt (finset.mem_union_right _) }, filter_eq $ set.ext $ λ x, by simp [cfilter.to_filter]; exactI ⟨λ ⟨s, h⟩, finite_subset (finite_mem_finset s) (compl_subset_comm.1 h), λ ⟨fs⟩, ⟨(-x).to_finset, λ a (h : a ∉ (-x).to_finset), classical.by_contradiction $ λ h', h (mem_to_finset.2 h')⟩⟩⟩ /-- Construct a realizer for filter bind -/ protected def bind {f : filter α} {m : α → filter β} (F : f.realizer) (G : ∀ i, (m i).realizer) : (f.bind m).realizer := ⟨Σ s : F.σ, Π i ∈ F.F s, (G i).σ, { f := λ ⟨s, f⟩, ⋃ i ∈ F.F s, (G i).F (f i H), pt := ⟨F.F.pt, λ i H, (G i).F.pt⟩, inf := λ ⟨a, f⟩ ⟨b, f'⟩, ⟨F.F.inf a b, λ i h, (G i).F.inf (f i (F.F.inf_le_left _ _ h)) (f' i (F.F.inf_le_right _ _ h))⟩, inf_le_left := λ ⟨a, f⟩ ⟨b, f'⟩ x, show (x ∈ ⋃ (i : α) (H : i ∈ F.F (F.F.inf a b)), _) → x ∈ ⋃ i (H : i ∈ F.F a), ((G i).F) (f i H), by simp; exact λ i h₁ h₂, ⟨i, F.F.inf_le_left _ _ h₁, (G i).F.inf_le_left _ _ h₂⟩, inf_le_right := λ ⟨a, f⟩ ⟨b, f'⟩ x, show (x ∈ ⋃ (i : α) (H : i ∈ F.F (F.F.inf a b)), _) → x ∈ ⋃ i (H : i ∈ F.F b), ((G i).F) (f' i H), by simp; exact λ i h₁ h₂, ⟨i, F.F.inf_le_right _ _ h₁, (G i).F.inf_le_right _ _ h₂⟩ }, filter_eq $ set.ext $ λ x, by cases F with _ F _; subst f; simp [cfilter.to_filter, mem_bind_sets]; exact ⟨λ ⟨s, f, h⟩, ⟨F s, ⟨s, subset.refl _⟩, λ i H, (G i).mem_sets.2 ⟨f i H, λ a h', h ⟨_, ⟨i, rfl⟩, _, ⟨H, rfl⟩, h'⟩⟩⟩, λ ⟨y, ⟨s, h⟩, f⟩, let ⟨f', h'⟩ := classical.axiom_of_choice (λ i:F s, (G i).mem_sets.1 (f i (h i.2))) in ⟨s, λ i h, f' ⟨i, h⟩, λ a ⟨_, ⟨i, rfl⟩, _, ⟨H, rfl⟩, m⟩, h' ⟨_, H⟩ m⟩⟩⟩ /-- Construct a realizer for indexed supremum -/ protected def Sup {f : α → filter β} (F : ∀ i, (f i).realizer) : (⨆ i, f i).realizer := let F' : (⨆ i, f i).realizer := ((realizer.bind realizer.top F).of_eq $ filter_eq $ set.ext $ by simp [filter.bind, eq_univ_iff_forall, supr_sets_eq]) in F'.of_equiv $ show (Σ u:unit, Π (i : α), true → (F i).σ) ≃ Π i, (F i).σ, from ⟨λ⟨_,f⟩ i, f i ⟨⟩, λ f, ⟨(), λ i _, f i⟩, λ ⟨⟨⟩, f⟩, by dsimp; congr; simp, λ f, rfl⟩ /-- Construct a realizer for the product of filters -/ protected def prod {f g : filter α} (F : f.realizer) (G : g.realizer) : (f.prod g).realizer := (F.vmap _).inf (G.vmap _) theorem le_iff {f g : filter α} (F : f.realizer) (G : g.realizer) : f ≤ g ↔ ∀ b : G.σ, ∃ a : F.σ, F.F a ≤ G.F b := ⟨λ H t, F.mem_sets.1 (H (G.mem_sets.2 ⟨t, subset.refl _⟩)), λ H x h, F.mem_sets.2 $ let ⟨s, h₁⟩ := G.mem_sets.1 h, ⟨t, h₂⟩ := H s in ⟨t, subset.trans h₂ h₁⟩⟩ theorem tendsto_iff (f : α → β) {l₁ : filter α} {l₂ : filter β} (L₁ : l₁.realizer) (L₂ : l₂.realizer) : tendsto f l₁ l₂ ↔ ∀ b, ∃ a, ∀ x ∈ L₁.F a, f x ∈ L₂.F b := (le_iff (L₁.map f) L₂).trans $ forall_congr $ λ b, exists_congr $ λ a, image_subset_iff theorem ne_bot_iff {f : filter α} (F : f.realizer) : f ≠ ⊥ ↔ ∀ a : F.σ, F.F a ≠ ∅ := by haveI := classical.prop_decidable; rw [not_iff_comm, ← lattice.le_bot_iff, F.le_iff realizer.bot]; simp [not_forall]; exact ⟨λ ⟨x, e⟩ _, ⟨x, le_of_eq e⟩, λ h, let ⟨x, h⟩ := h () in ⟨x, lattice.le_bot_iff.1 h⟩⟩ end filter.realizer
e8d47da52be0add6246b0ddb6d02989e67e3d591
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/analysis/analytic/composition.lean
76e2ec5396fec69121b8e29b3bd455ecce18fd86
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
58,762
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Johan Commelin -/ import analysis.analytic.basic import combinatorics.composition /-! # Composition of analytic functions in this file we prove that the composition of analytic functions is analytic. The argument is the following. Assume `g z = ∑' qₙ (z, ..., z)` and `f y = ∑' pₖ (y, ..., y)`. Then `g (f y) = ∑' qₙ (∑' pₖ (y, ..., y), ..., ∑' pₖ (y, ..., y)) = ∑' qₙ (p_{i₁} (y, ..., y), ..., p_{iₙ} (y, ..., y))`. For each `n` and `i₁, ..., iₙ`, define a `i₁ + ... + iₙ` multilinear function mapping `(y₀, ..., y_{i₁ + ... + iₙ - 1})` to `qₙ (p_{i₁} (y₀, ..., y_{i₁-1}), p_{i₂} (y_{i₁}, ..., y_{i₁ + i₂ - 1}), ..., p_{iₙ} (....)))`. Then `g ∘ f` is obtained by summing all these multilinear functions. To formalize this, we use compositions of an integer `N`, i.e., its decompositions into a sum `i₁ + ... + iₙ` of positive integers. Given such a composition `c` and two formal multilinear series `q` and `p`, let `q.comp_along_composition p c` be the above multilinear function. Then the `N`-th coefficient in the power series expansion of `g ∘ f` is the sum of these terms over all `c : composition N`. To complete the proof, we need to show that this power series has a positive radius of convergence. This follows from the fact that `composition N` has cardinality `2^(N-1)` and estimates on the norm of `qₙ` and `pₖ`, which give summability. We also need to show that it indeed converges to `g ∘ f`. For this, we note that the composition of partial sums converges to `g ∘ f`, and that it corresponds to a part of the whole sum, on a subset that increases to the whole space. By summability of the norms, this implies the overall convergence. ## Main results * `q.comp p` is the formal composition of the formal multilinear series `q` and `p`. * `has_fpower_series_at.comp` states that if two functions `g` and `f` admit power series expansions `q` and `p`, then `g ∘ f` admits a power series expansion given by `q.comp p`. * `analytic_at.comp` states that the composition of analytic functions is analytic. * `formal_multilinear_series.comp_assoc` states that composition is associative on formal multilinear series. ## Implementation details The main technical difficulty is to write down things. In particular, we need to define precisely `q.comp_along_composition p c` and to show that it is indeed a continuous multilinear function. This requires a whole interface built on the class `composition`. Once this is set, the main difficulty is to reorder the sums, writing the composition of the partial sums as a sum over some subset of `Σ n, composition n`. We need to check that the reordering is a bijection, running over difficulties due to the dependent nature of the types under consideration, that are controlled thanks to the interface for `composition`. The associativity of composition on formal multilinear series is a nontrivial result: it does not follow from the associativity of composition of analytic functions, as there is no uniqueness for the formal multilinear series representing a function (and also, it holds even when the radius of convergence of the series is `0`). Instead, we give a direct proof, which amounts to reordering double sums in a careful way. The change of variables is a canonical (combinatorial) bijection `composition.sigma_equiv_sigma_pi` between `(Σ (a : composition n), composition a.length)` and `(Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i))`, and is described in more details below in the paragraph on associativity. -/ noncomputable theory variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] {G : Type*} [normed_group G] [normed_space 𝕜 G] {H : Type*} [normed_group H] [normed_space 𝕜 H] open filter list open_locale topological_space big_operators classical nnreal ennreal /-! ### Composing formal multilinear series -/ namespace formal_multilinear_series /-! In this paragraph, we define the composition of formal multilinear series, by summing over all possible compositions of `n`. -/ /-- Given a formal multilinear series `p`, a composition `c` of `n` and the index `i` of a block of `c`, we may define a function on `fin n → E` by picking the variables in the `i`-th block of `n`, and applying the corresponding coefficient of `p` to these variables. This function is called `p.apply_composition c v i` for `v : fin n → E` and `i : fin c.length`. -/ def apply_composition (p : formal_multilinear_series 𝕜 E F) {n : ℕ} (c : composition n) : (fin n → E) → (fin (c.length) → F) := λ v i, p (c.blocks_fun i) (v ∘ (c.embedding i)) lemma apply_composition_ones (p : formal_multilinear_series 𝕜 E F) (n : ℕ) : p.apply_composition (composition.ones n) = λ v i, p 1 (λ _, v (fin.cast_le (composition.length_le _) i)) := begin funext v i, apply p.congr (composition.ones_blocks_fun _ _), intros j hjn hj1, obtain rfl : j = 0, { linarith }, refine congr_arg v _, rw [fin.ext_iff, fin.coe_cast_le, composition.ones_embedding, fin.coe_mk], end lemma apply_composition_single (p : formal_multilinear_series 𝕜 E F) {n : ℕ} (hn : 0 < n) (v : fin n → E) : p.apply_composition (composition.single n hn) v = λ j, p n v := begin ext j, refine p.congr (by simp) (λ i hi1 hi2, _), dsimp, congr' 1, convert composition.single_embedding hn ⟨i, hi2⟩, cases j, have : j_val = 0 := le_bot_iff.1 (nat.lt_succ_iff.1 j_property), unfold_coes, congr; try { assumption <|> simp }, end @[simp] lemma remove_zero_apply_composition (p : formal_multilinear_series 𝕜 E F) {n : ℕ} (c : composition n) : p.remove_zero.apply_composition c = p.apply_composition c := begin ext v i, simp [apply_composition, zero_lt_one.trans_le (c.one_le_blocks_fun i), remove_zero_of_pos], end /-- Technical lemma stating how `p.apply_composition` commutes with updating variables. This will be the key point to show that functions constructed from `apply_composition` retain multilinearity. -/ lemma apply_composition_update (p : formal_multilinear_series 𝕜 E F) {n : ℕ} (c : composition n) (j : fin n) (v : fin n → E) (z : E) : p.apply_composition c (function.update v j z) = function.update (p.apply_composition c v) (c.index j) (p (c.blocks_fun (c.index j)) (function.update (v ∘ (c.embedding (c.index j))) (c.inv_embedding j) z)) := begin ext k, by_cases h : k = c.index j, { rw h, let r : fin (c.blocks_fun (c.index j)) → fin n := c.embedding (c.index j), simp only [function.update_same], change p (c.blocks_fun (c.index j)) ((function.update v j z) ∘ r) = _, let j' := c.inv_embedding j, suffices B : (function.update v j z) ∘ r = function.update (v ∘ r) j' z, by rw B, suffices C : (function.update v (r j') z) ∘ r = function.update (v ∘ r) j' z, by { convert C, exact (c.embedding_comp_inv j).symm }, exact function.update_comp_eq_of_injective _ (c.embedding _).injective _ _ }, { simp only [h, function.update_eq_self, function.update_noteq, ne.def, not_false_iff], let r : fin (c.blocks_fun k) → fin n := c.embedding k, change p (c.blocks_fun k) ((function.update v j z) ∘ r) = p (c.blocks_fun k) (v ∘ r), suffices B : (function.update v j z) ∘ r = v ∘ r, by rw B, apply function.update_comp_eq_of_not_mem_range, rwa c.mem_range_embedding_iff' } end @[simp] lemma comp_continuous_linear_map_apply_composition {n : ℕ} (p : formal_multilinear_series 𝕜 F G) (f : E →L[𝕜] F) (c : composition n) (v : fin n → E) : (p.comp_continuous_linear_map f).apply_composition c v = p.apply_composition c (f ∘ v) := by simp [apply_composition] end formal_multilinear_series namespace continuous_multilinear_map open formal_multilinear_series /-- Given a formal multilinear series `p`, a composition `c` of `n` and a continuous multilinear map `f` in `c.length` variables, one may form a multilinear map in `n` variables by applying the right coefficient of `p` to each block of the composition, and then applying `f` to the resulting vector. It is called `f.comp_along_composition_aux p c`. This function admits a version as a continuous multilinear map, called `f.comp_along_composition p c` below. -/ def comp_along_composition_aux {n : ℕ} (p : formal_multilinear_series 𝕜 E F) (c : composition n) (f : continuous_multilinear_map 𝕜 (λ (i : fin c.length), F) G) : multilinear_map 𝕜 (λ i : fin n, E) G := { to_fun := λ v, f (p.apply_composition c v), map_add' := λ v i x y, by simp only [apply_composition_update, continuous_multilinear_map.map_add], map_smul' := λ v i c x, by simp only [apply_composition_update, continuous_multilinear_map.map_smul] } /-- The norm of `f.comp_along_composition_aux p c` is controlled by the product of the norms of the relevant bits of `f` and `p`. -/ lemma comp_along_composition_aux_bound {n : ℕ} (p : formal_multilinear_series 𝕜 E F) (c : composition n) (f : continuous_multilinear_map 𝕜 (λ (i : fin c.length), F) G) (v : fin n → E) : ∥f.comp_along_composition_aux p c v∥ ≤ ∥f∥ * (∏ i, ∥p (c.blocks_fun i)∥) * (∏ i : fin n, ∥v i∥) := calc ∥f.comp_along_composition_aux p c v∥ = ∥f (p.apply_composition c v)∥ : rfl ... ≤ ∥f∥ * ∏ i, ∥p.apply_composition c v i∥ : continuous_multilinear_map.le_op_norm _ _ ... ≤ ∥f∥ * ∏ i, ∥p (c.blocks_fun i)∥ * ∏ j : fin (c.blocks_fun i), ∥(v ∘ (c.embedding i)) j∥ : begin apply mul_le_mul_of_nonneg_left _ (norm_nonneg _), refine finset.prod_le_prod (λ i hi, norm_nonneg _) (λ i hi, _), apply continuous_multilinear_map.le_op_norm, end ... = ∥f∥ * (∏ i, ∥p (c.blocks_fun i)∥) * ∏ i (j : fin (c.blocks_fun i)), ∥(v ∘ (c.embedding i)) j∥ : by rw [finset.prod_mul_distrib, mul_assoc] ... = ∥f∥ * (∏ i, ∥p (c.blocks_fun i)∥) * (∏ i : fin n, ∥v i∥) : by { rw [← c.blocks_fin_equiv.prod_comp, ← finset.univ_sigma_univ, finset.prod_sigma], congr } /-- Given a formal multilinear series `p`, a composition `c` of `n` and a continuous multilinear map `f` in `c.length` variables, one may form a continuous multilinear map in `n` variables by applying the right coefficient of `p` to each block of the composition, and then applying `f` to the resulting vector. It is called `f.comp_along_composition p c`. It is constructed from the analogous multilinear function `f.comp_along_composition_aux p c`, together with a norm control to get the continuity. -/ def comp_along_composition {n : ℕ} (p : formal_multilinear_series 𝕜 E F) (c : composition n) (f : continuous_multilinear_map 𝕜 (λ (i : fin c.length), F) G) : continuous_multilinear_map 𝕜 (λ i : fin n, E) G := (f.comp_along_composition_aux p c).mk_continuous _ (f.comp_along_composition_aux_bound p c) @[simp] lemma comp_along_composition_apply {n : ℕ} (p : formal_multilinear_series 𝕜 E F) (c : composition n) (f : continuous_multilinear_map 𝕜 (λ (i : fin c.length), F) G) (v : fin n → E) : (f.comp_along_composition p c) v = f (p.apply_composition c v) := rfl end continuous_multilinear_map namespace formal_multilinear_series /-- Given two formal multilinear series `q` and `p` and a composition `c` of `n`, one may form a continuous multilinear map in `n` variables by applying the right coefficient of `p` to each block of the composition, and then applying `q c.length` to the resulting vector. It is called `q.comp_along_composition p c`. It is constructed from the analogous multilinear function `q.comp_along_composition_aux p c`, together with a norm control to get the continuity. -/ def comp_along_composition {n : ℕ} (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (c : composition n) : continuous_multilinear_map 𝕜 (λ i : fin n, E) G := (q c.length).comp_along_composition p c @[simp] lemma comp_along_composition_apply {n : ℕ} (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (c : composition n) (v : fin n → E) : (q.comp_along_composition p c) v = q c.length (p.apply_composition c v) := rfl /-- The norm of `q.comp_along_composition p c` is controlled by the product of the norms of the relevant bits of `q` and `p`. -/ lemma comp_along_composition_norm {n : ℕ} (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (c : composition n) : ∥q.comp_along_composition p c∥ ≤ ∥q c.length∥ * ∏ i, ∥p (c.blocks_fun i)∥ := multilinear_map.mk_continuous_norm_le _ (mul_nonneg (norm_nonneg _) (finset.prod_nonneg (λ i hi, norm_nonneg _))) _ lemma comp_along_composition_nnnorm {n : ℕ} (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (c : composition n) : nnnorm (q.comp_along_composition p c) ≤ nnnorm (q c.length) * ∏ i, nnnorm (p (c.blocks_fun i)) := by { rw ← nnreal.coe_le_coe, push_cast, exact q.comp_along_composition_norm p c } /-- Formal composition of two formal multilinear series. The `n`-th coefficient in the composition is defined to be the sum of `q.comp_along_composition p c` over all compositions of `n`. In other words, this term (as a multilinear function applied to `v_0, ..., v_{n-1}`) is `∑'_{k} ∑'_{i₁ + ... + iₖ = n} pₖ (q_{i_1} (...), ..., q_{i_k} (...))`, where one puts all variables `v_0, ..., v_{n-1}` in increasing order in the dots. In general, the composition `q ∘ p` only makes sense when the constant coefficient of `p` vanishes. We give a general formula but which ignores the value of `p 0` instead. -/ protected def comp (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) : formal_multilinear_series 𝕜 E G := λ n, ∑ c : composition n, q.comp_along_composition p c /-- The `0`-th coefficient of `q.comp p` is `q 0`. Since these maps are multilinear maps in zero variables, but on different spaces, we can not state this directly, so we state it when applied to arbitrary vectors (which have to be the zero vector). -/ lemma comp_coeff_zero (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (v : fin 0 → E) (v' : fin 0 → F) : (q.comp p) 0 v = q 0 v' := begin let c : composition 0 := composition.ones 0, dsimp [formal_multilinear_series.comp], have : {c} = (finset.univ : finset (composition 0)), { apply finset.eq_of_subset_of_card_le; simp [finset.card_univ, composition_card 0] }, rw [← this, finset.sum_singleton, comp_along_composition_apply], symmetry, congr' end @[simp] lemma comp_coeff_zero' (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (v : fin 0 → E) : (q.comp p) 0 v = q 0 (λ i, 0) := q.comp_coeff_zero p v _ /-- The `0`-th coefficient of `q.comp p` is `q 0`. When `p` goes from `E` to `E`, this can be expressed as a direct equality -/ lemma comp_coeff_zero'' (q : formal_multilinear_series 𝕜 E F) (p : formal_multilinear_series 𝕜 E E) : (q.comp p) 0 = q 0 := by { ext v, exact q.comp_coeff_zero p _ _ } /-- The first coefficient of a composition of formal multilinear series is the composition of the first coefficients seen as continuous linear maps. -/ lemma comp_coeff_one (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (v : fin 1 → E) : (q.comp p) 1 v = q 1 (λ i, p 1 v) := begin have : {composition.ones 1} = (finset.univ : finset (composition 1)) := finset.eq_univ_of_card _ (by simp [composition_card]), simp only [formal_multilinear_series.comp, comp_along_composition_apply, ← this, finset.sum_singleton], refine q.congr (by simp) (λ i hi1 hi2, _), simp only [apply_composition_ones], exact p.congr rfl (λ j hj1 hj2, by congr) end lemma remove_zero_comp_of_pos (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) {n : ℕ} (hn : 0 < n) : q.remove_zero.comp p n = q.comp p n := begin ext v, simp only [formal_multilinear_series.comp, comp_along_composition, continuous_multilinear_map.comp_along_composition_apply, continuous_multilinear_map.sum_apply], apply finset.sum_congr rfl (λ c hc, _), rw remove_zero_of_pos _ (c.length_pos_of_pos hn) end @[simp] lemma comp_remove_zero (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) : q.comp p.remove_zero = q.comp p := by { ext n, simp [formal_multilinear_series.comp] } /-! ### The identity formal power series We will now define the identity power series, and show that it is a neutral element for left and right composition. -/ section variables (𝕜 E) /-- The identity formal multilinear series, with all coefficients equal to `0` except for `n = 1` where it is (the continuous multilinear version of) the identity. -/ def id : formal_multilinear_series 𝕜 E E | 0 := 0 | 1 := (continuous_multilinear_curry_fin1 𝕜 E E).symm (continuous_linear_map.id 𝕜 E) | _ := 0 /-- The first coefficient of `id 𝕜 E` is the identity. -/ @[simp] lemma id_apply_one (v : fin 1 → E) : (formal_multilinear_series.id 𝕜 E) 1 v = v 0 := rfl /-- The `n`th coefficient of `id 𝕜 E` is the identity when `n = 1`. We state this in a dependent way, as it will often appear in this form. -/ lemma id_apply_one' {n : ℕ} (h : n = 1) (v : fin n → E) : (id 𝕜 E) n v = v ⟨0, h.symm ▸ zero_lt_one⟩ := begin subst n, apply id_apply_one end /-- For `n ≠ 1`, the `n`-th coefficient of `id 𝕜 E` is zero, by definition. -/ @[simp] lemma id_apply_ne_one {n : ℕ} (h : n ≠ 1) : (formal_multilinear_series.id 𝕜 E) n = 0 := by { cases n, { refl }, cases n, { contradiction }, refl } end @[simp] theorem comp_id (p : formal_multilinear_series 𝕜 E F) : p.comp (id 𝕜 E) = p := begin ext1 n, dsimp [formal_multilinear_series.comp], rw finset.sum_eq_single (composition.ones n), show comp_along_composition p (id 𝕜 E) (composition.ones n) = p n, { ext v, rw comp_along_composition_apply, apply p.congr (composition.ones_length n), intros, rw apply_composition_ones, refine congr_arg v _, rw [fin.ext_iff, fin.coe_cast_le, fin.coe_mk, fin.coe_mk], }, show ∀ (b : composition n), b ∈ finset.univ → b ≠ composition.ones n → comp_along_composition p (id 𝕜 E) b = 0, { assume b _ hb, obtain ⟨k, hk, lt_k⟩ : ∃ (k : ℕ) (H : k ∈ composition.blocks b), 1 < k := composition.ne_ones_iff.1 hb, obtain ⟨i, i_lt, hi⟩ : ∃ (i : ℕ) (h : i < b.blocks.length), b.blocks.nth_le i h = k := nth_le_of_mem hk, let j : fin b.length := ⟨i, b.blocks_length ▸ i_lt⟩, have A : 1 < b.blocks_fun j := by convert lt_k, ext v, rw [comp_along_composition_apply, continuous_multilinear_map.zero_apply], apply continuous_multilinear_map.map_coord_zero _ j, dsimp [apply_composition], rw id_apply_ne_one _ _ (ne_of_gt A), refl }, { simp } end @[simp] theorem id_comp (p : formal_multilinear_series 𝕜 E F) (h : p 0 = 0) : (id 𝕜 F).comp p = p := begin ext1 n, by_cases hn : n = 0, { rw [hn, h], ext v, rw [comp_coeff_zero', id_apply_ne_one _ _ zero_ne_one], refl }, { dsimp [formal_multilinear_series.comp], have n_pos : 0 < n := bot_lt_iff_ne_bot.mpr hn, rw finset.sum_eq_single (composition.single n n_pos), show comp_along_composition (id 𝕜 F) p (composition.single n n_pos) = p n, { ext v, rw [comp_along_composition_apply, id_apply_one' _ _ (composition.single_length n_pos)], dsimp [apply_composition], refine p.congr rfl (λ i him hin, congr_arg v $ _), ext, simp }, show ∀ (b : composition n), b ∈ finset.univ → b ≠ composition.single n n_pos → comp_along_composition (id 𝕜 F) p b = 0, { assume b _ hb, have A : b.length ≠ 1, by simpa [composition.eq_single_iff_length] using hb, ext v, rw [comp_along_composition_apply, id_apply_ne_one _ _ A], refl }, { simp } } end /-! ### Summability properties of the composition of formal power series-/ /-- If two formal multilinear series have positive radius of convergence, then the terms appearing in the definition of their composition are also summable (when multiplied by a suitable positive geometric term). -/ theorem comp_summable_nnreal (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (hq : 0 < q.radius) (hp : 0 < p.radius) : ∃ r > (0 : ℝ≥0), summable (λ i : Σ n, composition n, nnnorm (q.comp_along_composition p i.2) * r ^ i.1) := begin /- This follows from the fact that the growth rate of `∥qₙ∥` and `∥pₙ∥` is at most geometric, giving a geometric bound on each `∥q.comp_along_composition p op∥`, together with the fact that there are `2^(n-1)` compositions of `n`, giving at most a geometric loss. -/ rcases ennreal.lt_iff_exists_nnreal_btwn.1 (lt_min ennreal.zero_lt_one hq) with ⟨rq, rq_pos, hrq⟩, rcases ennreal.lt_iff_exists_nnreal_btwn.1 (lt_min ennreal.zero_lt_one hp) with ⟨rp, rp_pos, hrp⟩, simp only [lt_min_iff, ennreal.coe_lt_one_iff, ennreal.coe_pos] at hrp hrq rp_pos rq_pos, obtain ⟨Cq, hCq0, hCq⟩ : ∃ Cq > 0, ∀ n, nnnorm (q n) * rq^n ≤ Cq := q.nnnorm_mul_pow_le_of_lt_radius hrq.2, obtain ⟨Cp, hCp1, hCp⟩ : ∃ Cp ≥ 1, ∀ n, nnnorm (p n) * rp^n ≤ Cp, { rcases p.nnnorm_mul_pow_le_of_lt_radius hrp.2 with ⟨Cp, -, hCp⟩, exact ⟨max Cp 1, le_max_right _ _, λ n, (hCp n).trans (le_max_left _ _)⟩ }, let r0 : ℝ≥0 := (4 * Cp)⁻¹, have r0_pos : 0 < r0 := nnreal.inv_pos.2 (mul_pos zero_lt_four (zero_lt_one.trans_le hCp1)), set r : ℝ≥0 := rp * rq * r0, have r_pos : 0 < r := mul_pos (mul_pos rp_pos rq_pos) r0_pos, have I : ∀ (i : Σ (n : ℕ), composition n), nnnorm (q.comp_along_composition p i.2) * r ^ i.1 ≤ Cq / 4 ^ i.1, { rintros ⟨n, c⟩, have A, calc nnnorm (q c.length) * rq ^ n ≤ nnnorm (q c.length)* rq ^ c.length : mul_le_mul' le_rfl (pow_le_pow_of_le_one rq.2 hrq.1.le c.length_le) ... ≤ Cq : hCq _, have B, calc ((∏ i, nnnorm (p (c.blocks_fun i))) * rp ^ n) = ∏ i, nnnorm (p (c.blocks_fun i)) * rp ^ c.blocks_fun i : by simp only [finset.prod_mul_distrib, finset.prod_pow_eq_pow_sum, c.sum_blocks_fun] ... ≤ ∏ i : fin c.length, Cp : finset.prod_le_prod' (λ i _, hCp _) ... = Cp ^ c.length : by simp ... ≤ Cp ^ n : pow_le_pow hCp1 c.length_le, calc nnnorm (q.comp_along_composition p c) * r ^ n ≤ (nnnorm (q c.length) * ∏ i, nnnorm (p (c.blocks_fun i))) * r ^ n : mul_le_mul' (q.comp_along_composition_nnnorm p c) le_rfl ... = (nnnorm (q c.length) * rq ^ n) * ((∏ i, nnnorm (p (c.blocks_fun i))) * rp ^ n) * r0 ^ n : by { simp only [r, mul_pow], ac_refl } ... ≤ Cq * Cp ^ n * r0 ^ n : mul_le_mul' (mul_le_mul' A B) le_rfl ... = Cq / 4 ^ n : begin simp only [r0], field_simp [mul_pow, (zero_lt_one.trans_le hCp1).ne'], ac_refl end }, refine ⟨r, r_pos, nnreal.summable_of_le I _⟩, simp_rw div_eq_mul_inv, refine summable.mul_left _ _, have h4 : ∀ n : ℕ, 0 < (4 ^ n : ℝ≥0)⁻¹ := λ n, nnreal.inv_pos.2 (pow_pos zero_lt_four _), have : ∀ n : ℕ, has_sum (λ c : composition n, (4 ^ n : ℝ≥0)⁻¹) (2 ^ (n - 1) / 4 ^ n), { intro n, convert has_sum_fintype (λ c : composition n, (4 ^ n : ℝ≥0)⁻¹), simp [finset.card_univ, composition_card, div_eq_mul_inv] }, refine nnreal.summable_sigma.2 ⟨λ n, (this n).summable, (nnreal.summable_nat_add_iff 1).1 _⟩, convert (nnreal.summable_geometric (nnreal.div_lt_one_of_lt one_lt_two)).mul_left (1 / 4), ext1 n, rw [(this _).tsum_eq, nat.add_sub_cancel], field_simp [← mul_assoc, pow_succ', mul_pow, show (4 : ℝ≥0) = 2 * 2, from (two_mul 2).symm, mul_right_comm] end /-- Bounding below the radius of the composition of two formal multilinear series assuming summability over all compositions. -/ theorem le_comp_radius_of_summable (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (r : ℝ≥0) (hr : summable (λ i : (Σ n, composition n), nnnorm (q.comp_along_composition p i.2) * r ^ i.1)) : (r : ℝ≥0∞) ≤ (q.comp p).radius := begin refine le_radius_of_bound_nnreal _ (∑' i : (Σ n, composition n), nnnorm (comp_along_composition q p i.snd) * r ^ i.fst) (λ n, _), calc nnnorm (formal_multilinear_series.comp q p n) * r ^ n ≤ ∑' (c : composition n), nnnorm (comp_along_composition q p c) * r ^ n : begin rw [tsum_fintype, ← finset.sum_mul], exact mul_le_mul' (nnnorm_sum_le _ _) le_rfl end ... ≤ ∑' (i : Σ (n : ℕ), composition n), nnnorm (comp_along_composition q p i.snd) * r ^ i.fst : nnreal.tsum_comp_le_tsum_of_inj hr sigma_mk_injective end /-! ### Composing analytic functions Now, we will prove that the composition of the partial sums of `q` and `p` up to order `N` is given by a sum over some large subset of `Σ n, composition n` of `q.comp_along_composition p`, to deduce that the series for `q.comp p` indeed converges to `g ∘ f` when `q` is a power series for `g` and `p` is a power series for `f`. This proof is a big reindexing argument of a sum. Since it is a bit involved, we define first the source of the change of variables (`comp_partial_source`), its target (`comp_partial_target`) and the change of variables itself (`comp_change_of_variables`) before giving the main statement in `comp_partial_sum`. -/ /-- Source set in the change of variables to compute the composition of partial sums of formal power series. See also `comp_partial_sum`. -/ def comp_partial_sum_source (m M N : ℕ) : finset (Σ n, (fin n) → ℕ) := finset.sigma (finset.Ico m M) (λ (n : ℕ), fintype.pi_finset (λ (i : fin n), finset.Ico 1 N) : _) @[simp] lemma mem_comp_partial_sum_source_iff (m M N : ℕ) (i : Σ n, (fin n) → ℕ) : i ∈ comp_partial_sum_source m M N ↔ (m ≤ i.1 ∧ i.1 < M) ∧ ∀ (a : fin i.1), 1 ≤ i.2 a ∧ i.2 a < N := by simp only [comp_partial_sum_source, finset.Ico.mem, fintype.mem_pi_finset, finset.mem_sigma, iff_self] /-- Change of variables appearing to compute the composition of partial sums of formal power series -/ def comp_change_of_variables (m M N : ℕ) (i : Σ n, (fin n) → ℕ) (hi : i ∈ comp_partial_sum_source m M N) : (Σ n, composition n) := begin rcases i with ⟨n, f⟩, rw mem_comp_partial_sum_source_iff at hi, refine ⟨∑ j, f j, of_fn (λ a, f a), λ i hi', _, by simp [sum_of_fn]⟩, obtain ⟨j, rfl⟩ : ∃ (j : fin n), f j = i, by rwa [mem_of_fn, set.mem_range] at hi', exact (hi.2 j).1 end @[simp] lemma comp_change_of_variables_length (m M N : ℕ) {i : Σ n, (fin n) → ℕ} (hi : i ∈ comp_partial_sum_source m M N) : composition.length (comp_change_of_variables m M N i hi).2 = i.1 := begin rcases i with ⟨k, blocks_fun⟩, dsimp [comp_change_of_variables], simp only [composition.length, map_of_fn, length_of_fn] end lemma comp_change_of_variables_blocks_fun (m M N : ℕ) {i : Σ n, (fin n) → ℕ} (hi : i ∈ comp_partial_sum_source m M N) (j : fin i.1) : (comp_change_of_variables m M N i hi).2.blocks_fun ⟨j, (comp_change_of_variables_length m M N hi).symm ▸ j.2⟩ = i.2 j := begin rcases i with ⟨n, f⟩, dsimp [composition.blocks_fun, composition.blocks, comp_change_of_variables], simp only [map_of_fn, nth_le_of_fn', function.comp_app], apply congr_arg, exact fin.eta _ _ end /-- Target set in the change of variables to compute the composition of partial sums of formal power series, here given a a set. -/ def comp_partial_sum_target_set (m M N : ℕ) : set (Σ n, composition n) := {i | (m ≤ i.2.length) ∧ (i.2.length < M) ∧ (∀ (j : fin i.2.length), i.2.blocks_fun j < N)} lemma comp_partial_sum_target_subset_image_comp_partial_sum_source (m M N : ℕ) (i : Σ n, composition n) (hi : i ∈ comp_partial_sum_target_set m M N) : ∃ j (hj : j ∈ comp_partial_sum_source m M N), i = comp_change_of_variables m M N j hj := begin rcases i with ⟨n, c⟩, refine ⟨⟨c.length, c.blocks_fun⟩, _, _⟩, { simp only [comp_partial_sum_target_set, set.mem_set_of_eq] at hi, simp only [mem_comp_partial_sum_source_iff, hi.left, hi.right, true_and, and_true], exact λ a, c.one_le_blocks' _ }, { dsimp [comp_change_of_variables], rw composition.sigma_eq_iff_blocks_eq, simp only [composition.blocks_fun, composition.blocks, subtype.coe_eta, nth_le_map'], conv_lhs { rw ← of_fn_nth_le c.blocks } } end /-- Target set in the change of variables to compute the composition of partial sums of formal power series, here given a a finset. See also `comp_partial_sum`. -/ def comp_partial_sum_target (m M N : ℕ) : finset (Σ n, composition n) := set.finite.to_finset $ ((finset.finite_to_set _).dependent_image _).subset $ comp_partial_sum_target_subset_image_comp_partial_sum_source m M N @[simp] lemma mem_comp_partial_sum_target_iff {m M N : ℕ} {a : Σ n, composition n} : a ∈ comp_partial_sum_target m M N ↔ m ≤ a.2.length ∧ a.2.length < M ∧ (∀ (j : fin a.2.length), a.2.blocks_fun j < N) := by simp [comp_partial_sum_target, comp_partial_sum_target_set] /-- `comp_change_of_variables m M N` is a bijection between `comp_partial_sum_source m M N` and `comp_partial_sum_target m M N`, yielding equal sums for functions that correspond to each other under the bijection. As `comp_change_of_variables m M N` is a dependent function, stating that it is a bijection is not directly possible, but the consequence on sums can be stated more easily. -/ lemma comp_change_of_variables_sum {α : Type*} [add_comm_monoid α] (m M N : ℕ) (f : (Σ (n : ℕ), fin n → ℕ) → α) (g : (Σ n, composition n) → α) (h : ∀ e (he : e ∈ comp_partial_sum_source m M N), f e = g (comp_change_of_variables m M N e he)) : ∑ e in comp_partial_sum_source m M N, f e = ∑ e in comp_partial_sum_target m M N, g e := begin apply finset.sum_bij (comp_change_of_variables m M N), -- We should show that the correspondance we have set up is indeed a bijection -- between the index sets of the two sums. -- 1 - show that the image belongs to `comp_partial_sum_target m N N` { rintros ⟨k, blocks_fun⟩ H, rw mem_comp_partial_sum_source_iff at H, simp only [mem_comp_partial_sum_target_iff, composition.length, composition.blocks, H.left, map_of_fn, length_of_fn, true_and, comp_change_of_variables], assume j, simp only [composition.blocks_fun, (H.right _).right, nth_le_of_fn'] }, -- 2 - show that the composition gives the `comp_along_composition` application { rintros ⟨k, blocks_fun⟩ H, rw h }, -- 3 - show that the map is injective { rintros ⟨k, blocks_fun⟩ ⟨k', blocks_fun'⟩ H H' heq, obtain rfl : k = k', { have := (comp_change_of_variables_length m M N H).symm, rwa [heq, comp_change_of_variables_length] at this, }, congr, funext i, calc blocks_fun i = (comp_change_of_variables m M N _ H).2.blocks_fun _ : (comp_change_of_variables_blocks_fun m M N H i).symm ... = (comp_change_of_variables m M N _ H').2.blocks_fun _ : begin apply composition.blocks_fun_congr; try { rw heq }, refl end ... = blocks_fun' i : comp_change_of_variables_blocks_fun m M N H' i }, -- 4 - show that the map is surjective { assume i hi, apply comp_partial_sum_target_subset_image_comp_partial_sum_source m M N i, simpa [comp_partial_sum_target] using hi } end /-- The auxiliary set corresponding to the composition of partial sums asymptotically contains all possible compositions. -/ lemma comp_partial_sum_target_tendsto_at_top : tendsto (λ N, comp_partial_sum_target 0 N N) at_top at_top := begin apply monotone.tendsto_at_top_finset, { assume m n hmn a ha, have : ∀ i, i < m → i < n := λ i hi, lt_of_lt_of_le hi hmn, tidy }, { rintros ⟨n, c⟩, simp only [mem_comp_partial_sum_target_iff], obtain ⟨n, hn⟩ : bdd_above ↑(finset.univ.image (λ (i : fin c.length), c.blocks_fun i)) := finset.bdd_above _, refine ⟨max n c.length + 1, bot_le, lt_of_le_of_lt (le_max_right n c.length) (lt_add_one _), λ j, lt_of_le_of_lt (le_trans _ (le_max_left _ _)) (lt_add_one _)⟩, apply hn, simp only [finset.mem_image_of_mem, finset.mem_coe, finset.mem_univ] } end /-- Composing the partial sums of two multilinear series coincides with the sum over all compositions in `comp_partial_sum_target 0 N N`. This is precisely the motivation for the definition of `comp_partial_sum_target`. -/ lemma comp_partial_sum (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (N : ℕ) (z : E) : q.partial_sum N (∑ i in finset.Ico 1 N, p i (λ j, z)) = ∑ i in comp_partial_sum_target 0 N N, q.comp_along_composition p i.2 (λ j, z) := begin -- we expand the composition, using the multilinearity of `q` to expand along each coordinate. suffices H : ∑ n in finset.range N, ∑ r in fintype.pi_finset (λ (i : fin n), finset.Ico 1 N), q n (λ (i : fin n), p (r i) (λ j, z)) = ∑ i in comp_partial_sum_target 0 N N, q.comp_along_composition p i.2 (λ j, z), by simpa only [formal_multilinear_series.partial_sum, continuous_multilinear_map.map_sum_finset] using H, -- rewrite the first sum as a big sum over a sigma type, in the finset -- `comp_partial_sum_target 0 N N` rw [finset.range_eq_Ico, finset.sum_sigma'], -- use `comp_change_of_variables_sum`, saying that this change of variables respects sums apply comp_change_of_variables_sum 0 N N, rintros ⟨k, blocks_fun⟩ H, apply congr _ (comp_change_of_variables_length 0 N N H).symm, intros, rw ← comp_change_of_variables_blocks_fun 0 N N H, refl end end formal_multilinear_series open formal_multilinear_series /-- If two functions `g` and `f` have power series `q` and `p` respectively at `f x` and `x`, then `g ∘ f` admits the power series `q.comp p` at `x`. -/ theorem has_fpower_series_at.comp {g : F → G} {f : E → F} {q : formal_multilinear_series 𝕜 F G} {p : formal_multilinear_series 𝕜 E F} {x : E} (hg : has_fpower_series_at g q (f x)) (hf : has_fpower_series_at f p x) : has_fpower_series_at (g ∘ f) (q.comp p) x := begin /- Consider `rf` and `rg` such that `f` and `g` have power series expansion on the disks of radius `rf` and `rg`. -/ rcases hg with ⟨rg, Hg⟩, rcases hf with ⟨rf, Hf⟩, /- The terms defining `q.comp p` are geometrically summable in a disk of some radius `r`. -/ rcases q.comp_summable_nnreal p Hg.radius_pos Hf.radius_pos with ⟨r, r_pos : 0 < r, hr⟩, /- We will consider `y` which is smaller than `r` and `rf`, and also small enough that `f (x + y)` is close enough to `f x` to be in the disk where `g` is well behaved. Let `min (r, rf, δ)` be this new radius.-/ have : continuous_at f x := Hf.analytic_at.continuous_at, obtain ⟨δ, δpos, hδ⟩ : ∃ (δ : ℝ≥0∞) (H : 0 < δ), ∀ {z : E}, z ∈ emetric.ball x δ → f z ∈ emetric.ball (f x) rg, { have : emetric.ball (f x) rg ∈ 𝓝 (f x) := emetric.ball_mem_nhds _ Hg.r_pos, rcases emetric.mem_nhds_iff.1 (Hf.analytic_at.continuous_at this) with ⟨δ, δpos, Hδ⟩, exact ⟨δ, δpos, λ z hz, Hδ hz⟩ }, let rf' := min rf δ, have min_pos : 0 < min rf' r, by simp only [r_pos, Hf.r_pos, δpos, lt_min_iff, ennreal.coe_pos, and_self], /- We will show that `g ∘ f` admits the power series `q.comp p` in the disk of radius `min (r, rf', δ)`. -/ refine ⟨min rf' r, _⟩, refine ⟨le_trans (min_le_right rf' r) (formal_multilinear_series.le_comp_radius_of_summable q p r hr), min_pos, λ y hy, _⟩, /- Let `y` satisfy `∥y∥ < min (r, rf', δ)`. We want to show that `g (f (x + y))` is the sum of `q.comp p` applied to `y`. -/ -- First, check that `y` is small enough so that estimates for `f` and `g` apply. have y_mem : y ∈ emetric.ball (0 : E) rf := (emetric.ball_subset_ball (le_trans (min_le_left _ _) (min_le_left _ _))) hy, have fy_mem : f (x + y) ∈ emetric.ball (f x) rg, { apply hδ, have : y ∈ emetric.ball (0 : E) δ := (emetric.ball_subset_ball (le_trans (min_le_left _ _) (min_le_right _ _))) hy, simpa [edist_eq_coe_nnnorm_sub, edist_eq_coe_nnnorm] }, /- Now the proof starts. To show that the sum of `q.comp p` at `y` is `g (f (x + y))`, we will write `q.comp p` applied to `y` as a big sum over all compositions. Since the sum is summable, to get its convergence it suffices to get the convergence along some increasing sequence of sets. We will use the sequence of sets `comp_partial_sum_target 0 n n`, along which the sum is exactly the composition of the partial sums of `q` and `p`, by design. To show that it converges to `g (f (x + y))`, pointwise convergence would not be enough, but we have uniform convergence to save the day. -/ -- First step: the partial sum of `p` converges to `f (x + y)`. have A : tendsto (λ n, ∑ a in finset.Ico 1 n, p a (λ b, y)) at_top (𝓝 (f (x + y) - f x)), { have L : ∀ᶠ n in at_top, ∑ a in finset.range n, p a (λ b, y) - f x = ∑ a in finset.Ico 1 n, p a (λ b, y), { rw eventually_at_top, refine ⟨1, λ n hn, _⟩, symmetry, rw [eq_sub_iff_add_eq', finset.range_eq_Ico, ← Hf.coeff_zero (λi, y), finset.sum_eq_sum_Ico_succ_bot hn] }, have : tendsto (λ n, ∑ a in finset.range n, p a (λ b, y) - f x) at_top (𝓝 (f (x + y) - f x)) := (Hf.has_sum y_mem).tendsto_sum_nat.sub tendsto_const_nhds, exact tendsto.congr' L this }, -- Second step: the composition of the partial sums of `q` and `p` converges to `g (f (x + y))`. have B : tendsto (λ n, q.partial_sum n (∑ a in finset.Ico 1 n, p a (λ b, y))) at_top (𝓝 (g (f (x + y)))), { -- we use the fact that the partial sums of `q` converge locally uniformly to `g`, and that -- composition passes to the limit under locally uniform convergence. have B₁ : continuous_at (λ (z : F), g (f x + z)) (f (x + y) - f x), { refine continuous_at.comp _ (continuous_const.add continuous_id).continuous_at, simp only [add_sub_cancel'_right, id.def], exact Hg.continuous_on.continuous_at (is_open.mem_nhds (emetric.is_open_ball) fy_mem) }, have B₂ : f (x + y) - f x ∈ emetric.ball (0 : F) rg, by simpa [edist_eq_coe_nnnorm, edist_eq_coe_nnnorm_sub] using fy_mem, rw [← nhds_within_eq_of_open B₂ emetric.is_open_ball] at A, convert Hg.tendsto_locally_uniformly_on.tendsto_comp B₁.continuous_within_at B₂ A, simp only [add_sub_cancel'_right] }, -- Third step: the sum over all compositions in `comp_partial_sum_target 0 n n` converges to -- `g (f (x + y))`. As this sum is exactly the composition of the partial sum, this is a direct -- consequence of the second step have C : tendsto (λ n, ∑ i in comp_partial_sum_target 0 n n, q.comp_along_composition p i.2 (λ j, y)) at_top (𝓝 (g (f (x + y)))), by simpa [comp_partial_sum] using B, -- Fourth step: the sum over all compositions is `g (f (x + y))`. This follows from the -- convergence along a subsequence proved in the third step, and the fact that the sum is Cauchy -- thanks to the summability properties. have D : has_sum (λ i : (Σ n, composition n), q.comp_along_composition p i.2 (λ j, y)) (g (f (x + y))), { have cau : cauchy_seq (λ (s : finset (Σ n, composition n)), ∑ i in s, q.comp_along_composition p i.2 (λ j, y)), { apply cauchy_seq_finset_of_norm_bounded _ (nnreal.summable_coe.2 hr) _, simp only [coe_nnnorm, nnreal.coe_mul, nnreal.coe_pow], rintros ⟨n, c⟩, calc ∥(comp_along_composition q p c) (λ (j : fin n), y)∥ ≤ ∥comp_along_composition q p c∥ * ∏ j : fin n, ∥y∥ : by apply continuous_multilinear_map.le_op_norm ... ≤ ∥comp_along_composition q p c∥ * (r : ℝ) ^ n : begin apply mul_le_mul_of_nonneg_left _ (norm_nonneg _), rw [finset.prod_const, finset.card_fin], apply pow_le_pow_of_le_left (norm_nonneg _), rw [emetric.mem_ball, edist_eq_coe_nnnorm] at hy, have := (le_trans (le_of_lt hy) (min_le_right _ _)), rwa [ennreal.coe_le_coe, ← nnreal.coe_le_coe, coe_nnnorm] at this end }, exact tendsto_nhds_of_cauchy_seq_of_subseq cau comp_partial_sum_target_tendsto_at_top C }, -- Fifth step: the sum over `n` of `q.comp p n` can be expressed as a particular resummation of -- the sum over all compositions, by grouping together the compositions of the same -- integer `n`. The convergence of the whole sum therefore implies the converence of the sum -- of `q.comp p n` have E : has_sum (λ n, (q.comp p) n (λ j, y)) (g (f (x + y))), { apply D.sigma, assume n, dsimp [formal_multilinear_series.comp], convert has_sum_fintype _, simp only [continuous_multilinear_map.sum_apply], refl }, exact E end /-- If two functions `g` and `f` are analytic respectively at `f x` and `x`, then `g ∘ f` is analytic at `x`. -/ theorem analytic_at.comp {g : F → G} {f : E → F} {x : E} (hg : analytic_at 𝕜 g (f x)) (hf : analytic_at 𝕜 f x) : analytic_at 𝕜 (g ∘ f) x := let ⟨q, hq⟩ := hg, ⟨p, hp⟩ := hf in (hq.comp hp).analytic_at /-! ### Associativity of the composition of formal multilinear series In this paragraph, we prove the associativity of the composition of formal power series. By definition, ``` (r.comp q).comp p n v = ∑_{i₁ + ... + iₖ = n} (r.comp q)ₖ (p_{i₁} (v₀, ..., v_{i₁ -1}), p_{i₂} (...), ..., p_{iₖ}(...)) = ∑_{a : composition n} (r.comp q) a.length (apply_composition p a v) ``` decomposing `r.comp q` in the same way, we get ``` (r.comp q).comp p n v = ∑_{a : composition n} ∑_{b : composition a.length} r b.length (apply_composition q b (apply_composition p a v)) ``` On the other hand, ``` r.comp (q.comp p) n v = ∑_{c : composition n} r c.length (apply_composition (q.comp p) c v) ``` Here, `apply_composition (q.comp p) c v` is a vector of length `c.length`, whose `i`-th term is given by `(q.comp p) (c.blocks_fun i) (v_l, v_{l+1}, ..., v_{m-1})` where `{l, ..., m-1}` is the `i`-th block in the composition `c`, of length `c.blocks_fun i` by definition. To compute this term, we expand it as `∑_{dᵢ : composition (c.blocks_fun i)} q dᵢ.length (apply_composition p dᵢ v')`, where `v' = (v_l, v_{l+1}, ..., v_{m-1})`. Therefore, we get ``` r.comp (q.comp p) n v = ∑_{c : composition n} ∑_{d₀ : composition (c.blocks_fun 0), ..., d_{c.length - 1} : composition (c.blocks_fun (c.length - 1))} r c.length (λ i, q dᵢ.length (apply_composition p dᵢ v'ᵢ)) ``` To show that these terms coincide, we need to explain how to reindex the sums to put them in bijection (and then the terms we are summing will correspond to each other). Suppose we have a composition `a` of `n`, and a composition `b` of `a.length`. Then `b` indicates how to group together some blocks of `a`, giving altogether `b.length` blocks of blocks. These blocks of blocks can be called `d₀, ..., d_{a.length - 1}`, and one obtains a composition `c` of `n` by saying that each `dᵢ` is one single block. Conversely, if one starts from `c` and the `dᵢ`s, one can concatenate the `dᵢ`s to obtain a composition `a` of `n`, and register the lengths of the `dᵢ`s in a composition `b` of `a.length`. An example might be enlightening. Suppose `a = [2, 2, 3, 4, 2]`. It is a composition of length 5 of 13. The content of the blocks may be represented as `0011222333344`. Now take `b = [2, 3]` as a composition of `a.length = 5`. It says that the first 2 blocks of `a` should be merged, and the last 3 blocks of `a` should be merged, giving a new composition of `13` made of two blocks of length `4` and `9`, i.e., `c = [4, 9]`. But one can also remember that the new first block was initially made of two blocks of size `2`, so `d₀ = [2, 2]`, and the new second block was initially made of three blocks of size `3`, `4` and `2`, so `d₁ = [3, 4, 2]`. This equivalence is called `composition.sigma_equiv_sigma_pi n` below. We start with preliminary results on compositions, of a very specialized nature, then define the equivalence `composition.sigma_equiv_sigma_pi n`, and we deduce finally the associativity of composition of formal multilinear series in `formal_multilinear_series.comp_assoc`. -/ namespace composition variable {n : ℕ} /-- Rewriting equality in the dependent type `Σ (a : composition n), composition a.length)` in non-dependent terms with lists, requiring that the blocks coincide. -/ lemma sigma_composition_eq_iff (i j : Σ (a : composition n), composition a.length) : i = j ↔ i.1.blocks = j.1.blocks ∧ i.2.blocks = j.2.blocks := begin refine ⟨by rintro rfl; exact ⟨rfl, rfl⟩, _⟩, rcases i with ⟨a, b⟩, rcases j with ⟨a', b'⟩, rintros ⟨h, h'⟩, have H : a = a', by { ext1, exact h }, induction H, congr, ext1, exact h' end /-- Rewriting equality in the dependent type `Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i)` in non-dependent terms with lists, requiring that the lists of blocks coincide. -/ lemma sigma_pi_composition_eq_iff (u v : Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i)) : u = v ↔ of_fn (λ i, (u.2 i).blocks) = of_fn (λ i, (v.2 i).blocks) := begin refine ⟨λ H, by rw H, λ H, _⟩, rcases u with ⟨a, b⟩, rcases v with ⟨a', b'⟩, dsimp at H, have h : a = a', { ext1, have : map list.sum (of_fn (λ (i : fin (composition.length a)), (b i).blocks)) = map list.sum (of_fn (λ (i : fin (composition.length a')), (b' i).blocks)), by rw H, simp only [map_of_fn] at this, change of_fn (λ (i : fin (composition.length a)), (b i).blocks.sum) = of_fn (λ (i : fin (composition.length a')), (b' i).blocks.sum) at this, simpa [composition.blocks_sum, composition.of_fn_blocks_fun] using this }, induction h, simp only [true_and, eq_self_iff_true, heq_iff_eq], ext i : 2, have : nth_le (of_fn (λ (i : fin (composition.length a)), (b i).blocks)) i (by simp [i.is_lt]) = nth_le (of_fn (λ (i : fin (composition.length a)), (b' i).blocks)) i (by simp [i.is_lt]) := nth_le_of_eq H _, rwa [nth_le_of_fn, nth_le_of_fn] at this end /-- When `a` is a composition of `n` and `b` is a composition of `a.length`, `a.gather b` is the composition of `n` obtained by gathering all the blocks of `a` corresponding to a block of `b`. For instance, if `a = [6, 5, 3, 5, 2]` and `b = [2, 3]`, one should gather together the first two blocks of `a` and its last three blocks, giving `a.gather b = [11, 10]`. -/ def gather (a : composition n) (b : composition a.length) : composition n := { blocks := (a.blocks.split_wrt_composition b).map sum, blocks_pos := begin rw forall_mem_map_iff, intros j hj, suffices H : ∀ i ∈ j, 1 ≤ i, from calc 0 < j.length : length_pos_of_mem_split_wrt_composition hj ... ≤ j.sum : length_le_sum_of_one_le _ H, intros i hi, apply a.one_le_blocks, rw ← a.blocks.join_split_wrt_composition b, exact mem_join_of_mem hj hi, end, blocks_sum := by { rw [← sum_join, join_split_wrt_composition, a.blocks_sum] } } lemma length_gather (a : composition n) (b : composition a.length) : length (a.gather b) = b.length := show (map list.sum (a.blocks.split_wrt_composition b)).length = b.blocks.length, by rw [length_map, length_split_wrt_composition] /-- An auxiliary function used in the definition of `sigma_equiv_sigma_pi` below, associating to two compositions `a` of `n` and `b` of `a.length`, and an index `i` bounded by the length of `a.gather b`, the subcomposition of `a` made of those blocks belonging to the `i`-th block of `a.gather b`. -/ def sigma_composition_aux (a : composition n) (b : composition a.length) (i : fin (a.gather b).length) : composition ((a.gather b).blocks_fun i) := { blocks := nth_le (a.blocks.split_wrt_composition b) i (by { rw [length_split_wrt_composition, ← length_gather], exact i.2 }), blocks_pos := assume i hi, a.blocks_pos (by { rw ← a.blocks.join_split_wrt_composition b, exact mem_join_of_mem (nth_le_mem _ _ _) hi }), blocks_sum := by simp only [composition.blocks_fun, nth_le_map', composition.gather] } lemma length_sigma_composition_aux (a : composition n) (b : composition a.length) (i : fin b.length) : composition.length (composition.sigma_composition_aux a b ⟨i, (length_gather a b).symm ▸ i.2⟩) = composition.blocks_fun b i := show list.length (nth_le (split_wrt_composition a.blocks b) i _) = blocks_fun b i, by { rw [nth_le_map_rev list.length, nth_le_of_eq (map_length_split_wrt_composition _ _)], refl } lemma blocks_fun_sigma_composition_aux (a : composition n) (b : composition a.length) (i : fin b.length) (j : fin (blocks_fun b i)) : blocks_fun (sigma_composition_aux a b ⟨i, (length_gather a b).symm ▸ i.2⟩) ⟨j, (length_sigma_composition_aux a b i).symm ▸ j.2⟩ = blocks_fun a (embedding b i j) := show nth_le (nth_le _ _ _) _ _ = nth_le a.blocks _ _, by { rw [nth_le_of_eq (nth_le_split_wrt_composition _ _ _), nth_le_drop', nth_le_take'], refl } /-- Auxiliary lemma to prove that the composition of formal multilinear series is associative. Consider a composition `a` of `n` and a composition `b` of `a.length`. Grouping together some blocks of `a` according to `b` as in `a.gather b`, one can compute the total size of the blocks of `a` up to an index `size_up_to b i + j` (where the `j` corresponds to a set of blocks of `a` that do not fill a whole block of `a.gather b`). The first part corresponds to a sum of blocks in `a.gather b`, and the second one to a sum of blocks in the next block of `sigma_composition_aux a b`. This is the content of this lemma. -/ lemma size_up_to_size_up_to_add (a : composition n) (b : composition a.length) {i j : ℕ} (hi : i < b.length) (hj : j < blocks_fun b ⟨i, hi⟩) : size_up_to a (size_up_to b i + j) = size_up_to (a.gather b) i + (size_up_to (sigma_composition_aux a b ⟨i, (length_gather a b).symm ▸ hi⟩) j) := begin induction j with j IHj, { show sum (take ((b.blocks.take i).sum) a.blocks) = sum (take i (map sum (split_wrt_composition a.blocks b))), induction i with i IH, { refl }, { have A : i < b.length := nat.lt_of_succ_lt hi, have B : i < list.length (map list.sum (split_wrt_composition a.blocks b)), by simp [A], have C : 0 < blocks_fun b ⟨i, A⟩ := composition.blocks_pos' _ _ _, rw [sum_take_succ _ _ B, ← IH A C], have : take (sum (take i b.blocks)) a.blocks = take (sum (take i b.blocks)) (take (sum (take (i+1) b.blocks)) a.blocks), { rw [take_take, min_eq_left], apply monotone_sum_take _ (nat.le_succ _) }, rw [this, nth_le_map', nth_le_split_wrt_composition, ← take_append_drop (sum (take i b.blocks)) ((take (sum (take (nat.succ i) b.blocks)) a.blocks)), sum_append], congr, rw [take_append_drop] } }, { have A : j < blocks_fun b ⟨i, hi⟩ := lt_trans (lt_add_one j) hj, have B : j < length (sigma_composition_aux a b ⟨i, (length_gather a b).symm ▸ hi⟩), by { convert A, rw [← length_sigma_composition_aux], refl }, have C : size_up_to b i + j < size_up_to b (i + 1), { simp only [size_up_to_succ b hi, add_lt_add_iff_left], exact A }, have D : size_up_to b i + j < length a := lt_of_lt_of_le C (b.size_up_to_le _), have : size_up_to b i + nat.succ j = (size_up_to b i + j).succ := rfl, rw [this, size_up_to_succ _ D, IHj A, size_up_to_succ _ B], simp only [sigma_composition_aux, add_assoc, add_left_inj, fin.coe_mk], rw [nth_le_of_eq (nth_le_split_wrt_composition _ _ _), nth_le_drop', nth_le_take _ _ C] } end /-- Natural equivalence between `(Σ (a : composition n), composition a.length)` and `(Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i))`, that shows up as a change of variables in the proof that composition of formal multilinear series is associative. Consider a composition `a` of `n` and a composition `b` of `a.length`. Then `b` indicates how to group together some blocks of `a`, giving altogether `b.length` blocks of blocks. These blocks of blocks can be called `d₀, ..., d_{a.length - 1}`, and one obtains a composition `c` of `n` by saying that each `dᵢ` is one single block. The map `⟨a, b⟩ → ⟨c, (d₀, ..., d_{a.length - 1})⟩` is the direct map in the equiv. Conversely, if one starts from `c` and the `dᵢ`s, one can join the `dᵢ`s to obtain a composition `a` of `n`, and register the lengths of the `dᵢ`s in a composition `b` of `a.length`. This is the inverse map of the equiv. -/ def sigma_equiv_sigma_pi (n : ℕ) : (Σ (a : composition n), composition a.length) ≃ (Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i)) := { to_fun := λ i, ⟨i.1.gather i.2, i.1.sigma_composition_aux i.2⟩, inv_fun := λ i, ⟨ { blocks := (of_fn (λ j, (i.2 j).blocks)).join, blocks_pos := begin simp only [and_imp, mem_join, exists_imp_distrib, forall_mem_of_fn_iff], exact λ i j hj, composition.blocks_pos _ hj end, blocks_sum := by simp [sum_of_fn, composition.blocks_sum, composition.sum_blocks_fun] }, { blocks := of_fn (λ j, (i.2 j).length), blocks_pos := forall_mem_of_fn_iff.2 (λ j, composition.length_pos_of_pos _ (composition.blocks_pos' _ _ _)), blocks_sum := by { dsimp only [composition.length], simp [sum_of_fn] } }⟩, left_inv := begin -- the fact that we have a left inverse is essentially `join_split_wrt_composition`, -- but we need to massage it to take care of the dependent setting. rintros ⟨a, b⟩, rw sigma_composition_eq_iff, dsimp, split, { have A := length_map list.sum (split_wrt_composition a.blocks b), conv_rhs { rw [← join_split_wrt_composition a.blocks b, ← of_fn_nth_le (split_wrt_composition a.blocks b)] }, congr, { exact A }, { exact (fin.heq_fun_iff A).2 (λ i, rfl) } }, { have B : composition.length (composition.gather a b) = list.length b.blocks := composition.length_gather _ _, conv_rhs { rw [← of_fn_nth_le b.blocks] }, congr' 1, apply (fin.heq_fun_iff B).2 (λ i, _), rw [sigma_composition_aux, composition.length, nth_le_map_rev list.length, nth_le_of_eq (map_length_split_wrt_composition _ _)], refl } end, right_inv := begin -- the fact that we have a right inverse is essentially `split_wrt_composition_join`, -- but we need to massage it to take care of the dependent setting. rintros ⟨c, d⟩, have : map list.sum (of_fn (λ (i : fin (composition.length c)), (d i).blocks)) = c.blocks, by simp [map_of_fn, (∘), composition.blocks_sum, composition.of_fn_blocks_fun], rw sigma_pi_composition_eq_iff, dsimp, congr, { ext1, dsimp [composition.gather], rwa split_wrt_composition_join, simp only [map_of_fn] }, { rw fin.heq_fun_iff, { assume i, dsimp [composition.sigma_composition_aux], rw [nth_le_of_eq (split_wrt_composition_join _ _ _)], { simp only [nth_le_of_fn'] }, { simp only [map_of_fn] } }, { congr, ext1, dsimp [composition.gather], rwa split_wrt_composition_join, simp only [map_of_fn] } } end } end composition namespace formal_multilinear_series open composition theorem comp_assoc (r : formal_multilinear_series 𝕜 G H) (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) : (r.comp q).comp p = r.comp (q.comp p) := begin ext n v, /- First, rewrite the two compositions appearing in the theorem as two sums over complicated sigma types, as in the description of the proof above. -/ let f : (Σ (a : composition n), composition a.length) → H := λ c, r c.2.length (apply_composition q c.2 (apply_composition p c.1 v)), let g : (Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i)) → H := λ c, r c.1.length (λ (i : fin c.1.length), q (c.2 i).length (apply_composition p (c.2 i) (v ∘ c.1.embedding i))), suffices : ∑ c, f c = ∑ c, g c, by simpa only [formal_multilinear_series.comp, continuous_multilinear_map.sum_apply, comp_along_composition_apply, continuous_multilinear_map.map_sum, finset.sum_sigma', apply_composition], /- Now, we use `composition.sigma_equiv_sigma_pi n` to change variables in the second sum, and check that we get exactly the same sums. -/ rw ← (sigma_equiv_sigma_pi n).sum_comp, /- To check that we have the same terms, we should check that we apply the same component of `r`, and the same component of `q`, and the same component of `p`, to the same coordinate of `v`. This is true by definition, but at each step one needs to convince Lean that the types one considers are the same, using a suitable congruence lemma to avoid dependent type issues. This dance has to be done three times, one for `r`, one for `q` and one for `p`.-/ apply finset.sum_congr rfl, rintros ⟨a, b⟩ _, dsimp [f, g, sigma_equiv_sigma_pi], -- check that the `r` components are the same. Based on `composition.length_gather` apply r.congr (composition.length_gather a b).symm, intros i hi1 hi2, -- check that the `q` components are the same. Based on `length_sigma_composition_aux` apply q.congr (length_sigma_composition_aux a b _).symm, intros j hj1 hj2, -- check that the `p` components are the same. Based on `blocks_fun_sigma_composition_aux` apply p.congr (blocks_fun_sigma_composition_aux a b _ _).symm, intros k hk1 hk2, -- finally, check that the coordinates of `v` one is using are the same. Based on -- `size_up_to_size_up_to_add`. refine congr_arg v (fin.eq_of_veq _), dsimp [composition.embedding], rw [size_up_to_size_up_to_add _ _ hi1 hj1, add_assoc], end end formal_multilinear_series
a9d6f5396b9290c2bc24987fa890f6a9bc10486c
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/simp_command.lean
83d2a5d2c877fdd4bebb99d150821b63cb89e94f
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
2,524
lean
import tactic.simp_command import analysis.special_functions.trigonometric.deriv import analysis.calculus.deriv.inv /- Turn off trace messages only if the statements are simplified to true: -/ set_option trace.silence_simp_if_true true /-! Tests for the #simp command. -/ #simp 5 - 5 = 0 section arith def f (x : ℤ) := x + (x - x) #simp [f] f 3 = 3 mk_simp_attribute test "" attribute [test] f -- You can use the optional `:` to separate -- the simp lemmas and attributes from the expression to simplify. #simp with test : (f 3) = 3 attribute [simp] f #simp f 3 = 3 #simp only [f, eq_self_iff_true] f 3 = 3 + (3 - 3) local attribute [simp] sub_self variables (x : ℤ) #simp with test : (f x) = x #simp f x = x #simp only [f, eq_self_iff_true] f x = x + (x - x) #simp only [f, sub_self, eq_self_iff_true] f x = x + 0 end arith section real open real #simp [exp_ne_zero] : (λ x, deriv (λ x, (sin x) / (exp x)) x) = (λ (x : ℝ), (cos x * exp x - sin x * exp x) / exp x ^ 2) variables (x : ℝ) -- You can refer to local variables, rather than having to use lambdas. open real #simp [exp_ne_zero] : deriv (λ x, (sin x) / (exp x)) x = (cos x * exp x - sin x * exp x) / exp x ^ 2 end real section func_hyp variables (f : ℕ → ℕ) (hf : f 3 = 0) (hg : 9 = 55) #simp only [hg, eq_self_iff_true] : 9 = 55 #simp only [hf, add_zero, eq_self_iff_true] : 1 + f 3 = 1 end func_hyp namespace inst class magic_data (n : ℕ) := (dummy : ℕ) axiom spell (t : ℤ) (k : ℕ) [magic_data k] : (k = 3) ↔ (k = 77) variables (t : ℤ) (k : ℕ) [magic_data k] [ii : magic_data k] (h : k = 77 ↔ k = 8) -- We want to be able to emulate this: example : (t = t) ∧ (h = h) ∧ ((k = 3) ↔ (k = 8)) := begin simp [spell t, h] end -- Check that we can: #simp [spell t, h, ii] : (k = 3) ↔ (k = 8) #simp [spell t, h] : (k = 3) ↔ (k = 8) theorem spell' (k : ℕ) [magic_data k] : (k = 3) ↔ (k = 77) := spell 1 k attribute [simp] spell' #simp [h, ii] : (k = 3) ↔ (k = 8) #simp [h] : (k = 3) ↔ (k = 8) -- Check that the `#simp` resolver can handle depth > 2 recursive inclusions class doubly_magic_data (n : ℕ) [magic_data n] := (dummy : ℕ) variables (n : ℕ) [magic_data n] [doubly_magic_data n] (h₂ : n = 77 ↔ n = 8) @[simp] axiom spell2 (n : ℕ) [magic_data n] [doubly_magic_data n] : (n = 4) ↔ (n = 77) example : (h₂ = h₂) ∧ ((n = 4) ↔ (n = 8)) := begin simp [h₂], end #simp [h₂, ii] : (n = 4) ↔ (n = 8) #simp [h₂] : (n = 4) ↔ (n = 8) end inst
264aef4bbfa0c9649fd51512ced4e497ed7105bf
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/normed_space/linear_isometry.lean
38d372c854af04129181d2b4a7bc52db91e26d95
[ "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
26,442
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Frédéric Dupuis, Heather Macbeth -/ import analysis.normed.group.basic import topology.algebra.module.basic import linear_algebra.basis /-! # (Semi-)linear isometries In this file we define `linear_isometry σ₁₂ E E₂` (notation: `E →ₛₗᵢ[σ₁₂] E₂`) to be a semilinear isometric embedding of `E` into `E₂` and `linear_isometry_equiv` (notation: `E ≃ₛₗᵢ[σ₁₂] E₂`) to be a semilinear isometric equivalence between `E` and `E₂`. The notation for the associated purely linear concepts is `E →ₗᵢ[R] E₂`, `E ≃ₗᵢ[R] E₂`, and `E →ₗᵢ⋆[R] E₂`, `E ≃ₗᵢ⋆[R] E₂` for the star-linear versions. We also prove some trivial lemmas and provide convenience constructors. Since a lot of elementary properties don't require `∥x∥ = 0 → x = 0` we start setting up the theory for `semi_normed_group` and we specialize to `normed_group` when needed. -/ open function set variables {R R₂ R₃ R₄ E E₂ E₃ E₄ F : Type*} [semiring R] [semiring R₂] [semiring R₃] [semiring R₄] {σ₁₂ : R →+* R₂} {σ₂₁ : R₂ →+* R} {σ₁₃ : R →+* R₃} {σ₃₁ : R₃ →+* R} {σ₁₄ : R →+* R₄} {σ₄₁ : R₄ →+* R} {σ₂₃ : R₂ →+* R₃} {σ₃₂ : R₃ →+* R₂} {σ₂₄ : R₂ →+* R₄} {σ₄₂ : R₄ →+* R₂} {σ₃₄ : R₃ →+* R₄} {σ₄₃ : R₄ →+* R₃} [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂] [ring_hom_inv_pair σ₁₃ σ₃₁] [ring_hom_inv_pair σ₃₁ σ₁₃] [ring_hom_inv_pair σ₂₃ σ₃₂] [ring_hom_inv_pair σ₃₂ σ₂₃] [ring_hom_inv_pair σ₁₄ σ₄₁] [ring_hom_inv_pair σ₄₁ σ₁₄] [ring_hom_inv_pair σ₂₄ σ₄₂] [ring_hom_inv_pair σ₄₂ σ₂₄] [ring_hom_inv_pair σ₃₄ σ₄₃] [ring_hom_inv_pair σ₄₃ σ₃₄] [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] [ring_hom_comp_triple σ₁₂ σ₂₄ σ₁₄] [ring_hom_comp_triple σ₂₃ σ₃₄ σ₂₄] [ring_hom_comp_triple σ₁₃ σ₃₄ σ₁₄] [ring_hom_comp_triple σ₃₂ σ₂₁ σ₃₁] [ring_hom_comp_triple σ₄₂ σ₂₁ σ₄₁] [ring_hom_comp_triple σ₄₃ σ₃₂ σ₄₂] [ring_hom_comp_triple σ₄₃ σ₃₁ σ₄₁] [semi_normed_group E] [semi_normed_group E₂] [semi_normed_group E₃] [semi_normed_group E₄] [module R E] [module R₂ E₂] [module R₃ E₃] [module R₄ E₄] [normed_group F] [module R F] /-- A `σ₁₂`-semilinear isometric embedding of a normed `R`-module into an `R₂`-module. -/ structure linear_isometry (σ₁₂ : R →+* R₂) (E E₂ : Type*) [semi_normed_group E] [semi_normed_group E₂] [module R E] [module R₂ E₂] extends E →ₛₗ[σ₁₂] E₂ := (norm_map' : ∀ x, ∥to_linear_map x∥ = ∥x∥) notation E ` →ₛₗᵢ[`:25 σ₁₂:25 `] `:0 E₂:0 := linear_isometry σ₁₂ E E₂ notation E ` →ₗᵢ[`:25 R:25 `] `:0 E₂:0 := linear_isometry (ring_hom.id R) E E₂ notation E ` →ₗᵢ⋆[`:25 R:25 `] `:0 E₂:0 := linear_isometry (star_ring_end R) E E₂ namespace linear_isometry /-- We use `f₁` when we need the domain to be a `normed_space`. -/ variables (f : E →ₛₗᵢ[σ₁₂] E₂) (f₁ : F →ₛₗᵢ[σ₁₂] E₂) lemma to_linear_map_injective : injective (to_linear_map : (E →ₛₗᵢ[σ₁₂] E₂) → (E →ₛₗ[σ₁₂] E₂)) | ⟨f, _⟩ ⟨g, _⟩ rfl := rfl @[simp] lemma to_linear_map_inj {f g : E →ₛₗᵢ[σ₁₂] E₂} : f.to_linear_map = g.to_linear_map ↔ f = g := to_linear_map_injective.eq_iff instance : add_monoid_hom_class (E →ₛₗᵢ[σ₁₂] E₂) E E₂ := { coe := λ e, e.to_fun, coe_injective' := λ f g h, to_linear_map_injective (fun_like.coe_injective h), map_add := λ f, map_add f.to_linear_map, map_zero := λ f, map_zero f.to_linear_map } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (E →ₛₗᵢ[σ₁₂] E₂) (λ _, E → E₂) := ⟨λ f, f.to_fun⟩ @[simp] lemma coe_to_linear_map : ⇑f.to_linear_map = f := rfl @[simp] lemma coe_mk (f : E →ₛₗ[σ₁₂] E₂) (hf) : ⇑(mk f hf) = f := rfl lemma coe_injective : @injective (E →ₛₗᵢ[σ₁₂] E₂) (E → E₂) coe_fn := fun_like.coe_injective @[ext] lemma ext {f g : E →ₛₗᵢ[σ₁₂] E₂} (h : ∀ x, f x = g x) : f = g := coe_injective $ funext h protected lemma congr_arg {f : E →ₛₗᵢ[σ₁₂] E₂} : Π {x x' : E}, x = x' → f x = f x' | _ _ rfl := rfl protected lemma congr_fun {f g : E →ₛₗᵢ[σ₁₂] E₂} (h : f = g) (x : E) : f x = g x := h ▸ rfl @[simp] lemma map_zero : f 0 = 0 := f.to_linear_map.map_zero @[simp] lemma map_add (x y : E) : f (x + y) = f x + f y := f.to_linear_map.map_add x y @[simp] lemma map_neg (x : E) : f (- x) = - f x := f.to_linear_map.map_neg x @[simp] lemma map_sub (x y : E) : f (x - y) = f x - f y := f.to_linear_map.map_sub x y @[simp] lemma map_smulₛₗ (c : R) (x : E) : f (c • x) = σ₁₂ c • f x := f.to_linear_map.map_smulₛₗ c x @[simp] lemma map_smul [module R E₂] (f : E →ₗᵢ[R] E₂) (c : R) (x : E) : f (c • x) = c • f x := f.to_linear_map.map_smul c x @[simp] lemma norm_map (x : E) : ∥f x∥ = ∥x∥ := f.norm_map' x @[simp] lemma nnnorm_map (x : E) : ∥f x∥₊ = ∥x∥₊ := nnreal.eq $ f.norm_map x protected lemma isometry : isometry f := f.to_linear_map.to_add_monoid_hom.isometry_of_norm f.norm_map @[simp] lemma is_complete_image_iff {s : set E} : is_complete (f '' s) ↔ is_complete s := is_complete_image_iff f.isometry.uniform_inducing lemma is_complete_map_iff [ring_hom_surjective σ₁₂] {p : submodule R E} : is_complete (p.map f.to_linear_map : set E₂) ↔ is_complete (p : set E) := f.is_complete_image_iff instance complete_space_map [ring_hom_surjective σ₁₂] (p : submodule R E) [complete_space p] : complete_space (p.map f.to_linear_map) := (f.is_complete_map_iff.2 $ complete_space_coe_iff_is_complete.1 ‹_›).complete_space_coe @[simp] lemma dist_map (x y : E) : dist (f x) (f y) = dist x y := f.isometry.dist_eq x y @[simp] lemma edist_map (x y : E) : edist (f x) (f y) = edist x y := f.isometry.edist_eq x y protected lemma injective : injective f₁ := f₁.isometry.injective @[simp] lemma map_eq_iff {x y : F} : f₁ x = f₁ y ↔ x = y := f₁.injective.eq_iff lemma map_ne {x y : F} (h : x ≠ y) : f₁ x ≠ f₁ y := f₁.injective.ne h protected lemma lipschitz : lipschitz_with 1 f := f.isometry.lipschitz protected lemma antilipschitz : antilipschitz_with 1 f := f.isometry.antilipschitz @[continuity] protected lemma continuous : continuous f := f.isometry.continuous lemma ediam_image (s : set E) : emetric.diam (f '' s) = emetric.diam s := f.isometry.ediam_image s lemma ediam_range : emetric.diam (range f) = emetric.diam (univ : set E) := f.isometry.ediam_range lemma diam_image (s : set E) : metric.diam (f '' s) = metric.diam s := f.isometry.diam_image s lemma diam_range : metric.diam (range f) = metric.diam (univ : set E) := f.isometry.diam_range /-- Interpret a linear isometry as a continuous linear map. -/ def to_continuous_linear_map : E →SL[σ₁₂] E₂ := ⟨f.to_linear_map, f.continuous⟩ lemma to_continuous_linear_map_injective : function.injective (to_continuous_linear_map : _ → E →SL[σ₁₂] E₂) := λ x y h, coe_injective (congr_arg _ h : ⇑x.to_continuous_linear_map = _) @[simp] lemma to_continuous_linear_map_inj {f g : E →ₛₗᵢ[σ₁₂] E₂} : f.to_continuous_linear_map = g.to_continuous_linear_map ↔ f = g := to_continuous_linear_map_injective.eq_iff @[simp] lemma coe_to_continuous_linear_map : ⇑f.to_continuous_linear_map = f := rfl @[simp] lemma comp_continuous_iff {α : Type*} [topological_space α] {g : α → E} : continuous (f ∘ g) ↔ continuous g := f.isometry.comp_continuous_iff /-- The identity linear isometry. -/ def id : E →ₗᵢ[R] E := ⟨linear_map.id, λ x, rfl⟩ @[simp] lemma coe_id : ((id : E →ₗᵢ[R] E) : E → E) = _root_.id := rfl @[simp] lemma id_apply (x : E) : (id : E →ₗᵢ[R] E) x = x := rfl @[simp] lemma id_to_linear_map : (id.to_linear_map : E →ₗ[R] E) = linear_map.id := rfl @[simp] lemma id_to_continuous_linear_map : id.to_continuous_linear_map = continuous_linear_map.id R E := rfl instance : inhabited (E →ₗᵢ[R] E) := ⟨id⟩ /-- Composition of linear isometries. -/ def comp (g : E₂ →ₛₗᵢ[σ₂₃] E₃) (f : E →ₛₗᵢ[σ₁₂] E₂) : E →ₛₗᵢ[σ₁₃] E₃ := ⟨g.to_linear_map.comp f.to_linear_map, λ x, (g.norm_map _).trans (f.norm_map _)⟩ include σ₁₃ @[simp] lemma coe_comp (g : E₂ →ₛₗᵢ[σ₂₃] E₃) (f : E →ₛₗᵢ[σ₁₂] E₂) : ⇑(g.comp f) = g ∘ f := rfl omit σ₁₃ @[simp] lemma id_comp : (id : E₂ →ₗᵢ[R₂] E₂).comp f = f := ext $ λ x, rfl @[simp] lemma comp_id : f.comp id = f := ext $ λ x, rfl include σ₁₃ σ₂₄ σ₁₄ lemma comp_assoc (f : E₃ →ₛₗᵢ[σ₃₄] E₄) (g : E₂ →ₛₗᵢ[σ₂₃] E₃) (h : E →ₛₗᵢ[σ₁₂] E₂) : (f.comp g).comp h = f.comp (g.comp h) := rfl omit σ₁₃ σ₂₄ σ₁₄ instance : monoid (E →ₗᵢ[R] E) := { one := id, mul := comp, mul_assoc := comp_assoc, one_mul := id_comp, mul_one := comp_id } @[simp] lemma coe_one : ((1 : E →ₗᵢ[R] E) : E → E) = _root_.id := rfl @[simp] lemma coe_mul (f g : E →ₗᵢ[R] E) : ⇑(f * g) = f ∘ g := rfl lemma one_def : (1 : E →ₗᵢ[R] E) = id := rfl lemma mul_def (f g : E →ₗᵢ[R] E) : (f * g : E →ₗᵢ[R] E) = f.comp g := rfl end linear_isometry /-- Construct a `linear_isometry` from a `linear_map` satisfying `isometry`. -/ def linear_map.to_linear_isometry (f : E →ₛₗ[σ₁₂] E₂) (hf : isometry f) : E →ₛₗᵢ[σ₁₂] E₂ := { norm_map' := by { simp_rw [←dist_zero_right, ←f.map_zero], exact λ x, hf.dist_eq x _ }, .. f } namespace submodule variables {R' : Type*} [ring R'] [module R' E] (p : submodule R' E) /-- `submodule.subtype` as a `linear_isometry`. -/ def subtypeₗᵢ : p →ₗᵢ[R'] E := ⟨p.subtype, λ x, rfl⟩ @[simp] lemma coe_subtypeₗᵢ : ⇑p.subtypeₗᵢ = p.subtype := rfl @[simp] lemma subtypeₗᵢ_to_linear_map : p.subtypeₗᵢ.to_linear_map = p.subtype := rfl /-- `submodule.subtype` as a `continuous_linear_map`. -/ def subtypeL : p →L[R'] E := p.subtypeₗᵢ.to_continuous_linear_map @[simp] lemma coe_subtypeL : (p.subtypeL : p →ₗ[R'] E) = p.subtype := rfl @[simp] lemma coe_subtypeL' : ⇑p.subtypeL = p.subtype := rfl @[simp] lemma range_subtypeL : p.subtypeL.range = p := range_subtype _ @[simp] lemma ker_subtypeL : p.subtypeL.ker = ⊥ := ker_subtype _ end submodule /-- A semilinear isometric equivalence between two normed vector spaces. -/ structure linear_isometry_equiv (σ₁₂ : R →+* R₂) {σ₂₁ : R₂ →+* R} [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂] (E E₂ : Type*) [semi_normed_group E] [semi_normed_group E₂] [module R E] [module R₂ E₂] extends E ≃ₛₗ[σ₁₂] E₂ := (norm_map' : ∀ x, ∥to_linear_equiv x∥ = ∥x∥) notation E ` ≃ₛₗᵢ[`:25 σ₁₂:25 `] `:0 E₂:0 := linear_isometry_equiv σ₁₂ E E₂ notation E ` ≃ₗᵢ[`:25 R:25 `] `:0 E₂:0 := linear_isometry_equiv (ring_hom.id R) E E₂ notation E ` ≃ₗᵢ⋆[`:25 R:25 `] `:0 E₂:0 := linear_isometry_equiv (star_ring_end R) E E₂ namespace linear_isometry_equiv variables (e : E ≃ₛₗᵢ[σ₁₂] E₂) include σ₂₁ lemma to_linear_equiv_injective : injective (to_linear_equiv : (E ≃ₛₗᵢ[σ₁₂] E₂) → (E ≃ₛₗ[σ₁₂] E₂)) | ⟨e, _⟩ ⟨_, _⟩ rfl := rfl @[simp] lemma to_linear_equiv_inj {f g : E ≃ₛₗᵢ[σ₁₂] E₂} : f.to_linear_equiv = g.to_linear_equiv ↔ f = g := to_linear_equiv_injective.eq_iff instance : add_monoid_hom_class (E ≃ₛₗᵢ[σ₁₂] E₂) E E₂ := { coe := λ e, e.to_fun, coe_injective' := λ f g h, to_linear_equiv_injective (fun_like.coe_injective h), map_add := λ f, map_add f.to_linear_equiv, map_zero := λ f, map_zero f.to_linear_equiv } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (E ≃ₛₗᵢ[σ₁₂] E₂) (λ _, E → E₂) := ⟨λ f, f.to_fun⟩ lemma coe_injective : @function.injective (E ≃ₛₗᵢ[σ₁₂] E₂) (E → E₂) coe_fn := fun_like.coe_injective @[simp] lemma coe_mk (e : E ≃ₛₗ[σ₁₂] E₂) (he : ∀ x, ∥e x∥ = ∥x∥) : ⇑(mk e he) = e := rfl @[simp] lemma coe_to_linear_equiv (e : E ≃ₛₗᵢ[σ₁₂] E₂) : ⇑e.to_linear_equiv = e := rfl @[ext] lemma ext {e e' : E ≃ₛₗᵢ[σ₁₂] E₂} (h : ∀ x, e x = e' x) : e = e' := to_linear_equiv_injective $ linear_equiv.ext h protected lemma congr_arg {f : E ≃ₛₗᵢ[σ₁₂] E₂} : Π {x x' : E}, x = x' → f x = f x' | _ _ rfl := rfl protected lemma congr_fun {f g : E ≃ₛₗᵢ[σ₁₂] E₂} (h : f = g) (x : E) : f x = g x := h ▸ rfl /-- Construct a `linear_isometry_equiv` from a `linear_equiv` and two inequalities: `∀ x, ∥e x∥ ≤ ∥x∥` and `∀ y, ∥e.symm y∥ ≤ ∥y∥`. -/ def of_bounds (e : E ≃ₛₗ[σ₁₂] E₂) (h₁ : ∀ x, ∥e x∥ ≤ ∥x∥) (h₂ : ∀ y, ∥e.symm y∥ ≤ ∥y∥) : E ≃ₛₗᵢ[σ₁₂] E₂ := ⟨e, λ x, le_antisymm (h₁ x) $ by simpa only [e.symm_apply_apply] using h₂ (e x)⟩ @[simp] lemma norm_map (x : E) : ∥e x∥ = ∥x∥ := e.norm_map' x /-- Reinterpret a `linear_isometry_equiv` as a `linear_isometry`. -/ def to_linear_isometry : E →ₛₗᵢ[σ₁₂] E₂ := ⟨e.1, e.2⟩ lemma to_linear_isometry_injective : function.injective (to_linear_isometry : _ → E →ₛₗᵢ[σ₁₂] E₂) := λ x y h, coe_injective (congr_arg _ h : ⇑x.to_linear_isometry = _) @[simp] lemma to_linear_isometry_inj {f g : E ≃ₛₗᵢ[σ₁₂] E₂} : f.to_linear_isometry = g.to_linear_isometry ↔ f = g := to_linear_isometry_injective.eq_iff @[simp] lemma coe_to_linear_isometry : ⇑e.to_linear_isometry = e := rfl protected lemma isometry : isometry e := e.to_linear_isometry.isometry /-- Reinterpret a `linear_isometry_equiv` as an `isometric`. -/ def to_isometric : E ≃ᵢ E₂ := ⟨e.to_linear_equiv.to_equiv, e.isometry⟩ lemma to_isometric_injective : function.injective (to_isometric : (E ≃ₛₗᵢ[σ₁₂] E₂) → E ≃ᵢ E₂) := λ x y h, coe_injective (congr_arg _ h : ⇑x.to_isometric = _) @[simp] lemma to_isometric_inj {f g : E ≃ₛₗᵢ[σ₁₂] E₂} : f.to_isometric = g.to_isometric ↔ f = g := to_isometric_injective.eq_iff @[simp] lemma coe_to_isometric : ⇑e.to_isometric = e := rfl lemma range_eq_univ (e : E ≃ₛₗᵢ[σ₁₂] E₂) : set.range e = set.univ := by { rw ← coe_to_isometric, exact isometric.range_eq_univ _, } /-- Reinterpret a `linear_isometry_equiv` as an `homeomorph`. -/ def to_homeomorph : E ≃ₜ E₂ := e.to_isometric.to_homeomorph lemma to_homeomorph_injective : function.injective (to_homeomorph : (E ≃ₛₗᵢ[σ₁₂] E₂) → E ≃ₜ E₂) := λ x y h, coe_injective (congr_arg _ h : ⇑x.to_homeomorph = _) @[simp] lemma to_homeomorph_inj {f g : E ≃ₛₗᵢ[σ₁₂] E₂} : f.to_homeomorph = g.to_homeomorph ↔ f = g := to_homeomorph_injective.eq_iff @[simp] lemma coe_to_homeomorph : ⇑e.to_homeomorph = e := rfl protected lemma continuous : continuous e := e.isometry.continuous protected lemma continuous_at {x} : continuous_at e x := e.continuous.continuous_at protected lemma continuous_on {s} : continuous_on e s := e.continuous.continuous_on protected lemma continuous_within_at {s x} : continuous_within_at e s x := e.continuous.continuous_within_at /-- Interpret a `linear_isometry_equiv` as a continuous linear equiv. -/ def to_continuous_linear_equiv : E ≃SL[σ₁₂] E₂ := { .. e.to_linear_isometry.to_continuous_linear_map, .. e.to_homeomorph } lemma to_continuous_linear_equiv_injective : function.injective (to_continuous_linear_equiv : _ → E ≃SL[σ₁₂] E₂) := λ x y h, coe_injective (congr_arg _ h : ⇑x.to_continuous_linear_equiv = _) @[simp] lemma to_continuous_linear_equiv_inj {f g : E ≃ₛₗᵢ[σ₁₂] E₂} : f.to_continuous_linear_equiv = g.to_continuous_linear_equiv ↔ f = g := to_continuous_linear_equiv_injective.eq_iff @[simp] lemma coe_to_continuous_linear_equiv : ⇑e.to_continuous_linear_equiv = e := rfl omit σ₂₁ variables (R E) /-- Identity map as a `linear_isometry_equiv`. -/ def refl : E ≃ₗᵢ[R] E := ⟨linear_equiv.refl R E, λ x, rfl⟩ variables {R E} instance : inhabited (E ≃ₗᵢ[R] E) := ⟨refl R E⟩ @[simp] lemma coe_refl : ⇑(refl R E) = id := rfl /-- The inverse `linear_isometry_equiv`. -/ def symm : E₂ ≃ₛₗᵢ[σ₂₁] E := ⟨e.to_linear_equiv.symm, λ x, (e.norm_map _).symm.trans $ congr_arg norm $ e.to_linear_equiv.apply_symm_apply x⟩ @[simp] lemma apply_symm_apply (x : E₂) : e (e.symm x) = x := e.to_linear_equiv.apply_symm_apply x @[simp] lemma symm_apply_apply (x : E) : e.symm (e x) = x := e.to_linear_equiv.symm_apply_apply x @[simp] lemma map_eq_zero_iff {x : E} : e x = 0 ↔ x = 0 := e.to_linear_equiv.map_eq_zero_iff @[simp] lemma symm_symm : e.symm.symm = e := ext $ λ x, rfl @[simp] lemma to_linear_equiv_symm : e.to_linear_equiv.symm = e.symm.to_linear_equiv := rfl @[simp] lemma to_isometric_symm : e.to_isometric.symm = e.symm.to_isometric := rfl @[simp] lemma to_homeomorph_symm : e.to_homeomorph.symm = e.symm.to_homeomorph := rfl include σ₃₁ σ₃₂ /-- Composition of `linear_isometry_equiv`s as a `linear_isometry_equiv`. -/ def trans (e' : E₂ ≃ₛₗᵢ[σ₂₃] E₃) : E ≃ₛₗᵢ[σ₁₃] E₃ := ⟨e.to_linear_equiv.trans e'.to_linear_equiv, λ x, (e'.norm_map _).trans (e.norm_map _)⟩ include σ₁₃ σ₂₁ @[simp] lemma coe_trans (e₁ : E ≃ₛₗᵢ[σ₁₂] E₂) (e₂ : E₂ ≃ₛₗᵢ[σ₂₃] E₃) : ⇑(e₁.trans e₂) = e₂ ∘ e₁ := rfl @[simp] lemma trans_apply (e₁ : E ≃ₛₗᵢ[σ₁₂] E₂) (e₂ : E₂ ≃ₛₗᵢ[σ₂₃] E₃) (c : E) : (e₁.trans e₂ : E ≃ₛₗᵢ[σ₁₃] E₃) c = e₂ (e₁ c) := rfl @[simp] lemma to_linear_equiv_trans (e' : E₂ ≃ₛₗᵢ[σ₂₃] E₃) : (e.trans e').to_linear_equiv = e.to_linear_equiv.trans e'.to_linear_equiv := rfl omit σ₁₃ σ₂₁ σ₃₁ σ₃₂ @[simp] lemma trans_refl : e.trans (refl R₂ E₂) = e := ext $ λ x, rfl @[simp] lemma refl_trans : (refl R E).trans e = e := ext $ λ x, rfl @[simp] lemma self_trans_symm : e.trans e.symm = refl R E := ext e.symm_apply_apply @[simp] lemma symm_trans_self : e.symm.trans e = refl R₂ E₂ := ext e.apply_symm_apply @[simp] lemma symm_comp_self : e.symm ∘ e = id := funext e.symm_apply_apply @[simp] lemma self_comp_symm : e ∘ e.symm = id := e.symm.symm_comp_self include σ₁₃ σ₂₁ σ₃₂ σ₃₁ @[simp] lemma symm_trans (e₁ : E ≃ₛₗᵢ[σ₁₂] E₂) (e₂ : E₂ ≃ₛₗᵢ[σ₂₃] E₃) : (e₁.trans e₂).symm = e₂.symm.trans e₁.symm := rfl lemma coe_symm_trans (e₁ : E ≃ₛₗᵢ[σ₁₂] E₂) (e₂ : E₂ ≃ₛₗᵢ[σ₂₃] E₃) : ⇑(e₁.trans e₂).symm = e₁.symm ∘ e₂.symm := rfl include σ₁₄ σ₄₁ σ₄₂ σ₄₃ σ₂₄ lemma trans_assoc (eEE₂ : E ≃ₛₗᵢ[σ₁₂] E₂) (eE₂E₃ : E₂ ≃ₛₗᵢ[σ₂₃] E₃) (eE₃E₄ : E₃ ≃ₛₗᵢ[σ₃₄] E₄) : eEE₂.trans (eE₂E₃.trans eE₃E₄) = (eEE₂.trans eE₂E₃).trans eE₃E₄ := rfl omit σ₂₁ σ₃₁ σ₄₁ σ₃₂ σ₄₂ σ₄₃ σ₁₃ σ₂₄ σ₁₄ instance : group (E ≃ₗᵢ[R] E) := { mul := λ e₁ e₂, e₂.trans e₁, one := refl _ _, inv := symm, one_mul := trans_refl, mul_one := refl_trans, mul_assoc := λ _ _ _, trans_assoc _ _ _, mul_left_inv := self_trans_symm } @[simp] lemma coe_one : ⇑(1 : E ≃ₗᵢ[R] E) = id := rfl @[simp] lemma coe_mul (e e' : E ≃ₗᵢ[R] E) : ⇑(e * e') = e ∘ e' := rfl @[simp] lemma coe_inv (e : E ≃ₗᵢ[R] E) : ⇑(e⁻¹) = e.symm := rfl lemma one_def : (1 : E ≃ₗᵢ[R] E) = refl _ _ := rfl lemma mul_def (e e' : E ≃ₗᵢ[R] E) : (e * e' : E ≃ₗᵢ[R] E) = e'.trans e := rfl lemma inv_def (e : E ≃ₗᵢ[R] E) : (e⁻¹ : E ≃ₗᵢ[R] E) = e.symm := rfl /-! Lemmas about mixing the group structure with definitions. Because we have multiple ways to express `linear_isometry_equiv.refl`, `linear_isometry_equiv.symm`, and `linear_isometry_equiv.trans`, we want simp lemmas for every combination. The assumption made here is that if you're using the group structure, you want to preserve it after simp. This copies the approach used by the lemmas near `equiv.perm.trans_one`. -/ @[simp] lemma trans_one : e.trans (1 : E₂ ≃ₗᵢ[R₂] E₂) = e := trans_refl _ @[simp] lemma one_trans : (1 : E ≃ₗᵢ[R] E).trans e = e := refl_trans _ @[simp] lemma refl_mul (e : E ≃ₗᵢ[R] E) : (refl _ _) * e = e := trans_refl _ @[simp] lemma mul_refl (e : E ≃ₗᵢ[R] E) : e * (refl _ _) = e := refl_trans _ include σ₂₁ /-- Reinterpret a `linear_isometry_equiv` as a `continuous_linear_equiv`. -/ instance : has_coe_t (E ≃ₛₗᵢ[σ₁₂] E₂) (E ≃SL[σ₁₂] E₂) := ⟨λ e, ⟨e.to_linear_equiv, e.continuous, e.to_isometric.symm.continuous⟩⟩ instance : has_coe_t (E ≃ₛₗᵢ[σ₁₂] E₂) (E →SL[σ₁₂] E₂) := ⟨λ e, ↑(e : E ≃SL[σ₁₂] E₂)⟩ @[simp] lemma coe_coe : ⇑(e : E ≃SL[σ₁₂] E₂) = e := rfl @[simp] lemma coe_coe' : ((e : E ≃SL[σ₁₂] E₂) : E →SL[σ₁₂] E₂) = e := rfl @[simp] lemma coe_coe'' : ⇑(e : E →SL[σ₁₂] E₂) = e := rfl omit σ₂₁ @[simp] lemma map_zero : e 0 = 0 := e.1.map_zero @[simp] lemma map_add (x y : E) : e (x + y) = e x + e y := e.1.map_add x y @[simp] lemma map_sub (x y : E) : e (x - y) = e x - e y := e.1.map_sub x y @[simp] lemma map_smulₛₗ (c : R) (x : E) : e (c • x) = σ₁₂ c • e x := e.1.map_smulₛₗ c x @[simp] lemma map_smul [module R E₂] {e : E ≃ₗᵢ[R] E₂} (c : R) (x : E) : e (c • x) = c • e x := e.1.map_smul c x @[simp] lemma nnnorm_map (x : E) : ∥e x∥₊ = ∥x∥₊ := e.to_linear_isometry.nnnorm_map x @[simp] lemma dist_map (x y : E) : dist (e x) (e y) = dist x y := e.to_linear_isometry.dist_map x y @[simp] lemma edist_map (x y : E) : edist (e x) (e y) = edist x y := e.to_linear_isometry.edist_map x y protected lemma bijective : bijective e := e.1.bijective protected lemma injective : injective e := e.1.injective protected lemma surjective : surjective e := e.1.surjective @[simp] lemma map_eq_iff {x y : E} : e x = e y ↔ x = y := e.injective.eq_iff lemma map_ne {x y : E} (h : x ≠ y) : e x ≠ e y := e.injective.ne h protected lemma lipschitz : lipschitz_with 1 e := e.isometry.lipschitz protected lemma antilipschitz : antilipschitz_with 1 e := e.isometry.antilipschitz @[simp] lemma ediam_image (s : set E) : emetric.diam (e '' s) = emetric.diam s := e.isometry.ediam_image s @[simp] lemma diam_image (s : set E) : metric.diam (e '' s) = metric.diam s := e.isometry.diam_image s variables {α : Type*} [topological_space α] @[simp] lemma comp_continuous_on_iff {f : α → E} {s : set α} : continuous_on (e ∘ f) s ↔ continuous_on f s := e.isometry.comp_continuous_on_iff @[simp] lemma comp_continuous_iff {f : α → E} : continuous (e ∘ f) ↔ continuous f := e.isometry.comp_continuous_iff instance complete_space_map (p : submodule R E) [complete_space p] : complete_space (p.map (e.to_linear_equiv : E →ₛₗ[σ₁₂] E₂)) := e.to_linear_isometry.complete_space_map p include σ₂₁ /-- Construct a linear isometry equiv from a surjective linear isometry. -/ noncomputable def of_surjective (f : F →ₛₗᵢ[σ₁₂] E₂) (hfr : function.surjective f) : F ≃ₛₗᵢ[σ₁₂] E₂ := { norm_map' := f.norm_map, .. linear_equiv.of_bijective f.to_linear_map f.injective hfr } @[simp] lemma coe_of_surjective (f : F →ₛₗᵢ[σ₁₂] E₂) (hfr : function.surjective f) : ⇑(linear_isometry_equiv.of_surjective f hfr) = f := by { ext, refl } omit σ₂₁ variables (R) /-- The negation operation on a normed space `E`, considered as a linear isometry equivalence. -/ def neg : E ≃ₗᵢ[R] E := { norm_map' := norm_neg, .. linear_equiv.neg R } variables {R} @[simp] lemma coe_neg : (neg R : E → E) = λ x, -x := rfl @[simp] lemma symm_neg : (neg R : E ≃ₗᵢ[R] E).symm = neg R := rfl variables (R E E₂ E₃) /-- The natural equivalence `(E × E₂) × E₃ ≃ E × (E₂ × E₃)` is a linear isometry. -/ def prod_assoc [module R E₂] [module R E₃] : (E × E₂) × E₃ ≃ₗᵢ[R] E × E₂ × E₃ := { to_fun := equiv.prod_assoc E E₂ E₃, inv_fun := (equiv.prod_assoc E E₂ E₃).symm, map_add' := by simp, map_smul' := by simp, norm_map' := begin rintros ⟨⟨e, f⟩, g⟩, simp only [linear_equiv.coe_mk, equiv.prod_assoc_apply, prod.norm_def, max_assoc], end, .. equiv.prod_assoc E E₂ E₃, } @[simp] lemma coe_prod_assoc [module R E₂] [module R E₃] : (prod_assoc R E E₂ E₃ : (E × E₂) × E₃ → E × E₂ × E₃) = equiv.prod_assoc E E₂ E₃ := rfl @[simp] lemma coe_prod_assoc_symm [module R E₂] [module R E₃] : ((prod_assoc R E E₂ E₃).symm : E × E₂ × E₃ → (E × E₂) × E₃) = (equiv.prod_assoc E E₂ E₃).symm := rfl end linear_isometry_equiv /-- Two linear isometries are equal if they are equal on basis vectors. -/ lemma basis.ext_linear_isometry {ι : Type*} (b : basis ι R E) {f₁ f₂ : E →ₛₗᵢ[σ₁₂] E₂} (h : ∀ i, f₁ (b i) = f₂ (b i)) : f₁ = f₂ := linear_isometry.to_linear_map_injective $ b.ext h include σ₂₁ /-- Two linear isometric equivalences are equal if they are equal on basis vectors. -/ lemma basis.ext_linear_isometry_equiv {ι : Type*} (b : basis ι R E) {f₁ f₂ : E ≃ₛₗᵢ[σ₁₂] E₂} (h : ∀ i, f₁ (b i) = f₂ (b i)) : f₁ = f₂ := linear_isometry_equiv.to_linear_equiv_injective $ b.ext' h omit σ₂₁
20eddce6459ebf297f4b079ef8fa45d43dbb857f
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/stage0/src/Lean/Elab/Tactic/Injection.lean
e20e946b4d7e7dc90feee7eab0986ec64c864848
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,192
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Tactic.Injection import Lean.Elab.Tactic.ElabTerm namespace Lean.Elab.Tactic -- optional (" with " >> many1 ident') private def getInjectionNewIds (stx : Syntax) : List Name := if stx.isNone then [] else stx[1].getArgs.toList.map Syntax.getId private def checkUnusedIds (mvarId : MVarId) (unusedIds : List Name) : MetaM Unit := unless unusedIds.isEmpty do Meta.throwTacticEx `injection mvarId msg!"too many identifiers provided, unused: {unusedIds}" @[builtinTactic «injection»] def evalInjection : Tactic := fun stx => do -- parser! nonReservedSymbol "injection " >> termParser >> withIds let fvarId ← elabAsFVar stx[1] let ids := getInjectionNewIds stx[2] liftMetaTactic fun mvarId => do match ← Meta.injection mvarId fvarId ids (!ids.isEmpty) with | Meta.InjectionResult.solved => checkUnusedIds mvarId ids; pure [] | Meta.InjectionResult.subgoal mvarId' _ unusedIds => checkUnusedIds mvarId unusedIds; pure [mvarId'] end Lean.Elab.Tactic
cd92505547e8d64f02fe63265d2ec937a2d75fe8
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/algebra/invertible.lean
bd7b06b1d4c5e35100bc72b4d5ca37eabd8b5bd3
[ "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
9,967
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 algebra.group.units import algebra.ring.basic /-! # Invertible elements This file defines a typeclass `invertible a` for elements `a` with a two-sided multiplicative inverse. The intent of the typeclass is to provide a way to write e.g. `⅟2` in a ring like `ℤ[1/2]` where some inverses exist but there is no general `⁻¹` operator; or to specify that a field has characteristic `≠ 2`. It is the `Type`-valued analogue to the `Prop`-valued `is_unit`. For constructions of the invertible element given a characteristic, see `algebra/char_p/invertible` and other lemmas in that file. ## Notation * `⅟a` is `invertible.inv_of a`, the inverse of `a` ## Implementation notes The `invertible` class lives in `Type`, not `Prop`, to make computation easier. If multiplication is associative, `invertible` is a subsingleton anyway. The `simp` normal form tries to normalize `⅟a` to `a ⁻¹`. Otherwise, it pushes `⅟` inside the expression as much as possible. Since `invertible a` is not a `Prop` (but it is a `subsingleton`), we have to be careful about coherence issues: we should avoid having multiple non-defeq instances for `invertible a` in the same context. This file plays it safe and uses `def` rather than `instance` for most definitions, users can choose which instances to use at the point of use. For example, here's how you can use an `invertible 1` instance: ```lean variables {α : Type*} [monoid α] def something_that_needs_inverses (x : α) [invertible x] := sorry section local attribute [instance] invertible_one def something_one := something_that_needs_inverses 1 end ``` ## Tags invertible, inverse element, inv_of, a half, one half, a third, one third, ½, ⅓ -/ universes u variables {α : Type u} /-- `invertible a` gives a two-sided multiplicative inverse of `a`. -/ class invertible [has_mul α] [has_one α] (a : α) : Type u := (inv_of : α) (inv_of_mul_self : inv_of * a = 1) (mul_inv_of_self : a * inv_of = 1) -- This notation has the same precedence as `has_inv.inv`. notation `⅟`:1034 := invertible.inv_of @[simp] lemma inv_of_mul_self [has_mul α] [has_one α] (a : α) [invertible a] : ⅟a * a = 1 := invertible.inv_of_mul_self @[simp] lemma mul_inv_of_self [has_mul α] [has_one α] (a : α) [invertible a] : a * ⅟a = 1 := invertible.mul_inv_of_self @[simp] lemma inv_of_mul_self_assoc [monoid α] (a b : α) [invertible a] : ⅟a * (a * b) = b := by rw [←mul_assoc, inv_of_mul_self, one_mul] @[simp] lemma mul_inv_of_self_assoc [monoid α] (a b : α) [invertible a] : a * (⅟a * b) = b := by rw [←mul_assoc, mul_inv_of_self, one_mul] @[simp] lemma mul_inv_of_mul_self_cancel [monoid α] (a b : α) [invertible b] : a * ⅟b * b = a := by simp [mul_assoc] @[simp] lemma mul_mul_inv_of_self_cancel [monoid α] (a b : α) [invertible b] : a * b * ⅟b = a := by simp [mul_assoc] lemma inv_of_eq_right_inv [monoid α] {a b : α} [invertible a] (hac : a * b = 1) : ⅟a = b := left_inv_eq_right_inv (inv_of_mul_self _) hac lemma inv_of_eq_left_inv [monoid α] {a b : α} [invertible a] (hac : b * a = 1) : ⅟a = b := (left_inv_eq_right_inv hac (mul_inv_of_self _)).symm lemma invertible_unique {α : Type u} [monoid α] (a b : α) (h : a = b) [invertible a] [invertible b] : ⅟a = ⅟b := by { apply inv_of_eq_right_inv, rw [h, mul_inv_of_self], } instance [monoid α] (a : α) : subsingleton (invertible a) := ⟨ λ ⟨b, hba, hab⟩ ⟨c, hca, hac⟩, by { congr, exact left_inv_eq_right_inv hba hac } ⟩ /-- If `r` is invertible and `s = r`, then `s` is invertible. -/ def invertible.copy [monoid α] {r : α} (hr : invertible r) (s : α) (hs : s = r) : invertible s := { inv_of := ⅟r, inv_of_mul_self := by rw [hs, inv_of_mul_self], mul_inv_of_self := by rw [hs, mul_inv_of_self] } /-- An `invertible` element is a unit. -/ @[simps] def unit_of_invertible [monoid α] (a : α) [invertible a] : units α := { val := a, inv := ⅟a, val_inv := by simp, inv_val := by simp, } lemma is_unit_of_invertible [monoid α] (a : α) [invertible a] : is_unit a := ⟨unit_of_invertible a, rfl⟩ /-- Units are invertible in their associated monoid. -/ def units.invertible [monoid α] (u : units α) : invertible (u : α) := { inv_of := ↑(u⁻¹), inv_of_mul_self := u.inv_mul, mul_inv_of_self := u.mul_inv } @[simp] lemma inv_of_units [monoid α] (u : units α) [invertible (u : α)] : ⅟(u : α) = ↑(u⁻¹) := inv_of_eq_right_inv u.mul_inv lemma is_unit.nonempty_invertible [monoid α] {a : α} (h : is_unit a) : nonempty (invertible a) := let ⟨x, hx⟩ := h in ⟨x.invertible.copy _ hx.symm⟩ /-- Convert `is_unit` to `invertible` using `classical.choice`. Prefer `casesI h.nonempty_invertible` over `letI := h.invertible` if you want to avoid choice. -/ noncomputable def is_unit.invertible [monoid α] {a : α} (h : is_unit a) : invertible a := classical.choice h.nonempty_invertible @[simp] lemma nonempty_invertible_iff_is_unit [monoid α] (a : α) : nonempty (invertible a) ↔ is_unit a := ⟨nonempty.rec $ @is_unit_of_invertible _ _ _, is_unit.nonempty_invertible⟩ /-- Each element of a group is invertible. -/ def invertible_of_group [group α] (a : α) : invertible a := ⟨a⁻¹, inv_mul_self a, mul_inv_self a⟩ @[simp] lemma inv_of_eq_group_inv [group α] (a : α) [invertible a] : ⅟a = a⁻¹ := inv_of_eq_right_inv (mul_inv_self a) /-- `1` is the inverse of itself -/ def invertible_one [monoid α] : invertible (1 : α) := ⟨1, mul_one _, one_mul _⟩ @[simp] lemma inv_of_one [monoid α] [invertible (1 : α)] : ⅟(1 : α) = 1 := inv_of_eq_right_inv (mul_one _) /-- `-⅟a` is the inverse of `-a` -/ def invertible_neg [ring α] (a : α) [invertible a] : invertible (-a) := ⟨ -⅟a, by simp, by simp ⟩ @[simp] lemma inv_of_neg [ring α] (a : α) [invertible a] [invertible (-a)] : ⅟(-a) = -⅟a := inv_of_eq_right_inv (by simp) @[simp] lemma one_sub_inv_of_two [ring α] [invertible (2:α)] : 1 - (⅟2:α) = ⅟2 := (is_unit_of_invertible (2:α)).mul_right_inj.1 $ by rw [mul_sub, mul_inv_of_self, mul_one, bit0, add_sub_cancel] /-- `a` is the inverse of `⅟a`. -/ instance invertible_inv_of [has_one α] [has_mul α] {a : α} [invertible a] : invertible (⅟a) := ⟨ a, mul_inv_of_self a, inv_of_mul_self a ⟩ @[simp] lemma inv_of_inv_of [monoid α] {a : α} [invertible a] [invertible (⅟a)] : ⅟(⅟a) = a := inv_of_eq_right_inv (inv_of_mul_self _) /-- `⅟b * ⅟a` is the inverse of `a * b` -/ def invertible_mul [monoid α] (a b : α) [invertible a] [invertible b] : invertible (a * b) := ⟨ ⅟b * ⅟a, by simp [←mul_assoc], by simp [←mul_assoc] ⟩ @[simp] lemma inv_of_mul [monoid α] (a b : α) [invertible a] [invertible b] [invertible (a * b)] : ⅟(a * b) = ⅟b * ⅟a := inv_of_eq_right_inv (by simp [←mul_assoc]) theorem commute.inv_of_right [monoid α] {a b : α} [invertible b] (h : commute a b) : commute a (⅟b) := calc a * (⅟b) = (⅟b) * (b * a * (⅟b)) : by simp [mul_assoc] ... = (⅟b) * (a * b * ((⅟b))) : by rw h.eq ... = (⅟b) * a : by simp [mul_assoc] theorem commute.inv_of_left [monoid α] {a b : α} [invertible b] (h : commute b a) : commute (⅟b) a := calc (⅟b) * a = (⅟b) * (a * b * (⅟b)) : by simp [mul_assoc] ... = (⅟b) * (b * a * (⅟b)) : by rw h.eq ... = a * (⅟b) : by simp [mul_assoc] lemma commute_inv_of {M : Type*} [has_one M] [has_mul M] (m : M) [invertible m] : commute m (⅟m) := calc m * ⅟m = 1 : mul_inv_of_self m ... = ⅟ m * m : (inv_of_mul_self m).symm section monoid_with_zero variable [monoid_with_zero α] /-- A variant of `ring.inverse_unit`. -/ @[simp] lemma ring.inverse_invertible (x : α) [invertible x] : ring.inverse x = ⅟x := ring.inverse_unit (unit_of_invertible _) end monoid_with_zero section group_with_zero variable [group_with_zero α] lemma nonzero_of_invertible (a : α) [invertible a] : a ≠ 0 := λ ha, zero_ne_one $ calc 0 = ⅟a * a : by simp [ha] ... = 1 : inv_of_mul_self a /-- `a⁻¹` is an inverse of `a` if `a ≠ 0` -/ def invertible_of_nonzero {a : α} (h : a ≠ 0) : invertible a := ⟨ a⁻¹, inv_mul_cancel h, mul_inv_cancel h ⟩ @[simp] lemma inv_of_eq_inv (a : α) [invertible a] : ⅟a = a⁻¹ := inv_of_eq_right_inv (mul_inv_cancel (nonzero_of_invertible a)) @[simp] lemma inv_mul_cancel_of_invertible (a : α) [invertible a] : a⁻¹ * a = 1 := inv_mul_cancel (nonzero_of_invertible a) @[simp] lemma mul_inv_cancel_of_invertible (a : α) [invertible a] : a * a⁻¹ = 1 := mul_inv_cancel (nonzero_of_invertible a) @[simp] lemma div_mul_cancel_of_invertible (a b : α) [invertible b] : a / b * b = a := div_mul_cancel a (nonzero_of_invertible b) @[simp] lemma mul_div_cancel_of_invertible (a b : α) [invertible b] : a * b / b = a := mul_div_cancel a (nonzero_of_invertible b) @[simp] lemma div_self_of_invertible (a : α) [invertible a] : a / a = 1 := div_self (nonzero_of_invertible a) /-- `b / a` is the inverse of `a / b` -/ def invertible_div (a b : α) [invertible a] [invertible b] : invertible (a / b) := ⟨b / a, by simp [←mul_div_assoc], by simp [←mul_div_assoc]⟩ @[simp] lemma inv_of_div (a b : α) [invertible a] [invertible b] [invertible (a / b)] : ⅟(a / b) = b / a := inv_of_eq_right_inv (by simp [←mul_div_assoc]) /-- `a` is the inverse of `a⁻¹` -/ def invertible_inv {a : α} [invertible a] : invertible (a⁻¹) := ⟨ a, by simp, by simp ⟩ end group_with_zero /-- Monoid homs preserve invertibility. -/ def invertible.map {R : Type*} {S : Type*} [monoid R] [monoid S] (f : R →* S) (r : R) [invertible r] : invertible (f r) := { inv_of := f (⅟r), inv_of_mul_self := by rw [← f.map_mul, inv_of_mul_self, f.map_one], mul_inv_of_self := by rw [← f.map_mul, mul_inv_of_self, f.map_one] }
630723340b1b004ec7f2feb1fd03c01e4049715d
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/server/init_exit.lean
b421a2f68a429836f2d4ab9c9b651476db6bdcf9
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach" ]
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
634
lean
import Lean.Data.Lsp open IO Lean Lsp def main : IO Unit := do Ipc.runWith (←IO.appPath) #["--server"] do let hIn ← Ipc.stdin hIn.write (←FS.readBinFile "init_vscode_1_47_2.log") hIn.flush let initResp ← Ipc.readResponseAs 0 InitializeResult let regWatchReq ← Ipc.readRequestAs "client/registerCapability" Json Ipc.writeNotification ⟨"initialized", InitializedParams.mk⟩ Ipc.writeRequest ⟨1, "shutdown", Json.null⟩ let shutdownResp ← Ipc.readResponseAs 1 Json assert! shutdownResp.result.isNull Ipc.writeNotification ⟨"exit", Json.null⟩ discard Ipc.waitForExit
b9624e9a4041966551aa3be73fdf869cc6ee251f
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/interactive/t11.lean
f856783730001cce6a4d469df5f593f733cf6b47
[ "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
340
lean
(* auto = Repeat(OrElse(conj_hyp_tac(), conj_tac(), assumption_tac())) *) theorem T2 (A B : Bool) : A /\ B -> B /\ A := fun assumption : A /\ B, let lemma1 : A := _, lemma2 : B := _, conclusion : B /\ A := _ in conclusion. auto. done. auto. done. auto. done.
005e6afd5574ff5bd2f6bb45af05c21c57ebff26
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/hott/algebra/ordered_ring.hlean
55605590db29c684c94922b5a03a9c6bc85d8cc8
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
27,629
hlean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad Here an "ordered_ring" is partially ordered ring, which is ordered with respect to both a weak order and an associated strict order. Our numeric structures (int, rat, and real) will be instances of "linear_ordered_comm_ring". This development is modeled after Isabelle's library. -/ import algebra.ordered_group algebra.ring open eq eq.ops algebra set_option class.force_new true variable {A : Type} namespace algebra private definition absurd_a_lt_a {B : Type} {a : A} [s : strict_order A] (H : a < a) : B := absurd H (lt.irrefl a) /- semiring structures -/ structure ordered_semiring [class] (A : Type) extends semiring A, ordered_cancel_comm_monoid A := (mul_le_mul_of_nonneg_left: Πa b c, le a b → le zero c → le (mul c a) (mul c b)) (mul_le_mul_of_nonneg_right: Πa b c, le a b → le zero c → le (mul a c) (mul b c)) (mul_lt_mul_of_pos_left: Πa b c, lt a b → lt zero c → lt (mul c a) (mul c b)) (mul_lt_mul_of_pos_right: Πa b c, lt a b → lt zero c → lt (mul a c) (mul b c)) section variable [s : ordered_semiring A] variables (a b c d e : A) include s theorem mul_le_mul_of_nonneg_left {a b c : A} (Hab : a ≤ b) (Hc : 0 ≤ c) : c * a ≤ c * b := !ordered_semiring.mul_le_mul_of_nonneg_left Hab Hc theorem mul_le_mul_of_nonneg_right {a b c : A} (Hab : a ≤ b) (Hc : 0 ≤ c) : a * c ≤ b * c := !ordered_semiring.mul_le_mul_of_nonneg_right Hab Hc -- TODO: there are four variations, depending on which variables we assume to be nonneg theorem mul_le_mul {a b c d : A} (Hac : a ≤ c) (Hbd : b ≤ d) (nn_b : 0 ≤ b) (nn_c : 0 ≤ c) : a * b ≤ c * d := calc a * b ≤ c * b : mul_le_mul_of_nonneg_right Hac nn_b ... ≤ c * d : mul_le_mul_of_nonneg_left Hbd nn_c theorem mul_nonneg {a b : A} (Ha : a ≥ 0) (Hb : b ≥ 0) : a * b ≥ 0 := begin have H : 0 * b ≤ a * b, from mul_le_mul_of_nonneg_right Ha Hb, rewrite zero_mul at H, exact H end theorem mul_nonpos_of_nonneg_of_nonpos {a b : A} (Ha : a ≥ 0) (Hb : b ≤ 0) : a * b ≤ 0 := begin have H : a * b ≤ a * 0, from mul_le_mul_of_nonneg_left Hb Ha, rewrite mul_zero at H, exact H end theorem mul_nonpos_of_nonpos_of_nonneg {a b : A} (Ha : a ≤ 0) (Hb : b ≥ 0) : a * b ≤ 0 := begin have H : a * b ≤ 0 * b, from mul_le_mul_of_nonneg_right Ha Hb, rewrite zero_mul at H, exact H end theorem mul_lt_mul_of_pos_left {a b c : A} (Hab : a < b) (Hc : 0 < c) : c * a < c * b := !ordered_semiring.mul_lt_mul_of_pos_left Hab Hc theorem mul_lt_mul_of_pos_right {a b c : A} (Hab : a < b) (Hc : 0 < c) : a * c < b * c := !ordered_semiring.mul_lt_mul_of_pos_right Hab Hc -- TODO: once again, there are variations theorem mul_lt_mul {a b c d : A} (Hac : a < c) (Hbd : b ≤ d) (pos_b : 0 < b) (nn_c : 0 ≤ c) : a * b < c * d := calc a * b < c * b : mul_lt_mul_of_pos_right Hac pos_b ... ≤ c * d : mul_le_mul_of_nonneg_left Hbd nn_c theorem mul_pos {a b : A} (Ha : a > 0) (Hb : b > 0) : a * b > 0 := begin have H : 0 * b < a * b, from mul_lt_mul_of_pos_right Ha Hb, rewrite zero_mul at H, exact H end theorem mul_neg_of_pos_of_neg {a b : A} (Ha : a > 0) (Hb : b < 0) : a * b < 0 := begin have H : a * b < a * 0, from mul_lt_mul_of_pos_left Hb Ha, rewrite mul_zero at H, exact H end theorem mul_neg_of_neg_of_pos {a b : A} (Ha : a < 0) (Hb : b > 0) : a * b < 0 := begin have H : a * b < 0 * b, from mul_lt_mul_of_pos_right Ha Hb, rewrite zero_mul at H, exact H end end structure linear_ordered_semiring [class] (A : Type) extends ordered_semiring A, linear_strong_order_pair A := (zero_lt_one : lt zero one) section variable [s : linear_ordered_semiring A] variables {a b c : A} include s theorem zero_lt_one : 0 < (1:A) := linear_ordered_semiring.zero_lt_one A theorem lt_of_mul_lt_mul_left (H : c * a < c * b) (Hc : c ≥ 0) : a < b := lt_of_not_ge (assume H1 : b ≤ a, have H2 : c * b ≤ c * a, from mul_le_mul_of_nonneg_left H1 Hc, not_lt_of_ge H2 H) theorem lt_of_mul_lt_mul_right (H : a * c < b * c) (Hc : c ≥ 0) : a < b := lt_of_not_ge (assume H1 : b ≤ a, have H2 : b * c ≤ a * c, from mul_le_mul_of_nonneg_right H1 Hc, not_lt_of_ge H2 H) theorem le_of_mul_le_mul_left (H : c * a ≤ c * b) (Hc : c > 0) : a ≤ b := le_of_not_gt (assume H1 : b < a, have H2 : c * b < c * a, from mul_lt_mul_of_pos_left H1 Hc, not_le_of_gt H2 H) theorem le_of_mul_le_mul_right (H : a * c ≤ b * c) (Hc : c > 0) : a ≤ b := le_of_not_gt (assume H1 : b < a, have H2 : b * c < a * c, from mul_lt_mul_of_pos_right H1 Hc, not_le_of_gt H2 H) theorem le_iff_mul_le_mul_left (a b : A) {c : A} (H : c > 0) : a ≤ b ↔ c * a ≤ c * b := iff.intro (assume H', mul_le_mul_of_nonneg_left H' (le_of_lt H)) (assume H', le_of_mul_le_mul_left H' H) theorem le_iff_mul_le_mul_right (a b : A) {c : A} (H : c > 0) : a ≤ b ↔ a * c ≤ b * c := iff.intro (assume H', mul_le_mul_of_nonneg_right H' (le_of_lt H)) (assume H', le_of_mul_le_mul_right H' H) theorem pos_of_mul_pos_left (H : 0 < a * b) (H1 : 0 ≤ a) : 0 < b := lt_of_not_ge (assume H2 : b ≤ 0, have H3 : a * b ≤ 0, from mul_nonpos_of_nonneg_of_nonpos H1 H2, not_lt_of_ge H3 H) theorem pos_of_mul_pos_right (H : 0 < a * b) (H1 : 0 ≤ b) : 0 < a := lt_of_not_ge (assume H2 : a ≤ 0, have H3 : a * b ≤ 0, from mul_nonpos_of_nonpos_of_nonneg H2 H1, not_lt_of_ge H3 H) theorem nonneg_of_mul_nonneg_left (H : 0 ≤ a * b) (H1 : 0 < a) : 0 ≤ b := le_of_not_gt (assume H2 : b < 0, not_le_of_gt (mul_neg_of_pos_of_neg H1 H2) H) theorem nonneg_of_mul_nonneg_right (H : 0 ≤ a * b) (H1 : 0 < b) : 0 ≤ a := le_of_not_gt (assume H2 : a < 0, not_le_of_gt (mul_neg_of_neg_of_pos H2 H1) H) theorem neg_of_mul_neg_left (H : a * b < 0) (H1 : 0 ≤ a) : b < 0 := lt_of_not_ge (assume H2 : b ≥ 0, not_lt_of_ge (mul_nonneg H1 H2) H) theorem neg_of_mul_neg_right (H : a * b < 0) (H1 : 0 ≤ b) : a < 0 := lt_of_not_ge (assume H2 : a ≥ 0, not_lt_of_ge (mul_nonneg H2 H1) H) theorem nonpos_of_mul_nonpos_left (H : a * b ≤ 0) (H1 : 0 < a) : b ≤ 0 := le_of_not_gt (assume H2 : b > 0, not_le_of_gt (mul_pos H1 H2) H) theorem nonpos_of_mul_nonpos_right (H : a * b ≤ 0) (H1 : 0 < b) : a ≤ 0 := le_of_not_gt (assume H2 : a > 0, not_le_of_gt (mul_pos H2 H1) H) end structure decidable_linear_ordered_semiring [class] (A : Type) extends linear_ordered_semiring A, decidable_linear_order A /- ring structures -/ structure ordered_ring [class] (A : Type) extends ring A, ordered_comm_group A, zero_ne_one_class A := (mul_nonneg : Πa b, le zero a → le zero b → le zero (mul a b)) (mul_pos : Πa b, lt zero a → lt zero b → lt zero (mul a b)) theorem ordered_ring.mul_le_mul_of_nonneg_left [s : ordered_ring A] {a b c : A} (Hab : a ≤ b) (Hc : 0 ≤ c) : c * a ≤ c * b := have H1 : 0 ≤ b - a, from iff.elim_right !sub_nonneg_iff_le Hab, assert H2 : 0 ≤ c * (b - a), from ordered_ring.mul_nonneg _ _ Hc H1, begin rewrite mul_sub_left_distrib at H2, exact (iff.mp !sub_nonneg_iff_le H2) end theorem ordered_ring.mul_le_mul_of_nonneg_right [s : ordered_ring A] {a b c : A} (Hab : a ≤ b) (Hc : 0 ≤ c) : a * c ≤ b * c := have H1 : 0 ≤ b - a, from iff.elim_right !sub_nonneg_iff_le Hab, assert H2 : 0 ≤ (b - a) * c, from ordered_ring.mul_nonneg _ _ H1 Hc, begin rewrite mul_sub_right_distrib at H2, exact (iff.mp !sub_nonneg_iff_le H2) end theorem ordered_ring.mul_lt_mul_of_pos_left [s : ordered_ring A] {a b c : A} (Hab : a < b) (Hc : 0 < c) : c * a < c * b := have H1 : 0 < b - a, from iff.elim_right !sub_pos_iff_lt Hab, assert H2 : 0 < c * (b - a), from ordered_ring.mul_pos _ _ Hc H1, begin rewrite mul_sub_left_distrib at H2, exact (iff.mp !sub_pos_iff_lt H2) end theorem ordered_ring.mul_lt_mul_of_pos_right [s : ordered_ring A] {a b c : A} (Hab : a < b) (Hc : 0 < c) : a * c < b * c := have H1 : 0 < b - a, from iff.elim_right !sub_pos_iff_lt Hab, assert H2 : 0 < (b - a) * c, from ordered_ring.mul_pos _ _ H1 Hc, begin rewrite mul_sub_right_distrib at H2, exact (iff.mp !sub_pos_iff_lt H2) end definition ordered_ring.to_ordered_semiring [trans_instance] [reducible] [s : ordered_ring A] : ordered_semiring A := ⦃ ordered_semiring, s, mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add.left_cancel A _, add_right_cancel := @add.right_cancel A _, le_of_add_le_add_left := @le_of_add_le_add_left A _, mul_le_mul_of_nonneg_left := @ordered_ring.mul_le_mul_of_nonneg_left A _, mul_le_mul_of_nonneg_right := @ordered_ring.mul_le_mul_of_nonneg_right A _, mul_lt_mul_of_pos_left := @ordered_ring.mul_lt_mul_of_pos_left A _, mul_lt_mul_of_pos_right := @ordered_ring.mul_lt_mul_of_pos_right A _, lt_of_add_lt_add_left := @lt_of_add_lt_add_left A _⦄ section variable [s : ordered_ring A] variables {a b c : A} include s theorem mul_le_mul_of_nonpos_left (H : b ≤ a) (Hc : c ≤ 0) : c * a ≤ c * b := have Hc' : -c ≥ 0, from iff.mpr !neg_nonneg_iff_nonpos Hc, assert H1 : -c * b ≤ -c * a, from mul_le_mul_of_nonneg_left H Hc', have H2 : -(c * b) ≤ -(c * a), begin rewrite [-*neg_mul_eq_neg_mul at H1], exact H1 end, iff.mp !neg_le_neg_iff_le H2 theorem mul_le_mul_of_nonpos_right (H : b ≤ a) (Hc : c ≤ 0) : a * c ≤ b * c := have Hc' : -c ≥ 0, from iff.mpr !neg_nonneg_iff_nonpos Hc, assert H1 : b * -c ≤ a * -c, from mul_le_mul_of_nonneg_right H Hc', have H2 : -(b * c) ≤ -(a * c), begin rewrite [-*neg_mul_eq_mul_neg at H1], exact H1 end, iff.mp !neg_le_neg_iff_le H2 theorem mul_nonneg_of_nonpos_of_nonpos (Ha : a ≤ 0) (Hb : b ≤ 0) : 0 ≤ a * b := begin have H : 0 * b ≤ a * b, from mul_le_mul_of_nonpos_right Ha Hb, rewrite zero_mul at H, exact H end theorem mul_lt_mul_of_neg_left (H : b < a) (Hc : c < 0) : c * a < c * b := have Hc' : -c > 0, from iff.mpr !neg_pos_iff_neg Hc, assert H1 : -c * b < -c * a, from mul_lt_mul_of_pos_left H Hc', have H2 : -(c * b) < -(c * a), begin rewrite [-*neg_mul_eq_neg_mul at H1], exact H1 end, iff.mp !neg_lt_neg_iff_lt H2 theorem mul_lt_mul_of_neg_right (H : b < a) (Hc : c < 0) : a * c < b * c := have Hc' : -c > 0, from iff.mpr !neg_pos_iff_neg Hc, assert H1 : b * -c < a * -c, from mul_lt_mul_of_pos_right H Hc', have H2 : -(b * c) < -(a * c), begin rewrite [-*neg_mul_eq_mul_neg at H1], exact H1 end, iff.mp !neg_lt_neg_iff_lt H2 theorem mul_pos_of_neg_of_neg (Ha : a < 0) (Hb : b < 0) : 0 < a * b := begin have H : 0 * b < a * b, from mul_lt_mul_of_neg_right Ha Hb, rewrite zero_mul at H, exact H end end -- TODO: we can eliminate mul_pos_of_pos, but now it is not worth the effort to redeclare the -- class instance structure linear_ordered_ring [class] (A : Type) extends ordered_ring A, linear_strong_order_pair A := (zero_lt_one : lt zero one) definition linear_ordered_ring.to_linear_ordered_semiring [trans_instance] [reducible] [s : linear_ordered_ring A] : linear_ordered_semiring A := ⦃ linear_ordered_semiring, s, mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add.left_cancel A _, add_right_cancel := @add.right_cancel A _, le_of_add_le_add_left := @le_of_add_le_add_left A _, mul_le_mul_of_nonneg_left := @mul_le_mul_of_nonneg_left A _, mul_le_mul_of_nonneg_right := @mul_le_mul_of_nonneg_right A _, mul_lt_mul_of_pos_left := @mul_lt_mul_of_pos_left A _, mul_lt_mul_of_pos_right := @mul_lt_mul_of_pos_right A _, le_total := linear_ordered_ring.le_total, lt_of_add_lt_add_left := @lt_of_add_lt_add_left A _ ⦄ structure linear_ordered_comm_ring [class] (A : Type) extends linear_ordered_ring A, comm_monoid A theorem linear_ordered_comm_ring.eq_zero_sum_eq_zero_of_mul_eq_zero [s : linear_ordered_comm_ring A] {a b : A} (H : a * b = 0) : a = 0 ⊎ b = 0 := lt.by_cases (assume Ha : 0 < a, lt.by_cases (assume Hb : 0 < b, begin have H1 : 0 < a * b, from mul_pos Ha Hb, rewrite H at H1, apply absurd_a_lt_a H1 end) (assume Hb : 0 = b, sum.inr (Hb⁻¹)) (assume Hb : 0 > b, begin have H1 : 0 > a * b, from mul_neg_of_pos_of_neg Ha Hb, rewrite H at H1, apply absurd_a_lt_a H1 end)) (assume Ha : 0 = a, sum.inl (Ha⁻¹)) (assume Ha : 0 > a, lt.by_cases (assume Hb : 0 < b, begin have H1 : 0 > a * b, from mul_neg_of_neg_of_pos Ha Hb, rewrite H at H1, apply absurd_a_lt_a H1 end) (assume Hb : 0 = b, sum.inr (Hb⁻¹)) (assume Hb : 0 > b, begin have H1 : 0 < a * b, from mul_pos_of_neg_of_neg Ha Hb, rewrite H at H1, apply absurd_a_lt_a H1 end)) -- Linearity implies no zero divisors. Doesn't need commutativity. definition linear_ordered_comm_ring.to_integral_domain [trans_instance] [reducible] [s: linear_ordered_comm_ring A] : integral_domain A := ⦃ integral_domain, s, eq_zero_sum_eq_zero_of_mul_eq_zero := @linear_ordered_comm_ring.eq_zero_sum_eq_zero_of_mul_eq_zero A s ⦄ section variable [s : linear_ordered_ring A] variables (a b c : A) include s theorem mul_self_nonneg : a * a ≥ 0 := sum.elim (le.total 0 a) (assume H : a ≥ 0, mul_nonneg H H) (assume H : a ≤ 0, mul_nonneg_of_nonpos_of_nonpos H H) theorem zero_le_one : 0 ≤ (1:A) := one_mul 1 ▸ mul_self_nonneg 1 theorem pos_prod_pos_sum_neg_prod_neg_of_mul_pos {a b : A} (Hab : a * b > 0) : (a > 0 × b > 0) ⊎ (a < 0 × b < 0) := lt.by_cases (assume Ha : 0 < a, lt.by_cases (assume Hb : 0 < b, sum.inl (pair Ha Hb)) (assume Hb : 0 = b, begin rewrite [-Hb at Hab, mul_zero at Hab], apply absurd_a_lt_a Hab end) (assume Hb : b < 0, absurd Hab (lt.asymm (mul_neg_of_pos_of_neg Ha Hb)))) (assume Ha : 0 = a, begin rewrite [-Ha at Hab, zero_mul at Hab], apply absurd_a_lt_a Hab end) (assume Ha : a < 0, lt.by_cases (assume Hb : 0 < b, absurd Hab (lt.asymm (mul_neg_of_neg_of_pos Ha Hb))) (assume Hb : 0 = b, begin rewrite [-Hb at Hab, mul_zero at Hab], apply absurd_a_lt_a Hab end) (assume Hb : b < 0, sum.inr (pair Ha Hb))) theorem gt_of_mul_lt_mul_neg_left {a b c : A} (H : c * a < c * b) (Hc : c ≤ 0) : a > b := have nhc : -c ≥ 0, from neg_nonneg_of_nonpos Hc, have H2 : -(c * b) < -(c * a), from iff.mpr (neg_lt_neg_iff_lt _ _) H, have H3 : (-c) * b < (-c) * a, from calc (-c) * b = - (c * b) : neg_mul_eq_neg_mul ... < -(c * a) : H2 ... = (-c) * a : neg_mul_eq_neg_mul, lt_of_mul_lt_mul_left H3 nhc theorem zero_gt_neg_one : -1 < (0:A) := neg_zero ▸ (neg_lt_neg zero_lt_one) theorem le_of_mul_le_of_ge_one {a b c : A} (H : a * c ≤ b) (Hb : b ≥ 0) (Hc : c ≥ 1) : a ≤ b := have H' : a * c ≤ b * c, from calc a * c ≤ b : H ... = b * 1 : mul_one ... ≤ b * c : mul_le_mul_of_nonneg_left Hc Hb, le_of_mul_le_mul_right H' (lt_of_lt_of_le zero_lt_one Hc) theorem nonneg_le_nonneg_of_squares_le {a b : A} (Ha : a ≥ 0) (Hb : b ≥ 0) (H : a * a ≤ b * b) : a ≤ b := begin apply le_of_not_gt, intro Hab, let Hposa := lt_of_le_of_lt Hb Hab, let H' := calc b * b ≤ a * b : mul_le_mul_of_nonneg_right (le_of_lt Hab) Hb ... < a * a : mul_lt_mul_of_pos_left Hab Hposa, apply (not_le_of_gt H') H end end /- TODO: Isabelle's library has all kinds of cancelation rules for the simplifier. Search on mult_le_cancel_right1 in Rings.thy. -/ structure decidable_linear_ordered_comm_ring [class] (A : Type) extends linear_ordered_comm_ring A, decidable_linear_ordered_comm_group A section variable [s : decidable_linear_ordered_comm_ring A] variables {a b c : A} include s definition sign (a : A) : A := lt.cases a 0 (-1) 0 1 theorem sign_of_neg (H : a < 0) : sign a = -1 := lt.cases_of_lt H theorem sign_zero : sign 0 = (0:A) := lt.cases_of_eq rfl theorem sign_of_pos (H : a > 0) : sign a = 1 := lt.cases_of_gt H theorem sign_one : sign 1 = (1:A) := sign_of_pos zero_lt_one theorem sign_neg_one : sign (-1) = -(1:A) := sign_of_neg (neg_neg_of_pos zero_lt_one) theorem sign_sign (a : A) : sign (sign a) = sign a := lt.by_cases (assume H : a > 0, calc sign (sign a) = sign 1 : by rewrite (sign_of_pos H) ... = 1 : by rewrite sign_one ... = sign a : by rewrite (sign_of_pos H)) (assume H : 0 = a, calc sign (sign a) = sign (sign 0) : by rewrite H ... = sign 0 : by rewrite sign_zero at {1} ... = sign a : by rewrite -H) (assume H : a < 0, calc sign (sign a) = sign (-1) : by rewrite (sign_of_neg H) ... = -1 : by rewrite sign_neg_one ... = sign a : by rewrite (sign_of_neg H)) theorem pos_of_sign_eq_one (H : sign a = 1) : a > 0 := lt.by_cases (assume H1 : 0 < a, H1) (assume H1 : 0 = a, begin rewrite [-H1 at H, sign_zero at H], apply absurd H zero_ne_one end) (assume H1 : 0 > a, have H2 : -1 = 1, from (sign_of_neg H1)⁻¹ ⬝ H, absurd ((eq_zero_of_neg_eq H2)⁻¹) zero_ne_one) theorem eq_zero_of_sign_eq_zero (H : sign a = 0) : a = 0 := lt.by_cases (assume H1 : 0 < a, absurd (H⁻¹ ⬝ sign_of_pos H1) zero_ne_one) (assume H1 : 0 = a, H1⁻¹) (assume H1 : 0 > a, have H2 : 0 = -1, from H⁻¹ ⬝ sign_of_neg H1, have H3 : 1 = 0, from eq_neg_of_eq_neg H2 ⬝ neg_zero, absurd (H3⁻¹) zero_ne_one) theorem neg_of_sign_eq_neg_one (H : sign a = -1) : a < 0 := lt.by_cases (assume H1 : 0 < a, have H2 : -1 = 1, from H⁻¹ ⬝ (sign_of_pos H1), absurd ((eq_zero_of_neg_eq H2)⁻¹) zero_ne_one) (assume H1 : 0 = a, have H2 : (0:A) = -1, begin rewrite [-H1 at H, sign_zero at H], exact H end, have H3 : 1 = 0, from eq_neg_of_eq_neg H2 ⬝ neg_zero, absurd (H3⁻¹) zero_ne_one) (assume H1 : 0 > a, H1) theorem sign_neg (a : A) : sign (-a) = -(sign a) := lt.by_cases (assume H1 : 0 < a, calc sign (-a) = -1 : sign_of_neg (neg_neg_of_pos H1) ... = -(sign a) : by rewrite (sign_of_pos H1)) (assume H1 : 0 = a, calc sign (-a) = sign (-0) : by rewrite H1 ... = sign 0 : by rewrite neg_zero ... = 0 : by rewrite sign_zero ... = -0 : by rewrite neg_zero ... = -(sign 0) : by rewrite sign_zero ... = -(sign a) : by rewrite -H1) (assume H1 : 0 > a, calc sign (-a) = 1 : sign_of_pos (neg_pos_of_neg H1) ... = -(-1) : by rewrite neg_neg ... = -(sign a) : sign_of_neg H1) theorem sign_mul (a b : A) : sign (a * b) = sign a * sign b := lt.by_cases (assume z_lt_a : 0 < a, lt.by_cases (assume z_lt_b : 0 < b, by rewrite [sign_of_pos z_lt_a, sign_of_pos z_lt_b, sign_of_pos (mul_pos z_lt_a z_lt_b), one_mul]) (assume z_eq_b : 0 = b, by rewrite [-z_eq_b, mul_zero, *sign_zero, mul_zero]) (assume z_gt_b : 0 > b, by rewrite [sign_of_pos z_lt_a, sign_of_neg z_gt_b, sign_of_neg (mul_neg_of_pos_of_neg z_lt_a z_gt_b), one_mul])) (assume z_eq_a : 0 = a, by rewrite [-z_eq_a, zero_mul, *sign_zero, zero_mul]) (assume z_gt_a : 0 > a, lt.by_cases (assume z_lt_b : 0 < b, by rewrite [sign_of_neg z_gt_a, sign_of_pos z_lt_b, sign_of_neg (mul_neg_of_neg_of_pos z_gt_a z_lt_b), mul_one]) (assume z_eq_b : 0 = b, by rewrite [-z_eq_b, mul_zero, *sign_zero, mul_zero]) (assume z_gt_b : 0 > b, by rewrite [sign_of_neg z_gt_a, sign_of_neg z_gt_b, sign_of_pos (mul_pos_of_neg_of_neg z_gt_a z_gt_b), neg_mul_neg, one_mul])) theorem abs_eq_sign_mul (a : A) : abs a = sign a * a := lt.by_cases (assume H1 : 0 < a, calc abs a = a : abs_of_pos H1 ... = 1 * a : by rewrite one_mul ... = sign a * a : by rewrite (sign_of_pos H1)) (assume H1 : 0 = a, calc abs a = abs 0 : by rewrite H1 ... = 0 : by rewrite abs_zero ... = 0 * a : by rewrite zero_mul ... = sign 0 * a : by rewrite sign_zero ... = sign a * a : by rewrite H1) (assume H1 : a < 0, calc abs a = -a : abs_of_neg H1 ... = -1 * a : by rewrite neg_eq_neg_one_mul ... = sign a * a : by rewrite (sign_of_neg H1)) theorem eq_sign_mul_abs (a : A) : a = sign a * abs a := lt.by_cases (assume H1 : 0 < a, calc a = abs a : abs_of_pos H1 ... = 1 * abs a : by rewrite one_mul ... = sign a * abs a : by rewrite (sign_of_pos H1)) (assume H1 : 0 = a, calc a = 0 : H1⁻¹ ... = 0 * abs a : by rewrite zero_mul ... = sign 0 * abs a : by rewrite sign_zero ... = sign a * abs a : by rewrite H1) (assume H1 : a < 0, calc a = -(-a) : by rewrite neg_neg ... = -abs a : by rewrite (abs_of_neg H1) ... = -1 * abs a : by rewrite neg_eq_neg_one_mul ... = sign a * abs a : by rewrite (sign_of_neg H1)) theorem abs_dvd_iff (a b : A) : abs a ∣ b ↔ a ∣ b := abs.by_cases !iff.refl !neg_dvd_iff_dvd theorem abs_dvd_of_dvd {a b : A} : a ∣ b → abs a ∣ b := iff.mpr !abs_dvd_iff theorem dvd_abs_iff (a b : A) : a ∣ abs b ↔ a ∣ b := abs.by_cases !iff.refl !dvd_neg_iff_dvd theorem dvd_abs_of_dvd {a b : A} : a ∣ b → a ∣ abs b := iff.mpr !dvd_abs_iff theorem abs_mul (a b : A) : abs (a * b) = abs a * abs b := sum.elim (le.total 0 a) (assume H1 : 0 ≤ a, sum.elim (le.total 0 b) (assume H2 : 0 ≤ b, calc abs (a * b) = a * b : abs_of_nonneg (mul_nonneg H1 H2) ... = abs a * b : by rewrite (abs_of_nonneg H1) ... = abs a * abs b : by rewrite (abs_of_nonneg H2)) (assume H2 : b ≤ 0, calc abs (a * b) = -(a * b) : abs_of_nonpos (mul_nonpos_of_nonneg_of_nonpos H1 H2) ... = a * -b : by rewrite neg_mul_eq_mul_neg ... = abs a * -b : by rewrite (abs_of_nonneg H1) ... = abs a * abs b : by rewrite (abs_of_nonpos H2))) (assume H1 : a ≤ 0, sum.elim (le.total 0 b) (assume H2 : 0 ≤ b, calc abs (a * b) = -(a * b) : abs_of_nonpos (mul_nonpos_of_nonpos_of_nonneg H1 H2) ... = -a * b : by rewrite neg_mul_eq_neg_mul ... = abs a * b : by rewrite (abs_of_nonpos H1) ... = abs a * abs b : by rewrite (abs_of_nonneg H2)) (assume H2 : b ≤ 0, calc abs (a * b) = a * b : abs_of_nonneg (mul_nonneg_of_nonpos_of_nonpos H1 H2) ... = -a * -b : by rewrite neg_mul_neg ... = abs a * -b : by rewrite (abs_of_nonpos H1) ... = abs a * abs b : by rewrite (abs_of_nonpos H2))) theorem abs_mul_abs_self (a : A) : abs a * abs a = a * a := abs.by_cases rfl !neg_mul_neg theorem abs_mul_self (a : A) : abs (a * a) = a * a := by rewrite [abs_mul, abs_mul_abs_self] theorem sub_le_of_abs_sub_le_left (H : abs (a - b) ≤ c) : b - c ≤ a := if Hz : 0 ≤ a - b then (calc a ≥ b : (iff.mp !sub_nonneg_iff_le) Hz ... ≥ b - c : sub_le_of_nonneg _ (le.trans !abs_nonneg H)) else (have Habs : b - a ≤ c, by rewrite [abs_of_neg (lt_of_not_ge Hz) at H, neg_sub at H]; apply H, have Habs' : b ≤ c + a, from (iff.mpr !le_add_iff_sub_right_le) Habs, (iff.mp !le_add_iff_sub_left_le) Habs') theorem sub_le_of_abs_sub_le_right (H : abs (a - b) ≤ c) : a - c ≤ b := sub_le_of_abs_sub_le_left (!abs_sub ▸ H) theorem sub_lt_of_abs_sub_lt_left (H : abs (a - b) < c) : b - c < a := if Hz : 0 ≤ a - b then (calc a ≥ b : (iff.mp !sub_nonneg_iff_le) Hz ... > b - c : sub_lt_of_pos _ (lt_of_le_of_lt !abs_nonneg H)) else (have Habs : b - a < c, by rewrite [abs_of_neg (lt_of_not_ge Hz) at H, neg_sub at H]; apply H, have Habs' : b < c + a, from lt_add_of_sub_lt_right Habs, sub_lt_left_of_lt_add Habs') theorem sub_lt_of_abs_sub_lt_right (H : abs (a - b) < c) : a - c < b := sub_lt_of_abs_sub_lt_left (!abs_sub ▸ H) theorem abs_sub_square (a b : A) : abs (a - b) * abs (a - b) = a * a + b * b - (1 + 1) * a * b := begin rewrite [abs_mul_abs_self, *mul_sub_left_distrib, *mul_sub_right_distrib, sub_eq_add_neg (a*b), sub_add_eq_sub_sub, sub_neg_eq_add, *right_distrib, sub_add_eq_sub_sub, *one_mul, *add.assoc, {_ + b * b}add.comm, *sub_eq_add_neg], rewrite [{a*a + b*b}add.comm], rewrite [mul.comm b a, *add.assoc] end theorem abs_abs_sub_abs_le_abs_sub (a b : A) : abs (abs a - abs b) ≤ abs (a - b) := begin apply nonneg_le_nonneg_of_squares_le, repeat apply abs_nonneg, rewrite [*abs_sub_square, *abs_abs, *abs_mul_abs_self], apply sub_le_sub_left, rewrite *mul.assoc, apply mul_le_mul_of_nonneg_left, rewrite -abs_mul, apply le_abs_self, apply le_of_lt, apply add_pos, apply zero_lt_one, apply zero_lt_one end end /- TODO: Multiplication and one, starting with mult_right_le_one_le. -/ namespace norm_num theorem pos_bit0_helper [s : linear_ordered_semiring A] (a : A) (H : a > 0) : bit0 a > 0 := by rewrite ↑bit0; apply add_pos H H theorem nonneg_bit0_helper [s : linear_ordered_semiring A] (a : A) (H : a ≥ 0) : bit0 a ≥ 0 := by rewrite ↑bit0; apply add_nonneg H H theorem pos_bit1_helper [s : linear_ordered_semiring A] (a : A) (H : a ≥ 0) : bit1 a > 0 := begin rewrite ↑bit1, apply add_pos_of_nonneg_of_pos, apply nonneg_bit0_helper _ H, apply zero_lt_one end theorem nonneg_bit1_helper [s : linear_ordered_semiring A] (a : A) (H : a ≥ 0) : bit1 a ≥ 0 := by apply le_of_lt; apply pos_bit1_helper _ H theorem nonzero_of_pos_helper [s : linear_ordered_semiring A] (a : A) (H : a > 0) : a ≠ 0 := ne_of_gt H theorem nonzero_of_neg_helper [s : linear_ordered_ring A] (a : A) (H : a ≠ 0) : -a ≠ 0 := begin intro Ha, apply H, apply eq_of_neg_eq_neg, rewrite neg_zero, exact Ha end end norm_num end algebra
91cce4cf22b1bb45965329928a71ae14975b04f8
4a894698f2ae3f991490c25af3c13ea4435dac48
/src/instructor/lectures/lecture_1a.lean
e87d1c267b24f0306de567b06f5973658e349c84
[]
no_license
gnujey/cs2120f21
8a33f636346d59ade049dcc1726634f434ac1955
138d43446c443c1d15cd2f17fb607c4f0dff702f
refs/heads/main
1,690,598,880,775
1,631,132,566,000
1,631,132,566,000
405,182,739
1
0
null
1,631,299,824,000
1,631,299,823,000
null
UTF-8
Lean
false
false
10,048
lean
-- import definitions of real and rational numbers from mathlib import data.real.basic namespace cs2120 /- The first part of this lesson is in the file, lecture_1.md. Please start there then return here when you're done with that document. -/ /- NUMBER SYSTEMS -/ /- Mathematicians think about operations on many kinds of objects. In early mathematics, the objects are numbers. In later maths, they can be polynomials, matrices, functions, symmetries, or any manner of other "mathematical thingies". As we're going to see here, they can even be propositions and proofs. ℕ: Natural numbers. The non-negative whole numbers. {0, 1, 2, ...} ℤ: Integers: The negative and non-negative whole numbers. ℚ: Rationals: Ratios of an integer and a non-zero natural number. ℝ: Reals: Equivalence classes of convergent sequence of rationals. Irrational numbers: Real numbers not "isomorphic" to any rationals. But let's start with something really simple. The number, 1. Ok, it's actually not that simple, because 1 can be interpreted as denoting a natural number, integer, real number, rational number, identity matrix, identity function, identity element of a group, or any manner (again) of "mathematical thingy". If Lean sees a bare numeral, 1, it interprets it as the natural number, 1. It is possible to force many other interpretations however, as the following examples show. As you read the code, remember the following. Examples: Natural numbers: 0, 3, 11, 29 Integers: -29, 0, 3, 11 Rationals: 1/2, -3/4, 23/7 Reals: 0.000..., .333..., 3.1415... Irrationals: 3.1415..., e, sqrt 2 -/ def m := 1 -- 1 inferred to be a natural number (built into Lean) def n : ℕ := 1 -- 1 specified to be a natural number (non-negative whole number) def z : ℤ := 1 -- 1 as an integer (negative or non-negative whole number) def r : ℝ := 1.0 -- 1 as a real number (infinite decimal sequence) def q : ℚ := 1/1 -- 1 as a rational number (fraction) /- Each proceeding line of code has the following elements - def: a keyword, binds the given identifer to the given value - n, m, z, r, q: identifiers, a.k.a., variables or variable names - : T, where T is ℕ, ℤ, ℝ, or ℚ: specifies the *type* of the value - := 1.0: specifies the value, 1.0, to be bound to the identifier -/ /- The same definitions could be written as follows, allowing Lean to fill in type information that it can infer from the way in which the values are given. -/ def m' := 1 -- Lean assumes 1 is a natural number (built into Lean) def n' := (1 : ℕ) -- 1 as a natural number (non-negative whole number) def z' := (1 : ℤ) -- 1 as an integer (negative or non-negative whole number) def r' := (1.0 : ℝ) -- 1 as a real number (infinite decimal sequence) def q' := 1/1 -- Here Lean infers 1/1 is rational number (fraction) /- AXIOMS, PROPOSITIONS, PROOFS -/ /- Let's again talk about propositions and proofs involving "equality" propositions, such as the proposition that 1 = 1. We all *know* intuitively that 1 = 1, but how would you prove it, given that it's not an axiom of ordinary predicate logic? Without getting into the weeds, suffice it to say that the standard Lean Prover libraries define equality pretty much as we've discussed here: with an axiom in the form of a universal generaliztion: ∀ {T : Type} (t : T), t = t. In English, this says, "if you give me *any* Type, T, and any object, t, of that type, I will return you (and therefore there must be) a proof of the proposition, t = t; and the existence of this proof, in turn, justifies the *judgment* that the proposition, 1 = 1, is *true*. Let's take another look at the axiom that let's us *deduce* the *theorem* that 1 = 1. Here it is: ∀ {T : Type} (t : T), t = t. What that means is that if I choose any type, T, say T = ℕ, and any value of that type, say t = (1 : ℕ), then I should be able to apply the axiom to the argument values, ℕ and 1, to get back a *proof* of the proposition, 1 = 1. Indeed, that's just how it works, as the follow example shows formally (in Lean). -/ example : 1 = 1 := eq.refl 1 -- Lean inferns T = ℕ from 1 /- Yay! We just constructed a formal proof: a mathematical object that certifies that 1=1. It might not be super-impressive that Lean rejects "eq.refl 2" as a suitable proof (try it, and don't fail to read the entire error message when you hover your cursor over the red squiggle!); but the principle extends to commplex proofs of profound propositions. Nice: you've not only constructed a formal proof object but you have a "high assurance" check that the proof itself is correct, in that Lean actually accepts that it's correct. *That* is what Lean is really for: not just for formalizing mathematics and logic, but for checking that proofs *truly* prove what they claim to prove. -/ /- Of course, if formal proofs came without costs, we'd all be using them. The benefit of a *natural language* "proof description" (written in, say, English, but in a highly mathematical style) is that it's easier for people to follow, often because details can be elided on the assumption that the reader will know from context what is meant. In this case at hand, you could give a proof, of the proposition, 1 = 1, as follows: Proof: By the reflexive property of equality (applied to the particular value, 1). QED." If you and your audience both understand that you're *applying* the universal generalization given as an axiom to suitable values, then you can just leave out the parenthetical expression. How much detail to put in a proof description is a matter of style and of a willingness to make your readers fill in the missing details. The QED, by the way, is short for quod est demonstratum, Latin for "it is shown." It is a kind of traditional punctuation for natural language proof descriptions that signals that the proof is complete. The downside of using natural language proof descriptions in lieu of formal proof objects is that when things get complex, it can be nearly impossible to tell whether a proof in natural language is correct or not. In hard cases, it can require years of work by world experts to decide whether a proof is correct or faulty. In this class, we will insist, because all mathematicians do, that your propositions be fully formal, i.e., syntactically correct by the grammatical rules of predicate logic, as enforced by Lean. We will expose you to formal proofs to the extent that we believe that doing so will help you to understand how to write quasi-formal proof descriptions. Quasi-formal proofs are what most people use today, including instructors for follow-on CS courses. But there are now thriving communities in both mathematics and computer science that are aggressively pursuing the formalization, and the *computerization* of logic and proof. The community around Lean is most interested in formalizing mathematics for mathematicians. Other critically important applications of Lean and similar "proof assistants" arise in relation to the definition of programming languages, and in the formal (mathematical) specification and trustworthy and automated correctness checking of computer programs. -/ /- If you're getting the feeling that we are pointing you a little bit to a computational understand of what it means to construct or to use proofs, you're right. To make the point clearer, let's write our own proof-returning function@ We'll call it gimme_a_proof. It will take two arguments, a type, T, and a value, t, of that type; and it will return a proof of t = t, on the basis of which we can render the judgment that t = t is *true*. -/ def gimme_a_proof -- function name (T : Type) -- first argument (t : T) -- second argument : t = t -- return "type" := eq.refl t -- implementation /- Let's decode that. We're defining a function called gimme_a_proof that takes T and t as its arguments and promises to return a value of type t = t (a proof of this proposition). The way that it upholds this promise is by *applying* eq.refl to t, whatever it is, to construct a proof of t = t. That proof is the result and return value of this function. -/ /- Now that we've got this function defined, we can apply *it* to arguments to have it construct values that constitute proofs of t = t. If you hover over #reduce in the following Lean commands, Lean will report to you the results of applying the function to arguments of various numerical types. Remember when reading the outputs that "eq.refl x" *is* an object that serves as a proof of x = x -/ #reduce gimme_a_proof ℕ 9 #reduce gimme_a_proof bool tt #reduce gimme_a_proof ℚ 1 #reduce gimme_a_proof ℤ (-3) /- That wraps up this review (and extension) of our last lecture. Now for the quiz. -/ /-++++++++++ EXERCISES #1. Give a quasi-formal English language "proof" of the proposition that 2 = 2. Theorem: 2 = 2. Proof: [your answer here] -/ /-++++++++++ EXERCISE #2. Give, below, a formal statement and proof of the proposition, 2 = 2. (See above for a good example to follow!) -/ -- answer here example : 2 = 2 := @eq.refl ℕ 2 /- EXERCISE #3. Identify what form of reasoning is being used in each of the following made-up stories. Just give a one-word answer for each. A. Every time the bell has rung, I've gotten a nugget. The bell just rung, so I'm gonna get a nugget! (Dogs usually say "gonna," by the way). answer: B. The "clone repo into container" command did nothing. That was clearly wrong. I search around on the World Wide Web and notice someone saying something about that VSCode command needed to have git installed. Ah ha, I thought. That could be it. I'll do the obvious experiment and install git and see if it works. (It did, by the way.) answer: C. It's true that it's raining, and it's true that the streets are wet, so it must be true that "it's raining *and* the streets are wet." answer: -/ end cs2120
a7dc60f969713666b5c409e22e4e65ce4a7a58fb
952248371e69ccae722eb20bfe6815d8641554a8
/src/datatypes/default.lean
e7b2b28112f718e72237927e0edf5afb62520a7a
[]
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
109
lean
import datatypes.basic datatypes.comp datatypes.expr_form datatypes.proof datatypes.info
c7d14e6ee2d0f27f756c74704f8db3a0a3cddbd3
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/category_theory/limits/kan_extension.lean
fc36fe2b1fede49b50fa44e9a6efdc964e28ec05
[ "Apache-2.0" ]
permissive
JLimperg/aesop3
306cc6570c556568897ed2e508c8869667252e8a
a4a116f650cc7403428e72bd2e2c4cda300fe03f
refs/heads/master
1,682,884,916,368
1,620,320,033,000
1,620,320,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,213
lean
/- Copyright (c) 2021 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, Adam Topaz -/ import category_theory.punit import category_theory.structured_arrow import category_theory.limits.functor_category import category_theory.limits.shapes.terminal import tactic /-! # Kan extensions This file defines the right and left Kan extensions of a functor. They exist under the assumption that the target category has enough limits resp. colimits. The main definitions are `Ran ι` and `Lan ι`, where `ι : S ⥤ L` is a functor. Namely, `Ran ι` is the right Kan extension, while `Lan ι` is the left Kan extension, both as functors `(S ⥤ D) ⥤ (L ⥤ D)`. To access the right resp. left adjunction associated to these, use `Ran.adjunction` resp. `Lan.adjunction`. # Projects A lot of boilerplate could be generalized by defining and working with pseudofunctors. -/ noncomputable theory namespace category_theory open limits universes v u₁ u₂ u₃ variables {S : Type v} {L : Type u₂} {D : Type u₃} variables [category.{v} S] [category.{v} L] [category.{v} D] variables (ι : S ⥤ L) namespace Ran local attribute [simp] structured_arrow.proj /-- The diagram indexed by `Ran.index ι x` used to define `Ran`. -/ abbreviation diagram (F : S ⥤ D) (x : L) : structured_arrow x ι ⥤ D := structured_arrow.proj ⋙ F variable {ι} /-- A cone over `Ran.diagram ι F x` used to define `Ran`. -/ @[simp] def cone {F : S ⥤ D} {G : L ⥤ D} (x : L) (f : ι ⋙ G ⟶ F) : cone (diagram ι F x) := { X := G.obj x, π := { app := λ i, G.map i.hom ≫ f.app i.right, naturality' := begin rintro ⟨⟨il⟩, ir, i⟩ ⟨⟨jl⟩, jr, j⟩ ⟨⟨⟨fl⟩⟩, fr, ff⟩, dsimp at *, simp only [category.id_comp, category.assoc] at *, rw [ff], have := f.naturality, tidy, end } } variable (ι) /-- An auxiliary definition used to define `Ran`. -/ @[simps] def loc (F : S ⥤ D) [∀ x, has_limit (diagram ι F x)] : L ⥤ D := { obj := λ x, limit (diagram ι F x), map := λ x y f, limit.pre (diagram _ _ _) (structured_arrow.map f : structured_arrow _ ι ⥤ _), map_id' := begin intro l, ext j, simp only [category.id_comp, limit.pre_π], congr' 1, simp, end, map_comp' := begin intros x y z f g, ext j, erw [limit.pre_pre, limit.pre_π, limit.pre_π], congr' 1, tidy, end } /-- An auxiliary definition used to define `Ran` and `Ran.adjunction`. -/ @[simps] def equiv (F : S ⥤ D) [∀ x, has_limit (diagram ι F x)] (G : L ⥤ D) : (G ⟶ loc ι F) ≃ (((whiskering_left _ _ _).obj ι).obj G ⟶ F) := { to_fun := λ f, { app := λ x, f.app _ ≫ limit.π (diagram ι F (ι.obj x)) (structured_arrow.mk (𝟙 _)), naturality' := begin intros x y ff, dsimp only [whiskering_left], simp only [functor.comp_map, nat_trans.naturality_assoc, loc_map, category.assoc], congr' 1, erw limit.pre_π, change _ = _ ≫ (diagram ι F (ι.obj x)).map (structured_arrow.hom_mk _ _), rw limit.w, tidy, end }, inv_fun := λ f, { app := λ x, limit.lift (diagram ι F x) (cone _ f), naturality' := begin intros x y ff, ext j, erw [limit.lift_pre, limit.lift_π, category.assoc, limit.lift_π (cone _ f) j], tidy, end }, left_inv := begin intro x, ext k j, dsimp only [cone], rw limit.lift_π, simp only [nat_trans.naturality_assoc, loc_map], erw limit.pre_π, congr, cases j, tidy, end, right_inv := by tidy } end Ran /-- The right Kan extension of a functor. -/ @[simps] def Ran [∀ X, has_limits_of_shape (structured_arrow X ι) D] : (S ⥤ D) ⥤ L ⥤ D := adjunction.right_adjoint_of_equiv (λ F G, (Ran.equiv ι G F).symm) (by tidy) namespace Ran variable (D) /-- The adjunction associated to `Ran`. -/ def adjunction [∀ X, has_limits_of_shape (structured_arrow X ι) D] : (whiskering_left _ _ D).obj ι ⊣ Ran ι := adjunction.adjunction_of_equiv_right _ _ end Ran namespace Lan local attribute [simp] costructured_arrow.proj /-- The diagram indexed by `Ran.index ι x` used to define `Ran`. -/ abbreviation diagram (F : S ⥤ D) (x : L) : costructured_arrow ι x ⥤ D := costructured_arrow.proj ⋙ F variable {ι} /-- A cocone over `Lan.diagram ι F x` used to define `Lan`. -/ @[simp] def cocone {F : S ⥤ D} {G : L ⥤ D} (x : L) (f : F ⟶ ι ⋙ G) : cocone (diagram ι F x) := { X := G.obj x, ι := { app := λ i, f.app i.left ≫ G.map i.hom, naturality' := begin rintro ⟨ir, ⟨il⟩, i⟩ ⟨jl, ⟨jr⟩, j⟩ ⟨fl, ⟨⟨fl⟩⟩, ff⟩, dsimp at *, simp only [functor.comp_map, category.comp_id, nat_trans.naturality_assoc], rw [← G.map_comp, ff], tidy, end } } variable (ι) /-- An auxiliary definition used to define `Lan`. -/ @[simps] def loc (F : S ⥤ D) [I : ∀ x, has_colimit (diagram ι F x)] : L ⥤ D := { obj := λ x, colimit (diagram ι F x), map := λ x y f, colimit.pre (diagram _ _ _) (costructured_arrow.map f : costructured_arrow ι _ ⥤ _), map_id' := begin intro l, ext j, erw [colimit.ι_pre, category.comp_id], congr' 1, simp, end, map_comp' := begin intros x y z f g, ext j, let ff : costructured_arrow ι _ ⥤ _ := costructured_arrow.map f, let gg : costructured_arrow ι _ ⥤ _ := costructured_arrow.map g, let dd := diagram ι F z, -- I don't know why lean can't deduce the following three instances... haveI : has_colimit (ff ⋙ gg ⋙ dd) := I _, haveI : has_colimit ((ff ⋙ gg) ⋙ dd) := I _, haveI : has_colimit (gg ⋙ dd) := I _, change _ = colimit.ι ((ff ⋙ gg) ⋙ dd) j ≫ _ ≫ _, erw [colimit.pre_pre dd gg ff, colimit.ι_pre, colimit.ι_pre], congr' 1, simp, end } /-- An auxiliary definition used to define `Lan` and `Lan.adjunction`. -/ @[simps] def equiv (F : S ⥤ D) [I : ∀ x, has_colimit (diagram ι F x)] (G : L ⥤ D) : (loc ι F ⟶ G) ≃ (F ⟶ ((whiskering_left _ _ _).obj ι).obj G) := { to_fun := λ f, { app := λ x, by apply colimit.ι (diagram ι F (ι.obj x)) (costructured_arrow.mk (𝟙 _)) ≫ f.app _, -- sigh naturality' := begin intros x y ff, dsimp only [whiskering_left], simp only [functor.comp_map, category.assoc], rw [← f.naturality (ι.map ff), ← category.assoc, ← category.assoc], let fff : costructured_arrow ι _ ⥤ _ := costructured_arrow.map (ι.map ff), -- same issue :-( haveI : has_colimit (fff ⋙ diagram ι F (ι.obj y)) := I _, erw colimit.ι_pre (diagram ι F (ι.obj y)) fff (costructured_arrow.mk (𝟙 _)), let xx : costructured_arrow ι (ι.obj y) := costructured_arrow.mk (ι.map ff), let yy : costructured_arrow ι (ι.obj y) := costructured_arrow.mk (𝟙 _), let fff : xx ⟶ yy := costructured_arrow.hom_mk ff (by {simp only [costructured_arrow.mk_hom_eq_self], erw category.comp_id}), erw colimit.w (diagram ι F (ι.obj y)) fff, congr, simp, end }, inv_fun := λ f, { app := λ x, colimit.desc (diagram ι F x) (cocone _ f), naturality' := begin intros x y ff, ext j, erw [colimit.pre_desc, ← category.assoc, colimit.ι_desc, colimit.ι_desc], tidy, end }, left_inv := begin intro x, ext k j, rw colimit.ι_desc, dsimp only [cocone], rw [category.assoc, ← x.naturality j.hom, ← category.assoc], congr' 1, change colimit.ι _ _ ≫ colimit.pre (diagram ι F k) (costructured_arrow.map _) = _, rw colimit.ι_pre, congr, cases j, tidy, end, right_inv := by tidy } end Lan /-- The left Kan extension of a functor. -/ @[simps] def Lan [∀ X, has_colimits_of_shape (costructured_arrow ι X) D] : (S ⥤ D) ⥤ L ⥤ D := adjunction.left_adjoint_of_equiv (λ F G, Lan.equiv ι F G) (by tidy) namespace Lan variable (D) /-- The adjunction associated to `Lan`. -/ def adjunction [∀ X, has_colimits_of_shape (costructured_arrow ι X) D] : Lan ι ⊣ (whiskering_left _ _ D).obj ι := adjunction.adjunction_of_equiv_left _ _ end Lan end category_theory
476fb2bfd94d0bd8396ef3a0f14098e101477322
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/stage0/src/Lean/Meta/Closure.lean
cbc8622f8fa600ef0364001f4c04e4abad3849e9
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
14,444
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Std.ShareCommon import Lean.MetavarContext import Lean.Environment import Lean.Util.FoldConsts import Lean.Meta.Basic import Lean.Meta.Check /- This module provides functions for "closing" open terms and creating auxiliary definitions. Here, we say a term is "open" if it contains free/meta-variables. The "closure" is performed by lambda abstracting the free/meta-variables. Recall that in dependent type theory lambda abstracting a let-variable may produce type incorrect terms. For example, given the context ```lean (n : Nat := 20) (x : Vector α n) (y : Vector α 20) ``` the term `x = y` is correct. However, its closure using lambda abstractions is not. ```lean fun (n : Nat) (x : Vector α n) (y : Vector α 20) => x = y ``` A previous version of this module would address this issue by always use let-expressions to abstract let-vars. In the example above, it would produce ```lean let n : Nat := 20; fun (x : Vector α n) (y : Vector α 20) => x = y ``` This approach produces correct result, but produces unsatisfactory results when we want to create auxiliary definitions. For example, consider the context ```lean (x : Nat) (y : Nat := fact x) ``` and the term `h (g y)`, now suppose we want to create an auxiliary definition for `y`. The previous version of this module would compute the auxiliary definition ```lean def aux := fun (x : Nat) => let y : Nat := fact x; h (g y) ``` and would return the term `aux x` as a substitute for `h (g y)`. This is correct, but we will re-evaluate `fact x` whenever we use `aux`. In this module, we produce ```lean def aux := fun (y : Nat) => h (g y) ``` Note that in this particular case, it is safe to lambda abstract the let-varible `y`. This module uses the following approach to decide whether it is safe or not to lambda abstract a let-variable. 1) We enable zeta-expansion tracking in `MetaM`. That is, whenever we perform type checking if a let-variable needs to zeta expanded, we store it in the set `zetaFVarIds`. We say a let-variable is zeta expanded when we replace it with its value. 2) We use the `MetaM` type checker `check` to type check the expression we want to close, and the type of the binders. 3) If a let-variable is not in `zetaFVarIds`, we lambda abstract it. Remark: We still use let-expressions for let-variables in `zetaFVarIds`, but we move the `let` inside the lambdas. The idea is to make sure the auxiliary definition does not have an interleaving of `lambda` and `let` expressions. Thus, if the let-variable occurs in the type of one of the lambdas, we simply zeta-expand it there. As a final example consider the context ```lean (x_1 : Nat) (x_2 : Nat) (x_3 : Nat) (x : Nat := fact (10 + x_1 + x_2 + x_3)) (ty : Type := Nat → Nat) (f : ty := fun x => x) (n : Nat := 20) (z : f 10) ``` and we use this module to compute an auxiliary definition for the term ```lean (let y : { v : Nat // v = n } := ⟨20, rfl⟩; y.1 + n + f x, z + 10) ``` we obtain ```lean def aux (x : Nat) (f : Nat → Nat) (z : Nat) : Nat×Nat := let n : Nat := 20; (let y : {v // v=n} := {val := 20, property := ex._proof_1}; y.val+n+f x, z+10) ``` BTW, this module also provides the `zeta : Bool` flag. When set to true, it expands all let-variables occurring in the target expression. -/ namespace Lean.Meta namespace Closure structure ToProcessElement where fvarId : FVarId newFVarId : FVarId deriving Inhabited structure Context where zeta : Bool structure State where visitedLevel : LevelMap Level := {} visitedExpr : ExprStructMap Expr := {} levelParams : Array Name := #[] nextLevelIdx : Nat := 1 levelArgs : Array Level := #[] newLocalDecls : Array LocalDecl := #[] newLocalDeclsForMVars : Array LocalDecl := #[] newLetDecls : Array LocalDecl := #[] nextExprIdx : Nat := 1 exprMVarArgs : Array Expr := #[] exprFVarArgs : Array Expr := #[] toProcess : Array ToProcessElement := #[] abbrev ClosureM := ReaderT Context $ StateRefT State MetaM @[inline] def visitLevel (f : Level → ClosureM Level) (u : Level) : ClosureM Level := do if !u.hasMVar && !u.hasParam then pure u else let s ← get match s.visitedLevel.find? u with | some v => pure v | none => do let v ← f u modify fun s => { s with visitedLevel := s.visitedLevel.insert u v } pure v @[inline] def visitExpr (f : Expr → ClosureM Expr) (e : Expr) : ClosureM Expr := do if !e.hasLevelParam && !e.hasFVar && !e.hasMVar then pure e else let s ← get match s.visitedExpr.find? e with | some r => pure r | none => let r ← f e modify fun s => { s with visitedExpr := s.visitedExpr.insert e r } pure r def mkNewLevelParam (u : Level) : ClosureM Level := do let s ← get let p := (`u).appendIndexAfter s.nextLevelIdx modify fun s => { s with levelParams := s.levelParams.push p, nextLevelIdx := s.nextLevelIdx + 1, levelArgs := s.levelArgs.push u } pure $ mkLevelParam p partial def collectLevelAux : Level → ClosureM Level | u@(Level.succ v _) => return u.updateSucc! (← visitLevel collectLevelAux v) | u@(Level.max v w _) => return u.updateMax! (← visitLevel collectLevelAux v) (← visitLevel collectLevelAux w) | u@(Level.imax v w _) => return u.updateIMax! (← visitLevel collectLevelAux v) (← visitLevel collectLevelAux w) | u@(Level.mvar mvarId _) => mkNewLevelParam u | u@(Level.param _ _) => mkNewLevelParam u | u@(Level.zero _) => pure u def collectLevel (u : Level) : ClosureM Level := do -- u ← instantiateLevelMVars u visitLevel collectLevelAux u def preprocess (e : Expr) : ClosureM Expr := do let e ← instantiateMVars e let ctx ← read -- If we are not zeta-expanding let-decls, then we use `check` to find -- which let-decls are dependent. We say a let-decl is dependent if its lambda abstraction is type incorrect. if !ctx.zeta then check e pure e /-- Remark: This method does not guarantee unique user names. The correctness of the procedure does not rely on unique user names. Recall that the pretty printer takes care of unintended collisions. -/ def mkNextUserName : ClosureM Name := do let s ← get let n := (`_x).appendIndexAfter s.nextExprIdx modify fun s => { s with nextExprIdx := s.nextExprIdx + 1 } pure n def pushToProcess (elem : ToProcessElement) : ClosureM Unit := modify fun s => { s with toProcess := s.toProcess.push elem } partial def collectExprAux (e : Expr) : ClosureM Expr := do let collect (e : Expr) := visitExpr collectExprAux e match e with | Expr.proj _ _ s _ => return e.updateProj! (← collect s) | Expr.forallE _ d b _ => return e.updateForallE! (← collect d) (← collect b) | Expr.lam _ d b _ => return e.updateLambdaE! (← collect d) (← collect b) | Expr.letE _ t v b _ => return e.updateLet! (← collect t) (← collect v) (← collect b) | Expr.app f a _ => return e.updateApp! (← collect f) (← collect a) | Expr.mdata _ b _ => return e.updateMData! (← collect b) | Expr.sort u _ => return e.updateSort! (← collectLevel u) | Expr.const c us _ => return e.updateConst! (← us.mapM collectLevel) | Expr.mvar mvarId _ => let mvarDecl ← getMVarDecl mvarId let type ← preprocess mvarDecl.type let type ← collect type let newFVarId ← mkFreshFVarId let userName ← mkNextUserName modify fun s => { s with newLocalDeclsForMVars := s.newLocalDeclsForMVars.push $ LocalDecl.cdecl arbitrary newFVarId userName type BinderInfo.default, exprMVarArgs := s.exprMVarArgs.push e } return mkFVar newFVarId | Expr.fvar fvarId _ => match (← read).zeta, (← getLocalDecl fvarId).value? with | true, some value => collect (← preprocess value) | _, _ => let newFVarId ← mkFreshFVarId pushToProcess ⟨fvarId, newFVarId⟩ return mkFVar newFVarId | e => pure e def collectExpr (e : Expr) : ClosureM Expr := do let e ← preprocess e visitExpr collectExprAux e partial def pickNextToProcessAux (lctx : LocalContext) (i : Nat) (toProcess : Array ToProcessElement) (elem : ToProcessElement) : ToProcessElement × Array ToProcessElement := if h : i < toProcess.size then let elem' := toProcess.get ⟨i, h⟩ if (lctx.get! elem.fvarId).index < (lctx.get! elem'.fvarId).index then pickNextToProcessAux lctx (i+1) (toProcess.set ⟨i, h⟩ elem) elem' else pickNextToProcessAux lctx (i+1) toProcess elem else (elem, toProcess) def pickNextToProcess? : ClosureM (Option ToProcessElement) := do let lctx ← getLCtx let s ← get if s.toProcess.isEmpty then pure none else modifyGet fun s => let elem := s.toProcess.back let toProcess := s.toProcess.pop let (elem, toProcess) := pickNextToProcessAux lctx 0 toProcess elem (some elem, { s with toProcess := toProcess }) def pushFVarArg (e : Expr) : ClosureM Unit := modify fun s => { s with exprFVarArgs := s.exprFVarArgs.push e } def pushLocalDecl (newFVarId : FVarId) (userName : Name) (type : Expr) (bi := BinderInfo.default) : ClosureM Unit := do let type ← collectExpr type modify fun s => { s with newLocalDecls := s.newLocalDecls.push <| LocalDecl.cdecl arbitrary newFVarId userName type bi } partial def process : ClosureM Unit := do match (← pickNextToProcess?) with | none => pure () | some ⟨fvarId, newFVarId⟩ => let localDecl ← getLocalDecl fvarId match localDecl with | LocalDecl.cdecl _ _ userName type bi => pushLocalDecl newFVarId userName type bi pushFVarArg (mkFVar fvarId) process | LocalDecl.ldecl _ _ userName type val _ => let zetaFVarIds ← getZetaFVarIds if !zetaFVarIds.contains fvarId then /- Non-dependent let-decl Recall that if `fvarId` is in `zetaFVarIds`, then we zeta-expanded it during type checking (see `check` at `collectExpr`). Our type checker may zeta-expand declarations that are not needed, but this check is conservative, and seems to work well in practice. -/ pushLocalDecl newFVarId userName type pushFVarArg (mkFVar fvarId) process else /- Dependent let-decl -/ let type ← collectExpr type let val ← collectExpr val modify fun s => { s with newLetDecls := s.newLetDecls.push <| LocalDecl.ldecl arbitrary newFVarId userName type val false } /- We don't want to interleave let and lambda declarations in our closure. So, we expand any occurrences of newFVarId at `newLocalDecls` -/ modify fun s => { s with newLocalDecls := s.newLocalDecls.map (replaceFVarIdAtLocalDecl newFVarId val) } process @[inline] def mkBinding (isLambda : Bool) (decls : Array LocalDecl) (b : Expr) : Expr := let xs := decls.map LocalDecl.toExpr let b := b.abstract xs decls.size.foldRev (init := b) fun i b => let decl := decls[i] match decl with | LocalDecl.cdecl _ _ n ty bi => let ty := ty.abstractRange i xs if isLambda then Lean.mkLambda n bi ty b else Lean.mkForall n bi ty b | LocalDecl.ldecl _ _ n ty val nonDep => if b.hasLooseBVar 0 then let ty := ty.abstractRange i xs let val := val.abstractRange i xs mkLet n ty val b nonDep else b.lowerLooseBVars 1 1 def mkLambda (decls : Array LocalDecl) (b : Expr) : Expr := mkBinding true decls b def mkForall (decls : Array LocalDecl) (b : Expr) : Expr := mkBinding false decls b structure MkValueTypeClosureResult where levelParams : Array Name type : Expr value : Expr levelArgs : Array Level exprArgs : Array Expr def mkValueTypeClosureAux (type : Expr) (value : Expr) : ClosureM (Expr × Expr) := do resetZetaFVarIds withTrackingZeta do let type ← collectExpr type let value ← collectExpr value process pure (type, value) def mkValueTypeClosure (type : Expr) (value : Expr) (zeta : Bool) : MetaM MkValueTypeClosureResult := do let ((type, value), s) ← ((mkValueTypeClosureAux type value).run { zeta := zeta }).run {} let newLocalDecls := s.newLocalDecls.reverse ++ s.newLocalDeclsForMVars let newLetDecls := s.newLetDecls.reverse let type := mkForall newLocalDecls (mkForall newLetDecls type) let value := mkLambda newLocalDecls (mkLambda newLetDecls value) pure { type := type, value := value, levelParams := s.levelParams, levelArgs := s.levelArgs, exprArgs := s.exprFVarArgs.reverse ++ s.exprMVarArgs } end Closure /-- Create an auxiliary definition with the given name, type and value. The parameters `type` and `value` may contain free and meta variables. A "closure" is computed, and a term of the form `name.{u_1 ... u_n} t_1 ... t_m` is returned where `u_i`s are universe parameters and metavariables `type` and `value` depend on, and `t_j`s are free and meta variables `type` and `value` depend on. -/ def mkAuxDefinition (name : Name) (type : Expr) (value : Expr) (zeta : Bool := false) (compile : Bool := true) : MetaM Expr := do trace[Meta.debug] "{name} : {type} := {value}" let result ← Closure.mkValueTypeClosure type value zeta let env ← getEnv let decl := Declaration.defnDecl { name := name, levelParams := result.levelParams.toList, type := result.type, value := result.value, hints := ReducibilityHints.regular (getMaxHeight env result.value + 1), safety := if env.hasUnsafe result.type || env.hasUnsafe result.value then DefinitionSafety.unsafe else DefinitionSafety.safe } trace[Meta.debug] "{name} : {result.type} := {result.value}" addDecl decl if compile then compileDecl decl return mkAppN (mkConst name result.levelArgs.toList) result.exprArgs /-- Similar to `mkAuxDefinition`, but infers the type of `value`. -/ def mkAuxDefinitionFor (name : Name) (value : Expr) : MetaM Expr := do let type ← inferType value let type := type.headBeta mkAuxDefinition name type value end Lean.Meta
3139abed4b81e5b4bdac1b8d28e0af7d6b15aa82
38bf3fd2bb651ab70511408fcf70e2029e2ba310
/src/topology/constructions.lean
5f7642a8b4465b3686d6e8d53a98d7dea8a61b6f
[ "Apache-2.0" ]
permissive
JaredCorduan/mathlib
130392594844f15dad65a9308c242551bae6cd2e
d5de80376088954d592a59326c14404f538050a1
refs/heads/master
1,595,862,206,333
1,570,816,457,000
1,570,816,457,000
209,134,499
0
0
Apache-2.0
1,568,746,811,000
1,568,746,811,000
null
UTF-8
Lean
false
false
46,532
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot Constructions of new topological spaces from old ones: product, sum, subtype, quotient, list, vector -/ import topology.maps topology.subset_properties topology.separation topology.bases import topology.dense_embedding noncomputable theory open set filter lattice open_locale classical variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} section prod open topological_space variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] lemma continuous_fst : continuous (@prod.fst α β) := continuous_inf_dom_left continuous_induced_dom lemma continuous_snd : continuous (@prod.snd α β) := continuous_inf_dom_right continuous_induced_dom lemma continuous.prod_mk {f : γ → α} {g : γ → β} (hf : continuous f) (hg : continuous g) : continuous (λx, prod.mk (f x) (g x)) := continuous_inf_rng (continuous_induced_rng hf) (continuous_induced_rng hg) lemma continuous_swap : continuous (prod.swap : α × β → β × α) := continuous.prod_mk continuous_snd continuous_fst lemma is_open_prod {s : set α} {t : set β} (hs : is_open s) (ht : is_open t) : is_open (set.prod s t) := is_open_inter (continuous_fst s hs) (continuous_snd t ht) lemma nhds_prod_eq {a : α} {b : β} : nhds (a, b) = filter.prod (nhds a) (nhds b) := by rw [filter.prod, prod.topological_space, nhds_inf, nhds_induced, nhds_induced] instance [discrete_topology α] [discrete_topology β] : discrete_topology (α × β) := ⟨eq_of_nhds_eq_nhds $ assume ⟨a, b⟩, by rw [nhds_prod_eq, nhds_discrete α, nhds_discrete β, nhds_bot, filter.prod_pure_pure]⟩ lemma prod_mem_nhds_sets {s : set α} {t : set β} {a : α} {b : β} (ha : s ∈ nhds a) (hb : t ∈ nhds b) : set.prod s t ∈ nhds (a, b) := by rw [nhds_prod_eq]; exact prod_mem_prod ha hb lemma nhds_swap (a : α) (b : β) : nhds (a, b) = (nhds (b, a)).map prod.swap := by rw [nhds_prod_eq, filter.prod_comm, nhds_prod_eq]; refl lemma tendsto_prod_mk_nhds {γ} {a : α} {b : β} {f : filter γ} {ma : γ → α} {mb : γ → β} (ha : tendsto ma f (nhds a)) (hb : tendsto mb f (nhds b)) : tendsto (λc, (ma c, mb c)) f (nhds (a, b)) := by rw [nhds_prod_eq]; exact filter.tendsto.prod_mk ha hb lemma continuous_at.prod {f : α → β} {g : α → γ} {x : α} (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (λx, (f x, g x)) x := tendsto_prod_mk_nhds hf hg lemma prod_generate_from_generate_from_eq {α : Type*} {β : Type*} {s : set (set α)} {t : set (set β)} (hs : ⋃₀ s = univ) (ht : ⋃₀ t = univ) : @prod.topological_space α β (generate_from s) (generate_from t) = generate_from {g | ∃u∈s, ∃v∈t, g = set.prod u v} := let G := generate_from {g | ∃u∈s, ∃v∈t, g = set.prod u v} in le_antisymm (le_generate_from $ assume g ⟨u, hu, v, hv, g_eq⟩, g_eq.symm ▸ @is_open_prod _ _ (generate_from s) (generate_from t) _ _ (generate_open.basic _ hu) (generate_open.basic _ hv)) (le_inf (coinduced_le_iff_le_induced.mp $ le_generate_from $ assume u hu, have (⋃v∈t, set.prod u v) = prod.fst ⁻¹' u, from calc (⋃v∈t, set.prod u v) = set.prod u univ : set.ext $ assume ⟨a, b⟩, by rw ← ht; simp [and.left_comm] {contextual:=tt} ... = prod.fst ⁻¹' u : by simp [set.prod, preimage], show G.is_open (prod.fst ⁻¹' u), from this ▸ @is_open_Union _ _ G _ $ assume v, @is_open_Union _ _ G _ $ assume hv, generate_open.basic _ ⟨_, hu, _, hv, rfl⟩) (coinduced_le_iff_le_induced.mp $ le_generate_from $ assume v hv, have (⋃u∈s, set.prod u v) = prod.snd ⁻¹' v, from calc (⋃u∈s, set.prod u v) = set.prod univ v: set.ext $ assume ⟨a, b⟩, by rw [←hs]; by_cases b ∈ v; simp [h] {contextual:=tt} ... = prod.snd ⁻¹' v : by simp [set.prod, preimage], show G.is_open (prod.snd ⁻¹' v), from this ▸ @is_open_Union _ _ G _ $ assume u, @is_open_Union _ _ G _ $ assume hu, generate_open.basic _ ⟨_, hu, _, hv, rfl⟩)) lemma prod_eq_generate_from : prod.topological_space = generate_from {g | ∃(s:set α) (t:set β), is_open s ∧ is_open t ∧ g = set.prod s t} := le_antisymm (le_generate_from $ assume g ⟨s, t, hs, ht, g_eq⟩, g_eq.symm ▸ is_open_prod hs ht) (le_inf (ball_image_of_ball $ λt ht, generate_open.basic _ ⟨t, univ, by simpa [set.prod_eq] using ht⟩) (ball_image_of_ball $ λt ht, generate_open.basic _ ⟨univ, t, by simpa [set.prod_eq] using ht⟩)) lemma is_open_prod_iff {s : set (α×β)} : is_open s ↔ (∀a b, (a, b) ∈ s → ∃u v, is_open u ∧ is_open v ∧ a ∈ u ∧ b ∈ v ∧ set.prod u v ⊆ s) := begin rw [is_open_iff_nhds], simp [nhds_prod_eq, mem_prod_iff], simp [mem_nhds_sets_iff], exact forall_congr (assume a, ball_congr $ assume b h, ⟨assume ⟨u', ⟨u, us, uo, au⟩, v', ⟨v, vs, vo, bv⟩, h⟩, ⟨u, uo, v, vo, au, bv, subset.trans (set.prod_mono us vs) h⟩, assume ⟨u, uo, v, vo, au, bv, h⟩, ⟨u, ⟨u, subset.refl u, uo, au⟩, v, ⟨v, subset.refl v, vo, bv⟩, h⟩⟩) end /-- The first projection in a product of topological spaces sends open sets to open sets. -/ lemma is_open_map_fst : is_open_map (@prod.fst α β) := begin assume s hs, rw is_open_iff_forall_mem_open, assume x xs, rw mem_image_eq at xs, rcases xs with ⟨⟨y₁, y₂⟩, ys, yx⟩, rcases is_open_prod_iff.1 hs _ _ ys with ⟨o₁, o₂, o₁_open, o₂_open, yo₁, yo₂, ho⟩, simp at yx, rw yx at yo₁, refine ⟨o₁, _, o₁_open, yo₁⟩, assume z zs, rw mem_image_eq, exact ⟨(z, y₂), ho (by simp [zs, yo₂]), rfl⟩ end /-- The second projection in a product of topological spaces sends open sets to open sets. -/ lemma is_open_map_snd : is_open_map (@prod.snd α β) := begin /- This lemma could be proved by composing the fact that the first projection is open, and exchanging coordinates is a homeomorphism, hence open. As the `prod_comm` homeomorphism is defined later, we rather go for the direct proof, copy-pasting the proof for the first projection. -/ assume s hs, rw is_open_iff_forall_mem_open, assume x xs, rw mem_image_eq at xs, rcases xs with ⟨⟨y₁, y₂⟩, ys, yx⟩, rcases is_open_prod_iff.1 hs _ _ ys with ⟨o₁, o₂, o₁_open, o₂_open, yo₁, yo₂, ho⟩, simp at yx, rw yx at yo₂, refine ⟨o₂, _, o₂_open, yo₂⟩, assume z zs, rw mem_image_eq, exact ⟨(y₁, z), ho (by simp [zs, yo₁]), rfl⟩ end /-- A product set is open in a product space if and only if each factor is open, or one of them is empty -/ lemma is_open_prod_iff' [topological_space β] {s : set α} {t : set β} : is_open (set.prod s t) ↔ (is_open s ∧ is_open t) ∨ (s = ∅) ∨ (t = ∅) := begin by_cases h : set.prod s t = ∅, { simp [h, prod_eq_empty_iff.1 h] }, { have st : s ≠ ∅ ∧ t ≠ ∅, by rwa [← ne.def, prod_neq_empty_iff] at h, split, { assume H : is_open (set.prod s t), refine or.inl ⟨_, _⟩, show is_open s, { rw ← fst_image_prod s st.2, exact is_open_map_fst _ H }, show is_open t, { rw ← snd_image_prod st.1 t, exact is_open_map_snd _ H } }, { assume H, simp [st] at H, exact is_open_prod H.1 H.2 } } end lemma closure_prod_eq {s : set α} {t : set β} : closure (set.prod s t) = set.prod (closure s) (closure t) := set.ext $ assume ⟨a, b⟩, have filter.prod (nhds a) (nhds b) ⊓ principal (set.prod s t) = filter.prod (nhds a ⊓ principal s) (nhds b ⊓ principal t), by rw [←prod_inf_prod, prod_principal_principal], by simp [closure_eq_nhds, nhds_prod_eq, this]; exact prod_neq_bot lemma mem_closure2 {s : set α} {t : set β} {u : set γ} {f : α → β → γ} {a : α} {b : β} (hf : continuous (λp:α×β, f p.1 p.2)) (ha : a ∈ closure s) (hb : b ∈ closure t) (hu : ∀a b, a ∈ s → b ∈ t → f a b ∈ u) : f a b ∈ closure u := have (a, b) ∈ closure (set.prod s t), by rw [closure_prod_eq]; from ⟨ha, hb⟩, show (λp:α×β, f p.1 p.2) (a, b) ∈ closure u, from mem_closure hf this $ assume ⟨a, b⟩ ⟨ha, hb⟩, hu a b ha hb lemma is_closed_prod {s₁ : set α} {s₂ : set β} (h₁ : is_closed s₁) (h₂ : is_closed s₂) : is_closed (set.prod s₁ s₂) := closure_eq_iff_is_closed.mp $ by simp [h₁, h₂, closure_prod_eq, closure_eq_of_is_closed] lemma dense_range_prod {α : Type*} {γ : Type*} {f : α → β} {g : γ → δ} (hf : dense_range f) (hg : dense_range g) : dense_range (λ p : α × γ, (f p.1, g p.2)) := have closure (range $ λ p : α×γ, (f p.1, g p.2)) = set.prod (closure $ range f) (closure $ range g), by rw [←closure_prod_eq, prod_range_range_eq], assume ⟨b, d⟩, this.symm ▸ mem_prod.2 ⟨hf _, hg _⟩ protected lemma is_open_map.prod {f : α → β} {g : γ → δ} (hf : is_open_map f) (hg : is_open_map g) : is_open_map (λ p : α × γ, (f p.1, g p.2)) := begin rw [is_open_map_iff_nhds_le], rintros ⟨a, b⟩, rw [nhds_prod_eq, nhds_prod_eq, ← filter.prod_map_map_eq], exact filter.prod_mono ((is_open_map_iff_nhds_le f).1 hf a) ((is_open_map_iff_nhds_le g).1 hg b) end protected lemma open_embedding.prod {f : α → β} {g : γ → δ} (hf : open_embedding f) (hg : open_embedding g) : open_embedding (λx:α×γ, (f x.1, g x.2)) := open_embedding_of_embedding_open (hf.1.prod_mk hg.1) (hf.is_open_map.prod hg.is_open_map) section tube_lemma def nhds_contain_boxes (s : set α) (t : set β) : Prop := ∀ (n : set (α × β)) (hn : is_open n) (hp : set.prod s t ⊆ n), ∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ set.prod u v ⊆ n lemma nhds_contain_boxes.symm {s : set α} {t : set β} : nhds_contain_boxes s t → nhds_contain_boxes t s := assume H n hn hp, let ⟨u, v, uo, vo, su, tv, p⟩ := H (prod.swap ⁻¹' n) (continuous_swap n hn) (by rwa [←image_subset_iff, prod.swap, image_swap_prod]) in ⟨v, u, vo, uo, tv, su, by rwa [←image_subset_iff, prod.swap, image_swap_prod] at p⟩ lemma nhds_contain_boxes.comm {s : set α} {t : set β} : nhds_contain_boxes s t ↔ nhds_contain_boxes t s := iff.intro nhds_contain_boxes.symm nhds_contain_boxes.symm lemma nhds_contain_boxes_of_singleton {x : α} {y : β} : nhds_contain_boxes ({x} : set α) ({y} : set β) := assume n hn hp, let ⟨u, v, uo, vo, xu, yv, hp'⟩ := is_open_prod_iff.mp hn x y (hp $ by simp) in ⟨u, v, uo, vo, by simpa, by simpa, hp'⟩ lemma nhds_contain_boxes_of_compact {s : set α} (hs : compact s) (t : set β) (H : ∀ x ∈ s, nhds_contain_boxes ({x} : set α) t) : nhds_contain_boxes s t := assume n hn hp, have ∀x : subtype s, ∃uv : set α × set β, is_open uv.1 ∧ is_open uv.2 ∧ {↑x} ⊆ uv.1 ∧ t ⊆ uv.2 ∧ set.prod uv.1 uv.2 ⊆ n, from assume ⟨x, hx⟩, have set.prod {x} t ⊆ n, from subset.trans (prod_mono (by simpa) (subset.refl _)) hp, let ⟨ux,vx,H1⟩ := H x hx n hn this in ⟨⟨ux,vx⟩,H1⟩, let ⟨uvs, h⟩ := classical.axiom_of_choice this in have us_cover : s ⊆ ⋃i, (uvs i).1, from assume x hx, set.subset_Union _ ⟨x,hx⟩ (by simpa using (h ⟨x,hx⟩).2.2.1), let ⟨s0, _, s0_fin, s0_cover⟩ := compact_elim_finite_subcover_image hs (λi _, (h i).1) $ by rw bUnion_univ; exact us_cover in let u := ⋃(i ∈ s0), (uvs i).1 in let v := ⋂(i ∈ s0), (uvs i).2 in have is_open u, from is_open_bUnion (λi _, (h i).1), have is_open v, from is_open_bInter s0_fin (λi _, (h i).2.1), have t ⊆ v, from subset_bInter (λi _, (h i).2.2.2.1), have set.prod u v ⊆ n, from assume ⟨x',y'⟩ ⟨hx',hy'⟩, have ∃i ∈ s0, x' ∈ (uvs i).1, by simpa using hx', let ⟨i,is0,hi⟩ := this in (h i).2.2.2.2 ⟨hi, (bInter_subset_of_mem is0 : v ⊆ (uvs i).2) hy'⟩, ⟨u, v, ‹is_open u›, ‹is_open v›, s0_cover, ‹t ⊆ v›, ‹set.prod u v ⊆ n›⟩ lemma generalized_tube_lemma {s : set α} (hs : compact s) {t : set β} (ht : compact t) {n : set (α × β)} (hn : is_open n) (hp : set.prod s t ⊆ n) : ∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ set.prod u v ⊆ n := have _, from nhds_contain_boxes_of_compact hs t $ assume x _, nhds_contain_boxes.symm $ nhds_contain_boxes_of_compact ht {x} $ assume y _, nhds_contain_boxes_of_singleton, this n hn hp end tube_lemma lemma is_closed_diagonal [t2_space α] : is_closed {p:α×α | p.1 = p.2} := is_closed_iff_nhds.mpr $ assume ⟨a₁, a₂⟩ h, eq_of_nhds_neq_bot $ assume : nhds a₁ ⊓ nhds a₂ = ⊥, h $ let ⟨t₁, ht₁, t₂, ht₂, (h' : t₁ ∩ t₂ ⊆ ∅)⟩ := by rw [←empty_in_sets_eq_bot, mem_inf_sets] at this; exact this in begin change t₁ ∈ nhds a₁ at ht₁, change t₂ ∈ nhds a₂ at ht₂, rw [nhds_prod_eq, ←empty_in_sets_eq_bot], apply filter.sets_of_superset, apply inter_mem_inf_sets (prod_mem_prod ht₁ ht₂) (mem_principal_sets.mpr (subset.refl _)), exact assume ⟨x₁, x₂⟩ ⟨⟨hx₁, hx₂⟩, (heq : x₁ = x₂)⟩, show false, from @h' x₁ ⟨hx₁, heq.symm ▸ hx₂⟩ end lemma is_closed_eq [t2_space α] {f g : β → α} (hf : continuous f) (hg : continuous g) : is_closed {x:β | f x = g x} := continuous_iff_is_closed.mp (hf.prod_mk hg) _ is_closed_diagonal lemma diagonal_eq_range_diagonal_map {α : Type*} : {p:α×α | p.1 = p.2} = range (λx, (x,x)) := ext $ assume p, iff.intro (assume h, ⟨p.1, prod.ext_iff.2 ⟨rfl, h⟩⟩) (assume ⟨x, hx⟩, show p.1 = p.2, by rw ←hx) lemma prod_subset_compl_diagonal_iff_disjoint {α : Type*} {s t : set α} : set.prod s t ⊆ - {p:α×α | p.1 = p.2} ↔ s ∩ t = ∅ := by rw [eq_empty_iff_forall_not_mem, subset_compl_comm, diagonal_eq_range_diagonal_map, range_subset_iff]; simp lemma compact_compact_separated [t2_space α] {s t : set α} (hs : compact s) (ht : compact t) (hst : s ∩ t = ∅) : ∃u v : set α, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ u ∩ v = ∅ := by simp only [prod_subset_compl_diagonal_iff_disjoint.symm] at ⊢ hst; exact generalized_tube_lemma hs ht is_closed_diagonal hst lemma closed_of_compact [t2_space α] (s : set α) (hs : compact s) : is_closed s := is_open_compl_iff.mpr $ is_open_iff_forall_mem_open.mpr $ assume x hx, let ⟨u, v, uo, vo, su, xv, uv⟩ := compact_compact_separated hs (compact_singleton : compact {x}) (by rwa [inter_comm, ←subset_compl_iff_disjoint, singleton_subset_iff]) in have v ⊆ -s, from subset_compl_comm.mp (subset.trans su (subset_compl_iff_disjoint.mpr uv)), ⟨v, this, vo, by simpa using xv⟩ lemma locally_compact_of_compact_nhds [t2_space α] (h : ∀ x : α, ∃ s, s ∈ nhds x ∧ compact s) : locally_compact_space α := ⟨assume x n hn, let ⟨u, un, uo, xu⟩ := mem_nhds_sets_iff.mp hn in let ⟨k, kx, kc⟩ := h x in -- K is compact but not necessarily contained in N. -- K \ U is again compact and doesn't contain x, so -- we may find open sets V, W separating x from K \ U. -- Then K \ W is a compact neighborhood of x contained in U. let ⟨v, w, vo, wo, xv, kuw, vw⟩ := compact_compact_separated compact_singleton (compact_diff kc uo) (by rw [singleton_inter_eq_empty]; exact λ h, h.2 xu) in have wn : -w ∈ nhds x, from mem_nhds_sets_iff.mpr ⟨v, subset_compl_iff_disjoint.mpr vw, vo, singleton_subset_iff.mp xv⟩, ⟨k - w, filter.inter_mem_sets kx wn, subset.trans (diff_subset_comm.mp kuw) un, compact_diff kc wo⟩⟩ instance locally_compact_of_compact [t2_space α] [compact_space α] : locally_compact_space α := locally_compact_of_compact_nhds (assume x, ⟨univ, mem_nhds_sets is_open_univ trivial, compact_univ⟩) -- We can't make this an instance because it could cause an instance loop. lemma normal_of_compact_t2 [compact_space α] [t2_space α] : normal_space α := begin refine ⟨assume s t hs ht st, _⟩, simp only [disjoint_iff], exact compact_compact_separated (compact_of_closed hs) (compact_of_closed ht) st.eq_bot end /- TODO: more fine grained instances for first_countable_topology, separable_space, t2_space, ... -/ instance [second_countable_topology α] [second_countable_topology β] : second_countable_topology (α × β) := ⟨let ⟨a, ha₁, ha₂, ha₃, ha₄, ha₅⟩ := is_open_generated_countable_inter α in let ⟨b, hb₁, hb₂, hb₃, hb₄, hb₅⟩ := is_open_generated_countable_inter β in ⟨{g | ∃u∈a, ∃v∈b, g = set.prod u v}, have {g | ∃u∈a, ∃v∈b, g = set.prod u v} = (⋃u∈a, ⋃v∈b, {set.prod u v}), by apply set.ext; simp, by rw [this]; exact (countable_bUnion ha₁ $ assume u hu, countable_bUnion hb₁ $ by simp), by rw [ha₅, hb₅, prod_generate_from_generate_from_eq ha₄ hb₄]⟩⟩ lemma compact_prod (s : set α) (t : set β) (ha : compact s) (hb : compact t) : compact (set.prod s t) := begin rw compact_iff_ultrafilter_le_nhds at ha hb ⊢, intros f hf hfs, rw le_principal_iff at hfs, rcases ha (map prod.fst f) (ultrafilter_map hf) (le_principal_iff.2 (mem_map_sets_iff.2 ⟨_, hfs, image_subset_iff.2 (λ s h, h.1)⟩)) with ⟨a, sa, ha⟩, rcases hb (map prod.snd f) (ultrafilter_map hf) (le_principal_iff.2 (mem_map_sets_iff.2 ⟨_, hfs, image_subset_iff.2 (λ s h, h.2)⟩)) with ⟨b, tb, hb⟩, rw map_le_iff_le_comap at ha hb, refine ⟨⟨a, b⟩, ⟨sa, tb⟩, _⟩, rw nhds_prod_eq, exact le_inf ha hb end instance [compact_space α] [compact_space β] : compact_space (α × β) := ⟨begin have A : compact (set.prod (univ : set α) (univ : set β)) := compact_prod univ univ compact_univ compact_univ, have : set.prod (univ : set α) (univ : set β) = (univ : set (α × β)) := by simp, rwa this at A, end⟩ end prod section sum variables [topological_space α] [topological_space β] [topological_space γ] lemma continuous_inl : continuous (@sum.inl α β) := continuous_sup_rng_left continuous_coinduced_rng lemma continuous_inr : continuous (@sum.inr α β) := continuous_sup_rng_right continuous_coinduced_rng lemma continuous_sum_rec {f : α → γ} {g : β → γ} (hf : continuous f) (hg : continuous g) : @continuous (α ⊕ β) γ _ _ (@sum.rec α β (λ_, γ) f g) := continuous_sup_dom hf hg lemma embedding_inl : embedding (@sum.inl α β) := { induced := begin unfold sum.topological_space, apply le_antisymm, { rw ← coinduced_le_iff_le_induced, exact lattice.le_sup_left }, { intros u hu, existsi (sum.inl '' u), change (is_open (sum.inl ⁻¹' (@sum.inl α β '' u)) ∧ is_open (sum.inr ⁻¹' (@sum.inl α β '' u))) ∧ sum.inl ⁻¹' (sum.inl '' u) = u, have : sum.inl ⁻¹' (@sum.inl α β '' u) = u := preimage_image_eq u (λ _ _, sum.inl.inj_iff.mp), rw this, have : sum.inr ⁻¹' (@sum.inl α β '' u) = ∅ := eq_empty_iff_forall_not_mem.mpr (assume a ⟨b, _, h⟩, sum.inl_ne_inr h), rw this, exact ⟨⟨hu, is_open_empty⟩, rfl⟩ } end, inj := λ _ _, sum.inl.inj_iff.mp } lemma embedding_inr : embedding (@sum.inr α β) := { induced := begin unfold sum.topological_space, apply le_antisymm, { rw ← coinduced_le_iff_le_induced, exact lattice.le_sup_right }, { intros u hu, existsi (sum.inr '' u), change (is_open (sum.inl ⁻¹' (@sum.inr α β '' u)) ∧ is_open (sum.inr ⁻¹' (@sum.inr α β '' u))) ∧ sum.inr ⁻¹' (sum.inr '' u) = u, have : sum.inl ⁻¹' (@sum.inr α β '' u) = ∅ := eq_empty_iff_forall_not_mem.mpr (assume b ⟨a, _, h⟩, sum.inr_ne_inl h), rw this, have : sum.inr ⁻¹' (@sum.inr α β '' u) = u := preimage_image_eq u (λ _ _, sum.inr.inj_iff.mp), rw this, exact ⟨⟨is_open_empty, hu⟩, rfl⟩ } end, inj := λ _ _, sum.inr.inj_iff.mp } instance [compact_space α] [compact_space β] : compact_space (α ⊕ β) := ⟨begin have A : compact (@sum.inl α β '' univ) := compact_image compact_univ continuous_inl, have B : compact (@sum.inr α β '' univ) := compact_image compact_univ continuous_inr, have C := compact_union_of_compact A B, have : (@sum.inl α β '' univ) ∪ (@sum.inr α β '' univ) = univ := by ext; cases x; simp, rwa this at C, end⟩ end sum section subtype variables [topological_space α] [topological_space β] [topological_space γ] {p : α → Prop} lemma embedding_graph {f : α → β} (hf : continuous f) : embedding (λx, (x, f x)) := embedding_of_embedding_compose (continuous_id.prod_mk hf) continuous_fst embedding_id lemma embedding_subtype_val : embedding (@subtype.val α p) := ⟨⟨rfl⟩, subtype.val_injective⟩ lemma continuous_subtype_val : continuous (@subtype.val α p) := continuous_induced_dom lemma continuous_subtype_mk {f : β → α} (hp : ∀x, p (f x)) (h : continuous f) : continuous (λx, (⟨f x, hp x⟩ : subtype p)) := continuous_induced_rng h lemma continuous_inclusion {s t : set α} (h : s ⊆ t) : continuous (inclusion h) := continuous_subtype_mk _ continuous_subtype_val lemma continuous_at_subtype_val {p : α → Prop} {a : subtype p} : continuous_at subtype.val a := continuous_iff_continuous_at.mp continuous_subtype_val _ lemma map_nhds_subtype_val_eq {a : α} (ha : p a) (h : {a | p a} ∈ nhds a) : map (@subtype.val α p) (nhds ⟨a, ha⟩) = nhds a := map_nhds_induced_eq (by simp [subtype.val_image, h]) lemma nhds_subtype_eq_comap {a : α} {h : p a} : nhds (⟨a, h⟩ : subtype p) = comap subtype.val (nhds a) := nhds_induced _ _ lemma tendsto_subtype_rng {β : Type*} {p : α → Prop} {b : filter β} {f : β → subtype p} : ∀{a:subtype p}, tendsto f b (nhds a) ↔ tendsto (λx, subtype.val (f x)) b (nhds a.val) | ⟨a, ha⟩ := by rw [nhds_subtype_eq_comap, tendsto_comap_iff] lemma continuous_subtype_nhds_cover {ι : Sort*} {f : α → β} {c : ι → α → Prop} (c_cover : ∀x:α, ∃i, {x | c i x} ∈ nhds x) (f_cont : ∀i, continuous (λ(x : subtype (c i)), f x.val)) : continuous f := continuous_iff_continuous_at.mpr $ assume x, let ⟨i, (c_sets : {x | c i x} ∈ nhds x)⟩ := c_cover x in let x' : subtype (c i) := ⟨x, mem_of_nhds c_sets⟩ in calc map f (nhds x) = map f (map subtype.val (nhds x')) : congr_arg (map f) (map_nhds_subtype_val_eq _ $ c_sets).symm ... = map (λx:subtype (c i), f x.val) (nhds x') : rfl ... ≤ nhds (f x) : continuous_iff_continuous_at.mp (f_cont i) x' lemma continuous_subtype_is_closed_cover {ι : Sort*} {f : α → β} (c : ι → α → Prop) (h_lf : locally_finite (λi, {x | c i x})) (h_is_closed : ∀i, is_closed {x | c i x}) (h_cover : ∀x, ∃i, c i x) (f_cont : ∀i, continuous (λ(x : subtype (c i)), f x.val)) : continuous f := continuous_iff_is_closed.mpr $ assume s hs, have ∀i, is_closed (@subtype.val α {x | c i x} '' (f ∘ subtype.val ⁻¹' s)), from assume i, embedding_is_closed embedding_subtype_val (by simp [subtype.val_range]; exact h_is_closed i) (continuous_iff_is_closed.mp (f_cont i) _ hs), have is_closed (⋃i, @subtype.val α {x | c i x} '' (f ∘ subtype.val ⁻¹' s)), from is_closed_Union_of_locally_finite (locally_finite_subset h_lf $ assume i x ⟨⟨x', hx'⟩, _, heq⟩, heq ▸ hx') this, have f ⁻¹' s = (⋃i, @subtype.val α {x | c i x} '' (f ∘ subtype.val ⁻¹' s)), begin apply set.ext, have : ∀ (x : α), f x ∈ s ↔ ∃ (i : ι), c i x ∧ f x ∈ s := λ x, ⟨λ hx, let ⟨i, hi⟩ := h_cover x in ⟨i, hi, hx⟩, λ ⟨i, hi, hx⟩, hx⟩, simp [and.comm, and.left_comm], simpa [(∘)], end, by rwa [this] lemma closure_subtype {x : {a // p a}} {s : set {a // p a}}: x ∈ closure s ↔ x.val ∈ closure (subtype.val '' s) := closure_induced $ assume x y, subtype.eq lemma compact_iff_compact_image_of_embedding {s : set α} {f : α → β} (hf : embedding f) : compact s ↔ compact (f '' s) := iff.intro (assume h, compact_image h hf.continuous) $ assume h, begin rw compact_iff_ultrafilter_le_nhds at ⊢ h, intros u hu us', let u' : filter β := map f u, have : u' ≤ principal (f '' s), begin rw [map_le_iff_le_comap, comap_principal], convert us', exact preimage_image_eq _ hf.inj end, rcases h u' (ultrafilter_map hu) this with ⟨_, ⟨a, ha, ⟨⟩⟩, _⟩, refine ⟨a, ha, _⟩, rwa [hf.induced, nhds_induced, ←map_le_iff_le_comap] end lemma compact_iff_compact_in_subtype {s : set {a // p a}} : compact s ↔ compact (subtype.val '' s) := compact_iff_compact_image_of_embedding embedding_subtype_val lemma compact_iff_compact_univ {s : set α} : compact s ↔ compact (univ : set (subtype s)) := by rw [compact_iff_compact_in_subtype, image_univ, subtype.val_range]; refl lemma compact_iff_compact_space {s : set α} : compact s ↔ compact_space s := compact_iff_compact_univ.trans ⟨λ h, ⟨h⟩, @compact_space.compact_univ _ _⟩ end subtype section quotient variables [topological_space α] [topological_space β] [topological_space γ] variables {r : α → α → Prop} {s : setoid α} lemma quotient_map_quot_mk : quotient_map (@quot.mk α r) := ⟨quot.exists_rep, rfl⟩ lemma continuous_quot_mk : continuous (@quot.mk α r) := continuous_coinduced_rng lemma continuous_quot_lift {f : α → β} (hr : ∀ a b, r a b → f a = f b) (h : continuous f) : continuous (quot.lift f hr : quot r → β) := continuous_coinduced_dom h lemma quotient_map_quotient_mk : quotient_map (@quotient.mk α s) := quotient_map_quot_mk lemma continuous_quotient_mk : continuous (@quotient.mk α s) := continuous_coinduced_rng lemma continuous_quotient_lift {f : α → β} (hs : ∀ a b, a ≈ b → f a = f b) (h : continuous f) : continuous (quotient.lift f hs : quotient s → β) := continuous_coinduced_dom h instance quot.compact_space {r : α → α → Prop} [compact_space α] : compact_space (quot r) := ⟨begin have : quot.mk r '' univ = univ, by rw [image_univ, range_iff_surjective]; exact quot.exists_rep, rw ←this, exact compact_image compact_univ continuous_quot_mk end⟩ instance quotient.compact_space {s : setoid α} [compact_space α] : compact_space (quotient s) := quot.compact_space end quotient section pi variables {ι : Type*} {π : ι → Type*} open topological_space lemma continuous_pi [topological_space α] [∀i, topological_space (π i)] {f : α → Πi:ι, π i} (h : ∀i, continuous (λa, f a i)) : continuous f := continuous_infi_rng $ assume i, continuous_induced_rng $ h i lemma continuous_apply [∀i, topological_space (π i)] (i : ι) : continuous (λp:Πi, π i, p i) := continuous_infi_dom continuous_induced_dom lemma nhds_pi [t : ∀i, topological_space (π i)] {a : Πi, π i} : nhds a = (⨅i, comap (λx, x i) (nhds (a i))) := calc nhds a = (⨅i, @nhds _ (@topological_space.induced _ _ (λx:Πi, π i, x i) (t i)) a) : nhds_infi ... = (⨅i, comap (λx, x i) (nhds (a i))) : by simp [nhds_induced] /-- Tychonoff's theorem -/ lemma compact_pi_infinite [∀i, topological_space (π i)] {s : Πi:ι, set (π i)} : (∀i, compact (s i)) → compact {x : Πi:ι, π i | ∀i, x i ∈ s i} := begin simp [compact_iff_ultrafilter_le_nhds, nhds_pi], exact assume h f hf hfs, let p : Πi:ι, filter (π i) := λi, map (λx:Πi:ι, π i, x i) f in have ∀i:ι, ∃a, a∈s i ∧ p i ≤ nhds a, from assume i, h i (p i) (ultrafilter_map hf) $ show (λx:Πi:ι, π i, x i) ⁻¹' s i ∈ f.sets, from mem_sets_of_superset hfs $ assume x (hx : ∀i, x i ∈ s i), hx i, let ⟨a, ha⟩ := classical.axiom_of_choice this in ⟨a, assume i, (ha i).left, assume i, map_le_iff_le_comap.mp $ (ha i).right⟩ end lemma is_open_set_pi [∀a, topological_space (π a)] {i : set ι} {s : Πa, set (π a)} (hi : finite i) (hs : ∀a∈i, is_open (s a)) : is_open (pi i s) := by rw [pi_def]; exact (is_open_bInter hi $ assume a ha, continuous_apply a _ $ hs a ha) lemma pi_eq_generate_from [∀a, topological_space (π a)] : Pi.topological_space = generate_from {g | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, is_open (s a)) ∧ g = pi ↑i s} := le_antisymm (le_generate_from $ assume g ⟨s, i, hi, eq⟩, eq.symm ▸ is_open_set_pi (finset.finite_to_set _) hi) (le_infi $ assume a s ⟨t, ht, s_eq⟩, generate_open.basic _ $ ⟨function.update (λa, univ) a t, {a}, by simpa using ht, by ext f; simp [s_eq.symm, pi]⟩) lemma pi_generate_from_eq {g : Πa, set (set (π a))} : @Pi.topological_space ι π (λa, generate_from (g a)) = generate_from {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ g a) ∧ t = pi ↑i s} := let G := {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ g a) ∧ t = pi ↑i s} in begin rw [pi_eq_generate_from], refine le_antisymm (generate_from_mono _) (le_generate_from _), exact assume s ⟨t, i, ht, eq⟩, ⟨t, i, assume a ha, generate_open.basic _ (ht a ha), eq⟩, { rintros s ⟨t, i, hi, rfl⟩, rw [pi_def], apply is_open_bInter (finset.finite_to_set _), assume a ha, show ((generate_from G).coinduced (λf:Πa, π a, f a)).is_open (t a), refine le_generate_from _ _ (hi a ha), exact assume s hs, generate_open.basic _ ⟨function.update (λa, univ) a s, {a}, by simp [hs]⟩ } end lemma pi_generate_from_eq_fintype {g : Πa, set (set (π a))} [fintype ι] (hg : ∀a, ⋃₀ g a = univ) : @Pi.topological_space ι π (λa, generate_from (g a)) = generate_from {t | ∃(s:Πa, set (π a)), (∀a, s a ∈ g a) ∧ t = pi univ s} := let G := {t | ∃(s:Πa, set (π a)), (∀a, s a ∈ g a) ∧ t = pi univ s} in begin rw [pi_generate_from_eq], refine le_antisymm (generate_from_mono _) (le_generate_from _), exact assume s ⟨t, ht, eq⟩, ⟨t, finset.univ, by simp [ht, eq]⟩, { rintros s ⟨t, i, ht, rfl⟩, apply is_open_iff_forall_mem_open.2 _, assume f hf, choose c hc using show ∀a, ∃s, s ∈ g a ∧ f a ∈ s, { assume a, have : f a ∈ ⋃₀ g a, { rw [hg], apply mem_univ }, simpa }, refine ⟨pi univ (λa, if a ∈ i then t a else (c : Πa, set (π a)) a), _, _, _⟩, { simp [pi_if] }, { refine generate_open.basic _ ⟨_, assume a, _, rfl⟩, by_cases a ∈ i; simp [*, pi] at * }, { have : f ∈ pi {a | a ∉ i} c, { simp [*, pi] at * }, simpa [pi_if, hf] } } end instance second_countable_topology_fintype [fintype ι] [t : ∀a, topological_space (π a)] [sc : ∀a, second_countable_topology (π a)] : second_countable_topology (∀a, π a) := have ∀i, ∃b : set (set (π i)), countable b ∧ ∅ ∉ b ∧ is_topological_basis b, from assume a, @is_open_generated_countable_inter (π a) _ (sc a), let ⟨g, hg⟩ := classical.axiom_of_choice this in have t = (λa, generate_from (g a)), from funext $ assume a, (hg a).2.2.2.2, begin constructor, refine ⟨pi univ '' pi univ g, countable_image _ _, _⟩, { suffices : countable {f : Πa, set (π a) | ∀a, f a ∈ g a}, { simpa [pi] }, exact countable_pi (assume i, (hg i).1), }, rw [this, pi_generate_from_eq_fintype], { congr' 1, ext f, simp [pi, eq_comm] }, exact assume a, (hg a).2.2.2.1 end instance pi.compact [∀i:ι, topological_space (π i)] [∀i:ι, compact_space (π i)] : compact_space (Πi, π i) := ⟨begin have A : compact {x : Πi:ι, π i | ∀i, x i ∈ (univ : set (π i))} := compact_pi_infinite (λi, compact_univ), have : {x : Πi:ι, π i | ∀i, x i ∈ (univ : set (π i))} = univ := by ext; simp, rwa this at A, end⟩ end pi section sigma variables {ι : Type*} {σ : ι → Type*} [Π i, topological_space (σ i)] open lattice lemma continuous_sigma_mk {i : ι} : continuous (@sigma.mk ι σ i) := continuous_supr_rng continuous_coinduced_rng lemma is_open_sigma_iff {s : set (sigma σ)} : is_open s ↔ ∀ i, is_open (sigma.mk i ⁻¹' s) := by simp only [is_open_supr_iff, is_open_coinduced] lemma is_closed_sigma_iff {s : set (sigma σ)} : is_closed s ↔ ∀ i, is_closed (sigma.mk i ⁻¹' s) := is_open_sigma_iff lemma is_open_map_sigma_mk {i : ι} : is_open_map (@sigma.mk ι σ i) := begin intros s hs, rw is_open_sigma_iff, intro j, classical, by_cases h : i = j, { subst j, convert hs, exact set.preimage_image_eq _ injective_sigma_mk }, { convert is_open_empty, apply set.eq_empty_of_subset_empty, rintro x ⟨y, _, hy⟩, have : i = j, by cc, contradiction } end lemma is_open_range_sigma_mk {i : ι} : is_open (set.range (@sigma.mk ι σ i)) := by { rw ←set.image_univ, exact is_open_map_sigma_mk _ is_open_univ } lemma is_closed_map_sigma_mk {i : ι} : is_closed_map (@sigma.mk ι σ i) := begin intros s hs, rw is_closed_sigma_iff, intro j, classical, by_cases h : i = j, { subst j, convert hs, exact set.preimage_image_eq _ injective_sigma_mk }, { convert is_closed_empty, apply set.eq_empty_of_subset_empty, rintro x ⟨y, _, hy⟩, have : i = j, by cc, contradiction } end lemma is_closed_sigma_mk {i : ι} : is_closed (set.range (@sigma.mk ι σ i)) := by { rw ←set.image_univ, exact is_closed_map_sigma_mk _ is_closed_univ } lemma open_embedding_sigma_mk {i : ι} : open_embedding (@sigma.mk ι σ i) := open_embedding_of_continuous_injective_open continuous_sigma_mk injective_sigma_mk is_open_map_sigma_mk lemma closed_embedding_sigma_mk {i : ι} : closed_embedding (@sigma.mk ι σ i) := closed_embedding_of_continuous_injective_closed continuous_sigma_mk injective_sigma_mk is_closed_map_sigma_mk lemma embedding_sigma_mk {i : ι} : embedding (@sigma.mk ι σ i) := closed_embedding_sigma_mk.1 /-- A map out of a sum type is continuous if its restriction to each summand is. -/ lemma continuous_sigma [topological_space β] {f : sigma σ → β} (h : ∀ i, continuous (λ a, f ⟨i, a⟩)) : continuous f := continuous_supr_dom (λ i, continuous_coinduced_dom (h i)) lemma continuous_sigma_map {κ : Type*} {τ : κ → Type*} [Π k, topological_space (τ k)] {f₁ : ι → κ} {f₂ : Π i, σ i → τ (f₁ i)} (hf : ∀ i, continuous (f₂ i)) : continuous (sigma.map f₁ f₂) := continuous_sigma $ λ i, show continuous (λ a, sigma.mk (f₁ i) (f₂ i a)), from continuous_sigma_mk.comp (hf i) lemma is_open_map_sigma [topological_space β] {f : sigma σ → β} (h : ∀ i, is_open_map (λ a, f ⟨i, a⟩)) : is_open_map f := begin intros s hs, rw is_open_sigma_iff at hs, have : s = ⋃ i, sigma.mk i '' (sigma.mk i ⁻¹' s), { rw Union_image_preimage_sigma_mk_eq_self }, rw this, rw [image_Union], apply is_open_Union, intro i, rw [image_image], exact h i _ (hs i) end /-- The sum of embeddings is an embedding. -/ lemma embedding_sigma_map {τ : ι → Type*} [Π i, topological_space (τ i)] {f : Π i, σ i → τ i} (hf : ∀ i, embedding (f i)) : embedding (sigma.map id f) := begin refine ⟨⟨_⟩, injective_sigma_map function.injective_id (λ i, (hf i).inj)⟩, refine le_antisymm (continuous_iff_le_induced.mp (continuous_sigma_map (λ i, (hf i).continuous))) _, intros s hs, replace hs := is_open_sigma_iff.mp hs, have : ∀ i, ∃ t, is_open t ∧ f i ⁻¹' t = sigma.mk i ⁻¹' s, { intro i, apply is_open_induced_iff.mp, convert hs i, exact (hf i).induced.symm }, choose t ht using this, apply is_open_induced_iff.mpr, refine ⟨⋃ i, sigma.mk i '' t i, is_open_Union (λ i, is_open_map_sigma_mk _ (ht i).1), _⟩, ext p, rcases p with ⟨i, x⟩, change (sigma.mk i (f i x) ∈ ⋃ (i : ι), sigma.mk i '' t i) ↔ x ∈ sigma.mk i ⁻¹' s, rw [←(ht i).2, mem_Union], split, { rintro ⟨j, hj⟩, rw mem_image at hj, rcases hj with ⟨y, hy₁, hy₂⟩, rcases sigma.mk.inj_iff.mp hy₂ with ⟨rfl, hy⟩, replace hy := eq_of_heq hy, subst y, exact hy₁ }, { intro hx, use i, rw mem_image, exact ⟨f i x, hx, rfl⟩ } end end sigma namespace dense_inducing variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] /-- The product of two dense inducings is a dense inducing -/ protected lemma prod {e₁ : α → β} {e₂ : γ → δ} (de₁ : dense_inducing e₁) (de₂ : dense_inducing e₂) : dense_inducing (λ(p : α × γ), (e₁ p.1, e₂ p.2)) := { induced := (de₁.to_inducing.prod_mk de₂.to_inducing).induced, dense := dense_range_prod de₁.dense de₂.dense } end dense_inducing namespace dense_embedding variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] /-- The product of two dense embeddings is a dense embedding -/ protected lemma prod {e₁ : α → β} {e₂ : γ → δ} (de₁ : dense_embedding e₁) (de₂ : dense_embedding e₂) : dense_embedding (λ(p : α × γ), (e₁ p.1, e₂ p.2)) := { inj := assume ⟨x₁, x₂⟩ ⟨y₁, y₂⟩, by simp; exact assume h₁ h₂, ⟨de₁.inj h₁, de₂.inj h₂⟩, ..dense_inducing.prod de₁.to_dense_inducing de₂.to_dense_inducing } def subtype_emb {α : Type*} (p : α → Prop) (e : α → β) (x : {x // p x}) : {x // x ∈ closure (e '' {x | p x})} := ⟨e x.1, subset_closure $ mem_image_of_mem e x.2⟩ protected lemma subtype (p : α → Prop) {e : α → β} (de : dense_embedding e) : dense_embedding (subtype_emb p e) := { dense_embedding . dense := assume ⟨x, hx⟩, closure_subtype.mpr $ have (λ (x : {x // p x}), e (x.val)) = e ∘ subtype.val, from rfl, begin rw ← image_univ, simp [(image_comp _ _ _).symm, (∘), subtype_emb, -image_univ], rw [this, image_comp, subtype.val_image], simp, assumption end, inj := assume ⟨x, hx⟩ ⟨y, hy⟩ h, subtype.eq $ de.inj $ @@congr_arg subtype.val h, induced := (induced_iff_nhds_eq _).2 (assume ⟨x, hx⟩, by simp [subtype_emb, nhds_subtype_eq_comap, de.to_inducing.nhds_eq_comap, comap_comap_comp, (∘)]) } end dense_embedding lemma is_closed_property [topological_space β] {e : α → β} {p : β → Prop} (he : closure (range e) = univ) (hp : is_closed {x | p x}) (h : ∀a, p (e a)) : ∀b, p b := have univ ⊆ {b | p b}, from calc univ = closure (range e) : he.symm ... ⊆ closure {b | p b} : closure_mono $ range_subset_iff.mpr h ... = _ : closure_eq_of_is_closed hp, assume b, this trivial lemma is_closed_property2 [topological_space α] [topological_space β] {e : α → β} {p : β → β → Prop} (he : dense_embedding e) (hp : is_closed {q:β×β | p q.1 q.2}) (h : ∀a₁ a₂, p (e a₁) (e a₂)) : ∀b₁ b₂, p b₁ b₂ := have ∀q:β×β, p q.1 q.2, from is_closed_property (he.prod he).to_dense_inducing.closure_range hp $ assume a, h _ _, assume b₁ b₂, this ⟨b₁, b₂⟩ lemma is_closed_property3 [topological_space α] [topological_space β] {e : α → β} {p : β → β → β → Prop} (he : dense_embedding e) (hp : is_closed {q:β×β×β | p q.1 q.2.1 q.2.2}) (h : ∀a₁ a₂ a₃, p (e a₁) (e a₂) (e a₃)) : ∀b₁ b₂ b₃, p b₁ b₂ b₃ := have ∀q:β×β×β, p q.1 q.2.1 q.2.2, from is_closed_property (he.prod $ he.prod he).to_dense_inducing.closure_range hp $ assume ⟨a₁, a₂, a₃⟩, h _ _ _, assume b₁ b₂ b₃, this ⟨b₁, b₂, b₃⟩ lemma mem_closure_of_continuous [topological_space α] [topological_space β] {f : α → β} {a : α} {s : set α} {t : set β} (hf : continuous f) (ha : a ∈ closure s) (h : ∀a∈s, f a ∈ closure t) : f a ∈ closure t := calc f a ∈ f '' closure s : mem_image_of_mem _ ha ... ⊆ closure (f '' s) : image_closure_subset_closure_image hf ... ⊆ closure (closure t) : closure_mono $ image_subset_iff.mpr $ h ... ⊆ closure t : begin rw [closure_eq_of_is_closed], exact subset.refl _, exact is_closed_closure end lemma mem_closure_of_continuous2 [topological_space α] [topological_space β] [topological_space γ] {f : α → β → γ} {a : α} {b : β} {s : set α} {t : set β} {u : set γ} (hf : continuous (λp:α×β, f p.1 p.2)) (ha : a ∈ closure s) (hb : b ∈ closure t) (h : ∀a∈s, ∀b∈t, f a b ∈ closure u) : f a b ∈ closure u := have (a,b) ∈ closure (set.prod s t), by simp [closure_prod_eq, ha, hb], show f (a, b).1 (a, b).2 ∈ closure u, from @mem_closure_of_continuous (α×β) _ _ _ (λp:α×β, f p.1 p.2) (a,b) _ u hf this $ assume ⟨p₁, p₂⟩ ⟨h₁, h₂⟩, h p₁ h₁ p₂ h₂ /-- α and β are homeomorph, also called topological isomoph -/ structure homeomorph (α : Type*) (β : Type*) [topological_space α] [topological_space β] extends α ≃ β := (continuous_to_fun : continuous to_fun) (continuous_inv_fun : continuous inv_fun) infix ` ≃ₜ `:25 := homeomorph namespace homeomorph variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] instance : has_coe_to_fun (α ≃ₜ β) := ⟨λ_, α → β, λe, e.to_equiv⟩ lemma coe_eq_to_equiv (h : α ≃ₜ β) (a : α) : h a = h.to_equiv a := rfl protected def refl (α : Type*) [topological_space α] : α ≃ₜ α := { continuous_to_fun := continuous_id, continuous_inv_fun := continuous_id, .. equiv.refl α } protected def trans (h₁ : α ≃ₜ β) (h₂ : β ≃ₜ γ) : α ≃ₜ γ := { continuous_to_fun := h₂.continuous_to_fun.comp h₁.continuous_to_fun, continuous_inv_fun := h₁.continuous_inv_fun.comp h₂.continuous_inv_fun, .. equiv.trans h₁.to_equiv h₂.to_equiv } protected def symm (h : α ≃ₜ β) : β ≃ₜ α := { continuous_to_fun := h.continuous_inv_fun, continuous_inv_fun := h.continuous_to_fun, .. h.to_equiv.symm } protected lemma continuous (h : α ≃ₜ β) : continuous h := h.continuous_to_fun lemma symm_comp_self (h : α ≃ₜ β) : ⇑h.symm ∘ ⇑h = id := funext $ assume a, h.to_equiv.left_inv a lemma self_comp_symm (h : α ≃ₜ β) : ⇑h ∘ ⇑h.symm = id := funext $ assume a, h.to_equiv.right_inv a lemma range_coe (h : α ≃ₜ β) : range h = univ := eq_univ_of_forall $ assume b, ⟨h.symm b, congr_fun h.self_comp_symm b⟩ lemma image_symm (h : α ≃ₜ β) : image h.symm = preimage h := funext h.symm.to_equiv.image_eq_preimage lemma preimage_symm (h : α ≃ₜ β) : preimage h.symm = image h := (funext h.to_equiv.image_eq_preimage).symm lemma induced_eq {α : Type*} {β : Type*} [tα : topological_space α] [tβ : topological_space β] (h : α ≃ₜ β) : tβ.induced h = tα := le_antisymm (calc topological_space.induced ⇑h tβ ≤ _ : induced_mono (coinduced_le_iff_le_induced.1 h.symm.continuous) ... ≤ tα : by rw [induced_compose, symm_comp_self, induced_id] ; exact le_refl _) (coinduced_le_iff_le_induced.1 h.continuous) lemma coinduced_eq {α : Type*} {β : Type*} [tα : topological_space α] [tβ : topological_space β] (h : α ≃ₜ β) : tα.coinduced h = tβ := le_antisymm h.continuous begin have : (tβ.coinduced h.symm).coinduced h ≤ tα.coinduced h := coinduced_mono h.symm.continuous, rwa [coinduced_compose, self_comp_symm, coinduced_id] at this, end lemma compact_image {s : set α} (h : α ≃ₜ β) : compact (h '' s) ↔ compact s := ⟨λ hs, by have := compact_image hs h.symm.continuous; rwa [← image_comp, symm_comp_self, image_id] at this, λ hs, compact_image hs h.continuous⟩ lemma compact_preimage {s : set β} (h : α ≃ₜ β) : compact (h ⁻¹' s) ↔ compact s := by rw ← image_symm; exact h.symm.compact_image protected lemma embedding (h : α ≃ₜ β) : embedding h := ⟨⟨h.induced_eq.symm⟩, h.to_equiv.injective⟩ protected lemma dense_embedding (h : α ≃ₜ β) : dense_embedding h := { dense := assume a, by rw [h.range_coe, closure_univ]; trivial, inj := h.to_equiv.injective, induced := (induced_iff_nhds_eq _).2 (assume a, by rw [← nhds_induced, h.induced_eq]) } protected lemma is_open_map (h : α ≃ₜ β) : is_open_map h := begin assume s, rw ← h.preimage_symm, exact h.symm.continuous s end protected lemma is_closed_map (h : α ≃ₜ β) : is_closed_map h := begin assume s, rw ← h.preimage_symm, exact continuous_iff_is_closed.1 (h.symm.continuous) _ end def homeomorph_of_continuous_open (e : α ≃ β) (h₁ : continuous e) (h₂ : is_open_map e) : α ≃ₜ β := { continuous_to_fun := h₁, continuous_inv_fun := begin intros s hs, convert ← h₂ s hs using 1, apply e.image_eq_preimage end, .. e } protected lemma quotient_map (h : α ≃ₜ β) : quotient_map h := ⟨h.to_equiv.surjective, h.coinduced_eq.symm⟩ def prod_congr (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) : α × γ ≃ₜ β × δ := { continuous_to_fun := continuous.prod_mk (h₁.continuous.comp continuous_fst) (h₂.continuous.comp continuous_snd), continuous_inv_fun := continuous.prod_mk (h₁.symm.continuous.comp continuous_fst) (h₂.symm.continuous.comp continuous_snd), .. h₁.to_equiv.prod_congr h₂.to_equiv } section variables (α β γ) def prod_comm : α × β ≃ₜ β × α := { continuous_to_fun := continuous.prod_mk continuous_snd continuous_fst, continuous_inv_fun := continuous.prod_mk continuous_snd continuous_fst, .. equiv.prod_comm α β } def prod_assoc : (α × β) × γ ≃ₜ α × (β × γ) := { continuous_to_fun := continuous.prod_mk (continuous_fst.comp continuous_fst) (continuous.prod_mk (continuous_snd.comp continuous_fst) continuous_snd), continuous_inv_fun := continuous.prod_mk (continuous.prod_mk continuous_fst (continuous_fst.comp continuous_snd)) (continuous_snd.comp continuous_snd), .. equiv.prod_assoc α β γ } end section distrib variables {ι : Type*} {σ : ι → Type*} [Π i, topological_space (σ i)] def sigma_prod_distrib : ((Σ i, σ i) × β) ≃ₜ (Σ i, (σ i × β)) := homeomorph.symm $ homeomorph_of_continuous_open (equiv.sigma_prod_distrib σ β).symm (continuous_sigma $ λ i, continuous.prod_mk (continuous_sigma_mk.comp continuous_fst) continuous_snd) (is_open_map_sigma $ λ i, (open_embedding.prod open_embedding_sigma_mk open_embedding_id).is_open_map) end distrib end homeomorph
ef43c1b94e3cbe5cf1b414c4a5fe9d0605e1d608
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/error_loc_bug.lean
ea773443824bb7b362094bf8da770684a056caab
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
3,220
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura Define propositional calculus, valuation, provability, validity, prove soundness. This file is based on Floris van Doorn Coq files. Similar to soundness.lean, but defines Nc in Type. The idea is to be able to prove soundness using recursive equations. -/ import data.nat data.list open nat bool list decidable definition PropVar [reducible] := nat inductive PropF := | Var : PropVar → PropF | Bot : PropF | Conj : PropF → PropF → PropF | Disj : PropF → PropF → PropF | Impl : PropF → PropF → PropF namespace PropF notation `#`:max P:max := Var P notation A ∨ B := Disj A B notation A ∧ B := Conj A B infixr `⇒`:27 := Impl notation `⊥` := Bot definition Neg A := A ⇒ ⊥ notation ~ A := Neg A definition Top := ~⊥ notation `⊤` := Top definition BiImpl A B := A ⇒ B ∧ B ⇒ A infixr `⇔`:27 := BiImpl definition valuation := PropVar → bool reserve infix ` ⊢ `:26 /- Provability -/ inductive Nc : list PropF → PropF → Type := infix ⊢ := Nc | Nax : ∀ Γ A, A ∈ Γ → Γ ⊢ A | ImpI : ∀ Γ A B, A::Γ ⊢ B → Γ ⊢ A ⇒ B | ImpE : ∀ Γ A B, Γ ⊢ A ⇒ B → Γ ⊢ A → Γ ⊢ B | BotC : ∀ Γ A, (~A)::Γ ⊢ ⊥ → Γ ⊢ A | AndI : ∀ Γ A B, Γ ⊢ A → Γ ⊢ B → Γ ⊢ A ∧ B | AndE₁ : ∀ Γ A B, Γ ⊢ A ∧ B → Γ ⊢ A | AndE₂ : ∀ Γ A B, Γ ⊢ A ∧ B → Γ ⊢ B | OrI₁ : ∀ Γ A B, Γ ⊢ A → Γ ⊢ A ∨ B | OrI₂ : ∀ Γ A B, Γ ⊢ B → Γ ⊢ A ∨ B | OrE : ∀ Γ A B C, Γ ⊢ A ∨ B → A::Γ ⊢ C → B::Γ ⊢ C → Γ ⊢ C infix ⊢ := Nc open Nc -- Remark ⌞t⌟ indicates we should not pattern match on t. -- In the following lemma, we only need to pattern match on Γ ⊢ A, -- by pattern matching on A, we would be creating 10*6 cases instead of 10. lemma weakening2 : ∀ {Γ A Δ}, Γ ⊢ A → Γ ⊆ Δ → Δ ⊢ A | Γ ⌞A⌟ Δ (Nax Γ A Hin) Hs := !Nax (Hs A Hin) | Γ ⌞A ⇒ B⌟ Δ (ImpI Γ A B H) Hs := !ImpI (weakening2 H (cons_sub_cons A Hs)) | Γ ⌞B⌟ Δ (ImpE Γ A B H₁ H₂) Hs := !ImpE (weakening2 H₁ Hs) (weakening2 H₂ Hs) | Γ ⌞A⌟ Δ (BotC Γ A H) Hs := !BotC (weakening2 H (cons_sub_cons (~A) Hs)) | Γ ⌞A ∧ B⌟ Δ (AndI Γ A B H₁ H₂) Hs := !AndI (weakening2 H₁ Hs) (weakening2 H₂ Hs) | Γ ⌞A⌟ Δ (AndE₁ Γ A B H) Hs := !AndE₁ (weakening2 H Hs) | Γ ⌞B⌟ Δ (AndE₂ Γ A B H) Hs := !AndE₂ (weakening2 H Hs) | Γ ⌞A ∧ B⌟ Δ (OrI₁ Γ A B H) Hs := !OrI₁ (weakening2 H Hs) | Γ ⌞A ∨ B⌟ Δ (OrI₂ Γ A B H) Hs := !OrI₂ (weakening2 H Hs) | Γ ⌞C⌟ Δ (OrE Γ A B C H₁ H₂ H₃) Hs := !OrE (weakening2 H₁ Hs) (weakening2 H₂ (cons_sub_cons A Hs)) (weakening2 H₃ (cons_sub_cons B Hs)) end PropF
3fef72216e917e8de6a0a5ee881ca3a35227d6e6
63abd62053d479eae5abf4951554e1064a4c45b4
/src/topology/metric_space/pi_Lp.lean
bb01f549d8ec78a0b7b49137935be00797869c9c
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
12,024
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.mean_inequalities /-! # `L^p` distance on finite products of metric spaces Given finitely many metric spaces, one can put the max distance on their product, but there is also a whole family of natural distances, indexed by a real parameter `p ∈ [1, ∞)`, that also induce the product topology. We define them in this file. The distance on `Π i, α i` is given by $$ d(x, y) = \left(\sum d(x_i, y_i)^p\right)^{1/p}. $$ We give instances of this construction for emetric spaces, metric spaces, normed groups and normed spaces. To avoid conflicting instances, all these are defined on a copy of the original Pi type, named `pi_Lp p hp α`, where `hp : 1 ≤ p`. This assumption is included in the definition of the type to make sure that it is always available to typeclass inference to construct the instances. We ensure that the topology and uniform structure on `pi_Lp p hp α` are (defeq to) the product topology and product uniformity, to be able to use freely continuity statements for the coordinate functions, for instance. ## Implementation notes We only deal with the `L^p` distance on a product of finitely many metric spaces, which may be distinct. A closely related construction is the `L^p` norm on the space of functions from a measure space to a normed space, where the norm is $$ \left(\int ∥f (x)∥^p dμ\right)^{1/p}. $$ However, the topology induced by this construction is not the product topology, this only defines a seminorm (as almost everywhere zero functions have zero `L^p` norm), and some functions have infinite `L^p` norm. All these subtleties are not present in the case of finitely many metric spaces (which corresponds to the basis which is a finite space with the counting measure), hence it is worth devoting a file to this specific case which is particularly well behaved. The general case is not yet formalized in mathlib. To prove that the topology (and the uniform structure) on a finite product with the `L^p` distance are the same as those coming from the `L^∞` distance, we could argue that the `L^p` and `L^∞` norms are equivalent on `ℝ^n` for abstract (norm equivalence) reasons. Instead, we give a more explicit (easy) proof which provides a comparison between these two norms with explicit constants. -/ open real set filter open_locale big_operators uniformity topological_space noncomputable theory variables {ι : Type*} /-- A copy of a Pi type, on which we will put the `L^p` distance. Since the Pi type itself is already endowed with the `L^∞` distance, we need the type synonym to avoid confusing typeclass resolution. Also, we let it depend on `p`, to get a whole family of type on which we can put different distances, and we provide the assumption `hp` in the definition, to make it available to typeclass resolution when it looks for a distance on `pi_Lp p hp α`. -/ @[nolint unused_arguments] def pi_Lp {ι : Type*} (p : ℝ) (hp : 1 ≤ p) (α : ι → Type*) : Type* := Π (i : ι), α i instance {ι : Type*} (p : ℝ) (hp : 1 ≤ p) (α : ι → Type*) [∀ i, inhabited (α i)] : inhabited (pi_Lp p hp α) := ⟨λ i, default (α i)⟩ namespace pi_Lp variables (p : ℝ) (hp : 1 ≤ p) (α : ι → Type*) /-- Canonical bijection between `pi_Lp p hp α` and the original Pi type. We introduce it to be able to compare the `L^p` and `L^∞` distances through it. -/ protected def equiv : pi_Lp p hp α ≃ Π (i : ι), α i := equiv.refl _ section /-! ### The uniformity on finite `L^p` products is the product uniformity In this section, we put the `L^p` edistance on `pi_Lp p hp α`, and we check that the uniformity coming from this edistance coincides with the product uniformity, by showing that the canonical map to the Pi type (with the `L^∞` distance) is a uniform embedding, as it is both Lipschitz and antiLipschitz. We only register this emetric space structure as a temporary instance, as the true instance (to be registered later) will have as uniformity exactly the product uniformity, instead of the one coming from the edistance (which is equal to it, but not defeq). See Note [forgetful inheritance] explaining why having definitionally the right uniformity is often important. -/ variables [∀ i, emetric_space (α i)] [fintype ι] /-- Endowing the space `pi_Lp p hp α` with the `L^p` edistance. This definition is not satisfactory, as it does not register the fact that the topology and the uniform structure coincide with the product one. Therefore, we do not register it as an instance. Using this as a temporary emetric space instance, we will show that the uniform structure is equal (but not defeq) to the product one, and then register an instance in which we replace the uniform structure by the product one using this emetric space and `emetric_space.replace_uniformity`. -/ def emetric_aux : emetric_space (pi_Lp p hp α) := have pos : 0 < p := lt_of_lt_of_le zero_lt_one hp, { edist := λ f g, (∑ (i : ι), (edist (f i) (g i)) ^ p) ^ (1/p), edist_self := λ f, by simp [edist, ennreal.zero_rpow_of_pos pos, ennreal.zero_rpow_of_pos (inv_pos.2 pos)], edist_comm := λ f g, by simp [edist, edist_comm], edist_triangle := λ f g h, calc (∑ (i : ι), edist (f i) (h i) ^ p) ^ (1 / p) ≤ (∑ (i : ι), (edist (f i) (g i) + edist (g i) (h i)) ^ p) ^ (1 / p) : begin apply ennreal.rpow_le_rpow _ (one_div_nonneg.2 $ le_of_lt pos), refine finset.sum_le_sum (λ i hi, _), exact ennreal.rpow_le_rpow (edist_triangle _ _ _) (le_trans zero_le_one hp) end ... ≤ (∑ (i : ι), edist (f i) (g i) ^ p) ^ (1 / p) + (∑ (i : ι), edist (g i) (h i) ^ p) ^ (1 / p) : ennreal.Lp_add_le _ _ _ hp, eq_of_edist_eq_zero := λ f g hfg, begin simp [edist, ennreal.rpow_eq_zero_iff, pos, asymm pos, finset.sum_eq_zero_iff_of_nonneg] at hfg, exact funext hfg end } local attribute [instance] pi_Lp.emetric_aux lemma lipschitz_with_equiv : lipschitz_with 1 (pi_Lp.equiv p hp α) := begin have pos : 0 < p := lt_of_lt_of_le zero_lt_one hp, have cancel : p * (1/p) = 1 := mul_div_cancel' 1 (ne_of_gt pos), assume x y, simp only [edist, forall_prop_of_true, one_mul, finset.mem_univ, finset.sup_le_iff, ennreal.coe_one], assume i, calc edist (x i) (y i) = (edist (x i) (y i) ^ p) ^ (1/p) : by simp [← ennreal.rpow_mul, cancel, -one_div] ... ≤ (∑ (i : ι), edist (x i) (y i) ^ p) ^ (1 / p) : begin apply ennreal.rpow_le_rpow _ (one_div_nonneg.2 $ le_of_lt pos), exact finset.single_le_sum (λ i hi, (bot_le : (0 : ennreal) ≤ _)) (finset.mem_univ i) end end lemma antilipschitz_with_equiv : antilipschitz_with ((fintype.card ι : nnreal) ^ (1/p)) (pi_Lp.equiv p hp α) := begin have pos : 0 < p := lt_of_lt_of_le zero_lt_one hp, have nonneg : 0 ≤ 1 / p := one_div_nonneg.2 (le_of_lt pos), have cancel : p * (1/p) = 1 := mul_div_cancel' 1 (ne_of_gt pos), assume x y, simp [edist, -one_div], calc (∑ (i : ι), edist (x i) (y i) ^ p) ^ (1 / p) ≤ (∑ (i : ι), edist (pi_Lp.equiv p hp α x) (pi_Lp.equiv p hp α y) ^ p) ^ (1 / p) : begin apply ennreal.rpow_le_rpow _ nonneg, apply finset.sum_le_sum (λ i hi, _), apply ennreal.rpow_le_rpow _ (le_of_lt pos), exact finset.le_sup (finset.mem_univ i) end ... = (((fintype.card ι : nnreal)) ^ (1/p) : nnreal) * edist (pi_Lp.equiv p hp α x) (pi_Lp.equiv p hp α y) : begin simp only [nsmul_eq_mul, finset.card_univ, ennreal.rpow_one, finset.sum_const, ennreal.mul_rpow_of_nonneg _ _ nonneg, ←ennreal.rpow_mul, cancel], have : (fintype.card ι : ennreal) = (fintype.card ι : nnreal) := (ennreal.coe_nat (fintype.card ι)).symm, rw [this, ennreal.coe_rpow_of_nonneg _ nonneg] end end lemma aux_uniformity_eq : 𝓤 (pi_Lp p hp α) = @uniformity _ (Pi.uniform_space _) := begin have A : uniform_embedding (pi_Lp.equiv p hp α) := (antilipschitz_with_equiv p hp α).uniform_embedding (lipschitz_with_equiv p hp α).uniform_continuous, have : (λ (x : pi_Lp p hp α × pi_Lp p hp α), ((pi_Lp.equiv p hp α) x.fst, (pi_Lp.equiv p hp α) x.snd)) = id, by ext i; refl, rw [← A.comap_uniformity, this, comap_id] end end /-! ### Instances on finite `L^p` products -/ instance uniform_space [∀ i, uniform_space (α i)] : uniform_space (pi_Lp p hp α) := Pi.uniform_space _ variable [fintype ι] /-- emetric space instance on the product of finitely many emetric spaces, using the `L^p` edistance, and having as uniformity the product uniformity. -/ instance [∀ i, emetric_space (α i)] : emetric_space (pi_Lp p hp α) := (emetric_aux p hp α).replace_uniformity (aux_uniformity_eq p hp α).symm protected lemma edist {p : ℝ} {hp : 1 ≤ p} {α : ι → Type*} [∀ i, emetric_space (α i)] (x y : pi_Lp p hp α) : edist x y = (∑ (i : ι), (edist (x i) (y i)) ^ p) ^ (1/p) := rfl /-- metric space instance on the product of finitely many metric spaces, using the `L^p` distance, and having as uniformity the product uniformity. -/ instance [∀ i, metric_space (α i)] : metric_space (pi_Lp p hp α) := begin /- we construct the instance from the emetric space instance to avoid checking again that the uniformity is the same as the product uniformity, but we register nevertheless a nice formula for the distance -/ have pos : 0 < p := lt_of_lt_of_le zero_lt_one hp, refine emetric_space.to_metric_space_of_dist (λf g, (∑ (i : ι), (dist (f i) (g i)) ^ p) ^ (1/p)) (λ f g, _) (λ f g, _), { simp [pi_Lp.edist, ennreal.rpow_eq_top_iff, asymm pos, pos, ennreal.sum_eq_top_iff, edist_ne_top] }, { have A : ∀ (i : ι), i ∈ (finset.univ : finset ι) → edist (f i) (g i) ^ p < ⊤ := λ i hi, by simp [lt_top_iff_ne_top, edist_ne_top, le_of_lt pos], simp [dist, -one_div, pi_Lp.edist, ← ennreal.to_real_rpow, ennreal.to_real_sum A, dist_edist] } end protected lemma dist {p : ℝ} {hp : 1 ≤ p} {α : ι → Type*} [∀ i, metric_space (α i)] (x y : pi_Lp p hp α) : dist x y = (∑ (i : ι), (dist (x i) (y i)) ^ p) ^ (1/p) := rfl /-- normed group instance on the product of finitely many normed groups, using the `L^p` norm. -/ instance normed_group [∀i, normed_group (α i)] : normed_group (pi_Lp p hp α) := { norm := λf, (∑ (i : ι), norm (f i) ^ p) ^ (1/p), dist_eq := λ x y, by { simp [pi_Lp.dist, dist_eq_norm] }, .. pi.add_comm_group } lemma norm_eq {p : ℝ} {hp : 1 ≤ p} {α : ι → Type*} [∀i, normed_group (α i)] (f : pi_Lp p hp α) : ∥f∥ = (∑ (i : ι), ∥f i∥ ^ p) ^ (1/p) := rfl variables (𝕜 : Type*) [normed_field 𝕜] /-- The product of finitely many normed spaces is a normed space, with the `L^p` norm. -/ instance normed_space [∀i, normed_group (α i)] [∀i, normed_space 𝕜 (α i)] : normed_space 𝕜 (pi_Lp p hp α) := { norm_smul_le := begin assume c f, have : p * (1 / p) = 1 := mul_div_cancel' 1 (ne_of_gt (lt_of_lt_of_le zero_lt_one hp)), simp only [pi_Lp.norm_eq, norm_smul, mul_rpow, norm_nonneg, ←finset.mul_sum, pi.smul_apply], rw [mul_rpow (rpow_nonneg_of_nonneg (norm_nonneg _) _), ← rpow_mul (norm_nonneg _), this, rpow_one], exact finset.sum_nonneg (λ i hi, rpow_nonneg_of_nonneg (norm_nonneg _) _) end, .. pi.semimodule ι α 𝕜 } /- Register simplification lemmas for the applications of `pi_Lp` elements, as the usual lemmas for Pi types will not trigger. -/ variables {𝕜 p hp α} [∀i, normed_group (α i)] [∀i, normed_space 𝕜 (α i)] (c : 𝕜) (x y : pi_Lp p hp α) (i : ι) @[simp] lemma add_apply : (x + y) i = x i + y i := rfl @[simp] lemma sub_apply : (x - y) i = x i - y i := rfl @[simp] lemma smul_apply : (c • x) i = c • x i := rfl @[simp] lemma neg_apply : (-x) i = - (x i) := rfl end pi_Lp
b9415d588c82f04759b2cb5901f337bdc5b223fa
af6139dd14451ab8f69cf181cf3a20f22bd699be
/library/init/meta/relation_tactics.lean
8d9badbcd2d4cfd0119e88787959052bd6dde822
[ "Apache-2.0" ]
permissive
gitter-badger/lean-1
1cca01252d3113faa45681b6a00e1b5e3a0f6203
5c7ade4ee4f1cdf5028eabc5db949479d6737c85
refs/heads/master
1,611,425,383,521
1,487,871,140,000
1,487,871,140,000
82,995,612
0
0
null
1,487,905,618,000
1,487,905,618,000
null
UTF-8
Lean
false
false
1,536
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.function namespace tactic open expr private meta def relation_tactic (md : transparency) (op_for : environment → name → option name) (tac_name : string) : tactic unit := do tgt ← target, env ← get_env, r ← return $ get_app_fn tgt, match (op_for env (const_name r)) with | (some refl) := do r ← mk_const refl, apply_core r {md := md} >> return () | none := fail $ tac_name ++ " tactic failed, target is not a relation application with the expected property." end meta def reflexivity (md := semireducible) : tactic unit := relation_tactic md environment.refl_for "reflexivity" meta def symmetry (md := semireducible) : tactic unit := relation_tactic md environment.symm_for "symmetry" meta def transitivity (md := semireducible) : tactic unit := relation_tactic md environment.trans_for "transitivity" meta def relation_lhs_rhs : expr → tactic (name × expr × expr) := λ e, do (const c _) ← return e^.get_app_fn, env ← get_env, (some (arity, lhs_pos, rhs_pos)) ← return $ env^.relation_info c, args ← return $ get_app_args e, guard (args^.length = arity), (some lhs) ← return $ args^.nth lhs_pos, (some rhs) ← return $ args^.nth rhs_pos, return (c, lhs, rhs) meta def target_lhs_rhs : tactic (name × expr × expr) := target >>= relation_lhs_rhs end tactic
4bc42eb5bfe4584ab18915c66eb56020030ba218
ed27983dd289b3bcad416f0b1927105d6ef19db8
/src/inClassNotes/predicate_logic/impl.lean
d58975e18d4f60995d0590852084c9021d284aa9
[]
no_license
liuxin-James/complogic-s21
0d55b76dbe25024473d31d98b5b83655c365f811
13e03e0114626643b44015c654151fb651603486
refs/heads/master
1,681,109,264,463
1,618,848,261,000
1,618,848,261,000
337,599,491
0
0
null
1,613,141,619,000
1,612,925,555,000
null
UTF-8
Lean
false
false
1,601
lean
/- If P and Q are propositions, then P → Q is a proposition, as well. We just such an implication to be true if whenever P is true Q must be true as well. To prove P → Q, we thus *assume* that P is true (and in constructive logic this means we assume we have a proof of it, p : P), and in the context of this assumption, we show that Q must be true, in the sense that we can produce evidence (q : Q) that this is the case. This is a long way of saying that to prove P → Q, we assume we have a proof of P and in this context we must produce a proof of Q. In the constructive logic of Lean, this means we prove P → Q by showing that there is a function of type P to Q! Of course a function of this type is really a function of type ∀ (p : P), Q, which is notation for Π (p : P), Q which is just a non-dependent function type, P → Q. It all makes sense! -/ lemma and_commutes' : ∀ {P Q : Prop}, P ∧ Q → Q ∧ P := λ P Q h, and.intro (h.right) (h.left) /- This is the introduction rule for →. Assume you have a proof of the antcedent (P ∧ Q in this case) and show that in that context there is a proof of the conclusion (Q ∧ P). -/ /- Elimination -/ axioms (Person : Type) (fromCville : Person → Prop) axioms (Kevin Liu : Person) (kfc : fromCville Kevin) (lfc : fromCville Liu) -- let's construct a proof of fromCville Kevin ∧ fromCville Liu (P ∧ Q) theorem bfc : fromCville Kevin ∧ fromCville Liu := and.intro kfc lfc #check bfc #reduce bfc -- now we can *apply* and_commutes' to derive a proof of (Q ∧ P) #check and_commutes' bfc #reduce and_commutes' bfc
a93995df3332484782b1fb905a8b22ad3c62701a
271e26e338b0c14544a889c31c30b39c989f2e0f
/stage0/src/Init/System/FilePath.lean
fab5c64d5cc1e04496a6441a3bbae66b007230f1
[ "Apache-2.0" ]
permissive
dgorokho/lean4
805f99b0b60c545b64ac34ab8237a8504f89d7d4
e949a052bad59b1c7b54a82d24d516a656487d8a
refs/heads/master
1,607,061,363,851
1,578,006,086,000
1,578,006,086,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,629
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 -/ prelude import Init.System.Platform import Init.Data.String.Basic namespace System namespace FilePath open Platform /-- The character that separates directories. In the case where more than one character is possible, `pathSeparator` is the 'ideal' one. -/ def pathSeparator : Char := if isWindows then '\\' else '/' /-- The list of all possible separators. -/ def pathSeparators : List Char := if isWindows then ['\\', '/'] else ['/'] /-- The character that is used to separate the entries in the $PATH environment variable. -/ def searchPathSeparator : Char := if isWindows then ';' else ':' /-- The list of all possible separators. -/ def searchPathSeparators : List Char := if isWindows then [';', ':'] else [':'] def splitSearchPath (s : String) : List String := s.split (fun c => searchPathSeparators.elem c) /-- File extension character -/ def extSeparator : Char := '.' /-- Case-insensitive file system -/ def isCaseInsensitive : Bool := isWindows || isOSX def normalizePath (fname : String) : String := if pathSeparators.length == 1 && !isCaseInsensitive then fname else fname.map (fun c => if pathSeparators.any (fun c' => c == c') then pathSeparator -- else if isCaseInsensitive then c.toLower else c) def dirName (fname : String) : String := let fname := normalizePath fname; match fname.revPosOf pathSeparator with | none => "." | some pos => { Substring . str := fname, startPos := 0, stopPos := pos }.toString end FilePath end System
196d43388c8b0e9db16da8e4cfc6febe6ca61e34
9028d228ac200bbefe3a711342514dd4e4458bff
/src/order/bounded_lattice.lean
187f7f3fdf7abeb1b854cb684df535bc991efe82
[ "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
40,791
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 Defines bounded lattice type class hierarchy. Includes the Prop and fun instances. -/ import order.lattice import data.option.basic import tactic.pi_instances set_option old_structure_cmd true universes u v variables {α : Type u} {β : Type v} /-- Typeclass for the `⊤` (`\top`) notation -/ class has_top (α : Type u) := (top : α) /-- Typeclass for the `⊥` (`\bot`) notation -/ class has_bot (α : Type u) := (bot : α) notation `⊤` := has_top.top notation `⊥` := has_bot.bot attribute [pattern] has_bot.bot has_top.top /-- An `order_top` is a partial order with a maximal element. (We could state this on preorders, but then it wouldn't be unique so distinguishing one would seem odd.) -/ class order_top (α : Type u) extends has_top α, partial_order α := (le_top : ∀ a : α, a ≤ ⊤) section order_top variables [order_top α] {a b : α} @[simp] theorem le_top : a ≤ ⊤ := order_top.le_top a theorem top_unique (h : ⊤ ≤ a) : a = ⊤ := le_antisymm le_top h -- TODO: delete in favor of the next? theorem eq_top_iff : a = ⊤ ↔ ⊤ ≤ a := ⟨assume eq, eq.symm ▸ le_refl ⊤, top_unique⟩ @[simp] theorem top_le_iff : ⊤ ≤ a ↔ a = ⊤ := ⟨top_unique, λ h, h.symm ▸ le_refl ⊤⟩ @[simp] theorem not_top_lt : ¬ ⊤ < a := assume h, lt_irrefl a (lt_of_le_of_lt le_top h) theorem eq_top_mono (h : a ≤ b) (h₂ : a = ⊤) : b = ⊤ := top_le_iff.1 $ h₂ ▸ h lemma lt_top_iff_ne_top : a < ⊤ ↔ a ≠ ⊤ := begin haveI := classical.dec_eq α, haveI : decidable (⊤ ≤ a) := decidable_of_iff' _ top_le_iff, by simp [-top_le_iff, lt_iff_le_not_le, not_iff_not.2 (@top_le_iff _ _ a)] end lemma ne_top_of_lt (h : a < b) : a ≠ ⊤ := lt_top_iff_ne_top.1 $ lt_of_lt_of_le h le_top theorem ne_top_of_le_ne_top {a b : α} (hb : b ≠ ⊤) (hab : a ≤ b) : a ≠ ⊤ := assume ha, hb $ top_unique $ ha ▸ hab end order_top lemma strict_mono.top_preimage_top' [linear_order α] [order_top β] {f : α → β} (H : strict_mono f) {a} (h_top : f a = ⊤) (x : α) : x ≤ a := H.top_preimage_top (λ p, by { rw h_top, exact le_top }) x theorem order_top.ext_top {α} {A B : order_top α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : (by haveI := A; exact ⊤ : α) = ⊤ := top_unique $ by rw ← H; apply le_top theorem order_top.ext {α} {A B : order_top α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have := partial_order.ext H, have tt := order_top.ext_top H, casesI A, casesI B, injection this; congr' end /-- An `order_bot` is a partial order with a minimal element. (We could state this on preorders, but then it wouldn't be unique so distinguishing one would seem odd.) -/ class order_bot (α : Type u) extends has_bot α, partial_order α := (bot_le : ∀ a : α, ⊥ ≤ a) section order_bot variables [order_bot α] {a b : α} @[simp] theorem bot_le : ⊥ ≤ a := order_bot.bot_le a theorem bot_unique (h : a ≤ ⊥) : a = ⊥ := le_antisymm h bot_le -- TODO: delete? theorem eq_bot_iff : a = ⊥ ↔ a ≤ ⊥ := ⟨assume eq, eq.symm ▸ le_refl ⊥, bot_unique⟩ @[simp] theorem le_bot_iff : a ≤ ⊥ ↔ a = ⊥ := ⟨bot_unique, assume h, h.symm ▸ le_refl ⊥⟩ @[simp] theorem not_lt_bot : ¬ a < ⊥ := assume h, lt_irrefl a (lt_of_lt_of_le h bot_le) theorem ne_bot_of_le_ne_bot {a b : α} (hb : b ≠ ⊥) (hab : b ≤ a) : a ≠ ⊥ := assume ha, hb $ bot_unique $ ha ▸ hab theorem eq_bot_mono (h : a ≤ b) (h₂ : b = ⊥) : a = ⊥ := le_bot_iff.1 $ h₂ ▸ h lemma bot_lt_iff_ne_bot : ⊥ < a ↔ a ≠ ⊥ := begin haveI := classical.dec_eq α, haveI : decidable (a ≤ ⊥) := decidable_of_iff' _ le_bot_iff, simp [-le_bot_iff, lt_iff_le_not_le, not_iff_not.2 (@le_bot_iff _ _ a)] end lemma ne_bot_of_gt (h : a < b) : b ≠ ⊥ := bot_lt_iff_ne_bot.1 $ lt_of_le_of_lt bot_le h end order_bot lemma strict_mono.bot_preimage_bot' [linear_order α] [order_bot β] {f : α → β} (H : strict_mono f) {a} (h_bot : f a = ⊥) (x : α) : a ≤ x := H.bot_preimage_bot (λ p, by { rw h_bot, exact bot_le }) x theorem order_bot.ext_bot {α} {A B : order_bot α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : (by haveI := A; exact ⊥ : α) = ⊥ := bot_unique $ by rw ← H; apply bot_le theorem order_bot.ext {α} {A B : order_bot α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have := partial_order.ext H, have tt := order_bot.ext_bot H, casesI A, casesI B, injection this; congr' end /-- A `semilattice_sup_top` is a semilattice with top and join. -/ class semilattice_sup_top (α : Type u) extends order_top α, semilattice_sup α section semilattice_sup_top variables [semilattice_sup_top α] {a : α} @[simp] theorem top_sup_eq : ⊤ ⊔ a = ⊤ := sup_of_le_left le_top @[simp] theorem sup_top_eq : a ⊔ ⊤ = ⊤ := sup_of_le_right le_top end semilattice_sup_top /-- A `semilattice_sup_bot` is a semilattice with bottom and join. -/ class semilattice_sup_bot (α : Type u) extends order_bot α, semilattice_sup α section semilattice_sup_bot variables [semilattice_sup_bot α] {a b : α} @[simp] theorem bot_sup_eq : ⊥ ⊔ a = a := sup_of_le_right bot_le @[simp] theorem sup_bot_eq : a ⊔ ⊥ = a := sup_of_le_left bot_le @[simp] theorem sup_eq_bot_iff : a ⊔ b = ⊥ ↔ (a = ⊥ ∧ b = ⊥) := by rw [eq_bot_iff, sup_le_iff]; simp end semilattice_sup_bot instance nat.semilattice_sup_bot : semilattice_sup_bot ℕ := { bot := 0, bot_le := nat.zero_le, .. nat.distrib_lattice } /-- A `semilattice_inf_top` is a semilattice with top and meet. -/ class semilattice_inf_top (α : Type u) extends order_top α, semilattice_inf α section semilattice_inf_top variables [semilattice_inf_top α] {a b : α} @[simp] theorem top_inf_eq : ⊤ ⊓ a = a := inf_of_le_right le_top @[simp] theorem inf_top_eq : a ⊓ ⊤ = a := inf_of_le_left le_top @[simp] theorem inf_eq_top_iff : a ⊓ b = ⊤ ↔ (a = ⊤ ∧ b = ⊤) := by rw [eq_top_iff, le_inf_iff]; simp end semilattice_inf_top /-- A `semilattice_inf_bot` is a semilattice with bottom and meet. -/ class semilattice_inf_bot (α : Type u) extends order_bot α, semilattice_inf α section semilattice_inf_bot variables [semilattice_inf_bot α] {a : α} @[simp] theorem bot_inf_eq : ⊥ ⊓ a = ⊥ := inf_of_le_left bot_le @[simp] theorem inf_bot_eq : a ⊓ ⊥ = ⊥ := inf_of_le_right bot_le end semilattice_inf_bot /- Bounded lattices -/ /-- A bounded lattice is a lattice with a top and bottom element, denoted `⊤` and `⊥` respectively. This allows for the interpretation of all finite suprema and infima, taking `inf ∅ = ⊤` and `sup ∅ = ⊥`. -/ class bounded_lattice (α : Type u) extends lattice α, order_top α, order_bot α @[priority 100] -- see Note [lower instance priority] instance semilattice_inf_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_inf_top α := { le_top := assume x, @le_top α _ x, ..bl } @[priority 100] -- see Note [lower instance priority] instance semilattice_inf_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_inf_bot α := { bot_le := assume x, @bot_le α _ x, ..bl } @[priority 100] -- see Note [lower instance priority] instance semilattice_sup_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_sup_top α := { le_top := assume x, @le_top α _ x, ..bl } @[priority 100] -- see Note [lower instance priority] instance semilattice_sup_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_sup_bot α := { bot_le := assume x, @bot_le α _ x, ..bl } theorem bounded_lattice.ext {α} {A B : bounded_lattice α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have H1 : @bounded_lattice.to_lattice α A = @bounded_lattice.to_lattice α B := lattice.ext H, have H2 := order_bot.ext H, have H3 : @bounded_lattice.to_order_top α A = @bounded_lattice.to_order_top α B := order_top.ext H, have tt := order_bot.ext_bot H, casesI A, casesI B, injection H1; injection H2; injection H3; congr' end /-- A bounded distributive lattice is exactly what it sounds like. -/ class bounded_distrib_lattice α extends distrib_lattice α, bounded_lattice α lemma inf_eq_bot_iff_le_compl {α : Type u} [bounded_distrib_lattice α] {a b c : α} (h₁ : b ⊔ c = ⊤) (h₂ : b ⊓ c = ⊥) : a ⊓ b = ⊥ ↔ a ≤ c := ⟨assume : a ⊓ b = ⊥, calc a ≤ a ⊓ (b ⊔ c) : by simp [h₁] ... = (a ⊓ b) ⊔ (a ⊓ c) : by simp [inf_sup_left] ... ≤ c : by simp [this, inf_le_right], assume : a ≤ c, bot_unique $ calc a ⊓ b ≤ b ⊓ c : by { rw [inf_comm], exact inf_le_inf_left _ this } ... = ⊥ : h₂⟩ /- Prop instance -/ instance bounded_distrib_lattice_Prop : bounded_distrib_lattice Prop := { le := λa b, a → b, le_refl := assume _, id, le_trans := assume a b c f g, g ∘ f, le_antisymm := assume a b Hab Hba, propext ⟨Hab, Hba⟩, sup := or, le_sup_left := @or.inl, le_sup_right := @or.inr, sup_le := assume a b c, or.rec, inf := and, inf_le_left := @and.left, inf_le_right := @and.right, le_inf := assume a b c Hab Hac Ha, and.intro (Hab Ha) (Hac Ha), le_sup_inf := assume a b c H, or_iff_not_imp_left.2 $ λ Ha, ⟨H.1.resolve_left Ha, H.2.resolve_left Ha⟩, top := true, le_top := assume a Ha, true.intro, bot := false, bot_le := @false.elim } instance Prop.linear_order : linear_order Prop := { le_total := by intros p q; change (p → q) ∨ (q → p); tauto!, .. (_ : partial_order Prop) } @[simp] lemma le_iff_imp {p q : Prop} : p ≤ q ↔ (p → q) := iff.rfl section logic variable [preorder α] theorem monotone_and {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) : monotone (λx, p x ∧ q x) := assume a b h, and.imp (m_p h) (m_q h) -- Note: by finish [monotone] doesn't work theorem monotone_or {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) : monotone (λx, p x ∨ q x) := assume a b h, or.imp (m_p h) (m_q h) end logic instance pi.order_bot {α : Type*} {β : α → Type*} [∀ a, order_bot $ β a] : order_bot (Π a, β a) := { bot := λ _, ⊥, bot_le := λ x a, bot_le, .. pi.partial_order } /- Function lattices -/ instance pi.has_sup {ι : Type*} {α : ι → Type*} [Π i, has_sup (α i)] : has_sup (Π i, α i) := ⟨λ f g i, f i ⊔ g i⟩ @[simp] lemma sup_apply {ι : Type*} {α : ι → Type*} [Π i, has_sup (α i)] (f g : Π i, α i) (i : ι) : (f ⊔ g) i = f i ⊔ g i := rfl instance pi.has_inf {ι : Type*} {α : ι → Type*} [Π i, has_inf (α i)] : has_inf (Π i, α i) := ⟨λ f g i, f i ⊓ g i⟩ @[simp] lemma inf_apply {ι : Type*} {α : ι → Type*} [Π i, has_inf (α i)] (f g : Π i, α i) (i : ι) : (f ⊓ g) i = f i ⊓ g i := rfl instance pi.has_bot {ι : Type*} {α : ι → Type*} [Π i, has_bot (α i)] : has_bot (Π i, α i) := ⟨λ i, ⊥⟩ @[simp] lemma bot_apply {ι : Type*} {α : ι → Type*} [Π i, has_bot (α i)] (i : ι) : (⊥ : Π i, α i) i = ⊥ := rfl instance pi.has_top {ι : Type*} {α : ι → Type*} [Π i, has_top (α i)] : has_top (Π i, α i) := ⟨λ i, ⊤⟩ @[simp] lemma top_apply {ι : Type*} {α : ι → Type*} [Π i, has_top (α i)] (i : ι) : (⊤ : Π i, α i) i = ⊤ := rfl @[simps] instance pi.semilattice_sup {ι : Type*} {α : ι → Type*} [Π i, semilattice_sup (α i)] : semilattice_sup (Π i, α i) := by refine_struct { sup := (⊔), .. pi.partial_order }; tactic.pi_instance_derive_field @[simps] instance pi.semilattice_inf {ι : Type*} {α : ι → Type*} [Π i, semilattice_inf (α i)] : semilattice_inf (Π i, α i) := by refine_struct { inf := (⊓), .. pi.partial_order }; tactic.pi_instance_derive_field @[simps] instance pi.semilattice_inf_bot {ι : Type*} {α : ι → Type*} [Π i, semilattice_inf_bot (α i)] : semilattice_inf_bot (Π i, α i) := by refine_struct { inf := (⊓), bot := ⊥, .. pi.partial_order }; tactic.pi_instance_derive_field @[simps] instance pi.semilattice_inf_top {ι : Type*} {α : ι → Type*} [Π i, semilattice_inf_top (α i)] : semilattice_inf_top (Π i, α i) := by refine_struct { inf := (⊓), top := ⊤, .. pi.partial_order }; tactic.pi_instance_derive_field @[simps] instance pi.semilattice_sup_bot {ι : Type*} {α : ι → Type*} [Π i, semilattice_sup_bot (α i)] : semilattice_sup_bot (Π i, α i) := by refine_struct { sup := (⊔), bot := ⊥, .. pi.partial_order }; tactic.pi_instance_derive_field @[simps] instance pi.semilattice_sup_top {ι : Type*} {α : ι → Type*} [Π i, semilattice_sup_top (α i)] : semilattice_sup_top (Π i, α i) := by refine_struct { sup := (⊔), top := ⊤, .. pi.partial_order }; tactic.pi_instance_derive_field @[simps] instance pi.lattice {ι : Type*} {α : ι → Type*} [Π i, lattice (α i)] : lattice (Π i, α i) := { .. pi.semilattice_sup, .. pi.semilattice_inf } @[simps] instance pi.bounded_lattice {ι : Type*} {α : ι → Type*} [Π i, bounded_lattice (α i)] : bounded_lattice (Π i, α i) := { .. pi.semilattice_sup_top, .. pi.semilattice_inf_bot } lemma eq_bot_of_bot_eq_top {α : Type*} [bounded_lattice α] (hα : (⊥ : α) = ⊤) (x : α) : x = (⊥ : α) := eq_bot_mono le_top (eq.symm hα) lemma eq_top_of_bot_eq_top {α : Type*} [bounded_lattice α] (hα : (⊥ : α) = ⊤) (x : α) : x = (⊤ : α) := eq_top_mono bot_le hα lemma subsingleton_of_bot_eq_top {α : Type*} [bounded_lattice α] (hα : (⊥ : α) = (⊤ : α)) : subsingleton α := ⟨λ a b, by rw [eq_bot_of_bot_eq_top hα a, eq_bot_of_bot_eq_top hα b]⟩ /-- Attach `⊥` to a type. -/ def with_bot (α : Type*) := option α namespace with_bot meta instance {α} [has_to_format α] : has_to_format (with_bot α) := { to_format := λ x, match x with | none := "⊥" | (some x) := to_fmt x end } instance : has_coe_t α (with_bot α) := ⟨some⟩ instance has_bot : has_bot (with_bot α) := ⟨none⟩ instance : inhabited (with_bot α) := ⟨⊥⟩ lemma none_eq_bot : (none : with_bot α) = (⊥ : with_bot α) := rfl lemma some_eq_coe (a : α) : (some a : with_bot α) = (↑a : with_bot α) := rfl /-- Recursor for `with_bot` using the preferred forms `⊥` and `↑a`. -/ @[elab_as_eliminator] def rec_bot_coe {C : with_bot α → Sort*} (h₁ : C ⊥) (h₂ : Π (a : α), C a) : Π (n : with_bot α), C n := option.rec h₁ h₂ @[norm_cast] theorem coe_eq_coe {a b : α} : (a : with_bot α) = b ↔ a = b := by rw [← option.some.inj_eq a b]; refl @[priority 10] instance has_lt [has_lt α] : has_lt (with_bot α) := { lt := λ o₁ o₂ : option α, ∃ b ∈ o₂, ∀ a ∈ o₁, a < b } @[simp] theorem some_lt_some [has_lt α] {a b : α} : @has_lt.lt (with_bot α) _ (some a) (some b) ↔ a < b := by simp [(<)] lemma bot_lt_some [has_lt α] (a : α) : (⊥ : with_bot α) < some a := ⟨a, rfl, λ b hb, (option.not_mem_none _ hb).elim⟩ lemma bot_lt_coe [has_lt α] (a : α) : (⊥ : with_bot α) < a := bot_lt_some a instance [preorder α] : preorder (with_bot α) := { le := λ o₁ o₂ : option α, ∀ a ∈ o₁, ∃ b ∈ o₂, a ≤ b, lt := (<), lt_iff_le_not_le := by intros; cases a; cases b; simp [lt_iff_le_not_le]; simp [(<)]; split; refl, le_refl := λ o a ha, ⟨a, ha, le_refl _⟩, le_trans := λ o₁ o₂ o₃ h₁ h₂ a ha, let ⟨b, hb, ab⟩ := h₁ a ha, ⟨c, hc, bc⟩ := h₂ b hb in ⟨c, hc, le_trans ab bc⟩ } instance partial_order [partial_order α] : partial_order (with_bot α) := { le_antisymm := λ o₁ o₂ h₁ h₂, begin cases o₁ with a, { cases o₂ with b, {refl}, rcases h₂ b rfl with ⟨_, ⟨⟩, _⟩ }, { rcases h₁ a rfl with ⟨b, ⟨⟩, h₁'⟩, rcases h₂ b rfl with ⟨_, ⟨⟩, h₂'⟩, rw le_antisymm h₁' h₂' } end, .. with_bot.preorder } instance order_bot [partial_order α] : order_bot (with_bot α) := { bot_le := λ a a' h, option.no_confusion h, ..with_bot.partial_order, ..with_bot.has_bot } @[simp, norm_cast] theorem coe_le_coe [partial_order α] {a b : α} : (a : with_bot α) ≤ b ↔ a ≤ b := ⟨λ h, by rcases h a rfl with ⟨_, ⟨⟩, h⟩; exact h, λ h a' e, option.some_inj.1 e ▸ ⟨b, rfl, h⟩⟩ @[simp] theorem some_le_some [partial_order α] {a b : α} : @has_le.le (with_bot α) _ (some a) (some b) ↔ a ≤ b := coe_le_coe theorem coe_le [partial_order α] {a b : α} : ∀ {o : option α}, b ∈ o → ((a : with_bot α) ≤ o ↔ a ≤ b) | _ rfl := coe_le_coe @[norm_cast] lemma coe_lt_coe [partial_order α] {a b : α} : (a : with_bot α) < b ↔ a < b := some_lt_some lemma le_coe_get_or_else [preorder α] : ∀ (a : with_bot α) (b : α), a ≤ a.get_or_else b | (some a) b := le_refl a | none b := λ _ h, option.no_confusion h instance linear_order [linear_order α] : linear_order (with_bot α) := { le_total := λ o₁ o₂, begin cases o₁ with a, {exact or.inl bot_le}, cases o₂ with b, {exact or.inr bot_le}, simp [le_total] end, ..with_bot.partial_order } instance decidable_lt [has_lt α] [@decidable_rel α (<)] : @decidable_rel (with_bot α) (<) | none (some x) := is_true $ by existsi [x,rfl]; rintros _ ⟨⟩ | (some x) (some y) := if h : x < y then is_true $ by simp * else is_false $ by simp * | x none := is_false $ by rintro ⟨a,⟨⟨⟩⟩⟩ instance decidable_linear_order [decidable_linear_order α] : decidable_linear_order (with_bot α) := { decidable_le := λ a b, begin cases a with a, { exact is_true bot_le }, cases b with b, { exact is_false (mt (le_antisymm bot_le) (by simp)) }, { exact decidable_of_iff _ some_le_some } end, ..with_bot.linear_order } instance semilattice_sup [semilattice_sup α] : semilattice_sup_bot (with_bot α) := { sup := option.lift_or_get (⊔), le_sup_left := λ o₁ o₂ a ha, by cases ha; cases o₂; simp [option.lift_or_get], le_sup_right := λ o₁ o₂ a ha, by cases ha; cases o₁; simp [option.lift_or_get], sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases o₁ with b; cases o₂ with c; cases ha, { exact h₂ a rfl }, { exact h₁ a rfl }, { rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩, simp at h₂, exact ⟨d, rfl, sup_le h₁' h₂⟩ } end, ..with_bot.order_bot } instance semilattice_inf [semilattice_inf α] : semilattice_inf_bot (with_bot α) := { inf := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊓ b)), inf_le_left := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, inf_le_left⟩ end, inf_le_right := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, inf_le_right⟩ end, le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases ha, rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩, rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩, exact ⟨_, rfl, le_inf ab ac⟩ end, ..with_bot.order_bot } instance lattice [lattice α] : lattice (with_bot α) := { ..with_bot.semilattice_sup, ..with_bot.semilattice_inf } theorem lattice_eq_DLO [decidable_linear_order α] : lattice_of_decidable_linear_order = @with_bot.lattice α _ := lattice.ext $ λ x y, iff.rfl theorem sup_eq_max [decidable_linear_order α] (x y : with_bot α) : x ⊔ y = max x y := by rw [← sup_eq_max, lattice_eq_DLO] theorem inf_eq_min [decidable_linear_order α] (x y : with_bot α) : x ⊓ y = min x y := by rw [← inf_eq_min, lattice_eq_DLO] instance order_top [order_top α] : order_top (with_bot α) := { top := some ⊤, le_top := λ o a ha, by cases ha; exact ⟨_, rfl, le_top⟩, ..with_bot.partial_order } instance bounded_lattice [bounded_lattice α] : bounded_lattice (with_bot α) := { ..with_bot.lattice, ..with_bot.order_top, ..with_bot.order_bot } lemma well_founded_lt [partial_order α] (h : well_founded ((<) : α → α → Prop)) : well_founded ((<) : with_bot α → with_bot α → Prop) := have acc_bot : acc ((<) : with_bot α → with_bot α → Prop) ⊥ := acc.intro _ (λ a ha, (not_le_of_gt ha bot_le).elim), ⟨λ a, option.rec_on a acc_bot (λ a, acc.intro _ (λ b, option.rec_on b (λ _, acc_bot) (λ b, well_founded.induction h b (show ∀ b : α, (∀ c, c < b → (c : with_bot α) < a → acc ((<) : with_bot α → with_bot α → Prop) c) → (b : with_bot α) < a → acc ((<) : with_bot α → with_bot α → Prop) b, from λ b ih hba, acc.intro _ (λ c, option.rec_on c (λ _, acc_bot) (λ c hc, ih _ (some_lt_some.1 hc) (lt_trans hc hba)))))))⟩ instance densely_ordered [partial_order α] [densely_ordered α] [no_bot_order α] : densely_ordered (with_bot α) := ⟨ assume a b, match a, b with | a, none := assume h : a < ⊥, (not_lt_bot h).elim | none, some b := assume h, let ⟨a, ha⟩ := no_bot b in ⟨a, bot_lt_coe a, coe_lt_coe.2 ha⟩ | some a, some b := assume h, let ⟨a, ha₁, ha₂⟩ := exists_between (coe_lt_coe.1 h) in ⟨a, coe_lt_coe.2 ha₁, coe_lt_coe.2 ha₂⟩ end⟩ end with_bot --TODO(Mario): Construct using order dual on with_bot /-- Attach `⊤` to a type. -/ def with_top (α : Type*) := option α namespace with_top meta instance {α} [has_to_format α] : has_to_format (with_top α) := { to_format := λ x, match x with | none := "⊤" | (some x) := to_fmt x end } instance : has_coe_t α (with_top α) := ⟨some⟩ instance has_top : has_top (with_top α) := ⟨none⟩ instance : inhabited (with_top α) := ⟨⊤⟩ lemma none_eq_top : (none : with_top α) = (⊤ : with_top α) := rfl lemma some_eq_coe (a : α) : (some a : with_top α) = (↑a : with_top α) := rfl /-- Recursor for `with_top` using the preferred forms `⊤` and `↑a`. -/ @[elab_as_eliminator] def rec_top_coe {C : with_top α → Sort*} (h₁ : C ⊤) (h₂ : Π (a : α), C a) : Π (n : with_top α), C n := option.rec h₁ h₂ @[norm_cast] theorem coe_eq_coe {a b : α} : (a : with_top α) = b ↔ a = b := by rw [← option.some.inj_eq a b]; refl @[simp] theorem top_ne_coe {a : α} : ⊤ ≠ (a : with_top α) . @[simp] theorem coe_ne_top {a : α} : (a : with_top α) ≠ ⊤ . @[priority 10] instance has_lt [has_lt α] : has_lt (with_top α) := { lt := λ o₁ o₂ : option α, ∃ b ∈ o₁, ∀ a ∈ o₂, b < a } @[priority 10] instance has_le [has_le α] : has_le (with_top α) := { le := λ o₁ o₂ : option α, ∀ a ∈ o₂, ∃ b ∈ o₁, b ≤ a } @[simp] theorem some_lt_some [has_lt α] {a b : α} : @has_lt.lt (with_top α) _ (some a) (some b) ↔ a < b := by simp [(<)] @[simp] theorem some_le_some [has_le α] {a b : α} : @has_le.le (with_top α) _ (some a) (some b) ↔ a ≤ b := by simp [(≤)] @[simp] theorem le_none [has_le α] {a : with_top α} : @has_le.le (with_top α) _ a none := by simp [(≤)] @[simp] theorem some_lt_none [has_lt α] {a : α} : @has_lt.lt (with_top α) _ (some a) none := by simp [(<)]; existsi a; refl instance [preorder α] : preorder (with_top α) := { le := λ o₁ o₂ : option α, ∀ a ∈ o₂, ∃ b ∈ o₁, b ≤ a, lt := (<), lt_iff_le_not_le := by { intros; cases a; cases b; simp [lt_iff_le_not_le]; simp [(<),(≤)] }, le_refl := λ o a ha, ⟨a, ha, le_refl _⟩, le_trans := λ o₁ o₂ o₃ h₁ h₂ c hc, let ⟨b, hb, bc⟩ := h₂ c hc, ⟨a, ha, ab⟩ := h₁ b hb in ⟨a, ha, le_trans ab bc⟩, } instance partial_order [partial_order α] : partial_order (with_top α) := { le_antisymm := λ o₁ o₂ h₁ h₂, begin cases o₂ with b, { cases o₁ with a, {refl}, rcases h₂ a rfl with ⟨_, ⟨⟩, _⟩ }, { rcases h₁ b rfl with ⟨a, ⟨⟩, h₁'⟩, rcases h₂ a rfl with ⟨_, ⟨⟩, h₂'⟩, rw le_antisymm h₁' h₂' } end, .. with_top.preorder } instance order_top [partial_order α] : order_top (with_top α) := { le_top := λ a a' h, option.no_confusion h, ..with_top.partial_order, .. with_top.has_top } @[simp, norm_cast] theorem coe_le_coe [partial_order α] {a b : α} : (a : with_top α) ≤ b ↔ a ≤ b := ⟨λ h, by rcases h b rfl with ⟨_, ⟨⟩, h⟩; exact h, λ h a' e, option.some_inj.1 e ▸ ⟨a, rfl, h⟩⟩ theorem le_coe [partial_order α] {a b : α} : ∀ {o : option α}, a ∈ o → (@has_le.le (with_top α) _ o b ↔ a ≤ b) | _ rfl := coe_le_coe theorem le_coe_iff [partial_order α] (b : α) : ∀(x : with_top α), x ≤ b ↔ (∃a:α, x = a ∧ a ≤ b) | (some a) := by simp [some_eq_coe, coe_eq_coe] | none := by simp [none_eq_top] theorem coe_le_iff [partial_order α] (a : α) : ∀(x : with_top α), ↑a ≤ x ↔ (∀b:α, x = ↑b → a ≤ b) | (some b) := by simp [some_eq_coe, coe_eq_coe] | none := by simp [none_eq_top] theorem lt_iff_exists_coe [partial_order α] : ∀(a b : with_top α), a < b ↔ (∃p:α, a = p ∧ ↑p < b) | (some a) b := by simp [some_eq_coe, coe_eq_coe] | none b := by simp [none_eq_top] @[norm_cast] lemma coe_lt_coe [partial_order α] {a b : α} : (a : with_top α) < b ↔ a < b := some_lt_some lemma coe_lt_top [partial_order α] (a : α) : (a : with_top α) < ⊤ := some_lt_none lemma not_top_le_coe [partial_order α] (a : α) : ¬ (⊤:with_top α) ≤ ↑a := assume h, (lt_irrefl ⊤ (lt_of_le_of_lt h (coe_lt_top a))).elim instance linear_order [linear_order α] : linear_order (with_top α) := { le_total := λ o₁ o₂, begin cases o₁ with a, {exact or.inr le_top}, cases o₂ with b, {exact or.inl le_top}, simp [le_total] end, ..with_top.partial_order } instance decidable_linear_order [decidable_linear_order α] : decidable_linear_order (with_top α) := { decidable_le := λ a b, begin cases b with b, { exact is_true le_top }, cases a with a, { exact is_false (mt (le_antisymm le_top) (by simp)) }, { exact decidable_of_iff _ some_le_some } end, ..with_top.linear_order } instance semilattice_inf [semilattice_inf α] : semilattice_inf_top (with_top α) := { inf := option.lift_or_get (⊓), inf_le_left := λ o₁ o₂ a ha, by cases ha; cases o₂; simp [option.lift_or_get], inf_le_right := λ o₁ o₂ a ha, by cases ha; cases o₁; simp [option.lift_or_get], le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases o₂ with b; cases o₃ with c; cases ha, { exact h₂ a rfl }, { exact h₁ a rfl }, { rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩, simp at h₂, exact ⟨d, rfl, le_inf h₁' h₂⟩ } end, ..with_top.order_top } lemma coe_inf [semilattice_inf α] (a b : α) : ((a ⊓ b : α) : with_top α) = a ⊓ b := rfl instance semilattice_sup [semilattice_sup α] : semilattice_sup_top (with_top α) := { sup := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊔ b)), le_sup_left := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, le_sup_left⟩ end, le_sup_right := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, le_sup_right⟩ end, sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases ha, rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩, rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩, exact ⟨_, rfl, sup_le ab ac⟩ end, ..with_top.order_top } lemma coe_sup [semilattice_sup α] (a b : α) : ((a ⊔ b : α) : with_top α) = a ⊔ b := rfl instance lattice [lattice α] : lattice (with_top α) := { ..with_top.semilattice_sup, ..with_top.semilattice_inf } theorem lattice_eq_DLO [decidable_linear_order α] : lattice_of_decidable_linear_order = @with_top.lattice α _ := lattice.ext $ λ x y, iff.rfl theorem sup_eq_max [decidable_linear_order α] (x y : with_top α) : x ⊔ y = max x y := by rw [← sup_eq_max, lattice_eq_DLO] theorem inf_eq_min [decidable_linear_order α] (x y : with_top α) : x ⊓ y = min x y := by rw [← inf_eq_min, lattice_eq_DLO] instance order_bot [order_bot α] : order_bot (with_top α) := { bot := some ⊥, bot_le := λ o a ha, by cases ha; exact ⟨_, rfl, bot_le⟩, ..with_top.partial_order } instance bounded_lattice [bounded_lattice α] : bounded_lattice (with_top α) := { ..with_top.lattice, ..with_top.order_top, ..with_top.order_bot } lemma well_founded_lt {α : Type*} [partial_order α] (h : well_founded ((<) : α → α → Prop)) : well_founded ((<) : with_top α → with_top α → Prop) := have acc_some : ∀ a : α, acc ((<) : with_top α → with_top α → Prop) (some a) := λ a, acc.intro _ (well_founded.induction h a (show ∀ b, (∀ c, c < b → ∀ d : with_top α, d < some c → acc (<) d) → ∀ y : with_top α, y < some b → acc (<) y, from λ b ih c, option.rec_on c (λ hc, (not_lt_of_ge le_top hc).elim) (λ c hc, acc.intro _ (ih _ (some_lt_some.1 hc))))), ⟨λ a, option.rec_on a (acc.intro _ (λ y, option.rec_on y (λ h, (lt_irrefl _ h).elim) (λ _ _, acc_some _))) acc_some⟩ instance densely_ordered [partial_order α] [densely_ordered α] [no_top_order α] : densely_ordered (with_top α) := ⟨ assume a b, match a, b with | none, a := assume h : ⊤ < a, (not_top_lt h).elim | some a, none := assume h, let ⟨b, hb⟩ := no_top a in ⟨b, coe_lt_coe.2 hb, coe_lt_top b⟩ | some a, some b := assume h, let ⟨a, ha₁, ha₂⟩ := exists_between (coe_lt_coe.1 h) in ⟨a, coe_lt_coe.2 ha₁, coe_lt_coe.2 ha₂⟩ end⟩ lemma lt_iff_exists_coe_btwn [partial_order α] [densely_ordered α] [no_top_order α] {a b : with_top α} : (a < b) ↔ (∃ x : α, a < ↑x ∧ ↑x < b) := ⟨λ h, let ⟨y, hy⟩ := exists_between h, ⟨x, hx⟩ := (lt_iff_exists_coe _ _).1 hy.2 in ⟨x, hx.1 ▸ hy⟩, λ ⟨x, hx⟩, lt_trans hx.1 hx.2⟩ end with_top namespace subtype /-- A subtype forms a `⊔`-semilattice if `⊔` preserves the property. -/ protected def semilattice_sup [semilattice_sup α] {P : α → Prop} (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) : semilattice_sup {x : α // P x} := { sup := λ x y, ⟨x.1 ⊔ y.1, Psup x.2 y.2⟩, le_sup_left := λ x y, @le_sup_left _ _ (x : α) y, le_sup_right := λ x y, @le_sup_right _ _ (x : α) y, sup_le := λ x y z h1 h2, @sup_le α _ _ _ _ h1 h2, ..subtype.partial_order P } /-- A subtype forms a `⊓`-semilattice if `⊓` preserves the property. -/ protected def semilattice_inf [semilattice_inf α] {P : α → Prop} (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : semilattice_inf {x : α // P x} := { inf := λ x y, ⟨x.1 ⊓ y.1, Pinf x.2 y.2⟩, inf_le_left := λ x y, @inf_le_left _ _ (x : α) y, inf_le_right := λ x y, @inf_le_right _ _ (x : α) y, le_inf := λ x y z h1 h2, @le_inf α _ _ _ _ h1 h2, ..subtype.partial_order P } /-- A subtype forms a `⊔`-`⊥`-semilattice if `⊥` and `⊔` preserve the property. -/ protected def semilattice_sup_bot [semilattice_sup_bot α] {P : α → Prop} (Pbot : P ⊥) (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) : semilattice_sup_bot {x : α // P x} := { bot := ⟨⊥, Pbot⟩, bot_le := λ x, @bot_le α _ x, ..subtype.semilattice_sup Psup } /-- A subtype forms a `⊓`-`⊥`-semilattice if `⊥` and `⊓` preserve the property. -/ protected def semilattice_inf_bot [semilattice_inf_bot α] {P : α → Prop} (Pbot : P ⊥) (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : semilattice_inf_bot {x : α // P x} := { bot := ⟨⊥, Pbot⟩, bot_le := λ x, @bot_le α _ x, ..subtype.semilattice_inf Pinf } /-- A subtype forms a `⊓`-`⊤`-semilattice if `⊤` and `⊓` preserve the property. -/ protected def semilattice_inf_top [semilattice_inf_top α] {P : α → Prop} (Ptop : P ⊤) (Pinf : ∀{{x y}}, P x → P y → P (x ⊓ y)) : semilattice_inf_top {x : α // P x} := { top := ⟨⊤, Ptop⟩, le_top := λ x, @le_top α _ x, ..subtype.semilattice_inf Pinf } /-- A subtype forms a lattice if `⊔` and `⊓` preserve the property. -/ protected def lattice [lattice α] {P : α → Prop} (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : lattice {x : α // P x} := { ..subtype.semilattice_inf Pinf, ..subtype.semilattice_sup Psup } end subtype namespace order_dual variable (α) instance [has_bot α] : has_top (order_dual α) := ⟨(⊥ : α)⟩ instance [has_top α] : has_bot (order_dual α) := ⟨(⊤ : α)⟩ instance [order_bot α] : order_top (order_dual α) := { le_top := @bot_le α _, .. order_dual.partial_order α, .. order_dual.has_top α } instance [order_top α] : order_bot (order_dual α) := { bot_le := @le_top α _, .. order_dual.partial_order α, .. order_dual.has_bot α } instance [semilattice_inf_bot α] : semilattice_sup_top (order_dual α) := { .. order_dual.semilattice_sup α, .. order_dual.order_top α } instance [semilattice_inf_top α] : semilattice_sup_bot (order_dual α) := { .. order_dual.semilattice_sup α, .. order_dual.order_bot α } instance [semilattice_sup_bot α] : semilattice_inf_top (order_dual α) := { .. order_dual.semilattice_inf α, .. order_dual.order_top α } instance [semilattice_sup_top α] : semilattice_inf_bot (order_dual α) := { .. order_dual.semilattice_inf α, .. order_dual.order_bot α } instance [bounded_lattice α] : bounded_lattice (order_dual α) := { .. order_dual.lattice α, .. order_dual.order_top α, .. order_dual.order_bot α } instance [bounded_distrib_lattice α] : bounded_distrib_lattice (order_dual α) := { .. order_dual.bounded_lattice α, .. order_dual.distrib_lattice α } end order_dual namespace prod variables (α β) instance [has_top α] [has_top β] : has_top (α × β) := ⟨⟨⊤, ⊤⟩⟩ instance [has_bot α] [has_bot β] : has_bot (α × β) := ⟨⟨⊥, ⊥⟩⟩ instance [order_top α] [order_top β] : order_top (α × β) := { le_top := assume a, ⟨le_top, le_top⟩, .. prod.partial_order α β, .. prod.has_top α β } instance [order_bot α] [order_bot β] : order_bot (α × β) := { bot_le := assume a, ⟨bot_le, bot_le⟩, .. prod.partial_order α β, .. prod.has_bot α β } instance [semilattice_sup_top α] [semilattice_sup_top β] : semilattice_sup_top (α × β) := { .. prod.semilattice_sup α β, .. prod.order_top α β } instance [semilattice_inf_top α] [semilattice_inf_top β] : semilattice_inf_top (α × β) := { .. prod.semilattice_inf α β, .. prod.order_top α β } instance [semilattice_sup_bot α] [semilattice_sup_bot β] : semilattice_sup_bot (α × β) := { .. prod.semilattice_sup α β, .. prod.order_bot α β } instance [semilattice_inf_bot α] [semilattice_inf_bot β] : semilattice_inf_bot (α × β) := { .. prod.semilattice_inf α β, .. prod.order_bot α β } instance [bounded_lattice α] [bounded_lattice β] : bounded_lattice (α × β) := { .. prod.lattice α β, .. prod.order_top α β, .. prod.order_bot α β } instance [bounded_distrib_lattice α] [bounded_distrib_lattice β] : bounded_distrib_lattice (α × β) := { .. prod.bounded_lattice α β, .. prod.distrib_lattice α β } end prod section disjoint section semilattice_inf_bot variable [semilattice_inf_bot α] /-- Two elements of a lattice are disjoint if their inf is the bottom element. (This generalizes disjoint sets, viewed as members of the subset lattice.) -/ def disjoint (a b : α) : Prop := a ⊓ b ≤ ⊥ theorem disjoint.eq_bot {a b : α} (h : disjoint a b) : a ⊓ b = ⊥ := eq_bot_iff.2 h theorem disjoint_iff {a b : α} : disjoint a b ↔ a ⊓ b = ⊥ := eq_bot_iff.symm theorem disjoint.comm {a b : α} : disjoint a b ↔ disjoint b a := by rw [disjoint, disjoint, inf_comm] @[symm] theorem disjoint.symm ⦃a b : α⦄ : disjoint a b → disjoint b a := disjoint.comm.1 @[simp] theorem disjoint_bot_left {a : α} : disjoint ⊥ a := disjoint_iff.2 bot_inf_eq @[simp] theorem disjoint_bot_right {a : α} : disjoint a ⊥ := disjoint_iff.2 inf_bot_eq theorem disjoint.mono {a b c d : α} (h₁ : a ≤ b) (h₂ : c ≤ d) : disjoint b d → disjoint a c := le_trans (inf_le_inf h₁ h₂) theorem disjoint.mono_left {a b c : α} (h : a ≤ b) : disjoint b c → disjoint a c := disjoint.mono h (le_refl _) theorem disjoint.mono_right {a b c : α} (h : b ≤ c) : disjoint a c → disjoint a b := disjoint.mono (le_refl _) h @[simp] lemma disjoint_self {a : α} : disjoint a a ↔ a = ⊥ := by simp [disjoint] lemma disjoint.ne {a b : α} (ha : a ≠ ⊥) (hab : disjoint a b) : a ≠ b := by { intro h, rw [←h, disjoint_self] at hab, exact ha hab } end semilattice_inf_bot section bounded_distrib_lattice variables [bounded_distrib_lattice α] {a b c : α} @[simp] lemma disjoint_sup_left : disjoint (a ⊔ b) c ↔ disjoint a c ∧ disjoint b c := by simp only [disjoint_iff, inf_sup_right, sup_eq_bot_iff] @[simp] lemma disjoint_sup_right : disjoint a (b ⊔ c) ↔ disjoint a b ∧ disjoint a c := by simp only [disjoint_iff, inf_sup_left, sup_eq_bot_iff] lemma disjoint.sup_left (ha : disjoint a c) (hb : disjoint b c) : disjoint (a ⊔ b) c := disjoint_sup_left.2 ⟨ha, hb⟩ lemma disjoint.sup_right (hb : disjoint a b) (hc : disjoint a c) : disjoint a (b ⊔ c) := disjoint_sup_right.2 ⟨hb, hc⟩ end bounded_distrib_lattice end disjoint /-! ### `is_compl` predicate -/ /-- Two elements `x` and `y` are complements of each other if `x ⊔ y = ⊤` and `x ⊓ y = ⊥`. -/ structure is_compl [bounded_lattice α] (x y : α) : Prop := (inf_le_bot : x ⊓ y ≤ ⊥) (top_le_sup : ⊤ ≤ x ⊔ y) namespace is_compl section bounded_lattice variables [bounded_lattice α] {x y z : α} protected lemma disjoint (h : is_compl x y) : disjoint x y := h.1 @[symm] protected lemma symm (h : is_compl x y) : is_compl y x := ⟨by { rw inf_comm, exact h.1 }, by { rw sup_comm, exact h.2 }⟩ lemma of_eq (h₁ : x ⊓ y = ⊥) (h₂ : x ⊔ y = ⊤) : is_compl x y := ⟨le_of_eq h₁, le_of_eq h₂.symm⟩ lemma inf_eq_bot (h : is_compl x y) : x ⊓ y = ⊥ := h.disjoint.eq_bot lemma sup_eq_top (h : is_compl x y) : x ⊔ y = ⊤ := top_unique h.top_le_sup lemma to_order_dual (h : is_compl x y) : @is_compl (order_dual α) _ x y := ⟨h.2, h.1⟩ end bounded_lattice variables [bounded_distrib_lattice α] {x y z : α} lemma le_left_iff (h : is_compl x y) : z ≤ x ↔ disjoint z y := ⟨λ hz, h.disjoint.mono_left hz, λ hz, le_of_inf_le_sup_le (le_trans hz bot_le) (le_trans le_top h.top_le_sup)⟩ lemma le_right_iff (h : is_compl x y) : z ≤ y ↔ disjoint z x := h.symm.le_left_iff lemma left_le_iff (h : is_compl x y) : x ≤ z ↔ ⊤ ≤ z ⊔ y := h.to_order_dual.le_left_iff lemma right_le_iff (h : is_compl x y) : y ≤ z ↔ ⊤ ≤ z ⊔ x := h.symm.left_le_iff lemma antimono {x' y'} (h : is_compl x y) (h' : is_compl x' y') (hx : x ≤ x') : y' ≤ y := h'.right_le_iff.2 $ le_trans h.symm.top_le_sup (sup_le_sup_left hx _) lemma right_unique (hxy : is_compl x y) (hxz : is_compl x z) : y = z := le_antisymm (hxz.antimono hxy $ le_refl x) (hxy.antimono hxz $ le_refl x) lemma left_unique (hxz : is_compl x z) (hyz : is_compl y z) : x = y := hxz.symm.right_unique hyz.symm lemma sup_inf {x' y'} (h : is_compl x y) (h' : is_compl x' y') : is_compl (x ⊔ x') (y ⊓ y') := of_eq (by rw [inf_sup_right, ← inf_assoc, h.inf_eq_bot, bot_inf_eq, bot_sup_eq, inf_left_comm, h'.inf_eq_bot, inf_bot_eq]) (by rw [sup_inf_left, @sup_comm _ _ x, sup_assoc, h.sup_eq_top, sup_top_eq, top_inf_eq, sup_assoc, sup_left_comm, h'.sup_eq_top, sup_top_eq]) lemma inf_sup {x' y'} (h : is_compl x y) (h' : is_compl x' y') : is_compl (x ⊓ x') (y ⊔ y') := (h.symm.sup_inf h'.symm).symm lemma inf_left_eq_bot_iff (h : is_compl y z) : x ⊓ y = ⊥ ↔ x ≤ z := inf_eq_bot_iff_le_compl h.sup_eq_top h.inf_eq_bot lemma inf_right_eq_bot_iff (h : is_compl y z) : x ⊓ z = ⊥ ↔ x ≤ y := h.symm.inf_left_eq_bot_iff lemma disjoint_left_iff (h : is_compl y z) : disjoint x y ↔ x ≤ z := disjoint_iff.trans h.inf_left_eq_bot_iff lemma disjoint_right_iff (h : is_compl y z) : disjoint x z ↔ x ≤ y := h.symm.disjoint_left_iff end is_compl lemma is_compl_bot_top [bounded_lattice α] : is_compl (⊥ : α) ⊤ := is_compl.of_eq bot_inf_eq sup_top_eq lemma is_compl_top_bot [bounded_lattice α] : is_compl (⊤ : α) ⊥ := is_compl.of_eq inf_bot_eq top_sup_eq
f2209f07c1392dbbf903673a3108790329964f32
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/ring_theory/adjoin.lean
f97fed336367d0cffff5240ecb2a310dd4c52b08
[ "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
7,994
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Adjoining elements to form subalgebras. -/ import ring_theory.polynomial import ring_theory.principal_ideal_domain universes u v w open submodule ring namespace algebra variables {R : Type u} {A : Type v} variables [comm_ring R] [comm_ring A] variables [algebra R A] {s t : set A} theorem subset_adjoin : s ⊆ adjoin R s := set.subset.trans (set.subset_union_right _ _) subset_closure theorem adjoin_le {S : subalgebra R A} (H : s ⊆ S) : adjoin R s ≤ S := closure_subset $ set.union_subset S.3 H theorem adjoin_le_iff {S : subalgebra R A} : adjoin R s ≤ S ↔ s ⊆ S:= ⟨set.subset.trans subset_adjoin, adjoin_le⟩ theorem adjoin_mono (H : s ⊆ t) : adjoin R s ≤ adjoin R t := closure_subset (set.subset.trans (set.union_subset_union_right _ H) subset_closure) variables (R A) @[simp] theorem adjoin_empty : adjoin R (∅ : set A) = ⊥ := eq_bot_iff.2 $ adjoin_le $ set.empty_subset _ variables {A} variables (s t) theorem adjoin_union : adjoin R (s ∪ t) = (adjoin R s).under (adjoin (adjoin R s) t) := le_antisymm (closure_mono $ set.union_subset (set.range_subset_iff.2 $ λ r, or.inl ⟨algebra_map R (adjoin R s) r, rfl⟩) (set.union_subset_union_left _ $ λ x hxs, ⟨⟨_, subset_adjoin hxs⟩, rfl⟩)) (closure_subset $ set.union_subset (set.range_subset_iff.2 $ λ x, adjoin_mono (set.subset_union_left _ _) x.2) (set.subset.trans (set.subset_union_right _ _) subset_adjoin)) theorem adjoin_eq_span : (adjoin R s : submodule R A) = span R (monoid.closure s) := begin apply le_antisymm, { intros r hr, rcases ring.exists_list_of_mem_closure hr with ⟨L, HL, rfl⟩, clear hr, induction L with hd tl ih, { rw mem_coe, exact zero_mem _ }, rw list.forall_mem_cons at HL, rw [list.map_cons, list.sum_cons, mem_coe], refine submodule.add_mem _ _ (ih HL.2), replace HL := HL.1, clear ih tl, suffices : ∃ z r (hr : r ∈ monoid.closure s), has_scalar.smul.{u v} z r = list.prod hd, { rcases this with ⟨z, r, hr, hzr⟩, rw ← hzr, exact smul_mem _ _ (subset_span hr) }, induction hd with hd tl ih, { exact ⟨1, 1, is_submonoid.one_mem, one_smul _ _⟩ }, rw list.forall_mem_cons at HL, rcases (ih HL.2) with ⟨z, r, hr, hzr⟩, rw [list.prod_cons, ← hzr], rcases HL.1 with ⟨⟨hd, rfl⟩ | hs⟩ | rfl, { refine ⟨hd * z, r, hr, _⟩, rw [smul_def, smul_def, (algebra_map _ _).map_mul, _root_.mul_assoc] }, { refine ⟨z, hd * r, is_submonoid.mul_mem (monoid.subset_closure hs) hr, _⟩, rw [smul_def, smul_def, mul_left_comm] }, { refine ⟨-z, r, hr, _⟩, rw [neg_smul, neg_one_mul] } }, exact span_le.2 (show monoid.closure s ⊆ adjoin R s, from monoid.closure_subset subset_adjoin) end theorem adjoin_eq_range : adjoin R s = (mv_polynomial.aeval R A (coe : s → A)).range := le_antisymm (adjoin_le $ λ x hx, ⟨mv_polynomial.X ⟨x, hx⟩, mv_polynomial.eval₂_X _ _ _⟩) (λ x ⟨p, hp⟩, hp ▸ mv_polynomial.induction_on p (λ r, by rw [mv_polynomial.aeval_def, mv_polynomial.eval₂_C]; exact (adjoin R s).3 ⟨r, rfl⟩) (λ p q hp hq, by rw alg_hom.map_add; exact is_add_submonoid.add_mem hp hq) (λ p ⟨n, hn⟩ hp, by rw [alg_hom.map_mul, mv_polynomial.aeval_def _ _ _ (mv_polynomial.X _), mv_polynomial.eval₂_X]; exact is_submonoid.mul_mem hp (subset_adjoin hn))) theorem adjoin_singleton_eq_range (x : A) : adjoin R {x} = (polynomial.aeval R A x).range := le_antisymm (adjoin_le $ set.singleton_subset_iff.2 ⟨polynomial.X, polynomial.eval₂_X _ _⟩) (λ y ⟨p, hp⟩, hp ▸ polynomial.induction_on p (λ r, by rw [polynomial.aeval_def, polynomial.eval₂_C]; exact (adjoin R _).3 ⟨r, rfl⟩) (λ p q hp hq, by rw alg_hom.map_add; exact is_add_submonoid.add_mem hp hq) (λ n r ih, by { rw [pow_succ', ← ring.mul_assoc, alg_hom.map_mul, polynomial.aeval_def _ polynomial.X, polynomial.eval₂_X], exact is_submonoid.mul_mem ih (subset_adjoin $ or.inl rfl) })) theorem adjoin_union_coe_submodule : (adjoin R (s ∪ t) : submodule R A) = (adjoin R s) * (adjoin R t) := begin rw [adjoin_eq_span, adjoin_eq_span, adjoin_eq_span, span_mul_span], congr' 1, ext z, rw monoid.mem_closure_union_iff, split; { rintro ⟨y, hys, z, hzt, rfl⟩, exact ⟨_, hys, _, hzt, rfl⟩ } end variables {R s t} theorem adjoin_int (s : set R) : adjoin ℤ s = subalgebra_of_subring (ring.closure s) := le_antisymm (adjoin_le subset_closure) (closure_subset subset_adjoin) local attribute [instance] set.pointwise_mul_semiring theorem fg_trans (h1 : (adjoin R s : submodule R A).fg) (h2 : (adjoin (adjoin R s) t : submodule (adjoin R s) A).fg) : (adjoin R (s ∪ t) : submodule R A).fg := begin rcases fg_def.1 h1 with ⟨p, hp, hp'⟩, rcases fg_def.1 h2 with ⟨q, hq, hq'⟩, refine fg_def.2 ⟨p * q, set.pointwise_mul_finite hp hq, le_antisymm _ _⟩, { rw [span_le], rintros _ ⟨x, hx, y, hy, rfl⟩, change x * y ∈ _, refine is_submonoid.mul_mem _ _, { have : x ∈ (adjoin R s : submodule R A), { rw ← hp', exact subset_span hx }, exact adjoin_mono (set.subset_union_left _ _) this }, have : y ∈ (adjoin (adjoin R s) t : submodule (adjoin R s) A), { rw ← hq', exact subset_span hy }, change y ∈ adjoin R (s ∪ t), rwa adjoin_union }, { intros r hr, change r ∈ adjoin R (s ∪ t) at hr, rw adjoin_union at hr, change r ∈ (adjoin (adjoin R s) t : submodule (adjoin R s) A) at hr, haveI := classical.dec_eq A, haveI := classical.dec_eq R, rw [← hq', ← set.image_id q, finsupp.mem_span_iff_total (adjoin R s)] at hr, rcases hr with ⟨l, hlq, rfl⟩, have := @finsupp.total_apply A A (adjoin R s), rw [this, finsupp.sum, mem_coe], refine sum_mem _ _, intros z hz, change (l z).1 * _ ∈ _, have : (l z).1 ∈ (adjoin R s : submodule R A) := (l z).2, rw [← hp', ← set.image_id p, finsupp.mem_span_iff_total R] at this, rcases this with ⟨l2, hlp, hl⟩, have := @finsupp.total_apply A A R, rw this at hl, rw [←hl, finsupp.sum_mul], refine sum_mem _ _, intros t ht, change _ * _ ∈ _, rw smul_mul_assoc, refine smul_mem _ _ _, exact subset_span ⟨t, hlp ht, z, hlq hz, rfl⟩ } end end algebra namespace subalgebra variables {R : Type u} {A : Type v} variables [comm_ring R] [comm_ring A] [algebra R A] /-- A subalgebra `S` is finitely generated if there exists `t : finset A` such that `algebra.adjoin R t = S`. -/ def fg (S : subalgebra R A) : Prop := ∃ t : finset A, algebra.adjoin R ↑t = S theorem fg_def {S : subalgebra R A} : S.fg ↔ ∃ t : set A, set.finite t ∧ algebra.adjoin R t = S := ⟨λ ⟨t, ht⟩, ⟨↑t, set.finite_mem_finset t, ht⟩, λ ⟨t, ht1, ht2⟩, ⟨ht1.to_finset, by rwa set.finite.coe_to_finset⟩⟩ theorem fg_bot : (⊥ : subalgebra R A).fg := ⟨∅, algebra.adjoin_empty R A⟩ end subalgebra variables {R : Type u} {A : Type v} {B : Type w} variables [comm_ring R] [comm_ring A] [comm_ring B] [algebra R A] [algebra R B] instance alg_hom.is_noetherian_ring_range (f : A →ₐ[R] B) [is_noetherian_ring A] : is_noetherian_ring f.range := is_noetherian_ring_range f.to_ring_hom theorem is_noetherian_ring_of_fg {S : subalgebra R A} (HS : S.fg) [is_noetherian_ring R] : is_noetherian_ring S := let ⟨t, ht⟩ := HS in ht ▸ (algebra.adjoin_eq_range R (↑t : set A)).symm ▸ by haveI : is_noetherian_ring (mv_polynomial (↑t : set A) R) := mv_polynomial.is_noetherian_ring; convert alg_hom.is_noetherian_ring_range _; apply_instance theorem is_noetherian_ring_closure (s : set R) (hs : s.finite) : is_noetherian_ring (ring.closure s) := show is_noetherian_ring (subalgebra_of_subring (ring.closure s)), from algebra.adjoin_int s ▸ is_noetherian_ring_of_fg (subalgebra.fg_def.2 ⟨s, hs, rfl⟩)
c8b687546b361745e6a8d6d96672000ab68393ac
618003631150032a5676f229d13a079ac875ff77
/src/group_theory/congruence.lean
8208fdf580aefbd65215821ca2d315ffce06e9bf
[ "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
42,233
lean
/- Copyright (c) 2019 Amelia Livingston. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Amelia Livingston -/ import data.setoid.basic import algebra.pi_instances /-! # Congruence relations This file defines congruence relations: equivalence relations that preserve a binary operation, which in this case is multiplication or addition. The principal definition is a `structure` extending a `setoid` (an equivalence relation), and the inductive definition of the smallest congruence relation containing a binary relation is also given (see `con_gen`). The file also proves basic properties of the quotient of a type by a congruence relation, and the complete lattice of congruence relations on a type. We then establish an order-preserving bijection between the set of congruence relations containing a congruence relation `c` and the set of congruence relations on the quotient by `c`. The second half of the file concerns congruence relations on monoids, in which case the quotient by the congruence relation is also a monoid. There are results about the universal property of quotients of monoids, and the isomorphism theorems for monoids. ## Implementation notes The inductive definition of a congruence relation could be a nested inductive type, defined using the equivalence closure of a binary relation `eqv_gen`, but the recursor generated does not work. A nested inductive definition could conceivably shorten proofs, because they would allow invocation of the corresponding lemmas about `eqv_gen`. The lemmas `refl`, `symm` and `trans` are not tagged with `@[refl]`, `@[symm]`, and `@[trans]` respectively as these tags do not work on a structure coerced to a binary relation. There is a coercion from elements of a type to the element's equivalence class under a congruence relation. A congruence relation on a monoid `M` can be thought of as a submonoid of `M × M` for which membership is an equivalence relation, but whilst this fact is established in the file, it is not used, since this perspective adds more layers of definitional unfolding. ## Tags congruence, congruence relation, quotient, quotient by congruence relation, monoid, quotient monoid, isomorphism theorems -/ variables (M : Type*) {N : Type*} {P : Type*} set_option old_structure_cmd true open function setoid /-- A congruence relation on a type with an addition is an equivalence relation which preserves addition. -/ structure add_con [has_add M] extends setoid M := (add' : ∀ {w x y z}, r w x → r y z → r (w + y) (x + z)) /-- A congruence relation on a type with a multiplication is an equivalence relation which preserves multiplication. -/ @[to_additive add_con] structure con [has_mul M] extends setoid M := (mul' : ∀ {w x y z}, r w x → r y z → r (w * y) (x * z)) variables {M} /-- The inductively defined smallest additive congruence relation containing a given binary relation. -/ inductive add_con_gen.rel [has_add M] (r : M → M → Prop) : M → M → Prop | of : Π x y, r x y → add_con_gen.rel x y | refl : Π x, add_con_gen.rel x x | symm : Π x y, add_con_gen.rel x y → add_con_gen.rel y x | trans : Π x y z, add_con_gen.rel x y → add_con_gen.rel y z → add_con_gen.rel x z | add : Π w x y z, add_con_gen.rel w x → add_con_gen.rel y z → add_con_gen.rel (w + y) (x + z) /-- The inductively defined smallest multiplicative congruence relation containing a given binary relation. -/ @[to_additive add_con_gen.rel] inductive con_gen.rel [has_mul M] (r : M → M → Prop) : M → M → Prop | of : Π x y, r x y → con_gen.rel x y | refl : Π x, con_gen.rel x x | symm : Π x y, con_gen.rel x y → con_gen.rel y x | trans : Π x y z, con_gen.rel x y → con_gen.rel y z → con_gen.rel x z | mul : Π w x y z, con_gen.rel w x → con_gen.rel y z → con_gen.rel (w * y) (x * z) /-- The inductively defined smallest multiplicative congruence relation containing a given binary relation. -/ @[to_additive add_con_gen "The inductively defined smallest additive congruence relation containing a given binary relation."] def con_gen [has_mul M] (r : M → M → Prop) : con M := ⟨con_gen.rel r, ⟨con_gen.rel.refl, con_gen.rel.symm, con_gen.rel.trans⟩, con_gen.rel.mul⟩ namespace con section variables [has_mul M] [has_mul N] [has_mul P] (c : con M) @[to_additive] instance : inhabited (con M) := ⟨con_gen empty_relation⟩ /-- A coercion from a congruence relation to its underlying binary relation. -/ @[to_additive "A coercion from an additive congruence relation to its underlying binary relation."] instance : has_coe_to_fun (con M) := ⟨_, λ c, λ x y, c.r x y⟩ /-- Congruence relations are reflexive. -/ @[to_additive "Additive congruence relations are reflexive."] protected lemma refl (x) : c x x := c.2.1 x /-- Congruence relations are symmetric. -/ @[to_additive "Additive congruence relations are symmetric."] protected lemma symm : ∀ {x y}, c x y → c y x := λ _ _ h, c.2.2.1 h /-- Congruence relations are transitive. -/ @[to_additive "Additive congruence relations are transitive."] protected lemma trans : ∀ {x y z}, c x y → c y z → c x z := λ _ _ _ h, c.2.2.2 h /-- Multiplicative congruence relations preserve multiplication. -/ @[to_additive "Additive congruence relations preserve addition."] protected lemma mul : ∀ {w x y z}, c w x → c y z → c (w * y) (x * z) := λ _ _ _ _ h1 h2, c.3 h1 h2 /-- Given a type `M` with a multiplication, a congruence relation `c` on `M`, and elements of `M` `x, y`, `(x, y) ∈ M × M` iff `x` is related to `y` by `c`. -/ @[to_additive "Given a type `M` with an addition, `x, y ∈ M`, and an additive congruence relation `c` on `M`, `(x, y) ∈ M × M` iff `x` is related to `y` by `c`."] instance : has_mem (M × M) (con M) := ⟨λ x c, c x.1 x.2⟩ variables {c} /-- The map sending a congruence relation to its underlying binary relation is injective. -/ @[to_additive "The map sending an additive congruence relation to its underlying binary relation is injective."] lemma ext' {c d : con M} (H : c.r = d.r) : c = d := by cases c; cases d; simpa using H /-- Extensionality rule for congruence relations. -/ @[ext, to_additive "Extensionality rule for additive congruence relations."] lemma ext {c d : con M} (H : ∀ x y, c x y ↔ d x y) : c = d := ext' $ by ext; apply H attribute [ext] add_con.ext /-- The map sending a congruence relation to its underlying equivalence relation is injective. -/ @[to_additive "The map sending an additive congruence relation to its underlying equivalence relation is injective."] lemma to_setoid_inj {c d : con M} (H : c.to_setoid = d.to_setoid) : c = d := ext $ ext_iff.1 H /-- Iff version of extensionality rule for congruence relations. -/ @[to_additive "Iff version of extensionality rule for additive congruence relations."] lemma ext_iff {c d : con M} : (∀ x y, c x y ↔ d x y) ↔ c = d := ⟨ext, λ h _ _, h ▸ iff.rfl⟩ /-- Two congruence relations are equal iff their underlying binary relations are equal. -/ @[to_additive "Two additive congruence relations are equal iff their underlying binary relations are equal."] lemma ext'_iff {c d : con M} : c.r = d.r ↔ c = d := ⟨ext', λ h, h ▸ rfl⟩ /-- The kernel of a multiplication-preserving function as a congruence relation. -/ @[to_additive "The kernel of an addition-preserving function as an additive congruence relation."] def mul_ker (f : M → P) (h : ∀ x y, f (x * y) = f x * f y) : con M := { r := λ x y, f x = f y, iseqv := ⟨λ _, rfl, λ _ _, eq.symm, λ _ _ _, eq.trans⟩, mul' := λ _ _ _ _ h1 h2, by rw [h, h1, h2, h] } /-- Given types with multiplications `M, N`, the product of two congruence relations `c` on `M` and `d` on `N`: `(x₁, x₂), (y₁, y₂) ∈ M × N` are related by `c.prod d` iff `x₁` is related to `y₁` by `c` and `x₂` is related to `y₂` by `d`. -/ @[to_additive prod "Given types with additions `M, N`, the product of two congruence relations `c` on `M` and `d` on `N`: `(x₁, x₂), (y₁, y₂) ∈ M × N` are related by `c.prod d` iff `x₁` is related to `y₁` by `c` and `x₂` is related to `y₂` by `d`."] protected def prod (c : con M) (d : con N) : con (M × N) := { mul' := λ _ _ _ _ h1 h2, ⟨c.mul h1.1 h2.1, d.mul h1.2 h2.2⟩, ..c.to_setoid.prod d.to_setoid } /-- The product of an indexed collection of congruence relations. -/ @[to_additive "The product of an indexed collection of additive congruence relations."] def pi {ι : Type*} {f : ι → Type*} [Π i, has_mul (f i)] (C : Π i, con (f i)) : con (Π i, f i) := { mul' := λ _ _ _ _ h1 h2 i, (C i).mul (h1 i) (h2 i), ..@pi_setoid _ _ $ λ i, (C i).to_setoid } variables (c) @[simp, to_additive] lemma coe_eq : c.to_setoid.r = c := rfl -- Quotients /-- Defining the quotient by a congruence relation of a type with a multiplication. -/ @[to_additive "Defining the quotient by an additive congruence relation of a type with an addition."] protected def quotient := quotient $ c.to_setoid /-- Coercion from a type with a multiplication to its quotient by a congruence relation. See Note [use has_coe_t]. -/ @[to_additive "Coercion from a type with an addition to its quotient by an additive congruence relation", priority 0] instance : has_coe_t M c.quotient := ⟨@quotient.mk _ c.to_setoid⟩ /-- The quotient of a type with decidable equality by a congruence relation also has decidable equality. -/ @[to_additive "The quotient of a type with decidable equality by an additive congruence relation also has decidable equality."] instance [d : ∀ a b, decidable (c a b)] : decidable_eq c.quotient := @quotient.decidable_eq M c.to_setoid d /-- The function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes. -/ @[elab_as_eliminator, to_additive "The function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes."] protected def lift_on {β} {c : con M} (q : c.quotient) (f : M → β) (h : ∀ a b, c a b → f a = f b) : β := quotient.lift_on' q f h variables {c} /-- The inductive principle used to prove propositions about the elements of a quotient by a congruence relation. -/ @[elab_as_eliminator, to_additive "The inductive principle used to prove propositions about the elements of a quotient by an additive congruence relation."] protected lemma induction_on {C : c.quotient → Prop} (q : c.quotient) (H : ∀ x : M, C x) : C q := quotient.induction_on' q H /-- A version of `con.induction_on` for predicates which take two arguments. -/ @[elab_as_eliminator, to_additive "A version of `add_con.induction_on` for predicates which take two arguments."] protected lemma induction_on₂ {d : con N} {C : c.quotient → d.quotient → Prop} (p : c.quotient) (q : d.quotient) (H : ∀ (x : M) (y : N), C x y) : C p q := quotient.induction_on₂' p q H variables (c) /-- Two elements are related by a congruence relation `c` iff they are represented by the same element of the quotient by `c`. -/ @[simp, to_additive "Two elements are related by an additive congruence relation `c` iff they are represented by the same element of the quotient by `c`."] protected lemma eq {a b : M} : (a : c.quotient) = b ↔ c a b := quotient.eq' /-- The multiplication induced on the quotient by a congruence relation on a type with a multiplication. -/ @[to_additive "The addition induced on the quotient by an additive congruence relation on a type with an addition."] instance has_mul : has_mul c.quotient := ⟨λ x y, quotient.lift_on₂' x y (λ w z, ((w * z : M) : c.quotient)) $ λ _ _ _ _ h1 h2, c.eq.2 $ c.mul h1 h2⟩ /-- The kernel of the quotient map induced by a congruence relation `c` equals `c`. -/ @[simp, to_additive "The kernel of the quotient map induced by an additive congruence relation `c` equals `c`."] lemma mul_ker_mk_eq : mul_ker (coe : M → c.quotient) (λ x y, rfl) = c := ext $ λ x y, quotient.eq' variables {c} /-- The coercion to the quotient of a congruence relation commutes with multiplication (by definition). -/ @[simp, to_additive "The coercion to the quotient of an additive congruence relation commutes with addition (by definition)."] lemma coe_mul (x y : M) : (↑(x * y) : c.quotient) = ↑x * ↑y := rfl /-- Definition of the function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes. -/ @[simp, to_additive "Definition of the function on the quotient by an additive congruence relation `c` induced by a function that is constant on `c`'s equivalence classes."] protected lemma lift_on_beta {β} (c : con M) (f : M → β) (h : ∀ a b, c a b → f a = f b) (x : M) : con.lift_on (x : c.quotient) f h = f x := rfl /-- Makes an isomorphism of quotients by two congruence relations, given that the relations are equal. -/ @[to_additive "Makes an additive isomorphism of quotients by two additive congruence relations, given that the relations are equal."] protected def congr {c d : con M} (h : c = d) : c.quotient ≃* d.quotient := { map_mul' := λ x y, by rcases x; rcases y; refl, ..quotient.congr (equiv.refl M) $ by apply ext_iff.2 h } -- The complete lattice of congruence relations on a type /-- For congruence relations `c, d` on a type `M` with a multiplication, `c ≤ d` iff `∀ x y ∈ M`, `x` is related to `y` by `d` if `x` is related to `y` by `c`. -/ @[to_additive "For additive congruence relations `c, d` on a type `M` with an addition, `c ≤ d` iff `∀ x y ∈ M`, `x` is related to `y` by `d` if `x` is related to `y` by `c`."] instance : has_le (con M) := ⟨λ c d, ∀ ⦃x y⦄, c x y → d x y⟩ /-- Definition of `≤` for congruence relations. -/ @[to_additive "Definition of `≤` for additive congruence relations."] theorem le_def {c d : con M} : c ≤ d ↔ ∀ {x y}, c x y → d x y := iff.rfl /-- The infimum of a set of congruence relations on a given type with a multiplication. -/ @[to_additive "The infimum of a set of additive congruence relations on a given type with an addition."] instance : has_Inf (con M) := ⟨λ S, ⟨λ x y, ∀ c : con M, c ∈ S → c x y, ⟨λ x c hc, c.refl x, λ _ _ h c hc, c.symm $ h c hc, λ _ _ _ h1 h2 c hc, c.trans (h1 c hc) $ h2 c hc⟩, λ _ _ _ _ h1 h2 c hc, c.mul (h1 c hc) $ h2 c hc⟩⟩ /-- The infimum of a set of congruence relations is the same as the infimum of the set's image under the map to the underlying equivalence relation. -/ @[to_additive "The infimum of a set of additive congruence relations is the same as the infimum of the set's image under the map to the underlying equivalence relation."] lemma Inf_to_setoid (S : set (con M)) : (Inf S).to_setoid = Inf (to_setoid '' S) := setoid.ext' $ λ x y, ⟨λ h r ⟨c, hS, hr⟩, by rw ←hr; exact h c hS, λ h c hS, h c.to_setoid ⟨c, hS, rfl⟩⟩ /-- The infimum of a set of congruence relations is the same as the infimum of the set's image under the map to the underlying binary relation. -/ @[to_additive "The infimum of a set of additive congruence relations is the same as the infimum of the set's image under the map to the underlying binary relation."] lemma Inf_def (S : set (con M)) : (Inf S).r = Inf (r '' S) := by { ext, simp only [Inf_image, infi_apply, infi_Prop_eq], refl } @[to_additive] instance : partial_order (con M) := { le := (≤), lt := λ c d, c ≤ d ∧ ¬d ≤ c, le_refl := λ c _ _, id, le_trans := λ c1 c2 c3 h1 h2 x y h, h2 $ h1 h, lt_iff_le_not_le := λ _ _, iff.rfl, le_antisymm := λ c d hc hd, ext $ λ x y, ⟨λ h, hc h, λ h, hd h⟩ } /-- The complete lattice of congruence relations on a given type with a multiplication. -/ @[to_additive "The complete lattice of additive congruence relations on a given type with an addition."] instance : complete_lattice (con M) := { inf := λ c d, ⟨(c.to_setoid ⊓ d.to_setoid).1, (c.to_setoid ⊓ d.to_setoid).2, λ _ _ _ _ h1 h2, ⟨c.mul h1.1 h2.1, d.mul h1.2 h2.2⟩⟩, inf_le_left := λ _ _ _ _ h, h.1, inf_le_right := λ _ _ _ _ h, h.2, le_inf := λ _ _ _ hb hc _ _ h, ⟨hb h, hc h⟩, top := { mul' := by tauto, ..setoid.complete_lattice.top}, le_top := λ _ _ _ h, trivial, bot := { mul' := λ _ _ _ _ h1 h2, h1 ▸ h2 ▸ rfl, ..setoid.complete_lattice.bot}, bot_le := λ c x y h, h ▸ c.refl x, .. complete_lattice_of_Inf (con M) $ assume s, ⟨λ r hr x y h, (h : ∀ r ∈ s, (r : con M) x y) r hr, λ r hr x y h r' hr', hr hr' h⟩ } /-- The infimum of two congruence relations equals the infimum of the underlying binary operations. -/ @[to_additive "The infimum of two additive congruence relations equals the infimum of the underlying binary operations."] lemma inf_def {c d : con M} : (c ⊓ d).r = c.r ⊓ d.r := rfl /-- Definition of the infimum of two congruence relations. -/ @[to_additive "Definition of the infimum of two additive congruence relations."] theorem inf_iff_and {c d : con M} {x y} : (c ⊓ d) x y ↔ c x y ∧ d x y := iff.rfl /-- The inductively defined smallest congruence relation containing a binary relation `r` equals the infimum of the set of congruence relations containing `r`. -/ @[to_additive add_con_gen_eq "The inductively defined smallest additive congruence relation containing a binary relation `r` equals the infimum of the set of additive congruence relations containing `r`."] theorem con_gen_eq (r : M → M → Prop) : con_gen r = Inf {s : con M | ∀ x y, r x y → s x y} := le_antisymm (λ x y H, con_gen.rel.rec_on H (λ _ _ h _ hs, hs _ _ h) (con.refl _) (λ _ _ _, con.symm _) (λ _ _ _ _ _, con.trans _) $ λ w x y z _ _ h1 h2 c hc, c.mul (h1 c hc) $ h2 c hc) (Inf_le (λ _ _, con_gen.rel.of _ _)) /-- The smallest congruence relation containing a binary relation `r` is contained in any congruence relation containing `r`. -/ @[to_additive add_con_gen_le "The smallest additive congruence relation containing a binary relation `r` is contained in any additive congruence relation containing `r`."] theorem con_gen_le {r : M → M → Prop} {c : con M} (h : ∀ x y, r x y → c.r x y) : con_gen r ≤ c := by rw con_gen_eq; exact Inf_le h /-- Given binary relations `r, s` with `r` contained in `s`, the smallest congruence relation containing `s` contains the smallest congruence relation containing `r`. -/ @[to_additive add_con_gen_mono "Given binary relations `r, s` with `r` contained in `s`, the smallest additive congruence relation containing `s` contains the smallest additive congruence relation containing `r`."] theorem con_gen_mono {r s : M → M → Prop} (h : ∀ x y, r x y → s x y) : con_gen r ≤ con_gen s := con_gen_le $ λ x y hr, con_gen.rel.of _ _ $ h x y hr /-- Congruence relations equal the smallest congruence relation in which they are contained. -/ @[simp, to_additive add_con_gen_of_add_con "Additive congruence relations equal the smallest additive congruence relation in which they are contained."] lemma con_gen_of_con (c : con M) : con_gen c = c := le_antisymm (by rw con_gen_eq; exact Inf_le (λ _ _, id)) con_gen.rel.of /-- The map sending a binary relation to the smallest congruence relation in which it is contained is idempotent. -/ @[simp, to_additive add_con_gen_idem "The map sending a binary relation to the smallest additive congruence relation in which it is contained is idempotent."] lemma con_gen_idem (r : M → M → Prop) : con_gen (con_gen r) = con_gen r := con_gen_of_con _ /-- The supremum of congruence relations `c, d` equals the smallest congruence relation containing the binary relation '`x` is related to `y` by `c` or `d`'. -/ @[to_additive sup_eq_add_con_gen "The supremum of additive congruence relations `c, d` equals the smallest additive congruence relation containing the binary relation '`x` is related to `y` by `c` or `d`'."] lemma sup_eq_con_gen (c d : con M) : c ⊔ d = con_gen (λ x y, c x y ∨ d x y) := begin rw con_gen_eq, apply congr_arg Inf, simp only [le_def, or_imp_distrib, ← forall_and_distrib] end /-- The supremum of two congruence relations equals the smallest congruence relation containing the supremum of the underlying binary operations. -/ @[to_additive "The supremum of two additive congruence relations equals the smallest additive congruence relation containing the supremum of the underlying binary operations."] lemma sup_def {c d : con M} : c ⊔ d = con_gen (c.r ⊔ d.r) := by rw sup_eq_con_gen; refl /-- The supremum of a set of congruence relations `S` equals the smallest congruence relation containing the binary relation 'there exists `c ∈ S` such that `x` is related to `y` by `c`'. -/ @[to_additive Sup_eq_add_con_gen "The supremum of a set of additive congruence relations `S` equals the smallest additive congruence relation containing the binary relation 'there exists `c ∈ S` such that `x` is related to `y` by `c`'."] lemma Sup_eq_con_gen (S : set (con M)) : Sup S = con_gen (λ x y, ∃ c : con M, c ∈ S ∧ c x y) := begin rw con_gen_eq, apply congr_arg Inf, ext, exact ⟨λ h _ _ ⟨r, hr⟩, h hr.1 hr.2, λ h r hS _ _ hr, h _ _ ⟨r, hS, hr⟩⟩, end /-- The supremum of a set of congruence relations is the same as the smallest congruence relation containing the supremum of the set's image under the map to the underlying binary relation. -/ @[to_additive "The supremum of a set of additive congruence relations is the same as the smallest additive congruence relation containing the supremum of the set's image under the map to the underlying binary relation."] lemma Sup_def {S : set (con M)} : Sup S = con_gen (Sup (r '' S)) := begin rw Sup_eq_con_gen, congr, ext x y, erw [Sup_image, supr_apply, supr_apply, supr_Prop_eq], simp only [Sup_image, supr_Prop_eq, supr_apply, supr_Prop_eq, exists_prop], refl, end variables (M) /-- There is a Galois insertion of congruence relations on a type with a multiplication `M` into binary relations on `M`. -/ @[to_additive "There is a Galois insertion of additive congruence relations on a type with an addition `M` into binary relations on `M`."] protected def gi : @galois_insertion (M → M → Prop) (con M) _ _ con_gen r := { choice := λ r h, con_gen r, gc := λ r c, ⟨λ H _ _ h, H $ con_gen.rel.of _ _ h, λ H, con_gen_of_con c ▸ con_gen_mono H⟩, le_l_u := λ x, (con_gen_of_con x).symm ▸ le_refl x, choice_eq := λ _ _, rfl } variables {M} (c) /-- Given a function `f`, the smallest congruence relation containing the binary relation on `f`'s image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by a congruence relation `c`.' -/ @[to_additive "Given a function `f`, the smallest additive congruence relation containing the binary relation on `f`'s image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by an additive congruence relation `c`.'"] def map_gen (f : M → N) : con N := con_gen $ λ x y, ∃ a b, f a = x ∧ f b = y ∧ c a b /-- Given a surjective multiplicative-preserving function `f` whose kernel is contained in a congruence relation `c`, the congruence relation on `f`'s codomain defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by `c`.' -/ @[to_additive "Given a surjective addition-preserving function `f` whose kernel is contained in an additive congruence relation `c`, the additive congruence relation on `f`'s codomain defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by `c`.'"] def map_of_surjective (f : M → N) (H : ∀ x y, f (x * y) = f x * f y) (h : mul_ker f H ≤ c) (hf : surjective f) : con N := { mul' := λ w x y z ⟨a, b, hw, hx, h1⟩ ⟨p, q, hy, hz, h2⟩, ⟨a * p, b * q, by rw [H, hw, hy], by rw [H, hx, hz], c.mul h1 h2⟩, ..c.to_setoid.map_of_surjective f h hf } /-- A specialization of 'the smallest congruence relation containing a congruence relation `c` equals `c`'. -/ @[to_additive "A specialization of 'the smallest additive congruence relation containing an additive congruence relation `c` equals `c`'."] lemma map_of_surjective_eq_map_gen {c : con M} {f : M → N} (H : ∀ x y, f (x * y) = f x * f y) (h : mul_ker f H ≤ c) (hf : surjective f) : c.map_gen f = c.map_of_surjective f H h hf := by rw ←con_gen_of_con (c.map_of_surjective f H h hf); refl /-- Given types with multiplications `M, N` and a congruence relation `c` on `N`, a multiplication-preserving map `f : M → N` induces a congruence relation on `f`'s domain defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `c`.' -/ @[to_additive "Given types with additions `M, N` and an additive congruence relation `c` on `N`, an addition-preserving map `f : M → N` induces an additive congruence relation on `f`'s domain defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `c`.' "] def comap (f : M → N) (H : ∀ x y, f (x * y) = f x * f y) (c : con N) : con M := { mul' := λ w x y z h1 h2, show c (f (w * y)) (f (x * z)), by rw [H, H]; exact c.mul h1 h2, ..c.to_setoid.comap f } section open quotient /-- Given a congruence relation `c` on a type `M` with a multiplication, the order-preserving bijection between the set of congruence relations containing `c` and the congruence relations on the quotient of `M` by `c`. -/ @[to_additive "Given an additive congruence relation `c` on a type `M` with an addition, the order-preserving bijection between the set of additive congruence relations containing `c` and the additive congruence relations on the quotient of `M` by `c`."] def correspondence : ((≤) : {d // c ≤ d} → {d // c ≤ d} → Prop) ≃o ((≤) : con c.quotient → con c.quotient → Prop) := { to_fun := λ d, d.1.map_of_surjective coe _ (by rw mul_ker_mk_eq; exact d.2) $ @exists_rep _ c.to_setoid, inv_fun := λ d, ⟨comap (coe : M → c.quotient) (λ x y, rfl) d, λ _ _ h, show d _ _, by rw c.eq.2 h; exact d.refl _ ⟩, left_inv := λ d, subtype.ext.2 $ ext $ λ _ _, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in d.1.trans (d.1.symm $ d.2 $ c.eq.1 hx) $ d.1.trans H $ d.2 $ c.eq.1 hy, λ h, ⟨_, _, rfl, rfl, h⟩⟩, right_inv := λ d, let Hm : mul_ker (coe : M → c.quotient) (λ x y, rfl) ≤ comap (coe : M → c.quotient) (λ x y, rfl) d := λ x y h, show d _ _, by rw mul_ker_mk_eq at h; exact c.eq.2 h ▸ d.refl _ in ext $ λ x y, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in hx ▸ hy ▸ H, con.induction_on₂ x y $ λ w z h, ⟨w, z, rfl, rfl, h⟩⟩, ord' := λ s t, ⟨λ h _ _ hs, let ⟨a, b, hx, hy, Hs⟩ := hs in ⟨a, b, hx, hy, h Hs⟩, λ h _ _ hs, let ⟨a, b, hx, hy, ht⟩ := h ⟨_, _, rfl, rfl, hs⟩ in t.1.trans (t.1.symm $ t.2 $ eq_rel.1 hx) $ t.1.trans ht $ t.2 $ eq_rel.1 hy⟩ } end end -- Monoids variables {M} [monoid M] [monoid N] [monoid P] (c : con M) /-- The quotient of a monoid by a congruence relation is a monoid. -/ @[to_additive add_monoid "The quotient of an `add_monoid` by an additive congruence relation is an `add_monoid`."] instance monoid : monoid c.quotient := { one := ((1 : M) : c.quotient), mul := (*), mul_assoc := λ x y z, quotient.induction_on₃' x y z $ λ _ _ _, congr_arg coe $ mul_assoc _ _ _, mul_one := λ x, quotient.induction_on' x $ λ _, congr_arg coe $ mul_one _, one_mul := λ x, quotient.induction_on' x $ λ _, congr_arg coe $ one_mul _ } /-- The quotient of a `comm_monoid` by a congruence relation is a `comm_monoid`. -/ @[to_additive add_comm_monoid "The quotient of an `add_comm_monoid` by an additive congruence relation is an `add_comm_monoid`."] instance comm_monoid {α : Type*} [comm_monoid α] (c : con α) : comm_monoid c.quotient := { mul_comm := λ x y, con.induction_on₂ x y $ λ w z, by rw [←coe_mul, ←coe_mul, mul_comm], ..c.monoid} variables {c} /-- The 1 of the quotient of a monoid by a congruence relation is the equivalence class of the monoid's 1. -/ @[simp, to_additive "The 0 of the quotient of an `add_monoid` by an additive congruence relation is the equivalence class of the `add_monoid`'s 0."] lemma coe_one : ((1 : M) : c.quotient) = 1 := rfl variables (M c) /-- The submonoid of `M × M` defined by a congruence relation on a monoid `M`. -/ @[to_additive add_submonoid "The `add_submonoid` of `M × M` defined by an additive congruence relation on an `add_monoid` `M`."] protected def submonoid : submonoid (M × M) := { carrier := { x | c x.1 x.2 }, one_mem' := c.iseqv.1 1, mul_mem' := λ _ _, c.mul } variables {M c} /-- The congruence relation on a monoid `M` from a submonoid of `M × M` for which membership is an equivalence relation. -/ @[to_additive of_add_submonoid "The additive congruence relation on an `add_monoid` `M` from an `add_submonoid` of `M × M` for which membership is an equivalence relation."] def of_submonoid (N : submonoid (M × M)) (H : equivalence (λ x y, (x, y) ∈ N)) : con M := { r := λ x y, (x, y) ∈ N, iseqv := H, mul' := λ _ _ _ _, N.mul_mem } /-- Coercion from a congruence relation `c` on a monoid `M` to the submonoid of `M × M` whose elements are `(x, y)` such that `x` is related to `y` by `c`. -/ @[to_additive to_add_submonoid "Coercion from a congruence relation `c` on an `add_monoid` `M` to the `add_submonoid` of `M × M` whose elements are `(x, y)` such that `x` is related to `y` by `c`."] instance to_submonoid : has_coe (con M) (submonoid (M × M)) := ⟨λ c, c.submonoid M⟩ @[to_additive] lemma mem_coe {c : con M} {x y} : (x, y) ∈ (↑c : submonoid (M × M)) ↔ (x, y) ∈ c := iff.rfl @[to_additive to_add_submonoid_inj] theorem to_submonoid_inj (c d : con M) (H : (c : submonoid (M × M)) = d) : c = d := ext $ λ x y, show (x, y) ∈ (c : submonoid (M × M)) ↔ (x, y) ∈ ↑d, by rw H @[to_additive] lemma le_iff {c d : con M} : c ≤ d ↔ (c : submonoid (M × M)) ≤ d := ⟨λ h x H, h H, λ h x y hc, h $ show (x, y) ∈ c, from hc⟩ /-- The kernel of a monoid homomorphism as a congruence relation. -/ @[to_additive "The kernel of an `add_monoid` homomorphism as an additive congruence relation."] def ker (f : M →* P) : con M := mul_ker f f.3 /-- The definition of the congruence relation defined by a monoid homomorphism's kernel. -/ @[to_additive "The definition of the additive congruence relation defined by an `add_monoid` homomorphism's kernel."] lemma ker_rel (f : M →* P) {x y} : ker f x y ↔ f x = f y := iff.rfl /-- There exists an element of the quotient of a monoid by a congruence relation (namely 1). -/ @[to_additive "There exists an element of the quotient of an `add_monoid` by a congruence relation (namely 0)."] instance quotient.inhabited : inhabited c.quotient := ⟨((1 : M) : c.quotient)⟩ variables (c) /-- The natural homomorphism from a monoid to its quotient by a congruence relation. -/ @[to_additive "The natural homomorphism from an `add_monoid` to its quotient by an additive congruence relation."] def mk' : M →* c.quotient := ⟨coe, rfl, λ _ _, rfl⟩ variables (x y : M) /-- The kernel of the natural homomorphism from a monoid to its quotient by a congruence relation `c` equals `c`. -/ @[simp, to_additive "The kernel of the natural homomorphism from an `add_monoid` to its quotient by an additive congruence relation `c` equals `c`."] lemma mk'_ker : ker c.mk' = c := ext $ λ _ _, c.eq variables {c} /-- The natural homomorphism from a monoid to its quotient by a congruence relation is surjective. -/ @[to_additive "The natural homomorphism from an `add_monoid` to its quotient by a congruence relation is surjective."] lemma mk'_surjective : surjective c.mk' := λ x, by rcases x; exact ⟨x, rfl⟩ @[simp, to_additive] lemma comp_mk'_apply (g : c.quotient →* P) {x} : g.comp c.mk' x = g x := rfl /-- The elements related to `x ∈ M`, `M` a monoid, by the kernel of a monoid homomorphism are those in the preimage of `f(x)` under `f`. -/ @[to_additive "The elements related to `x ∈ M`, `M` an `add_monoid`, by the kernel of an `add_monoid` homomorphism are those in the preimage of `f(x)` under `f`. "] lemma ker_apply_eq_preimage {f : M →* P} (x) : (ker f) x = f ⁻¹' {f x} := set.ext $ λ x, ⟨λ h, set.mem_preimage.2 $ set.mem_singleton_iff.2 h.symm, λ h, (set.mem_singleton_iff.1 $ set.mem_preimage.1 h).symm⟩ /-- Given a monoid homomorphism `f : N → M` and a congruence relation `c` on `M`, the congruence relation induced on `N` by `f` equals the kernel of `c`'s quotient homomorphism composed with `f`. -/ @[to_additive "Given an `add_monoid` homomorphism `f : N → M` and an additive congruence relation `c` on `M`, the additive congruence relation induced on `N` by `f` equals the kernel of `c`'s quotient homomorphism composed with `f`."] lemma comap_eq {f : N →* M} : comap f f.map_mul c = ker (c.mk'.comp f) := ext $ λ x y, show c _ _ ↔ c.mk' _ = c.mk' _, by rw ←c.eq; refl variables (c) (f : M →* P) /-- The homomorphism on the quotient of a monoid by a congruence relation `c` induced by a homomorphism constant on `c`'s equivalence classes. -/ @[to_additive "The homomorphism on the quotient of an `add_monoid` by an additive congruence relation `c` induced by a homomorphism constant on `c`'s equivalence classes."] def lift (H : c ≤ ker f) : c.quotient →* P := { to_fun := λ x, con.lift_on x f $ λ _ _ h, H h, map_one' := by rw ←f.map_one; refl, map_mul' := λ x y, con.induction_on₂ x y $ λ m n, f.map_mul m n ▸ rfl } variables {c f} /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] lemma lift_mk' (H : c ≤ ker f) (x) : c.lift f H (c.mk' x) = f x := rfl /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] lemma lift_coe (H : c ≤ ker f) (x : M) : c.lift f H x = f x := rfl /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] theorem lift_comp_mk' (H : c ≤ ker f) : (c.lift f H).comp c.mk' = f := by ext; refl /-- Given a homomorphism `f` from the quotient of a monoid by a congruence relation, `f` equals the homomorphism on the quotient induced by `f` composed with the natural map from the monoid to the quotient. -/ @[simp, to_additive "Given a homomorphism `f` from the quotient of an `add_monoid` by an additive congruence relation, `f` equals the homomorphism on the quotient induced by `f` composed with the natural map from the `add_monoid` to the quotient."] lemma lift_apply_mk' (f : c.quotient →* P) : c.lift (f.comp c.mk') (λ x y h, show f ↑x = f ↑y, by rw c.eq.2 h) = f := by ext; rcases x; refl /-- Homomorphisms on the quotient of a monoid by a congruence relation are equal if they are equal on elements that are coercions from the monoid. -/ @[to_additive "Homomorphisms on the quotient of an `add_monoid` by an additive congruence relation are equal if they are equal on elements that are coercions from the `add_monoid`."] lemma lift_funext (f g : c.quotient →* P) (h : ∀ a : M, f a = g a) : f = g := begin rw [←lift_apply_mk' f, ←lift_apply_mk' g], congr' 1, exact monoid_hom.ext_iff.2 h, end /-- The uniqueness part of the universal property for quotients of monoids. -/ @[to_additive "The uniqueness part of the universal property for quotients of `add_monoid`s."] theorem lift_unique (H : c ≤ ker f) (g : c.quotient →* P) (Hg : g.comp c.mk' = f) : g = c.lift f H := lift_funext g (c.lift f H) $ λ x, by rw [lift_coe H, ←comp_mk'_apply, Hg] /-- Given a congruence relation `c` on a monoid and a homomorphism `f` constant on `c`'s equivalence classes, `f` has the same image as the homomorphism that `f` induces on the quotient. -/ @[to_additive "Given an additive congruence relation `c` on an `add_monoid` and a homomorphism `f` constant on `c`'s equivalence classes, `f` has the same image as the homomorphism that `f` induces on the quotient."] theorem lift_range (H : c ≤ ker f) : (c.lift f H).mrange = f.mrange := submonoid.ext $ λ x, ⟨λ ⟨y, hy⟩, by revert hy; rcases y; exact λ hy, ⟨y, hy.1, by rw [hy.2.symm, ←lift_coe H]; refl⟩, λ ⟨y, hy⟩, ⟨↑y, hy.1, by rw ←hy.2; refl⟩⟩ /-- Surjective monoid homomorphisms constant on a congruence relation `c`'s equivalence classes induce a surjective homomorphism on `c`'s quotient. -/ @[to_additive "Surjective `add_monoid` homomorphisms constant on an additive congruence relation `c`'s equivalence classes induce a surjective homomorphism on `c`'s quotient."] lemma lift_surjective_of_surjective (h : c ≤ ker f) (hf : surjective f) : surjective (c.lift f h) := λ y, exists.elim (hf y) $ λ w hw, ⟨w, (lift_mk' h w).symm ▸ hw⟩ variables (c f) /-- Given a monoid homomorphism `f` from `M` to `P`, the kernel of `f` is the unique congruence relation on `M` whose induced map from the quotient of `M` to `P` is injective. -/ @[to_additive "Given an `add_monoid` homomorphism `f` from `M` to `P`, the kernel of `f` is the unique additive congruence relation on `M` whose induced map from the quotient of `M` to `P` is injective."] lemma ker_eq_lift_of_injective (H : c ≤ ker f) (h : injective (c.lift f H)) : ker f = c := to_setoid_inj $ ker_eq_lift_of_injective f H h variables {c} /-- The homomorphism induced on the quotient of a monoid by the kernel of a monoid homomorphism. -/ @[to_additive "The homomorphism induced on the quotient of an `add_monoid` by the kernel of an `add_monoid` homomorphism."] def ker_lift : (ker f).quotient →* P := (ker f).lift f $ λ _ _, id variables {f} /-- The diagram described by the universal property for quotients of monoids, when the congruence relation is the kernel of the homomorphism, commutes. -/ @[simp, to_additive "The diagram described by the universal property for quotients of `add_monoid`s, when the additive congruence relation is the kernel of the homomorphism, commutes."] lemma ker_lift_mk (x : M) : ker_lift f x = f x := rfl /-- Given a monoid homomorphism `f`, the induced homomorphism on the quotient by `f`'s kernel has the same image as `f`. -/ @[simp, to_additive "Given an `add_monoid` homomorphism `f`, the induced homomorphism on the quotient by `f`'s kernel has the same image as `f`."] lemma ker_lift_range_eq : (ker_lift f).mrange = f.mrange := lift_range $ λ _ _, id /-- A monoid homomorphism `f` induces an injective homomorphism on the quotient by `f`'s kernel. -/ @[to_additive "An `add_monoid` homomorphism `f` induces an injective homomorphism on the quotient by `f`'s kernel."] lemma injective_ker_lift (f : M →* P) : injective (ker_lift f) := λ x y, quotient.induction_on₂' x y $ λ _ _, (ker f).eq.2 /-- Given congruence relations `c, d` on a monoid such that `d` contains `c`, `d`'s quotient map induces a homomorphism from the quotient by `c` to the quotient by `d`. -/ @[to_additive "Given additive congruence relations `c, d` on an `add_monoid` such that `d` contains `c`, `d`'s quotient map induces a homomorphism from the quotient by `c` to the quotient by `d`."] def map (c d : con M) (h : c ≤ d) : c.quotient →* d.quotient := c.lift d.mk' $ λ x y hc, show (ker d.mk') x y, from (mk'_ker d).symm ▸ h hc /-- Given congruence relations `c, d` on a monoid such that `d` contains `c`, the definition of the homomorphism from the quotient by `c` to the quotient by `d` induced by `d`'s quotient map. -/ @[to_additive "Given additive congruence relations `c, d` on an `add_monoid` such that `d` contains `c`, the definition of the homomorphism from the quotient by `c` to the quotient by `d` induced by `d`'s quotient map."] lemma map_apply {c d : con M} (h : c ≤ d) (x) : c.map d h x = c.lift d.mk' (λ x y hc, d.eq.2 $ h hc) x := rfl variables (c) /-- The first isomorphism theorem for monoids. -/ @[to_additive "The first isomorphism theorem for `add_monoid`s."] noncomputable def quotient_ker_equiv_range (f : M →* P) : (ker f).quotient ≃* f.mrange := { map_mul' := monoid_hom.map_mul _, ..@equiv.of_bijective _ _ ((@mul_equiv.to_monoid_hom (ker_lift f).mrange _ _ _ $ mul_equiv.submonoid_congr ker_lift_range_eq).comp (ker_lift f).mrange_restrict) $ (equiv.bijective _).comp ⟨λ x y h, injective_ker_lift f $ by rcases x; rcases y; injections, λ ⟨w, z, hzm, hz⟩, ⟨z, by rcases hz; rcases _x; refl⟩⟩ } /-- The first isomorphism theorem for monoids in the case of a surjective homomorphism. -/ @[to_additive "The first isomorphism theorem for `add_monoid`s in the case of a surjective homomorphism."] noncomputable def quotient_ker_equiv_of_surjective (f : M →* P) (hf : surjective f) : (ker f).quotient ≃* P := { map_mul' := monoid_hom.map_mul _, ..@equiv.of_bijective _ _ (ker_lift f) ⟨injective_ker_lift f, lift_surjective_of_surjective (le_refl _) hf⟩ } /-- The second isomorphism theorem for monoids. -/ @[to_additive "The second isomorphism theorem for `add_monoid`s."] noncomputable def comap_quotient_equiv (f : N →* M) : (comap f f.map_mul c).quotient ≃* (c.mk'.comp f).mrange := (con.congr comap_eq).trans $ quotient_ker_equiv_range $ c.mk'.comp f /-- The third isomorphism theorem for monoids. -/ @[to_additive "The third isomorphism theorem for `add_monoid`s."] def quotient_quotient_equiv_quotient (c d : con M) (h : c ≤ d) : (ker (c.map d h)).quotient ≃* d.quotient := { map_mul' := λ x y, con.induction_on₂ x y $ λ w z, con.induction_on₂ w z $ λ a b, show _ = d.mk' a * d.mk' b, by rw ←d.mk'.map_mul; refl, ..quotient_quotient_equiv_quotient c.to_setoid d.to_setoid h } end con
b827bece41cdd744feb3c9e2fdf7b1ba6b736dcb
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/category_theory/adjunction/fully_faithful.lean
0bba89b066cb20259512e4fdce53627f3a61520c
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,577
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.adjunction.basic import category_theory.conj import category_theory.yoneda /-! # Adjoints of fully faithful functors A left adjoint is fully faithful, if and only if the unit is an isomorphism (and similarly for right adjoints and the counit). `adjunction.restrict_fully_faithful` shows that an adjunction can be restricted along fully faithful inclusions. ## Future work The statements from Riehl 4.5.13 for adjoints which are either full, or faithful. -/ open category_theory namespace category_theory universes v₁ v₂ u₁ u₂ open category open opposite variables {C : Type u₁} [category.{v₁} C] variables {D : Type u₂} [category.{v₂} D] variables {L : C ⥤ D} {R : D ⥤ C} (h : L ⊣ R) /-- If the left adjoint is fully faithful, then the unit is an isomorphism. See * Lemma 4.5.13 from [Riehl][riehl2017] * https://math.stackexchange.com/a/2727177 * https://stacks.math.columbia.edu/tag/07RB (we only prove the forward direction!) -/ instance unit_is_iso_of_L_fully_faithful [full L] [faithful L] : is_iso (adjunction.unit h) := @nat_iso.is_iso_of_is_iso_app _ _ _ _ _ _ (adjunction.unit h) $ λ X, @yoneda.is_iso _ _ _ _ ((adjunction.unit h).app X) ⟨⟨{ app := λ Y f, L.preimage ((h.hom_equiv (unop Y) (L.obj X)).symm f) }, ⟨begin ext x f, dsimp, apply L.map_injective, simp, end, begin ext x f, dsimp, simp only [adjunction.hom_equiv_counit, preimage_comp, preimage_map, category.assoc], rw ←h.unit_naturality, simp, end⟩⟩⟩ /-- If the right adjoint is fully faithful, then the counit is an isomorphism. See https://stacks.math.columbia.edu/tag/07RB (we only prove the forward direction!) -/ instance counit_is_iso_of_R_fully_faithful [full R] [faithful R] : is_iso (adjunction.counit h) := @nat_iso.is_iso_of_is_iso_app _ _ _ _ _ _ (adjunction.counit h) $ λ X, @is_iso_of_op _ _ _ _ _ $ @coyoneda.is_iso _ _ _ _ ((adjunction.counit h).app X).op ⟨⟨{ app := λ Y f, R.preimage ((h.hom_equiv (R.obj X) Y) f) }, ⟨begin ext x f, dsimp, apply R.map_injective, simp, end, begin ext x f, dsimp, simp only [adjunction.hom_equiv_unit, preimage_comp, preimage_map], rw ←h.counit_naturality, simp, end⟩⟩⟩ /-- If the unit of an adjunction is an isomorphism, then its inverse on the image of L is given by L whiskered with the counit. -/ @[simp] lemma inv_map_unit {X : C} [is_iso (h.unit.app X)] : inv (L.map (h.unit.app X)) = h.counit.app (L.obj X) := is_iso.inv_eq_of_hom_inv_id h.left_triangle_components /-- If the unit is an isomorphism, bundle one has an isomorphism `L ⋙ R ⋙ L ≅ L`. -/ @[simps] noncomputable def whisker_left_L_counit_iso_of_is_iso_unit [is_iso h.unit] : L ⋙ R ⋙ L ≅ L := (L.associator R L).symm ≪≫ iso_whisker_right (as_iso h.unit).symm L ≪≫ functor.left_unitor _ /-- If the counit of an adjunction is an isomorphism, then its inverse on the image of R is given by R whiskered with the unit. -/ @[simp] lemma inv_counit_map {X : D} [is_iso (h.counit.app X)] : inv (R.map (h.counit.app X)) = h.unit.app (R.obj X) := is_iso.inv_eq_of_inv_hom_id h.right_triangle_components /-- If the counit of an is an isomorphism, one has an isomorphism `(R ⋙ L ⋙ R) ≅ R`. -/ @[simps] noncomputable def whisker_left_R_unit_iso_of_is_iso_counit [is_iso h.counit] : (R ⋙ L ⋙ R) ≅ R := (R.associator L R).symm ≪≫ iso_whisker_right (as_iso h.counit) R ≪≫ functor.left_unitor _ /-- If the unit is an isomorphism, then the left adjoint is full-/ noncomputable def L_full_of_unit_is_iso [is_iso h.unit] : full L := { preimage := λ X Y f, (h.hom_equiv X (L.obj Y) f) ≫ inv (h.unit.app Y) } /-- If the unit is an isomorphism, then the left adjoint is faithful-/ lemma L_faithful_of_unit_is_iso [is_iso h.unit] : faithful L := { map_injective' := λ X Y f g H, begin rw ←(h.hom_equiv X (L.obj Y)).apply_eq_iff_eq at H, simpa using H =≫ inv (h.unit.app Y), end } /-- If the counit is an isomorphism, then the right adjoint is full-/ noncomputable def R_full_of_counit_is_iso [is_iso h.counit] : full R := { preimage := λ X Y f, inv (h.counit.app X) ≫ (h.hom_equiv (R.obj X) Y).symm f } /-- If the counit is an isomorphism, then the right adjoint is faithful-/ lemma R_faithful_of_counit_is_iso [is_iso h.counit] : faithful R := { map_injective' := λ X Y f g H, begin rw ←(h.hom_equiv (R.obj X) Y).symm.apply_eq_iff_eq at H, simpa using inv (h.counit.app X) ≫= H, end } -- TODO also do the statements from Riehl 4.5.13 for full and faithful separately? universes v₃ v₄ u₃ u₄ variables {C' : Type u₃} [category.{v₃} C'] variables {D' : Type u₄} [category.{v₄} D'] -- TODO: This needs some lemmas describing the produced adjunction, probably in terms of `adj`, -- `iC` and `iD`. /-- If `C` is a full subcategory of `C'` and `D` is a full subcategory of `D'`, then we can restrict an adjunction `L' ⊣ R'` where `L' : C' ⥤ D'` and `R' : D' ⥤ C'` to `C` and `D`. The construction here is slightly more general, in that `C` is required only to have a full and faithful "inclusion" functor `iC : C ⥤ C'` (and similarly `iD : D ⥤ D'`) which commute (up to natural isomorphism) with the proposed restrictions. -/ def adjunction.restrict_fully_faithful (iC : C ⥤ C') (iD : D ⥤ D') {L' : C' ⥤ D'} {R' : D' ⥤ C'} (adj : L' ⊣ R') {L : C ⥤ D} {R : D ⥤ C} (comm1 : iC ⋙ L' ≅ L ⋙ iD) (comm2 : iD ⋙ R' ≅ R ⋙ iC) [full iC] [faithful iC] [full iD] [faithful iD] : L ⊣ R := adjunction.mk_of_hom_equiv { hom_equiv := λ X Y, calc (L.obj X ⟶ Y) ≃ (iD.obj (L.obj X) ⟶ iD.obj Y) : equiv_of_fully_faithful iD ... ≃ (L'.obj (iC.obj X) ⟶ iD.obj Y) : iso.hom_congr (comm1.symm.app X) (iso.refl _) ... ≃ (iC.obj X ⟶ R'.obj (iD.obj Y)) : adj.hom_equiv _ _ ... ≃ (iC.obj X ⟶ iC.obj (R.obj Y)) : iso.hom_congr (iso.refl _) (comm2.app Y) ... ≃ (X ⟶ R.obj Y) : (equiv_of_fully_faithful iC).symm, hom_equiv_naturality_left_symm' := λ X' X Y f g, begin apply iD.map_injective, simpa using (comm1.inv.naturality_assoc f _).symm, end, hom_equiv_naturality_right' := λ X Y' Y f g, begin apply iC.map_injective, suffices : R'.map (iD.map g) ≫ comm2.hom.app Y = comm2.hom.app Y' ≫ iC.map (R.map g), simp [this], apply comm2.hom.naturality g, end } end category_theory
1f6f0dbfc279d4e6e4e2790a49397829686d6fe9
3f48345ac9bbaa421714efc9872a0409379bb4ae
/src/set_category/colimits/Pushout.lean
45412d740cb16e1d499ba199c3a3d742b2edc25d
[]
no_license
QaisHamarneh/Coalgebra-in-Lean
b4318ee6d83780e5c734eb78fed98b1fe8016f7e
bd0452df98bc64b608e5dfd7babc42c301bb6a46
refs/heads/master
1,663,371,200,241
1,661,004,695,000
1,661,004,695,000
209,798,828
0
0
null
null
null
null
UTF-8
Lean
false
false
4,033
lean
import category_theory.types import help_functions import set_category.colimits.Sum import set_category.colimits.Coequalizer import tactic.tidy universes u v namespace Pushout open category_theory set classical help_functions sum Sum Coequalizer local notation f ` ⊚ `:80 g:80 := category_struct.comp g f def is_pushout {X : Type v} [category X] {A B₁ B₂: X} (f : A ⟶ B₁) (g : A ⟶ B₂) (P : X) (p₁ : B₁ ⟶ P) (p₂ : B₂ ⟶ P) : Prop := p₁ ⊚ f = p₂ ⊚ g ∧ Π (Q : X) (q₁ : B₁ ⟶ Q) (q₂ : B₂ ⟶ Q), q₁ ⊚ f = q₂ ⊚ g → (∃! h : P ⟶ Q, q₁ = h ⊚ p₁ ∧ q₂ = h ⊚ p₂) lemma coequalizer_sum_is_pushout_cat {X : Type v} [category X] {A B₁ B₂: X} (f : A ⟶ B₁) (g : A ⟶ B₂) (S P : X) (s₁ : B₁ ⟶ S) (s₂ : B₂ ⟶ S) (p : S ⟶ P) (is_sm : is_sum S s₁ s₂) (is_coeq: is_coequalizer (s₁ ⊚ f) (s₂ ⊚ g) p): is_pushout f g P (p ⊚ s₁) (p ⊚ s₂) := begin have comm : (p ⊚ s₁) ⊚ f = (p ⊚ s₂) ⊚ g := by tidy, split, exact comm, intros Q q₁ q₂ qfg, have sm : _ := is_sm Q q₁ q₂, let s := some sm, have spec : q₁ = s ⊚ s₁ ∧ q₂ = s ⊚ s₂ := (some_spec sm).1, have sf_sg : s ⊚ s₁ ⊚ f = s ⊚ s₂ ⊚ g := calc (s ⊚ s₁) ⊚ f = q₁ ⊚ f : by rw ← spec.1 ... = q₂ ⊚ g : qfg ... = s ⊚ s₂ ⊚ g : by rw spec.2, have coeq : ∃! (h : P ⟶ Q), h ⊚ p = s := is_coeq.2 Q s (by tidy), let h := some coeq, have h_spec : s = h ⊚ p := eq.symm (some_spec coeq).1, use h, split, split, by simp [h_spec , spec.1], by simp [h_spec , spec.2], intros q spec_q, have h01 : q₁ = q ⊚ p ⊚ s₁ := by tidy, have h02 : q₂ = q ⊚ p ⊚ s₂ := by tidy, have q_s : q ⊚ p = s := jointly_epi_cat s₁ s₂ is_sm (q ⊚ p) s (spec.1 ▸ (eq.symm h01)) (spec.2 ▸ (eq.symm h02)), exact (some_spec coeq).2 q q_s end variables {A B₁ B₂: Type u} (f : A ⟶ B₁) (g : A ⟶ B₂) lemma coequalizer_sum_is_pushout : let S := B₁ ⊕ B₂ in let B_Θ := @theta A S (inl ∘ f) (inr ∘ g) in let π_Θ := @coequalizer A S (inl ∘ f) (inr ∘ g) in is_pushout f g B_Θ (π_Θ ∘ inl) (π_Θ ∘ inr) := begin intros S B_Θ π_Θ, have is_sm : _ := @disjoint_union_is_sum B₁ B₂, have is_coeq: _ := @quot_is_coequalizer A S (inl ∘ f) (inr ∘ g), have comm : (π_Θ ∘ inl) ∘ f = (π_Θ ∘ inr) ∘ g := by tidy, split, exact comm, intros Q q₁ q₂ qfg, have sm : _ := is_sm Q q₁ q₂, let s := some sm, have spec : q₁ = s ∘ inl ∧ q₂ = s ∘ inr := (some_spec sm).1, have sf_sg : s ∘ inl ∘ f = s ∘ inr ∘ g := calc (s ∘ inl) ∘ f = q₁ ∘ f : by rw ← spec.1 ... = q₂ ∘ g : qfg ... = s ∘ inr ∘ g : by rw spec.2, have coeq : ∃! (h : B_Θ → Q), h ∘ π_Θ = s := is_coeq.2 Q s sf_sg, let h := some coeq, have h_spec : s = h ∘ π_Θ := eq.symm (some_spec coeq).1, use h, split, split, by simp [h_spec , spec.1], by simp [h_spec , spec.2], intros q spec_q, have q_s : q ∘ π_Θ = s := jointly_epi s (q ∘ π_Θ) (spec.1 ▸ (eq.symm spec_q.1)) (spec.2 ▸ (eq.symm spec_q.2)), exact (some_spec coeq).2 q q_s end end Pushout
728074ea11b41ee407046e964ef78bb154738b20
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/tests/lean/run/tactic11.lean
86c612f5f6cf3080de28848358cda22b3e480350
[ "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
287
lean
import logic theorem tst (a b : Prop) (H : a ↔ b) : b ↔ a := have H1 [fact] : a → b, -- We need to mark H1 as fact, otherwise it is not visible by tactics from iff_elim_left H, by apply iff_intro; apply (assume Hb, iff_elim_right H Hb); apply (assume Ha, H1 Ha)
c164d59cc354eb1b2efcdfc095e9ddee9e1db126
b561a44b48979a98df50ade0789a21c79ee31288
/stage0/src/Lean/MetavarContext.lean
3860b2970af597d84b1c7c8a7c2c198450f9bc80
[ "Apache-2.0" ]
permissive
3401ijk/lean4
97659c475ebd33a034fed515cb83a85f75ccfb06
a5b1b8de4f4b038ff752b9e607b721f15a9a4351
refs/heads/master
1,693,933,007,651
1,636,424,845,000
1,636,424,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
54,428
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.MonadCache import Lean.LocalContext namespace Lean /- The metavariable context stores metavariable declarations and their assignments. It is used in the elaborator, tactic framework, unifier (aka `isDefEq`), and type class resolution (TC). First, we list all the requirements imposed by these modules. - We may invoke TC while executing `isDefEq`. We need this feature to be able to solve unification problems such as: ``` f ?a (ringAdd ?s) ?x ?y =?= f Int intAdd n m ``` where `(?a : Type) (?s : Ring ?a) (?x ?y : ?a)` During `isDefEq` (i.e., unification), it will need to solve the constrain ``` ringAdd ?s =?= intAdd ``` We say `ringAdd ?s` is stuck because it cannot be reduced until we synthesize the term `?s : Ring ?a` using TC. This can be done since we have assigned `?a := Int` when solving `?a =?= Int`. - TC uses `isDefEq`, and `isDefEq` may create TC problems as shown above. Thus, we may have nested TC problems. - `isDefEq` extends the local context when going inside binders. Thus, the local context for nested TC may be an extension of the local context for outer TC. - TC should not assign metavariables created by the elaborator, simp, tactic framework, and outer TC problems. Reason: TC commits to the first solution it finds. Consider the TC problem `Coe Nat ?x`, where `?x` is a metavariable created by the caller. There are many solutions to this problem (e.g., `?x := Int`, `?x := Real`, ...), and it doesn’t make sense to commit to the first one since TC does not know the constraints the caller may impose on `?x` after the TC problem is solved. Remark: we claim it is not feasible to make the whole system backtrackable, and allow the caller to backtrack back to TC and ask it for another solution if the first one found did not work. We claim it would be too inefficient. - TC metavariables should not leak outside of TC. Reason: we want to get rid of them after we synthesize the instance. - `simp` invokes `isDefEq` for matching the left-hand-side of equations to terms in our goal. Thus, it may invoke TC indirectly. - In Lean3, we didn’t have to create a fresh pattern for trying to match the left-hand-side of equations when executing `simp`. We had a mechanism called "tmp" metavariables. It avoided this overhead, but it created many problems since `simp` may indirectly call TC which may recursively call TC. Moreover, we may want to allow TC to invoke tactics in the future. Thus, when `simp` invokes `isDefEq`, it may indirectly invoke a tactic and `simp` itself. The Lean3 approach assumed that metavariables were short-lived, this is not true in Lean4, and to some extent was also not true in Lean3 since `simp`, in principle, could trigger an arbitrary number of nested TC problems. - Here are some possible call stack traces we could have in Lean3 (and Lean4). ``` Elaborator (-> TC -> isDefEq)+ Elaborator -> isDefEq (-> TC -> isDefEq)* Elaborator -> simp -> isDefEq (-> TC -> isDefEq)* ``` In Lean4, TC may also invoke tactics in the future. - In Lean3 and Lean4, TC metavariables are not really short-lived. We solve an arbitrary number of unification problems, and we may have nested TC invocations. - TC metavariables do not share the same local context even in the same invocation. In the C++ and Lean implementations we use a trick to ensure they do: https://github.com/leanprover/lean/blob/92826917a252a6092cffaf5fc5f1acb1f8cef379/src/library/type_context.cpp#L3583-L3594 - Metavariables may be natural, synthetic or syntheticOpaque. a) Natural metavariables may be assigned by unification (i.e., `isDefEq`). b) Synthetic metavariables may still be assigned by unification, but whenever possible `isDefEq` will avoid the assignment. For example, if we have the unification constaint `?m =?= ?n`, where `?m` is synthetic, but `?n` is not, `isDefEq` solves it by using the assignment `?n := ?m`. We use synthetic metavariables for type class resolution. Any module that creates synthetic metavariables, must also check whether they have been assigned by `isDefEq`, and then still synthesize them, and check whether the sythesized result is compatible with the one assigned by `isDefEq`. c) SyntheticOpaque metavariables are never assigned by `isDefEq`. That is, the constraint `?n =?= Nat.succ Nat.zero` always fail if `?n` is a syntheticOpaque metavariable. This kind of metavariable is created by tactics such as `intro`. Reason: in the tactic framework, subgoals as represented as metavariables, and a subgoal `?n` is considered as solved whenever the metavariable is assigned. This distinction was not precise in Lean3 and produced counterintuitive behavior. For example, the following hack was added in Lean3 to work around one of these issues: https://github.com/leanprover/lean/blob/92826917a252a6092cffaf5fc5f1acb1f8cef379/src/library/type_context.cpp#L2751 - When creating lambda/forall expressions, we need to convert/abstract free variables and convert them to bound variables. Now, suppose we a trying to create a lambda/forall expression by abstracting free variable `xs` and a term `t[?m]` which contains a metavariable `?m`, and the local context of `?m` contains `xs`. The term ``` fun xs => t[?m] ``` will be ill-formed if we later assign a term `s` to `?m`, and `s` contains free variables in `xs`. We address this issue by changing the free variable abstraction procedure. We consider two cases: `?m` is natural, `?m` is synthetic. Assume the type of `?m` is `A[xs]`. Then, in both cases we create an auxiliary metavariable `?n` with type `forall xs => A[xs]`, and local context := local context of `?m` - `xs`. In both cases, we produce the term `fun xs => t[?n xs]` 1- If `?m` is natural or synthetic, then we assign `?m := ?n xs`, and we produce the term `fun xs => t[?n xs]` 2- If `?m` is syntheticOpaque, then we mark `?n` as a syntheticOpaque variable. However, `?n` is managed by the metavariable context itself. We say we have a "delayed assignment" `?n xs := ?m`. That is, after a term `s` is assigned to `?m`, and `s` does not contain metavariables, we replace any occurrence `?n ts` with `s[xs := ts]`. Gruesome details: - When we create the type `forall xs => A` for `?n`, we may encounter the same issue if `A` contains metavariables. So, the process above is recursive. We claim it terminates because we keep creating new metavariables with smaller local contexts. - Suppose, we have `t[?m]` and we want to create a let-expression by abstracting a let-decl free variable `x`, and the local context of `?m` contatins `x`. Similarly to the previous case ``` let x : T := v; t[?m] ``` will be ill-formed if we later assign a term `s` to `?m`, and `s` contains free variable `x`. Again, assume the type of `?m` is `A[x]`. 1- If `?m` is natural or synthetic, then we create `?n : (let x : T := v; A[x])` with and local context := local context of `?m` - `x`, we assign `?m := ?n`, and produce the term `let x : T := v; t[?n]`. That is, we are just making sure `?n` must never be assigned to a term containing `x`. 2- If `?m` is syntheticOpaque, we create a fresh syntheticOpaque `?n` with type `?n : T -> (let x : T := v; A[x])` and local context := local context of `?m` - `x`, create the delayed assignment `?n #[x] := ?m`, and produce the term `let x : T := v; t[?n x]`. Now suppose we assign `s` to `?m`. We do not assign the term `fun (x : T) => s` to `?n`, since `fun (x : T) => s` may not even be type correct. Instead, we just replace applications `?n r` with `s[x/r]`. The term `r` may not necessarily be a bound variable. For example, a tactic may have reduced `let x : T := v; t[?n x]` into `t[?n v]`. We are essentially using the pair "delayed assignment + application" to implement a delayed substitution. - We use TC for implementing coercions. Both Joe Hendrix and Reid Barton reported a nasty limitation. In Lean3, TC will not be used if there are metavariables in the TC problem. For example, the elaborator will not try to synthesize `Coe Nat ?x`. This is good, but this constraint is too strict for problems such as `Coe (Vector Bool ?n) (BV ?n)`. The coercion exists independently of `?n`. Thus, during TC, we want `isDefEq` to throw an exception instead of return `false` whenever it tries to assign a metavariable owned by its caller. The idea is to sign to the caller that it cannot solve the TC problem at this point, and more information is needed. That is, the caller must make progress an assign its metavariables before trying to invoke TC again. In Lean4, we are using a simpler design for the `MetavarContext`. - No distinction betwen temporary and regular metavariables. - Metavariables have a `depth` Nat field. - MetavarContext also has a `depth` field. - We bump the `MetavarContext` depth when we create a nested problem. Example: Elaborator (depth = 0) -> Simplifier matcher (depth = 1) -> TC (level = 2) -> TC (level = 3) -> ... - When `MetavarContext` is at depth N, `isDefEq` does not assign variables from `depth < N`. - Metavariables from depth N+1 must be fully assigned before we return to level N. - New design even allows us to invoke tactics from TC. * Main concern We don't have tmp metavariables anymore in Lean4. Thus, before trying to match the left-hand-side of an equation in `simp`. We first must bump the level of the `MetavarContext`, create fresh metavariables, then create a new pattern by replacing the free variable on the left-hand-side with these metavariables. We are hoping to minimize this overhead by - Using better indexing data structures in `simp`. They should reduce the number of time `simp` must invoke `isDefEq`. - Implementing `isDefEqApprox` which ignores metavariables and returns only `false` or `undef`. It is a quick filter that allows us to fail quickly and avoid the creation of new fresh metavariables, and a new pattern. - Adding built-in support for arithmetic, Logical connectives, etc. Thus, we avoid a bunch of lemmas in the simp set. - Adding support for AC-rewriting. In Lean3, users use AC lemmas as rewriting rules for "sorting" terms. This is inefficient, requires a quadratic number of rewrite steps, and does not preserve the structure of the goal. The temporary metavariables were also used in the "app builder" module used in Lean3. The app builder uses `isDefEq`. So, it could, in principle, invoke an arbitrary number of nested TC problems. However, in Lean3, all app builder uses are controlled. That is, it is mainly used to synthesize implicit arguments using very simple unification and/or non-nested TC. So, if the "app builder" becomes a bottleneck without tmp metavars, we may solve the issue by implementing `isDefEqCheap` that never invokes TC and uses tmp metavars. -/ structure LocalInstance where className : Name fvar : Expr deriving Inhabited abbrev LocalInstances := Array LocalInstance instance : BEq LocalInstance where beq i₁ i₂ := i₁.fvar == i₂.fvar /-- Remove local instance with the given `fvarId`. Do nothing if `localInsts` does not contain any free variable with id `fvarId`. -/ def LocalInstances.erase (localInsts : LocalInstances) (fvarId : FVarId) : LocalInstances := match localInsts.findIdx? (fun inst => inst.fvar.fvarId! == fvarId) with | some idx => localInsts.eraseIdx idx | _ => localInsts inductive MetavarKind where | natural | synthetic | syntheticOpaque deriving Inhabited, Repr def MetavarKind.isSyntheticOpaque : MetavarKind → Bool | MetavarKind.syntheticOpaque => true | _ => false def MetavarKind.isNatural : MetavarKind → Bool | MetavarKind.natural => true | _ => false structure MetavarDecl where userName : Name := Name.anonymous lctx : LocalContext type : Expr depth : Nat localInstances : LocalInstances kind : MetavarKind numScopeArgs : Nat := 0 -- See comment at `CheckAssignment` `Meta/ExprDefEq.lean` index : Nat -- We use this field to track how old a metavariable is. It is set using a counter at `MetavarContext` deriving Inhabited /-- A delayed assignment for a metavariable `?m`. It represents an assignment of the form `?m := (fun fvars => val)`. The local context `lctx` provides the declarations for `fvars`. Note that `fvars` may not be defined in the local context for `?m`. - TODO: after we delete the old frontend, we can remove the field `lctx`. This field is only used in old C++ implementation. -/ structure DelayedMetavarAssignment where lctx : LocalContext fvars : Array Expr val : Expr open Std (HashMap PersistentHashMap) structure MetavarContext where depth : Nat := 0 mvarCounter : Nat := 0 -- Counter for setting the field `index` at `MetavarDecl` lDepth : PersistentHashMap MVarId Nat := {} decls : PersistentHashMap MVarId MetavarDecl := {} userNames : PersistentHashMap Name MVarId := {} lAssignment : PersistentHashMap MVarId Level := {} eAssignment : PersistentHashMap MVarId Expr := {} dAssignment : PersistentHashMap MVarId DelayedMetavarAssignment := {} class MonadMCtx (m : Type → Type) where getMCtx : m MetavarContext modifyMCtx : (MetavarContext → MetavarContext) → m Unit export MonadMCtx (getMCtx modifyMCtx) instance (m n) [MonadLift m n] [MonadMCtx m] : MonadMCtx n where getMCtx := liftM (getMCtx : m _) modifyMCtx := fun f => liftM (modifyMCtx f : m _) namespace MetavarContext instance : Inhabited MetavarContext := ⟨{}⟩ @[export lean_mk_metavar_ctx] def mkMetavarContext : Unit → MetavarContext := fun _ => {} /- Low level API for adding/declaring metavariable declarations. It is used to implement actions in the monads `MetaM`, `ElabM` and `TacticM`. It should not be used directly since the argument `(mvarId : MVarId)` is assumed to be "unique". -/ def addExprMVarDecl (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) (lctx : LocalContext) (localInstances : LocalInstances) (type : Expr) (kind : MetavarKind := MetavarKind.natural) (numScopeArgs : Nat := 0) : MetavarContext := { mctx with mvarCounter := mctx.mvarCounter + 1 decls := mctx.decls.insert mvarId { depth := mctx.depth index := mctx.mvarCounter userName lctx localInstances type kind numScopeArgs } userNames := if userName.isAnonymous then mctx.userNames else mctx.userNames.insert userName mvarId } def addExprMVarDeclExp (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) (lctx : LocalContext) (localInstances : LocalInstances) (type : Expr) (kind : MetavarKind) : MetavarContext := addExprMVarDecl mctx mvarId userName lctx localInstances type kind /- Low level API for adding/declaring universe level metavariable declarations. It is used to implement actions in the monads `MetaM`, `ElabM` and `TacticM`. It should not be used directly since the argument `(mvarId : MVarId)` is assumed to be "unique". -/ def addLevelMVarDecl (mctx : MetavarContext) (mvarId : MVarId) : MetavarContext := { mctx with lDepth := mctx.lDepth.insert mvarId mctx.depth } def findDecl? (mctx : MetavarContext) (mvarId : MVarId) : Option MetavarDecl := mctx.decls.find? mvarId def getDecl (mctx : MetavarContext) (mvarId : MVarId) : MetavarDecl := match mctx.decls.find? mvarId with | some decl => decl | none => panic! "unknown metavariable" def findUserName? (mctx : MetavarContext) (userName : Name) : Option MVarId := mctx.userNames.find? userName def setMVarKind (mctx : MetavarContext) (mvarId : MVarId) (kind : MetavarKind) : MetavarContext := let decl := mctx.getDecl mvarId { mctx with decls := mctx.decls.insert mvarId { decl with kind := kind } } def renameMVar (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) : MetavarContext := let decl := mctx.getDecl mvarId { mctx with decls := mctx.decls.insert mvarId { decl with userName := userName } userNames := let userNames := mctx.userNames.erase decl.userName if userName.isAnonymous then userNames else userNames.insert userName mvarId } /- Update the type of the given metavariable. This function assumes the new type is definitionally equal to the current one -/ def setMVarType (mctx : MetavarContext) (mvarId : MVarId) (type : Expr) : MetavarContext := let decl := mctx.getDecl mvarId { mctx with decls := mctx.decls.insert mvarId { decl with type := type } } def findLevelDepth? (mctx : MetavarContext) (mvarId : MVarId) : Option Nat := mctx.lDepth.find? mvarId def getLevelDepth (mctx : MetavarContext) (mvarId : MVarId) : Nat := match mctx.findLevelDepth? mvarId with | some d => d | none => panic! "unknown metavariable" def isAnonymousMVar (mctx : MetavarContext) (mvarId : MVarId) : Bool := match mctx.findDecl? mvarId with | none => false | some mvarDecl => mvarDecl.userName.isAnonymous def assignLevel (m : MetavarContext) (mvarId : MVarId) (val : Level) : MetavarContext := { m with lAssignment := m.lAssignment.insert mvarId val } def assignExpr (m : MetavarContext) (mvarId : MVarId) (val : Expr) : MetavarContext := { m with eAssignment := m.eAssignment.insert mvarId val } def assignDelayed (m : MetavarContext) (mvarId : MVarId) (lctx : LocalContext) (fvars : Array Expr) (val : Expr) : MetavarContext := { m with dAssignment := m.dAssignment.insert mvarId { lctx := lctx, fvars := fvars, val := val } } def getLevelAssignment? (m : MetavarContext) (mvarId : MVarId) : Option Level := m.lAssignment.find? mvarId def getExprAssignment? (m : MetavarContext) (mvarId : MVarId) : Option Expr := m.eAssignment.find? mvarId def getDelayedAssignment? (m : MetavarContext) (mvarId : MVarId) : Option DelayedMetavarAssignment := m.dAssignment.find? mvarId def isLevelAssigned (m : MetavarContext) (mvarId : MVarId) : Bool := m.lAssignment.contains mvarId def isExprAssigned (m : MetavarContext) (mvarId : MVarId) : Bool := m.eAssignment.contains mvarId def isDelayedAssigned (m : MetavarContext) (mvarId : MVarId) : Bool := m.dAssignment.contains mvarId def eraseDelayed (m : MetavarContext) (mvarId : MVarId) : MetavarContext := { m with dAssignment := m.dAssignment.erase mvarId } /- Given a sequence of delayed assignments ``` mvarId₁ := mvarId₂ ...; ... mvarIdₙ := mvarId_root ... -- where `mvarId_root` is not delayed assigned ``` in `mctx`, `getDelayedRoot mctx mvarId₁` return `mvarId_root`. If `mvarId₁` is not delayed assigned then return `mvarId₁` -/ partial def getDelayedRoot (m : MetavarContext) : MVarId → MVarId | mvarId => match getDelayedAssignment? m mvarId with | some d => match d.val.getAppFn with | Expr.mvar mvarId _ => getDelayedRoot m mvarId | _ => mvarId | none => mvarId def isLevelAssignable (mctx : MetavarContext) (mvarId : MVarId) : Bool := match mctx.lDepth.find? mvarId with | some d => d == mctx.depth | _ => panic! "unknown universe metavariable" def isExprAssignable (mctx : MetavarContext) (mvarId : MVarId) : Bool := let decl := mctx.getDecl mvarId decl.depth == mctx.depth def incDepth (mctx : MetavarContext) : MetavarContext := { mctx with depth := mctx.depth + 1 } /-- Return true iff the given level contains an assigned metavariable. -/ def hasAssignedLevelMVar (mctx : MetavarContext) : Level → Bool | Level.succ lvl _ => lvl.hasMVar && hasAssignedLevelMVar mctx lvl | Level.max lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignedLevelMVar mctx lvl₁) || (lvl₂.hasMVar && hasAssignedLevelMVar mctx lvl₂) | Level.imax lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignedLevelMVar mctx lvl₁) || (lvl₂.hasMVar && hasAssignedLevelMVar mctx lvl₂) | Level.mvar mvarId _ => mctx.isLevelAssigned mvarId | Level.zero _ => false | Level.param _ _ => false /-- Return `true` iff expression contains assigned (level/expr) metavariables or delayed assigned mvars -/ def hasAssignedMVar (mctx : MetavarContext) : Expr → Bool | Expr.const _ lvls _ => lvls.any (hasAssignedLevelMVar mctx) | Expr.sort lvl _ => hasAssignedLevelMVar mctx lvl | Expr.app f a _ => (f.hasMVar && hasAssignedMVar mctx f) || (a.hasMVar && hasAssignedMVar mctx a) | Expr.letE _ t v b _ => (t.hasMVar && hasAssignedMVar mctx t) || (v.hasMVar && hasAssignedMVar mctx v) || (b.hasMVar && hasAssignedMVar mctx b) | Expr.forallE _ d b _ => (d.hasMVar && hasAssignedMVar mctx d) || (b.hasMVar && hasAssignedMVar mctx b) | Expr.lam _ d b _ => (d.hasMVar && hasAssignedMVar mctx d) || (b.hasMVar && hasAssignedMVar mctx b) | Expr.fvar _ _ => false | Expr.bvar _ _ => false | Expr.lit _ _ => false | Expr.mdata _ e _ => e.hasMVar && hasAssignedMVar mctx e | Expr.proj _ _ e _ => e.hasMVar && hasAssignedMVar mctx e | Expr.mvar mvarId _ => mctx.isExprAssigned mvarId || mctx.isDelayedAssigned mvarId /-- Return true iff the given level contains a metavariable that can be assigned. -/ def hasAssignableLevelMVar (mctx : MetavarContext) : Level → Bool | Level.succ lvl _ => lvl.hasMVar && hasAssignableLevelMVar mctx lvl | Level.max lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignableLevelMVar mctx lvl₁) || (lvl₂.hasMVar && hasAssignableLevelMVar mctx lvl₂) | Level.imax lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignableLevelMVar mctx lvl₁) || (lvl₂.hasMVar && hasAssignableLevelMVar mctx lvl₂) | Level.mvar mvarId _ => mctx.isLevelAssignable mvarId | Level.zero _ => false | Level.param _ _ => false /-- Return `true` iff expression contains a metavariable that can be assigned. -/ def hasAssignableMVar (mctx : MetavarContext) : Expr → Bool | Expr.const _ lvls _ => lvls.any (hasAssignableLevelMVar mctx) | Expr.sort lvl _ => hasAssignableLevelMVar mctx lvl | Expr.app f a _ => (f.hasMVar && hasAssignableMVar mctx f) || (a.hasMVar && hasAssignableMVar mctx a) | Expr.letE _ t v b _ => (t.hasMVar && hasAssignableMVar mctx t) || (v.hasMVar && hasAssignableMVar mctx v) || (b.hasMVar && hasAssignableMVar mctx b) | Expr.forallE _ d b _ => (d.hasMVar && hasAssignableMVar mctx d) || (b.hasMVar && hasAssignableMVar mctx b) | Expr.lam _ d b _ => (d.hasMVar && hasAssignableMVar mctx d) || (b.hasMVar && hasAssignableMVar mctx b) | Expr.fvar _ _ => false | Expr.bvar _ _ => false | Expr.lit _ _ => false | Expr.mdata _ e _ => e.hasMVar && hasAssignableMVar mctx e | Expr.proj _ _ e _ => e.hasMVar && hasAssignableMVar mctx e | Expr.mvar mvarId _ => mctx.isExprAssignable mvarId /- Notes on artificial eta-expanded terms due to metavariables. We try avoid synthetic terms such as `((fun x y => t) a b)` in the output produced by the elaborator. This kind of term may be generated when instantiating metavariable assignments. This module tries to avoid their generation because they often introduce unnecessary dependencies and may affect automation. When elaborating terms, we use metavariables to represent "holes". Each hole has a context which includes all free variables that may be used to "fill" the hole. Suppose, we create a metavariable (hole) `?m : Nat` in a context containing `(x : Nat) (y : Nat) (b : Bool)`, then we can assign terms such as `x + y` to `?m` since `x` and `y` are in the context used to create `?m`. Now, suppose we have the term `?m + 1` and we want to create the lambda expression `fun x => ?m + 1`. This term is not correct since we may assign to `?m` a term containing `x`. We address this issue by create a synthetic metavariable `?n : Nat → Nat` and adding the delayed assignment `?n #[x] := ?m`, and the term `fun x => ?n x + 1`. When we later assign a term `t[x]` to `?m`, `fun x => t[x]` is assigned to `?n`, and if we substitute it at `fun x => ?n x + 1`, we produce `fun x => ((fun x => t[x]) x) + 1`. To avoid this term eta-expanded term, we apply beta-reduction when instantiating metavariable assignments in this module. This operation is performed at `instantiateExprMVars`, `elimMVarDeps`, and `levelMVarToParam`. -/ partial def instantiateLevelMVars [Monad m] [MonadMCtx m] : Level → m Level | lvl@(Level.succ lvl₁ _) => return Level.updateSucc! lvl (← instantiateLevelMVars lvl₁) | lvl@(Level.max lvl₁ lvl₂ _) => return Level.updateMax! lvl (← instantiateLevelMVars lvl₁) (← instantiateLevelMVars lvl₂) | lvl@(Level.imax lvl₁ lvl₂ _) => return Level.updateIMax! lvl (← instantiateLevelMVars lvl₁) (← instantiateLevelMVars lvl₂) | lvl@(Level.mvar mvarId _) => do match getLevelAssignment? (← getMCtx) mvarId with | some newLvl => if !newLvl.hasMVar then pure newLvl else do let newLvl' ← instantiateLevelMVars newLvl modifyMCtx fun mctx => mctx.assignLevel mvarId newLvl' pure newLvl' | none => pure lvl | lvl => pure lvl /-- instantiateExprMVars main function -/ partial def instantiateExprMVars [Monad m] [MonadMCtx m] [STWorld ω m] [MonadLiftT (ST ω) m] (e : Expr) : MonadCacheT ExprStructEq Expr m Expr := if !e.hasMVar then pure e else checkCache { val := e : ExprStructEq } fun _ => do match e with | Expr.proj _ _ s _ => return e.updateProj! (← instantiateExprMVars s) | Expr.forallE _ d b _ => return e.updateForallE! (← instantiateExprMVars d) (← instantiateExprMVars b) | Expr.lam _ d b _ => return e.updateLambdaE! (← instantiateExprMVars d) (← instantiateExprMVars b) | Expr.letE _ t v b _ => return e.updateLet! (← instantiateExprMVars t) (← instantiateExprMVars v) (← instantiateExprMVars b) | Expr.const _ lvls _ => return e.updateConst! (← lvls.mapM instantiateLevelMVars) | Expr.sort lvl _ => return e.updateSort! (← instantiateLevelMVars lvl) | Expr.mdata _ b _ => return e.updateMData! (← instantiateExprMVars b) | Expr.app .. => e.withApp fun f args => do let instArgs (f : Expr) : MonadCacheT ExprStructEq Expr m Expr := do let args ← args.mapM instantiateExprMVars pure (mkAppN f args) let instApp : MonadCacheT ExprStructEq Expr m Expr := do let wasMVar := f.isMVar let f ← instantiateExprMVars f if wasMVar && f.isLambda then /- Some of the arguments in args are irrelevant after we beta reduce. -/ instantiateExprMVars (f.betaRev args.reverse) else instArgs f match f with | Expr.mvar mvarId _ => let mctx ← getMCtx match mctx.getDelayedAssignment? mvarId with | none => instApp | some { fvars := fvars, val := val, .. } => /- Apply "delayed substitution" (i.e., delayed assignment + application). That is, `f` is some metavariable `?m`, that is delayed assigned to `val`. If after instantiating `val`, we obtain `newVal`, and `newVal` does not contain metavariables, we replace the free variables `fvars` in `newVal` with the first `fvars.size` elements of `args`. -/ if fvars.size > args.size then /- We don't have sufficient arguments for instantiating the free variables `fvars`. This can only happy if a tactic or elaboration function is not implemented correctly. We decided to not use `panic!` here and report it as an error in the frontend when we are checking for unassigned metavariables in an elaborated term. -/ instArgs f else let newVal ← instantiateExprMVars val if newVal.hasExprMVar then instArgs f else do let args ← args.mapM instantiateExprMVars /- Example: suppose we have `?m t1 t2 t3` That is, `f := ?m` and `args := #[t1, t2, t3]` Morever, `?m` is delayed assigned `?m #[x, y] := f x y` where, `fvars := #[x, y]` and `newVal := f x y`. After abstracting `newVal`, we have `f (Expr.bvar 0) (Expr.bvar 1)`. After `instantiaterRevRange 0 2 args`, we have `f t1 t2`. After `mkAppRange 2 3`, we have `f t1 t2 t3` -/ let newVal := newVal.abstract fvars let result := newVal.instantiateRevRange 0 fvars.size args let result := mkAppRange result fvars.size args.size args pure result | _ => instApp | e@(Expr.mvar mvarId _) => checkCache { val := e : ExprStructEq } fun _ => do let mctx ← getMCtx match mctx.getExprAssignment? mvarId with | some newE => do let newE' ← instantiateExprMVars newE modifyMCtx fun mctx => mctx.assignExpr mvarId newE' pure newE' | none => pure e | e => pure e instance : MonadMCtx (StateRefT MetavarContext (ST ω)) where getMCtx := get modifyMCtx := modify def instantiateMVars (mctx : MetavarContext) (e : Expr) : Expr × MetavarContext := if !e.hasMVar then (e, mctx) else let instantiate {ω} (e : Expr) : (MonadCacheT ExprStructEq Expr $ StateRefT MetavarContext $ ST ω) Expr := instantiateExprMVars e runST fun _ => instantiate e |>.run |>.run mctx def instantiateLCtxMVars (mctx : MetavarContext) (lctx : LocalContext) : LocalContext × MetavarContext := lctx.foldl (init := ({}, mctx)) fun (lctx, mctx) ldecl => match ldecl with | LocalDecl.cdecl _ fvarId userName type bi => let (type, mctx) := mctx.instantiateMVars type (lctx.mkLocalDecl fvarId userName type bi, mctx) | LocalDecl.ldecl _ fvarId userName type value nonDep => let (type, mctx) := mctx.instantiateMVars type let (value, mctx) := mctx.instantiateMVars value (lctx.mkLetDecl fvarId userName type value nonDep, mctx) def instantiateMVarDeclMVars (mctx : MetavarContext) (mvarId : MVarId) : MetavarContext := let mvarDecl := mctx.getDecl mvarId let (lctx, mctx) := mctx.instantiateLCtxMVars mvarDecl.lctx let (type, mctx) := mctx.instantiateMVars mvarDecl.type { mctx with decls := mctx.decls.insert mvarId { mvarDecl with lctx := lctx, type := type } } namespace DependsOn private abbrev M := StateM ExprSet private def shouldVisit (e : Expr) : M Bool := do if !e.hasMVar && !e.hasFVar then return false else if (← get).contains e then return false else modify fun s => s.insert e return true @[specialize] private partial def dep (mctx : MetavarContext) (p : FVarId → Bool) (e : Expr) : M Bool := let rec visit (e : Expr) : M Bool := do if !(← shouldVisit e) then pure false else visitMain e, visitMain : Expr → M Bool | Expr.proj _ _ s _ => visit s | Expr.forallE _ d b _ => visit d <||> visit b | Expr.lam _ d b _ => visit d <||> visit b | Expr.letE _ t v b _ => visit t <||> visit v <||> visit b | Expr.mdata _ b _ => visit b | Expr.app f a _ => visit a <||> if f.isApp then visitMain f else visit f | Expr.mvar mvarId _ => match mctx.getExprAssignment? mvarId with | some a => visit a | none => let lctx := (mctx.getDecl mvarId).lctx return lctx.any fun decl => p decl.fvarId | Expr.fvar fvarId _ => return p fvarId | e => pure false visit e @[inline] partial def main (mctx : MetavarContext) (p : FVarId → Bool) (e : Expr) : M Bool := if !e.hasFVar && !e.hasMVar then pure false else dep mctx p e end DependsOn /-- Return `true` iff `e` depends on a free variable `x` s.t. `p x` is `true`. For each metavariable `?m` occurring in `x` 1- If `?m := t`, then we visit `t` looking for `x` 2- If `?m` is unassigned, then we consider the worst case and check whether `x` is in the local context of `?m`. This case is a "may dependency". That is, we may assign a term `t` to `?m` s.t. `t` contains `x`. -/ @[inline] def findExprDependsOn (mctx : MetavarContext) (e : Expr) (p : FVarId → Bool) : Bool := DependsOn.main mctx p e |>.run' {} /-- Similar to `findExprDependsOn`, but checks the expressions in the given local declaration depends on a free variable `x` s.t. `p x` is `true`. -/ @[inline] def findLocalDeclDependsOn (mctx : MetavarContext) (localDecl : LocalDecl) (p : FVarId → Bool) : Bool := match localDecl with | LocalDecl.cdecl (type := t) .. => findExprDependsOn mctx t p | LocalDecl.ldecl (type := t) (value := v) .. => (DependsOn.main mctx p t <||> DependsOn.main mctx p v).run' {} def exprDependsOn (mctx : MetavarContext) (e : Expr) (fvarId : FVarId) : Bool := findExprDependsOn mctx e fun fvarId' => fvarId == fvarId' def localDeclDependsOn (mctx : MetavarContext) (localDecl : LocalDecl) (fvarId : FVarId) : Bool := findLocalDeclDependsOn mctx localDecl fun fvarId' => fvarId == fvarId' namespace MkBinding inductive Exception where | revertFailure (mctx : MetavarContext) (lctx : LocalContext) (toRevert : Array Expr) (decl : LocalDecl) instance : ToString Exception where toString | Exception.revertFailure _ lctx toRevert decl => "failed to revert " ++ toString (toRevert.map (fun x => "'" ++ toString (lctx.getFVar! x).userName ++ "'")) ++ ", '" ++ toString decl.userName ++ "' depends on them, and it is an auxiliary declaration created by the elaborator" ++ " (possible solution: use tactic 'clear' to remove '" ++ toString decl.userName ++ "' from local context)" /-- `MkBinding` and `elimMVarDepsAux` are mutually recursive, but `cache` is only used at `elimMVarDepsAux`. We use a single state object for convenience. We have a `NameGenerator` because we need to generate fresh auxiliary metavariables. -/ structure State where mctx : MetavarContext ngen : NameGenerator cache : HashMap ExprStructEq Expr := {} abbrev MCore := EStateM Exception State abbrev M := ReaderT Bool MCore def preserveOrder : M Bool := read instance : MonadHashMapCacheAdapter ExprStructEq Expr M where getCache := do let s ← get; pure s.cache modifyCache := fun f => modify fun s => { s with cache := f s.cache } /-- Return the local declaration of the free variable `x` in `xs` with the smallest index -/ private def getLocalDeclWithSmallestIdx (lctx : LocalContext) (xs : Array Expr) : LocalDecl := do let mut d : LocalDecl := lctx.getFVar! xs[0] for i in [1:xs.size] do let curr := lctx.getFVar! xs[i] if curr.index < d.index then d := curr return d /-- Given `toRevert` an array of free variables s.t. `lctx` contains their declarations, return a new array of free variables that contains `toRevert` and all free variables in `lctx` that may depend on `toRevert`. Remark: the result is sorted by `LocalDecl` indices. Remark: We used to throw an `Exception.revertFailure` exception when an auxiliary declaration had to be reversed. Recall that auxiliary declarations are created when compiling (mutually) recursive definitions. The `revertFailure` due to auxiliary declaration dependency was originally introduced in Lean3 to address issue https://github.com/leanprover/lean/issues/1258. In Lean4, this solution is not satisfactory because all definitions/theorems are potentially recursive. So, even an simple (incomplete) definition such as ``` variables {α : Type} in def f (a : α) : List α := _ ``` would trigger the `Exception.revertFailure` exception. In the definition above, the elaborator creates the auxiliary definition `f : {α : Type} → List α`. The `_` is elaborated as a new fresh variable `?m` that contains `α : Type`, `a : α`, and `f : α → List α` in its context, When we try to create the lambda `fun {α : Type} (a : α) => ?m`, we first need to create an auxiliary `?n` which do not contain `α` and `a` in its context. That is, we create the metavariable `?n : {α : Type} → (a : α) → (f : α → List α) → List α`, add the delayed assignment `?n #[α, a, f] := ?m α a f`, and create the lambda `fun {α : Type} (a : α) => ?n α a f`. See `elimMVarDeps` for more information. If we kept using the Lean3 approach, we would get the `Exception.revertFailure` exception because we are reverting the auxiliary definition `f`. Note that https://github.com/leanprover/lean/issues/1258 is not an issue in Lean4 because we have changed how we compile recursive definitions. -/ def collectDeps (mctx : MetavarContext) (lctx : LocalContext) (toRevert : Array Expr) (preserveOrder : Bool) : Except Exception (Array Expr) := do if toRevert.size == 0 then pure toRevert else if preserveOrder then -- Make sure none of `toRevert` is an AuxDecl -- Make sure toRevert[j] does not depend on toRevert[i] for j > i toRevert.size.forM fun i => do let fvar := toRevert[i] let decl := lctx.getFVar! fvar i.forM fun j => do let prevFVar := toRevert[j] let prevDecl := lctx.getFVar! prevFVar if localDeclDependsOn mctx prevDecl fvar.fvarId! then throw (Exception.revertFailure mctx lctx toRevert prevDecl) let newToRevert := if preserveOrder then toRevert else Array.mkEmpty toRevert.size let firstDeclToVisit := getLocalDeclWithSmallestIdx lctx toRevert let initSize := newToRevert.size lctx.foldlM (init := newToRevert) (start := firstDeclToVisit.index) fun (newToRevert : Array Expr) decl => if initSize.any fun i => decl.fvarId == (newToRevert.get! i).fvarId! then pure newToRevert else if toRevert.any fun x => decl.fvarId == x.fvarId! then pure (newToRevert.push decl.toExpr) else if findLocalDeclDependsOn mctx decl (fun fvarId => newToRevert.any fun x => x.fvarId! == fvarId) then pure (newToRevert.push decl.toExpr) else pure newToRevert /-- Create a new `LocalContext` by removing the free variables in `toRevert` from `lctx`. We use this function when we create auxiliary metavariables at `elimMVarDepsAux`. -/ def reduceLocalContext (lctx : LocalContext) (toRevert : Array Expr) : LocalContext := toRevert.foldr (init := lctx) fun x lctx => lctx.erase x.fvarId! @[inline] private def getMCtx : M MetavarContext := return (← get).mctx /-- Return free variables in `xs` that are in the local context `lctx` -/ private def getInScope (lctx : LocalContext) (xs : Array Expr) : Array Expr := xs.foldl (init := #[]) fun scope x => if lctx.contains x.fvarId! then scope.push x else scope /-- Execute `x` with an empty cache, and then restore the original cache. -/ @[inline] private def withFreshCache (x : M α) : M α := do let cache ← modifyGet fun s => (s.cache, { s with cache := {} }) let a ← x modify fun s => { s with cache := cache } pure a /-- Create an application `mvar ys` where `ys` are the free variables. See "Gruesome details" in the beginning of the file for understanding how let-decl free variables are handled. -/ private def mkMVarApp (lctx : LocalContext) (mvar : Expr) (xs : Array Expr) (kind : MetavarKind) : Expr := xs.foldl (init := mvar) fun e x => match kind with | MetavarKind.syntheticOpaque => mkApp e x | _ => if (lctx.getFVar! x).isLet then e else mkApp e x /-- Return true iff some `e` in `es` depends on `fvarId` -/ private def anyDependsOn (mctx : MetavarContext) (es : Array Expr) (fvarId : FVarId) : Bool := es.any fun e => exprDependsOn mctx e fvarId mutual private partial def visit (xs : Array Expr) (e : Expr) : M Expr := if !e.hasMVar then pure e else checkCache { val := e : ExprStructEq } fun _ => elim xs e private partial def elim (xs : Array Expr) (e : Expr) : M Expr := match e with | Expr.proj _ _ s _ => return e.updateProj! (← visit xs s) | Expr.forallE _ d b _ => return e.updateForallE! (← visit xs d) (← visit xs b) | Expr.lam _ d b _ => return e.updateLambdaE! (← visit xs d) (← visit xs b) | Expr.letE _ t v b _ => return e.updateLet! (← visit xs t) (← visit xs v) (← visit xs b) | Expr.mdata _ b _ => return e.updateMData! (← visit xs b) | Expr.app _ _ _ => e.withApp fun f args => elimApp xs f args | Expr.mvar mvarId _ => elimApp xs e #[] | e => return e private partial def mkAuxMVarType (lctx : LocalContext) (xs : Array Expr) (kind : MetavarKind) (e : Expr) : M Expr := do let e ← abstractRangeAux xs xs.size e xs.size.foldRevM (init := e) fun i e => let x := xs[i] match lctx.getFVar! x with | LocalDecl.cdecl _ _ n type bi => do let type := type.headBeta let type ← abstractRangeAux xs i type pure <| Lean.mkForall n bi type e | LocalDecl.ldecl _ _ n type value nonDep => do let type := type.headBeta let type ← abstractRangeAux xs i type let value ← abstractRangeAux xs i value let e := mkLet n type value e nonDep match kind with | MetavarKind.syntheticOpaque => -- See "Gruesome details" section in the beginning of the file let e := e.liftLooseBVars 0 1 pure <| mkForall n BinderInfo.default type e | _ => pure e where abstractRangeAux (xs : Array Expr) (i : Nat) (e : Expr) : M Expr := do let e ← elim xs e pure (e.abstractRange i xs) private partial def elimMVar (xs : Array Expr) (mvarId : MVarId) (args : Array Expr) : M (Expr × Array Expr) := do let mctx ← getMCtx let mvarDecl := mctx.getDecl mvarId let mvarLCtx := mvarDecl.lctx let toRevert := getInScope mvarLCtx xs if toRevert.size == 0 then let args ← args.mapM (visit xs) return (mkAppN (mkMVar mvarId) args, #[]) else /- `newMVarKind` is the kind for the new auxiliary metavariable. There is an alternative approach where we use ``` let newMVarKind := if !mctx.isExprAssignable mvarId || mvarDecl.isSyntheticOpaque then MetavarKind.syntheticOpaque else MetavarKind.natural ``` In this approach, we use the natural kind for the new auxiliary metavariable if the original metavariable is synthetic and assignable. Since we mainly use synthetic metavariables for pending type class (TC) resolution problems, this approach may minimize the number of TC resolution problems that may need to be resolved. A potential disadvantage is that `isDefEq` will not eagerly use `synthPending` for natural metavariables. That being said, we should try this approach as soon as we have an extensive test suite. -/ let newMVarKind := if !mctx.isExprAssignable mvarId then MetavarKind.syntheticOpaque else mvarDecl.kind /- If `mvarId` is the lhs of a delayed assignment `?m #[x_1, ... x_n] := val`, then `nestedFVars` is `#[x_1, ..., x_n]`. In this case, we produce a new `syntheticOpaque` metavariable `?n` and a delayed assignment ``` ?n #[y_1, ..., y_m, x_1, ... x_n] := ?m x_1 ... x_n ``` where `#[y_1, ..., y_m]` is `toRevert` after `collectDeps`. Remark: `newMVarKind != MetavarKind.syntheticOpaque ==> nestedFVars == #[]` -/ let rec cont (nestedFVars : Array Expr) (nestedLCtx : LocalContext) : M (Expr × Array Expr) := do let args ← args.mapM (visit xs) let preserve ← preserveOrder match collectDeps mctx mvarLCtx toRevert preserve with | Except.error ex => throw ex | Except.ok toRevert => let newMVarLCtx := reduceLocalContext mvarLCtx toRevert let newLocalInsts := mvarDecl.localInstances.filter fun inst => toRevert.all fun x => inst.fvar != x -- Remark: we must reset the before processing `mkAuxMVarType` because `toRevert` may not be equal to `xs` let newMVarType ← withFreshCache do mkAuxMVarType mvarLCtx toRevert newMVarKind mvarDecl.type let newMVarId := { name := (← get).ngen.curr } let newMVar := mkMVar newMVarId let result := mkMVarApp mvarLCtx newMVar toRevert newMVarKind let numScopeArgs := mvarDecl.numScopeArgs + result.getAppNumArgs modify fun s => { s with mctx := s.mctx.addExprMVarDecl newMVarId Name.anonymous newMVarLCtx newLocalInsts newMVarType newMVarKind numScopeArgs, ngen := s.ngen.next } match newMVarKind with | MetavarKind.syntheticOpaque => modify fun s => { s with mctx := assignDelayed s.mctx newMVarId nestedLCtx (toRevert ++ nestedFVars) (mkAppN (mkMVar mvarId) nestedFVars) } | _ => modify fun s => { s with mctx := assignExpr s.mctx mvarId result } return (mkAppN result args, toRevert) if !mvarDecl.kind.isSyntheticOpaque then cont #[] mvarLCtx else match mctx.getDelayedAssignment? mvarId with | none => cont #[] mvarLCtx | some { fvars := fvars, lctx := nestedLCtx, .. } => cont fvars nestedLCtx -- Remark: nestedLCtx is bigger than mvarLCtx private partial def elimApp (xs : Array Expr) (f : Expr) (args : Array Expr) : M Expr := do match f with | Expr.mvar mvarId _ => match (← getMCtx).getExprAssignment? mvarId with | some newF => if newF.isLambda then let args ← args.mapM (visit xs) elim xs <| newF.betaRev args.reverse else elimApp xs newF args | none => return (← elimMVar xs mvarId args).1 | _ => return mkAppN (← visit xs f) (← args.mapM (visit xs)) end partial def elimMVarDeps (xs : Array Expr) (e : Expr) : M Expr := if !e.hasMVar then pure e else withFreshCache do elim xs e partial def revert (xs : Array Expr) (mvarId : MVarId) : M (Expr × Array Expr) := withFreshCache do elimMVar xs mvarId #[] /-- Similar to `Expr.abstractRange`, but handles metavariables correctly. It uses `elimMVarDeps` to ensure `e` and the type of the free variables `xs` do not contain a metavariable `?m` s.t. local context of `?m` contains a free variable in `xs`. `elimMVarDeps` is defined later in this file. -/ @[inline] def abstractRange (xs : Array Expr) (i : Nat) (e : Expr) : M Expr := do let e ← elimMVarDeps xs e pure (e.abstractRange i xs) /-- Similar to `LocalContext.mkBinding`, but handles metavariables correctly. If `usedOnly == false` then `forall` and `lambda` expressions are created only for used variables. If `usedLetOnly == false` then `let` expressions are created only for used (let-) variables. -/ @[specialize] def mkBinding (isLambda : Bool) (lctx : LocalContext) (xs : Array Expr) (e : Expr) (usedOnly : Bool) (usedLetOnly : Bool) : M (Expr × Nat) := do let e ← abstractRange xs xs.size e xs.size.foldRevM (fun i (p : Expr × Nat) => do let (e, num) := p; let x := xs[i] match lctx.getFVar! x with | LocalDecl.cdecl _ _ n type bi => if !usedOnly || e.hasLooseBVar 0 then let type := type.headBeta; let type ← abstractRange xs i type if isLambda then pure (Lean.mkLambda n bi type e, num + 1) else pure (Lean.mkForall n bi type e, num + 1) else pure (e.lowerLooseBVars 1 1, num) | LocalDecl.ldecl _ _ n type value nonDep => if !usedLetOnly || e.hasLooseBVar 0 then let type ← abstractRange xs i type let value ← abstractRange xs i value pure (mkLet n type value e nonDep, num + 1) else pure (e.lowerLooseBVars 1 1, num)) (e, 0) end MkBinding abbrev MkBindingM := ReaderT LocalContext MkBinding.MCore def elimMVarDeps (xs : Array Expr) (e : Expr) (preserveOrder : Bool) : MkBindingM Expr := fun _ => MkBinding.elimMVarDeps xs e preserveOrder def revert (xs : Array Expr) (mvarId : MVarId) (preserveOrder : Bool) : MkBindingM (Expr × Array Expr) := fun _ => MkBinding.revert xs mvarId preserveOrder def mkBinding (isLambda : Bool) (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) : MkBindingM (Expr × Nat) := fun lctx => MkBinding.mkBinding isLambda lctx xs e usedOnly usedLetOnly false @[inline] def mkLambda (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) : MkBindingM Expr := do let (e, _) ← mkBinding (isLambda := true) xs e usedOnly usedLetOnly pure e @[inline] def mkForall (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) : MkBindingM Expr := do let (e, _) ← mkBinding (isLambda := false) xs e usedOnly usedLetOnly pure e @[inline] def abstractRange (e : Expr) (n : Nat) (xs : Array Expr) : MkBindingM Expr := fun _ => MkBinding.abstractRange xs n e false /-- `isWellFormed mctx lctx e` return true if - All locals in `e` are declared in `lctx` - All metavariables `?m` in `e` have a local context which is a subprefix of `lctx` or are assigned, and the assignment is well-formed. -/ partial def isWellFormed (mctx : MetavarContext) (lctx : LocalContext) : Expr → Bool | Expr.mdata _ e _ => isWellFormed mctx lctx e | Expr.proj _ _ e _ => isWellFormed mctx lctx e | e@(Expr.app f a _) => (!e.hasExprMVar && !e.hasFVar) || (isWellFormed mctx lctx f && isWellFormed mctx lctx a) | e@(Expr.lam _ d b _) => (!e.hasExprMVar && !e.hasFVar) || (isWellFormed mctx lctx d && isWellFormed mctx lctx b) | e@(Expr.forallE _ d b _) => (!e.hasExprMVar && !e.hasFVar) || (isWellFormed mctx lctx d && isWellFormed mctx lctx b) | e@(Expr.letE _ t v b _) => (!e.hasExprMVar && !e.hasFVar) || (isWellFormed mctx lctx t && isWellFormed mctx lctx v && isWellFormed mctx lctx b) | Expr.const .. => true | Expr.bvar .. => true | Expr.sort .. => true | Expr.lit .. => true | Expr.mvar mvarId _ => let mvarDecl := mctx.getDecl mvarId; if mvarDecl.lctx.isSubPrefixOf lctx then true else match mctx.getExprAssignment? mvarId with | none => false | some v => isWellFormed mctx lctx v | Expr.fvar fvarId _ => lctx.contains fvarId namespace LevelMVarToParam structure Context where paramNamePrefix : Name alreadyUsedPred : Name → Bool structure State where mctx : MetavarContext paramNames : Array Name := #[] nextParamIdx : Nat cache : HashMap ExprStructEq Expr := {} abbrev M := ReaderT Context $ StateM State instance : MonadCache ExprStructEq Expr M where findCached? e := return (← get).cache.find? e cache e v := modify fun s => { s with cache := s.cache.insert e v } partial def mkParamName : M Name := do let ctx ← read let s ← get let newParamName := ctx.paramNamePrefix.appendIndexAfter s.nextParamIdx if ctx.alreadyUsedPred newParamName then modify fun s => { s with nextParamIdx := s.nextParamIdx + 1 } mkParamName else do modify fun s => { s with nextParamIdx := s.nextParamIdx + 1, paramNames := s.paramNames.push newParamName } pure newParamName partial def visitLevel (u : Level) : M Level := do match u with | Level.succ v _ => return u.updateSucc! (← visitLevel v) | Level.max v₁ v₂ _ => return u.updateMax! (← visitLevel v₁) (← visitLevel v₂) | Level.imax v₁ v₂ _ => return u.updateIMax! (← visitLevel v₁) (← visitLevel v₂) | Level.zero _ => pure u | Level.param .. => pure u | Level.mvar mvarId _ => let s ← get match s.mctx.getLevelAssignment? mvarId with | some v => visitLevel v | none => let p ← mkParamName let p := mkLevelParam p modify fun s => { s with mctx := s.mctx.assignLevel mvarId p } pure p partial def main (e : Expr) : M Expr := if !e.hasMVar then return e else checkCache { val := e : ExprStructEq } fun _ => do match e with | Expr.proj _ _ s _ => return e.updateProj! (← main s) | Expr.forallE _ d b _ => return e.updateForallE! (← main d) (← main b) | Expr.lam _ d b _ => return e.updateLambdaE! (← main d) (← main b) | Expr.letE _ t v b _ => return e.updateLet! (← main t) (← main v) (← main b) | Expr.app .. => e.withApp fun f args => visitApp f args | Expr.mdata _ b _ => return e.updateMData! (← main b) | Expr.const _ us _ => return e.updateConst! (← us.mapM visitLevel) | Expr.sort u _ => return e.updateSort! (← visitLevel u) | Expr.mvar .. => visitApp e #[] | e => return e where visitApp (f : Expr) (args : Array Expr) : M Expr := do match f with | Expr.mvar mvarId .. => match (← get).mctx.getExprAssignment? mvarId with | some v => return (← visitApp v args).headBeta | none => return mkAppN f (← args.mapM main) | _ => return mkAppN (← main f) (← args.mapM main) end LevelMVarToParam structure UnivMVarParamResult where mctx : MetavarContext newParamNames : Array Name nextParamIdx : Nat expr : Expr def levelMVarToParam (mctx : MetavarContext) (alreadyUsedPred : Name → Bool) (e : Expr) (paramNamePrefix : Name := `u) (nextParamIdx : Nat := 1) : UnivMVarParamResult := let (e, s) := LevelMVarToParam.main e { paramNamePrefix := paramNamePrefix, alreadyUsedPred := alreadyUsedPred } { mctx := mctx, nextParamIdx := nextParamIdx } { mctx := s.mctx, newParamNames := s.paramNames, nextParamIdx := s.nextParamIdx, expr := e } def getExprAssignmentDomain (mctx : MetavarContext) : Array MVarId := mctx.eAssignment.foldl (init := #[]) fun a mvarId _ => Array.push a mvarId end MetavarContext end Lean
60713aa2ec596e80a58c620cd2ede51dc6c6b78b
d6124c8dbe5661dcc5b8c9da0a56fbf1f0480ad6
/test/out/script/verify.lean
020b88935b1c4240cdb5f3da3acd5a3ba202b298
[ "Apache-2.0" ]
permissive
xubaiw/lean4-papyrus
c3fbbf8ba162eb5f210155ae4e20feb2d32c8182
02e82973a5badda26fc0f9fd15b3d37e2eb309e0
refs/heads/master
1,691,425,756,824
1,632,122,825,000
1,632,123,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
324
lean
import Papyrus open Papyrus Script llvm module foo do define i32 @main() do ret i32 0 #verify foo #verify foo >>= (·.getFunction "main") llvm module bug do define i32 @main() do ret i8 0 #verify bug -- Error: Function return type does not match operand #verify bug >>= (·.getFunction "main") -- Same Error
568809c13e1ed6cf55de6490d2ecf8b733ffa199
1a61aba1b67cddccce19532a9596efe44be4285f
/library/data/int/basic.lean
1c10c3bce91df571dd6c7885548cdf736ab80afc
[ "Apache-2.0" ]
permissive
eigengrau/lean
07986a0f2548688c13ba36231f6cdbee82abf4c6
f8a773be1112015e2d232661ce616d23f12874d0
refs/heads/master
1,610,939,198,566
1,441,352,386,000
1,441,352,494,000
41,903,576
0
0
null
1,441,352,210,000
1,441,352,210,000
null
UTF-8
Lean
false
false
23,613
lean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Jeremy Avigad The integers, with addition, multiplication, and subtraction. The representation of the integers is chosen to compute efficiently. To faciliate proving things about these operations, we show that the integers are a quotient of ℕ × ℕ with the usual equivalence relation, ≡, and functions abstr : ℕ × ℕ → ℤ repr : ℤ → ℕ × ℕ satisfying: abstr_repr (a : ℤ) : abstr (repr a) = a repr_abstr (p : ℕ × ℕ) : repr (abstr p) ≡ p abstr_eq (p q : ℕ × ℕ) : p ≡ q → abstr p = abstr q For example, to "lift" statements about add to statements about padd, we need to prove the following: repr_add (a b : ℤ) : repr (a + b) = padd (repr a) (repr b) padd_congr (p p' q q' : ℕ × ℕ) (H1 : p ≡ p') (H2 : q ≡ q') : padd p q ≡ p' q' -/ import data.nat.basic data.nat.order data.nat.sub data.prod import algebra.relation algebra.binary algebra.ordered_ring open eq.ops open prod relation nat open decidable binary /- the type of integers -/ inductive int : Type := | of_nat : nat → int | neg_succ_of_nat : nat → int notation `ℤ` := int definition int.of_num [coercion] [reducible] [constructor] (n : num) : ℤ := int.of_nat (nat.of_num n) namespace int attribute int.of_nat [coercion] notation `-[1+` n `]` := int.neg_succ_of_nat n -- for pretty-printing output /- definitions of basic functions -/ definition neg_of_nat : ℕ → ℤ | 0 := 0 | (succ m) := -[1+ m] definition sub_nat_nat (m n : ℕ) : ℤ := match n - m with | 0 := m - n -- m ≥ n | (succ k) := -[1+ k] -- m < n, and n - m = succ k end definition neg (a : ℤ) : ℤ := int.cases_on a neg_of_nat succ definition add : ℤ → ℤ → ℤ | (of_nat m) (of_nat n) := m + n | (of_nat m) -[1+ n] := sub_nat_nat m (succ n) | -[1+ m] (of_nat n) := sub_nat_nat n (succ m) | -[1+ m] -[1+ n] := neg_of_nat (succ m + succ n) definition mul : ℤ → ℤ → ℤ | (of_nat m) (of_nat n) := m * n | (of_nat m) -[1+ n] := neg_of_nat (m * succ n) | -[1+ m] (of_nat n) := neg_of_nat (succ m * n) | -[1+ m] -[1+ n] := succ m * succ n /- notation -/ protected definition prio : num := num.pred std.priority.default prefix [priority int.prio] - := int.neg infix [priority int.prio] + := int.add infix [priority int.prio] * := int.mul /- some basic functions and properties -/ theorem of_nat.inj {m n : ℕ} (H : of_nat m = of_nat n) : m = n := int.no_confusion H imp.id theorem of_nat_eq_of_nat (m n : ℕ) : of_nat m = of_nat n ↔ m = n := iff.intro of_nat.inj !congr_arg theorem neg_succ_of_nat.inj {m n : ℕ} (H : neg_succ_of_nat m = neg_succ_of_nat n) : m = n := int.no_confusion H imp.id theorem neg_succ_of_nat_eq (n : ℕ) : -[1+ n] = -(n + 1) := rfl private definition has_decidable_eq₂ : Π (a b : ℤ), decidable (a = b) | (of_nat m) (of_nat n) := decidable_of_decidable_of_iff (nat.has_decidable_eq m n) (iff.symm (of_nat_eq_of_nat m n)) | (of_nat m) -[1+ n] := inr (by contradiction) | -[1+ m] (of_nat n) := inr (by contradiction) | -[1+ m] -[1+ n] := if H : m = n then inl (congr_arg neg_succ_of_nat H) else inr (not.mto neg_succ_of_nat.inj H) definition has_decidable_eq [instance] : decidable_eq ℤ := has_decidable_eq₂ theorem of_nat_add (n m : nat) : of_nat (n + m) = of_nat n + of_nat m := rfl theorem of_nat_succ (n : ℕ) : of_nat (succ n) = of_nat n + 1 := rfl theorem of_nat_mul (n m : ℕ) : of_nat (n * m) = of_nat n * of_nat m := rfl theorem sub_nat_nat_of_ge {m n : ℕ} (H : m ≥ n) : sub_nat_nat m n = of_nat (m - n) := show sub_nat_nat m n = nat.cases_on 0 (m - n) _, from (sub_eq_zero_of_le H) ▸ rfl section local attribute sub_nat_nat [reducible] theorem sub_nat_nat_of_lt {m n : ℕ} (H : m < n) : sub_nat_nat m n = -[1+ pred (n - m)] := have H1 : n - m = succ (pred (n - m)), from (succ_pred_of_pos (sub_pos_of_lt H))⁻¹, show sub_nat_nat m n = nat.cases_on (succ (pred (n - m))) (m - n) _, from H1 ▸ rfl end definition nat_abs (a : ℤ) : ℕ := int.cases_on a function.id succ theorem nat_abs_of_nat (n : ℕ) : nat_abs n = n := rfl theorem eq_zero_of_nat_abs_eq_zero : Π {a : ℤ}, nat_abs a = 0 → a = 0 | (of_nat m) H := congr_arg of_nat H | -[1+ m'] H := absurd H !succ_ne_zero /- int is a quotient of ordered pairs of natural numbers -/ protected definition equiv (p q : ℕ × ℕ) : Prop := pr1 p + pr2 q = pr2 p + pr1 q local infix `≡` := int.equiv protected theorem equiv.refl [refl] {p : ℕ × ℕ} : p ≡ p := !add.comm protected theorem equiv.symm [symm] {p q : ℕ × ℕ} (H : p ≡ q) : q ≡ p := calc pr1 q + pr2 p = pr2 p + pr1 q : add.comm ... = pr1 p + pr2 q : H⁻¹ ... = pr2 q + pr1 p : add.comm protected theorem equiv.trans [trans] {p q r : ℕ × ℕ} (H1 : p ≡ q) (H2 : q ≡ r) : p ≡ r := add.cancel_right (calc pr1 p + pr2 r + pr2 q = pr1 p + pr2 q + pr2 r : add.right_comm ... = pr2 p + pr1 q + pr2 r : {H1} ... = pr2 p + (pr1 q + pr2 r) : add.assoc ... = pr2 p + (pr2 q + pr1 r) : {H2} ... = pr2 p + pr2 q + pr1 r : add.assoc ... = pr2 p + pr1 r + pr2 q : add.right_comm) protected theorem equiv_equiv : is_equivalence int.equiv := is_equivalence.mk @equiv.refl @equiv.symm @equiv.trans protected theorem equiv_cases {p q : ℕ × ℕ} (H : p ≡ q) : (pr1 p ≥ pr2 p ∧ pr1 q ≥ pr2 q) ∨ (pr1 p < pr2 p ∧ pr1 q < pr2 q) := or.elim (@le_or_gt (pr2 p) (pr1 p)) (suppose pr1 p ≥ pr2 p, have pr2 p + pr1 q ≥ pr2 p + pr2 q, from H ▸ add_le_add_right this (pr2 q), or.inl (and.intro `pr1 p ≥ pr2 p` (le_of_add_le_add_left this))) (suppose pr1 p < pr2 p, have pr2 p + pr1 q < pr2 p + pr2 q, from H ▸ add_lt_add_right this (pr2 q), or.inr (and.intro `pr1 p < pr2 p` (lt_of_add_lt_add_left this))) protected theorem equiv_of_eq {p q : ℕ × ℕ} (H : p = q) : p ≡ q := H ▸ equiv.refl /- the representation and abstraction functions -/ definition abstr (a : ℕ × ℕ) : ℤ := sub_nat_nat (pr1 a) (pr2 a) theorem abstr_of_ge {p : ℕ × ℕ} (H : pr1 p ≥ pr2 p) : abstr p = of_nat (pr1 p - pr2 p) := sub_nat_nat_of_ge H theorem abstr_of_lt {p : ℕ × ℕ} (H : pr1 p < pr2 p) : abstr p = -[1+ pred (pr2 p - pr1 p)] := sub_nat_nat_of_lt H definition repr : ℤ → ℕ × ℕ | (of_nat m) := (m, 0) | -[1+ m] := (0, succ m) theorem abstr_repr : Π (a : ℤ), abstr (repr a) = a | (of_nat m) := (sub_nat_nat_of_ge (zero_le m)) | -[1+ m] := rfl theorem repr_sub_nat_nat (m n : ℕ) : repr (sub_nat_nat m n) ≡ (m, n) := lt_ge_by_cases (take H : m < n, have H1 : repr (sub_nat_nat m n) = (0, n - m), by rewrite [sub_nat_nat_of_lt H, -(succ_pred_of_pos (sub_pos_of_lt H))], H1⁻¹ ▸ (!zero_add ⬝ (sub_add_cancel (le_of_lt H))⁻¹)) (take H : m ≥ n, have H1 : repr (sub_nat_nat m n) = (m - n, 0), from sub_nat_nat_of_ge H ▸ rfl, H1⁻¹ ▸ ((sub_add_cancel H) ⬝ !zero_add⁻¹)) theorem repr_abstr (p : ℕ × ℕ) : repr (abstr p) ≡ p := !prod.eta ▸ !repr_sub_nat_nat theorem abstr_eq {p q : ℕ × ℕ} (Hequiv : p ≡ q) : abstr p = abstr q := or.elim (int.equiv_cases Hequiv) (and.rec (assume (Hp : pr1 p ≥ pr2 p) (Hq : pr1 q ≥ pr2 q), have H : pr1 p - pr2 p = pr1 q - pr2 q, from calc pr1 p - pr2 p = pr1 p + pr2 q - pr2 q - pr2 p : add_sub_cancel ... = pr2 p + pr1 q - pr2 q - pr2 p : Hequiv ... = pr2 p + (pr1 q - pr2 q) - pr2 p : add_sub_assoc Hq ... = pr1 q - pr2 q + pr2 p - pr2 p : add.comm ... = pr1 q - pr2 q : add_sub_cancel, abstr_of_ge Hp ⬝ (H ▸ rfl) ⬝ (abstr_of_ge Hq)⁻¹)) (and.rec (assume (Hp : pr1 p < pr2 p) (Hq : pr1 q < pr2 q), have H : pr2 p - pr1 p = pr2 q - pr1 q, from calc pr2 p - pr1 p = pr2 p + pr1 q - pr1 q - pr1 p : add_sub_cancel ... = pr1 p + pr2 q - pr1 q - pr1 p : Hequiv ... = pr1 p + (pr2 q - pr1 q) - pr1 p : add_sub_assoc (le_of_lt Hq) ... = pr2 q - pr1 q + pr1 p - pr1 p : add.comm ... = pr2 q - pr1 q : add_sub_cancel, abstr_of_lt Hp ⬝ (H ▸ rfl) ⬝ (abstr_of_lt Hq)⁻¹)) theorem equiv_iff (p q : ℕ × ℕ) : (p ≡ q) ↔ (abstr p = abstr q) := iff.intro abstr_eq (assume H, equiv.trans (H ▸ equiv.symm (repr_abstr p)) (repr_abstr q)) theorem equiv_iff3 (p q : ℕ × ℕ) : (p ≡ q) ↔ ((p ≡ p) ∧ (q ≡ q) ∧ (abstr p = abstr q)) := iff.trans !equiv_iff (iff.symm (iff.trans (and_iff_right !equiv.refl) (and_iff_right !equiv.refl))) theorem eq_abstr_of_equiv_repr {a : ℤ} {p : ℕ × ℕ} (Hequiv : repr a ≡ p) : a = abstr p := !abstr_repr⁻¹ ⬝ abstr_eq Hequiv theorem eq_of_repr_equiv_repr {a b : ℤ} (H : repr a ≡ repr b) : a = b := eq_abstr_of_equiv_repr H ⬝ !abstr_repr section local attribute abstr [reducible] local attribute dist [reducible] theorem nat_abs_abstr : Π (p : ℕ × ℕ), nat_abs (abstr p) = dist (pr1 p) (pr2 p) | (m, n) := lt_ge_by_cases (assume H : m < n, calc nat_abs (abstr (m, n)) = nat_abs (-[1+ pred (n - m)]) : int.abstr_of_lt H ... = n - m : succ_pred_of_pos (sub_pos_of_lt H) ... = dist m n : dist_eq_sub_of_le (le_of_lt H)) (assume H : m ≥ n, (abstr_of_ge H)⁻¹ ▸ (dist_eq_sub_of_ge H)⁻¹) end theorem cases_of_nat_succ (a : ℤ) : (∃n : ℕ, a = of_nat n) ∨ (∃n : ℕ, a = - (of_nat (succ n))) := int.cases_on a (take m, or.inl (exists.intro _ rfl)) (take m, or.inr (exists.intro _ rfl)) theorem cases_of_nat (a : ℤ) : (∃n : ℕ, a = of_nat n) ∨ (∃n : ℕ, a = - of_nat n) := or.imp_right (Exists.rec (take n, (exists.intro _))) !cases_of_nat_succ theorem by_cases_of_nat {P : ℤ → Prop} (a : ℤ) (H1 : ∀n : ℕ, P (of_nat n)) (H2 : ∀n : ℕ, P (- of_nat n)) : P a := or.elim (cases_of_nat a) (assume H, obtain (n : ℕ) (H3 : a = n), from H, H3⁻¹ ▸ H1 n) (assume H, obtain (n : ℕ) (H3 : a = -n), from H, H3⁻¹ ▸ H2 n) theorem by_cases_of_nat_succ {P : ℤ → Prop} (a : ℤ) (H1 : ∀n : ℕ, P (of_nat n)) (H2 : ∀n : ℕ, P (- of_nat (succ n))) : P a := or.elim (cases_of_nat_succ a) (assume H, obtain (n : ℕ) (H3 : a = n), from H, H3⁻¹ ▸ H1 n) (assume H, obtain (n : ℕ) (H3 : a = -(succ n)), from H, H3⁻¹ ▸ H2 n) /- int is a ring -/ /- addition -/ definition padd (p q : ℕ × ℕ) : ℕ × ℕ := (pr1 p + pr1 q, pr2 p + pr2 q) theorem repr_add : Π (a b : ℤ), repr (add a b) ≡ padd (repr a) (repr b) | (of_nat m) (of_nat n) := !equiv.refl | (of_nat m) -[1+ n] := (!zero_add ▸ rfl)⁻¹ ▸ !repr_sub_nat_nat | -[1+ m] (of_nat n) := (!zero_add ▸ rfl)⁻¹ ▸ !repr_sub_nat_nat | -[1+ m] -[1+ n] := !repr_sub_nat_nat theorem padd_congr {p p' q q' : ℕ × ℕ} (Ha : p ≡ p') (Hb : q ≡ q') : padd p q ≡ padd p' q' := calc pr1 p + pr1 q + (pr2 p' + pr2 q') = pr1 p + pr2 p' + (pr1 q + pr2 q') : add.comm4 ... = pr2 p + pr1 p' + (pr1 q + pr2 q') : {Ha} ... = pr2 p + pr1 p' + (pr2 q + pr1 q') : {Hb} ... = pr2 p + pr2 q + (pr1 p' + pr1 q') : add.comm4 theorem padd_comm (p q : ℕ × ℕ) : padd p q = padd q p := calc (pr1 p + pr1 q, pr2 p + pr2 q) = (pr1 q + pr1 p, pr2 p + pr2 q) : add.comm ... = (pr1 q + pr1 p, pr2 q + pr2 p) : add.comm theorem padd_assoc (p q r : ℕ × ℕ) : padd (padd p q) r = padd p (padd q r) := calc (pr1 p + pr1 q + pr1 r, pr2 p + pr2 q + pr2 r) = (pr1 p + (pr1 q + pr1 r), pr2 p + pr2 q + pr2 r) : add.assoc ... = (pr1 p + (pr1 q + pr1 r), pr2 p + (pr2 q + pr2 r)) : add.assoc theorem add.comm (a b : ℤ) : a + b = b + a := eq_of_repr_equiv_repr (equiv.trans !repr_add (equiv.symm (!padd_comm ▸ !repr_add))) theorem add.assoc (a b c : ℤ) : a + b + c = a + (b + c) := eq_of_repr_equiv_repr (calc repr (a + b + c) ≡ padd (repr (a + b)) (repr c) : repr_add ... ≡ padd (padd (repr a) (repr b)) (repr c) : padd_congr !repr_add !equiv.refl ... = padd (repr a) (padd (repr b) (repr c)) : !padd_assoc ... ≡ padd (repr a) (repr (b + c)) : padd_congr !equiv.refl !repr_add ... ≡ repr (a + (b + c)) : repr_add) theorem add_zero : Π (a : ℤ), a + 0 = a := int.rec (λm, rfl) (λm, rfl) theorem zero_add (a : ℤ) : 0 + a = a := !add.comm ▸ !add_zero /- negation -/ definition pneg (p : ℕ × ℕ) : ℕ × ℕ := (pr2 p, pr1 p) -- note: this is =, not just ≡ theorem repr_neg : Π (a : ℤ), repr (- a) = pneg (repr a) | 0 := rfl | (succ m) := rfl | -[1+ m] := rfl theorem pneg_congr {p p' : ℕ × ℕ} (H : p ≡ p') : pneg p ≡ pneg p' := eq.symm H theorem pneg_pneg (p : ℕ × ℕ) : pneg (pneg p) = p := !prod.eta theorem nat_abs_neg (a : ℤ) : nat_abs (-a) = nat_abs a := calc nat_abs (-a) = nat_abs (abstr (repr (-a))) : abstr_repr ... = nat_abs (abstr (pneg (repr a))) : repr_neg ... = dist (pr1 (pneg (repr a))) (pr2 (pneg (repr a))) : nat_abs_abstr ... = dist (pr2 (pneg (repr a))) (pr1 (pneg (repr a))) : dist.comm ... = nat_abs (abstr (repr a)) : nat_abs_abstr ... = nat_abs a : abstr_repr theorem padd_pneg (p : ℕ × ℕ) : padd p (pneg p) ≡ (0, 0) := show pr1 p + pr2 p + 0 = pr2 p + pr1 p + 0, from !nat.add.comm ▸ rfl theorem padd_padd_pneg (p q : ℕ × ℕ) : padd (padd p q) (pneg q) ≡ p := calc pr1 p + pr1 q + pr2 q + pr2 p = pr1 p + (pr1 q + pr2 q) + pr2 p : nat.add.assoc ... = pr1 p + (pr1 q + pr2 q + pr2 p) : nat.add.assoc ... = pr1 p + (pr2 q + pr1 q + pr2 p) : nat.add.comm ... = pr1 p + (pr2 q + pr2 p + pr1 q) : add.right_comm ... = pr1 p + (pr2 p + pr2 q + pr1 q) : nat.add.comm ... = pr2 p + pr2 q + pr1 q + pr1 p : nat.add.comm theorem add.left_inv (a : ℤ) : -a + a = 0 := have H : repr (-a + a) ≡ repr 0, from calc repr (-a + a) ≡ padd (repr (neg a)) (repr a) : repr_add ... = padd (pneg (repr a)) (repr a) : repr_neg ... ≡ repr 0 : padd_pneg, eq_of_repr_equiv_repr H /- nat abs -/ definition pabs (p : ℕ × ℕ) : ℕ := dist (pr1 p) (pr2 p) theorem pabs_congr {p q : ℕ × ℕ} (H : p ≡ q) : pabs p = pabs q := calc pabs p = nat_abs (abstr p) : nat_abs_abstr ... = nat_abs (abstr q) : abstr_eq H ... = pabs q : nat_abs_abstr theorem nat_abs_eq_pabs_repr (a : ℤ) : nat_abs a = pabs (repr a) := calc nat_abs a = nat_abs (abstr (repr a)) : abstr_repr ... = pabs (repr a) : nat_abs_abstr theorem nat_abs_add_le (a b : ℤ) : nat_abs (a + b) ≤ nat_abs a + nat_abs b := calc nat_abs (a + b) = pabs (repr (a + b)) : nat_abs_eq_pabs_repr ... = pabs (padd (repr a) (repr b)) : pabs_congr !repr_add ... ≤ pabs (repr a) + pabs (repr b) : dist_add_add_le_add_dist_dist ... = pabs (repr a) + nat_abs b : nat_abs_eq_pabs_repr ... = nat_abs a + nat_abs b : nat_abs_eq_pabs_repr section local attribute nat_abs [reducible] theorem nat_abs_mul : Π (a b : ℤ), nat_abs (a * b) = (nat_abs a) * (nat_abs b) | (of_nat m) (of_nat n) := rfl | (of_nat m) -[1+ n] := !nat_abs_neg ▸ rfl | -[1+ m] (of_nat n) := !nat_abs_neg ▸ rfl | -[1+ m] -[1+ n] := rfl end /- multiplication -/ definition pmul (p q : ℕ × ℕ) : ℕ × ℕ := (pr1 p * pr1 q + pr2 p * pr2 q, pr1 p * pr2 q + pr2 p * pr1 q) theorem repr_neg_of_nat (m : ℕ) : repr (neg_of_nat m) = (0, m) := nat.cases_on m rfl (take m', rfl) -- note: we have =, not just ≡ theorem repr_mul : Π (a b : ℤ), repr (a * b) = pmul (repr a) (repr b) | (of_nat m) (of_nat n) := calc (m * n + 0 * 0, m * 0 + 0) = (m * n + 0 * 0, m * 0 + 0 * n) : zero_mul | (of_nat m) -[1+ n] := calc repr (m * -[1+ n]) = (m * 0 + 0, m * succ n + 0 * 0) : repr_neg_of_nat ... = (m * 0 + 0 * succ n, m * succ n + 0 * 0) : zero_mul | -[1+ m] (of_nat n) := calc repr (-[1+ m] * n) = (0 + succ m * 0, succ m * n) : repr_neg_of_nat ... = (0 + succ m * 0, 0 + succ m * n) : nat.zero_add ... = (0 * n + succ m * 0, 0 + succ m * n) : zero_mul | -[1+ m] -[1+ n] := calc (succ m * succ n, 0) = (succ m * succ n, 0 * succ n) : zero_mul ... = (0 + succ m * succ n, 0 * succ n) : nat.zero_add theorem equiv_mul_prep {xa ya xb yb xn yn xm ym : ℕ} (H1 : xa + yb = ya + xb) (H2 : xn + ym = yn + xm) : xa*xn+ya*yn+(xb*ym+yb*xm) = xa*yn+ya*xn+(xb*xm+yb*ym) := nat.add.cancel_right (calc xa*xn+ya*yn + (xb*ym+yb*xm) + (yb*xn+xb*yn + (xb*xn+yb*yn)) = xa*xn+ya*yn + (yb*xn+xb*yn) + (xb*ym+yb*xm + (xb*xn+yb*yn)) : add.comm4 ... = xa*xn+ya*yn + (yb*xn+xb*yn) + (xb*xn+yb*yn + (xb*ym+yb*xm)) : nat.add.comm ... = xa*xn+yb*xn + (ya*yn+xb*yn) + (xb*xn+xb*ym + (yb*yn+yb*xm)) : !congr_arg2 add.comm4 add.comm4 ... = ya*xn+xb*xn + (xa*yn+yb*yn) + (xb*yn+xb*xm + (yb*xn+yb*ym)) : by rewrite[-+mul.left_distrib,-+mul.right_distrib]; exact H1 ▸ H2 ▸ rfl ... = ya*xn+xa*yn + (xb*xn+yb*yn) + (xb*yn+yb*xn + (xb*xm+yb*ym)) : !congr_arg2 add.comm4 add.comm4 ... = xa*yn+ya*xn + (xb*xn+yb*yn) + (yb*xn+xb*yn + (xb*xm+yb*ym)) : !nat.add.comm ▸ !nat.add.comm ▸ rfl ... = xa*yn+ya*xn + (yb*xn+xb*yn) + (xb*xn+yb*yn + (xb*xm+yb*ym)) : add.comm4 ... = xa*yn+ya*xn + (yb*xn+xb*yn) + (xb*xm+yb*ym + (xb*xn+yb*yn)) : nat.add.comm ... = xa*yn+ya*xn + (xb*xm+yb*ym) + (yb*xn+xb*yn + (xb*xn+yb*yn)) : add.comm4) theorem pmul_congr {p p' q q' : ℕ × ℕ} : p ≡ p' → q ≡ q' → pmul p q ≡ pmul p' q' := equiv_mul_prep theorem pmul_comm (p q : ℕ × ℕ) : pmul p q = pmul q p := show (_,_) = (_,_), from !congr_arg2 (!congr_arg2 !mul.comm !mul.comm) (!nat.add.comm ⬝ (!congr_arg2 !mul.comm !mul.comm)) theorem mul.comm (a b : ℤ) : a * b = b * a := eq_of_repr_equiv_repr ((calc repr (a * b) = pmul (repr a) (repr b) : repr_mul ... = pmul (repr b) (repr a) : pmul_comm ... = repr (b * a) : repr_mul) ▸ !equiv.refl) private theorem pmul_assoc_prep {p1 p2 q1 q2 r1 r2 : ℕ} : ((p1*q1+p2*q2)*r1+(p1*q2+p2*q1)*r2, (p1*q1+p2*q2)*r2+(p1*q2+p2*q1)*r1) = (p1*(q1*r1+q2*r2)+p2*(q1*r2+q2*r1), p1*(q1*r2+q2*r1)+p2*(q1*r1+q2*r2)) := by rewrite[+mul.left_distrib,+mul.right_distrib,*mul.assoc]; exact (congr_arg2 pair (!add.comm4 ⬝ (!congr_arg !nat.add.comm)) (!add.comm4 ⬝ (!congr_arg !nat.add.comm))) theorem pmul_assoc (p q r: ℕ × ℕ) : pmul (pmul p q) r = pmul p (pmul q r) := pmul_assoc_prep theorem mul.assoc (a b c : ℤ) : (a * b) * c = a * (b * c) := eq_of_repr_equiv_repr ((calc repr (a * b * c) = pmul (repr (a * b)) (repr c) : repr_mul ... = pmul (pmul (repr a) (repr b)) (repr c) : repr_mul ... = pmul (repr a) (pmul (repr b) (repr c)) : pmul_assoc ... = pmul (repr a) (repr (b * c)) : repr_mul ... = repr (a * (b * c)) : repr_mul) ▸ !equiv.refl) theorem mul_one : Π (a : ℤ), a * 1 = a | (of_nat m) := !zero_add -- zero_add happens to be def. = to this thm | -[1+ m] := !nat.zero_add ▸ rfl theorem one_mul (a : ℤ) : 1 * a = a := mul.comm a 1 ▸ mul_one a private theorem mul_distrib_prep {a1 a2 b1 b2 c1 c2 : ℕ} : ((a1+b1)*c1+(a2+b2)*c2, (a1+b1)*c2+(a2+b2)*c1) = (a1*c1+a2*c2+(b1*c1+b2*c2), a1*c2+a2*c1+(b1*c2+b2*c1)) := by rewrite[+mul.right_distrib] ⬝ (!congr_arg2 !add.comm4 !add.comm4) theorem mul.right_distrib (a b c : ℤ) : (a + b) * c = a * c + b * c := eq_of_repr_equiv_repr (calc repr ((a + b) * c) = pmul (repr (a + b)) (repr c) : repr_mul ... ≡ pmul (padd (repr a) (repr b)) (repr c) : pmul_congr !repr_add equiv.refl ... = padd (pmul (repr a) (repr c)) (pmul (repr b) (repr c)) : mul_distrib_prep ... = padd (repr (a * c)) (pmul (repr b) (repr c)) : repr_mul ... = padd (repr (a * c)) (repr (b * c)) : repr_mul ... ≡ repr (a * c + b * c) : repr_add) theorem mul.left_distrib (a b c : ℤ) : a * (b + c) = a * b + a * c := calc a * (b + c) = (b + c) * a : mul.comm ... = b * a + c * a : mul.right_distrib ... = a * b + c * a : mul.comm ... = a * b + a * c : mul.comm theorem zero_ne_one : (0 : int) ≠ 1 := assume H : 0 = 1, !succ_ne_zero (of_nat.inj H)⁻¹ theorem eq_zero_or_eq_zero_of_mul_eq_zero {a b : ℤ} (H : a * b = 0) : a = 0 ∨ b = 0 := or.imp eq_zero_of_nat_abs_eq_zero eq_zero_of_nat_abs_eq_zero (eq_zero_or_eq_zero_of_mul_eq_zero (H ▸ (nat_abs_mul a b)⁻¹)) section migrate_algebra open [classes] algebra protected definition integral_domain [reducible] : algebra.integral_domain int := ⦃algebra.integral_domain, add := add, add_assoc := add.assoc, zero := zero, zero_add := zero_add, add_zero := add_zero, neg := neg, add_left_inv := add.left_inv, add_comm := add.comm, mul := mul, mul_assoc := mul.assoc, one := 1, one_mul := one_mul, mul_one := mul_one, left_distrib := mul.left_distrib, right_distrib := mul.right_distrib, mul_comm := mul.comm, zero_ne_one := zero_ne_one, eq_zero_or_eq_zero_of_mul_eq_zero := @eq_zero_or_eq_zero_of_mul_eq_zero⦄ local attribute int.integral_domain [instance] definition sub (a b : ℤ) : ℤ := algebra.sub a b infix [priority int.prio] - := int.sub definition dvd (a b : ℤ) : Prop := algebra.dvd a b notation [priority int.prio] a ∣ b := dvd a b migrate from algebra with int replacing sub → sub, dvd → dvd end migrate_algebra /- additional properties -/ theorem of_nat_sub {m n : ℕ} (H : m ≥ n) : m - n = sub m n := assert m - n + n = m, from nat.sub_add_cancel H, begin symmetry, apply sub_eq_of_eq_add, rewrite [-of_nat_add, this] end -- (sub_eq_of_eq_add (!congr_arg (nat.sub_add_cancel H)⁻¹))⁻¹ theorem neg_succ_of_nat_eq' (m : ℕ) : -[1+ m] = -m - 1 := by rewrite [neg_succ_of_nat_eq, of_nat_add, neg_add] definition succ (a : ℤ) := a + (succ zero) definition pred (a : ℤ) := a - (succ zero) theorem pred_succ (a : ℤ) : pred (succ a) = a := !sub_add_cancel theorem succ_pred (a : ℤ) : succ (pred a) = a := !add_sub_cancel theorem neg_succ (a : ℤ) : -succ a = pred (-a) := by rewrite [↑succ,neg_add] theorem succ_neg_succ (a : ℤ) : succ (-succ a) = -a := by rewrite [neg_succ,succ_pred] theorem neg_pred (a : ℤ) : -pred a = succ (-a) := by rewrite [↑pred,neg_sub,sub_eq_add_neg,add.comm] theorem pred_neg_pred (a : ℤ) : pred (-pred a) = -a := by rewrite [neg_pred,pred_succ] theorem pred_nat_succ (n : ℕ) : pred (nat.succ n) = n := pred_succ n theorem neg_nat_succ (n : ℕ) : -nat.succ n = pred (-n) := !neg_succ theorem succ_neg_nat_succ (n : ℕ) : succ (-nat.succ n) = -n := !succ_neg_succ definition rec_nat_on [unfold 2] {P : ℤ → Type} (z : ℤ) (H0 : P 0) (Hsucc : Π⦃n : ℕ⦄, P n → P (succ n)) (Hpred : Π⦃n : ℕ⦄, P (-n) → P (-nat.succ n)) : P z := int.rec (nat.rec H0 Hsucc) (λn, nat.rec H0 Hpred (nat.succ n)) z --the only computation rule of rec_nat_on which is not definitional theorem rec_nat_on_neg {P : ℤ → Type} (n : nat) (H0 : P zero) (Hsucc : Π⦃n : nat⦄, P n → P (succ n)) (Hpred : Π⦃n : nat⦄, P (-n) → P (-nat.succ n)) : rec_nat_on (-nat.succ n) H0 Hsucc Hpred = Hpred (rec_nat_on (-n) H0 Hsucc Hpred) := nat.rec rfl (λn H, rfl) n end int
01a72a1d5950b15b5d3ae9c70e89da964d30a7c7
b32d3853770e6eaf06817a1b8c52064baaed0ef1
/src/super/prover_state.lean
0e330155b56090689ac5a59b0cd66123b58c3177
[]
no_license
gebner/super2
4d58b7477b6f7d945d5d866502982466db33ab0b
9bc5256c31750021ab97d6b59b7387773e54b384
refs/heads/master
1,635,021,682,021
1,634,886,326,000
1,634,886,326,000
225,600,688
4
2
null
1,598,209,306,000
1,575,371,550,000
Lean
UTF-8
Lean
false
false
7,482
lean
import super.clause super.lpo namespace super open tactic native @[reducible] def clause_id := ℕ @[derive decidable_eq] meta structure derived_clause := (id : clause_id) (cls : clause) (selected : list ℕ) namespace derived_clause meta instance : has_to_tactic_format derived_clause := ⟨λ c, do c_fmt ← pp c.cls, pure $ to_fmt c.id ++ ": " ++ c_fmt ++ " (sel: " ++ to_fmt c.selected ++ ")"⟩ meta instance : has_to_string derived_clause := ⟨λ c, to_string c.id ++ ": " ++ to_string c.cls ++ " (sel: " ++ to_string c.selected ++ ")"⟩ meta instance : has_repr derived_clause := ⟨to_string⟩ meta def clone (dc : derived_clause) : tactic derived_clause := do cls' ← dc.cls.clone, pure { cls := cls', ..dc } meta def selected_lits (dc : derived_clause) : list (literal × ℕ) := do let lits := dc.cls.literals, i ← dc.selected, some l ← pure (lits.nth i) | [], pure (l, i) end derived_clause meta structure prover_state := (active : rb_map clause_id derived_clause) (passive : rb_map clause_id derived_clause) (prec : list name) (clause_counter : ℕ) (steps : list (expr × expr)) meta def prover_state.initial : prover_state := { active := mk_rb_map, passive := mk_rb_map, prec := [], clause_counter := 0, steps := [] } meta def prover := state_t prover_state tactic namespace prover local attribute [reducible] prover meta instance : monad prover := infer_instance meta instance : alternative prover := infer_instance meta instance : monad_state _ prover := infer_instance meta instance : has_monad_lift tactic prover := infer_instance meta instance (α : Type) : has_coe (tactic α) (prover α) := ⟨monad_lift⟩ end prover meta def literal_selection_strategy := derived_clause → prover derived_clause meta def clause_selection_strategy := ℕ → prover clause_id meta def get_active : prover (rb_map clause_id derived_clause) := prover_state.active <$> get meta def add_active (a : derived_clause) : prover punit := modify $ λ st, { active := st.active.insert a.id a, ..st } meta def get_passive : prover (rb_map clause_id derived_clause) := prover_state.passive <$> get meta def consume_passive (id : clause_id) : prover derived_clause := do st ← get, put { passive := st.passive.erase id, ..st }, some cls ← pure (st.passive.find id) | fail "consume_passive: unknown id", pure cls meta def get_precedence : prover (list name) := prover_state.prec <$> get meta def term_order := expr → expr → bool meta def get_term_order : prover term_order := mk_lpo <$> get_precedence private meta def set_precedence (new_prec : list name) : prover punit := modify $ λ st, { prec := new_prec, ..st } -- TODO: rethink this meta def register_consts_in_precedence (consts : list name) : prover unit := do p ← get_precedence, let p_set := rb_map.set_of_list p, let new_syms := consts.filter (λ c, ¬ p_set.contains c), set_precedence (new_syms ++ p) meta def get_clause_count : prover ℕ := prover_state.clause_counter <$> get meta def get_new_cls_id : prover clause_id := do state ← get, put { state with clause_counter := state.clause_counter + 1 }, return state.clause_counter meta def add_passive (strat : literal_selection_strategy) (c : clause) : prover clause_id := do c.check_if_debug, id ← get_new_cls_id, c_ty ← c.ty.to_expr, register_consts_in_precedence (contained_funsyms c_ty).to_list, -- TODO: rethink this dc ← strat { id := id, cls := c, selected := [] }, modify $ λ st, { passive := st.passive.insert id dc, ..st }, pure id meta def remove_redundant (id : clause_id) : prover unit := modify $ λ st, { active := st.active.erase id, ..st } meta def preprocessing_rule := list clause → prover (list clause) meta def simplification_rule := clause → prover (option clause) @[inline] meta def simplification_rule.as_preprocessing_rule (r : simplification_rule) : preprocessing_rule := λ cs, list.join <$> cs.mmap (λ c, clause.check_results_if_debug $ option.to_list <$> r c) meta def inference_rule := derived_clause → prover (list clause) meta def retrieve {α} (p : prover α) : prover α := do s ← get, ↑(tactic.retrieve $ prod.fst <$> p.run s) meta def retrieve_packed (ps : list (prover (list clause))) : prover (list clause) := (list.join <$> monad.sequence (do p ← ps, pure $ retrieve $ p >>= list.mmap (λ c, c.pack))) >>= list.mmap (λ c : packed_clause, clause.check_result_if_debug c.unpack) private meta def unfold_head1 : expr → tactic expr | (expr.const n ls) := do d ← get_decl n, some v ← pure $ d.instantiate_value_univ_params ls | fail "instantiate_value_univ_params", pure v | (expr.app a b) := expr.app' <$> unfold_head1 a <*> pure b | e := pure e meta def intern (c : clause) : prover clause := do i ← (λ st : prover_state, st.steps.length) <$> get, new_prf ← c.mk_decl i, let step := new_prf.get_app_fn, step_repl ← unfold_head1 step, modify $ λ st, { steps := st.steps ++ [(step, step_repl)], ..st }, pure { prf := new_prf, ..c } meta def intern_sk_term (e : expr) : prover expr := do i ← (λ st : prover_state, st.steps.length) <$> get, ty ← infer_type e, e' ← add_aux_decl ((`_super.sk).mk_numeral (unsigned.of_nat i)) ty e ff, let step := e'.get_app_fn, step_repl ← unfold_head1 step, modify $ λ st, { steps := st.steps ++ [(step, step_repl)], ..st }, pure e' meta def intern_derived (c : derived_clause) : prover derived_clause := do cls ← intern c.cls, pure { cls := cls, ..c } private meta def abstract_super_steps : expr → state_t (rb_map expr expr) tactic expr | fn@(expr.const (name.mk_numeral i (name.mk_string cat `_super)) _) := do lc ← flip rb_map.find fn <$> get, match lc with | some lc := pure lc | none := do ty ← state_t.lift $ infer_type fn, lc ← state_t.lift $ mk_local' (cat ++ "_" ++ to_string i : string) binder_info.default ty, state_t.modify $ λ st, st.insert fn lc, pure lc end | (expr.lam n bi a b) := expr.lam n bi <$> abstract_super_steps a <*> abstract_super_steps b | (expr.pi n bi a b) := expr.pi n bi <$> abstract_super_steps a <*> abstract_super_steps b | (expr.elet n a b c) := expr.elet n <$> abstract_super_steps a <*> abstract_super_steps b <*> abstract_super_steps c | (expr.sort u) := pure $ expr.sort u | e@(expr.const _ _) := pure e | e@(expr.var _) := pure e | e@(expr.local_const _ _ _ _) := pure e | e@(expr.mvar _ _ _) := pure e | (expr.macro md es) := expr.macro md <$> es.mmap abstract_super_steps | (expr.app a b) := expr.app <$> abstract_super_steps a <*> abstract_super_steps b private meta def unfold_defs_core : list (expr × expr) → expr → state_t (rb_map expr expr) tactic expr | (⟨fn, repl⟩ :: steps) e := do e ← unfold_defs_core steps e, lcs ← rb_map.to_list <$> get, lcs.mfoldr (λ ⟨fn', lc⟩ e, do some repl' ← state_t.lift $ tactic.retrieve $ try_core $ unify fn fn' >> instantiate_mvars repl | pure e, state_t.modify $ λ st, st.erase fn', repl' ← abstract_super_steps repl', ty' ← state_t.lift $ infer_type repl', ty' ← abstract_super_steps ty', pure $ expr.elet lc.local_pp_name ty' repl' (e.abstract_local lc.local_uniq_name)) e | [] e := abstract_super_steps e meta def unfold_defs (e : expr) : prover expr := do steps ← prover_state.steps <$> get, (e', lcs) ← (unfold_defs_core steps e).run mk_rb_map, 0 ← pure lcs.size | fail "unfold_defs did not unfold all defs", pure e' end super
aab2aa7bc44e96a8a7b32901f60eb29ec717d273
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/category_theory/limits/shapes/constructions/binary_products.lean
dddbf1dbdb628d0350a89f191ab91c90e00e35d1
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
1,630
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.limits.shapes.pullbacks import category_theory.limits.shapes.binary_products universes v u /-! # Constructing binary product from pullbacks and terminal object. If a category has pullbacks and a terminal object, then it has binary products. TODO: provide the dual result. -/ open category_theory category_theory.category category_theory.limits /-- Any category with pullbacks and terminal object has binary products. -/ -- This is not an instance, as it is not always how one wants to construct binary products! def has_binary_products_of_terminal_and_pullbacks (C : Type u) [𝒞 : category.{v} C] [has_terminal C] [has_pullbacks C] : has_binary_products C := { has_limits_of_shape := { has_limit := λ F, { cone := { X := pullback (terminal.from (F.obj walking_pair.left)) (terminal.from (F.obj walking_pair.right)), π := discrete.nat_trans (λ x, walking_pair.cases_on x pullback.fst pullback.snd)}, is_limit := { lift := λ c, pullback.lift ((c.π).app walking_pair.left) ((c.π).app walking_pair.right) (subsingleton.elim _ _), fac' := λ s c, walking_pair.cases_on c (limit.lift_π _ _) (limit.lift_π _ _), uniq' := λ s m J, begin rw [←J, ←J], ext; rw limit.lift_π; refl end } } } }
b21f687acdcb8083b5980f4b9e245bcb5ea78755
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/linear/functor_category.lean
594349a2a5381cfb2b429048be8d93b8b4c11bde
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
1,779
lean
/- Copyright (c) 2022 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.preadditive.functor_category import category_theory.linear.basic /-! # Linear structure on functor categories > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. If `C` and `D` are categories and `D` is `R`-linear, then `C ⥤ D` is also `R`-linear. -/ open_locale big_operators namespace category_theory open category_theory.limits linear variables {R : Type*} [semiring R] variables {C D : Type*} [category C] [category D] [preadditive D] [linear R D] instance functor_category_linear : linear R (C ⥤ D) := { hom_module := λ F G, { smul := λ r α, { app := λ X, r • α.app X, naturality' := by { intros, rw [comp_smul, smul_comp, α.naturality] } }, one_smul := by { intros, ext, apply one_smul }, zero_smul := by { intros, ext, apply zero_smul }, smul_zero := by { intros, ext, apply smul_zero }, add_smul := by { intros, ext, apply add_smul }, smul_add := by { intros, ext, apply smul_add }, mul_smul := by { intros, ext, apply mul_smul } }, smul_comp' := by { intros, ext, apply smul_comp }, comp_smul' := by { intros, ext, apply comp_smul } } namespace nat_trans variables {F G : C ⥤ D} /-- Application of a natural transformation at a fixed object, as group homomorphism -/ @[simps] def app_linear_map (X : C) : (F ⟶ G) →ₗ[R] (F.obj X ⟶ G.obj X) := { to_fun := λ α, α.app X, map_add' := λ _ _, rfl, map_smul' := λ _ _, rfl, } @[simp] lemma app_smul (X : C) (r : R) (α : F ⟶ G) : (r • α).app X = r • α.app X := rfl end nat_trans end category_theory
d9598ad953e7f54db185e097a5e0c010b2ea3685
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/constructor1.lean
a76ddbcb13dae1cabde34ab9fd051733ad75b6fe
[ "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
669
lean
open tactic example (p q : Prop) : p → q → p ∧ q := by do intros, constructor, assumption, assumption example (p q : Prop) : p → q → p ∧ q := by do intros, split, assumption, assumption example (p q : Prop) : p → p ∨ q := by do intros, left, assumption example (p q : Prop) : q → p ∨ q := by do intros, right, assumption example (p q : Prop) : p → p ∨ q := by do intros, constructor_idx 1, assumption example (p q : Prop) : q → p ∨ q := by do intros, constructor_idx 2, assumption example (a : nat) : a = a := by constructor example (a b : nat) : ∃ x, x = a := by do a ← get_local `a, existsi a, trace_state, constructor
3880386d37e197ee59e082cf7cf432332364dc53
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/topology/subset_properties.lean
e6b139d16b8f16cd9cc77dbbd269425f32cf49a3
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
31,157
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 Properties of subsets of topological spaces: compact, clopen, irreducible, connected, totally disconnected, totally separated. -/ import topology.constructions open set filter lattice classical open_locale classical topological_space universes u v variables {α : Type u} {β : Type v} [topological_space α] /- compact sets -/ section compact /-- A set `s` is compact if for every filter `f` that contains `s`, every set of `f` also meets every neighborhood of some `a ∈ s`. -/ def compact (s : set α) := ∀f, f ≠ ⊥ → f ≤ principal s → ∃a∈s, f ⊓ 𝓝 a ≠ ⊥ lemma compact_inter {s t : set α} (hs : compact s) (ht : is_closed t) : compact (s ∩ t) := assume f hnf hstf, let ⟨a, hsa, (ha : f ⊓ 𝓝 a ≠ ⊥)⟩ := hs f hnf (le_trans hstf (le_principal_iff.2 (inter_subset_left _ _))) in have ∀a, principal t ⊓ 𝓝 a ≠ ⊥ → a ∈ t, by intro a; rw [inf_comm]; rw [is_closed_iff_nhds] at ht; exact ht a, have a ∈ t, from this a $ neq_bot_of_le_neq_bot ha $ inf_le_inf (le_trans hstf (le_principal_iff.2 (inter_subset_right _ _))) (le_refl _), ⟨a, ⟨hsa, this⟩, ha⟩ lemma compact_diff {s t : set α} (hs : compact s) (ht : is_open t) : compact (s \ t) := compact_inter hs (is_closed_compl_iff.mpr ht) lemma compact_of_is_closed_subset {s t : set α} (hs : compact s) (ht : is_closed t) (h : t ⊆ s) : compact t := by convert ← compact_inter hs ht; exact inter_eq_self_of_subset_right h lemma compact_adherence_nhdset {s t : set α} {f : filter α} (hs : compact s) (hf₂ : f ≤ principal s) (ht₁ : is_open t) (ht₂ : ∀a∈s, 𝓝 a ⊓ f ≠ ⊥ → a ∈ t) : t ∈ f := classical.by_cases mem_sets_of_neq_bot $ assume : f ⊓ principal (- t) ≠ ⊥, let ⟨a, ha, (hfa : f ⊓ principal (-t) ⊓ 𝓝 a ≠ ⊥)⟩ := hs _ this $ inf_le_left_of_le hf₂ in have a ∈ t, from ht₂ a ha $ neq_bot_of_le_neq_bot hfa $ le_inf inf_le_right $ inf_le_left_of_le inf_le_left, have 𝓝 a ⊓ principal (-t) ≠ ⊥, from neq_bot_of_le_neq_bot hfa $ le_inf inf_le_right $ inf_le_left_of_le inf_le_right, have ∀s∈(𝓝 a ⊓ principal (-t)).sets, s ≠ ∅, from forall_sets_neq_empty_iff_neq_bot.mpr this, have false, from this _ ⟨t, mem_nhds_sets ht₁ ‹a ∈ t›, -t, subset.refl _, subset.refl _⟩ (inter_compl_self _), by contradiction lemma compact_iff_ultrafilter_le_nhds {s : set α} : compact s ↔ (∀f, is_ultrafilter f → f ≤ principal s → ∃a∈s, f ≤ 𝓝 a) := ⟨assume hs : compact s, assume f hf hfs, let ⟨a, ha, h⟩ := hs _ hf.left hfs in ⟨a, ha, le_of_ultrafilter hf h⟩, assume hs : (∀f, is_ultrafilter f → f ≤ principal s → ∃a∈s, f ≤ 𝓝 a), assume f hf hfs, let ⟨a, ha, (h : ultrafilter_of f ≤ 𝓝 a)⟩ := hs (ultrafilter_of f) (ultrafilter_ultrafilter_of hf) (le_trans ultrafilter_of_le hfs) in have ultrafilter_of f ⊓ 𝓝 a ≠ ⊥, by simp only [inf_of_le_left, h]; exact (ultrafilter_ultrafilter_of hf).left, ⟨a, ha, neq_bot_of_le_neq_bot this (inf_le_inf ultrafilter_of_le (le_refl _))⟩⟩ lemma compact_elim_finite_subcover {s : set α} {c : set (set α)} (hs : compact s) (hc₁ : ∀t∈c, is_open t) (hc₂ : s ⊆ ⋃₀ c) : ∃c'⊆c, finite c' ∧ s ⊆ ⋃₀ c' := classical.by_contradiction $ assume h, have h : ∀{c'}, c' ⊆ c → finite c' → ¬ s ⊆ ⋃₀ c', from assume c' h₁ h₂ h₃, h ⟨c', h₁, h₂, h₃⟩, let f : filter α := (⨅c':{c' : set (set α) // c' ⊆ c ∧ finite c'}, principal (s - ⋃₀ c')), ⟨a, ha⟩ := @exists_mem_of_ne_empty α s (assume h', h (empty_subset _) finite_empty $ h'.symm ▸ empty_subset _) in have f ≠ ⊥, from infi_neq_bot_of_directed ⟨a⟩ (assume ⟨c₁, hc₁, hc'₁⟩ ⟨c₂, hc₂, hc'₂⟩, ⟨⟨c₁ ∪ c₂, union_subset hc₁ hc₂, finite_union hc'₁ hc'₂⟩, principal_mono.mpr $ diff_subset_diff_right $ sUnion_mono $ subset_union_left _ _, principal_mono.mpr $ diff_subset_diff_right $ sUnion_mono $ subset_union_right _ _⟩) (assume ⟨c', hc'₁, hc'₂⟩, show principal (s \ _) ≠ ⊥, by simp only [ne.def, principal_eq_bot_iff, diff_eq_empty]; exact h hc'₁ hc'₂), have f ≤ principal s, from infi_le_of_le ⟨∅, empty_subset _, finite_empty⟩ $ show principal (s \ ⋃₀∅) ≤ principal s, from le_principal_iff.2 (diff_subset _ _), let ⟨a, ha, (h : f ⊓ 𝓝 a ≠ ⊥)⟩ := hs f ‹f ≠ ⊥› this, ⟨t, ht₁, (ht₂ : a ∈ t)⟩ := hc₂ ha in have f ≤ principal (-t), from infi_le_of_le ⟨{t}, by rwa singleton_subset_iff, finite_insert _ finite_empty⟩ $ principal_mono.mpr $ show s - ⋃₀{t} ⊆ - t, begin rw sUnion_singleton; exact assume x ⟨_, hnt⟩, hnt end, have is_closed (- t), from is_open_compl_iff.mp $ by rw lattice.neg_neg; exact hc₁ t ht₁, have a ∈ - t, from is_closed_iff_nhds.mp this _ $ neq_bot_of_le_neq_bot h $ le_inf inf_le_right (inf_le_left_of_le ‹f ≤ principal (- t)›), this ‹a ∈ t› lemma compact_elim_finite_subcover_image {s : set α} {b : set β} {c : β → set α} (hs : compact s) (hc₁ : ∀i∈b, is_open (c i)) (hc₂ : s ⊆ ⋃i∈b, c i) : ∃b'⊆b, finite b' ∧ s ⊆ ⋃i∈b', c i := if h : b = ∅ then ⟨∅, empty_subset _, finite_empty, h ▸ hc₂⟩ else let ⟨i, hi⟩ := exists_mem_of_ne_empty h in have hc'₁ : ∀i∈c '' b, is_open i, from assume i ⟨j, hj, h⟩, h ▸ hc₁ _ hj, have hc'₂ : s ⊆ ⋃₀ (c '' b), by rwa set.sUnion_image, let ⟨d, hd₁, hd₂, hd₃⟩ := compact_elim_finite_subcover hs hc'₁ hc'₂ in have ∀x : d, ∃i, i ∈ b ∧ c i = x, from assume ⟨x, hx⟩, hd₁ hx, let ⟨f', hf⟩ := axiom_of_choice this, f := λx:set α, (if h : x ∈ d then f' ⟨x, h⟩ else i : β) in have ∀(x : α) (i : set α), i ∈ d → x ∈ i → (∃ (i : β), i ∈ f '' d ∧ x ∈ c i), from assume x i hid hxi, ⟨f i, mem_image_of_mem f hid, by simpa only [f, dif_pos hid, (hf ⟨_, hid⟩).2] using hxi⟩, ⟨f '' d, assume i ⟨j, hj, h⟩, h ▸ by simpa only [f, dif_pos hj] using (hf ⟨_, hj⟩).1, finite_image f hd₂, subset.trans hd₃ $ by simpa only [subset_def, mem_sUnion, exists_imp_distrib, mem_Union, exists_prop, and_imp]⟩ section -- this proof times out without this local attribute [instance, priority 1000] classical.prop_decidable lemma compact_of_finite_subcover {s : set α} (h : ∀c, (∀t∈c, is_open t) → s ⊆ ⋃₀ c → ∃c'⊆c, finite c' ∧ s ⊆ ⋃₀ c') : compact s := assume f hfn hfs, classical.by_contradiction $ assume : ¬ (∃x∈s, f ⊓ 𝓝 x ≠ ⊥), have hf : ∀x∈s, 𝓝 x ⊓ f = ⊥, by simpa only [not_exists, not_not, inf_comm], have ¬ ∃x∈s, ∀t∈f.sets, x ∈ closure t, from assume ⟨x, hxs, hx⟩, have ∅ ∈ 𝓝 x ⊓ f, by rw [empty_in_sets_eq_bot, hf x hxs], let ⟨t₁, ht₁, t₂, ht₂, ht⟩ := by rw [mem_inf_sets] at this; exact this in have ∅ ∈ 𝓝 x ⊓ principal t₂, from (𝓝 x ⊓ principal t₂).sets_of_superset (inter_mem_inf_sets ht₁ (subset.refl t₂)) ht, have 𝓝 x ⊓ principal t₂ = ⊥, by rwa [empty_in_sets_eq_bot] at this, by simp only [closure_eq_nhds] at hx; exact hx t₂ ht₂ this, have ∀x∈s, ∃t∈f.sets, x ∉ closure t, by simpa only [not_exists, not_forall], let c := (λt, - closure t) '' f.sets, ⟨c', hcc', hcf, hsc'⟩ := h c (assume t ⟨s, hs, h⟩, h ▸ is_closed_closure) (by simpa only [subset_def, sUnion_image, mem_Union]) in let ⟨b, hb⟩ := axiom_of_choice $ show ∀s:c', ∃t, t ∈ f ∧ - closure t = s, from assume ⟨x, hx⟩, hcc' hx in have (⋂s∈c', if h : s ∈ c' then b ⟨s, h⟩ else univ) ∈ f, from Inter_mem_sets hcf $ assume t ht, by rw [dif_pos ht]; exact (hb ⟨t, ht⟩).left, have s ∩ (⋂s∈c', if h : s ∈ c' then b ⟨s, h⟩ else univ) ∈ f, from inter_mem_sets (le_principal_iff.1 hfs) this, have ∅ ∈ f, from mem_sets_of_superset this $ assume x ⟨hxs, hxi⟩, let ⟨t, htc', hxt⟩ := (show ∃t ∈ c', x ∈ t, from hsc' hxs) in have -closure (b ⟨t, htc'⟩) = t, from (hb _).right, have x ∈ - t, from this ▸ (calc x ∈ b ⟨t, htc'⟩ : by rw mem_bInter_iff at hxi; have h := hxi t htc'; rwa [dif_pos htc'] at h ... ⊆ closure (b ⟨t, htc'⟩) : subset_closure ... ⊆ - - closure (b ⟨t, htc'⟩) : by rw lattice.neg_neg; exact subset.refl _), show false, from this hxt, hfn $ by rwa [empty_in_sets_eq_bot] at this end lemma compact_iff_finite_subcover {s : set α} : compact s ↔ (∀c, (∀t∈c, is_open t) → s ⊆ ⋃₀ c → ∃c'⊆c, finite c' ∧ s ⊆ ⋃₀ c') := ⟨assume hc c, compact_elim_finite_subcover hc, compact_of_finite_subcover⟩ lemma compact_empty : compact (∅ : set α) := assume f hnf hsf, not.elim hnf $ empty_in_sets_eq_bot.1 $ le_principal_iff.1 hsf lemma compact_singleton {a : α} : compact ({a} : set α) := compact_of_finite_subcover $ assume c hc₁ hc₂, let ⟨i, hic, hai⟩ := (show ∃i ∈ c, a ∈ i, from mem_sUnion.1 $ singleton_subset_iff.1 hc₂) in ⟨{i}, singleton_subset_iff.2 hic, finite_singleton _, by rwa [sUnion_singleton, singleton_subset_iff]⟩ lemma compact_bUnion_of_compact {s : set β} {f : β → set α} (hs : finite s) : (∀i ∈ s, compact (f i)) → compact (⋃i ∈ s, f i) := assume hf, compact_of_finite_subcover $ assume c c_open c_cover, have ∀i : subtype s, ∃c' ⊆ c, finite c' ∧ f i ⊆ ⋃₀ c', from assume ⟨i, hi⟩, compact_elim_finite_subcover (hf i hi) c_open (calc f i ⊆ ⋃i ∈ s, f i : subset_bUnion_of_mem hi ... ⊆ ⋃₀ c : c_cover), let ⟨finite_subcovers, h⟩ := axiom_of_choice this in let c' := ⋃i, finite_subcovers i in have c' ⊆ c, from Union_subset (λi, (h i).fst), have finite c', from @finite_Union _ _ hs.fintype _ (λi, (h i).snd.1), have (⋃i ∈ s, f i) ⊆ ⋃₀ c', from bUnion_subset $ λi hi, calc f i ⊆ ⋃₀ finite_subcovers ⟨i,hi⟩ : (h ⟨i,hi⟩).snd.2 ... ⊆ ⋃₀ c' : sUnion_mono (subset_Union _ _), ⟨c', ‹c' ⊆ c›, ‹finite c'›, this⟩ lemma compact_Union_of_compact {f : β → set α} [fintype β] (h : ∀i, compact (f i)) : compact (⋃i, f i) := by rw ← bUnion_univ; exact compact_bUnion_of_compact finite_univ (λ i _, h i) lemma compact_of_finite {s : set α} (hs : finite s) : compact s := bUnion_of_singleton s ▸ compact_bUnion_of_compact hs (λ _ _, compact_singleton) lemma compact_union_of_compact {s t : set α} (hs : compact s) (ht : compact t) : compact (s ∪ t) := by rw union_eq_Union; exact compact_Union_of_compact (λ b, by cases b; assumption) section tube_lemma variables [topological_space β] def nhds_contain_boxes (s : set α) (t : set β) : Prop := ∀ (n : set (α × β)) (hn : is_open n) (hp : set.prod s t ⊆ n), ∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ set.prod u v ⊆ n lemma nhds_contain_boxes.symm {s : set α} {t : set β} : nhds_contain_boxes s t → nhds_contain_boxes t s := assume H n hn hp, let ⟨u, v, uo, vo, su, tv, p⟩ := H (prod.swap ⁻¹' n) (continuous_swap n hn) (by rwa [←image_subset_iff, prod.swap, image_swap_prod]) in ⟨v, u, vo, uo, tv, su, by rwa [←image_subset_iff, prod.swap, image_swap_prod] at p⟩ lemma nhds_contain_boxes.comm {s : set α} {t : set β} : nhds_contain_boxes s t ↔ nhds_contain_boxes t s := iff.intro nhds_contain_boxes.symm nhds_contain_boxes.symm lemma nhds_contain_boxes_of_singleton {x : α} {y : β} : nhds_contain_boxes ({x} : set α) ({y} : set β) := assume n hn hp, let ⟨u, v, uo, vo, xu, yv, hp'⟩ := is_open_prod_iff.mp hn x y (hp $ by simp) in ⟨u, v, uo, vo, by simpa, by simpa, hp'⟩ lemma nhds_contain_boxes_of_compact {s : set α} (hs : compact s) (t : set β) (H : ∀ x ∈ s, nhds_contain_boxes ({x} : set α) t) : nhds_contain_boxes s t := assume n hn hp, have ∀x : subtype s, ∃uv : set α × set β, is_open uv.1 ∧ is_open uv.2 ∧ {↑x} ⊆ uv.1 ∧ t ⊆ uv.2 ∧ set.prod uv.1 uv.2 ⊆ n, from assume ⟨x, hx⟩, have set.prod {x} t ⊆ n, from subset.trans (prod_mono (by simpa) (subset.refl _)) hp, let ⟨ux,vx,H1⟩ := H x hx n hn this in ⟨⟨ux,vx⟩,H1⟩, let ⟨uvs, h⟩ := classical.axiom_of_choice this in have us_cover : s ⊆ ⋃i, (uvs i).1, from assume x hx, set.subset_Union _ ⟨x,hx⟩ (by simpa using (h ⟨x,hx⟩).2.2.1), let ⟨s0, _, s0_fin, s0_cover⟩ := compact_elim_finite_subcover_image hs (λi _, (h i).1) $ by rw bUnion_univ; exact us_cover in let u := ⋃(i ∈ s0), (uvs i).1 in let v := ⋂(i ∈ s0), (uvs i).2 in have is_open u, from is_open_bUnion (λi _, (h i).1), have is_open v, from is_open_bInter s0_fin (λi _, (h i).2.1), have t ⊆ v, from subset_bInter (λi _, (h i).2.2.2.1), have set.prod u v ⊆ n, from assume ⟨x',y'⟩ ⟨hx',hy'⟩, have ∃i ∈ s0, x' ∈ (uvs i).1, by simpa using hx', let ⟨i,is0,hi⟩ := this in (h i).2.2.2.2 ⟨hi, (bInter_subset_of_mem is0 : v ⊆ (uvs i).2) hy'⟩, ⟨u, v, ‹is_open u›, ‹is_open v›, s0_cover, ‹t ⊆ v›, ‹set.prod u v ⊆ n›⟩ lemma generalized_tube_lemma {s : set α} (hs : compact s) {t : set β} (ht : compact t) {n : set (α × β)} (hn : is_open n) (hp : set.prod s t ⊆ n) : ∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ set.prod u v ⊆ n := have _, from nhds_contain_boxes_of_compact hs t $ assume x _, nhds_contain_boxes.symm $ nhds_contain_boxes_of_compact ht {x} $ assume y _, nhds_contain_boxes_of_singleton, this n hn hp end tube_lemma /-- Type class for compact spaces. Separation is sometimes included in the definition, especially in the French literature, but we do not include it here. -/ class compact_space (α : Type*) [topological_space α] : Prop := (compact_univ : compact (univ : set α)) lemma compact_univ [h : compact_space α] : compact (univ : set α) := h.compact_univ lemma compact_of_closed [compact_space α] {s : set α} (h : is_closed s) : compact s := compact_of_is_closed_subset compact_univ h (subset_univ _) variables [topological_space β] lemma compact_image {s : set α} {f : α → β} (hs : compact s) (hf : continuous f) : compact (f '' s) := compact_of_finite_subcover $ assume c hco hcs, have hdo : ∀t∈c, is_open (f ⁻¹' t), from assume t' ht, hf _ $ hco _ ht, have hds : s ⊆ ⋃i∈c, f ⁻¹' i, by simpa [subset_def, -mem_image] using hcs, let ⟨d', hcd', hfd', hd'⟩ := compact_elim_finite_subcover_image hs hdo hds in ⟨d', hcd', hfd', by simpa [subset_def, -mem_image, image_subset_iff] using hd'⟩ lemma compact_range [compact_space α] {f : α → β} (hf : continuous f) : compact (range f) := by rw ← image_univ; exact compact_image compact_univ hf lemma compact_iff_compact_image_of_embedding {s : set α} {f : α → β} (hf : embedding f) : compact s ↔ compact (f '' s) := iff.intro (assume h, compact_image h hf.continuous) $ assume h, begin rw compact_iff_ultrafilter_le_nhds at ⊢ h, intros u hu us', let u' : filter β := map f u, have : u' ≤ principal (f '' s), begin rw [map_le_iff_le_comap, comap_principal], convert us', exact preimage_image_eq _ hf.inj end, rcases h u' (ultrafilter_map hu) this with ⟨_, ⟨a, ha, ⟨⟩⟩, _⟩, refine ⟨a, ha, _⟩, rwa [hf.induced, nhds_induced, ←map_le_iff_le_comap] end lemma compact_iff_compact_in_subtype {p : α → Prop} {s : set {a // p a}} : compact s ↔ compact (subtype.val '' s) := compact_iff_compact_image_of_embedding embedding_subtype_val lemma compact_iff_compact_univ {s : set α} : compact s ↔ compact (univ : set (subtype s)) := by rw [compact_iff_compact_in_subtype, image_univ, subtype.val_range]; refl lemma compact_iff_compact_space {s : set α} : compact s ↔ compact_space s := compact_iff_compact_univ.trans ⟨λ h, ⟨h⟩, @compact_space.compact_univ _ _⟩ lemma compact_prod (s : set α) (t : set β) (ha : compact s) (hb : compact t) : compact (set.prod s t) := begin rw compact_iff_ultrafilter_le_nhds at ha hb ⊢, intros f hf hfs, rw le_principal_iff at hfs, rcases ha (map prod.fst f) (ultrafilter_map hf) (le_principal_iff.2 (mem_map_sets_iff.2 ⟨_, hfs, image_subset_iff.2 (λ s h, h.1)⟩)) with ⟨a, sa, ha⟩, rcases hb (map prod.snd f) (ultrafilter_map hf) (le_principal_iff.2 (mem_map_sets_iff.2 ⟨_, hfs, image_subset_iff.2 (λ s h, h.2)⟩)) with ⟨b, tb, hb⟩, rw map_le_iff_le_comap at ha hb, refine ⟨⟨a, b⟩, ⟨sa, tb⟩, _⟩, rw nhds_prod_eq, exact le_inf ha hb end instance [compact_space α] [compact_space β] : compact_space (α × β) := ⟨begin have A : compact (set.prod (univ : set α) (univ : set β)) := compact_prod univ univ compact_univ compact_univ, have : set.prod (univ : set α) (univ : set β) = (univ : set (α × β)) := by simp, rwa this at A, end⟩ instance [compact_space α] [compact_space β] : compact_space (α ⊕ β) := ⟨begin have A : compact (@sum.inl α β '' univ) := compact_image compact_univ continuous_inl, have B : compact (@sum.inr α β '' univ) := compact_image compact_univ continuous_inr, have C := compact_union_of_compact A B, have : (@sum.inl α β '' univ) ∪ (@sum.inr α β '' univ) = univ := by ext; cases x; simp, rwa this at C, end⟩ section tychonoff variables {ι : Type*} {π : ι → Type*} [∀i, topological_space (π i)] /-- Tychonoff's theorem -/ lemma compact_pi_infinite {s : Πi:ι, set (π i)} : (∀i, compact (s i)) → compact {x : Πi:ι, π i | ∀i, x i ∈ s i} := begin simp [compact_iff_ultrafilter_le_nhds, nhds_pi], exact assume h f hf hfs, let p : Πi:ι, filter (π i) := λi, map (λx:Πi:ι, π i, x i) f in have ∀i:ι, ∃a, a∈s i ∧ p i ≤ 𝓝 a, from assume i, h i (p i) (ultrafilter_map hf) $ show (λx:Πi:ι, π i, x i) ⁻¹' s i ∈ f.sets, from mem_sets_of_superset hfs $ assume x (hx : ∀i, x i ∈ s i), hx i, let ⟨a, ha⟩ := classical.axiom_of_choice this in ⟨a, assume i, (ha i).left, assume i, map_le_iff_le_comap.mp $ (ha i).right⟩ end instance pi.compact [∀i:ι, compact_space (π i)] : compact_space (Πi, π i) := ⟨begin have A : compact {x : Πi:ι, π i | ∀i, x i ∈ (univ : set (π i))} := compact_pi_infinite (λi, compact_univ), have : {x : Πi:ι, π i | ∀i, x i ∈ (univ : set (π i))} = univ := by ext; simp, rwa this at A, end⟩ end tychonoff instance quot.compact_space {r : α → α → Prop} [compact_space α] : compact_space (quot r) := ⟨begin have : quot.mk r '' univ = univ, by rw [image_univ, range_iff_surjective]; exact quot.exists_rep, rw ←this, exact compact_image compact_univ continuous_quot_mk end⟩ instance quotient.compact_space {s : setoid α} [compact_space α] : compact_space (quotient s) := quot.compact_space /-- There are various definitions of "locally compact space" in the literature, which agree for Hausdorff spaces but not in general. This one is the precise condition on X needed for the evaluation `map C(X, Y) × X → Y` to be continuous for all `Y` when `C(X, Y)` is given the compact-open topology. -/ class locally_compact_space (α : Type*) [topological_space α] : Prop := (local_compact_nhds : ∀ (x : α) (n ∈ 𝓝 x), ∃ s ∈ 𝓝 x, s ⊆ n ∧ compact s) end compact section clopen def is_clopen (s : set α) : Prop := is_open s ∧ is_closed s theorem is_clopen_union {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∪ t) := ⟨is_open_union hs.1 ht.1, is_closed_union hs.2 ht.2⟩ theorem is_clopen_inter {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∩ t) := ⟨is_open_inter hs.1 ht.1, is_closed_inter hs.2 ht.2⟩ @[simp] theorem is_clopen_empty : is_clopen (∅ : set α) := ⟨is_open_empty, is_closed_empty⟩ @[simp] theorem is_clopen_univ : is_clopen (univ : set α) := ⟨is_open_univ, is_closed_univ⟩ theorem is_clopen_compl {s : set α} (hs : is_clopen s) : is_clopen (-s) := ⟨hs.2, is_closed_compl_iff.2 hs.1⟩ @[simp] theorem is_clopen_compl_iff {s : set α} : is_clopen (-s) ↔ is_clopen s := ⟨λ h, compl_compl s ▸ is_clopen_compl h, is_clopen_compl⟩ theorem is_clopen_diff {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s-t) := is_clopen_inter hs (is_clopen_compl ht) end clopen section irreducible /-- A irreducible set is one where there is no non-trivial pair of disjoint opens. -/ def is_irreducible (s : set α) : Prop := ∀ (u v : set α), is_open u → is_open v → (∃ x, x ∈ s ∩ u) → (∃ x, x ∈ s ∩ v) → ∃ x, x ∈ s ∩ (u ∩ v) theorem is_irreducible_empty : is_irreducible (∅ : set α) := λ _ _ _ _ _ ⟨x, h1, h2⟩, h1.elim theorem is_irreducible_singleton {x} : is_irreducible ({x} : set α) := λ u v _ _ ⟨y, h1, h2⟩ ⟨z, h3, h4⟩, by rw mem_singleton_iff at h1 h3; substs y z; exact ⟨x, or.inl rfl, h2, h4⟩ theorem is_irreducible_closure {s : set α} (H : is_irreducible s) : is_irreducible (closure s) := λ u v hu hv ⟨y, hycs, hyu⟩ ⟨z, hzcs, hzv⟩, let ⟨p, hpu, hps⟩ := exists_mem_of_ne_empty (mem_closure_iff.1 hycs u hu hyu) in let ⟨q, hqv, hqs⟩ := exists_mem_of_ne_empty (mem_closure_iff.1 hzcs v hv hzv) in let ⟨r, hrs, hruv⟩ := H u v hu hv ⟨p, hps, hpu⟩ ⟨q, hqs, hqv⟩ in ⟨r, subset_closure hrs, hruv⟩ theorem exists_irreducible (s : set α) (H : is_irreducible s) : ∃ t : set α, is_irreducible t ∧ s ⊆ t ∧ ∀ u, is_irreducible u → t ⊆ u → u = t := let ⟨m, hm, hsm, hmm⟩ := zorn.zorn_subset₀ { t : set α | is_irreducible t } (λ c hc hcc hcn, let ⟨t, htc⟩ := exists_mem_of_ne_empty hcn in ⟨⋃₀ c, λ u v hu hv ⟨y, hy, hyu⟩ ⟨z, hz, hzv⟩, let ⟨p, hpc, hyp⟩ := mem_sUnion.1 hy, ⟨q, hqc, hzq⟩ := mem_sUnion.1 hz in or.cases_on (zorn.chain.total hcc hpc hqc) (assume hpq : p ⊆ q, let ⟨x, hxp, hxuv⟩ := hc hqc u v hu hv ⟨y, hpq hyp, hyu⟩ ⟨z, hzq, hzv⟩ in ⟨x, mem_sUnion_of_mem hxp hqc, hxuv⟩) (assume hqp : q ⊆ p, let ⟨x, hxp, hxuv⟩ := hc hpc u v hu hv ⟨y, hyp, hyu⟩ ⟨z, hqp hzq, hzv⟩ in ⟨x, mem_sUnion_of_mem hxp hpc, hxuv⟩), λ x hxc, set.subset_sUnion_of_mem hxc⟩) s H in ⟨m, hm, hsm, λ u hu hmu, hmm _ hu hmu⟩ def irreducible_component (x : α) : set α := classical.some (exists_irreducible {x} is_irreducible_singleton) theorem is_irreducible_irreducible_component {x : α} : is_irreducible (irreducible_component x) := (classical.some_spec (exists_irreducible {x} is_irreducible_singleton)).1 theorem mem_irreducible_component {x : α} : x ∈ irreducible_component x := singleton_subset_iff.1 (classical.some_spec (exists_irreducible {x} is_irreducible_singleton)).2.1 theorem eq_irreducible_component {x : α} : ∀ {s : set α}, is_irreducible s → irreducible_component x ⊆ s → s = irreducible_component x := (classical.some_spec (exists_irreducible {x} is_irreducible_singleton)).2.2 theorem is_closed_irreducible_component {x : α} : is_closed (irreducible_component x) := closure_eq_iff_is_closed.1 $ eq_irreducible_component (is_irreducible_closure is_irreducible_irreducible_component) subset_closure /-- A irreducible space is one where there is no non-trivial pair of disjoint opens. -/ class irreducible_space (α : Type u) [topological_space α] : Prop := (is_irreducible_univ : is_irreducible (univ : set α)) theorem irreducible_exists_mem_inter [irreducible_space α] {s t : set α} : is_open s → is_open t → (∃ x, x ∈ s) → (∃ x, x ∈ t) → ∃ x, x ∈ s ∩ t := by simpa only [univ_inter, univ_subset_iff] using @irreducible_space.is_irreducible_univ α _ _ s t end irreducible section connected /-- A connected set is one where there is no non-trivial open partition. -/ def is_connected (s : set α) : Prop := ∀ (u v : set α), is_open u → is_open v → s ⊆ u ∪ v → (∃ x, x ∈ s ∩ u) → (∃ x, x ∈ s ∩ v) → ∃ x, x ∈ s ∩ (u ∩ v) theorem is_connected_of_is_irreducible {s : set α} (H : is_irreducible s) : is_connected s := λ _ _ hu hv _, H _ _ hu hv theorem is_connected_empty : is_connected (∅ : set α) := is_connected_of_is_irreducible is_irreducible_empty theorem is_connected_singleton {x} : is_connected ({x} : set α) := is_connected_of_is_irreducible is_irreducible_singleton theorem is_connected_sUnion (x : α) (c : set (set α)) (H1 : ∀ s ∈ c, x ∈ s) (H2 : ∀ s ∈ c, is_connected s) : is_connected (⋃₀ c) := begin rintro u v hu hv hUcuv ⟨y, hyUc, hyu⟩ ⟨z, hzUc, hzv⟩, cases classical.em (c = ∅) with hc hc, { rw [hc, sUnion_empty] at hyUc, exact hyUc.elim }, cases ne_empty_iff_exists_mem.1 hc with s hs, cases hUcuv (mem_sUnion_of_mem (H1 s hs) hs) with hxu hxv, { rcases hzUc with ⟨t, htc, hzt⟩, specialize H2 t htc u v hu hv (subset.trans (subset_sUnion_of_mem htc) hUcuv), cases H2 ⟨x, H1 t htc, hxu⟩ ⟨z, hzt, hzv⟩ with r hr, exact ⟨r, mem_sUnion_of_mem hr.1 htc, hr.2⟩ }, { rcases hyUc with ⟨t, htc, hyt⟩, specialize H2 t htc u v hu hv (subset.trans (subset_sUnion_of_mem htc) hUcuv), cases H2 ⟨y, hyt, hyu⟩ ⟨x, H1 t htc, hxv⟩ with r hr, exact ⟨r, mem_sUnion_of_mem hr.1 htc, hr.2⟩ } end theorem is_connected_union (x : α) {s t : set α} (H1 : x ∈ s) (H2 : x ∈ t) (H3 : is_connected s) (H4 : is_connected t) : is_connected (s ∪ t) := have _ := is_connected_sUnion x {t,s} (by rintro r (rfl | rfl | h); [exact H1, exact H2, exact h.elim]) (by rintro r (rfl | rfl | h); [exact H3, exact H4, exact h.elim]), have h2 : ⋃₀ {t, s} = s ∪ t, from (sUnion_insert _ _).trans (by rw sUnion_singleton), by rwa h2 at this theorem is_connected_closure {s : set α} (H : is_connected s) : is_connected (closure s) := λ u v hu hv hcsuv ⟨y, hycs, hyu⟩ ⟨z, hzcs, hzv⟩, let ⟨p, hpu, hps⟩ := exists_mem_of_ne_empty (mem_closure_iff.1 hycs u hu hyu) in let ⟨q, hqv, hqs⟩ := exists_mem_of_ne_empty (mem_closure_iff.1 hzcs v hv hzv) in let ⟨r, hrs, hruv⟩ := H u v hu hv (subset.trans subset_closure hcsuv) ⟨p, hps, hpu⟩ ⟨q, hqs, hqv⟩ in ⟨r, subset_closure hrs, hruv⟩ def connected_component (x : α) : set α := ⋃₀ { s : set α | is_connected s ∧ x ∈ s } theorem is_connected_connected_component {x : α} : is_connected (connected_component x) := is_connected_sUnion x _ (λ _, and.right) (λ _, and.left) theorem mem_connected_component {x : α} : x ∈ connected_component x := mem_sUnion_of_mem (mem_singleton x) ⟨is_connected_singleton, mem_singleton x⟩ theorem subset_connected_component {x : α} {s : set α} (H1 : is_connected s) (H2 : x ∈ s) : s ⊆ connected_component x := λ z hz, mem_sUnion_of_mem hz ⟨H1, H2⟩ theorem is_closed_connected_component {x : α} : is_closed (connected_component x) := closure_eq_iff_is_closed.1 $ subset.antisymm (subset_connected_component (is_connected_closure is_connected_connected_component) (subset_closure mem_connected_component)) subset_closure theorem irreducible_component_subset_connected_component {x : α} : irreducible_component x ⊆ connected_component x := subset_connected_component (is_connected_of_is_irreducible is_irreducible_irreducible_component) mem_irreducible_component /-- A connected space is one where there is no non-trivial open partition. -/ class connected_space (α : Type u) [topological_space α] : Prop := (is_connected_univ : is_connected (univ : set α)) instance irreducible_space.connected_space (α : Type u) [topological_space α] [irreducible_space α] : connected_space α := ⟨is_connected_of_is_irreducible $ irreducible_space.is_irreducible_univ α⟩ theorem exists_mem_inter [connected_space α] {s t : set α} : is_open s → is_open t → s ∪ t = univ → (∃ x, x ∈ s) → (∃ x, x ∈ t) → ∃ x, x ∈ s ∩ t := by simpa only [univ_inter, univ_subset_iff] using @connected_space.is_connected_univ α _ _ s t theorem is_clopen_iff [connected_space α] {s : set α} : is_clopen s ↔ s = ∅ ∨ s = univ := ⟨λ hs, classical.by_contradiction $ λ h, have h1 : s ≠ ∅ ∧ -s ≠ ∅, from ⟨mt or.inl h, mt (λ h2, or.inr $ (by rw [← compl_compl s, h2, compl_empty] : s = univ)) h⟩, let ⟨_, h2, h3⟩ := exists_mem_inter hs.1 hs.2 (union_compl_self s) (ne_empty_iff_exists_mem.1 h1.1) (ne_empty_iff_exists_mem.1 h1.2) in h3 h2, by rintro (rfl | rfl); [exact is_clopen_empty, exact is_clopen_univ]⟩ end connected section totally_disconnected def is_totally_disconnected (s : set α) : Prop := ∀ t, t ⊆ s → is_connected t → subsingleton t theorem is_totally_disconnected_empty : is_totally_disconnected (∅ : set α) := λ t ht _, ⟨λ ⟨_, h⟩, (ht h).elim⟩ theorem is_totally_disconnected_singleton {x} : is_totally_disconnected ({x} : set α) := λ t ht _, ⟨λ ⟨p, hp⟩ ⟨q, hq⟩, subtype.eq $ show p = q, from (eq_of_mem_singleton (ht hp)).symm ▸ (eq_of_mem_singleton (ht hq)).symm⟩ class totally_disconnected_space (α : Type u) [topological_space α] : Prop := (is_totally_disconnected_univ : is_totally_disconnected (univ : set α)) end totally_disconnected section totally_separated def is_totally_separated (s : set α) : Prop := ∀ x ∈ s, ∀ y ∈ s, x ≠ y → ∃ u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ s ⊆ u ∪ v ∧ u ∩ v = ∅ theorem is_totally_separated_empty : is_totally_separated (∅ : set α) := λ x, false.elim theorem is_totally_separated_singleton {x} : is_totally_separated ({x} : set α) := λ p hp q hq hpq, (hpq $ (eq_of_mem_singleton hp).symm ▸ (eq_of_mem_singleton hq).symm).elim theorem is_totally_disconnected_of_is_totally_separated {s : set α} (H : is_totally_separated s) : is_totally_disconnected s := λ t hts ht, ⟨λ ⟨x, hxt⟩ ⟨y, hyt⟩, subtype.eq $ classical.by_contradiction $ assume hxy : x ≠ y, let ⟨u, v, hu, hv, hxu, hyv, hsuv, huv⟩ := H x (hts hxt) y (hts hyt) hxy in let ⟨r, hrt, hruv⟩ := ht u v hu hv (subset.trans hts hsuv) ⟨x, hxt, hxu⟩ ⟨y, hyt, hyv⟩ in ((ext_iff _ _).1 huv r).1 hruv⟩ class totally_separated_space (α : Type u) [topological_space α] : Prop := (is_totally_separated_univ : is_totally_separated (univ : set α)) instance totally_separated_space.totally_disconnected_space (α : Type u) [topological_space α] [totally_separated_space α] : totally_disconnected_space α := ⟨is_totally_disconnected_of_is_totally_separated $ totally_separated_space.is_totally_separated_univ α⟩ end totally_separated
83a2f0b257976c63ad78ece519fd5bd42e823e25
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/multiset/sections.lean
6f873a4ca2f404582c04cdcfd80c7d3814d61a3f
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
2,340
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import data.multiset.bind /-! # Sections of a multiset > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ namespace multiset variables {α : Type*} section sections /-- The sections of a multiset of multisets `s` consists of all those multisets which can be put in bijection with `s`, so each element is an member of the corresponding multiset. -/ def sections (s : multiset (multiset α)) : multiset (multiset α) := multiset.rec_on s {0} (λs _ c, s.bind $ λa, c.map (multiset.cons a)) (assume a₀ a₁ s pi, by simp [map_bind, bind_bind a₀ a₁, cons_swap]) @[simp] lemma sections_zero : sections (0 : multiset (multiset α)) = {0} := rfl @[simp] lemma sections_cons (s : multiset (multiset α)) (m : multiset α) : sections (m ::ₘ s) = m.bind (λa, (sections s).map (multiset.cons a)) := rec_on_cons m s lemma coe_sections : ∀(l : list (list α)), sections ((l.map (λl:list α, (l : multiset α))) : multiset (multiset α)) = ((l.sections.map (λl:list α, (l : multiset α))) : multiset (multiset α)) | [] := rfl | (a :: l) := begin simp, rw [← cons_coe, sections_cons, bind_map_comm, coe_sections l], simp [list.sections, (∘), list.bind] end @[simp] lemma sections_add (s t : multiset (multiset α)) : sections (s + t) = (sections s).bind (λm, (sections t).map ((+) m)) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, bind_assoc, map_bind, bind_map, -add_comm]) lemma mem_sections {s : multiset (multiset α)} : ∀{a}, a ∈ sections s ↔ s.rel (λs a, a ∈ s) a := multiset.induction_on s (by simp) (assume a s ih a', by simp [ih, rel_cons_left, -exists_and_distrib_left, exists_and_distrib_left.symm, eq_comm]) lemma card_sections {s : multiset (multiset α)} : card (sections s) = prod (s.map card) := multiset.induction_on s (by simp) (by simp {contextual := tt}) lemma prod_map_sum [comm_semiring α] {s : multiset (multiset α)} : prod (s.map sum) = sum ((sections s).map prod) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, map_bind, sum_map_mul_left, sum_map_mul_right]) end sections end multiset
66b64875fce8e604557dfcea21579ba8f8638992
5acd49ee775f675999521ca7f8c05b3a6ac4dde5
/tutorial world/l1_refl.lean
64a5ace80feba1987c025a69086d271f08cb6330
[]
no_license
mothematician/lean-tutorial-imperial
0284556885a69ab0aa2cb1a5699276eb5fc04b1e
1e68a6341616450c7f5d3e2b35a56fc95bdfced4
refs/heads/main
1,691,400,920,101
1,633,792,591,000
1,633,792,591,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
166
lean
namespace Nat theorem example1 (x y z : Nat) : x * y + z = x * y + z := rfl theorem example2 (x y : Nat) (h : y = x + 7) : 2 * y = 2 * (x + 7) := rw end Nat
21c175468b88c94c5cf4c07ed739ddf4e57f36cb
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/logic/unnamed_669.lean
dbfa6ead8352f435b7c439789ee28e38d12e45d5
[]
no_license
jamescheuk91/mathematics_in_lean
09f1f87d2b0dce53464ff0cbe592c568ff59cf5e
4452499264e2975bca2f42565c0925506ba5dda3
refs/heads/master
1,679,716,410,967
1,613,957,947,000
1,613,957,947,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
653
lean
import data.real.basic def fn_ub (f : ℝ → ℝ) (a : ℝ) : Prop := ∀ x, f x ≤ a def fn_lb (f : ℝ → ℝ) (a : ℝ) : Prop := ∀ x, a ≤ f x def fn_has_ub (f : ℝ → ℝ) := ∃ a, fn_ub f a def fn_has_lb (f : ℝ → ℝ) := ∃ a, fn_lb f a theorem fn_ub_add {f g : ℝ → ℝ} {a b : ℝ} (hfa : fn_ub f a) (hgb : fn_ub g b) : fn_ub (λ x, f x + g x) (a + b) := λ x, add_le_add (hfa x) (hgb x) variables {f g : ℝ → ℝ} -- BEGIN example (ubf : fn_has_ub f) (ubg : fn_has_ub g) : fn_has_ub (λ x, f x + g x) := begin cases ubf with a ubfa, cases ubg with b ubfb, use a + b, apply fn_ub_add ubfa ubfb end -- END
1c909f30a20488dd407c8c069952c852e02c6f3f
92b50235facfbc08dfe7f334827d47281471333b
/library/data/stream.lean
40d07827eec3138e9d65db5705bae872d0250a80
[ "Apache-2.0" ]
permissive
htzh/lean
24f6ed7510ab637379ec31af406d12584d31792c
d70c79f4e30aafecdfc4a60b5d3512199200ab6e
refs/heads/master
1,607,677,731,270
1,437,089,952,000
1,437,089,952,000
37,078,816
0
0
null
1,433,780,956,000
1,433,780,955,000
null
UTF-8
Lean
false
false
22,505
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ import data.nat data.list data.equiv open nat function option definition stream (A : Type) := nat → A namespace stream variables {A B C : Type} definition cons (a : A) (s : stream A) : stream A := λ i, match i with | 0 := a | succ n := s n end notation h :: t := cons h t definition head [reducible] (s : stream A) : A := s 0 definition tail (s : stream A) : stream A := λ i, s (i+1) definition drop (n : nat) (s : stream A) : stream A := λ i, s (i+n) definition nth [reducible] (n : nat) (s : stream A) : A := s n protected theorem eta (s : stream A) : head s :: tail s = s := funext (λ i, begin cases i, repeat reflexivity end) theorem nth_zero_cons (a : A) (s : stream A) : nth 0 (a :: s) = a := rfl theorem head_cons (a : A) (s : stream A) : head (a :: s) = a := rfl theorem tail_cons (a : A) (s : stream A) : tail (a :: s) = s := rfl theorem tail_drop (n : nat) (s : stream A) : tail (drop n s) = drop n (tail s) := funext (λ i, begin esimp [tail, drop], congruence, rewrite add.right_comm end) theorem nth_drop (n m : nat) (s : stream A) : nth n (drop m s) = nth (n+m) s := rfl theorem tail_eq_drop (s : stream A) : tail s = drop 1 s := rfl theorem drop_drop (n m : nat) (s : stream A) : drop n (drop m s) = drop (n+m) s := funext (λ i, begin esimp [drop], rewrite add.assoc end) theorem nth_succ (n : nat) (s : stream A) : nth (succ n) s = nth n (tail s) := rfl theorem drop_succ (n : nat) (s : stream A) : drop (succ n) s = drop n (tail s) := rfl protected theorem ext {s₁ s₂ : stream A} : (∀ n, nth n s₁ = nth n s₂) → s₁ = s₂ := assume h, funext h definition all (p : A → Prop) (s : stream A) := ∀ n, p (nth n s) definition any (p : A → Prop) (s : stream A) := ∃ n, p (nth n s) theorem all_def (p : A → Prop) (s : stream A) : all p s = ∀ n, p (nth n s) := rfl theorem any_def (p : A → Prop) (s : stream A) : any p s = ∃ n, p (nth n s) := rfl definition mem (a : A) (s : stream A) := any (λ b, a = b) s notation e ∈ s := mem e s theorem mem_cons (a : A) (s : stream A) : a ∈ (a::s) := exists.intro 0 rfl theorem mem_cons_of_mem {a : A} {s : stream A} (b : A) : a ∈ s → a ∈ b :: s := assume ains, obtain n (h : a = nth n s), from ains, exists.intro (succ n) (by rewrite [nth_succ, tail_cons, h]) theorem eq_or_mem_of_mem_cons {a b : A} {s : stream A} : a ∈ b::s → a = b ∨ a ∈ s := assume ainbs, obtain n (h : a = nth n (b::s)), from ainbs, begin cases n with n', {left, exact h}, {right, rewrite [nth_succ at h, tail_cons at h], existsi n', exact h} end theorem mem_of_nth_eq {n : nat} {s : stream A} {a : A} : a = nth n s → a ∈ s := assume h, exists.intro n h section map variable (f : A → B) definition map (s : stream A) : stream B := λ n, f (nth n s) theorem drop_map (n : nat) (s : stream A) : drop n (map f s) = map f (drop n s) := stream.ext (λ i, rfl) theorem nth_map (n : nat) (s : stream A) : nth n (map f s) = f (nth n s) := rfl theorem tail_map (s : stream A) : tail (map f s) = map f (tail s) := begin rewrite tail_eq_drop end theorem head_map (s : stream A) : head (map f s) = f (head s) := rfl theorem map_eq (s : stream A) : map f s = f (head s) :: map f (tail s) := by rewrite [-stream.eta, tail_map, head_map] theorem map_cons (a : A) (s : stream A) : map f (a :: s) = f a :: map f s := by rewrite [-stream.eta, map_eq] theorem map_id (s : stream A) : map id s = s := rfl theorem map_map (g : B → C) (f : A → B) (s : stream A) : map g (map f s) = map (g ∘ f) s := rfl theorem mem_map {a : A} {s : stream A} : a ∈ s → f a ∈ map f s := assume ains, obtain n (h : a = nth n s), from ains, exists.intro n (by rewrite [nth_map, h]) end map section zip variable (f : A → B → C) definition zip (s₁ : stream A) (s₂ : stream B) : stream C := λ n, f (nth n s₁) (nth n s₂) theorem drop_zip (n : nat) (s₁ : stream A) (s₂ : stream B) : drop n (zip f s₁ s₂) = zip f (drop n s₁) (drop n s₂) := stream.ext (λ i, rfl) theorem nth_zip (n : nat) (s₁ : stream A) (s₂ : stream B) : nth n (zip f s₁ s₂) = f (nth n s₁) (nth n s₂) := rfl theorem head_zip (s₁ : stream A) (s₂ : stream B) : head (zip f s₁ s₂) = f (head s₁) (head s₂) := rfl theorem tail_zip (s₁ : stream A) (s₂ : stream B) : tail (zip f s₁ s₂) = zip f (tail s₁) (tail s₂) := rfl theorem zip_eq (s₁ : stream A) (s₂ : stream B) : zip f s₁ s₂ = f (head s₁) (head s₂) :: zip f (tail s₁) (tail s₂) := by rewrite [-stream.eta] end zip definition const (a : A) : stream A := λ n, a theorem mem_const (a : A) : a ∈ const a := exists.intro 0 rfl theorem const_eq (a : A) : const a = a :: const a := begin apply stream.ext, intro n, cases n, repeat reflexivity end theorem tail_const (a : A) : tail (const a) = const a := by rewrite [const_eq at {1}] theorem map_const (f : A → B) (a : A) : map f (const a) = const (f a) := rfl theorem nth_const (n : nat) (a : A) : nth n (const a) = a := rfl theorem drop_const (n : nat) (a : A) : drop n (const a) = const a := stream.ext (λ i, rfl) definition iterate (f : A → A) (a : A) : stream A := λ n, nat.rec_on n a (λ n r, f r) theorem head_iterate (f : A → A) (a : A) : head (iterate f a) = a := rfl theorem tail_iterate (f : A → A) (a : A) : tail (iterate f a) = iterate f (f a) := begin apply funext, intro n, induction n with n' IH, {reflexivity}, {esimp [tail, iterate] at *, rewrite add_one at *, esimp at *, rewrite IH} end theorem iterate_eq (f : A → A) (a : A) : iterate f a = a :: iterate f (f a) := begin rewrite [-stream.eta], congruence, exact !tail_iterate end theorem nth_zero_iterate (f : A → A) (a : A) : nth 0 (iterate f a) = a := rfl theorem nth_succ_iterate (n : nat) (f : A → A) (a : A) : nth (succ n) (iterate f a) = nth n (iterate f (f a)) := by rewrite [nth_succ, tail_iterate] section bisim variable (R : stream A → stream A → Prop) local infix ~ := R definition is_bisimulation := ∀ ⦃s₁ s₂⦄, s₁ ~ s₂ → head s₁ = head s₂ ∧ tail s₁ ~ tail s₂ lemma nth_of_bisim (bisim : is_bisimulation R) : ∀ {s₁ s₂} n, s₁ ~ s₂ → nth n s₁ = nth n s₂ ∧ drop (n+1) s₁ ~ drop (n+1) s₂ | s₁ s₂ 0 h := bisim h | s₁ s₂ (n+1) h := obtain h₁ (trel : tail s₁ ~ tail s₂), from bisim h, nth_of_bisim n trel -- If two streams are bisimilar, then they are equal theorem eq_of_bisim (bisim : is_bisimulation R) : ∀ {s₁ s₂}, s₁ ~ s₂ → s₁ = s₂ := λ s₁ s₂ r, stream.ext (λ n, and.elim_left (nth_of_bisim R bisim n r)) end bisim theorem bisim_simple (s₁ s₂ : stream A) : head s₁ = head s₂ → s₁ = tail s₁ → s₂ = tail s₂ → s₁ = s₂ := assume hh ht₁ ht₂, eq_of_bisim (λ s₁ s₂, head s₁ = head s₂ ∧ s₁ = tail s₁ ∧ s₂ = tail s₂) (λ s₁ s₂ h, obtain h₁ h₂ h₃, from h, begin constructor, exact h₁, rewrite [-h₂, -h₃], exact h end) (and.intro hh (and.intro ht₁ ht₂)) -- AKA coinduction freeze theorem coinduction.{l} {A : Type.{l}} {s₁ s₂ : stream A} : head s₁ = head s₂ → (∀ (B : Type.{l}) (fr : stream A → B), fr s₁ = fr s₂ → fr (tail s₁) = fr (tail s₂)) → s₁ = s₂ := assume hh ht, eq_of_bisim (λ s₁ s₂, head s₁ = head s₂ ∧ ∀ (B : Type) (fr : stream A → B), fr s₁ = fr s₂ → fr (tail s₁) = fr (tail s₂)) (λ s₁ s₂ h, have h₁ : head s₁ = head s₂, from and.elim_left h, have h₂ : head (tail s₁) = head (tail s₂), from and.elim_right h A (@head A) h₁, have h₃ : ∀ (B : Type) (fr : stream A → B), fr (tail s₁) = fr (tail s₂) → fr (tail (tail s₁)) = fr (tail (tail s₂)), from λ B fr, and.elim_right h B (λ s, fr (tail s)), and.intro h₁ (and.intro h₂ h₃)) (and.intro hh ht) theorem iterate_id (a : A) : iterate id a = const a := coinduction rfl (λ B fr ch, by rewrite [tail_iterate, tail_const]; exact ch) local attribute stream [reducible] theorem map_iterate (f : A → A) (a : A) : iterate f (f a) = map f (iterate f a) := begin apply funext, intro n, induction n with n' IH, {reflexivity}, { esimp [map, iterate, nth] at *, rewrite IH } end section corec definition corec (f : A → B) (g : A → A) : A → stream B := λ a, map f (iterate g a) theorem corec_def (f : A → B) (g : A → A) (a : A) : corec f g a = map f (iterate g a) := rfl theorem corec_eq (f : A → B) (g : A → A) (a : A) : corec f g a = f a :: corec f g (g a) := by rewrite [corec_def, map_eq, head_iterate, tail_iterate] theorem corec_id_id_eq_const (a : A) : corec id id a = const a := by rewrite [corec_def, map_id, iterate_id] theorem corec_id_f_eq_iterate (f : A → A) (a : A) : corec id f a = iterate f a := rfl end corec -- corec is also known as unfold definition unfolds (g : A → B) (f : A → A) (a : A) : stream B := corec g f a theorem unfolds_eq (g : A → B) (f : A → A) (a : A) : unfolds g f a = g a :: unfolds g f (f a) := by esimp [ unfolds ]; rewrite [corec_eq] theorem nth_unfolds_head_tail : ∀ (n : nat) (s : stream A), nth n (unfolds head tail s) = nth n s := begin intro n, induction n with n' ih, {intro s, reflexivity}, {intro s, rewrite [*nth_succ, unfolds_eq, tail_cons, ih]} end theorem unfolds_head_eq : ∀ (s : stream A), unfolds head tail s = s := λ s, stream.ext (λ n, nth_unfolds_head_tail n s) definition interleave (s₁ s₂ : stream A) : stream A := corec (λ p, obtain s₁ s₂, from p, head s₁) (λ p, obtain s₁ s₂, from p, (s₂, tail s₁)) (s₁, s₂) infix `⋈`:65 := interleave theorem interleave_eq (s₁ s₂ : stream A) : s₁ ⋈ s₂ = head s₁ :: head s₂ :: (tail s₁ ⋈ tail s₂) := begin esimp [interleave], rewrite corec_eq, esimp, congruence, rewrite corec_eq end theorem tail_interleave (s₁ s₂ : stream A) : tail (s₁ ⋈ s₂) = s₂ ⋈ (tail s₁) := by esimp [interleave]; rewrite corec_eq theorem interleave_tail_tail (s₁ s₂ : stream A) : tail s₁ ⋈ tail s₂ = tail (tail (s₁ ⋈ s₂)) := by rewrite [interleave_eq s₁ s₂] theorem nth_interleave_left : ∀ (n : nat) (s₁ s₂ : stream A), nth (2*n) (s₁ ⋈ s₂) = nth n s₁ | 0 s₁ s₂ := rfl | (succ n) s₁ s₂ := begin change nth (succ (succ (2*n))) (s₁ ⋈ s₂) = nth (succ n) s₁, rewrite [*nth_succ, interleave_eq, *tail_cons, nth_interleave_left] end theorem nth_interleave_right : ∀ (n : nat) (s₁ s₂ : stream A), nth (2*n+1) (s₁ ⋈ s₂) = nth n s₂ | 0 s₁ s₂ := rfl | (succ n) s₁ s₂ := begin change nth (succ (succ (2*n+1))) (s₁ ⋈ s₂) = nth (succ n) s₂, rewrite [*nth_succ, interleave_eq, *tail_cons, nth_interleave_right] end theorem mem_interleave_left {a : A} {s₁ : stream A} (s₂ : stream A) : a ∈ s₁ → a ∈ s₁ ⋈ s₂ := assume ains₁, obtain n h, from ains₁, exists.intro (2*n) (by rewrite [h, nth_interleave_left]) theorem mem_interleave_right {a : A} {s₁ : stream A} (s₂ : stream A) : a ∈ s₂ → a ∈ s₁ ⋈ s₂ := assume ains₂, obtain n h, from ains₂, exists.intro (2*n+1) (by rewrite [h, nth_interleave_right]) definition even (s : stream A) : stream A := corec (λ s, head s) (λ s, tail (tail s)) s definition odd (s : stream A) : stream A := even (tail s) theorem odd_eq (s : stream A) : odd s = even (tail s) := rfl theorem head_even (s : stream A) : head (even s) = head s := rfl theorem tail_even (s : stream A) : tail (even s) = even (tail (tail s)) := by esimp [even]; rewrite corec_eq theorem even_cons_cons (a₁ a₂ : A) (s : stream A) : even (a₁ :: a₂ :: s) = a₁ :: even s := by esimp [even]; rewrite corec_eq theorem even_tail (s : stream A) : even (tail s) = odd s := rfl theorem even_interleave (s₁ s₂ : stream A) : even (s₁ ⋈ s₂) = s₁ := eq_of_bisim (λ s₁' s₁, ∃ s₂, s₁' = even (s₁ ⋈ s₂)) (λ s₁' s₁ h, obtain s₂ (h₁ : s₁' = even (s₁ ⋈ s₂)), from h, begin rewrite h₁, constructor, {reflexivity}, {existsi (tail s₂), rewrite [interleave_eq, even_cons_cons, tail_cons]} end) (exists.intro s₂ rfl) theorem interleave_even_odd (s₁ : stream A) : even s₁ ⋈ odd s₁ = s₁ := eq_of_bisim (λ s' s, s' = even s ⋈ odd s) (λ s' s (h : s' = even s ⋈ odd s), begin rewrite h, constructor, {reflexivity}, {esimp, rewrite [*odd_eq, tail_interleave, tail_even]} end) rfl theorem nth_even : ∀ (n : nat) (s : stream A), nth n (even s) = nth (2*n) s | 0 s := rfl | (succ n) s := begin change nth (succ n) (even s) = nth (succ (succ (2 * n))) s, rewrite [+nth_succ, tail_even, nth_even] end theorem nth_odd : ∀ (n : nat) (s : stream A), nth n (odd s) = nth (2*n + 1) s := λ n s, by rewrite [odd_eq, nth_even] theorem mem_of_mem_even (a : A) (s : stream A) : a ∈ even s → a ∈ s := assume aines, obtain n h, from aines, exists.intro (2*n) (by rewrite [h, nth_even]) theorem mem_of_mem_odd (a : A) (s : stream A) : a ∈ odd s → a ∈ s := assume ainos, obtain n h, from ainos, exists.intro (2*n+1) (by rewrite [h, nth_odd]) open list definition append : list A → stream A → stream A | [] s := s | (a::l) s := a :: append l s theorem nil_append (s : stream A) : append [] s = s := rfl theorem cons_append (a : A) (l : list A) (s : stream A) : append (a::l) s = a :: append l s := rfl infix ++ := append -- the following local notation is used just to make the following theorem clear local infix `++ₛ`:65 := append theorem append_append : ∀ (l₁ l₂ : list A) (s : stream A), (l₁ ++ l₂) ++ₛ s = l₁ ++ (l₂ ++ₛ s) | [] l₂ s := rfl | (a::l₁) l₂ s := by rewrite [list.append_cons, *cons_append, append_append] theorem map_append (f : A → B) : ∀ (l : list A) (s : stream A), map f (l ++ s) = list.map f l ++ map f s | [] s := rfl | (a::l) s := by rewrite [cons_append, list.map_cons, map_cons, cons_append, map_append] theorem drop_append : ∀ (l : list A) (s : stream A), drop (length l) (l ++ s) = s | [] s := by esimp | (a::l) s := by rewrite [length_cons, add_one, drop_succ, cons_append, tail_cons, drop_append] theorem append_head_tail (s : stream A) : [head s] ++ tail s = s := by rewrite [cons_append, nil_append, stream.eta] theorem mem_append_right : ∀ {a : A} (l : list A) {s : stream A}, a ∈ s → a ∈ l ++ s | a [] s h := h | a (b::l) s h := have ih : a ∈ l ++ s, from mem_append_right l h, !mem_cons_of_mem ih theorem mem_append_left : ∀ {a : A} {l : list A} (s : stream A), a ∈ l → a ∈ l ++ s | a [] s h := absurd h !not_mem_nil | a (b::l) s h := or.elim (list.eq_or_mem_of_mem_cons h) (λ (aeqb : a = b), exists.intro 0 aeqb) (λ (ainl : a ∈ l), mem_cons_of_mem b (mem_append_left s ainl)) definition approx : nat → stream A → list A | 0 s := [] | (n+1) s := head s :: approx n (tail s) theorem approx_zero (s : stream A) : approx 0 s = [] := rfl theorem approx_succ (n : nat) (s : stream A) : approx (succ n) s = head s :: approx n (tail s) := rfl theorem nth_approx : ∀ (n : nat) (s : stream A), list.nth (approx (succ n) s) n = some (nth n s) | 0 s := rfl | (n+1) s := begin rewrite [approx_succ, add_one, list.nth_succ, nth_approx] end theorem append_approx_drop : ∀ (n : nat) (s : stream A), append (approx n s) (drop n s) = s := begin intro n, induction n with n' ih, {intro s, reflexivity}, {intro s, rewrite [approx_succ, drop_succ, cons_append, ih (tail s), stream.eta]} end -- Take lemma reduces a proof of equality of infinite streams to an -- induction over all their finite approximations. theorem take_lemma (s₁ s₂ : stream A) : (∀ (n : nat), approx n s₁ = approx n s₂) → s₁ = s₂ := begin intro h, apply stream.ext, intro n, induction n with n ih, {injection (h 1), assumption}, {have h₁ : some (nth (succ n) s₁) = some (nth (succ n) s₂), by rewrite [-*nth_approx, h (succ (succ n))], injection h₁, assumption} end -- auxiliary definition for cycle corecursive definition private definition cycle_f : A × list A × A × list A → A | (v, _, _, _) := v -- auxiliary definition for cycle corecursive definition private definition cycle_g : A × list A × A × list A → A × list A × A × list A | (v₁, [], v₀, l₀) := (v₀, l₀, v₀, l₀) | (v₁, v₂::l₂, v₀, l₀) := (v₂, l₂, v₀, l₀) private lemma cycle_g_cons (a : A) (a₁ : A) (l₁ : list A) (a₀ : A) (l₀ : list A) : cycle_g (a, a₁::l₁, a₀, l₀) = (a₁, l₁, a₀, l₀) := rfl definition cycle : Π (l : list A), l ≠ nil → stream A | [] h := absurd rfl h | (a::l) h := corec cycle_f cycle_g (a, l, a, l) theorem cycle_eq : ∀ (l : list A) (h : l ≠ nil), cycle l h = l ++ cycle l h | [] h := absurd rfl h | (a::l) h := have gen : ∀ l' a', corec cycle_f cycle_g (a', l', a, l) = (a' :: l') ++ₛ corec cycle_f cycle_g (a, l, a, l), begin intro l', induction l' with a₁ l₁ ih, {intro a', rewrite [corec_eq]}, {intro a', rewrite [corec_eq, cycle_g_cons, ih a₁]} end, gen l a theorem mem_cycle {a : A} {l : list A} : ∀ (h : l ≠ []), a ∈ l → a ∈ cycle l h := assume h ainl, by rewrite [cycle_eq]; exact !mem_append_left ainl theorem cycle_singleton (a : A) (h : [a] ≠ nil) : cycle [a] h = const a := coinduction rfl (λ B fr ch, by rewrite [cycle_eq, const_eq]; exact ch) definition tails (s : stream A) : stream (stream A) := corec id tail (tail s) theorem tails_eq (s : stream A) : tails s = tail s :: tails (tail s) := by esimp [tails]; rewrite [corec_eq] theorem nth_tails : ∀ (n : nat) (s : stream A), nth n (tails s) = drop n (tail s) := begin intro n, induction n with n' ih, {intros, reflexivity}, {intro s, rewrite [nth_succ, drop_succ, tails_eq, tail_cons, ih]} end theorem tails_eq_iterate (s : stream A) : tails s = iterate tail (tail s) := rfl definition inits_core (l : list A) (s : stream A) : stream (list A) := corec prod.pr1 (λ p, match p with (l', s') := (l' ++ [head s'], tail s') end) (l, s) definition inits (s : stream A) : stream (list A) := inits_core [head s] (tail s) theorem inits_core_eq (l : list A) (s : stream A) : inits_core l s = l :: inits_core (l ++ [head s]) (tail s) := by esimp [inits_core]; rewrite [corec_eq] theorem tail_inits (s : stream A) : tail (inits s) = inits_core [head s, head (tail s)] (tail (tail s)) := by esimp [inits]; rewrite inits_core_eq theorem inits_tail (s : stream A) : inits (tail s) = inits_core [head (tail s)] (tail (tail s)) := rfl theorem cons_nth_inits_core : ∀ (a : A) (n : nat) (l : list A) (s : stream A), a :: nth n (inits_core l s) = nth n (inits_core (a::l) s) := begin intro a n, induction n with n' ih, {intros, reflexivity}, {intro l s, rewrite [*nth_succ, inits_core_eq, +tail_cons, ih, inits_core_eq (a::l) s] } end theorem nth_inits : ∀ (n : nat) (s : stream A), nth n (inits s) = approx (succ n) s := begin intro n, induction n with n' ih, {intros, reflexivity}, {intros, rewrite [nth_succ, approx_succ, -ih, tail_inits, inits_tail, cons_nth_inits_core]} end theorem inits_eq (s : stream A) : inits s = [head s] :: map (list.cons (head s)) (inits (tail s)) := begin apply stream.ext, intro n, cases n, {reflexivity}, {rewrite [nth_inits, nth_succ, tail_cons, nth_map, nth_inits]} end theorem zip_inits_tails (s : stream A) : zip append (inits s) (tails s) = const s := begin apply stream.ext, intro n, rewrite [nth_zip, nth_inits, nth_tails, nth_const, approx_succ, cons_append, append_approx_drop, stream.eta] end definition pure (a : A) : stream A := const a definition apply (f : stream (A → B)) (s : stream A) : stream B := λ n, (nth n f) (nth n s) infix `⊛`:75 := apply -- input as \o* theorem identity (s : stream A) : pure id ⊛ s = s := rfl theorem composition (g : stream (B → C)) (f : stream (A → B)) (s : stream A) : pure compose ⊛ g ⊛ f ⊛ s = g ⊛ (f ⊛ s) := rfl theorem homomorphism (f : A → B) (a : A) : pure f ⊛ pure a = pure (f a) := rfl theorem interchange (fs : stream (A → B)) (a : A) : fs ⊛ pure a = pure (λ f, f a) ⊛ fs := rfl theorem map_eq_apply (f : A → B) (s : stream A) : map f s = pure f ⊛ s := rfl definition nats : stream nat := λ n, n theorem nth_nats (n : nat) : nth n nats = n := rfl theorem nats_eq : nats = 0 :: map succ nats := begin apply stream.ext, intro n, cases n, reflexivity, rewrite [nth_succ] end section open equiv lemma stream_equiv_of_equiv {A B : Type} : A ≃ B → stream A ≃ stream B | (mk f g l r) := mk (map f) (map g) begin intros, rewrite [map_map, id_of_left_inverse l, map_id] end begin intros, rewrite [map_map, id_of_righ_inverse r, map_id] end end definition lex (lt : A → A → Prop) (s₁ s₂ : stream A) : Prop := ∃ i, lt (nth i s₁) (nth i s₂) ∧ ∀ j, j < i → nth j s₁ = nth j s₂ definition lex.trans {s₁ s₂ s₃} {lt : A → A → Prop} : transitive lt → lex lt s₁ s₂ → lex lt s₂ s₃ → lex lt s₁ s₃ := assume htrans h₁ h₂, obtain i₁ hlt₁ he₁, from h₁, obtain i₂ hlt₂ he₂, from h₂, lt.by_cases (λ i₁lti₂ : i₁ < i₂, assert aux : nth i₁ s₂ = nth i₁ s₃, from he₂ _ i₁lti₂, begin existsi i₁, split, {rewrite -aux, exact hlt₁}, {intro j jlti₁, transitivity nth j s₂, exact !he₁ jlti₁, exact !he₂ (lt.trans jlti₁ i₁lti₂)} end) (λ i₁eqi₂ : i₁ = i₂, begin subst i₂, existsi i₁, split, exact htrans hlt₁ hlt₂, intro j jlti₁, transitivity nth j s₂, exact !he₁ jlti₁; exact !he₂ jlti₁ end) (λ i₂lti₁ : i₂ < i₁, assert aux : nth i₂ s₁ = nth i₂ s₂, from he₁ _ i₂lti₁, begin existsi i₂, split, {rewrite aux, exact hlt₂}, {intro j jlti₂, transitivity nth j s₂, exact !he₁ (lt.trans jlti₂ i₂lti₁), exact !he₂ jlti₂} end) end stream
79299e7d3e028a2e298883bf14fb894f3984db32
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/sheaves/presheaf_of_functions_auto.lean
3f08e5dda4da1608ad8ea53eaa6006f812b3063a
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
6,932
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.yoneda import Mathlib.topology.sheaves.presheaf import Mathlib.topology.category.TopCommRing import Mathlib.topology.algebra.continuous_functions import Mathlib.PostPort universes v u_1 u namespace Mathlib /-! # Presheaves of functions We construct some simple examples of presheaves of functions on a topological space. * `presheaf_to_Type X f`, where `f : X → Type`, is the presheaf of dependently-typed (not-necessarily continuous) functions * `presheaf_to_Type X T`, where `T : Type`, is the presheaf of (not-necessarily-continuous) functions to a fixed target type `T` * `presheaf_to_Top X T`, where `T : Top`, is the presheaf of continuous functions into a topological space `T` * `presheaf_To_TopCommRing X R`, where `R : TopCommRing` is the presheaf valued in `CommRing` of functions functions into a topological ring `R` * as an example of the previous construction, `presheaf_to_TopCommRing X (TopCommRing.of ℂ)` is the presheaf of rings of continuous complex-valued functions on `X`. -/ namespace Top /-- The presheaf of dependently typed functions on `X`, with fibres given by a type family `f`. There is no requirement that the functions are continuous, here. -/ def presheaf_to_Types (X : Top) (T : ↥X → Type v) : presheaf (Type v) X := category_theory.functor.mk (fun (U : topological_space.opens ↥Xᵒᵖ) => (x : ↥(opposite.unop U)) → T ↑x) fun (U V : topological_space.opens ↥Xᵒᵖ) (i : U ⟶ V) (g : (x : ↥(opposite.unop U)) → T ↑x) (x : ↥(opposite.unop V)) => g (coe_fn (category_theory.has_hom.hom.unop i) x) @[simp] theorem presheaf_to_Types_obj (X : Top) {T : ↥X → Type v} {U : topological_space.opens ↥Xᵒᵖ} : category_theory.functor.obj (presheaf_to_Types X T) U = ((x : ↥(opposite.unop U)) → T ↑x) := rfl @[simp] theorem presheaf_to_Types_map (X : Top) {T : ↥X → Type v} {U : topological_space.opens ↥Xᵒᵖ} {V : topological_space.opens ↥Xᵒᵖ} {i : U ⟶ V} {f : category_theory.functor.obj (presheaf_to_Types X T) U} : category_theory.functor.map (presheaf_to_Types X T) i f = fun (x : ↥(opposite.unop V)) => f (coe_fn (category_theory.has_hom.hom.unop i) x) := rfl /-- The presheaf of functions on `X` with values in a type `T`. There is no requirement that the functions are continuous, here. -/ -- We don't just define this in terms of `presheaf_to_Types`, -- as it's helpful later to see (at a syntactic level) that `(presheaf_to_Type X T).obj U` -- is a non-dependent function. -- We don't use `@[simps]` to generate the projection lemmas here, -- as it turns out to be useful to have `presheaf_to_Type_map` -- written as an equality of functions (rather than being applied to some argument). def presheaf_to_Type (X : Top) (T : Type v) : presheaf (Type v) X := category_theory.functor.mk (fun (U : topological_space.opens ↥Xᵒᵖ) => ↥(opposite.unop U) → T) fun (U V : topological_space.opens ↥Xᵒᵖ) (i : U ⟶ V) (g : ↥(opposite.unop U) → T) => g ∘ ⇑(category_theory.has_hom.hom.unop i) @[simp] theorem presheaf_to_Type_obj (X : Top) {T : Type v} {U : topological_space.opens ↥Xᵒᵖ} : category_theory.functor.obj (presheaf_to_Type X T) U = (↥(opposite.unop U) → T) := rfl @[simp] theorem presheaf_to_Type_map (X : Top) {T : Type v} {U : topological_space.opens ↥Xᵒᵖ} {V : topological_space.opens ↥Xᵒᵖ} {i : U ⟶ V} {f : category_theory.functor.obj (presheaf_to_Type X T) U} : category_theory.functor.map (presheaf_to_Type X T) i f = f ∘ ⇑(category_theory.has_hom.hom.unop i) := rfl /-- The presheaf of continuous functions on `X` with values in fixed target topological space `T`. -/ def presheaf_to_Top (X : Top) (T : Top) : presheaf (Type v) X := category_theory.functor.op (topological_space.opens.to_Top X) ⋙ category_theory.functor.obj category_theory.yoneda T @[simp] theorem presheaf_to_Top_obj (X : Top) (T : Top) (U : topological_space.opens ↥Xᵒᵖ) : category_theory.functor.obj (presheaf_to_Top X T) U = (category_theory.functor.obj (topological_space.opens.to_Top X) (opposite.unop U) ⟶ T) := rfl /-- The (bundled) commutative ring of continuous functions from a topological space to a topological commutative ring, with pointwise multiplication. -/ -- TODO upgrade the result to TopCommRing? def continuous_functions (X : Topᵒᵖ) (R : TopCommRing) : CommRing := CommRing.of (opposite.unop X ⟶ category_theory.functor.obj (category_theory.forget₂ TopCommRing Top) R) namespace continuous_functions /-- Pulling back functions into a topological ring along a continuous map is a ring homomorphism. -/ def pullback {X : Topᵒᵖ} {Y : Topᵒᵖ} (f : X ⟶ Y) (R : TopCommRing) : continuous_functions X R ⟶ continuous_functions Y R := ring_hom.mk (fun (g : ↥(continuous_functions X R)) => category_theory.has_hom.hom.unop f ≫ g) sorry sorry sorry sorry /-- A homomorphism of topological rings can be postcomposed with functions from a source space `X`; this is a ring homomorphism (with respect to the pointwise ring operations on functions). -/ def map (X : Topᵒᵖ) {R : TopCommRing} {S : TopCommRing} (φ : R ⟶ S) : continuous_functions X R ⟶ continuous_functions X S := ring_hom.mk (fun (g : ↥(continuous_functions X R)) => g ≫ category_theory.functor.map (category_theory.forget₂ TopCommRing Top) φ) sorry sorry sorry sorry end continuous_functions /-- An upgraded version of the Yoneda embedding, observing that the continuous maps from `X : Top` to `R : TopCommRing` form a commutative ring, functorial in both `X` and `R`. -/ def CommRing_yoneda : TopCommRing ⥤ Topᵒᵖ ⥤ CommRing := category_theory.functor.mk (fun (R : TopCommRing) => category_theory.functor.mk (fun (X : Topᵒᵖ) => continuous_functions X R) fun (X Y : Topᵒᵖ) (f : X ⟶ Y) => continuous_functions.pullback f R) fun (R S : TopCommRing) (φ : R ⟶ S) => category_theory.nat_trans.mk fun (X : Topᵒᵖ) => continuous_functions.map X φ /-- The presheaf (of commutative rings), consisting of functions on an open set `U ⊆ X` with values in some topological commutative ring `T`. For example, we could construct the presheaf of continuous complex valued functions of `X` as ``` presheaf_to_TopCommRing X (TopCommRing.of ℂ) ``` (this requires `import topology.instances.complex`). -/ def presheaf_to_TopCommRing (X : Top) (T : TopCommRing) : presheaf CommRing X := category_theory.functor.op (topological_space.opens.to_Top X) ⋙ category_theory.functor.obj CommRing_yoneda T end Mathlib
ad6b426b682f4ab1058afa9ae07b57aa24261b60
88fb7558b0636ec6b181f2a548ac11ad3919f8a5
/library/init/meta/tactic.lean
6e4bfd9fc62a87fe3913f4ffd6b3072e3efe4455
[ "Apache-2.0" ]
permissive
moritayasuaki/lean
9f666c323cb6fa1f31ac597d777914aed41e3b7a
ae96ebf6ee953088c235ff7ae0e8c95066ba8001
refs/heads/master
1,611,135,440,814
1,493,852,869,000
1,493,852,869,000
90,269,903
0
0
null
1,493,906,291,000
1,493,906,291,000
null
UTF-8
Lean
false
false
39,949
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.function init.data.option.basic init.util import init.category.combinators init.category.monad init.category.alternative init.category.monad_fail import init.data.nat.div init.meta.exceptional init.meta.format init.meta.environment import init.meta.pexpr init.data.to_string init.data.string.basic init.meta.interaction_monad meta constant tactic_state : Type universes u v namespace tactic_state meta constant env : tactic_state → environment meta constant to_format : tactic_state → format /- Format expression with respect to the main goal in the tactic state. If the tactic state does not contain any goals, then format expression using an empty local context. -/ meta constant format_expr : tactic_state → expr → format meta constant get_options : tactic_state → options meta constant set_options : tactic_state → options → tactic_state end tactic_state meta instance : has_to_format tactic_state := ⟨tactic_state.to_format⟩ meta instance : has_to_string tactic_state := ⟨λ s, (to_fmt s).to_string s.get_options⟩ @[reducible] meta def tactic := interaction_monad tactic_state @[reducible] meta def tactic_result := interaction_monad.result tactic_state namespace tactic export interaction_monad (hiding failed fail) meta def failed {α : Type} : tactic α := interaction_monad.failed meta def fail {α : Type u} {β : Type v} [has_to_format β] (msg : β) : tactic α := interaction_monad.fail msg end tactic namespace tactic_result export interaction_monad.result end tactic_result open tactic open tactic_result infixl ` >>=[tactic] `:2 := interaction_monad_bind infixl ` >>[tactic] `:2 := interaction_monad_seq meta instance : alternative tactic := { interaction_monad.monad with failure := @interaction_monad.failed _, orelse := @interaction_monad_orelse _ } meta def {u₁ u₂} tactic.up {α : Type u₂} (t : tactic α) : tactic (ulift.{u₁} α) := λ s, match t s with | success a s' := success (ulift.up a) s' | exception t ref s := exception t ref s end meta def {u₁ u₂} tactic.down {α : Type u₂} (t : tactic (ulift.{u₁} α)) : tactic α := λ s, match t s with | success (ulift.up a) s' := success a s' | exception t ref s := exception t ref s end namespace tactic variables {α : Type u} meta def try_core (t : tactic α) : tactic (option α) := λ s, result.cases_on (t s) (λ a, success (some a)) (λ e ref s', success none s) meta def skip : tactic unit := success () meta def try (t : tactic α) : tactic unit := try_core t >>[tactic] skip meta def fail_if_success {α : Type u} (t : tactic α) : tactic unit := λ s, result.cases_on (t s) (λ a s, mk_exception "fail_if_success combinator failed, given tactic succeeded" none s) (λ e ref s', success () s) open nat /- (repeat_at_most n t): repeat the given tactic at most n times or until t fails -/ meta def repeat_at_most : nat → tactic unit → tactic unit | 0 t := skip | (succ n) t := (do t, repeat_at_most n t) <|> skip /- (repeat_exactly n t) : execute t n times -/ meta def repeat_exactly : nat → tactic unit → tactic unit | 0 t := skip | (succ n) t := do t, repeat_exactly n t meta def repeat : tactic unit → tactic unit := repeat_at_most 100000 meta def returnopt (e : option α) : tactic α := λ s, match e with | (some a) := success a s | none := mk_exception "failed" none s end meta instance opt_to_tac : has_coe (option α) (tactic α) := ⟨returnopt⟩ /- Decorate t's exceptions with msg -/ meta def decorate_ex (msg : format) (t : tactic α) : tactic α := λ s, result.cases_on (t s) success (λ opt_thunk, match opt_thunk with | some e := exception (some (λ u, msg ++ format.nest 2 (format.line ++ e u))) | none := exception none end) @[inline] meta def write (s' : tactic_state) : tactic unit := λ s, success () s' @[inline] meta def read : tactic tactic_state := λ s, success s s meta def get_options : tactic options := do s ← read, return s.get_options meta def set_options (o : options) : tactic unit := do s ← read, write (s.set_options o) meta def save_options {α : Type} (t : tactic α) : tactic α := do o ← get_options, a ← t, set_options o, return a meta def returnex {α : Type} (e : exceptional α) : tactic α := λ s, match e with | exceptional.success a := success a s | exceptional.exception ._ f := match get_options s with | success opt _ := exception (some (λ u, f opt)) none s | exception _ _ _ := exception (some (λ u, f options.mk)) none s end end meta instance ex_to_tac {α : Type} : has_coe (exceptional α) (tactic α) := ⟨returnex⟩ end tactic meta def tactic_format_expr (e : expr) : tactic format := do s ← tactic.read, return (tactic_state.format_expr s e) meta class has_to_tactic_format (α : Type u) := (to_tactic_format : α → tactic format) meta instance : has_to_tactic_format expr := ⟨tactic_format_expr⟩ meta def tactic.pp {α : Type u} [has_to_tactic_format α] : α → tactic format := has_to_tactic_format.to_tactic_format open tactic format meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (list α) := ⟨has_map.map to_fmt ∘ monad.mapm pp⟩ meta instance (α : Type u) (β : Type v) [has_to_tactic_format α] [has_to_tactic_format β] : has_to_tactic_format (α × β) := ⟨λ ⟨a, b⟩, to_fmt <$> (prod.mk <$> pp a <*> pp b)⟩ meta def option_to_tactic_format {α : Type u} [has_to_tactic_format α] : option α → tactic format | (some a) := do fa ← pp a, return (to_fmt "(some " ++ fa ++ ")") | none := return "none" meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (option α) := ⟨option_to_tactic_format⟩ @[priority 10] meta instance has_to_format_to_has_to_tactic_format (α : Type) [has_to_format α] : has_to_tactic_format α := ⟨(λ x, return x) ∘ to_fmt⟩ namespace tactic open tactic_state meta def get_env : tactic environment := do s ← read, return $ env s meta def get_decl (n : name) : tactic declaration := do s ← read, (env s).get n meta def trace {α : Type u} [has_to_tactic_format α] (a : α) : tactic unit := do fmt ← pp a, return $ _root_.trace_fmt fmt (λ u, ()) meta def trace_call_stack : tactic unit := take state, _root_.trace_call_stack (success () state) meta def timetac {α : Type u} (desc : string) (t : tactic α) : tactic α := λ s, timeit desc (t s) meta def trace_state : tactic unit := do s ← read, trace $ to_fmt s inductive transparency | all | semireducible | instances | reducible | none export transparency (reducible semireducible) /- (eval_expr α e) evaluates 'e' IF 'e' has type 'α'. -/ meta constant eval_expr (α : Type u) [reflected α] : expr → tactic α /- Return the partial term/proof constructed so far. Note that the resultant expression may contain variables that are not declarate in the current main goal. -/ meta constant result : tactic expr /- Display the partial term/proof constructed so far. This tactic is *not* equivalent to do { r ← result, s ← read, return (format_expr s r) } because this one will format the result with respect to the current goal, and trace_result will do it with respect to the initial goal. -/ meta constant format_result : tactic format /- Return target type of the main goal. Fail if tactic_state does not have any goal left. -/ meta constant target : tactic expr meta constant intro_core : name → tactic expr meta constant intron : nat → tactic unit /- Clear the given local constant. The tactic fails if the given expression is not a local constant. -/ meta constant clear : expr → tactic unit meta constant revert_lst : list expr → tactic nat /-- Return `e` in weak head normal form with respect to the given transparency setting. -/ meta constant whnf (e : expr) (md := semireducible) : tactic expr /- (head) eta expand the given expression -/ meta constant head_eta_expand : expr → tactic expr /- (head) beta reduction -/ meta constant head_beta : expr → tactic expr /- (head) zeta reduction -/ meta constant head_zeta : expr → tactic expr /- zeta reduction -/ meta constant zeta : expr → tactic expr /- (head) eta reduction -/ meta constant head_eta : expr → tactic expr /-- Succeeds if `t` and `s` can be unified using the given transparency setting. -/ meta constant unify (t s : expr) (md := semireducible) : tactic unit /- Similar to `unify`, but it treats metavariables as constants. -/ meta constant is_def_eq (t s : expr) (md := semireducible) : tactic unit /- Infer the type of the given expression. Remark: transparency does not affect type inference -/ meta constant infer_type : expr → tactic expr meta constant get_local : name → tactic expr /- Resolve a name using the current local context, environment, aliases, etc. -/ meta constant resolve_name : name → tactic pexpr /- Return the hypothesis in the main goal. Fail if tactic_state does not have any goal left. -/ meta constant local_context : tactic (list expr) meta constant get_unused_name : name → option nat → tactic name /-- Helper tactic for creating simple applications where some arguments are inferred using type inference. Example, given ``` rel.{l_1 l_2} : Pi (α : Type.{l_1}) (β : α -> Type.{l_2}), (Pi x : α, β x) -> (Pi x : α, β x) -> , Prop nat : Type real : Type vec.{l} : Pi (α : Type l) (n : nat), Type.{l1} f g : Pi (n : nat), vec real n ``` then ``` mk_app_core semireducible "rel" [f, g] ``` returns the application ``` rel.{1 2} nat (fun n : nat, vec real n) f g ``` The unification constraints due to type inference are solved using the transparency `md`. -/ meta constant mk_app (fn : name) (args : list expr) (md := semireducible) : tactic expr /-- Similar to `mk_app`, but allows to specify which arguments are explicit/implicit. Example, given `(a b : nat)` then ``` mk_mapp "ite" [some (a > b), none, none, some a, some b] ``` returns the application ``` @ite.{1} (a > b) (nat.decidable_gt a b) nat a b ``` -/ meta constant mk_mapp (fn : name) (args : list (option expr)) (md := semireducible) : tactic expr /-- (mk_congr_arg h₁ h₂) is a more efficient version of (mk_app `congr_arg [h₁, h₂]) -/ meta constant mk_congr_arg : expr → expr → tactic expr /-- (mk_congr_fun h₁ h₂) is a more efficient version of (mk_app `congr_fun [h₁, h₂]) -/ meta constant mk_congr_fun : expr → expr → tactic expr /-- (mk_congr h₁ h₂) is a more efficient version of (mk_app `congr [h₁, h₂]) -/ meta constant mk_congr : expr → expr → tactic expr /-- (mk_eq_refl h) is a more efficient version of (mk_app `eq.refl [h]) -/ meta constant mk_eq_refl : expr → tactic expr /-- (mk_eq_symm h) is a more efficient version of (mk_app `eq.symm [h]) -/ meta constant mk_eq_symm : expr → tactic expr /-- (mk_eq_trans h₁ h₂) is a more efficient version of (mk_app `eq.trans [h₁, h₂]) -/ meta constant mk_eq_trans : expr → expr → tactic expr /-- (mk_eq_mp h₁ h₂) is a more efficient version of (mk_app `eq.mp [h₁, h₂]) -/ meta constant mk_eq_mp : expr → expr → tactic expr /-- (mk_eq_mpr h₁ h₂) is a more efficient version of (mk_app `eq.mpr [h₁, h₂]) -/ meta constant mk_eq_mpr : expr → expr → tactic expr /- Given a local constant t, if t has type (lhs = rhs) apply susbstitution. Otherwise, try to find a local constant that has type of the form (t = t') or (t' = t). The tactic fails if the given expression is not a local constant. -/ meta constant subst : expr → tactic unit /-- Close the current goal using `e`. Fail is the type of `e` is not definitionally equal to the target type. -/ meta constant exact (e : expr) (md := semireducible) : tactic unit /-- Elaborate the given quoted expression with respect to the current main goal. If `allow_mvars` is tt, then metavariables are tolerated and become new goals. If `report_errors` is ff, then errors are reported using position information from q. -/ meta constant to_expr (q : pexpr) (allow_mvars := tt) : tactic expr /- Return true if the given expression is a type class. -/ meta constant is_class : expr → tactic bool /- Try to create an instance of the given type class. -/ meta constant mk_instance : expr → tactic expr /- Change the target of the main goal. The input expression must be definitionally equal to the current target. -/ meta constant change : expr → tactic unit /- (assert_core H T), adds a new goal for T, and change target to (T -> target). -/ meta constant assert_core : name → expr → tactic unit /- (assertv_core H T P), change target to (T -> target) if P has type T. -/ meta constant assertv_core : name → expr → expr → tactic unit /- (define_core H T), adds a new goal for T, and change target to (let H : T := ?M in target) in the current goal. -/ meta constant define_core : name → expr → tactic unit /- (definev_core H T P), change target to (Let H : T := P in target) if P has type T. -/ meta constant definev_core : name → expr → expr → tactic unit /- rotate goals to the left -/ meta constant rotate_left : nat → tactic unit meta constant get_goals : tactic (list expr) meta constant set_goals : list expr → tactic unit /-- Configuration options for the `apply` tactic. -/ structure apply_cfg := (md := semireducible) (approx := tt) (all := ff) (use_instances := tt) /-- Apply the expression `e` to the main goal, the unification is performed using the transparency mode in `cfg`. If cfg.approx is `tt`, then fallback to first-order unification, and approximate context during unification. If cfg.all is `tt`, then all unassigned meta-variables are added as new goals. If cfg.use_instances is `tt`, then use type class resolution to instantiate unassigned meta-variables. It returns a list of all introduced meta variables, even the assigned ones. -/ meta constant apply_core (e : expr) (cfg : apply_cfg := {}) : tactic (list expr) /- Create a fresh meta universe variable. -/ meta constant mk_meta_univ : tactic level /- Create a fresh meta-variable with the given type. The scope of the new meta-variable is the local context of the main goal. -/ meta constant mk_meta_var : expr → tactic expr /- Return the value assigned to the given universe meta-variable. Fail if argument is not an universe meta-variable or if it is not assigned. -/ meta constant get_univ_assignment : level → tactic level /- Return the value assigned to the given meta-variable. Fail if argument is not a meta-variable or if it is not assigned. -/ meta constant get_assignment : expr → tactic expr meta constant mk_fresh_name : tactic name /- Return a hash code for expr that ignores inst_implicit arguments, and proofs. -/ meta constant abstract_hash : expr → tactic nat /- Return the "weight" of the given expr while ignoring inst_implicit arguments, and proofs. -/ meta constant abstract_weight : expr → tactic nat meta constant abstract_eq : expr → expr → tactic bool /- Induction on `h` using recursor `rec`, names for the new hypotheses are retrieved from `ns`. If `ns` does not have sufficient names, then use the internal binder names in the recursor. It returns for each new goal a list of new hypotheses and a list of substitutions for hypotheses depending on `h`. The substitutions map internal names to their replacement terms. If the replacement is again a hypothesis the user name stays the same. The internal names are only valid in the original goal, not in the type context of the new goal. If `rec` is none, then the type of `h` is inferred, if it is of the form `C ...`, tactic uses `C.rec` -/ meta constant induction (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic (list (list expr × list (name × expr))) /- Apply `cases_on` recursor, names for the new hypotheses are retrieved from `ns`. `h` must be a local constant. It returns for each new goal the name of the constructor, a list of new hypotheses, and a list of substitutions for hypotheses depending on `h`. The number of new goals may be smaller than the number of constructors. Some goals may be discarded when the indices to not match. See `induction` for information on the list of substitutions. The `cases` tactic is implemented using this one, and it relaxes the restriction of `h`. -/ meta constant cases_core (h : expr) (ns : list name := []) (md := semireducible) : tactic (list (name × list expr × list (name × expr))) /- Similar to cases tactic, but does not revert/intro/clear hypotheses. -/ meta constant destruct (e : expr) (md := semireducible) : tactic unit /- Generalizes the target with respect to `e`. -/ meta constant generalize (e : expr) (n : name := `_x) (md := semireducible) : tactic unit /- instantiate assigned metavariables in the given expression -/ meta constant instantiate_mvars : expr → tactic expr /- Add the given declaration to the environment -/ meta constant add_decl : declaration → tactic unit /- (doc_string env d k) return the doc string for d (if available) -/ meta constant doc_string : name → tactic string meta constant add_doc_string : name → string → tactic unit /-- Create an auxiliary definition with name `c` where `type` and `value` may contain local constants and meta-variables. This function collects all dependencies (universe parameters, universe metavariables, local constants (aka hypotheses) and metavariables). It updates the environment in the tactic_state, and returns an expression of the form (c.{l_1 ... l_n} a_1 ... a_m) where l_i's and a_j's are the collected dependencies. -/ meta constant add_aux_decl (c : name) (type : expr) (val : expr) (is_lemma : bool) : tactic expr meta constant module_doc_strings : tactic (list (option name × string)) /- Set attribute `attr_name` for constant `c_name` with the given priority. If the priority is none, then use default -/ meta constant set_basic_attribute (attr_name : name) (c_name : name) (persistent := ff) (prio : option nat := none) : tactic unit /- (unset_attribute attr_name c_name) -/ meta constant unset_attribute : name → name → tactic unit /- (has_attribute attr_name c_name) succeeds if the declaration `decl_name` has the attribute `attr_name`. The result is the priority. -/ meta constant has_attribute : name → name → tactic nat /- (copy_attribute attr_name c_name d_name) copy attribute `attr_name` from `src` to `tgt` if it is defined for `src` -/ meta def copy_attribute (attr_name : name) (src : name) (p : bool) (tgt : name) : tactic unit := try $ do prio ← has_attribute attr_name src, set_basic_attribute attr_name tgt p (some prio) /-- Name of the declaration currently being elaborated. -/ meta constant decl_name : tactic name /- (save_type_info e ref) save (typeof e) at position associated with ref -/ meta constant save_type_info : expr → expr → tactic unit meta constant save_info_thunk : pos → (unit → format) → tactic unit /-- Return list of currently open namespaces -/ meta constant open_namespaces : tactic (list name) /-- Return tt iff `t` "occurs" in `e`. The occurrence checking is performed using keyed matching with the given transparency setting. We say `t` occurs in `e` by keyed matching iff there is a subterm `s` s.t. `t` and `s` have the same head, and `is_def_eq t s md` The main idea is to minimize the number of `is_def_eq` checks performed. -/ meta constant kdepends_on (e t : expr) (md := reducible) : tactic bool open list nat meta def induction' (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic unit := induction h ns rec md >> return () /-- Remark: set_goals will erase any solved goal -/ meta def cleanup : tactic unit := get_goals >>= set_goals /- Auxiliary definition used to implement begin ... end blocks -/ meta def step {α : Type u} (t : tactic α) : tactic unit := t >>[tactic] cleanup meta def istep {α : Type u} (line col : ℕ) (t : tactic α) : tactic unit := λ s, (@scope_trace _ line col (step t s)).clamp_pos line col meta def is_prop (e : expr) : tactic bool := do t ← infer_type e, return (t = ```(Prop)) /-- Return true iff n is the name of declaration that is a proposition. -/ meta def is_prop_decl (n : name) : tactic bool := do env ← get_env, d ← env.get n, t ← return $ d.type, is_prop t meta def is_proof (e : expr) : tactic bool := infer_type e >>= is_prop meta def whnf_no_delta (e : expr) : tactic expr := whnf e transparency.none meta def whnf_target : tactic unit := target >>= whnf >>= change meta def intro (n : name) : tactic expr := do t ← target, if expr.is_pi t ∨ expr.is_let t then intro_core n else whnf_target >> intro_core n meta def intro1 : tactic expr := intro `_ meta def intros : tactic (list expr) := do t ← target, match t with | expr.pi _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs) | expr.elet _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs) | _ := return [] end meta def intro_lst : list name → tactic (list expr) | [] := return [] | (n::ns) := do H ← intro n, Hs ← intro_lst ns, return (H :: Hs) /-- Returns n fully qualified if it refers to a constant, or else fails. -/ meta def resolve_constant (n : name) : tactic name := do (expr.const n _) ← pexpr.to_raw_expr <$> resolve_name n, pure n meta def to_expr_strict (q : pexpr) : tactic expr := to_expr q meta def revert (l : expr) : tactic nat := revert_lst [l] meta def clear_lst : list name → tactic unit | [] := skip | (n::ns) := do H ← get_local n, clear H, clear_lst ns meta def match_not (e : expr) : tactic expr := match (expr.is_not e) with | (some a) := return a | none := fail "expression is not a negation" end meta def match_and (e : expr) : tactic (expr × expr) := match (expr.is_and e) with | (some (α, β)) := return (α, β) | none := fail "expression is not a conjunction" end meta def match_or (e : expr) : tactic (expr × expr) := match (expr.is_or e) with | (some (α, β)) := return (α, β) | none := fail "expression is not a disjunction" end meta def match_eq (e : expr) : tactic (expr × expr) := match (expr.is_eq e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not an equality" end meta def match_ne (e : expr) : tactic (expr × expr) := match (expr.is_ne e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not a disequality" end meta def match_heq (e : expr) : tactic (expr × expr × expr × expr) := do match (expr.is_heq e) with | (some (α, lhs, β, rhs)) := return (α, lhs, β, rhs) | none := fail "expression is not a heterogeneous equality" end meta def match_refl_app (e : expr) : tactic (name × expr × expr) := do env ← get_env, match (environment.is_refl_app env e) with | (some (R, lhs, rhs)) := return (R, lhs, rhs) | none := fail "expression is not an application of a reflexive relation" end meta def match_app_of (e : expr) (n : name) : tactic (list expr) := guard (expr.is_app_of e n) >> return e.get_app_args meta def get_local_type (n : name) : tactic expr := get_local n >>= infer_type meta def trace_result : tactic unit := format_result >>= trace meta def rexact (e : expr) : tactic unit := exact e reducible /- (find_same_type t es) tries to find in es an expression with type definitionally equal to t -/ meta def find_same_type : expr → list expr → tactic expr | e [] := failed | e (H :: Hs) := do t ← infer_type H, (unify e t >> return H) <|> find_same_type e Hs meta def find_assumption (e : expr) : tactic expr := do ctx ← local_context, find_same_type e ctx meta def assumption : tactic unit := do { ctx ← local_context, t ← target, H ← find_same_type t ctx, exact H } <|> fail "assumption tactic failed" meta def save_info (p : pos) : tactic unit := do s ← read, tactic.save_info_thunk p (λ _, tactic_state.to_format s) notation `‹` p `›` := show p, by assumption /- Swap first two goals, do nothing if tactic state does not have at least two goals. -/ meta def swap : tactic unit := do gs ← get_goals, match gs with | (g₁ :: g₂ :: rs) := set_goals (g₂ :: g₁ :: rs) | e := skip end /- (assert h t), adds a new goal for t, and the hypothesis (h : t) in the current goal. -/ meta def assert (h : name) (t : expr) : tactic unit := assert_core h t >> swap >> intro h >> swap /- (assertv h t v), adds the hypothesis (h : t) in the current goal if v has type t. -/ meta def assertv (h : name) (t : expr) (v : expr) : tactic unit := assertv_core h t v >> intro h >> return () /- (define h t), adds a new goal for t, and the hypothesis (h : t := ?M) in the current goal. -/ meta def define (h : name) (t : expr) : tactic unit := define_core h t >> swap >> intro h >> swap /- (definev h t v), adds the hypothesis (h : t := v) in the current goal if v has type t. -/ meta def definev (h : name) (t : expr) (v : expr) : tactic unit := definev_core h t v >> intro h >> return () /- Add (h : t := pr) to the current goal -/ meta def pose (h : name) (pr : expr) : tactic unit := do t ← infer_type pr, definev h t pr /- Add (h : t) to the current goal, given a proof (pr : t) -/ meta def note (n : name) (pr : expr) : tactic unit := do t ← infer_type pr, assertv n t pr /- Return the number of goals that need to be solved -/ meta def num_goals : tactic nat := do gs ← get_goals, return (length gs) /- We have to provide the instance argument `[has_mod nat]` because mod for nat was not defined yet -/ meta def rotate_right (n : nat) [has_mod nat] : tactic unit := do ng ← num_goals, if ng = 0 then skip else rotate_left (ng - n % ng) meta def rotate : nat → tactic unit := rotate_left /- first [t_1, ..., t_n] applies the first tactic that doesn't fail. The tactic fails if all t_i's fail. -/ meta def first {α : Type u} : list (tactic α) → tactic α | [] := fail "first tactic failed, no more alternatives" | (t::ts) := t <|> first ts /- Applies the given tactic to the main goal and fails if it is not solved. -/ meta def solve1 (tac : tactic unit) : tactic unit := do gs ← get_goals, match gs with | [] := fail "focus tactic failed, there isn't any goal left to focus" | (g::rs) := do set_goals [g], tac, gs' ← get_goals, match gs' with | [] := set_goals rs | gs := fail "focus tactic failed, focused goal has not been solved" end end /- solve [t_1, ... t_n] applies the first tactic that solves the main goal. -/ meta def solve (ts : list (tactic unit)) : tactic unit := first $ map solve1 ts private meta def focus_aux : list (tactic unit) → list expr → list expr → tactic unit | [] gs rs := set_goals $ rs ++ gs | (t::ts) (g::gs) rs := do set_goals [g], t, rs' ← get_goals, focus_aux ts gs (rs ++ rs') | (t::ts) [] rs := fail "focus tactic failed, insufficient number of goals" /- focus [t_1, ..., t_n] applies t_i to the i-th goal. Fails if there are less tha n goals. -/ meta def focus (ts : list (tactic unit)) : tactic unit := do gs ← get_goals, focus_aux ts gs [] meta def focus1 {α} (tac : tactic α) : tactic α := do g::gs ← get_goals, match gs with | [] := tac | _ := do set_goals [g], a ← tac, gs' ← get_goals, set_goals (gs' ++ gs), return a end private meta def all_goals_core (tac : tactic unit) : list expr → list expr → tactic unit | [] ac := set_goals ac | (g :: gs) ac := do set_goals [g], tac, new_gs ← get_goals, all_goals_core gs (ac ++ new_gs) /- Apply the given tactic to all goals. -/ meta def all_goals (tac : tactic unit) : tactic unit := do gs ← get_goals, all_goals_core tac gs [] private meta def any_goals_core (tac : tactic unit) : list expr → list expr → bool → tactic unit | [] ac progress := guard progress >> set_goals ac | (g :: gs) ac progress := do set_goals [g], succeeded ← try_core tac, new_gs ← get_goals, any_goals_core gs (ac ++ new_gs) (succeeded.is_some || progress) /- Apply the given tactic to any goal where it succeeds. The tactic succeeds only if tac succeeds for at least one goal. -/ meta def any_goals (tac : tactic unit) : tactic unit := do gs ← get_goals, any_goals_core tac gs [] ff /- LCF-style AND_THEN tactic. It applies tac1, and if succeed applies tac2 to each subgoal produced by tac1 -/ meta def seq (tac1 : tactic unit) (tac2 : tactic unit) : tactic unit := do g::gs ← get_goals, set_goals [g], tac1, all_goals tac2, gs' ← get_goals, set_goals (gs' ++ gs) meta instance : has_andthen (tactic unit) := ⟨seq⟩ meta constant is_trace_enabled_for : name → bool /- Execute tac only if option trace.n is set to true. -/ meta def when_tracing (n : name) (tac : tactic unit) : tactic unit := when (is_trace_enabled_for n = tt) tac /- Fail if there are no remaining goals. -/ meta def fail_if_no_goals : tactic unit := do n ← num_goals, when (n = 0) (fail "tactic failed, there are no goals to be solved") /- Fail if there are unsolved goals. -/ meta def done : tactic unit := do n ← num_goals, when (n ≠ 0) (fail "done tactic failed, there are unsolved goals") meta def apply (e : expr) : tactic unit := apply_core e >> return () meta def fapply (e : expr) : tactic unit := apply_core e {all := tt} >> return () /- Try to solve the main goal using type class resolution. -/ meta def apply_instance : tactic unit := do tgt ← target >>= instantiate_mvars, b ← is_class tgt, if b then mk_instance tgt >>= exact else fail "apply_instance tactic fail, target is not a type class" /- Create a list of universe meta-variables of the given size. -/ meta def mk_num_meta_univs : nat → tactic (list level) | 0 := return [] | (succ n) := do l ← mk_meta_univ, ls ← mk_num_meta_univs n, return (l::ls) /- Return (expr.const c [l_1, ..., l_n]) where l_i's are fresh universe meta-variables. -/ meta def mk_const (c : name) : tactic expr := do env ← get_env, decl ← env.get c, let num := decl.univ_params.length, ls ← mk_num_meta_univs num, return (expr.const c ls) /-- Apply the constant `c` -/ meta def applyc (c : name) : tactic unit := mk_const c >>= apply meta def save_const_type_info (n : name) (ref : expr) : tactic unit := try (do c ← mk_const n, save_type_info c ref) /- Create a fresh universe ?u, a metavariable (?T : Type.{?u}), and return metavariable (?M : ?T). This action can be used to create a meta-variable when we don't know its type at creation time -/ meta def mk_mvar : tactic expr := do u ← mk_meta_univ, t ← mk_meta_var (expr.sort u), mk_meta_var t /-- Makes a sorry macro with a meta-variable as its type. -/ meta def mk_sorry : tactic expr := do u ← mk_meta_univ, t ← mk_meta_var (expr.sort u), return $ expr.mk_sorry t /-- Closes the main goal using sorry. -/ meta def admit : tactic unit := target >>= exact ∘ expr.mk_sorry meta def mk_local' (pp_name : name) (bi : binder_info) (type : expr) : tactic expr := do uniq_name ← mk_fresh_name, return $ expr.local_const uniq_name pp_name bi type meta def mk_local_def (pp_name : name) (type : expr) : tactic expr := mk_local' pp_name binder_info.default type meta def mk_local_pis : expr → tactic (list expr × expr) | (expr.pi n bi d b) := do p ← mk_local' n bi d, (ps, r) ← mk_local_pis (expr.instantiate_var b p), return ((p :: ps), r) | e := return ([], e) private meta def get_pi_arity_aux : expr → tactic nat | (expr.pi n bi d b) := do m ← mk_fresh_name, let l := expr.local_const m n bi d, new_b ← whnf (expr.instantiate_var b l), r ← get_pi_arity_aux new_b, return (r + 1) | e := return 0 /- Compute the arity of the given (Pi-)type -/ meta def get_pi_arity (type : expr) : tactic nat := whnf type >>= get_pi_arity_aux /- Compute the arity of the given function -/ meta def get_arity (fn : expr) : tactic nat := infer_type fn >>= get_pi_arity meta def triv : tactic unit := mk_const `trivial >>= exact notation `dec_trivial` := of_as_true (by tactic.triv) meta def by_contradiction (H : option name := none) : tactic expr := do tgt : expr ← target, (match_not tgt >> return ()) <|> (mk_mapp `decidable.by_contradiction [some tgt, none] >>= apply) <|> fail "tactic by_contradiction failed, target is not a negation nor a decidable proposition (remark: when 'local attribute classical.prop_decidable [instance]' is used all propositions are decidable)", match H with | some n := intro n | none := intro1 end meta def by_cases (e : expr) : tactic unit := do dec_e ← (mk_app `decidable [e] <|> fail "by_cases tactic failed, type is not a proposition"), inst ← (mk_instance dec_e <|> fail "by_cases tactic failed, type of given expression is not decidable"), em ← mk_app `decidable.em [e, inst], destruct em private meta def generalizes_aux (md : transparency) : list expr → tactic unit | [] := skip | (e::es) := generalize e `x md >> generalizes_aux es meta def generalizes (es : list expr) (md := semireducible) : tactic unit := generalizes_aux md es private meta def kdependencies_core (e : expr) (md : transparency) : list expr → list expr → tactic (list expr) | [] r := return r | (h::hs) r := do type ← infer_type h, d ← kdepends_on type e md, if d then kdependencies_core hs (h::r) else kdependencies_core hs r /-- Return all hypotheses that depends on `e` The dependency test is performed using `kdepends_on` with the given transparency setting. -/ meta def kdependencies (e : expr) (md := reducible) : tactic (list expr) := do ctx ← local_context, kdependencies_core e md ctx [] /-- Revert all hypotheses that depend on `e` -/ meta def revert_kdependencies (e : expr) (md := reducible) : tactic nat := kdependencies e md >>= revert_lst meta def revert_kdeps (e : expr) (md := reducible) := revert_kdependencies e md /-- Similar to `cases_core`, but `e` doesn't need to be a hypothesis. Remark, it reverts dependencies using `revert_kdeps`. Two different transparency modes are used `md` and `dmd`. The mode `md` is used with `cases_core` and `dmd` with `generalize` and `revert_kdeps`. -/ meta def cases (e : expr) (ids : list name := []) (md := semireducible) (dmd := semireducible) : tactic unit := if e.is_local_constant then cases_core e ids md >> return () else do x ← mk_fresh_name, n ← revert_kdependencies e dmd, (tactic.generalize e x dmd) <|> (do t ← infer_type e, tactic.assertv x t e, get_local x >>= tactic.revert, return ()), h ← tactic.intro1, (step (cases_core h ids md); intron n) meta def refine (e : pexpr) : tactic unit := do tgt : expr ← target, to_expr ``(%%e : %%tgt) tt >>= exact private meta def get_undeclared_const (env : environment) (base : name) : ℕ → name | i := let n := base <.> ("_aux_" ++ to_string i) in if ¬env.contains n then n else get_undeclared_const (i+1) meta def new_aux_decl_name : tactic name := do env ← get_env, n ← decl_name, return $ get_undeclared_const env n 1 private meta def mk_aux_decl_name : option name → tactic name | none := new_aux_decl_name | (some suffix) := do p ← decl_name, return $ p ++ suffix meta def abstract (tac : tactic unit) (suffix : option name := none) (zeta_reduce := tt) : tactic unit := do fail_if_no_goals, gs ← get_goals, type ← if zeta_reduce then target >>= zeta else target, is_lemma ← is_prop type, m ← mk_meta_var type, set_goals [m], tac, n ← num_goals, when (n ≠ 0) (fail "abstract tactic failed, there are unsolved goals"), set_goals gs, val ← instantiate_mvars m, val ← if zeta_reduce then zeta val else return val, c ← mk_aux_decl_name suffix, e ← add_aux_decl c type val is_lemma, exact e /- (solve_aux type tac) synthesize an element of 'type' using tactic 'tac' -/ meta def solve_aux {α : Type} (type : expr) (tac : tactic α) : tactic (α × expr) := do m ← mk_meta_var type, gs ← get_goals, set_goals [m], a ← tac, set_goals gs, return (a, m) /-- Return tt iff 'd' is a declaration in one of the current open namespaces -/ meta def in_open_namespaces (d : name) : tactic bool := do ns ← open_namespaces, env ← get_env, return $ ns.any (λ n, n.is_prefix_of d) && env.contains d /-- Execute tac for 'max' "heartbeats". The heartbeat is approx. the maximum number of memory allocations (in thousands) performed by 'tac'. This is a deterministic way of interrupting long running tactics. -/ meta def try_for {α} (max : nat) (tac : tactic α) : tactic α := λ s, match _root_.try_for max (tac s) with | some r := r | none := mk_exception "try_for tactic failed, timeout" none s end meta def add_meta_definition (n : name) (lvls : list name) (type value : expr) : tactic unit := add_decl (declaration.defn n lvls type value reducibility_hints.abbrev ff) meta def apply_opt_param : tactic unit := do ```(opt_param %%t %%v) ← target, exact v meta def apply_auto_param : tactic unit := do ```(auto_param %%type %%tac_name_expr) ← target, change type, tac_name ← eval_expr name tac_name_expr, tac ← eval_expr (tactic unit) (expr.const tac_name []), tac meta def rename (curr : name) (new : name) : tactic unit := do h ← get_local curr, n ← revert h, intro new, intron (n - 1) end tactic notation [parsing_only] `command`:max := tactic unit open tactic namespace list meta def for_each {α} : list α → (α → tactic unit) → tactic unit | [] fn := skip | (e::es) fn := do fn e, for_each es fn meta def any_of {α β} : list α → (α → tactic β) → tactic β | [] fn := failed | (e::es) fn := do opt_b ← try_core (fn e), match opt_b with | some b := return b | none := any_of es fn end end list /- Define id_locked using meta-programming because we don't have syntax for setting reducibility_hints. See module init.meta.declaration. Remark: id_locked is used in the builtin implementation of tactic.change -/ run_cmd do let l := level.param `l, let Ty := expr.sort l, type ← to_expr ``(Π (α : %%Ty), α → α), val ← to_expr ``(λ (α : %%Ty) (a : α), a), add_decl (declaration.defn `id_locked [`l] type val reducibility_hints.opaque tt) lemma id_locked_eq {α : Type u} (a : α) : id_locked α a = a := rfl /- Install monad laws tactic and use it to prove some instances. -/ meta def control_laws_tac := whnf_target >> intros >> to_expr ``(rfl) >>= exact meta def unsafe_monad_from_pure_bind {m : Type u → Type v} (pure : Π {α : Type u}, α → m α) (bind : Π {α β : Type u}, m α → (α → m β) → m β) : monad m := {pure := @pure, bind := @bind, id_map := undefined, pure_bind := undefined, bind_assoc := undefined} meta instance : monad task := {map := @task.map, bind := @task.bind, pure := @task.pure, id_map := undefined, pure_bind := undefined, bind_assoc := undefined, bind_pure_comp_eq_map := undefined}
de8ad20d7340f6a9fb7f3e04d06ad5427edc349e
e94d3f31e48d06d252ee7307fe71efe1d500f274
/library/init/tactic.lean
83047789ea432b82cb18ec00c7f83773a071ee14
[ "Apache-2.0" ]
permissive
GallagherCommaJack/lean
e4471240a069d82f97cb361d2bf1a029de3f4256
226f8bafeb9baaa5a2ac58000c83d6beb29991e2
refs/heads/master
1,610,725,100,482
1,459,194,829,000
1,459,195,377,000
55,377,224
0
0
null
1,459,731,701,000
1,459,731,700,000
null
UTF-8
Lean
false
false
7,925
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura This is just a trick to embed the 'tactic language' as a Lean expression. We should view 'tactic' as automation that when execute produces a term. tactic.builtin is just a "dummy" for creating the definitions that are actually implemented in C++ -/ prelude import init.datatypes init.reserved_notation init.num inductive tactic : Type := builtin : tactic namespace tactic -- Remark the following names are not arbitrary, the tactic module -- uses them when converting Lean expressions into actual tactic objects. -- The bultin 'by' construct triggers the process of converting a -- a term of type 'tactic' into a tactic that sythesizes a term definition and_then (t1 t2 : tactic) : tactic := builtin definition or_else (t1 t2 : tactic) : tactic := builtin definition par (t1 t2 : tactic) : tactic := builtin definition fixpoint (f : tactic → tactic) : tactic := builtin definition repeat (t : tactic) : tactic := builtin definition at_most (t : tactic) (k : num) : tactic := builtin definition discard (t : tactic) (k : num) : tactic := builtin definition focus_at (t : tactic) (i : num) : tactic := builtin definition try_for (t : tactic) (ms : num) : tactic := builtin definition all_goals (t : tactic) : tactic := builtin definition now : tactic := builtin definition assumption : tactic := builtin definition eassumption : tactic := builtin definition state : tactic := builtin definition fail : tactic := builtin definition id : tactic := builtin definition beta : tactic := builtin definition info : tactic := builtin definition whnf : tactic := builtin definition contradiction : tactic := builtin definition exfalso : tactic := builtin definition congruence : tactic := builtin definition rotate_left (k : num) := builtin definition rotate_right (k : num) := builtin definition rotate (k : num) := rotate_left k definition norm_num : tactic := builtin -- This is just a trick to embed expressions into tactics. -- The nested expressions are "raw". They tactic should -- elaborate them when it is executed. inductive expr : Type := builtin : expr inductive expr_list : Type := | nil : expr_list | cons : expr → expr_list → expr_list -- auxiliary type used to mark optional list of arguments definition opt_expr_list := expr_list -- auxiliary types used to mark that the expression is suppose to be an identifier, optional, or a list. definition identifier := expr definition identifier_list := expr_list definition opt_identifier_list := expr_list -- Remark: the parser has special support for tactics containing `location` parameters. -- It will parse the optional `at ...` modifier. definition location := expr -- Marker for instructing the parser to parse it as 'with <expr>' definition with_expr := expr -- Marker for instructing the parser to parse it as '?(using <expr>)' definition using_expr := expr -- Constant used to denote the case were no expression was provided definition none_expr : expr := expr.builtin definition apply (e : expr) : tactic := builtin definition eapply (e : expr) : tactic := builtin definition fapply (e : expr) : tactic := builtin definition rename (a b : identifier) : tactic := builtin definition intro (e : opt_identifier_list) : tactic := builtin definition generalize_tac (e : expr) (id : identifier) : tactic := builtin definition clear (e : identifier_list) : tactic := builtin definition revert (e : identifier_list) : tactic := builtin definition refine (e : expr) : tactic := builtin definition exact (e : expr) : tactic := builtin -- Relaxed version of exact that does not enforce goal type definition rexact (e : expr) : tactic := builtin definition check_expr (e : expr) : tactic := builtin definition trace (s : string) : tactic := builtin -- rewrite_tac is just a marker for the builtin 'rewrite' notation -- used to create instances of this tactic. definition rewrite_tac (e : expr_list) : tactic := builtin definition xrewrite_tac (e : expr_list) : tactic := builtin definition krewrite_tac (e : expr_list) : tactic := builtin definition replace (old : expr) (new : with_expr) (loc : location) : tactic := builtin -- Arguments: -- - ls : lemmas to be used (if not provided, then blast will choose them) -- - ds : definitions that can be unfolded (if not provided, then blast will choose them) definition blast (ls : opt_identifier_list) (ds : opt_identifier_list) : tactic := builtin -- with_options_tac is just a marker for the builtin 'with_options' notation definition with_options_tac (o : expr) (t : tactic) : tactic := builtin -- with_options_tac is just a marker for the builtin 'with_attributes' notation definition with_attributes_tac (o : expr) (n : identifier_list) (t : tactic) : tactic := builtin definition simp : tactic := #tactic with_options [blast.strategy "simp"] blast definition simp_nohyps : tactic := #tactic with_options [blast.strategy "simp_nohyps"] blast definition simp_topdown : tactic := #tactic with_options [blast.strategy "simp", simplify.top_down true] blast definition inst_simp : tactic := #tactic with_options [blast.strategy "ematch_simp"] blast definition rec_simp : tactic := #tactic with_options [blast.strategy "rec_simp"] blast definition rec_inst_simp : tactic := #tactic with_options [blast.strategy "rec_ematch_simp"] blast definition grind : tactic := #tactic with_options [blast.strategy "grind"] blast definition grind_simp : tactic := #tactic with_options [blast.strategy "grind_simp"] blast definition cases (h : expr) (ids : opt_identifier_list) : tactic := builtin definition induction (h : expr) (rec : using_expr) (ids : opt_identifier_list) : tactic := builtin definition intros (ids : opt_identifier_list) : tactic := builtin definition generalizes (es : expr_list) : tactic := builtin definition clears (ids : identifier_list) : tactic := builtin definition reverts (ids : identifier_list) : tactic := builtin definition change (e : expr) : tactic := builtin definition assert_hypothesis (id : identifier) (e : expr) : tactic := builtin definition note_tac (id : identifier) (e : expr) : tactic := builtin definition constructor (k : option num) : tactic := builtin definition fconstructor (k : option num) : tactic := builtin definition existsi (e : expr) : tactic := builtin definition split : tactic := builtin definition left : tactic := builtin definition right : tactic := builtin definition injection (e : expr) (ids : opt_identifier_list) : tactic := builtin definition subst (ids : identifier_list) : tactic := builtin definition substvars : tactic := builtin definition reflexivity : tactic := builtin definition symmetry : tactic := builtin definition transitivity (e : expr) : tactic := builtin definition try (t : tactic) : tactic := or_else t id definition repeat1 (t : tactic) : tactic := and_then t (repeat t) definition focus (t : tactic) : tactic := focus_at t 0 definition determ (t : tactic) : tactic := at_most t 1 definition trivial : tactic := or_else (or_else (apply eq.refl) (apply true.intro)) assumption definition do (n : num) (t : tactic) : tactic := nat.rec id (λn t', and_then t t') (nat.of_num n) end tactic tactic_infixl `;`:15 := tactic.and_then tactic_notation T1 `:`:15 T2 := tactic.focus (tactic.and_then T1 (tactic.all_goals T2)) tactic_notation `(` h `|` r:(foldl `|` (e r, tactic.or_else r e) h) `)` := r --tactic_notation `replace` s `with` t := tactic.replace_tac s t
a6f6dcb8ee6417b8c221af2265cbe394efa1ab16
dd4e652c749fea9ac77e404005cb3470e5f75469
/src/nat.lean
a9bad663cc33fa06ee6c5835a0e58bfe696c658c
[]
no_license
skbaek/cvx
e32822ad5943541539966a37dee162b0a5495f55
c50c790c9116f9fac8dfe742903a62bdd7292c15
refs/heads/master
1,623,803,010,339
1,618,058,958,000
1,618,058,958,000
176,293,135
3
2
null
null
null
null
UTF-8
Lean
false
false
315
lean
import data.nat.basic namespace nat lemma max_succ_succ {m n} : max (succ m) (succ n) = succ (max m n) := begin by_cases h1 : m ≤ n, rw [max_eq_right h1, max_eq_right (succ_le_succ h1)], { rw not_le at h1, have h2 := le_of_lt h1, rw [max_eq_left h2, max_eq_left (succ_le_succ h2)] } end end nat
60f281327dfc09f424ff87e10a304540f043ac73
ec62863c729b7eedee77b86d974f2c529fa79d25
/2/b.lean
0ea69260c65875e134011ad2199435b792af2c9e
[]
no_license
rwbarton/advent-of-lean-4
2ac9b17ba708f66051e3d8cd694b0249bc433b65
417c7e2718253ba7148c0279fcb251b6fc291477
refs/heads/main
1,675,917,092,057
1,609,864,581,000
1,609,864,581,000
317,700,289
24
0
null
null
null
null
UTF-8
Lean
false
false
735
lean
structure Passwd where min : Int max : Int letter : Char str : String instance : Inhabited Passwd := ⟨⟨0,0,'a',"a"⟩⟩ instance : ToString Passwd := ⟨λ p => s!"{p.min}-{p.max} {p.letter}: {p.str}"⟩ def parseLine (s : String) : Passwd := match s.splitOn with | [a,b,c] => match a.splitOn "-" with | [x,y] => ⟨x.toInt!, y.toInt!, b.front, c⟩ | _ => panic! "bad format" | _ => panic! "bad format" def isValid (p : Passwd) : Bool := (p.str.get (p.min.toNat - 1) == p.letter) != (p.str.get (p.max.toNat - 1) == p.letter) def solve (xs : List String) : Int := (xs.filter (λ x => isValid (parseLine x))).length def main : IO Unit := do let input ← IO.FS.lines "a.in" IO.print s!"{solve input.toList}\n"
d6f00de103c1056aa46573a4bd45fecd009dc37d
8e6cad62ec62c6c348e5faaa3c3f2079012bdd69
/src/data/polynomial/degree/lemmas.lean
4b0da0c9f8afd259aa28c90e75d2008ff8653dcf
[ "Apache-2.0" ]
permissive
benjamindavidson/mathlib
8cc81c865aa8e7cf4462245f58d35ae9a56b150d
fad44b9f670670d87c8e25ff9cdf63af87ad731e
refs/heads/master
1,679,545,578,362
1,615,343,014,000
1,615,343,014,000
312,926,983
0
0
Apache-2.0
1,615,360,301,000
1,605,399,418,000
Lean
UTF-8
Lean
false
false
9,586
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.eval import tactic.interval_cases /-! # Theory of degrees of polynomials Some of the main results include - `nat_degree_comp_le` : The degree of the composition is at most the product of degrees -/ noncomputable theory local attribute [instance, priority 100] classical.prop_decidable open finsupp finset namespace polynomial universes u v w variables {R : Type u} {S : Type v} { ι : Type w} {a b : R} {m n : ℕ} section semiring variables [semiring R] {p q r : polynomial R} section degree lemma nat_degree_comp_le : nat_degree (p.comp q) ≤ nat_degree p * nat_degree q := if h0 : p.comp q = 0 then by rw [h0, nat_degree_zero]; exact nat.zero_le _ else with_bot.coe_le_coe.1 $ calc ↑(nat_degree (p.comp q)) = degree (p.comp q) : (degree_eq_nat_degree h0).symm ... = _ : congr_arg degree comp_eq_sum_left ... ≤ _ : degree_sum_le _ _ ... ≤ _ : sup_le (λ n hn, calc degree (C (coeff p n) * q ^ n) ≤ degree (C (coeff p n)) + degree (q ^ n) : degree_mul_le _ _ ... ≤ nat_degree (C (coeff p n)) + n •ℕ (degree q) : add_le_add degree_le_nat_degree (degree_pow_le _ _) ... ≤ nat_degree (C (coeff p n)) + n •ℕ (nat_degree q) : add_le_add_left (nsmul_le_nsmul_of_le_right (@degree_le_nat_degree _ _ q) n) _ ... = (n * nat_degree q : ℕ) : by rw [nat_degree_C, with_bot.coe_zero, zero_add, ← with_bot.coe_nsmul, nsmul_eq_mul]; simp ... ≤ (nat_degree p * nat_degree q : ℕ) : with_bot.coe_le_coe.2 $ mul_le_mul_of_nonneg_right (le_nat_degree_of_ne_zero (finsupp.mem_support_iff.1 hn)) (nat.zero_le _)) lemma degree_map_le [semiring S] (f : R →+* S) : degree (map f p) ≤ degree p := if h : map f p = 0 then by simp [h] else begin rw [degree_eq_nat_degree h], refine le_degree_of_ne_zero (mt (congr_arg f) _), rw [← coeff_map f, is_semiring_hom.map_zero f], exact mt leading_coeff_eq_zero.1 h end lemma nat_degree_map_le [semiring S] (f : R →+* S) : (map f p).nat_degree ≤ p.nat_degree := begin by_cases hp : p = 0, { simp [hp] }, { rw [← with_bot.coe_le_coe, ← degree_eq_nat_degree hp], by_cases hfp : map f p = 0, { simp [hfp, zero_le_degree_iff.mpr hp] }, { simp [← degree_eq_nat_degree hfp, degree_map_le] } } end lemma degree_map_eq_of_leading_coeff_ne_zero [semiring S] (f : R →+* S) (hf : f (leading_coeff p) ≠ 0) : degree (p.map f) = degree p := le_antisymm (degree_map_le f) $ have hp0 : p ≠ 0, from λ hp0, by simpa [hp0, is_semiring_hom.map_zero f] using hf, begin rw [degree_eq_nat_degree hp0], refine le_degree_of_ne_zero _, rw [coeff_map], exact hf end lemma nat_degree_map_of_leading_coeff_ne_zero [semiring S] (f : R →+* S) (hf : f (leading_coeff p) ≠ 0) : nat_degree (p.map f) = nat_degree p := nat_degree_eq_of_degree_eq (degree_map_eq_of_leading_coeff_ne_zero f hf) lemma leading_coeff_map_of_leading_coeff_ne_zero [semiring S] (f : R →+* S) (hf : f (leading_coeff p) ≠ 0) : leading_coeff (p.map f) = f (leading_coeff p) := begin unfold leading_coeff, rw [coeff_map, nat_degree_map_of_leading_coeff_ne_zero f hf], end lemma degree_pos_of_root {p : polynomial R} (hp : p ≠ 0) (h : is_root p a) : 0 < degree p := lt_of_not_ge $ λ hlt, begin have := eq_C_of_degree_le_zero hlt, rw [is_root, this, eval_C] at h, exact hp (finsupp.ext (λ n, show coeff p n = 0, from nat.cases_on n h (λ _, coeff_eq_zero_of_degree_lt (lt_of_le_of_lt hlt (with_bot.coe_lt_coe.2 (nat.succ_pos _)))))), end lemma nat_degree_le_iff_coeff_eq_zero : p.nat_degree ≤ n ↔ ∀ N : ℕ, n < N → p.coeff N = 0 := by simp_rw [nat_degree_le_iff_degree_le, degree_le_iff_coeff_zero, with_bot.coe_lt_coe] lemma nat_degree_C_mul_le (a : R) (f : polynomial R) : (C a * f).nat_degree ≤ f.nat_degree := calc (C a * f).nat_degree ≤ (C a).nat_degree + f.nat_degree : nat_degree_mul_le ... = 0 + f.nat_degree : by rw nat_degree_C a ... = f.nat_degree : zero_add _ lemma nat_degree_mul_C_le (f : polynomial R) (a : R) : (f * C a).nat_degree ≤ f.nat_degree := calc (f * C a).nat_degree ≤ f.nat_degree + (C a).nat_degree : nat_degree_mul_le ... = f.nat_degree + 0 : by rw nat_degree_C a ... = f.nat_degree : add_zero _ lemma eq_nat_degree_of_le_mem_support (pn : p.nat_degree ≤ n) (ns : n ∈ p.support) : p.nat_degree = n := le_antisymm pn (le_nat_degree_of_mem_supp _ ns) lemma nat_degree_C_mul_eq_of_mul_eq_one {ai : R} (au : ai * a = 1) : (C a * p).nat_degree = p.nat_degree := le_antisymm (nat_degree_C_mul_le a p) (calc p.nat_degree = (1 * p).nat_degree : by nth_rewrite 0 [← one_mul p] ... = (C ai * (C a * p)).nat_degree : by rw [← C_1, ← au, ring_hom.map_mul, ← mul_assoc] ... ≤ (C a * p).nat_degree : nat_degree_C_mul_le ai (C a * p)) lemma nat_degree_mul_C_eq_of_mul_eq_one {ai : R} (au : a * ai = 1) : (p * C a).nat_degree = p.nat_degree := le_antisymm (nat_degree_mul_C_le p a) (calc p.nat_degree = (p * 1).nat_degree : by nth_rewrite 0 [← mul_one p] ... = ((p * C a) * C ai).nat_degree : by rw [← C_1, ← au, ring_hom.map_mul, ← mul_assoc] ... ≤ (p * C a).nat_degree : nat_degree_mul_C_le (p * C a) ai) /-- Although not explicitly stated, the assumptions of lemma `nat_degree_mul_C_eq_of_mul_ne_zero` force the polynomial `p` to be non-zero, via `p.leading_coeff ≠ 0`. Lemma `nat_degree_mul_C_eq_of_no_zero_divisors` below separates cases, in order to overcome this hurdle. -/ lemma nat_degree_mul_C_eq_of_mul_ne_zero (h : p.leading_coeff * a ≠ 0) : (p * C a).nat_degree = p.nat_degree := begin refine eq_nat_degree_of_le_mem_support (nat_degree_mul_C_le p a) _, refine mem_support_iff_coeff_ne_zero.mpr _, rwa coeff_mul_C, end /-- Although not explicitly stated, the assumptions of lemma `nat_degree_C_mul_eq_of_mul_ne_zero` force the polynomial `p` to be non-zero, via `p.leading_coeff ≠ 0`. Lemma `nat_degree_C_mul_eq_of_no_zero_divisors` below separates cases, in order to overcome this hurdle. -/ lemma nat_degree_C_mul_eq_of_mul_ne_zero (h : a * p.leading_coeff ≠ 0) : (C a * p).nat_degree = p.nat_degree := begin refine eq_nat_degree_of_le_mem_support (nat_degree_C_mul_le a p) _, refine mem_support_iff_coeff_ne_zero.mpr _, rwa coeff_C_mul, end lemma nat_degree_add_coeff_mul (f g : polynomial R) : (f * g).coeff (f.nat_degree + g.nat_degree) = f.coeff f.nat_degree * g.coeff g.nat_degree := by simp only [coeff_nat_degree, coeff_mul_degree_add_degree] lemma nat_degree_lt_coeff_mul (h : p.nat_degree + q.nat_degree < m + n) : (p * q).coeff (m + n) = 0 := coeff_eq_zero_of_nat_degree_lt (nat_degree_mul_le.trans_lt h) variables [semiring S] lemma nat_degree_pos_of_eval₂_root {p : polynomial R} (hp : p ≠ 0) (f : R →+* S) {z : S} (hz : eval₂ f z p = 0) (inj : ∀ (x : R), f x = 0 → x = 0) : 0 < nat_degree p := lt_of_not_ge $ λ hlt, begin rw [eq_C_of_nat_degree_le_zero hlt, eval₂_C] at hz, refine hp (finsupp.ext (λ n, _)), cases n, { exact inj _ hz }, { exact coeff_eq_zero_of_nat_degree_lt (lt_of_le_of_lt hlt (nat.succ_pos _)) } end lemma degree_pos_of_eval₂_root {p : polynomial R} (hp : p ≠ 0) (f : R →+* S) {z : S} (hz : eval₂ f z p = 0) (inj : ∀ (x : R), f x = 0 → x = 0) : 0 < degree p := nat_degree_pos_iff_degree_pos.mp (nat_degree_pos_of_eval₂_root hp f hz inj) section injective open function variables {f : R →+* S} (hf : injective f) include hf lemma degree_map_eq_of_injective (p : polynomial R) : degree (p.map f) = degree p := if h : p = 0 then by simp [h] else degree_map_eq_of_leading_coeff_ne_zero _ (by rw [← is_semiring_hom.map_zero f]; exact mt hf.eq_iff.1 (mt leading_coeff_eq_zero.1 h)) lemma degree_map' (p : polynomial R) : degree (p.map f) = degree p := p.degree_map_eq_of_injective hf lemma nat_degree_map' (p : polynomial R) : nat_degree (p.map f) = nat_degree p := nat_degree_eq_of_degree_eq (degree_map' hf p) lemma leading_coeff_map' (p : polynomial R) : leading_coeff (p.map f) = f (leading_coeff p) := begin unfold leading_coeff, rw [coeff_map, nat_degree_map' hf p], end end injective section variable {f : polynomial R} lemma monomial_nat_degree_leading_coeff_eq_self (h : f.support.card ≤ 1) : monomial f.nat_degree f.leading_coeff = f := begin interval_cases f.support.card with H, { have : f = 0 := finsupp.card_support_eq_zero.1 H, simp [this] }, { obtain ⟨n, x, hx, rfl : f = monomial n x⟩ := finsupp.card_support_eq_one'.1 H, simp [hx] } end lemma C_mul_X_pow_eq_self (h : f.support.card ≤ 1) : C f.leading_coeff * X^f.nat_degree = f := by rw [C_mul_X_pow_eq_monomial, monomial_nat_degree_leading_coeff_eq_self h] end end degree end semiring section no_zero_divisors variables [semiring R] [no_zero_divisors R] {p q : polynomial R} lemma nat_degree_mul_C_eq_of_no_zero_divisors (a0 : a ≠ 0) : (p * C a).nat_degree = p.nat_degree := begin by_cases p0 : p = 0, { rw [p0, zero_mul] }, { exact nat_degree_mul_C_eq_of_mul_ne_zero (mul_ne_zero (leading_coeff_ne_zero.mpr p0) a0) } end lemma nat_degree_C_mul_eq_of_no_zero_divisors (a0 : a ≠ 0) : (C a * p).nat_degree = p.nat_degree := begin by_cases p0 : p = 0, { rw [p0, mul_zero] }, { exact nat_degree_C_mul_eq_of_mul_ne_zero (mul_ne_zero a0 (leading_coeff_ne_zero.mpr p0)) } end end no_zero_divisors end polynomial
aed2e93a5fc030ee637814e4f0fb2b5c351f71e7
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/number_theory/divisors.lean
3a8ba38bb04944482ab89dda245153b78c2f68c9
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
8,136
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.big_operators.order import Mathlib.tactic.default import Mathlib.data.nat.prime import Mathlib.PostPort universes u_1 namespace Mathlib /-! # Divisor finsets This file defines sets of divisors of a natural number. This is particularly useful as background for defining Dirichlet convolution. ## Main Definitions Let `n : ℕ`. All of the following definitions are in the `nat` namespace: * `divisors n` is the `finset` of natural numbers that divide `n`. * `proper_divisors n` is the `finset` of natural numbers that divide `n`, other than `n`. * `divisors_antidiagonal n` is the `finset` of pairs `(x,y)` such that `x * y = n`. * `perfect n` is true when `n` is positive and the sum of `proper_divisors n` is `n`. ## Implementation details * `divisors 0`, `proper_divisors 0`, and `divisors_antidiagonal 0` are defined to be `∅`. ## Tags divisors, perfect numbers -/ namespace nat /-- `divisors n` is the `finset` of divisors of `n`. As a special case, `divisors 0 = ∅`. -/ def divisors (n : ℕ) : finset ℕ := finset.filter (fun (x : ℕ) => x ∣ n) (finset.Ico 1 (n + 1)) /-- `proper_divisors n` is the `finset` of divisors of `n`, other than `n`. As a special case, `proper_divisors 0 = ∅`. -/ def proper_divisors (n : ℕ) : finset ℕ := finset.filter (fun (x : ℕ) => x ∣ n) (finset.Ico 1 n) /-- `divisors_antidiagonal n` is the `finset` of pairs `(x,y)` such that `x * y = n`. As a special case, `divisors_antidiagonal 0 = ∅`. -/ def divisors_antidiagonal (n : ℕ) : finset (ℕ × ℕ) := finset.filter (fun (x : ℕ × ℕ) => prod.fst x * prod.snd x = n) (finset.product (finset.Ico 1 (n + 1)) (finset.Ico 1 (n + 1))) theorem proper_divisors.not_self_mem {n : ℕ} : ¬n ∈ proper_divisors n := sorry @[simp] theorem mem_proper_divisors {n : ℕ} {m : ℕ} : n ∈ proper_divisors m ↔ n ∣ m ∧ n < m := sorry theorem divisors_eq_proper_divisors_insert_self_of_pos {n : ℕ} (h : 0 < n) : divisors n = insert n (proper_divisors n) := sorry @[simp] theorem mem_divisors {n : ℕ} {m : ℕ} : n ∈ divisors m ↔ n ∣ m ∧ m ≠ 0 := sorry theorem dvd_of_mem_divisors {n : ℕ} {m : ℕ} (h : n ∈ divisors m) : n ∣ m := sorry @[simp] theorem mem_divisors_antidiagonal {n : ℕ} {x : ℕ × ℕ} : x ∈ divisors_antidiagonal n ↔ prod.fst x * prod.snd x = n ∧ n ≠ 0 := sorry theorem divisor_le {n : ℕ} {m : ℕ} : n ∈ divisors m → n ≤ m := sorry theorem divisors_subset_of_dvd {n : ℕ} {m : ℕ} (hzero : n ≠ 0) (h : m ∣ n) : divisors m ⊆ divisors n := iff.mpr finset.subset_iff fun (x : ℕ) (hx : x ∈ divisors m) => iff.mpr mem_divisors { left := dvd.trans (and.left (iff.mp mem_divisors hx)) h, right := hzero } theorem divisors_subset_proper_divisors {n : ℕ} {m : ℕ} (hzero : n ≠ 0) (h : m ∣ n) (hdiff : m ≠ n) : divisors m ⊆ proper_divisors n := sorry @[simp] theorem divisors_zero : divisors 0 = ∅ := sorry @[simp] theorem proper_divisors_zero : proper_divisors 0 = ∅ := sorry theorem proper_divisors_subset_divisors {n : ℕ} : proper_divisors n ⊆ divisors n := sorry @[simp] theorem divisors_one : divisors 1 = singleton 1 := sorry @[simp] theorem proper_divisors_one : proper_divisors 1 = ∅ := sorry theorem pos_of_mem_divisors {n : ℕ} {m : ℕ} (h : m ∈ divisors n) : 0 < m := sorry theorem pos_of_mem_proper_divisors {n : ℕ} {m : ℕ} (h : m ∈ proper_divisors n) : 0 < m := pos_of_mem_divisors (proper_divisors_subset_divisors h) theorem one_mem_proper_divisors_iff_one_lt {n : ℕ} : 1 ∈ proper_divisors n ↔ 1 < n := eq.mpr (id (Eq._oldrec (Eq.refl (1 ∈ proper_divisors n ↔ 1 < n)) (propext mem_proper_divisors))) (eq.mpr (id (Eq._oldrec (Eq.refl (1 ∣ n ∧ 1 < n ↔ 1 < n)) (propext (and_iff_right (one_dvd n))))) (iff.refl (1 < n))) @[simp] theorem divisors_antidiagonal_zero : divisors_antidiagonal 0 = ∅ := sorry @[simp] theorem divisors_antidiagonal_one : divisors_antidiagonal 1 = singleton (1, 1) := sorry theorem swap_mem_divisors_antidiagonal {n : ℕ} {x : ℕ × ℕ} (h : x ∈ divisors_antidiagonal n) : prod.swap x ∈ divisors_antidiagonal n := sorry theorem fst_mem_divisors_of_mem_antidiagonal {n : ℕ} {x : ℕ × ℕ} (h : x ∈ divisors_antidiagonal n) : prod.fst x ∈ divisors n := sorry theorem snd_mem_divisors_of_mem_antidiagonal {n : ℕ} {x : ℕ × ℕ} (h : x ∈ divisors_antidiagonal n) : prod.snd x ∈ divisors n := sorry @[simp] theorem map_swap_divisors_antidiagonal {n : ℕ} : finset.map (function.embedding.mk prod.swap (function.right_inverse.injective prod.swap_right_inverse)) (divisors_antidiagonal n) = divisors_antidiagonal n := sorry theorem sum_divisors_eq_sum_proper_divisors_add_self {n : ℕ} : (finset.sum (divisors n) fun (i : ℕ) => i) = (finset.sum (proper_divisors n) fun (i : ℕ) => i) + n := sorry /-- `n : ℕ` is perfect if and only the sum of the proper divisors of `n` is `n` and `n` is positive. -/ def perfect (n : ℕ) := (finset.sum (proper_divisors n) fun (i : ℕ) => i) = n ∧ 0 < n theorem perfect_iff_sum_proper_divisors {n : ℕ} (h : 0 < n) : perfect n ↔ (finset.sum (proper_divisors n) fun (i : ℕ) => i) = n := and_iff_left h theorem perfect_iff_sum_divisors_eq_two_mul {n : ℕ} (h : 0 < n) : perfect n ↔ (finset.sum (divisors n) fun (i : ℕ) => i) = bit0 1 * n := sorry theorem mem_divisors_prime_pow {p : ℕ} (pp : prime p) (k : ℕ) {x : ℕ} : x ∈ divisors (p ^ k) ↔ ∃ (j : ℕ), ∃ (H : j ≤ k), x = p ^ j := sorry theorem prime.divisors {p : ℕ} (pp : prime p) : divisors p = insert 1 (singleton p) := sorry theorem prime.proper_divisors {p : ℕ} (pp : prime p) : proper_divisors p = singleton 1 := sorry theorem divisors_prime_pow {p : ℕ} (pp : prime p) (k : ℕ) : divisors (p ^ k) = finset.map (function.embedding.mk (pow p) (pow_right_injective (prime.two_le pp))) (finset.range (k + 1)) := sorry theorem eq_proper_divisors_of_subset_of_sum_eq_sum {n : ℕ} {s : finset ℕ} (hsub : s ⊆ proper_divisors n) : ((finset.sum s fun (x : ℕ) => x) = finset.sum (proper_divisors n) fun (x : ℕ) => x) → s = proper_divisors n := sorry theorem sum_proper_divisors_dvd {n : ℕ} (h : (finset.sum (proper_divisors n) fun (x : ℕ) => x) ∣ n) : (finset.sum (proper_divisors n) fun (x : ℕ) => x) = 1 ∨ (finset.sum (proper_divisors n) fun (x : ℕ) => x) = n := sorry @[simp] theorem prime.sum_proper_divisors {α : Type u_1} [add_comm_monoid α] {p : ℕ} {f : ℕ → α} (h : prime p) : (finset.sum (proper_divisors p) fun (x : ℕ) => f x) = f 1 := sorry @[simp] theorem prime.sum_divisors {α : Type u_1} [add_comm_monoid α] {p : ℕ} {f : ℕ → α} (h : prime p) : (finset.sum (divisors p) fun (x : ℕ) => f x) = f p + f 1 := sorry theorem proper_divisors_eq_singleton_one_iff_prime {n : ℕ} : proper_divisors n = singleton 1 ↔ prime n := sorry theorem sum_proper_divisors_eq_one_iff_prime {n : ℕ} : (finset.sum (proper_divisors n) fun (x : ℕ) => x) = 1 ↔ prime n := sorry @[simp] theorem prod_divisors_prime {α : Type u_1} [comm_monoid α] {p : ℕ} {f : ℕ → α} (h : prime p) : (finset.prod (divisors p) fun (x : ℕ) => f x) = f p * f 1 := prime.sum_divisors h @[simp] theorem sum_divisors_prime_pow {α : Type u_1} [add_comm_monoid α] {k : ℕ} {p : ℕ} {f : ℕ → α} (h : prime p) : (finset.sum (divisors (p ^ k)) fun (x : ℕ) => f x) = finset.sum (finset.range (k + 1)) fun (x : ℕ) => f (p ^ x) := sorry @[simp] theorem prod_divisors_prime_pow {α : Type u_1} [comm_monoid α] {k : ℕ} {p : ℕ} {f : ℕ → α} (h : prime p) : (finset.prod (divisors (p ^ k)) fun (x : ℕ) => f x) = finset.prod (finset.range (k + 1)) fun (x : ℕ) => f (p ^ x) := sum_divisors_prime_pow h @[simp] theorem filter_dvd_eq_divisors {n : ℕ} (h : n ≠ 0) : finset.filter (fun (x : ℕ) => x ∣ n) (finset.range (Nat.succ n)) = divisors n := sorry
9d1881d5ac18cc6cce3fe5ac4d4a326d0f5b2daa
94e33a31faa76775069b071adea97e86e218a8ee
/src/dynamics/omega_limit.lean
96876df8dda8c9f692fba23e19ec16f287cd19a4
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
16,562
lean
/- Copyright (c) 2020 Jean Lo. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jean Lo -/ import dynamics.flow /-! # ω-limits For a function `ϕ : τ → α → β` where `β` is a topological space, we define the ω-limit under `ϕ` of a set `s` in `α` with respect to filter `f` on `τ`: an element `y : β` is in the ω-limit of `s` if the forward images of `s` intersect arbitrarily small neighbourhoods of `y` frequently "in the direction of `f`". In practice `ϕ` is often a continuous monoid-act, but the definition requires only that `ϕ` has a coercion to the appropriate function type. In the case where `τ` is `ℕ` or `ℝ` and `f` is `at_top`, we recover the usual definition of the ω-limit set as the set of all `y` such that there exist sequences `(tₙ)`, `(xₙ)` such that `ϕ tₙ xₙ ⟶ y` as `n ⟶ ∞`. ## Notations The `omega_limit` locale provides the localised notation `ω` for `omega_limit`, as well as `ω⁺` and `ω⁻` for `omega_limit at_top` and `omega_limit at_bot` respectively for when the acting monoid is endowed with an order. -/ open set function filter open_locale topological_space /-! ### Definition and notation -/ section omega_limit variables {τ : Type*} {α : Type*} {β : Type*} {ι : Type*} /-- The ω-limit of a set `s` under `ϕ` with respect to a filter `f` is ⋂ u ∈ f, cl (ϕ u s). -/ def omega_limit [topological_space β] (f : filter τ) (ϕ : τ → α → β) (s : set α) : set β := ⋂ u ∈ f, closure (image2 ϕ u s) localized "notation `ω` := omega_limit" in omega_limit localized "notation `ω⁺` := omega_limit filter.at_top" in omega_limit localized "notation `ω⁻` := omega_limit filter.at_bot" in omega_limit variables [topological_space β] variables (f : filter τ) (ϕ : τ → α → β) (s s₁ s₂: set α) /-! ### Elementary properties -/ lemma omega_limit_def : ω f ϕ s = ⋂ u ∈ f, closure (image2 ϕ u s) := rfl lemma omega_limit_subset_of_tendsto {m : τ → τ} {f₁ f₂ : filter τ} (hf : tendsto m f₁ f₂) : ω f₁ (λ t x, ϕ (m t) x) s ⊆ ω f₂ ϕ s := begin refine Inter₂_mono' (λ u hu, ⟨m ⁻¹' u, tendsto_def.mp hf _ hu, _⟩), rw ←image2_image_left, exact closure_mono (image2_subset (image_preimage_subset _ _) subset.rfl), end lemma omega_limit_mono_left {f₁ f₂ : filter τ} (hf : f₁ ≤ f₂) : ω f₁ ϕ s ⊆ ω f₂ ϕ s := omega_limit_subset_of_tendsto ϕ s (tendsto_id'.2 hf) lemma omega_limit_mono_right {s₁ s₂ : set α} (hs : s₁ ⊆ s₂) : ω f ϕ s₁ ⊆ ω f ϕ s₂ := Inter₂_mono $ λ u hu, closure_mono (image2_subset subset.rfl hs) lemma is_closed_omega_limit : is_closed (ω f ϕ s) := is_closed_Inter $ λ u, is_closed_Inter $ λ hu, is_closed_closure lemma maps_to_omega_limit' {α' β' : Type*} [topological_space β'] {f : filter τ} {ϕ : τ → α → β} {ϕ' : τ → α' → β'} {ga : α → α'} {s' : set α'} (hs : maps_to ga s s') {gb : β → β'} (hg : ∀ᶠ t in f, eq_on (gb ∘ (ϕ t)) (ϕ' t ∘ ga) s) (hgc : continuous gb) : maps_to gb (ω f ϕ s) (ω f ϕ' s') := begin simp only [omega_limit_def, mem_Inter, maps_to], intros y hy u hu, refine map_mem_closure hgc (hy _ (inter_mem hu hg)) (forall_image2_iff.2 $ λ t ht x hx, _), calc gb (ϕ t x) = ϕ' t (ga x) : ht.2 hx ... ∈ image2 ϕ' u s' : mem_image2_of_mem ht.1 (hs hx) end lemma maps_to_omega_limit {α' β' : Type*} [topological_space β'] {f : filter τ} {ϕ : τ → α → β} {ϕ' : τ → α' → β'} {ga : α → α'} {s' : set α'} (hs : maps_to ga s s') {gb : β → β'} (hg : ∀ t x, gb (ϕ t x) = ϕ' t (ga x)) (hgc : continuous gb) : maps_to gb (ω f ϕ s) (ω f ϕ' s') := maps_to_omega_limit' _ hs (eventually_of_forall $ λ t x hx, hg t x) hgc lemma omega_limit_image_eq {α' : Type*} (ϕ : τ → α' → β) (f : filter τ) (g : α → α') : ω f ϕ (g '' s) = ω f (λ t x, ϕ t (g x)) s := by simp only [omega_limit, image2_image_right] lemma omega_limit_preimage_subset {α' : Type*} (ϕ : τ → α' → β) (s : set α') (f : filter τ) (g : α → α') : ω f (λ t x, ϕ t (g x)) (g ⁻¹' s) ⊆ ω f ϕ s := maps_to_omega_limit _ (maps_to_preimage _ _) (λ t x, rfl) continuous_id /-! ### Equivalent definitions of the omega limit The next few lemmas are various versions of the property characterising ω-limits: -/ /-- An element `y` is in the ω-limit set of `s` w.r.t. `f` if the preimages of an arbitrary neighbourhood of `y` frequently (w.r.t. `f`) intersects of `s`. -/ lemma mem_omega_limit_iff_frequently (y : β) : y ∈ ω f ϕ s ↔ ∀ n ∈ 𝓝 y, ∃ᶠ t in f, (s ∩ ϕ t ⁻¹' n).nonempty := begin simp_rw [frequently_iff, omega_limit_def, mem_Inter, mem_closure_iff_nhds], split, { intros h _ hn _ hu, rcases h _ hu _ hn with ⟨_, _, _, _, ht, hx, hϕtx⟩, exact ⟨_, ht, _, hx, by rwa [mem_preimage, hϕtx]⟩, }, { intros h _ hu _ hn, rcases h _ hn hu with ⟨_, ht, _, hx, hϕtx⟩, exact ⟨_, hϕtx, _, _, ht, hx, rfl⟩ } end /-- An element `y` is in the ω-limit set of `s` w.r.t. `f` if the forward images of `s` frequently (w.r.t. `f`) intersect arbitrary neighbourhoods of `y`. -/ lemma mem_omega_limit_iff_frequently₂ (y : β) : y ∈ ω f ϕ s ↔ ∀ n ∈ 𝓝 y, ∃ᶠ t in f, (ϕ t '' s ∩ n).nonempty := by simp_rw [mem_omega_limit_iff_frequently, image_inter_nonempty_iff] /-- An element `y` is in the ω-limit of `x` w.r.t. `f` if the forward images of `x` frequently (w.r.t. `f`) falls within an arbitrary neighbourhood of `y`. -/ lemma mem_omega_limit_singleton_iff_map_cluster_point (x : α) (y : β) : y ∈ ω f ϕ {x} ↔ map_cluster_pt y f (λ t, ϕ t x) := by simp_rw [mem_omega_limit_iff_frequently, map_cluster_pt_iff, singleton_inter_nonempty, mem_preimage] /-! ### Set operations and omega limits -/ lemma omega_limit_inter : ω f ϕ (s₁ ∩ s₂) ⊆ ω f ϕ s₁ ∩ ω f ϕ s₂ := subset_inter (omega_limit_mono_right _ _ (inter_subset_left _ _)) (omega_limit_mono_right _ _(inter_subset_right _ _)) lemma omega_limit_Inter (p : ι → set α) : ω f ϕ (⋂ i, p i) ⊆ ⋂ i, ω f ϕ (p i) := subset_Inter $ λ i, omega_limit_mono_right _ _ (Inter_subset _ _) lemma omega_limit_union : ω f ϕ (s₁ ∪ s₂) = ω f ϕ s₁ ∪ ω f ϕ s₂ := begin ext y, split, { simp only [mem_union, mem_omega_limit_iff_frequently, union_inter_distrib_right, union_nonempty, frequently_or_distrib], contrapose!, simp only [not_frequently, not_nonempty_iff_eq_empty, ← subset_empty_iff], rintro ⟨⟨n₁, hn₁, h₁⟩, ⟨n₂, hn₂, h₂⟩⟩, refine ⟨n₁ ∩ n₂, inter_mem hn₁ hn₂, h₁.mono $ λ t, _, h₂.mono $ λ t, _⟩, exacts [subset.trans $ inter_subset_inter_right _ $ preimage_mono $ inter_subset_left _ _, subset.trans $ inter_subset_inter_right _ $ preimage_mono $ inter_subset_right _ _] }, { rintros (hy|hy), exacts [omega_limit_mono_right _ _ (subset_union_left _ _) hy, omega_limit_mono_right _ _ (subset_union_right _ _) hy] }, end lemma omega_limit_Union (p : ι → set α) : (⋃ i, ω f ϕ (p i)) ⊆ ω f ϕ ⋃ i, p i := by { rw Union_subset_iff, exact λ i, omega_limit_mono_right _ _ (subset_Union _ _)} /-! Different expressions for omega limits, useful for rewrites. In particular, one may restrict the intersection to sets in `f` which are subsets of some set `v` also in `f`. -/ lemma omega_limit_eq_Inter : ω f ϕ s = ⋂ u : ↥f.sets, closure (image2 ϕ u s) := bInter_eq_Inter _ _ lemma omega_limit_eq_bInter_inter {v : set τ} (hv : v ∈ f) : ω f ϕ s = ⋂ u ∈ f, closure (image2 ϕ (u ∩ v) s) := subset.antisymm (Inter₂_mono' $ λ u hu, ⟨u ∩ v, inter_mem hu hv, subset.rfl⟩) (Inter₂_mono $ λ u hu, closure_mono $ image2_subset (inter_subset_left _ _) subset.rfl) lemma omega_limit_eq_Inter_inter {v : set τ} (hv : v ∈ f) : ω f ϕ s = ⋂ (u : ↥f.sets), closure (image2 ϕ (u ∩ v) s) := by { rw omega_limit_eq_bInter_inter _ _ _ hv, apply bInter_eq_Inter } lemma omega_limit_subset_closure_fw_image {u : set τ} (hu : u ∈ f) : ω f ϕ s ⊆ closure (image2 ϕ u s) := begin rw omega_limit_eq_Inter, intros _ hx, rw mem_Inter at hx, exact hx ⟨u, hu⟩, end /-! ### `ω-limits and compactness -/ /-- A set is eventually carried into any open neighbourhood of its ω-limit: if `c` is a compact set such that `closure {ϕ t x | t ∈ v, x ∈ s} ⊆ c` for some `v ∈ f` and `n` is an open neighbourhood of `ω f ϕ s`, then for some `u ∈ f` we have `closure {ϕ t x | t ∈ u, x ∈ s} ⊆ n`. -/ lemma eventually_closure_subset_of_is_compact_absorbing_of_is_open_of_omega_limit_subset' {c : set β} (hc₁ : is_compact c) (hc₂ : ∃ v ∈ f, closure (image2 ϕ v s) ⊆ c) {n : set β} (hn₁ : is_open n) (hn₂ : ω f ϕ s ⊆ n) : ∃ u ∈ f, closure (image2 ϕ u s) ⊆ n := begin rcases hc₂ with ⟨v, hv₁, hv₂⟩, let k := closure (image2 ϕ v s), have hk : is_compact (k \ n) := is_compact.diff (compact_of_is_closed_subset hc₁ is_closed_closure hv₂) hn₁, let j := λ u, (closure (image2 ϕ (u ∩ v) s))ᶜ, have hj₁ : ∀ u ∈ f, is_open (j u), from λ _ _, (is_open_compl_iff.mpr is_closed_closure), have hj₂ : k \ n ⊆ ⋃ u ∈ f, j u, begin have : (⋃ u ∈ f, j u) = ⋃ (u : ↥f.sets), j u, from bUnion_eq_Union _ _, rw [this, diff_subset_comm, diff_Union], rw omega_limit_eq_Inter_inter _ _ _ hv₁ at hn₂, simp_rw diff_compl, rw ←inter_Inter, exact subset.trans (inter_subset_right _ _) hn₂, end, rcases hk.elim_finite_subcover_image hj₁ hj₂ with ⟨g, hg₁ : ∀ u ∈ g, u ∈ f, hg₂, hg₃⟩, let w := (⋂ u ∈ g, u) ∩ v, have hw₂ : w ∈ f, by simpa *, have hw₃ : k \ n ⊆ (closure (image2 ϕ w s))ᶜ, from calc k \ n ⊆ ⋃ u ∈ g, j u : hg₃ ... ⊆ (closure (image2 ϕ w s))ᶜ : begin simp only [Union_subset_iff, compl_subset_compl], intros u hu, mono* using [w], exact Inter_subset_of_subset u (Inter_subset_of_subset hu subset.rfl), end, have hw₄ : kᶜ ⊆ (closure (image2 ϕ w s))ᶜ, begin rw compl_subset_compl, calc closure (image2 ϕ w s) ⊆ _ : closure_mono (image2_subset (inter_subset_right _ _) subset.rfl) end, have hnc : nᶜ ⊆ (k \ n) ∪ kᶜ, by rw [union_comm, ←inter_subset, diff_eq, inter_comm], have hw : closure (image2 ϕ w s) ⊆ n, from compl_subset_compl.mp (subset.trans hnc (union_subset hw₃ hw₄)), exact ⟨_, hw₂, hw⟩ end /-- A set is eventually carried into any open neighbourhood of its ω-limit: if `c` is a compact set such that `closure {ϕ t x | t ∈ v, x ∈ s} ⊆ c` for some `v ∈ f` and `n` is an open neighbourhood of `ω f ϕ s`, then for some `u ∈ f` we have `closure {ϕ t x | t ∈ u, x ∈ s} ⊆ n`. -/ lemma eventually_closure_subset_of_is_compact_absorbing_of_is_open_of_omega_limit_subset [t2_space β] {c : set β} (hc₁ : is_compact c) (hc₂ : ∀ᶠ t in f, maps_to (ϕ t) s c) {n : set β} (hn₁ : is_open n) (hn₂ : ω f ϕ s ⊆ n) : ∃ u ∈ f, closure (image2 ϕ u s) ⊆ n := eventually_closure_subset_of_is_compact_absorbing_of_is_open_of_omega_limit_subset' f ϕ _ hc₁ ⟨_, hc₂, closure_minimal (image2_subset_iff.2 (λ t, id)) hc₁.is_closed⟩ hn₁ hn₂ lemma eventually_maps_to_of_is_compact_absorbing_of_is_open_of_omega_limit_subset [t2_space β] {c : set β} (hc₁ : is_compact c) (hc₂ : ∀ᶠ t in f, maps_to (ϕ t) s c) {n : set β} (hn₁ : is_open n) (hn₂ : ω f ϕ s ⊆ n) : ∀ᶠ t in f, maps_to (ϕ t) s n := begin rcases eventually_closure_subset_of_is_compact_absorbing_of_is_open_of_omega_limit_subset f ϕ s hc₁ hc₂ hn₁ hn₂ with ⟨u, hu_mem, hu⟩, refine mem_of_superset hu_mem (λ t ht x hx, _), exact hu (subset_closure $ mem_image2_of_mem ht hx) end lemma eventually_closure_subset_of_is_open_of_omega_limit_subset [compact_space β] {v : set β} (hv₁ : is_open v) (hv₂ : ω f ϕ s ⊆ v) : ∃ u ∈ f, closure (image2 ϕ u s) ⊆ v := eventually_closure_subset_of_is_compact_absorbing_of_is_open_of_omega_limit_subset' _ _ _ compact_univ ⟨univ, univ_mem, subset_univ _⟩ hv₁ hv₂ lemma eventually_maps_to_of_is_open_of_omega_limit_subset [compact_space β] {v : set β} (hv₁ : is_open v) (hv₂ : ω f ϕ s ⊆ v) : ∀ᶠ t in f, maps_to (ϕ t) s v := begin rcases eventually_closure_subset_of_is_open_of_omega_limit_subset f ϕ s hv₁ hv₂ with ⟨u, hu_mem, hu⟩, refine mem_of_superset hu_mem (λ t ht x hx, _), exact hu (subset_closure $ mem_image2_of_mem ht hx) end /-- The ω-limit of a nonempty set w.r.t. a nontrivial filter is nonempty. -/ lemma nonempty_omega_limit_of_is_compact_absorbing [ne_bot f] {c : set β} (hc₁ : is_compact c) (hc₂ : ∃ v ∈ f, closure (image2 ϕ v s) ⊆ c) (hs : s.nonempty) : (ω f ϕ s).nonempty := begin rcases hc₂ with ⟨v, hv₁, hv₂⟩, rw omega_limit_eq_Inter_inter _ _ _ hv₁, apply is_compact.nonempty_Inter_of_directed_nonempty_compact_closed, { rintro ⟨u₁, hu₁⟩ ⟨u₂, hu₂⟩, use ⟨u₁ ∩ u₂, inter_mem hu₁ hu₂⟩, split, all_goals { exact closure_mono (image2_subset (inter_subset_inter_left _ (by simp)) subset.rfl) }}, { intro u, have hn : (image2 ϕ (u ∩ v) s).nonempty, from nonempty.image2 (nonempty_of_mem (inter_mem u.prop hv₁)) hs, exact hn.mono subset_closure }, { intro _, apply compact_of_is_closed_subset hc₁ is_closed_closure, calc _ ⊆ closure (image2 ϕ v s) : closure_mono (image2_subset (inter_subset_right _ _) subset.rfl) ... ⊆ c : hv₂ }, { exact λ _, is_closed_closure }, end lemma nonempty_omega_limit [compact_space β] [ne_bot f] (hs : s.nonempty) : (ω f ϕ s).nonempty := nonempty_omega_limit_of_is_compact_absorbing _ _ _ compact_univ ⟨univ, univ_mem, subset_univ _⟩ hs end omega_limit /-! ### ω-limits of Flows by a Monoid -/ namespace flow variables {τ : Type*} [topological_space τ] [add_monoid τ] [has_continuous_add τ] {α : Type*} [topological_space α] (f : filter τ) (ϕ : flow τ α) (s : set α) open_locale omega_limit lemma is_invariant_omega_limit (hf : ∀ t, tendsto ((+) t) f f) : is_invariant ϕ (ω f ϕ s) := begin refine λ t, maps_to.mono_right _ (omega_limit_subset_of_tendsto ϕ s (hf t)), exact maps_to_omega_limit _ (maps_to_id _) (λ t' x, (ϕ.map_add _ _ _).symm) (continuous_const.flow ϕ continuous_id) end lemma omega_limit_image_subset (t : τ) (ht : tendsto (+ t) f f) : ω f ϕ (ϕ t '' s) ⊆ ω f ϕ s := begin simp only [omega_limit_image_eq, ← map_add], exact omega_limit_subset_of_tendsto ϕ s ht end end flow /-! ### ω-limits of Flows by a Group -/ namespace flow variables {τ : Type*} [topological_space τ] [add_comm_group τ] [topological_add_group τ] {α : Type*} [topological_space α] (f : filter τ) (ϕ : flow τ α) (s : set α) open_locale omega_limit /-- the ω-limit of a forward image of `s` is the same as the ω-limit of `s`. -/ @[simp] lemma omega_limit_image_eq (hf : ∀ t, tendsto (+ t) f f) (t : τ) : ω f ϕ (ϕ t '' s) = ω f ϕ s := subset.antisymm (omega_limit_image_subset _ _ _ _ (hf t)) $ calc ω f ϕ s = ω f ϕ (ϕ (-t) '' (ϕ t '' s)) : by simp [image_image, ← map_add] ... ⊆ ω f ϕ (ϕ t '' s) : omega_limit_image_subset _ _ _ _ (hf _) lemma omega_limit_omega_limit (hf : ∀ t, tendsto ((+) t) f f) : ω f ϕ (ω f ϕ s) ⊆ ω f ϕ s := begin simp only [subset_def, mem_omega_limit_iff_frequently₂, frequently_iff], intros _ h, rintro n hn u hu, rcases mem_nhds_iff.mp hn with ⟨o, ho₁, ho₂, ho₃⟩, rcases h o (is_open.mem_nhds ho₂ ho₃) hu with ⟨t, ht₁, ht₂⟩, have l₁ : (ω f ϕ s ∩ o).nonempty, from ht₂.mono (inter_subset_inter_left _ ((is_invariant_iff_image _ _).mp (is_invariant_omega_limit _ _ _ hf) _)), have l₂ : ((closure (image2 ϕ u s)) ∩ o).nonempty := l₁.mono (λ b hb, ⟨omega_limit_subset_closure_fw_image _ _ _ hu hb.1, hb.2⟩), have l₃ : (o ∩ image2 ϕ u s).nonempty, begin rcases l₂ with ⟨b, hb₁, hb₂⟩, exact mem_closure_iff_nhds.mp hb₁ o (is_open.mem_nhds ho₂ hb₂) end, rcases l₃ with ⟨ϕra, ho, ⟨_, _, hr, ha, hϕra⟩⟩, exact ⟨_, hr, ϕra, ⟨_, ha, hϕra⟩, ho₁ ho⟩, end end flow
35a506d05c9902c14687a20a5153c8851ae1f0aa
3d2a7f1582fe5bae4d0bdc2fe86e997521239a65
/spatial-reasoning/spatial-reasoning-problem-06.lean
27afe444904ae0fa256d5efa25435c0122208c30
[]
no_license
own-pt/common-sense-lean
e4fa643ae010459de3d1bf673be7cbc7062563c9
f672210aecb4172f5bae265e43e6867397e13b1c
refs/heads/master
1,622,065,660,261
1,589,487,533,000
1,589,487,533,000
254,167,782
3
2
null
1,589,487,535,000
1,586,370,214,000
Lean
UTF-8
Lean
false
false
1,777
lean
/- Spatial Reasoning Problem 06 -/ /- It can be found at: SpatialQs.txt -/ -- (6) A bookcase is on the floor. A book is on the bookcase. Is the book higher than the floor? universe V constant U : Type constants Right Left Book Furniture Floor On TransitivePositionalAttribute PositionalAttribute Above : U constant ins : U → U → Prop constant located : U → U → Prop constant subclass : U → U → Prop constant orientation: U → U → U → Prop /- (exists (?B ?F ?BOOK) (and (instance ?BOOK Book) (instance ?B Furniture) (instance ?F Floor) (orientation ?B ?F On) (orientation ?BOOK ?B On))) -/ axiom a1 : ∃ b f book : U , ins book Book ∧ ins b Furniture ∧ ins f Floor ∧ orientation b f On ∧ orientation book b On /- (subclass TransitivePositionalAttribute PositionalAttribute) -/ axiom a2 : subclass TransitivePositionalAttribute PositionalAttribute /- (=> (and (orientation ?A ?B ?P) (orientation ?B ?C ?P) (instance ?P TransitivePositionalAttribute)) (orientation ?A ?C ?P)) -/ axiom a3 : ∀ a b c p : U, (orientation a b p ∧ orientation b c p ∧ ins p TransitivePositionalAttribute) → orientation a c p /- (=> (and (orientation ?A ?B On) (orientation ?B ?C On)) (orientation ?A ?C Above)) -/ axiom a4 : ∀ a b c : U, orientation a b On ∧ orientation b c On → orientation a c Above theorem book_above_floor : ∃ (book : U) (f : U), orientation book f Above := begin apply exists.elim a1, assume b h1, apply exists.elim h1, assume f h2, apply exists.elim h2, assume book h3, apply exists.intro book, apply exists.intro f, apply a4 book b f, split, exact h3.right.right.right.right, exact h3.right.right.right.left end
fa28347e79697ab6e7452bf66b458118788e7a80
da23b545e1653cafd4ab88b3a42b9115a0b1355f
/test/intro_at_least_one.lean
dfe7d8eb701e10916d60585ee26da2f532d42d43
[]
no_license
minchaowu/lean-tidy
137f5058896e0e81dae84bf8d02b74101d21677a
2d4c52d66cf07c59f8746e405ba861b4fa0e3835
refs/heads/master
1,585,283,406,120
1,535,094,033,000
1,535,094,033,000
145,945,792
0
0
null
null
null
null
UTF-8
Lean
false
false
343
lean
import tidy.intro_at_least_one import tidy.force example : ∀ x : ℕ, ∀ y : ℕ, true := begin intro_at_least_one, trivial, end example : true := begin success_if_fail { intro_at_least_one }, trivial, end def f := ∀ x : ℕ, true example : f := begin success_if_fail { force `[intros] }, intro_at_least_one, trivial end
8259d3a98d3686d9d5187d6a0ac6a6227613b0a4
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/algebra/algebra/tower.lean
e57cbb3a5fed9d50dee5e2bda6234baa79e8bd63
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,854
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.algebra.subalgebra /-! # Towers of algebras In this file we prove basic facts about towers of algebra. An algebra tower A/S/R is expressed by having instances of `algebra A S`, `algebra R S`, `algebra R A` and `is_scalar_tower R S A`, the later asserting the compatibility condition `(r • s) • a = r • (s • a)`. An important definition is `to_alg_hom R S A`, the canonical `R`-algebra homomorphism `S →ₐ[R] A`. -/ universes u v w u₁ v₁ variables (R : Type u) (S : Type v) (A : Type w) (B : Type u₁) (M : Type v₁) namespace algebra variables [comm_semiring R] [semiring A] [algebra R A] variables [add_comm_monoid M] [semimodule R M] [semimodule A M] [is_scalar_tower R A M] variables {A} /-- The `R`-algebra morphism `A → End (M)` corresponding to the representation of the algebra `A` on the `R`-module `M`. -/ def lsmul : A →ₐ[R] module.End R M := { map_one' := by { ext m, exact one_smul A m }, map_mul' := by { intros a b, ext c, exact smul_assoc a b c }, map_zero' := by { ext m, exact zero_smul A m }, commutes' := by { intro r, ext m, exact algebra_map_smul A r m }, .. (show A →ₗ[R] M →ₗ[R] M, from linear_map.mk₂ R (•) (λ x y z, add_smul x y z) (λ c x y, smul_assoc c x y) (λ x y z, smul_add x y z) (λ c x y, smul_algebra_smul_comm c x y)) } @[simp] lemma lsmul_coe (a : A) : (lsmul R M a : M → M) = (•) a := rfl @[simp] lemma lmul_algebra_map (x : R) : lmul R A (algebra_map R A x) = algebra.lsmul R A x := eq.symm $ linear_map.ext $ smul_def'' x end algebra namespace is_scalar_tower section semimodule variables [comm_semiring R] [semiring A] [algebra R A] variables [add_comm_monoid M] [semimodule R M] [semimodule A M] [is_scalar_tower R A M] variables {R} (A) {M} theorem algebra_map_smul (r : R) (x : M) : algebra_map R A r • x = r • x := by rw [algebra.algebra_map_eq_smul_one, smul_assoc, one_smul] end semimodule section semiring variables [comm_semiring R] [comm_semiring S] [semiring A] [semiring B] variables [algebra R S] [algebra S A] [algebra S B] variables {R S A} theorem of_algebra_map_eq [algebra R A] (h : ∀ x, algebra_map R A x = algebra_map S A (algebra_map R S x)) : is_scalar_tower R S A := ⟨λ x y z, by simp_rw [algebra.smul_def, ring_hom.map_mul, mul_assoc, h]⟩ /-- See note [partially-applied ext lemmas]. -/ theorem of_algebra_map_eq' [algebra R A] (h : algebra_map R A = (algebra_map S A).comp (algebra_map R S)) : is_scalar_tower R S A := of_algebra_map_eq $ ring_hom.ext_iff.1 h variables (R S A) instance subalgebra (S₀ : subalgebra R S) : is_scalar_tower S₀ S A := of_algebra_map_eq $ λ x, rfl variables [algebra R A] [algebra R B] variables [is_scalar_tower R S A] [is_scalar_tower R S B] theorem algebra_map_eq : algebra_map R A = (algebra_map S A).comp (algebra_map R S) := ring_hom.ext $ λ x, by simp_rw [ring_hom.comp_apply, algebra.algebra_map_eq_smul_one, smul_assoc, one_smul] theorem algebra_map_apply (x : R) : algebra_map R A x = algebra_map S A (algebra_map R S x) := by rw [algebra_map_eq R S A, ring_hom.comp_apply] instance subalgebra' (S₀ : subalgebra R S) : is_scalar_tower R S₀ A := @is_scalar_tower.of_algebra_map_eq R S₀ A _ _ _ _ _ _ $ λ _, (is_scalar_tower.algebra_map_apply R S A _ : _) @[ext] lemma algebra.ext {S : Type u} {A : Type v} [comm_semiring S] [semiring A] (h1 h2 : algebra S A) (h : ∀ {r : S} {x : A}, (by haveI := h1; exact r • x) = r • x) : h1 = h2 := begin unfreezingI { cases h1 with f1 g1 h11 h12, cases h2 with f2 g2 h21 h22, cases f1, cases f2, congr', { ext r x, exact h }, ext r, erw [← mul_one (g1 r), ← h12, ← mul_one (g2 r), ← h22, h], refl } end variables (R S A) theorem algebra_comap_eq : algebra.comap.algebra R S A = ‹_› := algebra.ext _ _ $ λ x (z : A), calc algebra_map R S x • z = (x • 1 : S) • z : by rw algebra.algebra_map_eq_smul_one ... = x • (1 : S) • z : by rw smul_assoc ... = (by exact x • z : A) : by rw one_smul /-- In a tower, the canonical map from the middle element to the top element is an algebra homomorphism over the bottom element. -/ def to_alg_hom : S →ₐ[R] A := { commutes' := λ _, (algebra_map_apply _ _ _ _).symm, .. algebra_map S A } lemma to_alg_hom_apply (y : S) : to_alg_hom R S A y = algebra_map S A y := rfl @[simp] lemma coe_to_alg_hom : ↑(to_alg_hom R S A) = algebra_map S A := ring_hom.ext $ λ _, rfl @[simp] lemma coe_to_alg_hom' : (to_alg_hom R S A : S → A) = algebra_map S A := rfl variables (R) {S A B} instance right : is_scalar_tower S A A := ⟨λ x y z, by rw [smul_eq_mul, smul_eq_mul, algebra.smul_mul_assoc]⟩ instance comap {R S A : Type*} [comm_semiring R] [comm_semiring S] [semiring A] [algebra R S] [algebra S A] : is_scalar_tower R S (algebra.comap R S A) := of_algebra_map_eq $ λ x, rfl -- conflicts with is_scalar_tower.subalgebra @[priority 999] instance subsemiring (U : subsemiring S) : is_scalar_tower U S A := of_algebra_map_eq $ λ x, rfl section local attribute [instance] algebra.of_is_subring subset.comm_ring -- conflicts with is_scalar_tower.subalgebra @[priority 999] instance subring {S A : Type*} [comm_ring S] [ring A] [algebra S A] (U : set S) [is_subring U] : is_scalar_tower U S A := of_algebra_map_eq $ λ x, rfl end @[nolint instance_priority] instance of_ring_hom {R A B : Type*} [comm_semiring R] [comm_semiring A] [comm_semiring B] [algebra R A] [algebra R B] (f : A →ₐ[R] B) : @is_scalar_tower R A B _ (f.to_ring_hom.to_algebra.to_has_scalar) _ := by { letI := (f : A →+* B).to_algebra, exact of_algebra_map_eq (λ x, (f.commutes x).symm) } end semiring section division_ring variables [field R] [division_ring S] [algebra R S] [char_zero R] [char_zero S] instance rat : is_scalar_tower ℚ R S := of_algebra_map_eq $ λ x, ((algebra_map R S).map_rat_cast x).symm end division_ring end is_scalar_tower section homs variables [comm_semiring R] [comm_semiring S] [semiring A] [semiring B] variables [algebra R S] [algebra S A] [algebra S B] variables [algebra R A] [algebra R B] variables [is_scalar_tower R S A] [is_scalar_tower R S B] variables (R) {A S B} open is_scalar_tower namespace alg_hom /-- R ⟶ S induces S-Alg ⥤ R-Alg -/ def restrict_scalars (f : A →ₐ[S] B) : A →ₐ[R] B := { commutes' := λ r, by { rw [algebra_map_apply R S A, algebra_map_apply R S B], exact f.commutes (algebra_map R S r) }, .. (f : A →+* B) } lemma restrict_scalars_apply (f : A →ₐ[S] B) (x : A) : f.restrict_scalars R x = f x := rfl @[simp] lemma coe_restrict_scalars (f : A →ₐ[S] B) : (f.restrict_scalars R : A →+* B) = f := rfl @[simp] lemma coe_restrict_scalars' (f : A →ₐ[S] B) : (restrict_scalars R f : A → B) = f := rfl end alg_hom namespace alg_equiv /-- R ⟶ S induces S-Alg ⥤ R-Alg -/ def restrict_scalars (f : A ≃ₐ[S] B) : A ≃ₐ[R] B := { commutes' := λ r, by { rw [algebra_map_apply R S A, algebra_map_apply R S B], exact f.commutes (algebra_map R S r) }, .. (f : A ≃+* B) } lemma restrict_scalars_apply (f : A ≃ₐ[S] B) (x : A) : f.restrict_scalars R x = f x := rfl @[simp] lemma coe_restrict_scalars (f : A ≃ₐ[S] B) : (f.restrict_scalars R : A ≃+* B) = f := rfl @[simp] lemma coe_restrict_scalars' (f : A ≃ₐ[S] B) : (restrict_scalars R f : A → B) = f := rfl end alg_equiv end homs namespace subalgebra open is_scalar_tower section semiring variables (R) {S A} [comm_semiring R] [comm_semiring S] [semiring A] variables [algebra R S] [algebra S A] [algebra R A] [is_scalar_tower R S A] /-- If A/S/R is a tower of algebras then the `res`triction of a S-subalgebra of A is an R-subalgebra of A. -/ def res (U : subalgebra S A) : subalgebra R A := { algebra_map_mem' := λ x, by { rw algebra_map_apply R S A, exact U.algebra_map_mem _ }, .. U } @[simp] lemma res_top : res R (⊤ : subalgebra S A) = ⊤ := algebra.eq_top_iff.2 $ λ _, show _ ∈ (⊤ : subalgebra S A), from algebra.mem_top @[simp] lemma mem_res {U : subalgebra S A} {x : A} : x ∈ res R U ↔ x ∈ U := iff.rfl lemma res_inj {U V : subalgebra S A} (H : res R U = res R V) : U = V := ext $ λ x, by rw [← mem_res R, H, mem_res] /-- Produces a map from `subalgebra.under`. -/ def of_under {R A B : Type*} [comm_semiring R] [comm_semiring A] [semiring B] [algebra R A] [algebra R B] (S : subalgebra R A) (U : subalgebra S A) [algebra S B] [is_scalar_tower R S B] (f : U →ₐ[S] B) : S.under U →ₐ[R] B := { commutes' := λ r, (f.commutes (algebra_map R S r)).trans (algebra_map_apply R S B r).symm, .. f } end semiring end subalgebra namespace is_scalar_tower open subalgebra variables [comm_semiring R] [comm_semiring S] [comm_semiring A] variables [algebra R S] [algebra S A] [algebra R A] [is_scalar_tower R S A] theorem range_under_adjoin (t : set A) : (to_alg_hom R S A).range.under (algebra.adjoin _ t) = res R (algebra.adjoin S t) := subalgebra.ext $ λ z, show z ∈ subsemiring.closure (set.range (algebra_map (to_alg_hom R S A).range A) ∪ t : set A) ↔ z ∈ subsemiring.closure (set.range (algebra_map S A) ∪ t : set A), from suffices set.range (algebra_map (to_alg_hom R S A).range A) = set.range (algebra_map S A), by rw this, by { ext z, exact ⟨λ ⟨⟨x, y, _, h1⟩, h2⟩, ⟨y, h2 ▸ h1⟩, λ ⟨y, hy⟩, ⟨⟨z, y, set.mem_univ _, hy⟩, rfl⟩⟩ } end is_scalar_tower section semiring variables {R S A} variables [comm_semiring R] [semiring S] [add_comm_monoid A] variables [algebra R S] [semimodule S A] [semimodule R A] [is_scalar_tower R S A] namespace submodule open is_scalar_tower theorem smul_mem_span_smul_of_mem {s : set S} {t : set A} {k : S} (hks : k ∈ span R s) {x : A} (hx : x ∈ t) : k • x ∈ span R (s • t) := span_induction hks (λ c hc, subset_span $ set.mem_smul.2 ⟨c, x, hc, hx, rfl⟩) (by { rw zero_smul, exact zero_mem _ }) (λ c₁ c₂ ih₁ ih₂, by { rw add_smul, exact add_mem _ ih₁ ih₂ }) (λ b c hc, by { rw is_scalar_tower.smul_assoc, exact smul_mem _ _ hc }) theorem smul_mem_span_smul {s : set S} (hs : span R s = ⊤) {t : set A} {k : S} {x : A} (hx : x ∈ span R t) : k • x ∈ span R (s • t) := span_induction hx (λ x hx, smul_mem_span_smul_of_mem (hs.symm ▸ mem_top) hx) (by { rw smul_zero, exact zero_mem _ }) (λ x y ihx ihy, by { rw smul_add, exact add_mem _ ihx ihy }) (λ c x hx, smul_comm c k x ▸ smul_mem _ _ hx) theorem smul_mem_span_smul' {s : set S} (hs : span R s = ⊤) {t : set A} {k : S} {x : A} (hx : x ∈ span R (s • t)) : k • x ∈ span R (s • t) := span_induction hx (λ x hx, let ⟨p, q, hp, hq, hpq⟩ := set.mem_smul.1 hx in by { rw [← hpq, smul_smul], exact smul_mem_span_smul_of_mem (hs.symm ▸ mem_top) hq }) (by { rw smul_zero, exact zero_mem _ }) (λ x y ihx ihy, by { rw smul_add, exact add_mem _ ihx ihy }) (λ c x hx, smul_comm c k x ▸ smul_mem _ _ hx) theorem span_smul {s : set S} (hs : span R s = ⊤) (t : set A) : span R (s • t) = (span S t).restrict_scalars R := le_antisymm (span_le.2 $ λ x hx, let ⟨p, q, hps, hqt, hpqx⟩ := set.mem_smul.1 hx in hpqx ▸ (span S t).smul_mem p (subset_span hqt)) $ λ p hp, span_induction hp (λ x hx, one_smul S x ▸ smul_mem_span_smul hs (subset_span hx)) (zero_mem _) (λ _ _, add_mem _) (λ k x hx, smul_mem_span_smul' hs hx) end submodule end semiring section ring namespace algebra variables [comm_semiring R] [ring A] [algebra R A] variables [add_comm_group M] [module A M] [semimodule R M] [is_scalar_tower R A M] lemma lsmul_injective [no_zero_smul_divisors A M] {x : A} (hx : x ≠ 0) : function.injective (lsmul R M x) := smul_injective hx end algebra end ring
2d20f93e72c020f2caa21ac5ca9492ec839d3ed6
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/equiv/transfer_instance.lean
18f6b5e8a4d1d2f66c74c99270dae3162161d7e3
[ "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
13,520
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import data.equiv.basic import algebra.field import algebra.module import algebra.algebra.basic import algebra.group.type_tags import ring_theory.ideal.basic /-! # Transfer algebraic structures across `equiv`s In this file we prove theorems of the following form: if `β` has a group structure and `α ≃ β` then `α` has a group structure, and similarly for monoids, semigroups, rings, integral domains, fields and so on. Note that most of these constructions can also be obtained using the `transport` tactic. ## Tags equiv, group, ring, field, module, algebra -/ universes u v variables {α : Type u} {β : Type v} namespace equiv section instances variables (e : α ≃ β) /-- Transfer `has_one` across an `equiv` -/ @[to_additive "Transfer `has_zero` across an `equiv`"] protected def has_one [has_one β] : has_one α := ⟨e.symm 1⟩ @[to_additive] lemma one_def [has_one β] : @has_one.one _ (equiv.has_one e) = e.symm 1 := rfl /-- Transfer `has_mul` across an `equiv` -/ @[to_additive "Transfer `has_add` across an `equiv`"] protected def has_mul [has_mul β] : has_mul α := ⟨λ x y, e.symm (e x * e y)⟩ @[to_additive] lemma mul_def [has_mul β] (x y : α) : @has_mul.mul _ (equiv.has_mul e) x y = e.symm (e x * e y) := rfl /-- Transfer `has_div` across an `equiv` -/ @[to_additive "Transfer `has_sub` across an `equiv`"] protected def has_div [has_div β] : has_div α := ⟨λ x y, e.symm (e x / e y)⟩ @[to_additive] lemma div_def [has_div β] (x y : α) : @has_div.div _ (equiv.has_div e) x y = e.symm (e x / e y) := rfl /-- Transfer `has_inv` across an `equiv` -/ @[to_additive "Transfer `has_neg` across an `equiv`"] protected def has_inv [has_inv β] : has_inv α := ⟨λ x, e.symm (e x)⁻¹⟩ @[to_additive] lemma inv_def [has_inv β] (x : α) : @has_inv.inv _ (equiv.has_inv e) x = e.symm (e x)⁻¹ := rfl /-- Transfer `has_scalar` across an `equiv` -/ protected def has_scalar {R : Type*} [has_scalar R β] : has_scalar R α := ⟨λ r x, e.symm (r • (e x))⟩ lemma smul_def {R : Type*} [has_scalar R β] (r : R) (x : α) : @has_scalar.smul _ _ (equiv.has_scalar e) r x = e.symm (r • (e x)) := rfl /-- An equivalence `e : α ≃ β` gives a multiplicative equivalence `α ≃* β` where the multiplicative structure on `α` is the one obtained by transporting a multiplicative structure on `β` back along `e`. -/ @[to_additive "An equivalence `e : α ≃ β` gives a additive equivalence `α ≃+ β` where the additive structure on `α` is the one obtained by transporting an additive structure on `β` back along `e`."] def mul_equiv (e : α ≃ β) [has_mul β] : by { letI := equiv.has_mul e, exact α ≃* β } := begin introsI, exact { map_mul' := λ x y, by { apply e.symm.injective, simp, refl, }, ..e } end @[simp, to_additive] lemma mul_equiv_apply (e : α ≃ β) [has_mul β] (a : α) : (mul_equiv e) a = e a := rfl @[to_additive] lemma mul_equiv_symm_apply (e : α ≃ β) [has_mul β] (b : β) : by { letI := equiv.has_mul e, exact (mul_equiv e).symm b = e.symm b } := begin intros, refl, end /-- An equivalence `e : α ≃ β` gives a ring equivalence `α ≃+* β` where the ring structure on `α` is the one obtained by transporting a ring structure on `β` back along `e`. -/ def ring_equiv (e : α ≃ β) [has_add β] [has_mul β] : by { letI := equiv.has_add e, letI := equiv.has_mul e, exact α ≃+* β } := begin introsI, exact { map_add' := λ x y, by { apply e.symm.injective, simp, refl, }, map_mul' := λ x y, by { apply e.symm.injective, simp, refl, }, ..e } end @[simp] lemma ring_equiv_apply (e : α ≃ β) [has_add β] [has_mul β] (a : α) : (ring_equiv e) a = e a := rfl lemma ring_equiv_symm_apply (e : α ≃ β) [has_add β] [has_mul β] (b : β) : by { letI := equiv.has_add e, letI := equiv.has_mul e, exact (ring_equiv e).symm b = e.symm b } := begin intros, refl, end /-- Transfer `semigroup` across an `equiv` -/ @[to_additive "Transfer `add_semigroup` across an `equiv`"] protected def semigroup [semigroup β] : semigroup α := let mul := e.has_mul in by resetI; apply e.injective.semigroup _; intros; exact e.apply_symm_apply _ /-- Transfer `semigroup_with_zero` across an `equiv` -/ protected def semigroup_with_zero [semigroup_with_zero β] : semigroup_with_zero α := let mul := e.has_mul, zero := e.has_zero in by resetI; apply e.injective.semigroup_with_zero _; intros; exact e.apply_symm_apply _ /-- Transfer `comm_semigroup` across an `equiv` -/ @[to_additive "Transfer `add_comm_semigroup` across an `equiv`"] protected def comm_semigroup [comm_semigroup β] : comm_semigroup α := let mul := e.has_mul in by resetI; apply e.injective.comm_semigroup _; intros; exact e.apply_symm_apply _ /-- Transfer `mul_zero_class` across an `equiv` -/ protected def mul_zero_class [mul_zero_class β] : mul_zero_class α := let zero := e.has_zero, mul := e.has_mul in by resetI; apply e.injective.mul_zero_class _; intros; exact e.apply_symm_apply _ /-- Transfer `mul_one_class` across an `equiv` -/ @[to_additive "Transfer `add_zero_class` across an `equiv`"] protected def mul_one_class [mul_one_class β] : mul_one_class α := let one := e.has_one, mul := e.has_mul in by resetI; apply e.injective.mul_one_class _; intros; exact e.apply_symm_apply _ /-- Transfer `mul_zero_one_class` across an `equiv` -/ protected def mul_zero_one_class [mul_zero_one_class β] : mul_zero_one_class α := let zero := e.has_zero, one := e.has_one,mul := e.has_mul in by resetI; apply e.injective.mul_zero_one_class _; intros; exact e.apply_symm_apply _ /-- Transfer `monoid` across an `equiv` -/ @[to_additive "Transfer `add_monoid` across an `equiv`"] protected def monoid [monoid β] : monoid α := let one := e.has_one, mul := e.has_mul in by resetI; apply e.injective.monoid _; intros; exact e.apply_symm_apply _ /-- Transfer `comm_monoid` across an `equiv` -/ @[to_additive "Transfer `add_comm_monoid` across an `equiv`"] protected def comm_monoid [comm_monoid β] : comm_monoid α := let one := e.has_one, mul := e.has_mul in by resetI; apply e.injective.comm_monoid _; intros; exact e.apply_symm_apply _ /-- Transfer `group` across an `equiv` -/ @[to_additive "Transfer `add_group` across an `equiv`"] protected def group [group β] : group α := let one := e.has_one, mul := e.has_mul, inv := e.has_inv, div := e.has_div in by resetI; apply e.injective.group _; intros; exact e.apply_symm_apply _ /-- Transfer `comm_group` across an `equiv` -/ @[to_additive "Transfer `add_comm_group` across an `equiv`"] protected def comm_group [comm_group β] : comm_group α := let one := e.has_one, mul := e.has_mul, inv := e.has_inv, div := e.has_div in by resetI; apply e.injective.comm_group _; intros; exact e.apply_symm_apply _ /-- Transfer `non_unital_non_assoc_semiring` across an `equiv` -/ protected def non_unital_non_assoc_semiring [non_unital_non_assoc_semiring β] : non_unital_non_assoc_semiring α := let zero := e.has_zero, add := e.has_add, mul := e.has_mul in by resetI; apply e.injective.non_unital_non_assoc_semiring _; intros; exact e.apply_symm_apply _ /-- Transfer `non_unital_semiring` across an `equiv` -/ protected def non_unital_semiring [non_unital_semiring β] : non_unital_semiring α := let zero := e.has_zero, add := e.has_add, mul := e.has_mul in by resetI; apply e.injective.non_unital_semiring _; intros; exact e.apply_symm_apply _ /-- Transfer `non_assoc_semiring` across an `equiv` -/ protected def non_assoc_semiring [non_assoc_semiring β] : non_assoc_semiring α := let zero := e.has_zero, add := e.has_add, one := e.has_one, mul := e.has_mul in by resetI; apply e.injective.non_assoc_semiring _; intros; exact e.apply_symm_apply _ /-- Transfer `semiring` across an `equiv` -/ protected def semiring [semiring β] : semiring α := let zero := e.has_zero, add := e.has_add, one := e.has_one, mul := e.has_mul in by resetI; apply e.injective.semiring _; intros; exact e.apply_symm_apply _ /-- Transfer `comm_semiring` across an `equiv` -/ protected def comm_semiring [comm_semiring β] : comm_semiring α := let zero := e.has_zero, add := e.has_add, one := e.has_one, mul := e.has_mul in by resetI; apply e.injective.comm_semiring _; intros; exact e.apply_symm_apply _ /-- Transfer `ring` across an `equiv` -/ protected def ring [ring β] : ring α := let zero := e.has_zero, add := e.has_add, one := e.has_one, mul := e.has_mul, neg := e.has_neg, sub := e.has_sub in by resetI; apply e.injective.ring _; intros; exact e.apply_symm_apply _ /-- Transfer `comm_ring` across an `equiv` -/ protected def comm_ring [comm_ring β] : comm_ring α := let zero := e.has_zero, add := e.has_add, one := e.has_one, mul := e.has_mul, neg := e.has_neg, sub := e.has_sub in by resetI; apply e.injective.comm_ring _; intros; exact e.apply_symm_apply _ /-- Transfer `nonzero` across an `equiv` -/ protected theorem nontrivial [nontrivial β] : nontrivial α := e.surjective.nontrivial /-- Transfer `domain` across an `equiv` -/ protected def domain [domain β] : domain α := let zero := e.has_zero, add := e.has_add, one := e.has_one, mul := e.has_mul, neg := e.has_neg, sub := e.has_sub in by resetI; apply e.injective.domain _; intros; exact e.apply_symm_apply _ /-- Transfer `integral_domain` across an `equiv` -/ protected def integral_domain [integral_domain β] : integral_domain α := let zero := e.has_zero, add := e.has_add, one := e.has_one, mul := e.has_mul, neg := e.has_neg, sub := e.has_sub in by resetI; apply e.injective.integral_domain _; intros; exact e.apply_symm_apply _ /-- Transfer `division_ring` across an `equiv` -/ protected def division_ring [division_ring β] : division_ring α := let zero := e.has_zero, add := e.has_add, one := e.has_one, mul := e.has_mul, neg := e.has_neg, sub := e.has_sub, inv := e.has_inv, div := e.has_div in by resetI; apply e.injective.division_ring _; intros; exact e.apply_symm_apply _ /-- Transfer `field` across an `equiv` -/ protected def field [field β] : field α := let zero := e.has_zero, add := e.has_add, one := e.has_one, mul := e.has_mul, neg := e.has_neg, sub := e.has_sub, inv := e.has_inv, div := e.has_div in by resetI; apply e.injective.field _; intros; exact e.apply_symm_apply _ section R variables (R : Type*) include R section variables [monoid R] /-- Transfer `mul_action` across an `equiv` -/ protected def mul_action (e : α ≃ β) [mul_action R β] : mul_action R α := { one_smul := by simp [smul_def], mul_smul := by simp [smul_def, mul_smul], ..equiv.has_scalar e } /-- Transfer `distrib_mul_action` across an `equiv` -/ protected def distrib_mul_action (e : α ≃ β) [add_comm_monoid β] : begin letI := equiv.add_comm_monoid e, exact Π [distrib_mul_action R β], distrib_mul_action R α end := begin intros, letI := equiv.add_comm_monoid e, exact ( { smul_zero := by simp [zero_def, smul_def], smul_add := by simp [add_def, smul_def, smul_add], ..equiv.mul_action R e } : distrib_mul_action R α) end end section variables [semiring R] /-- Transfer `module` across an `equiv` -/ protected def module (e : α ≃ β) [add_comm_monoid β] : begin letI := equiv.add_comm_monoid e, exact Π [module R β], module R α end := begin introsI, exact ( { zero_smul := by simp [zero_def, smul_def], add_smul := by simp [add_def, smul_def, add_smul], ..equiv.distrib_mul_action R e } : module R α) end /-- An equivalence `e : α ≃ β` gives a linear equivalence `α ≃ₗ[R] β` where the `R`-module structure on `α` is the one obtained by transporting an `R`-module structure on `β` back along `e`. -/ def linear_equiv (e : α ≃ β) [add_comm_monoid β] [module R β] : begin letI := equiv.add_comm_monoid e, letI := equiv.module R e, exact α ≃ₗ[R] β end := begin introsI, exact { map_smul' := λ r x, by { apply e.symm.injective, simp, refl, }, ..equiv.add_equiv e } end end section variables [comm_semiring R] /-- Transfer `algebra` across an `equiv` -/ protected def algebra (e : α ≃ β) [semiring β] : begin letI := equiv.semiring e, exact Π [algebra R β], algebra R α end := begin introsI, fapply ring_hom.to_algebra', { exact ((ring_equiv e).symm : β →+* α).comp (algebra_map R β), }, { intros r x, simp only [function.comp_app, ring_hom.coe_comp], have p := ring_equiv_symm_apply e, dsimp at p, erw p, clear p, apply (ring_equiv e).injective, simp only [(ring_equiv e).map_mul], simp [algebra.commutes], } end /-- An equivalence `e : α ≃ β` gives an algebra equivalence `α ≃ₐ[R] β` where the `R`-algebra structure on `α` is the one obtained by transporting an `R`-algebra structure on `β` back along `e`. -/ def alg_equiv (e : α ≃ β) [semiring β] [algebra R β] : begin letI := equiv.semiring e, letI := equiv.algebra R e, exact α ≃ₐ[R] β end := begin introsI, exact { commutes' := λ r, by { apply e.symm.injective, simp, refl, }, ..equiv.ring_equiv e } end end end R end instances end equiv namespace ring_equiv protected lemma local_ring {A B : Type*} [comm_ring A] [local_ring A] [comm_ring B] (e : A ≃+* B) : local_ring B := begin haveI := e.symm.to_equiv.nontrivial, refine @local_of_surjective A B _ _ _ _ e e.to_equiv.surjective, end end ring_equiv
1d713ba4425af9ea4e7125b03b361f3101f3a463
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/logic/embedding.lean
604cfac8383c2e255305e749d62d46abf1157fed
[ "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
16,305
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import data.equiv.basic import data.set.basic import data.sigma.basic /-! # Injective functions -/ universes u v w x namespace function /-- `α ↪ β` is a bundled injective function. -/ @[nolint has_inhabited_instance] -- depending on cardinalities, an injective function may not exist structure embedding (α : Sort*) (β : Sort*) := (to_fun : α → β) (inj' : injective to_fun) infixr ` ↪ `:25 := embedding instance {α : Sort u} {β : Sort v} : has_coe_to_fun (α ↪ β) (λ _, α → β) := ⟨embedding.to_fun⟩ initialize_simps_projections embedding (to_fun → apply) end function section equiv variables {α : Sort u} {β : Sort v} (f : α ≃ β) /-- Convert an `α ≃ β` to `α ↪ β`. This is also available as a coercion `equiv.coe_embedding`. The explicit `equiv.to_embedding` version is preferred though, since the coercion can have issues inferring the type of the resulting embedding. For example: ```lean -- Works: example (s : finset (fin 3)) (f : equiv.perm (fin 3)) : s.map f.to_embedding = s.map f := by simp -- Error, `f` has type `fin 3 ≃ fin 3` but is expected to have type `fin 3 ↪ ?m_1 : Type ?` example (s : finset (fin 3)) (f : equiv.perm (fin 3)) : s.map f = s.map f.to_embedding := by simp ``` -/ @[simps] protected def equiv.to_embedding : α ↪ β := ⟨f, f.injective⟩ instance equiv.coe_embedding : has_coe (α ≃ β) (α ↪ β) := ⟨equiv.to_embedding⟩ @[reducible] instance equiv.perm.coe_embedding : has_coe (equiv.perm α) (α ↪ α) := equiv.coe_embedding @[simp] lemma equiv.coe_eq_to_embedding : ↑f = f.to_embedding := rfl /-- Given an equivalence to a subtype, produce an embedding to the elements of the corresponding set. -/ @[simps] def equiv.as_embedding {p : β → Prop} (e : α ≃ subtype p) : α ↪ β := ⟨coe ∘ e, subtype.coe_injective.comp e.injective⟩ @[simp] lemma equiv.as_embedding_range {α β : Sort*} {p : β → Prop} (e : α ≃ subtype p) : set.range e.as_embedding = set_of p := set.ext $ λ x, ⟨λ ⟨y, h⟩, h ▸ subtype.coe_prop (e y), λ hs, ⟨e.symm ⟨x, hs⟩, by simp⟩⟩ end equiv namespace function namespace embedding lemma coe_injective {α β} : @function.injective (α ↪ β) (α → β) coe_fn | ⟨x, _⟩ ⟨y, _⟩ rfl := rfl @[ext] lemma ext {α β} {f g : embedding α β} (h : ∀ x, f x = g x) : f = g := coe_injective (funext h) lemma ext_iff {α β} {f g : embedding α β} : (∀ x, f x = g x) ↔ f = g := ⟨ext, λ h _, by rw h⟩ @[simp] theorem to_fun_eq_coe {α β} (f : α ↪ β) : to_fun f = f := rfl @[simp] theorem coe_fn_mk {α β} (f : α → β) (i) : (@mk _ _ f i : α → β) = f := rfl @[simp] lemma mk_coe {α β : Type*} (f : α ↪ β) (inj) : (⟨f, inj⟩ : α ↪ β) = f := by { ext, simp } protected theorem injective {α β} (f : α ↪ β) : injective f := f.inj' @[simp] lemma apply_eq_iff_eq {α β : Type*} (f : α ↪ β) (x y : α) : f x = f y ↔ x = y := f.injective.eq_iff /-- The identity map as a `function.embedding`. -/ @[refl, simps {simp_rhs := tt}] protected def refl (α : Sort*) : α ↪ α := ⟨id, injective_id⟩ /-- Composition of `f : α ↪ β` and `g : β ↪ γ`. -/ @[trans, simps {simp_rhs := tt}] protected def trans {α β γ} (f : α ↪ β) (g : β ↪ γ) : α ↪ γ := ⟨g ∘ f, g.injective.comp f.injective⟩ @[simp] lemma equiv_to_embedding_trans_symm_to_embedding {α β : Sort*} (e : α ≃ β) : e.to_embedding.trans e.symm.to_embedding = embedding.refl _ := by { ext, simp, } @[simp] lemma equiv_symm_to_embedding_trans_to_embedding {α β : Sort*} (e : α ≃ β) : e.symm.to_embedding.trans e.to_embedding = embedding.refl _ := by { ext, simp, } /-- Transfer an embedding along a pair of equivalences. -/ @[simps { fully_applied := ff }] protected def congr {α : Sort u} {β : Sort v} {γ : Sort w} {δ : Sort x} (e₁ : α ≃ β) (e₂ : γ ≃ δ) (f : α ↪ γ) : (β ↪ δ) := (equiv.to_embedding e₁.symm).trans (f.trans e₂.to_embedding) /-- A right inverse `surj_inv` of a surjective function as an `embedding`. -/ protected noncomputable def of_surjective {α β} (f : β → α) (hf : surjective f) : α ↪ β := ⟨surj_inv hf, injective_surj_inv _⟩ /-- Convert a surjective `embedding` to an `equiv` -/ protected noncomputable def equiv_of_surjective {α β} (f : α ↪ β) (hf : surjective f) : α ≃ β := equiv.of_bijective f ⟨f.injective, hf⟩ /-- There is always an embedding from an empty type. --/ protected def of_is_empty {α β} [is_empty α] : α ↪ β := ⟨is_empty_elim, is_empty_elim⟩ /-- Change the value of an embedding `f` at one point. If the prescribed image is already occupied by some `f a'`, then swap the values at these two points. -/ def set_value {α β} (f : α ↪ β) (a : α) (b : β) [∀ a', decidable (a' = a)] [∀ a', decidable (f a' = b)] : α ↪ β := ⟨λ a', if a' = a then b else if f a' = b then f a else f a', begin intros x y h, dsimp at h, split_ifs at h; try { substI b }; try { simp only [f.injective.eq_iff] at * }; cc end⟩ theorem set_value_eq {α β} (f : α ↪ β) (a : α) (b : β) [∀ a', decidable (a' = a)] [∀ a', decidable (f a' = b)] : set_value f a b a = b := by simp [set_value] /-- Embedding into `option` -/ @[simps { fully_applied := ff }] protected def some {α} : α ↪ option α := ⟨some, option.some_injective α⟩ /-- Given an embedding `f : α ↪ β` and a point outside of `set.range f`, construct an embedding `option α ↪ β`. -/ @[simps] def option_elim {α β} (f : α ↪ β) (x : β) (h : x ∉ set.range f) : option α ↪ β := ⟨λ o, o.elim x f, option.injective_iff.2 ⟨f.2, h⟩⟩ /-- Embedding of a `subtype`. -/ def subtype {α} (p : α → Prop) : subtype p ↪ α := ⟨coe, λ _ _, subtype.ext_val⟩ @[simp] lemma coe_subtype {α} (p : α → Prop) : ⇑(subtype p) = coe := rfl /-- Choosing an element `b : β` gives an embedding of `punit` into `β`. -/ def punit {β : Sort*} (b : β) : punit ↪ β := ⟨λ _, b, by { rintros ⟨⟩ ⟨⟩ _, refl, }⟩ /-- Fixing an element `b : β` gives an embedding `α ↪ α × β`. -/ def sectl (α : Sort*) {β : Sort*} (b : β) : α ↪ α × β := ⟨λ a, (a, b), λ a a' h, congr_arg prod.fst h⟩ /-- Fixing an element `a : α` gives an embedding `β ↪ α × β`. -/ def sectr {α : Sort*} (a : α) (β : Sort*): β ↪ α × β := ⟨λ b, (a, b), λ b b' h, congr_arg prod.snd h⟩ /-- Restrict the codomain of an embedding. -/ def cod_restrict {α β} (p : set β) (f : α ↪ β) (H : ∀ a, f a ∈ p) : α ↪ p := ⟨λ a, ⟨f a, H a⟩, λ a b h, f.injective (@congr_arg _ _ _ _ subtype.val h)⟩ @[simp] theorem cod_restrict_apply {α β} (p) (f : α ↪ β) (H a) : cod_restrict p f H a = ⟨f a, H a⟩ := rfl /-- If `e₁` and `e₂` are embeddings, then so is `prod.map e₁ e₂ : (a, b) ↦ (e₁ a, e₂ b)`. -/ def prod_map {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : α × γ ↪ β × δ := ⟨prod.map e₁ e₂, e₁.injective.prod_map e₂.injective⟩ @[simp] lemma coe_prod_map {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : ⇑(e₁.prod_map e₂) = prod.map e₁ e₂ := rfl section sum open sum /-- If `e₁` and `e₂` are embeddings, then so is `sum.map e₁ e₂`. -/ def sum_map {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : α ⊕ γ ↪ β ⊕ δ := ⟨sum.map e₁ e₂, assume s₁ s₂ h, match s₁, s₂, h with | inl a₁, inl a₂, h := congr_arg inl $ e₁.injective $ inl.inj h | inr b₁, inr b₂, h := congr_arg inr $ e₂.injective $ inr.inj h end⟩ @[simp] theorem coe_sum_map {α β γ δ} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : ⇑(sum_map e₁ e₂) = sum.map e₁ e₂ := rfl /-- The embedding of `α` into the sum `α ⊕ β`. -/ @[simps] def inl {α β : Type*} : α ↪ α ⊕ β := ⟨sum.inl, λ a b, sum.inl.inj⟩ /-- The embedding of `β` into the sum `α ⊕ β`. -/ @[simps] def inr {α β : Type*} : β ↪ α ⊕ β := ⟨sum.inr, λ a b, sum.inr.inj⟩ end sum section sigma variables {α α' : Type*} {β : α → Type*} {β' : α' → Type*} /-- `sigma.mk` as an `function.embedding`. -/ @[simps apply] def sigma_mk (a : α) : β a ↪ Σ x, β x := ⟨sigma.mk a, sigma_mk_injective⟩ /-- If `f : α ↪ α'` is an embedding and `g : Π a, β α ↪ β' (f α)` is a family of embeddings, then `sigma.map f g` is an embedding. -/ @[simps apply] def sigma_map (f : α ↪ α') (g : Π a, β a ↪ β' (f a)) : (Σ a, β a) ↪ Σ a', β' a' := ⟨sigma.map f (λ a, g a), f.injective.sigma_map (λ a, (g a).injective)⟩ end sigma /-- Define an embedding `(Π a : α, β a) ↪ (Π a : α, γ a)` from a family of embeddings `e : Π a, (β a ↪ γ a)`. This embedding sends `f` to `λ a, e a (f a)`. -/ @[simps] def Pi_congr_right {α : Sort*} {β γ : α → Sort*} (e : ∀ a, β a ↪ γ a) : (Π a, β a) ↪ (Π a, γ a) := ⟨λf a, e a (f a), λ f₁ f₂ h, funext $ λ a, (e a).injective (congr_fun h a)⟩ /-- An embedding `e : α ↪ β` defines an embedding `(γ → α) ↪ (γ → β)` that sends each `f` to `e ∘ f`. -/ def arrow_congr_right {α : Sort u} {β : Sort v} {γ : Sort w} (e : α ↪ β) : (γ → α) ↪ (γ → β) := Pi_congr_right (λ _, e) @[simp] lemma arrow_congr_right_apply {α : Sort u} {β : Sort v} {γ : Sort w} (e : α ↪ β) (f : γ ↪ α) : arrow_congr_right e f = e ∘ f := rfl /-- An embedding `e : α ↪ β` defines an embedding `(α → γ) ↪ (β → γ)` for any inhabited type `γ`. This embedding sends each `f : α → γ` to a function `g : β → γ` such that `g ∘ e = f` and `g y = default γ` whenever `y ∉ range e`. -/ noncomputable def arrow_congr_left {α : Sort u} {β : Sort v} {γ : Sort w} [inhabited γ] (e : α ↪ β) : (α → γ) ↪ (β → γ) := ⟨λ f, extend e f (λ _, default γ), λ f₁ f₂ h, funext $ λ x, by simpa only [extend_apply e.injective] using congr_fun h (e x)⟩ /-- Restrict both domain and codomain of an embedding. -/ protected def subtype_map {α β} {p : α → Prop} {q : β → Prop} (f : α ↪ β) (h : ∀{{x}}, p x → q (f x)) : {x : α // p x} ↪ {y : β // q y} := ⟨subtype.map f h, subtype.map_injective h f.2⟩ open set /-- `set.image` as an embedding `set α ↪ set β`. -/ @[simps apply] protected def image {α β} (f : α ↪ β) : set α ↪ set β := ⟨image f, f.2.image_injective⟩ lemma swap_apply {α β : Type*} [decidable_eq α] [decidable_eq β] (f : α ↪ β) (x y z : α) : equiv.swap (f x) (f y) (f z) = f (equiv.swap x y z) := f.injective.swap_apply x y z lemma swap_comp {α β : Type*} [decidable_eq α] [decidable_eq β] (f : α ↪ β) (x y : α) : equiv.swap (f x) (f y) ∘ f = f ∘ equiv.swap x y := f.injective.swap_comp x y end embedding end function namespace equiv open function.embedding /-- The type of embeddings `α ↪ β` is equivalent to the subtype of all injective functions `α → β`. -/ def subtype_injective_equiv_embedding (α β : Sort*) : {f : α → β // function.injective f} ≃ (α ↪ β) := { to_fun := λ f, ⟨f.val, f.property⟩, inv_fun := λ f, ⟨f, f.injective⟩, left_inv := λ f, by simp, right_inv := λ f, by {ext, refl} } /-- If `α₁ ≃ α₂` and `β₁ ≃ β₂`, then the type of embeddings `α₁ ↪ β₁` is equivalent to the type of embeddings `α₂ ↪ β₂`. -/ @[congr, simps apply] def embedding_congr {α β γ δ : Sort*} (h : α ≃ β) (h' : γ ≃ δ) : (α ↪ γ) ≃ (β ↪ δ) := { to_fun := λ f, f.congr h h', inv_fun := λ f, f.congr h.symm h'.symm, left_inv := λ x, by {ext, simp}, right_inv := λ x, by {ext, simp} } @[simp] lemma embedding_congr_refl {α β : Sort*} : embedding_congr (equiv.refl α) (equiv.refl β) = equiv.refl (α ↪ β) := by {ext, refl} @[simp] lemma embedding_congr_trans {α₁ β₁ α₂ β₂ α₃ β₃ : Sort*} (e₁ : α₁ ≃ α₂) (e₁' : β₁ ≃ β₂) (e₂ : α₂ ≃ α₃) (e₂' : β₂ ≃ β₃) : embedding_congr (e₁.trans e₂) (e₁'.trans e₂') = (embedding_congr e₁ e₁').trans (embedding_congr e₂ e₂') := rfl @[simp] lemma embedding_congr_symm {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : (embedding_congr e₁ e₂).symm = embedding_congr e₁.symm e₂.symm := rfl lemma embedding_congr_apply_trans {α₁ β₁ γ₁ α₂ β₂ γ₂ : Sort*} (ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) (ec : γ₁ ≃ γ₂) (f : α₁ ↪ β₁) (g : β₁ ↪ γ₁) : equiv.embedding_congr ea ec (f.trans g) = (equiv.embedding_congr ea eb f).trans (equiv.embedding_congr eb ec g) := by {ext, simp} @[simp] lemma refl_to_embedding {α : Type*} : (equiv.refl α).to_embedding = function.embedding.refl α := rfl @[simp] lemma trans_to_embedding {α β γ : Type*} (e : α ≃ β) (f : β ≃ γ) : (e.trans f).to_embedding = e.to_embedding.trans f.to_embedding := rfl end equiv namespace set /-- The injection map is an embedding between subsets. -/ @[simps apply] def embedding_of_subset {α} (s t : set α) (h : s ⊆ t) : s ↪ t := ⟨λ x, ⟨x.1, h x.2⟩, λ ⟨x, hx⟩ ⟨y, hy⟩ h, by { congr, injection h }⟩ end set section subtype variable {α : Type*} /-- A subtype `{x // p x ∨ q x}` over a disjunction of `p q : α → Prop` can be injectively split into a sum of subtypes `{x // p x} ⊕ {x // q x}` such that `¬ p x` is sent to the right. -/ def subtype_or_left_embedding (p q : α → Prop) [decidable_pred p] : {x // p x ∨ q x} ↪ {x // p x} ⊕ {x // q x} := ⟨λ x, if h : p x then sum.inl ⟨x, h⟩ else sum.inr ⟨x, x.prop.resolve_left h⟩, begin intros x y, dsimp only, split_ifs; simp [subtype.ext_iff] end⟩ lemma subtype_or_left_embedding_apply_left {p q : α → Prop} [decidable_pred p] (x : {x // p x ∨ q x}) (hx : p x) : subtype_or_left_embedding p q x = sum.inl ⟨x, hx⟩ := dif_pos hx lemma subtype_or_left_embedding_apply_right {p q : α → Prop} [decidable_pred p] (x : {x // p x ∨ q x}) (hx : ¬ p x) : subtype_or_left_embedding p q x = sum.inr ⟨x, x.prop.resolve_left hx⟩ := dif_neg hx /-- A subtype `{x // p x}` can be injectively sent to into a subtype `{x // q x}`, if `p x → q x` for all `x : α`. -/ @[simps] def subtype.imp_embedding (p q : α → Prop) (h : p ≤ q) : {x // p x} ↪ {x // q x} := ⟨λ x, ⟨x, h x x.prop⟩, λ x y, by simp [subtype.ext_iff]⟩ /-- A subtype `{x // p x ∨ q x}` over a disjunction of `p q : α → Prop` is equivalent to a sum of subtypes `{x // p x} ⊕ {x // q x}` such that `¬ p x` is sent to the right, when `disjoint p q`. See also `equiv.sum_compl`, for when `is_compl p q`. -/ @[simps apply] def subtype_or_equiv (p q : α → Prop) [decidable_pred p] (h : disjoint p q) : {x // p x ∨ q x} ≃ {x // p x} ⊕ {x // q x} := { to_fun := subtype_or_left_embedding p q, inv_fun := sum.elim (subtype.imp_embedding _ _ (λ x hx, (or.inl hx : p x ∨ q x))) (subtype.imp_embedding _ _ (λ x hx, (or.inr hx : p x ∨ q x))), left_inv := λ x, begin by_cases hx : p x, { rw subtype_or_left_embedding_apply_left _ hx, simp [subtype.ext_iff] }, { rw subtype_or_left_embedding_apply_right _ hx, simp [subtype.ext_iff] }, end, right_inv := λ x, begin cases x, { simp only [sum.elim_inl], rw subtype_or_left_embedding_apply_left, { simp }, { simpa using x.prop } }, { simp only [sum.elim_inr], rw subtype_or_left_embedding_apply_right, { simp }, { suffices : ¬ p x, { simpa }, intro hp, simpa using h x ⟨hp, x.prop⟩ } } end } @[simp] lemma subtype_or_equiv_symm_inl (p q : α → Prop) [decidable_pred p] (h : disjoint p q) (x : {x // p x}) : (subtype_or_equiv p q h).symm (sum.inl x) = ⟨x, or.inl x.prop⟩ := rfl @[simp] lemma subtype_or_equiv_symm_inr (p q : α → Prop) [decidable_pred p] (h : disjoint p q) (x : {x // q x}) : (subtype_or_equiv p q h).symm (sum.inr x) = ⟨x, or.inr x.prop⟩ := rfl end subtype
20174a3b2ff8e2fe7504da22305381ad58663bbe
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/topology/category/Top/opens.lean
286dcaf1666fe4dcee5cf12e2ef3bc37d603461f
[ "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
9,005
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 topology.category.Top.basic import category_theory.eq_to_hom import category_theory.category.preorder /-! # The category of open sets in a topological space. We define `to_Top : opens X ⥤ Top` and `map (f : X ⟶ Y) : opens Y ⥤ opens X`, given by taking preimages of open sets. Unfortunately `opens` isn't (usefully) a functor `Top ⥤ Cat`. (One can in fact define such a functor, but using it results in unresolvable `eq.rec` terms in goals.) Really it's a 2-functor from (spaces, continuous functions, equalities) to (categories, functors, natural isomorphisms). We don't attempt to set up the full theory here, but do provide the natural isomorphisms `map_id : map (𝟙 X) ≅ 𝟭 (opens X)` and `map_comp : map (f ≫ g) ≅ map g ⋙ map f`. Beyond that, there's a collection of simp lemmas for working with these constructions. -/ open category_theory open topological_space open opposite universe u namespace topological_space.opens variables {X Y Z : Top.{u}} /-! Since `opens X` has a partial order, it automatically receives a `category` instance. Unfortunately, because we do not allow morphisms in `Prop`, the morphisms `U ⟶ V` are not just proofs `U ≤ V`, but rather `ulift (plift (U ≤ V))`. -/ instance opens_hom_has_coe_to_fun {U V : opens X} : has_coe_to_fun (U ⟶ V) (λ f, U → V) := ⟨λ f x, ⟨x, f.le x.2⟩⟩ /-! We now construct as morphisms various inclusions of open sets. -/ -- This is tedious, but necessary because we decided not to allow Prop as morphisms in a category... /-- The inclusion `U ⊓ V ⟶ U` as a morphism in the category of open sets. -/ def inf_le_left (U V : opens X) : U ⊓ V ⟶ U := inf_le_left.hom /-- The inclusion `U ⊓ V ⟶ V` as a morphism in the category of open sets. -/ def inf_le_right (U V : opens X) : U ⊓ V ⟶ V := inf_le_right.hom /-- The inclusion `U i ⟶ supr U` as a morphism in the category of open sets. -/ def le_supr {ι : Type*} (U : ι → opens X) (i : ι) : U i ⟶ supr U := (le_supr U i).hom /-- The inclusion `⊥ ⟶ U` as a morphism in the category of open sets. -/ def bot_le (U : opens X) : ⊥ ⟶ U := bot_le.hom /-- The inclusion `U ⟶ ⊤` as a morphism in the category of open sets. -/ def le_top (U : opens X) : U ⟶ ⊤ := le_top.hom -- We do not mark this as a simp lemma because it breaks open `x`. -- Nevertheless, it is useful in `sheaf_of_functions`. lemma inf_le_left_apply (U V : opens X) (x) : (inf_le_left U V) x = ⟨x.1, (@_root_.inf_le_left _ _ U V : _ ≤ _) x.2⟩ := rfl @[simp] lemma inf_le_left_apply_mk (U V : opens X) (x) (m) : (inf_le_left U V) ⟨x, m⟩ = ⟨x, (@_root_.inf_le_left _ _ U V : _ ≤ _) m⟩ := rfl @[simp] lemma le_supr_apply_mk {ι : Type*} (U : ι → opens X) (i : ι) (x) (m) : (le_supr U i) ⟨x, m⟩ = ⟨x, (_root_.le_supr U i : _) m⟩ := rfl /-- The functor from open sets in `X` to `Top`, realising each open set as a topological space itself. -/ def to_Top (X : Top.{u}) : opens X ⥤ Top := { obj := λ U, ⟨U.val, infer_instance⟩, map := λ U V i, ⟨λ x, ⟨x.1, i.le x.2⟩, (embedding.continuous_iff embedding_subtype_coe).2 continuous_induced_dom⟩ } @[simp] lemma to_Top_map (X : Top.{u}) {U V : opens X} {f : U ⟶ V} {x} {h} : ((to_Top X).map f) ⟨x, h⟩ = ⟨x, f.le h⟩ := rfl /-- The inclusion map from an open subset to the whole space, as a morphism in `Top`. -/ @[simps] def inclusion {X : Top.{u}} (U : opens X) : (to_Top X).obj U ⟶ X := { to_fun := _, continuous_to_fun := continuous_subtype_coe } lemma open_embedding {X : Top.{u}} (U : opens X) : open_embedding (inclusion U) := is_open.open_embedding_subtype_coe U.2 /-- The inclusion of the top open subset (i.e. the whole space) is an isomorphism. -/ def inclusion_top_iso (X : Top.{u}) : (to_Top X).obj ⊤ ≅ X := { hom := inclusion ⊤, inv := ⟨λ x, ⟨x, trivial⟩, continuous_def.2 $ λ U ⟨S, hS, hSU⟩, hSU ▸ hS⟩ } /-- `opens.map f` gives the functor from open sets in Y to open set in X, given by taking preimages under f. -/ def map (f : X ⟶ Y) : opens Y ⥤ opens X := { obj := λ U, ⟨ f ⁻¹' U.val, U.property.preimage f.continuous ⟩, map := λ U V i, ⟨ ⟨ λ x h, i.le h ⟩ ⟩ }. @[simp] lemma map_obj (f : X ⟶ Y) (U) (p) : (map f).obj ⟨U, p⟩ = ⟨f ⁻¹' U, p.preimage f.continuous⟩ := rfl @[simp] lemma map_id_obj (U : opens X) : (map (𝟙 X)).obj U = U := let ⟨_,_⟩ := U in rfl @[simp] lemma map_id_obj' (U) (p) : (map (𝟙 X)).obj ⟨U, p⟩ = ⟨U, p⟩ := rfl @[simp] lemma map_id_obj_unop (U : (opens X)ᵒᵖ) : (map (𝟙 X)).obj (unop U) = unop U := let ⟨_,_⟩ := U.unop in rfl @[simp] lemma op_map_id_obj (U : (opens X)ᵒᵖ) : (map (𝟙 X)).op.obj U = U := by simp /-- The inclusion `U ⟶ (map f).obj ⊤` as a morphism in the category of open sets. -/ def le_map_top (f : X ⟶ Y) (U : opens X) : U ⟶ (map f).obj ⊤ := le_top U @[simp] lemma map_comp_obj (f : X ⟶ Y) (g : Y ⟶ Z) (U) : (map (f ≫ g)).obj U = (map f).obj ((map g).obj U) := rfl @[simp] lemma map_comp_obj' (f : X ⟶ Y) (g : Y ⟶ Z) (U) (p) : (map (f ≫ g)).obj ⟨U, p⟩ = (map f).obj ((map g).obj ⟨U, p⟩) := rfl @[simp] lemma map_comp_map (f : X ⟶ Y) (g : Y ⟶ Z) {U V} (i : U ⟶ V) : (map (f ≫ g)).map i = (map f).map ((map g).map i) := rfl @[simp] lemma map_comp_obj_unop (f : X ⟶ Y) (g : Y ⟶ Z) (U) : (map (f ≫ g)).obj (unop U) = (map f).obj ((map g).obj (unop U)) := rfl @[simp] lemma op_map_comp_obj (f : X ⟶ Y) (g : Y ⟶ Z) (U) : (map (f ≫ g)).op.obj U = (map f).op.obj ((map g).op.obj U) := rfl lemma map_supr (f : X ⟶ Y) {ι : Type*} (U : ι → opens Y) : (map f).obj (supr U) = supr ((map f).obj ∘ U) := begin apply subtype.eq, rw [supr_def, supr_def, map_obj], dsimp, rw set.preimage_Union, refl, end section variable (X) /-- The functor `opens X ⥤ opens X` given by taking preimages under the identity function is naturally isomorphic to the identity functor. -/ @[simps] def map_id : map (𝟙 X) ≅ 𝟭 (opens X) := { hom := { app := λ U, eq_to_hom (map_id_obj U) }, inv := { app := λ U, eq_to_hom (map_id_obj U).symm } } lemma map_id_eq : map (𝟙 X) = 𝟭 (opens X) := by { unfold map, congr, ext, refl, ext } end /-- The natural isomorphism between taking preimages under `f ≫ g`, and the composite of taking preimages under `g`, then preimages under `f`. -/ @[simps] def map_comp (f : X ⟶ Y) (g : Y ⟶ Z) : map (f ≫ g) ≅ map g ⋙ map f := { hom := { app := λ U, eq_to_hom (map_comp_obj f g U) }, inv := { app := λ U, eq_to_hom (map_comp_obj f g U).symm } } lemma map_comp_eq (f : X ⟶ Y) (g : Y ⟶ Z) : map (f ≫ g) = map g ⋙ map f := rfl /-- If two continuous maps `f g : X ⟶ Y` are equal, then the functors `opens Y ⥤ opens X` they induce are isomorphic. -/ -- We could make `f g` implicit here, but it's nice to be able to see when -- they are the identity (often!) def map_iso (f g : X ⟶ Y) (h : f = g) : map f ≅ map g := nat_iso.of_components (λ U, eq_to_iso (congr_fun (congr_arg functor.obj (congr_arg map h)) U) ) (by obviously) lemma map_eq (f g : X ⟶ Y) (h : f = g) : map f = map g := by { unfold map, congr, ext, rw h, rw h, assumption' } @[simp] lemma map_iso_refl (f : X ⟶ Y) (h) : map_iso f f h = iso.refl (map _) := rfl @[simp] lemma map_iso_hom_app (f g : X ⟶ Y) (h : f = g) (U : opens Y) : (map_iso f g h).hom.app U = eq_to_hom (congr_fun (congr_arg functor.obj (congr_arg map h)) U) := rfl @[simp] lemma map_iso_inv_app (f g : X ⟶ Y) (h : f = g) (U : opens Y) : (map_iso f g h).inv.app U = eq_to_hom (congr_fun (congr_arg functor.obj (congr_arg map h.symm)) U) := rfl end topological_space.opens /-- An open map `f : X ⟶ Y` induces a functor `opens X ⥤ opens Y`. -/ @[simps] def is_open_map.functor {X Y : Top} {f : X ⟶ Y} (hf : is_open_map f) : opens X ⥤ opens Y := { obj := λ U, ⟨f '' U, hf U U.2⟩, map := λ U V h, ⟨⟨set.image_subset _ h.down.down⟩⟩ } /-- An open map `f : X ⟶ Y` induces an adjunction between `opens X` and `opens Y`. -/ def is_open_map.adjunction {X Y : Top} {f : X ⟶ Y} (hf : is_open_map f) : adjunction hf.functor (topological_space.opens.map f) := adjunction.mk_of_unit_counit { unit := { app := λ U, hom_of_le $ λ x hxU, ⟨x, hxU, rfl⟩ }, counit := { app := λ V, hom_of_le $ λ y ⟨x, hfxV, hxy⟩, hxy ▸ hfxV } } namespace topological_space.opens open topological_space lemma inclusion_top_functor (X : Top) : (@opens.open_embedding X ⊤).is_open_map.functor = map (inclusion_top_iso X).inv := begin apply functor.hext, intro, abstract obj_eq { ext, exact ⟨ λ ⟨⟨_,_⟩,h,rfl⟩, h, λ h, ⟨⟨x,trivial⟩,h,rfl⟩ ⟩ }, intros, apply subsingleton.helim, congr' 1, iterate 2 {apply inclusion_top_functor.obj_eq}, end end topological_space.opens
c4a4aca729ab6d47811fcc02ffd7c15a9c2b907d
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/computability/tm_to_partrec.lean
3ea2adca013c1b5f11d35239376745f3953b1dbf
[ "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
64,652
lean
/- Copyright (c) 2020 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import computability.halting import computability.turing_machine import data.num.lemmas /-! # Modelling partial recursive functions using Turing machines This file defines a simplified basis for partial recursive functions, and a `turing.TM2` model Turing machine for evaluating these functions. This amounts to a constructive proof that every `partrec` function can be evaluated by a Turing machine. ## Main definitions * `to_partrec.code`: a simplified basis for partial recursive functions, valued in `list ℕ →. list ℕ`. * `to_partrec.code.eval`: semantics for a `to_partrec.code` program * `partrec_to_TM2.tr`: A TM2 turing machine which can evaluate `code` programs -/ open function (update) open relation namespace turing /-! ## A simplified basis for partrec This section constructs the type `code`, which is a data type of programs with `list ℕ` input and output, with enough expressivity to write any partial recursive function. The primitives are: * `zero'` appends a `0` to the input. That is, `zero' v = 0 :: v`. * `succ` returns the successor of the head of the input, defaulting to zero if there is no head: * `succ [] = [1]` * `succ (n :: v) = [n + 1]` * `tail` returns the tail of the input * `tail [] = []` * `tail (n :: v) = v` * `cons f fs` calls `f` and `fs` on the input and conses the results: * `cons f fs v = (f v).head :: fs v` * `comp f g` calls `f` on the output of `g`: * `comp f g v = f (g v)` * `case f g` cases on the head of the input, calling `f` or `g` depending on whether it is zero or a successor (similar to `nat.cases_on`). * `case f g [] = f []` * `case f g (0 :: v) = f v` * `case f g (n+1 :: v) = g (n :: v)` * `fix f` calls `f` repeatedly, using the head of the result of `f` to decide whether to call `f` again or finish: * `fix f v = []` if `f v = []` * `fix f v = w` if `f v = 0 :: w` * `fix f v = fix f w` if `f v = n+1 :: w` (the exact value of `n` is discarded) This basis is convenient because it is closer to the Turing machine model - the key operations are splitting and merging of lists of unknown length, while the messy `n`-ary composition operation from the traditional basis for partial recursive functions is absent - but it retains a compositional semantics. The first step in transitioning to Turing machines is to make a sequential evaluator for this basis, which we take up in the next section. -/ namespace to_partrec /-- The type of codes for primitive recursive functions. Unlike `nat.partrec.code`, this uses a set of operations on `list ℕ`. See `code.eval` for a description of the behavior of the primitives. -/ @[derive inhabited] inductive code | zero' | succ | tail | cons : code → code → code | comp : code → code → code | case : code → code → code | fix : code → code /-- The semantics of the `code` primitives, as partial functions `list ℕ →. list ℕ`. By convention we functions that return a single result return a singleton `[n]`, or in some cases `n :: v` where `v` will be ignored by a subsequent function. * `zero'` appends a `0` to the input. That is, `zero' v = 0 :: v`. * `succ` returns the successor of the head of the input, defaulting to zero if there is no head: * `succ [] = [1]` * `succ (n :: v) = [n + 1]` * `tail` returns the tail of the input * `tail [] = []` * `tail (n :: v) = v` * `cons f fs` calls `f` and `fs` on the input and conses the results: * `cons f fs v = (f v).head :: fs v` * `comp f g` calls `f` on the output of `g`: * `comp f g v = f (g v)` * `case f g` cases on the head of the input, calling `f` or `g` depending on whether it is zero or a successor (similar to `nat.cases_on`). * `case f g [] = f []` * `case f g (0 :: v) = f v` * `case f g (n+1 :: v) = g (n :: v)` * `fix f` calls `f` repeatedly, using the head of the result of `f` to decide whether to call `f` again or finish: * `fix f v = []` if `f v = []` * `fix f v = w` if `f v = 0 :: w` * `fix f v = fix f w` if `f v = n+1 :: w` (the exact value of `n` is discarded) -/ @[simp] def code.eval : code → list ℕ →. list ℕ | code.zero' := λ v, pure (0 :: v) | code.succ := λ v, pure [v.head.succ] | code.tail := λ v, pure v.tail | (code.cons f fs) := λ v, do n ← code.eval f v, ns ← code.eval fs v, pure (n.head :: ns) | (code.comp f g) := λ v, g.eval v >>= f.eval | (code.case f g) := λ v, v.head.elim (f.eval v.tail) (λ y _, g.eval (y :: v.tail)) | (code.fix f) := pfun.fix $ λ v, (f.eval v).map $ λ v, if v.head = 0 then sum.inl v.tail else sum.inr v.tail namespace code /-- `nil` is the constant nil function: `nil v = []`. -/ def nil : code := tail.comp succ @[simp] theorem nil_eval (v) : nil.eval v = pure [] := by simp [nil] /-- `id` is the identity function: `id v = v`. -/ def id : code := tail.comp zero' @[simp] theorem id_eval (v) : id.eval v = pure v := by simp [id] /-- `head` gets the head of the input list: `head [] = [0]`, `head (n :: v) = [n]`. -/ def head : code := cons id nil @[simp] theorem head_eval (v) : head.eval v = pure [v.head] := by simp [head] /-- `zero` is the constant zero function: `zero v = [0]`. -/ def zero : code := cons zero' nil @[simp] theorem zero_eval (v) : zero.eval v = pure [0] := by simp [zero] /-- `pred` returns the predecessor of the head of the input: `pred [] = [0]`, `pred (0 :: v) = [0]`, `pred (n+1 :: v) = [n]`. -/ def pred : code := case zero head @[simp] theorem pred_eval (v) : pred.eval v = pure [v.head.pred] := by simp [pred]; cases v.head; simp /-- `rfind f` performs the function of the `rfind` primitive of partial recursive functions. `rfind f v` returns the smallest `n` such that `(f (n :: v)).head = 0`. It is implemented as: rfind f v = pred (fix (λ (n::v), f (n::v) :: n+1 :: v) (0 :: v)) The idea is that the initial state is `0 :: v`, and the `fix` keeps `n :: v` as its internal state; it calls `f (n :: v)` as the exit test and `n+1 :: v` as the next state. At the end we get `n+1 :: v` where `n` is the desired output, and `pred (n+1 :: v) = [n]` returns the result. -/ def rfind (f : code) : code := comp pred $ comp (fix $ cons f $ cons succ tail) zero' /-- `prec f g` implements the `prec` (primitive recursion) operation of partial recursive functions. `prec f g` evaluates as: * `prec f g [] = [f []]` * `prec f g (0 :: v) = [f v]` * `prec f g (n+1 :: v) = [g (n :: prec f g (n :: v) :: v)]` It is implemented as: G (a :: b :: IH :: v) = (b :: a+1 :: b-1 :: g (a :: IH :: v) :: v) F (0 :: f_v :: v) = (f_v :: v) F (n+1 :: f_v :: v) = (fix G (0 :: n :: f_v :: v)).tail.tail prec f g (a :: v) = [(F (a :: f v :: v)).head] Because `fix` always evaluates its body at least once, we must special case the `0` case to avoid calling `g` more times than necessary (which could be bad if `g` diverges). If the input is `0 :: v`, then `F (0 :: f v :: v) = (f v :: v)` so we return `[f v]`. If the input is `n+1 :: v`, we evaluate the function from the bottom up, with initial state `0 :: n :: f v :: v`. The first number counts up, providing arguments for the applications to `g`, while the second number counts down, providing the exit condition (this is the initial `b` in the return value of `G`, which is stripped by `fix`). After the `fix` is complete, the final state is `n :: 0 :: res :: v` where `res` is the desired result, and the rest reduces this to `[res]`. -/ def prec (f g : code) : code := let G := cons tail $ cons succ $ cons (comp pred tail) $ cons (comp g $ cons id $ comp tail tail) $ comp tail $ comp tail tail in let F := case id $ comp (comp (comp tail tail) (fix G)) zero' in cons (comp F (cons head $ cons (comp f tail) tail)) nil local attribute [-simp] roption.bind_eq_bind roption.map_eq_map roption.pure_eq_some theorem exists_code.comp {m n} {f : vector ℕ n →. ℕ} {g : fin n → vector ℕ m →. ℕ} (hf : ∃ c : code, ∀ v : vector ℕ n, c.eval v.1 = pure <$> f v) (hg : ∀ i, ∃ c : code, ∀ v : vector ℕ m, c.eval v.1 = pure <$> g i v) : ∃ c : code, ∀ v : vector ℕ m, c.eval v.1 = pure <$> (vector.m_of_fn (λ i, g i v) >>= f) := begin suffices : ∃ c : code, ∀ v : vector ℕ m, c.eval v.1 = subtype.val <$> vector.m_of_fn (λ i, g i v), { obtain ⟨cf, hf⟩ := hf, obtain ⟨cg, hg⟩ := this, exact ⟨cf.comp cg, λ v, by { simp [hg, hf, map_bind, seq_bind_eq, (∘), -subtype.val_eq_coe], refl }⟩ }, clear hf f, induction n with n IH, { exact ⟨nil, λ v, by simp [vector.m_of_fn]; refl⟩ }, { obtain ⟨cg, hg₁⟩ := hg 0, obtain ⟨cl, hl⟩ := IH (λ i, hg i.succ), exact ⟨cons cg cl, λ v, by { simp [vector.m_of_fn, hg₁, map_bind, seq_bind_eq, bind_assoc, (∘), hl, -subtype.val_eq_coe], refl }⟩ }, end theorem exists_code {n} {f : vector ℕ n →. ℕ} (hf : nat.partrec' f) : ∃ c : code, ∀ v : vector ℕ n, c.eval v.1 = pure <$> f v := begin induction hf with n f hf, induction hf, case prim zero { exact ⟨zero', λ ⟨[], _⟩, rfl⟩ }, case prim succ { exact ⟨succ, λ ⟨[v], _⟩, rfl⟩ }, case prim nth : n i { refine fin.succ_rec (λ n, _) (λ n i IH, _) i, { exact ⟨head, λ ⟨list.cons a as, _⟩, by simp; refl⟩ }, { obtain ⟨c, h⟩ := IH, exact ⟨c.comp tail, λ v, by simpa [← vector.nth_tail] using h v.tail⟩ } }, case prim comp : m n f g hf hg IHf IHg { simpa [roption.bind_eq_bind] using exists_code.comp IHf IHg }, case prim prec : n f g hf hg IHf IHg { obtain ⟨cf, hf⟩ := IHf, obtain ⟨cg, hg⟩ := IHg, simp only [roption.map_eq_map, roption.map_some, pfun.coe_val] at hf hg, refine ⟨prec cf cg, λ v, _⟩, rw ← v.cons_head_tail, specialize hf v.tail, replace hg := λ a b, hg (a ::ᵥ b ::ᵥ v.tail), simp only [vector.cons_val, vector.tail_val] at hf hg, simp only [roption.map_eq_map, roption.map_some, vector.cons_val, vector.cons_tail, vector.cons_head, pfun.coe_val, vector.tail_val], simp only [← roption.pure_eq_some] at hf hg ⊢, induction v.head with n IH; simp [prec, hf, bind_assoc, ← roption.map_eq_map, ← bind_pure_comp_eq_map, show ∀ x, pure x = [x], from λ _, rfl, -subtype.val_eq_coe], suffices : ∀ a b, a + b = n → (n.succ :: 0 :: g (n ::ᵥ (nat.elim (f v.tail) (λ y IH, g (y ::ᵥ IH ::ᵥ v.tail)) n) ::ᵥ v.tail) :: v.val.tail : list ℕ) ∈ pfun.fix (λ v : list ℕ, do x ← cg.eval (v.head :: v.tail.tail), pure $ if v.tail.head = 0 then sum.inl (v.head.succ :: v.tail.head.pred :: x.head :: v.tail.tail.tail : list ℕ) else sum.inr (v.head.succ :: v.tail.head.pred :: x.head :: v.tail.tail.tail)) (a :: b :: nat.elim (f v.tail) (λ y IH, g (y ::ᵥ IH ::ᵥ v.tail)) a :: v.val.tail), { rw (_ : pfun.fix _ _ = pure _), swap, exact roption.eq_some_iff.2 (this 0 n (zero_add n)), simp only [list.head, pure_bind, list.tail_cons] }, intros a b e, induction b with b IH generalizing a e, { refine pfun.mem_fix_iff.2 (or.inl $ roption.eq_some_iff.1 _), simp only [hg, ← e, pure_bind, list.tail_cons], refl }, { refine pfun.mem_fix_iff.2 (or.inr ⟨_, _, IH (a+1) (by rwa add_right_comm)⟩), simp only [hg, eval, pure_bind, nat.elim_succ, list.tail], exact roption.mem_some_iff.2 rfl } }, case comp : m n f g hf hg IHf IHg { exact exists_code.comp IHf IHg }, case rfind : n f hf IHf { obtain ⟨cf, hf⟩ := IHf, refine ⟨rfind cf, λ v, _⟩, replace hf := λ a, hf (a ::ᵥ v), simp only [roption.map_eq_map, roption.map_some, vector.cons_val, pfun.coe_val, show ∀ x, pure x = [x], from λ _, rfl] at hf ⊢, refine roption.ext (λ x, _), simp only [rfind, roption.bind_eq_bind, roption.pure_eq_some, roption.map_eq_map, roption.bind_some, exists_prop, eval, list.head, pred_eval, roption.map_some, bool.ff_eq_to_bool_iff, roption.mem_bind_iff, list.length, roption.mem_map_iff, nat.mem_rfind, list.tail, bool.tt_eq_to_bool_iff, roption.mem_some_iff, roption.map_bind], split, { rintro ⟨v', h1, rfl⟩, suffices : ∀ (v₁ : list ℕ), v' ∈ pfun.fix (λ v, (cf.eval v).bind $ λ y, roption.some $ if y.head = 0 then sum.inl (v.head.succ :: v.tail) else sum.inr (v.head.succ :: v.tail)) v₁ → ∀ n, v₁ = n :: v.val → (∀ m < n, ¬f (m ::ᵥ v) = 0) → (∃ (a : ℕ), (f (a ::ᵥ v) = 0 ∧ ∀ {m : ℕ}, m < a → ¬f (m ::ᵥ v) = 0) ∧ [a] = [v'.head.pred]), { exact this _ h1 0 rfl (by rintro _ ⟨⟩) }, clear h1, intros v₀ h1, refine pfun.fix_induction h1 (λ v₁ h2 IH, _), clear h1, rintro n rfl hm, have := pfun.mem_fix_iff.1 h2, simp only [hf, roption.bind_some] at this, split_ifs at this, { simp only [list.head, exists_false, or_false, roption.mem_some_iff, list.tail_cons, false_and] at this, subst this, exact ⟨_, ⟨h, hm⟩, rfl⟩ }, { simp only [list.head, exists_eq_left, roption.mem_some_iff, list.tail_cons, false_or] at this, refine IH _ this (by simp [hf, h, -subtype.val_eq_coe]) _ rfl (λ m h', _), obtain h|rfl := nat.lt_succ_iff_lt_or_eq.1 h', exacts [hm _ h, h] } }, { rintro ⟨n, ⟨hn, hm⟩, rfl⟩, refine ⟨n.succ :: v.1, _, rfl⟩, have : (n.succ :: v.1 : list ℕ) ∈ pfun.fix (λ v, (cf.eval v).bind $ λ y, roption.some $ if y.head = 0 then sum.inl (v.head.succ :: v.tail) else sum.inr (v.head.succ :: v.tail)) (n :: v.val) := pfun.mem_fix_iff.2 (or.inl (by simp [hf, hn, -subtype.val_eq_coe])), generalize_hyp : (n.succ :: v.1 : list ℕ) = w at this ⊢, clear hn, induction n with n IH, {exact this}, refine IH (λ m h', hm (nat.lt_succ_of_lt h')) (pfun.mem_fix_iff.2 (or.inr ⟨_, _, this⟩)), simp only [hf, hm n.lt_succ_self, roption.bind_some, list.head, eq_self_iff_true, if_false, roption.mem_some_iff, and_self, list.tail_cons] } } end end code /-! ## From compositional semantics to sequential semantics Our initial sequential model is designed to be as similar as possible to the compositional semantics in terms of its primitives, but it is a sequential semantics, meaning that rather than defining an `eval c : list ℕ →. list ℕ` function for each program, defined by recursion on programs, we have a type `cfg` with a step function `step : cfg → option cfg` that provides a deterministic evaluation order. In order to do this, we introduce the notion of a *continuation*, which can be viewed as a `code` with a hole in it where evaluation is currently taking place. Continuations can be assigned a `list ℕ →. list ℕ` semantics as well, with the interpretation being that given a `list ℕ` result returned from the code in the hole, the remainder of the program will evaluate to a `list ℕ` final value. The continuations are: * `halt`: the empty continuation: the hole is the whole program, whatever is returned is the final result. In our notation this is just `_`. * `cons₁ fs v k`: evaluating the first part of a `cons`, that is `k (_ :: fs v)`, where `k` is the outer continuation. * `cons₂ ns k`: evaluating the second part of a `cons`: `k (ns.head :: _)`. (Technically we don't need to hold on to all of `ns` here since we are already committed to taking the head, but this is more regular.) * `comp f k`: evaluating the first part of a composition: `k (f _)`. * `fix f k`: waiting for the result of `f` in a `fix f` expression: `k (if _.head = 0 then _.tail else fix f (_.tail))` The type `cfg` of evaluation states is: * `ret k v`: we have received a result, and are now evaluating the continuation `k` with result `v`; that is, `k v` where `k` is ready to evaluate. * `halt v`: we are done and the result is `v`. The main theorem of this section is that for each code `c`, the state `step_normal c halt v` steps to `v'` in finitely many steps if and only if `code.eval c v = some v'`. -/ /-- The type of continuations, built up during evaluation of a `code` expression. -/ @[derive inhabited] inductive cont | halt | cons₁ : code → list ℕ → cont → cont | cons₂ : list ℕ → cont → cont | comp : code → cont → cont | fix : code → cont → cont /-- The semantics of a continuation. -/ def cont.eval : cont → list ℕ →. list ℕ | cont.halt := pure | (cont.cons₁ fs as k) := λ v, do ns ← code.eval fs as, cont.eval k (v.head :: ns) | (cont.cons₂ ns k) := λ v, cont.eval k (ns.head :: v) | (cont.comp f k) := λ v, code.eval f v >>= cont.eval k | (cont.fix f k) := λ v, if v.head = 0 then k.eval v.tail else f.fix.eval v.tail >>= k.eval /-- The semantics of a continuation. -/ @[derive inhabited] inductive cfg | halt : list ℕ → cfg | ret : cont → list ℕ → cfg /-- Evaluating `c : code` in a continuation `k : cont` and input `v : list ℕ`. This goes by recursion on `c`, building an augmented continuation and a value to pass to it. * `zero' v = 0 :: v` evaluates immediately, so we return it to the parent continuation * `succ v = [v.head.succ]` evaluates immediately, so we return it to the parent continuation * `tail v = v.tail` evaluates immediately, so we return it to the parent continuation * `cons f fs v = (f v).head :: fs v` requires two sub-evaluations, so we evaluate `f v` in the continuation `k (_.head :: fs v)` (called `cont.cons₁ fs v k`) * `comp f g v = f (g v)` requires two sub-evaluations, so we evaluate `g v` in the continuation `k (f _)` (called `cont.comp f k`) * `case f g v = v.head.cases_on (f v.tail) (λ n, g (n :: v.tail))` has the information needed to evaluate the case statement, so we do that and transition to either `f v` or `g (n :: v.tail)`. * `fix f v = let v' := f v in if v'.head = 0 then k v'.tail else fix f v'.tail` needs to first evaluate `f v`, so we do that and leave the rest for the continuation (called `cont.fix f k`) -/ def step_normal : code → cont → list ℕ → cfg | code.zero' k v := cfg.ret k (0 :: v) | code.succ k v := cfg.ret k [v.head.succ] | code.tail k v := cfg.ret k v.tail | (code.cons f fs) k v := step_normal f (cont.cons₁ fs v k) v | (code.comp f g) k v := step_normal g (cont.comp f k) v | (code.case f g) k v := v.head.elim (step_normal f k v.tail) (λ y _, step_normal g k (y :: v.tail)) | (code.fix f) k v := step_normal f (cont.fix f k) v /-- Evaluating a continuation `k : cont` on input `v : list ℕ`. This is the second part of evaluation, when we receive results from continuations built by `step_normal`. * `cont.halt v = v`, so we are done and transition to the `cfg.halt v` state * `cont.cons₁ fs as k v = k (v.head :: fs as)`, so we evaluate `fs as` now with the continuation `k (v.head :: _)` (called `cons₂ v k`). * `cont.cons₂ ns k v = k (ns.head :: v)`, where we now have everything we need to evaluate `ns.head :: v`, so we return it to `k`. * `cont.comp f k v = k (f v)`, so we call `f v` with `k` as the continuation. * `cont.fix f k v = k (if v.head = 0 then k v.tail else fix f v.tail)`, where `v` is a value, so we evaluate the if statement and either call `k` with `v.tail`, or call `fix f v` with `k` as the continuation (which immediately calls `f` with `cont.fix f k` as the continuation). -/ def step_ret : cont → list ℕ → cfg | cont.halt v := cfg.halt v | (cont.cons₁ fs as k) v := step_normal fs (cont.cons₂ v k) as | (cont.cons₂ ns k) v := step_ret k (ns.head :: v) | (cont.comp f k) v := step_normal f k v | (cont.fix f k) v := if v.head = 0 then step_ret k v.tail else step_normal f (cont.fix f k) v.tail /-- If we are not done (in `cfg.halt` state), then we must be still stuck on a continuation, so this main loop calls `step_ret` with the new continuation. The overall `step` function transitions from one `cfg` to another, only halting at the `cfg.halt` state. -/ def step : cfg → option cfg | (cfg.halt _) := none | (cfg.ret k v) := some (step_ret k v) /-- In order to extract a compositional semantics from the sequential execution behavior of configurations, we observe that continuations have a monoid structure, with `cont.halt` as the unit and `cont.then` as the multiplication. `cont.then k₁ k₂` runs `k₁` until it halts, and then takes the result of `k₁` and passes it to `k₂`. We will not prove it is associative (although it is), but we are instead interested in the associativity law `k₂ (eval c k₁) = eval c (k₁.then k₂)`. This holds at both the sequential and compositional levels, and allows us to express running a machine without the ambient continuation and relate it to the original machine's evaluation steps. In the literature this is usually where one uses Turing machines embedded inside other Turing machines, but this approach allows us to avoid changing the ambient type `cfg` in the middle of the recursion. -/ def cont.then : cont → cont → cont | cont.halt k' := k' | (cont.cons₁ fs as k) k' := cont.cons₁ fs as (k.then k') | (cont.cons₂ ns k) k' := cont.cons₂ ns (k.then k') | (cont.comp f k) k' := cont.comp f (k.then k') | (cont.fix f k) k' := cont.fix f (k.then k') theorem cont.then_eval {k k' : cont} {v} : (k.then k').eval v = k.eval v >>= k'.eval := begin induction k generalizing v; simp only [cont.eval, cont.then, bind_assoc, pure_bind, *], { simp only [← k_ih] }, { split_ifs; [refl, simp only [← k_ih, bind_assoc]] } end /-- The `then k` function is a "configuration homomorphism". Its operation on states is to append `k` to the continuation of a `cfg.ret` state, and to run `k` on `v` if we are in the `cfg.halt v` state. -/ def cfg.then : cfg → cont → cfg | (cfg.halt v) k' := step_ret k' v | (cfg.ret k v) k' := cfg.ret (k.then k') v /-- The `step_normal` function respects the `then k'` homomorphism. Note that this is an exact equality, not a simulation; the original and embedded machines move in lock-step until the embedded machine reaches the halt state. -/ theorem step_normal_then (c) (k k' : cont) (v) : step_normal c (k.then k') v = (step_normal c k v).then k' := begin induction c with generalizing k v; simp only [cont.then, step_normal, cfg.then, *] {constructor_eq := ff}, case turing.to_partrec.code.cons : c c' ih ih' { rw [← ih, cont.then] }, case turing.to_partrec.code.comp : c c' ih ih' { rw [← ih', cont.then] }, { cases v.head; simp only [nat.elim] }, case turing.to_partrec.code.fix : c ih { rw [← ih, cont.then] }, end /-- The `step_ret` function respects the `then k'` homomorphism. Note that this is an exact equality, not a simulation; the original and embedded machines move in lock-step until the embedded machine reaches the halt state. -/ theorem step_ret_then {k k' : cont} {v} : step_ret (k.then k') v = (step_ret k v).then k' := begin induction k generalizing v; simp only [cont.then, step_ret, cfg.then, *], { rw ← step_normal_then, refl }, { rw ← step_normal_then }, { split_ifs, {rw ← k_ih}, {rw ← step_normal_then, refl} }, end /-- This is a temporary definition, because we will prove in `code_is_ok` that it always holds. It asserts that `c` is semantically correct; that is, for any `k` and `v`, `eval (step_normal c k v) = eval (cfg.ret k (code.eval c v))`, as an equality of partial values (so one diverges iff the other does). In particular, we can let `k = cont.halt`, and then this asserts that `step_normal c cont.halt v` evaluates to `cfg.halt (code.eval c v)`. -/ def code.ok (c : code) := ∀ k v, eval step (step_normal c k v) = code.eval c v >>= λ v, eval step (cfg.ret k v) theorem code.ok.zero {c} (h : code.ok c) {v} : eval step (step_normal c cont.halt v) = cfg.halt <$> code.eval c v := begin rw [h, ← bind_pure_comp_eq_map], congr, funext v, exact roption.eq_some_iff.2 (mem_eval.2 ⟨refl_trans_gen.single rfl, rfl⟩), end theorem step_normal.is_ret (c k v) : ∃ k' v', step_normal c k v = cfg.ret k' v' := begin induction c generalizing k v, iterate 3 { exact ⟨_, _, rfl⟩ }, case cons : f fs IHf IHfs { apply IHf }, case comp : f g IHf IHg { apply IHg }, case case : f g IHf IHg { rw step_normal, cases v.head; simp only [nat.elim]; [apply IHf, apply IHg] }, case fix : f IHf { apply IHf }, end theorem cont_eval_fix {f k v} (fok : code.ok f) : eval step (step_normal f (cont.fix f k) v) = f.fix.eval v >>= λ v, eval step (cfg.ret k v) := begin refine roption.ext (λ x, _), simp only [roption.bind_eq_bind, roption.mem_bind_iff], split, { suffices : ∀ c, x ∈ eval step c → ∀ v c', c = cfg.then c' (cont.fix f k) → reaches step (step_normal f cont.halt v) c' → ∃ v₁ ∈ f.eval v, ∃ v₂ ∈ (if list.head v₁ = 0 then pure v₁.tail else f.fix.eval v₁.tail), x ∈ eval step (cfg.ret k v₂), { intro h, obtain ⟨v₁, hv₁, v₂, hv₂, h₃⟩ := this _ h _ _ (step_normal_then _ cont.halt _ _) refl_trans_gen.refl, refine ⟨v₂, pfun.mem_fix_iff.2 _, h₃⟩, simp only [roption.eq_some_iff.2 hv₁, roption.map_some], split_ifs at hv₂ ⊢, { rw roption.mem_some_iff.1 hv₂, exact or.inl (roption.mem_some _) }, { exact or.inr ⟨_, roption.mem_some _, hv₂⟩ } }, refine λ c he, eval_induction he (λ y h IH, _), rintro v (⟨v'⟩ | ⟨k',v'⟩) rfl hr; rw cfg.then at h IH, { have := mem_eval.2 ⟨hr, rfl⟩, rw [fok, roption.bind_eq_bind, roption.mem_bind_iff] at this, obtain ⟨v'', h₁, h₂⟩ := this, rw reaches_eval at h₂, swap, exact refl_trans_gen.single rfl, cases roption.mem_unique h₂ (mem_eval.2 ⟨refl_trans_gen.refl, rfl⟩), refine ⟨v', h₁, _⟩, rw [step_ret] at h, revert h, by_cases he : v'.head = 0; simp only [exists_prop, if_pos, if_false, he]; intro h, { refine ⟨_, roption.mem_some _, _⟩, rw reaches_eval, exact h, exact refl_trans_gen.single rfl }, { obtain ⟨k₀, v₀, e₀⟩ := step_normal.is_ret f cont.halt v'.tail, have e₁ := step_normal_then f cont.halt (cont.fix f k) v'.tail, rw [e₀, cont.then, cfg.then] at e₁, obtain ⟨v₁, hv₁, v₂, hv₂, h₃⟩ := IH (step_ret (k₀.then (cont.fix f k)) v₀) _ _ v'.tail _ step_ret_then _, { refine ⟨_, pfun.mem_fix_iff.2 _, h₃⟩, simp only [roption.eq_some_iff.2 hv₁, roption.map_some, roption.mem_some_iff], split_ifs at hv₂ ⊢; [exact or.inl (roption.mem_some_iff.1 hv₂), exact or.inr ⟨_, rfl, hv₂⟩] }, { rwa [← @reaches_eval _ _ (cfg.ret (k₀.then (cont.fix f k)) v₀), ← e₁], exact refl_trans_gen.single rfl }, { rw [step_ret, if_neg he, e₁], refl }, { apply refl_trans_gen.single, rw e₀, exact rfl } } }, { rw reaches_eval at h, swap, exact refl_trans_gen.single rfl, exact IH _ h rfl _ _ step_ret_then (refl_trans_gen.tail hr rfl) } }, { rintro ⟨v', he, hr⟩, rw reaches_eval at hr, swap, exact refl_trans_gen.single rfl, refine pfun.fix_induction he (λ v (he : v' ∈ f.fix.eval v) IH, _), rw [fok, roption.bind_eq_bind, roption.mem_bind_iff], obtain he | ⟨v'', he₁', he₂'⟩ := pfun.mem_fix_iff.1 he, { obtain ⟨v', he₁, he₂⟩ := (roption.mem_map_iff _).1 he, split_ifs at he₂; cases he₂, refine ⟨_, he₁, _⟩, rw reaches_eval, swap, exact refl_trans_gen.single rfl, rwa [step_ret, if_pos h] }, { obtain ⟨v₁, he₁, he₂⟩ := (roption.mem_map_iff _).1 he₁', split_ifs at he₂; cases he₂, clear he₂ he₁', change _ ∈ f.fix.eval _ at he₂', refine ⟨_, he₁, _⟩, rw reaches_eval, swap, exact refl_trans_gen.single rfl, rwa [step_ret, if_neg h], exact IH v₁.tail he₂' ((roption.mem_map_iff _).2 ⟨_, he₁, if_neg h⟩) } } end theorem code_is_ok (c) : code.ok c := begin induction c; intros k v; rw step_normal, iterate 3 { simp only [code.eval, pure_bind] }, case cons : f fs IHf IHfs { rw [code.eval, IHf], simp only [bind_assoc, cont.eval, pure_bind], congr, funext v, rw [reaches_eval], swap, exact refl_trans_gen.single rfl, rw [step_ret, IHfs], congr, funext v', refine eq.trans _ (eq.symm _); try {exact reaches_eval (refl_trans_gen.single rfl)} }, case comp : f g IHf IHg { rw [code.eval, IHg], simp only [bind_assoc, cont.eval, pure_bind], congr, funext v, rw [reaches_eval], swap, exact refl_trans_gen.single rfl, rw [step_ret, IHf] }, case case : f g IHf IHg { simp only [code.eval], cases v.head; simp only [nat.elim, code.eval]; [apply IHf, apply IHg] }, case fix : f IHf { rw cont_eval_fix IHf }, end theorem step_normal_eval (c v) : eval step (step_normal c cont.halt v) = cfg.halt <$> c.eval v := (code_is_ok c).zero theorem step_ret_eval {k v} : eval step (step_ret k v) = cfg.halt <$> k.eval v := begin induction k generalizing v, case halt : { simp only [mem_eval, cont.eval, map_pure], exact roption.eq_some_iff.2 (mem_eval.2 ⟨refl_trans_gen.refl, rfl⟩) }, case cons₁ : fs as k IH { rw [cont.eval, step_ret, code_is_ok], simp only [← bind_pure_comp_eq_map, bind_assoc], congr, funext v', rw [reaches_eval], swap, exact refl_trans_gen.single rfl, rw [step_ret, IH, bind_pure_comp_eq_map] }, case cons₂ : ns k IH { rw [cont.eval, step_ret], exact IH }, case comp : f k IH { rw [cont.eval, step_ret, code_is_ok], simp only [← bind_pure_comp_eq_map, bind_assoc], congr, funext v', rw [reaches_eval], swap, exact refl_trans_gen.single rfl, rw [IH, bind_pure_comp_eq_map] }, case fix : f k IH { rw [cont.eval, step_ret], simp only [bind_pure_comp_eq_map], split_ifs, { exact IH }, simp only [← bind_pure_comp_eq_map, bind_assoc, cont_eval_fix (code_is_ok _)], congr, funext, rw [bind_pure_comp_eq_map, ← IH], exact reaches_eval (refl_trans_gen.single rfl) }, end end to_partrec /-! ## Simulating sequentialized partial recursive functions in TM2 At this point we have a sequential model of partial recursive functions: the `cfg` type and `step : cfg → option cfg` function from the previous section. The key feature of this model is that it does a finite amount of computation (in fact, an amount which is statically bounded by the size of the program) between each step, and no individual step can diverge (unlike the compositional semantics, where every sub-part of the computation is potentially divergent). So we can utilize the same techniques as in the other TM simulations in `computability.turing_machine` to prove that each step corresponds to a finite number of steps in a lower level model. (We don't prove it here, but in anticipation of the complexity class P, the simulation is actually polynomial-time as well.) The target model is `turing.TM2`, which has a fixed finite set of stacks, a bit of local storage, with programs selected from a potentially infinite (but finitely accessible) set of program positions, or labels `Λ`, each of which executes a finite sequence of basic stack commands. For this program we will need four stacks, each on an alphabet `Γ'` like so: inductive Γ' | Cons | cons | bit0 | bit1 We represent a number as a bit sequence, lists of numbers by putting `cons` after each element, and lists of lists of natural numbers by putting `Cons` after each list. For example: 0 ~> [] 1 ~> [bit1] 6 ~> [bit0, bit1, bit1] [1, 2] ~> [bit1, cons, bit0, bit1, cons] [[], [1, 2]] ~> [Cons, bit1, cons, bit0, bit1, cons, Cons] The four stacks are `main`, `rev`, `aux`, `stack`. In normal mode, `main` contains the input to the current program (a `list ℕ`) and `stack` contains data (a `list (list ℕ)`) associated to the current continuation, and in `ret` mode `main` contains the value that is being passed to the continuation and `stack` contains the data for the continuation. The `rev` and `aux` stacks are usually empty; `rev` is used to store reversed data when e.g. moving a value from one stack to another, while `aux` is used as a temporary for a `main`/`stack` swap that happens during `cons₁` evaluation. The only local store we need is `option Γ'`, which stores the result of the last pop operation. (Most of our working data are natural numbers, which are too large to fit in the local store.) The continuations from the previous section are data-carrying, containing all the values that have been computed and are awaiting other arguments. In order to have only a finite number of continuations appear in the program so that they can be used in machine states, we separate the data part (anything with type `list ℕ`) from the `cont` type, producing a `cont'` type that lacks this information. The data is kept on the `stack` stack. Because we want to have subroutines for e.g. moving an entire stack to another place, we use an infinite inductive type `Λ'` so that we can execute a program and then return to do something else without having to define too many different kinds of intermediate states. (We must nevertheless prove that only finitely many labels are accessible.) The labels are: * `move p k₁ k₂ q`: move elements from stack `k₁` to `k₂` while `p` holds of the value being moved. The last element, that fails `p`, is placed in neither stack but left in the local store. At the end of the operation, `k₂` will have the elements of `k₁` in reverse order. Then do `q`. * `clear p k q`: delete elements from stack `k` until `p` is true. Like `move`, the last element is left in the local storage. Then do `q`. * `copy q`: Move all elements from `rev` to both `main` and `stack` (in reverse order), then do `q`. That is, it takes `(a, b, c, d)` to `(b.reverse ++ a, [], c, b.reverse ++ d)`. * `push k f q`: push `f s`, where `s` is the local store, to stack `k`, then do `q`. This is a duplicate of the `push` instruction that is part of the TM2 model, but by having a subroutine just for this purpose we can build up programs to execute inside a `goto` statement, where we have the flexibility to be general recursive. * `read (f : option Γ' → Λ')`: go to state `f s` where `s` is the local store. Again this is only here for convenience. * `succ q`: perform a successor operation. Assuming `[n]` is encoded on `main` before, `[n+1]` will be on main after. This implements successor for binary natural numbers. * `pred q₁ q₂`: perform a predecessor operation or `case` statement. If `[]` is encoded on `main` before, then we transition to `q₁` with `[]` on main; if `(0 :: v)` is on `main` before then `v` will be on `main` after and we transition to `q₁`; and if `(n+1 :: v)` is on `main` before then `n :: v` will be on `main` after and we transition to `q₂`. * `ret k`: call continuation `k`. Each continuation has its own interpretation of the data in `stack` and sets up the data for the next continuation. * `ret (cons₁ fs k)`: `v :: k_data` on `stack` and `ns` on `main`, and the next step expects `v` on `main` and `ns :: k_data` on `stack`. So we have to do a little dance here with six reverse-moves using the `aux` stack to perform a three-point swap, each of which involves two reversals. * `ret (cons₂ k)`: `ns :: k_data` is on `stack` and `v` is on `main`, and we have to put `ns.head :: v` on `main` and `k_data` on `stack`. This is done using the `head` subroutine. * `ret (fix f k)`: This stores no data, so we just check if `main` starts with `0` and if so, remove it and call `k`, otherwise `clear` the first value and call `f`. * `ret halt`: the stack is empty, and `main` has the output. Do nothing and halt. In addition to these basic states, we define some additional subroutines that are used in the above: * `push'`, `peek'`, `pop'` are special versions of the builtins that use the local store to supply inputs and outputs. * `unrev`: special case `move ff rev main` to move everything from `rev` back to `main`. Used as a cleanup operation in several functions. * `move_excl p k₁ k₂ q`: same as `move` but pushes the last value read back onto the source stack. * `move₂ p k₁ k₂ q`: double `move`, so that the result comes out in the right order at the target stack. Implemented as `move_excl p k rev; move ff rev k₂`. Assumes that neither `k₁` nor `k₂` is `rev` and `rev` is initially empty. * `head k q`: get the first natural number from stack `k` and reverse-move it to `rev`, then clear the rest of the list at `k` and then `unrev` to reverse-move the head value to `main`. This is used with `k = main` to implement regular `head`, i.e. if `v` is on `main` before then `[v.head]` will be on `main` after; and also with `k = stack` for the `cons` operation, which has `v` on `main` and `ns :: k_data` on `stack`, and results in `k_data` on `stack` and `ns.head :: v` on `main`. * `tr_normal` is the main entry point, defining states that perform a given `code` computation. It mostly just dispatches to functions written above. The main theorem of this section is `tr_eval`, which asserts that for each that for each code `c`, the state `init c v` steps to `halt v'` in finitely many steps if and only if `code.eval c v = some v'`. -/ namespace partrec_to_TM2 section open to_partrec /-- The alphabet for the stacks in the program. `bit0` and `bit1` are used to represent `ℕ` values as lists of binary digits, `cons` is used to separate `list ℕ` values, and `Cons` is used to separate `list (list ℕ)` values. See the section documentation. -/ @[derive [decidable_eq, inhabited]] inductive Γ' | Cons | cons | bit0 | bit1 /-- The four stacks used by the program. `main` is used to store the input value in `tr_normal` mode and the output value in `Λ'.ret` mode, while `stack` is used to keep all the data for the continuations. `rev` is used to store reversed lists when transferring values between stacks, and `aux` is only used once in `cons₁`. See the section documentation. -/ @[derive [decidable_eq, inhabited]] inductive K' | main | rev | aux | stack open K' /-- Continuations as in `to_partrec.cont` but with the data removed. This is done because we want the set of all continuations in the program to be finite (so that it can ultimately be encoded into the finite state machine of a Turing machine), but a continuation can handle a potentially infinite number of data values during execution. -/ @[derive inhabited] inductive cont' | halt | cons₁ : code → cont' → cont' | cons₂ : cont' → cont' | comp : code → cont' → cont' | fix : code → cont' → cont' /-- The set of program positions. We make extensive use of inductive types here to let us describe "subroutines"; for example `clear p k q` is a program that clears stack `k`, then does `q` where `q` is another label. In order to prevent this from resulting in an infinite number of distinct accessible states, we are careful to be non-recursive (although loops are okay). See the section documentation for a description of all the programs. -/ inductive Λ' | move (p : Γ' → bool) (k₁ k₂ : K') (q : Λ') | clear (p : Γ' → bool) (k : K') (q : Λ') | copy (q : Λ') | push (k : K') (s : option Γ' → option Γ') (q : Λ') | read (f : option Γ' → Λ') | succ (q : Λ') | pred (q₁ q₂ : Λ') | ret (k : cont') instance : inhabited Λ' := ⟨Λ'.ret cont'.halt⟩ /-- The type of TM2 statements used by this machine. -/ @[derive inhabited] def stmt' := TM2.stmt (λ _:K', Γ') Λ' (option Γ') /-- The type of TM2 configurations used by this machine. -/ @[derive inhabited] def cfg' := TM2.cfg (λ _:K', Γ') Λ' (option Γ') open TM2.stmt /-- A predicate that detects the end of a natural number, either `Γ'.cons` or `Γ'.Cons` (or implicitly the end of the list), for use in predicate-taking functions like `move` and `clear`. -/ def nat_end : Γ' → bool | Γ'.Cons := tt | Γ'.cons := tt | _ := ff /-- Pop a value from the stack and place the result in local store. -/ @[simp] def pop' (k : K') : stmt' → stmt' := pop k (λ x v, v) /-- Peek a value from the stack and place the result in local store. -/ @[simp] def peek' (k : K') : stmt' → stmt' := peek k (λ x v, v) /-- Push the value in the local store to the given stack. -/ @[simp] def push' (k : K') : stmt' → stmt' := push k (λ x, x.iget) /-- Move everything from the `rev` stack to the `main` stack (reversed). -/ def unrev := Λ'.move (λ _, ff) rev main /-- Move elements from `k₁` to `k₂` while `p` holds, with the last element being left on `k₁`. -/ def move_excl (p k₁ k₂ q) := Λ'.move p k₁ k₂ $ Λ'.push k₁ id q /-- Move elements from `k₁` to `k₂` without reversion, by performing a double move via the `rev` stack. -/ def move₂ (p k₁ k₂ q) := move_excl p k₁ rev $ Λ'.move (λ _, ff) rev k₂ q /-- Assuming `tr_list v` is on the front of stack `k`, remove it, and push `v.head` onto `main`. See the section documentation. -/ def head (k : K') (q : Λ') : Λ' := Λ'.move nat_end k rev $ Λ'.push rev (λ _, some Γ'.cons) $ Λ'.read $ λ s, (if s = some Γ'.Cons then id else Λ'.clear (λ x, x = Γ'.Cons) k) $ unrev q /-- The program that evaluates code `c` with continuation `k`. This expects an initial state where `tr_list v` is on `main`, `tr_cont_stack k` is on `stack`, and `aux` and `rev` are empty. See the section documentation for details. -/ @[simp] def tr_normal : code → cont' → Λ' | code.zero' k := Λ'.push main (λ _, some Γ'.cons) $ Λ'.ret k | code.succ k := head main $ Λ'.succ $ Λ'.ret k | code.tail k := Λ'.clear nat_end main $ Λ'.ret k | (code.cons f fs) k := Λ'.push stack (λ _, some Γ'.Cons) $ Λ'.move (λ _, ff) main rev $ Λ'.copy $ tr_normal f (cont'.cons₁ fs k) | (code.comp f g) k := tr_normal g (cont'.comp f k) | (code.case f g) k := Λ'.pred (tr_normal f k) (tr_normal g k) | (code.fix f) k := tr_normal f (cont'.fix f k) /-- The main program. See the section documentation for details. -/ @[simp] def tr : Λ' → stmt' | (Λ'.move p k₁ k₂ q) := pop' k₁ $ branch (λ s, s.elim tt p) ( goto $ λ _, q ) ( push' k₂ $ goto $ λ _, Λ'.move p k₁ k₂ q ) | (Λ'.push k f q) := branch (λ s, (f s).is_some) ( push k (λ s, (f s).iget) $ goto $ λ _, q ) ( goto $ λ _, q ) | (Λ'.read q) := goto q | (Λ'.clear p k q) := pop' k $ branch (λ s, s.elim tt p) ( goto $ λ _, q ) ( goto $ λ _, Λ'.clear p k q ) | (Λ'.copy q) := pop' rev $ branch option.is_some ( push' main $ push' stack $ goto $ λ _, Λ'.copy q ) ( goto $ λ _, q ) | (Λ'.succ q) := pop' main $ branch (λ s, s = some Γ'.bit1) ( push rev (λ _, Γ'.bit0) $ goto $ λ _, Λ'.succ q ) $ branch (λ s, s = some Γ'.cons) ( push main (λ _, Γ'.cons) $ push main (λ _, Γ'.bit1) $ goto $ λ _, unrev q ) ( push main (λ _, Γ'.bit1) $ goto $ λ _, unrev q ) | (Λ'.pred q₁ q₂) := pop' main $ branch (λ s, s = some Γ'.bit0) ( push rev (λ _, Γ'.bit1) $ goto $ λ _, Λ'.pred q₁ q₂ ) $ branch (λ s, nat_end s.iget) ( goto $ λ _, q₁ ) ( peek' main $ branch (λ s, nat_end s.iget) ( goto $ λ _, unrev q₂ ) ( push rev (λ _, Γ'.bit0) $ goto $ λ _, unrev q₂ ) ) | (Λ'.ret (cont'.cons₁ fs k)) := goto $ λ _, move₂ (λ _, ff) main aux $ move₂ (λ s, s = Γ'.Cons) stack main $ move₂ (λ _, ff) aux stack $ tr_normal fs (cont'.cons₂ k) | (Λ'.ret (cont'.cons₂ k)) := goto $ λ _, head stack $ Λ'.ret k | (Λ'.ret (cont'.comp f k)) := goto $ λ _, tr_normal f k | (Λ'.ret (cont'.fix f k)) := pop' main $ goto $ λ s, cond (nat_end s.iget) (Λ'.ret k) $ Λ'.clear nat_end main $ tr_normal f (cont'.fix f k) | (Λ'.ret cont'.halt) := load (λ _, none) $ halt /-- Translating a `cont` continuation to a `cont'` continuation simply entails dropping all the data. This data is instead encoded in `tr_cont_stack` in the configuration. -/ def tr_cont : cont → cont' | cont.halt := cont'.halt | (cont.cons₁ c _ k) := cont'.cons₁ c (tr_cont k) | (cont.cons₂ _ k) := cont'.cons₂ (tr_cont k) | (cont.comp c k) := cont'.comp c (tr_cont k) | (cont.fix c k) := cont'.fix c (tr_cont k) /-- We use `pos_num` to define the translation of binary natural numbers. A natural number is represented as a little-endian list of `bit0` and `bit1` elements: 1 = [bit1] 2 = [bit0, bit1] 3 = [bit1, bit1] 4 = [bit0, bit0, bit1] In particular, this representation guarantees no trailing `bit0`'s at the end of the list. -/ def tr_pos_num : pos_num → list Γ' | pos_num.one := [Γ'.bit1] | (pos_num.bit0 n) := Γ'.bit0 :: tr_pos_num n | (pos_num.bit1 n) := Γ'.bit1 :: tr_pos_num n /-- We use `num` to define the translation of binary natural numbers. Positive numbers are translated using `tr_pos_num`, and `tr_num 0 = []`. So there are never any trailing `bit0`'s in a translated `num`. 0 = [] 1 = [bit1] 2 = [bit0, bit1] 3 = [bit1, bit1] 4 = [bit0, bit0, bit1] -/ def tr_num : num → list Γ' | num.zero := [] | (num.pos n) := tr_pos_num n /-- Because we use binary encoding, we define `tr_nat` in terms of `tr_num`, using `num`, which are binary natural numbers. (We could also use `nat.binary_rec_on`, but `num` and `pos_num` make for easy inductions.) -/ def tr_nat (n : ℕ) : list Γ' := tr_num n @[simp] theorem tr_nat_zero : tr_nat 0 = [] := rfl /-- Lists are translated with a `cons` after each encoded number. For example: [] = [] [0] = [cons] [1] = [bit1, cons] [6, 0] = [bit0, bit1, bit1, cons, cons] -/ @[simp] def tr_list : list ℕ → list Γ' | [] := [] | (n :: ns) := tr_nat n ++ Γ'.cons :: tr_list ns /-- Lists of lists are translated with a `Cons` after each encoded list. For example: [] = [] [[]] = [Cons] [[], []] = [Cons, Cons] [[0]] = [cons, Cons] [[1, 2], [0]] = [bit1, cons, bit0, bit1, cons, Cons, cons, Cons] -/ @[simp] def tr_llist : list (list ℕ) → list Γ' | [] := [] | (l :: ls) := tr_list l ++ Γ'.Cons :: tr_llist ls /-- The data part of a continuation is a list of lists, which is encoded on the `stack` stack using `tr_llist`. -/ @[simp] def cont_stack : cont → list (list ℕ) | cont.halt := [] | (cont.cons₁ _ ns k) := ns :: cont_stack k | (cont.cons₂ ns k) := ns :: cont_stack k | (cont.comp _ k) := cont_stack k | (cont.fix _ k) := cont_stack k /-- The data part of a continuation is a list of lists, which is encoded on the `stack` stack using `tr_llist`. -/ def tr_cont_stack (k : cont) := tr_llist (cont_stack k) /-- This is the nondependent eliminator for `K'`, but we use it specifically here in order to represent the stack data as four lists rather than as a function `K' → list Γ'`, because this makes rewrites easier. The theorems `K'.elim_update_main` et. al. show how such a function is updated after an `update` to one of the components. -/ @[simp] def K'.elim (a b c d : list Γ') : K' → list Γ' | K'.main := a | K'.rev := b | K'.aux := c | K'.stack := d @[simp] theorem K'.elim_update_main {a b c d a'} : update (K'.elim a b c d) main a' = K'.elim a' b c d := by funext x; cases x; refl @[simp] theorem K'.elim_update_rev {a b c d b'} : update (K'.elim a b c d) rev b' = K'.elim a b' c d := by funext x; cases x; refl @[simp] theorem K'.elim_update_aux {a b c d c'} : update (K'.elim a b c d) aux c' = K'.elim a b c' d := by funext x; cases x; refl @[simp] theorem K'.elim_update_stack {a b c d d'} : update (K'.elim a b c d) stack d' = K'.elim a b c d' := by funext x; cases x; refl /-- The halting state corresponding to a `list ℕ` output value. -/ def halt (v : list ℕ) : cfg' := ⟨none, none, K'.elim (tr_list v) [] [] []⟩ /-- The `cfg` states map to `cfg'` states almost one to one, except that in normal operation the local store contains an arbitrary garbage value. To make the final theorem cleaner we explicitly clear it in the halt state so that there is exactly one configuration corresponding to output `v`. -/ def tr_cfg : cfg → cfg' → Prop | (cfg.ret k v) c' := ∃ s, c' = ⟨some (Λ'.ret (tr_cont k)), s, K'.elim (tr_list v) [] [] (tr_cont_stack k)⟩ | (cfg.halt v) c' := c' = halt v /-- This could be a general list definition, but it is also somewhat specialized to this application. `split_at_pred p L` will search `L` for the first element satisfying `p`. If it is found, say `L = l₁ ++ a :: l₂` where `a` satisfies `p` but `l₁` does not, then it returns `(l₁, some a, l₂)`. Otherwise, if there is no such element, it returns `(L, none, [])`. -/ def split_at_pred {α} (p : α → bool) : list α → list α × option α × list α | [] := ([], none, []) | (a :: as) := cond (p a) ([], some a, as) $ let ⟨l₁, o, l₂⟩ := split_at_pred as in ⟨a :: l₁, o, l₂⟩ theorem split_at_pred_eq {α} (p : α → bool) : ∀ L l₁ o l₂, (∀ x ∈ l₁, p x = ff) → option.elim o (L = l₁ ∧ l₂ = []) (λ a, p a = tt ∧ L = l₁ ++ a :: l₂) → split_at_pred p L = (l₁, o, l₂) | [] _ none _ _ ⟨rfl, rfl⟩ := rfl | [] l₁ (some o) l₂ h₁ ⟨h₂, h₃⟩ := by simp at h₃; contradiction | (a :: L) l₁ o l₂ h₁ h₂ := begin rw [split_at_pred], have IH := split_at_pred_eq L, cases o, { cases l₁ with a' l₁; rcases h₂ with ⟨⟨⟩, rfl⟩, rw [h₁ a (or.inl rfl), cond, IH L none [] _ ⟨rfl, rfl⟩], refl, exact λ x h, h₁ x (or.inr h) }, { cases l₁ with a' l₁; rcases h₂ with ⟨h₂, ⟨⟩⟩, {rw [h₂, cond]}, rw [h₁ a (or.inl rfl), cond, IH l₁ (some o) l₂ _ ⟨h₂, _⟩]; try {refl}, exact λ x h, h₁ x (or.inr h) }, end theorem split_at_pred_ff {α} (L : list α) : split_at_pred (λ _, ff) L = (L, none, []) := split_at_pred_eq _ _ _ _ _ (λ _ _, rfl) ⟨rfl, rfl⟩ theorem move_ok {p k₁ k₂ q s L₁ o L₂} {S : K' → list Γ'} (h₁ : k₁ ≠ k₂) (e : split_at_pred p (S k₁) = (L₁, o, L₂)) : reaches₁ (TM2.step tr) ⟨some (Λ'.move p k₁ k₂ q), s, S⟩ ⟨some q, o, update (update S k₁ L₂) k₂ (L₁.reverse_core (S k₂))⟩ := begin induction L₁ with a L₁ IH generalizing S s, { rw [(_ : [].reverse_core _ = _), function.update_eq_self], swap, { rw function.update_noteq h₁.symm, refl }, refine trans_gen.head' rfl _, simp, cases S k₁ with a Sk, {cases e, refl}, simp [split_at_pred] at e ⊢, cases p a; simp at e ⊢, { revert e, rcases split_at_pred p Sk with ⟨_, _, _⟩, rintro ⟨⟩ }, { simp only [e] } }, { refine trans_gen.head rfl _, simp, cases e₁ : S k₁ with a' Sk; rw [e₁, split_at_pred] at e, {cases e}, cases e₂ : p a'; simp only [e₂, cond] at e, swap, {cases e}, rcases e₃ : split_at_pred p Sk with ⟨_, _, _⟩, rw [e₃, split_at_pred] at e, cases e, simp [e₂], convert @IH (update (update S k₁ Sk) k₂ (a :: S k₂)) _ _ using 2; simp [function.update_noteq, h₁, h₁.symm, e₃, list.reverse_core], simp [function.update_comm h₁.symm] } end theorem unrev_ok {q s} {S : K' → list Γ'} : reaches₁ (TM2.step tr) ⟨some (unrev q), s, S⟩ ⟨some q, none, update (update S rev []) main (list.reverse_core (S rev) (S main))⟩ := move_ok dec_trivial $ split_at_pred_ff _ theorem move₂_ok {p k₁ k₂ q s L₁ o L₂} {S : K' → list Γ'} (h₁ : k₁ ≠ rev ∧ k₂ ≠ rev ∧ k₁ ≠ k₂) (h₂ : S rev = []) (e : split_at_pred p (S k₁) = (L₁, o, L₂)) : reaches₁ (TM2.step tr) ⟨some (move₂ p k₁ k₂ q), s, S⟩ ⟨some q, none, update (update S k₁ (o.elim id list.cons L₂)) k₂ (L₁ ++ S k₂)⟩ := begin refine (move_ok h₁.1 e).trans (trans_gen.head rfl _), cases o; simp only [option.elim, tr, id.def], { convert move_ok h₁.2.1.symm (split_at_pred_ff _) using 2, simp only [function.update_comm h₁.1, function.update_idem], rw show update S rev [] = S, by rw [← h₂, function.update_eq_self], simp only [function.update_noteq h₁.2.2.symm, function.update_noteq h₁.2.1, function.update_noteq h₁.1.symm, list.reverse_core_eq, h₂, function.update_same, list.append_nil, list.reverse_reverse] }, { convert move_ok h₁.2.1.symm (split_at_pred_ff _) using 2, simp only [h₂, function.update_comm h₁.1, list.reverse_core_eq, function.update_same, list.append_nil, function.update_idem], rw show update S rev [] = S, by rw [← h₂, function.update_eq_self], simp only [function.update_noteq h₁.1.symm, function.update_noteq h₁.2.2.symm, function.update_noteq h₁.2.1, function.update_same, list.reverse_reverse] }, end theorem clear_ok {p k q s L₁ o L₂} {S : K' → list Γ'} (e : split_at_pred p (S k) = (L₁, o, L₂)) : reaches₁ (TM2.step tr) ⟨some (Λ'.clear p k q), s, S⟩ ⟨some q, o, update S k L₂⟩ := begin induction L₁ with a L₁ IH generalizing S s, { refine trans_gen.head' rfl _, simp, cases S k with a Sk, {cases e, refl}, simp [split_at_pred] at e ⊢, cases p a; simp at e ⊢, { revert e, rcases split_at_pred p Sk with ⟨_, _, _⟩, rintro ⟨⟩ }, { simp only [e] } }, { refine trans_gen.head rfl _, simp, cases e₁ : S k with a' Sk; rw [e₁, split_at_pred] at e, {cases e}, cases e₂ : p a'; simp only [e₂, cond] at e, swap, {cases e}, rcases e₃ : split_at_pred p Sk with ⟨_, _, _⟩, rw [e₃, split_at_pred] at e, cases e, simp [e₂], convert @IH (update S k Sk) _ _ using 2; simp [e₃] } end theorem copy_ok (q s a b c d) : reaches₁ (TM2.step tr) ⟨some (Λ'.copy q), s, K'.elim a b c d⟩ ⟨some q, none, K'.elim (list.reverse_core b a) [] c (list.reverse_core b d)⟩ := begin induction b with x b IH generalizing a d s, { refine trans_gen.single _, simp, refl }, refine trans_gen.head rfl _, simp, exact IH _ _ _, end theorem tr_pos_num_nat_end : ∀ n (x ∈ tr_pos_num n), nat_end x = ff | pos_num.one _ (or.inl rfl) := rfl | (pos_num.bit0 n) _ (or.inl rfl) := rfl | (pos_num.bit0 n) _ (or.inr h) := tr_pos_num_nat_end n _ h | (pos_num.bit1 n) _ (or.inl rfl) := rfl | (pos_num.bit1 n) _ (or.inr h) := tr_pos_num_nat_end n _ h theorem tr_num_nat_end : ∀ n (x ∈ tr_num n), nat_end x = ff | (num.pos n) x h := tr_pos_num_nat_end n x h theorem tr_nat_nat_end (n) : ∀ x ∈ tr_nat n, nat_end x = ff := tr_num_nat_end _ theorem tr_list_ne_Cons : ∀ l (x ∈ tr_list l), x ≠ Γ'.Cons | (a :: l) x h := begin simp [tr_list] at h, obtain h | rfl | h := h, { rintro rfl, cases tr_nat_nat_end _ _ h }, { rintro ⟨⟩ }, { exact tr_list_ne_Cons l _ h } end theorem head_main_ok {q s L} {c d : list Γ'} : reaches₁ (TM2.step tr) ⟨some (head main q), s, K'.elim (tr_list L) [] c d⟩ ⟨some q, none, K'.elim (tr_list [L.head]) [] c d⟩ := begin let o : option Γ' := list.cases_on L none (λ _ _, some Γ'.cons), refine (move_ok dec_trivial (split_at_pred_eq _ _ (tr_nat L.head) o (tr_list L.tail) (tr_nat_nat_end _) _)).trans (trans_gen.head rfl (trans_gen.head rfl _)), { cases L; exact ⟨rfl, rfl⟩ }, simp [show o ≠ some Γ'.Cons, by cases L; rintro ⟨⟩], refine (clear_ok (split_at_pred_eq _ _ _ none [] _ ⟨rfl, rfl⟩)).trans _, { exact λ x h, (to_bool_ff (tr_list_ne_Cons _ _ h)) }, convert unrev_ok, simp [list.reverse_core_eq], end theorem head_stack_ok {q s L₁ L₂ L₃} : reaches₁ (TM2.step tr) ⟨some (head stack q), s, K'.elim (tr_list L₁) [] [] (tr_list L₂ ++ Γ'.Cons :: L₃)⟩ ⟨some q, none, K'.elim (tr_list (L₂.head :: L₁)) [] [] L₃⟩ := begin cases L₂ with a L₂, { refine trans_gen.trans (move_ok dec_trivial (split_at_pred_eq _ _ [] (some Γ'.Cons) L₃ (by rintro _ ⟨⟩) ⟨rfl, rfl⟩)) (trans_gen.head rfl (trans_gen.head rfl _)), convert unrev_ok, simp, refl }, { refine trans_gen.trans (move_ok dec_trivial (split_at_pred_eq _ _ (tr_nat a) (some Γ'.cons) (tr_list L₂ ++ Γ'.Cons :: L₃) (tr_nat_nat_end _) ⟨rfl, by simp⟩)) (trans_gen.head rfl (trans_gen.head rfl _)), simp, refine trans_gen.trans (clear_ok (split_at_pred_eq _ _ (tr_list L₂) (some Γ'.Cons) L₃ (λ x h, (to_bool_ff (tr_list_ne_Cons _ _ h))) ⟨rfl, by simp⟩)) _, convert unrev_ok, simp [list.reverse_core_eq] }, end theorem succ_ok {q s n} {c d : list Γ'} : reaches₁ (TM2.step tr) ⟨some (Λ'.succ q), s, K'.elim (tr_list [n]) [] c d⟩ ⟨some q, none, K'.elim (tr_list [n.succ]) [] c d⟩ := begin simp [tr_nat, num.add_one], cases (n:num) with a, { refine trans_gen.head rfl _, simp, rw if_neg, swap, rintro ⟨⟩, rw if_pos, swap, refl, convert unrev_ok, simp, refl }, simp [num.succ, tr_num, num.succ'], suffices : ∀ l₁, ∃ l₁' l₂' s', list.reverse_core l₁ (tr_pos_num a.succ) = list.reverse_core l₁' l₂' ∧ reaches₁ (TM2.step tr) ⟨some q.succ, s, K'.elim (tr_pos_num a ++ [Γ'.cons]) l₁ c d⟩ ⟨some (unrev q), s', K'.elim (l₂' ++ [Γ'.cons]) l₁' c d⟩, { obtain ⟨l₁', l₂', s', e, h⟩ := this [], simp [list.reverse_core] at e, refine h.trans _, convert unrev_ok using 2, simp [e, list.reverse_core_eq] }, induction a with m IH m IH generalizing s; intro l₁, { refine ⟨Γ'.bit0 :: l₁, [Γ'.bit1], some Γ'.cons, rfl, trans_gen.head rfl (trans_gen.single _)⟩, simp [tr_pos_num] }, { obtain ⟨l₁', l₂', s', e, h⟩ := IH (Γ'.bit0 :: l₁), refine ⟨l₁', l₂', s', e, trans_gen.head _ h⟩, swap, simp [pos_num.succ, tr_pos_num] }, { refine ⟨l₁, _, some Γ'.bit0, rfl, trans_gen.single _⟩, simp, refl }, end theorem pred_ok (q₁ q₂ s v) (c d : list Γ') : ∃ s', reaches₁ (TM2.step tr) ⟨some (Λ'.pred q₁ q₂), s, K'.elim (tr_list v) [] c d⟩ (v.head.elim ⟨some q₁, s', K'.elim (tr_list v.tail) [] c d⟩ (λ n _, ⟨some q₂, s', K'.elim (tr_list (n :: v.tail)) [] c d⟩)) := begin rcases v with _|⟨_|n, v⟩, { refine ⟨none, trans_gen.single _⟩, simp, refl }, { refine ⟨some Γ'.cons, trans_gen.single _⟩, simp, refl }, refine ⟨none, _⟩, simp [tr_nat, num.add_one, num.succ, tr_num], cases (n:num) with a, { simp [tr_pos_num, tr_num, show num.zero.succ' = pos_num.one, from rfl], refine trans_gen.head rfl _, convert unrev_ok, simp, refl }, simp [tr_num, num.succ'], suffices : ∀ l₁, ∃ l₁' l₂' s', list.reverse_core l₁ (tr_pos_num a) = list.reverse_core l₁' l₂' ∧ reaches₁ (TM2.step tr) ⟨some (q₁.pred q₂), s, K'.elim (tr_pos_num a.succ ++ Γ'.cons :: tr_list v) l₁ c d⟩ ⟨some (unrev q₂), s', K'.elim (l₂' ++ Γ'.cons :: tr_list v) l₁' c d⟩, { obtain ⟨l₁', l₂', s', e, h⟩ := this [], simp [list.reverse_core] at e, refine h.trans _, convert unrev_ok using 2, simp [e, list.reverse_core_eq] }, induction a with m IH m IH generalizing s; intro l₁, { refine ⟨Γ'.bit1 :: l₁, [], some Γ'.cons, rfl, trans_gen.head rfl (trans_gen.single _)⟩, simp [tr_pos_num, show pos_num.one.succ = pos_num.one.bit0, from rfl], refl }, { obtain ⟨l₁', l₂', s', e, h⟩ := IH (some Γ'.bit0) (Γ'.bit1 :: l₁), refine ⟨l₁', l₂', s', e, trans_gen.head _ h⟩, simp, refl }, { obtain ⟨a, l, e, h⟩ : ∃ a l, tr_pos_num m = a :: l ∧ nat_end a = ff, { cases m; refine ⟨_, _, rfl, rfl⟩ }, refine ⟨Γ'.bit0 :: l₁, _, some a, rfl, trans_gen.single _⟩, simp [tr_pos_num, pos_num.succ, e, h, nat_end, show some Γ'.bit1 ≠ some Γ'.bit0, from dec_trivial] }, end theorem tr_normal_respects (c k v s) : ∃ b₂, tr_cfg (step_normal c k v) b₂ ∧ reaches₁ (TM2.step tr) ⟨some (tr_normal c (tr_cont k)), s, K'.elim (tr_list v) [] [] (tr_cont_stack k)⟩ b₂ := begin induction c generalizing k v s, case zero' : { refine ⟨_, ⟨s, rfl⟩, trans_gen.single _⟩, simp }, case succ : { refine ⟨_, ⟨none, rfl⟩, head_main_ok.trans succ_ok⟩ }, case tail : { let o : option Γ' := list.cases_on v none (λ _ _, some Γ'.cons), refine ⟨_, ⟨o, rfl⟩, _⟩, convert clear_ok _, simp, swap, refine split_at_pred_eq _ _ (tr_nat v.head) _ _ (tr_nat_nat_end _) _, cases v; exact ⟨rfl, rfl⟩ }, case cons : f fs IHf IHfs { obtain ⟨c, h₁, h₂⟩ := IHf (cont.cons₁ fs v k) v none, refine ⟨c, h₁, trans_gen.head rfl $ (move_ok dec_trivial (split_at_pred_ff _)).trans _⟩, simp [step_normal], refine (copy_ok _ none [] (tr_list v).reverse _ _).trans _, convert h₂ using 2, simp [list.reverse_core_eq, tr_cont_stack] }, case comp : f g IHf IHg { exact IHg (cont.comp f k) v s }, case case : f g IHf IHg { rw step_normal, obtain ⟨s', h⟩ := pred_ok _ _ s v _ _, cases v.head with n, { obtain ⟨c, h₁, h₂⟩ := IHf k _ s', exact ⟨_, h₁, h.trans h₂⟩ }, { obtain ⟨c, h₁, h₂⟩ := IHg k _ s', exact ⟨_, h₁, h.trans h₂⟩ } }, case fix : f IH { apply IH } end theorem tr_ret_respects (k v s) : ∃ b₂, tr_cfg (step_ret k v) b₂ ∧ reaches₁ (TM2.step tr) ⟨some (Λ'.ret (tr_cont k)), s, K'.elim (tr_list v) [] [] (tr_cont_stack k)⟩ b₂ := begin induction k generalizing v s, case halt : { exact ⟨_, rfl, trans_gen.single rfl⟩ }, case cons₁ : fs as k IH { obtain ⟨s', h₁, h₂⟩ := tr_normal_respects fs (cont.cons₂ v k) as none, refine ⟨s', h₁, trans_gen.head rfl _⟩, simp, refine (move₂_ok dec_trivial _ (split_at_pred_ff _)).trans _, {refl}, simp, refine (move₂_ok dec_trivial _ _).trans _, swap 4, {refl}, swap 4, {exact (split_at_pred_eq _ _ _ (some Γ'.Cons) _ (λ x h, to_bool_ff (tr_list_ne_Cons _ _ h)) ⟨rfl, rfl⟩)}, refine (move₂_ok dec_trivial _ (split_at_pred_ff _)).trans _, {refl}, simp, exact h₂ }, case cons₂ : ns k IH { obtain ⟨c, h₁, h₂⟩ := IH (ns.head :: v) none, exact ⟨c, h₁, trans_gen.head rfl $ head_stack_ok.trans h₂⟩ }, case comp : f k IH { obtain ⟨s', h₁, h₂⟩ := tr_normal_respects f k v s, exact ⟨_, h₁, trans_gen.head rfl h₂⟩ }, case fix : f k IH { rw [step_ret], have : if v.head = 0 then nat_end (tr_list v).head'.iget = tt ∧ (tr_list v).tail = tr_list v.tail else nat_end (tr_list v).head'.iget = ff ∧ (tr_list v).tail = (tr_nat v.head).tail ++ Γ'.cons :: tr_list v.tail, { cases v with n, {exact ⟨rfl, rfl⟩}, cases n, {exact ⟨rfl, rfl⟩}, rw [tr_list, list.head, tr_nat, nat.cast_succ, num.add_one, num.succ, list.tail], cases (n:num).succ'; exact ⟨rfl, rfl⟩ }, by_cases v.head = 0; simp [h] at this ⊢, { obtain ⟨c, h₁, h₂⟩ := IH v.tail (tr_list v).head', refine ⟨c, h₁, trans_gen.head rfl _⟩, simp [tr_cont, tr_cont_stack, this], exact h₂ }, { obtain ⟨s', h₁, h₂⟩ := tr_normal_respects f (cont.fix f k) v.tail (some Γ'.cons), refine ⟨_, h₁, trans_gen.head rfl $ trans_gen.trans _ h₂⟩, swap 3, simp [tr_cont, this.1], convert clear_ok (split_at_pred_eq _ _ (tr_nat v.head).tail (some Γ'.cons) _ _ _) using 2, { simp }, { exact λ x h, tr_nat_nat_end _ _ (list.tail_subset _ h) }, { exact ⟨rfl, this.2⟩ } } }, end theorem tr_respects : respects step (TM2.step tr) tr_cfg | (cfg.ret k v) _ ⟨s, rfl⟩ := tr_ret_respects _ _ _ | (cfg.halt v) _ rfl := rfl /-- The initial state, evaluating function `c` on input `v`. -/ def init (c : code) (v : list ℕ) : cfg' := ⟨some (tr_normal c cont'.halt), none, K'.elim (tr_list v) [] [] []⟩ theorem tr_init (c v) : ∃ b, tr_cfg (step_normal c cont.halt v) b ∧ reaches₁ (TM2.step tr) (init c v) b := tr_normal_respects _ _ _ _ theorem tr_eval (c v) : eval (TM2.step tr) (init c v) = halt <$> code.eval c v := begin obtain ⟨i, h₁, h₂⟩ := tr_init c v, refine roption.ext (λ x, _), rw [reaches_eval h₂.to_refl], simp, refine ⟨λ h, _, _⟩, { obtain ⟨c, hc₁, hc₂⟩ := tr_eval_rev tr_respects h₁ h, simp [step_normal_eval] at hc₂, obtain ⟨v', hv, rfl⟩ := hc₂, exact ⟨_, hv, hc₁.symm⟩ }, { rintro ⟨v', hv, rfl⟩, have := tr_eval tr_respects h₁, simp [step_normal_eval] at this, obtain ⟨_, ⟨⟩, h⟩ := this _ hv rfl, exact h } end end end partrec_to_TM2 end turing
58ecb1bf803a5c073da9c92dff463d56781fc133
82e44445c70db0f03e30d7be725775f122d72f3e
/src/ring_theory/adjoin_root.lean
f610dbee419e3f6641830a254477c38c852b7bbc
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
9,905
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Chris Hughes Adjoining roots of polynomials -/ import data.polynomial.field_division import linear_algebra.finite_dimensional import ring_theory.adjoin.basic import ring_theory.power_basis import ring_theory.principal_ideal_domain /-! # Adjoining roots of polynomials This file defines the commutative ring `adjoin_root f`, the ring R[X]/(f) obtained from a commutative ring `R` and a polynomial `f : R[X]`. If furthermore `R` is a field and `f` is irreducible, the field structure on `adjoin_root f` is constructed. ## Main definitions and results The main definitions are in the `adjoin_root` namespace. * `mk f : polynomial R →+* adjoin_root f`, the natural ring homomorphism. * `of f : R →+* adjoin_root f`, the natural ring homomorphism. * `root f : adjoin_root f`, the image of X in R[X]/(f). * `lift (i : R →+* S) (x : S) (h : f.eval₂ i x = 0) : (adjoin_root f) →+* S`, the ring homomorphism from R[X]/(f) to S extending `i : R →+* S` and sending `X` to `x`. * `lift_hom (x : S) (hfx : aeval x f = 0) : adjoin_root f →ₐ[R] S`, the algebra homomorphism from R[X]/(f) to S extending `algebra_map R S` and sending `X` to `x` * `equiv : (adjoin_root f →ₐ[F] E) ≃ {x // x ∈ (f.map (algebra_map F E)).roots}` a bijection between algebra homomorphisms from `adjoin_root` and roots of `f` in `S` -/ noncomputable theory open_locale classical open_locale big_operators universes u v w variables {R : Type u} {S : Type v} {K : Type w} open polynomial ideal /-- Adjoin a root of a polynomial `f` to a commutative ring `R`. We define the new ring as the quotient of `R` by the principal ideal of `f`. -/ def adjoin_root [comm_ring R] (f : polynomial R) : Type u := ideal.quotient (span {f} : ideal (polynomial R)) namespace adjoin_root section comm_ring variables [comm_ring R] (f : polynomial R) instance : comm_ring (adjoin_root f) := ideal.quotient.comm_ring _ instance : inhabited (adjoin_root f) := ⟨0⟩ instance : decidable_eq (adjoin_root f) := classical.dec_eq _ /-- Ring homomorphism from `R[x]` to `adjoin_root f` sending `X` to the `root`. -/ def mk : polynomial R →+* adjoin_root f := ideal.quotient.mk _ @[elab_as_eliminator] theorem induction_on {C : adjoin_root f → Prop} (x : adjoin_root f) (ih : ∀ p : polynomial R, C (mk f p)) : C x := quotient.induction_on' x ih /-- Embedding of the original ring `R` into `adjoin_root f`. -/ def of : R →+* adjoin_root f := (mk f).comp C instance : algebra R (adjoin_root f) := (of f).to_algebra @[simp] lemma algebra_map_eq : algebra_map R (adjoin_root f) = of f := rfl /-- The adjoined root. -/ def root : adjoin_root f := mk f X variables {f} instance adjoin_root.has_coe_t : has_coe_t R (adjoin_root f) := ⟨of f⟩ @[simp] lemma mk_self : mk f f = 0 := quotient.sound' (mem_span_singleton.2 $ by simp) @[simp] lemma mk_C (x : R) : mk f (C x) = x := rfl @[simp] lemma mk_X : mk f X = root f := rfl @[simp] lemma aeval_eq (p : polynomial R) : aeval (root f) p = mk f p := polynomial.induction_on p (λ x, by { rw aeval_C, refl }) (λ p q ihp ihq, by rw [alg_hom.map_add, ring_hom.map_add, ihp, ihq]) (λ n x ih, by { rw [alg_hom.map_mul, aeval_C, alg_hom.map_pow, aeval_X, ring_hom.map_mul, mk_C, ring_hom.map_pow, mk_X], refl }) theorem adjoin_root_eq_top : algebra.adjoin R ({root f} : set (adjoin_root f)) = ⊤ := algebra.eq_top_iff.2 $ λ x, induction_on f x $ λ p, (algebra.adjoin_singleton_eq_range R (root f)).symm ▸ ⟨p, aeval_eq p⟩ @[simp] lemma eval₂_root (f : polynomial R) : f.eval₂ (of f) (root f) = 0 := by rw [← algebra_map_eq, ← aeval_def, aeval_eq, mk_self] lemma is_root_root (f : polynomial R) : is_root (f.map (of f)) (root f) := by rw [is_root, eval_map, eval₂_root] variables [comm_ring S] /-- Lift a ring homomorphism `i : R →+* S` to `adjoin_root f →+* S`. -/ def lift (i : R →+* S) (x : S) (h : f.eval₂ i x = 0) : (adjoin_root f) →+* S := begin apply ideal.quotient.lift _ (eval₂_ring_hom i x), intros g H, rcases mem_span_singleton.1 H with ⟨y, hy⟩, rw [hy, ring_hom.map_mul, coe_eval₂_ring_hom, h, zero_mul] end variables {i : R →+* S} {a : S} {h : f.eval₂ i a = 0} @[simp] lemma lift_mk {g : polynomial R} : lift i a h (mk f g) = g.eval₂ i a := ideal.quotient.lift_mk _ _ _ @[simp] lemma lift_root : lift i a h (root f) = a := by rw [root, lift_mk, eval₂_X] @[simp] lemma lift_of {x : R} : lift i a h x = i x := by rw [← mk_C x, lift_mk, eval₂_C] @[simp] lemma lift_comp_of : (lift i a h).comp (of f) = i := ring_hom.ext $ λ _, @lift_of _ _ _ _ _ _ _ h _ variables (f) [algebra R S] /-- Produce an algebra homomorphism `adjoin_root f →ₐ[R] S` sending `root f` to a root of `f` in `S`. -/ def lift_hom (x : S) (hfx : aeval x f = 0) : adjoin_root f →ₐ[R] S := { commutes' := λ r, show lift _ _ hfx r = _, from lift_of, .. lift (algebra_map R S) x hfx } @[simp] lemma coe_lift_hom (x : S) (hfx : aeval x f = 0) : (lift_hom f x hfx : adjoin_root f →+* S) = lift (algebra_map R S) x hfx := rfl @[simp] lemma aeval_alg_hom_eq_zero (ϕ : adjoin_root f →ₐ[R] S) : aeval (ϕ (root f)) f = 0 := begin have h : ϕ.to_ring_hom.comp (of f) = algebra_map R S := ring_hom.ext_iff.mpr (ϕ.commutes), rw [aeval_def, ←h, ←ring_hom.map_zero ϕ.to_ring_hom, ←eval₂_root f, hom_eval₂], refl, end @[simp] lemma lift_hom_eq_alg_hom (f : polynomial R) (ϕ : adjoin_root f →ₐ[R] S) : lift_hom f (ϕ (root f)) (aeval_alg_hom_eq_zero f ϕ) = ϕ := begin suffices : ϕ.equalizer (lift_hom f (ϕ (root f)) (aeval_alg_hom_eq_zero f ϕ)) = ⊤, { exact (alg_hom.ext (λ x, (set_like.ext_iff.mp (this) x).mpr algebra.mem_top)).symm }, rw [eq_top_iff, ←adjoin_root_eq_top, algebra.adjoin_le_iff, set.singleton_subset_iff], exact (@lift_root _ _ _ _ _ _ _ (aeval_alg_hom_eq_zero f ϕ)).symm, end /-- If `E` is a field extension of `F` and `f` is a polynomial over `F` then the set of maps from `F[x]/(f)` into `E` is in bijection with the set of roots of `f` in `E`. -/ def equiv (F E : Type*) [field F] [field E] [algebra F E] (f : polynomial F) (hf : f ≠ 0) : (adjoin_root f →ₐ[F] E) ≃ {x // x ∈ (f.map (algebra_map F E)).roots} := { to_fun := λ ϕ, ⟨ϕ (root f), begin rw [mem_roots (map_ne_zero hf), is_root.def, ←eval₂_eq_eval_map], exact aeval_alg_hom_eq_zero f ϕ, exact field.to_nontrivial E, end⟩, inv_fun := λ x, lift_hom f ↑x (begin rw [aeval_def, eval₂_eq_eval_map, ←is_root.def, ←mem_roots (map_ne_zero hf)], exact subtype.mem x, exact field.to_nontrivial E end), left_inv := λ ϕ, lift_hom_eq_alg_hom f ϕ, right_inv := λ x, begin ext, refine @lift_root F E _ f _ _ ↑x _, rw [eval₂_eq_eval_map, ←is_root.def, ←mem_roots (map_ne_zero hf), ←multiset.mem_to_finset], exact multiset.mem_to_finset.mpr (subtype.mem x), exact field.to_nontrivial E end } end comm_ring section irreducible variables [field K] {f : polynomial K} [irreducible f] instance is_maximal_span : is_maximal (span {f} : ideal (polynomial K)) := principal_ideal_ring.is_maximal_of_irreducible ‹irreducible f› noncomputable instance field : field (adjoin_root f) := { ..adjoin_root.comm_ring f, ..ideal.quotient.field (span {f} : ideal (polynomial K)) } lemma coe_injective : function.injective (coe : K → adjoin_root f) := (of f).injective variable (f) lemma mul_div_root_cancel : ((X - C (root f)) * (f.map (of f) / (X - C (root f))) : polynomial (adjoin_root f)) = f.map (of f) := mul_div_eq_iff_is_root.2 $ is_root_root _ end irreducible section power_basis variables [field K] {f : polynomial K} /-- The elements `1, root f, ..., root f ^ (d - 1)` form a basis for `adjoin_root f`, where `f` is an irreducible polynomial over a field of degree `d`. -/ def power_basis_aux (hf : f ≠ 0) : basis (fin f.nat_degree) K (adjoin_root f) := begin set f' := f * C (f.leading_coeff⁻¹) with f'_def, have deg_f' : f'.nat_degree = f.nat_degree, { rw [nat_degree_mul hf, nat_degree_C, add_zero], { rwa [ne.def, C_eq_zero, inv_eq_zero, leading_coeff_eq_zero] } }, have f'_monic : monic f' := monic_mul_leading_coeff_inv hf, have aeval_f' : aeval (root f) f' = 0, { rw [f'_def, alg_hom.map_mul, aeval_eq, mk_self, zero_mul] }, have hx : is_integral K (root f) := ⟨f', f'_monic, aeval_f'⟩, have minpoly_eq : f' = minpoly K (root f), { apply minpoly.unique K _ f'_monic aeval_f', intros q q_monic q_aeval, have commutes : (lift (algebra_map K (adjoin_root f)) (root f) q_aeval).comp (mk q) = mk f, { ext, { simp only [ring_hom.comp_apply, mk_C, lift_of], refl }, { simp only [ring_hom.comp_apply, mk_X, lift_root] } }, rw [degree_eq_nat_degree f'_monic.ne_zero, degree_eq_nat_degree q_monic.ne_zero, with_bot.coe_le_coe, deg_f'], apply nat_degree_le_of_dvd, { have : mk f q = 0, by rw [←commutes, ring_hom.comp_apply, mk_self, ring_hom.map_zero], rwa [←ideal.mem_span_singleton, ←ideal.quotient.eq_zero_iff_mem] }, { exact q_monic.ne_zero } }, apply @basis.mk _ _ _ (λ (i : fin f.nat_degree), (root f ^ i.val)), { rw [←deg_f', minpoly_eq], exact hx.linear_independent_pow }, { rw _root_.eq_top_iff, rintros y -, rw [←deg_f', minpoly_eq], apply hx.mem_span_pow, obtain ⟨g⟩ := y, use g, rw aeval_eq, refl } end /-- The power basis `1, root f, ..., root f ^ (d - 1)` for `adjoin_root f`, where `f` is an irreducible polynomial over a field of degree `d`. -/ @[simps] def power_basis (hf : f ≠ 0) : power_basis K (adjoin_root f) := { gen := root f, dim := f.nat_degree, basis := power_basis_aux hf, basis_eq_pow := basis.mk_apply _ _ } end power_basis end adjoin_root
8123335b9708e2f3a5f7f73f15e538fa462588ca
076f5040b63237c6dd928c6401329ed5adcb0e44
/instructor-notes/2019.09.24.lean
216215b5e4b62f8c0f390fe3035df59d029cc1cb
[]
no_license
kevinsullivan/uva-cs-dm-f19
0f123689cf6cb078f263950b18382a7086bf30be
09a950752884bd7ade4be33e9e89a2c4b1927167
refs/heads/master
1,594,771,841,541
1,575,853,850,000
1,575,853,850,000
205,433,890
4
9
null
1,571,592,121,000
1,567,188,539,000
Lean
UTF-8
Lean
false
false
8,451
lean
namespace mlist open list -- Lean-provided data type /- Lists in Lean are "polymorphic." They can contain elements of any specified type. Your homework is to implement lists of natural numbers in particular. Soon you'll see how to make the type of list elements into a parameter/argument. To help with your homework, let's look at lists as provided by Lean's library. -/ /- Inductive definition: A list is either empty or it is constucted (thus "cons") from an element and a one-smaller list. -/ /- We represent an empty list by a term, nil. -/ def e : list nat := nil #check e #eval e /- We represent a non-empty list by a term, cons h t, where h is the element at the "head" of the list and "t", the tail of the overall list, is the one-smaller list that follows the head. It in turn can be (a term representing) the empty list or a non-empty list. -/ -- The list, [1] def l1 : list nat := cons 1 -- head element nil -- tail list #eval l1 -- The list, [1, 2] def l2 : list nat := cons 1 ( cons 2 e ) def l3 : list nat := cons 1 ( cons 2 ( cons 3 nil ) ) def l3' : list nat := cons 1 ( cons 2 ( cons 3 nil ) ) -- The list, [1, 2, 3] #eval l3 -- note use of nice notation! def my_list : list string := cons "I" ( cons "love" ( cons "DM" (nil) ) ) #eval my_list -- note nice notation def my_list' : list string := ["I", "love", "DM"] -- Nested lists, response to question -- represent [ [1,2], [3,4], [0,10] ] -- notice the *type* of this list def nested_list : list (list nat) := cons ( ) -- [1,2] ( cons (_) -- [3,4] ( cons (_) -- [0,10] nil ) ) -- you can (and should) fill in _s #check e #eval e #check l3 #eval l3 -- Lean supports list notation! def l4 : list nat := [1, 2, 3, 4] #check l4 #eval l4 /- OK, now that we've seen how to use nil and cons terms to represent lists, it's time to define functions that operate on lists represented by such terms. -/ -- A function to prepend nat h to list t def prepend : nat → list nat → list nat | h t := cons h t #eval prepend 1 [2, 3, 4] /- Head takes a value of type list nat and returns the nat head of the list if it is not empty otherwise it returns zero. -/ def mhead : list nat → nat | [] := 0 | (cons h t) := h #eval mhead [] #eval mhead [1, 2, 3] def mtail : list nat → list nat | [] := [] | (cons h t) := t #eval mtail [] #eval mtail [1, 2, 3] -- return length of list def mlength : list nat → nat | [] := 0 | (cons _ t) := 1 + (mlength t) #eval mlength [] #eval mlength l2 -- mlength [1 , 2] -- 1 + (mlength [1]) -- 1 + (1 + (mlength [])) -- 1 + (1 + 0) -- 1 + 1 -- 2 -- the final result #eval mlength l4 /- mlength [1, 2, 3, 4] 1 + (mlength [2, 3, 4]) 1 + (1 + mlength [3, 4]) 1 + (1 + (1 + mlength [4])) 1 + (1 + (1 + (1 + mlength []))) 1 + (1 + (1 + (1 + 0))) 1 + (1 + (1 + 1)) 1 + (1 + 2) 1 + 3 4 -- the final result -/ /- After review of preceding, START 9/26/2019 From Here -/ /- Warmup exercise: write countdown function. Given a natural number, n, return a list of natural numbers, [n, n-1, ..., 0]. -/ open nat def countdown : ℕ → list nat | 0 := [0] | (succ n') := cons (succ n') (countdown n') #eval countdown 10 /- Exercise: write fib function. The key new element in this definition is that it has two base cases instead of one, and the third, recursive, case uses a more complex form of pattern matching. -/ def fib : ℕ → ℕ | nat.zero := nat.zero | (nat.succ nat.zero) := (nat.succ nat.zero) | (nat.succ (nat.succ n')) := (fib n') + (fib (nat.succ n')) /- We can clean up this definition using Lean's built-in machanisms for writing natural number values. The following logic is absolutely equivant to the preceding version. -/ def fib' : ℕ → ℕ | 0 := 0 | 1 := 1 | (n' + 2) := (fib n') + (fib (n' + 1)) #eval fib 10 #eval fib' 10 /- Now a function that takes a list (of nats) and that returns a new list, like the first, except that every element in the first list is doubled in the second list. Study the second case especially carefully. On the left of the :=, we take apart the argument list into a head, h, and a tail, t. On the right, we use cons to build a new list: one with 2*t at its head and with a doubled version of t as its tail. The doubled version of t is returned by the recusive application of mdouble to t. -/ def mdouble : list ℕ → list ℕ | [] := [] | (cons h t) := cons (h*2) (mdouble t) #eval mdouble [] #eval mdouble l4 /- We don't want to have to write multiple functions like mdouble that differ only in the function applied to h. The solution is to make that function a parameter. This generalizes the function to one that can transform any list of natural numbers into a corresponding list where the new list elements are computed by applying the function to the elements of the original list. -/ def mmap : (ℕ → ℕ) → list ℕ → list ℕ | f [] := [] | f (cons h t) := cons (f h) (mmap f t) #eval mmap nat.succ [1,2,3,4] -- add one to each element #eval mmap (λ (n : ℕ), n*n) [1,2,3,4] -- square each element /- A "reduce" function takes a list as an argument and reduces it to a single value by applying an operation between elements in the list. If the operation is add, the result is the sum of the elements in the list. If the operation is mul, the result is the product of all the elements in the list. A key issue in this design is that the value to return in the base case depends on the operation being applied: in short, the base case must return the "identity element" for the given operator, such a 0 for add and 1 for mult. -/ def mreduce_add : list ℕ → nat | [] := 0 | (cons h t) := h + (mreduce_add t) #eval mreduce_add [1,2,3,4,5,6,7,8,9,10] def mreduce_mult : list ℕ → nat | [] := 1 | (cons h t ) := h * (mreduce_mult t) #eval mreduce_mult [1,2,3,4,5,6,7,8,9,10] /- Once again we can generalize from these examples by replacing specific details that vary from version to version with parameters. The general "reduce" function thus takes both a binary operation (such as add or mul) and the identity value for that operator as parameters. -/ def mreduce : (ℕ → ℕ → ℕ) → ℕ → (list ℕ) → nat | f id [] := id | f id (cons h t) := f h (mreduce f id t) #eval mreduce nat.add 0 [10,9,8,7,6,5] #eval mreduce nat.mul 1 [10,9,8,7,6,5] /- Filter -/ def mfilter : (ℕ → bool) → list ℕ → list ℕ | p [] := [] | p (cons h t) := if (p h) then cons h (mfilter p t) else (mfilter p t) def lt_5 (n : ℕ) : bool := n < 5 def even (n : ℕ) : bool := n % 2 = 0 #eval mfilter lt_5 (countdown 10) #eval mfilter even (countdown 10) -- double every element of a list def mdouble : list nat → list nat | [] := [] | (cons h t) := cons (2*h) (mdouble t) #eval mdouble l4 -- apply a fun to every list element def mmap : (nat → nat) → list nat → list nat | f nil := nil | f (cons h t) := cons (f h) (mmap f t) #eval mmap nat.succ l4 -- Lean nat.succ #eval mmap (λ n: nat, n*n) l4 --square -- A function that computes the sum of -- all the numbers in a list of nats. def mlist_sum : list nat → nat | nil := 0 | (cons h t) := h + mlist_sum t #eval mlist_sum [] #eval mlist_sum l4 -- A function that computes the product -- of the numbers in a list of nats. def mlist_prod : list nat → nat | nil := 1 | (cons h t) := h * mlist_prod t #eval mlist_prod [] #eval mlist_prod l4 -- Can we generalize? /- Yes. Fold. Take identity element, binary function, and list of nat, as arguments, and "reduce" the list using the given operator along with its correct identity value. -/ def mlist_fold : -- also called "reduce" nat → (ℕ → ℕ → ℕ) → list nat → nat | id f nil := id | id f (cons h t) := f h (mlist_fold id f t) #eval mlist_fold 0 nat.add l4 #eval mlist_fold 1 nat.mul l4 -- recursion problems -- 1. args in wrong order (in add) -- 2. *must* use by-cases style end mlist
4dd8ab80bf8dc57d282da98b90ba38f45678ffa3
4e0d7c3132ce31edc5829849735dd25db406b144
/lean/love07_metaprogramming_exercise_sheet.lean
9a3c72e10ad11f0200719ee4e945bf08e0e79aba
[]
no_license
gonzalgu/logical_verification_2020
a0013a6c22ea254e9f4d245f2948f0f4d44df4bb
724d0457dff2c3ff10f9ab2170388f4c5e958b75
refs/heads/master
1,660,886,374,533
1,589,859,641,000
1,589,859,641,000
256,069,971
0
0
null
1,586,997,430,000
1,586,997,429,000
null
UTF-8
Lean
false
false
9,132
lean
import .love07_metaprogramming_demo /-! # LoVe Exercise 7: Metaprogramming -/ set_option pp.beta true namespace LoVe /-! ## ## Question 1: A Term Exploder In this exercise, we develop a string format for the `expr` metatype. By default, there is no `has_repr` instance to print a nice string. For example: -/ #eval (expr.app (expr.var 0) (expr.var 1) : expr) -- result: `[external]` #eval (`(λx : ℕ, x + x) : expr) -- result: `[external]` /-! 1.1. Define a metafunction `expr.repr` that converts an `expr` into a `string`. It is acceptable to leave out some fields from the `expr` constructors, such as the level `l` of a sort, the binder information `bi` of a `λ` or `∀` binder, and the arguments of the `macro` constructor. Hint: Use `name.to_string` to convert a name to a string, and `repr` for other types that belong to the `has_repr` type class. -/ private meta def aux (name : string) (args : list string) : string := name ++ "(" ++ string.intercalate ", " args ++ ")" -- enter your definition here meta def expr.repr : expr → string | (expr.var i) := aux "Var" [repr i] --"var(" ++ repr i ++ ")" | (expr.sort l) := aux "Sort" [l.to_string] | (expr.const n lvls) := aux "Const" [n.to_string, lvls.to_string] | (expr.mvar n pn t) := aux "Mvar" [n.to_string, pn.to_string, expr.repr t] | (expr.local_const n pn _ t) := aux "Local_const" [n.to_string, pn.to_string,expr.repr t] | (expr.app e₁ e₂) := aux "App" [expr.repr e₁, expr.repr e₂] | (expr.lam n _ t b) := aux "Lam" [n.to_string, expr.repr t, expr.repr b] | (expr.pi n _ t b) := aux "Pi " [n.to_string, expr.repr t, expr.repr b] | (expr.elet n t a b) := aux "Elet " [n.to_string, expr.repr t, expr.repr a, expr.repr b] /-! We register `expr.repr` in the `has_repr` type class, so that we can use `repr` without qualification in the future, and so that it is available to `#eval`. We need the `meta` keyword in front of the command we enter. -/ meta instance expr.has_repr : has_repr expr := { repr := expr.repr } /-! 1.2. Test your setup. -/ #eval (expr.app (expr.var 0) (expr.var 1) : expr) #eval (`(λx : ℕ, x + x) : expr) /-! 1.3. Compare your answer with `expr.to_raw_fmt`. -/ #check expr.to_raw_fmt /-! ## Question 2: `destruct_and` on Steroids Recall from the lecture that `destruct_and` fails on easy goals such as -/ #check abc_ac /-! We will now address this by developing a new tactic called `destro_and`, which applies both **des**truction and in**tro**duction rules for conjunction. It will also go automatically through the hypotheses instead of taking an argument. We will develop it in three steps. 2.1. Develop a tactic `intro_ands` that replaces all goals of the form `a ∧ b` with two new goals `a` and `b` systematically, until all top-level conjunctions are gone. For this, we can use tactics such as `tactic.repeat` (which repeatedly applies a tactic on all goals and subgoals until the tactic fails on each of the goal) and `tactic.applyc` (which can be used to apply a rule, in connection with backtick quoting). -/ meta def intro_ands : tactic unit := do tactic.repeat (tactic.applyc ``and.intro) lemma abcd_bd (a b c d : Prop) (h : a ∧ (b ∧ c) ∧ d) : b ∧ d := begin intro_ands, /- The proof state should be as follows: 2 goals a b c d : Prop, h : a ∧ (b ∧ c) ∧ d ⊢ b a b c d : Prop, h : a ∧ (b ∧ c) ∧ d ⊢ d -/ repeat { sorry } end lemma abcd_bacb (a b c d : Prop) (h : a ∧ (b ∧ c) ∧ d) : b ∧ (a ∧ (c ∧ b)) := begin intro_ands, /- The proof state should be as follows: 4 goals a b c d : Prop, h : a ∧ (b ∧ c) ∧ d ⊢ b a b c d : Prop, h : a ∧ (b ∧ c) ∧ d ⊢ a a b c d : Prop, h : a ∧ (b ∧ c) ∧ d ⊢ c a b c d : Prop, h : a ∧ (b ∧ c) ∧ d ⊢ b -/ repeat { sorry } end /-! 2.2. Develop a tactic `destruct_ands` that replaces hypotheses of the form `h : a ∧ b` by two new hypotheses `h_left : a` and `h_right : b` systematically, until all top-level conjunctions are gone. Here is imperative-style pseudocode that you can follow: 1. Retrieve the list of hypotheses from the context. This is provided by the metaconstant `local_context`. 2. Find the first hypothesis (= term) with a type (= proposition) of the form `_ ∧ _`. Here, you can use the `list.mfirst` function, in conjunction with pattern matching. You can use `infer_type` to query the type of a term. 3. Perform a case split on the first found hypothesis. This can be achieved using the `cases` metafunction. 4. Repeat. The above procedure might fail if there exists no hypotheses of the required form. Make sure to handle this failure gracefully, for example using `tactic.try` or `<|> pure ()`. -/ #check @tactic.trace #check @list.mfirst #check @tactic.infer_type #check @tactic.cases private meta def helper_fun(exp : expr) : tactic expr := do t <- tactic.infer_type exp, match t with | `(%%a ∧ %%b) := pure exp | _ := tactic.failed end #check list.mfirst helper_fun #check tactic.set_env #check tactic.get_env meta def destruct_ands : tactic unit := tactic.repeat $ do{ ctx <- tactic.local_context, fst <- list.mfirst helper_fun ctx, lstNames <- tactic.cases fst, return () } --pure () lemma abcd_bd₂ (a b c d : Prop) (h : a ∧ (b ∧ c) ∧ d) : b ∧ d := begin destruct_ands, /- The proof state should be as follows: a b c d : Prop, h_left : a, h_right_right : d, h_right_left_left : b, h_right_left_right : c ⊢ b ∧ d -/ sorry end lemma or_abcd_b_or_d (a b c d : Prop) (h : a ∨ (b ∨ c) ∨ d) : b ∨ d := begin destruct_ands, end /-! 2.3. Combine the two tactics developed above and `tactic.assumption` to implement the desired `destro_and` tactic. -/ meta def destro_and : tactic unit := do destruct_ands, intro_ands, tactic.repeat $ tactic.assumption lemma abcd_bd₃ (a b c d : Prop) (h : a ∧ (b ∧ c) ∧ d) : b ∧ d := begin destro_and, end --by destro_and lemma abcd_bacb₂ (a b c d : Prop) (h : a ∧ (b ∧ c) ∧ d) : b ∧ (a ∧ (c ∧ b)) := by destro_and lemma abd_bacb (a b c d : Prop) (h : a ∧ b ∧ d) : b ∧ (a ∧ (c ∧ b)) := begin destro_and, /- The proof state should be roughly as follows: a b c d : Prop, h_left : a, h_right_left : b, h_right_right : d ⊢ c -/ sorry -- unprovable end /-! 2.4. Provide some more examples for `destro_and` to convince yourself that it works as expected also on more complicated examples. -/ -- enter your examples here /-! ## Question 3 (**optional**): A Theorem Finder We will implement a function that allows us to find theorems by constants appearing in their statements. So given a list of constant names, the function will list all theorems in which all these constants appear. You can use the following metaconstants: * `declaration` contains all data (name, type, value) associated with a declaration understood broadly (e.g., axiom, lemma, constant, etc.). * `tactic.get_env` gives us access to the `environment`, a metatype thats lists all `declaration`s (including all theorems). * `environment.fold` allows us to walk through the environment and collect data. * `expr.fold` allows us to walk through an expression and collect data. 3.1 (**optional**). Write a metafunction that checks whether an expression contains a specific constant. You can use `expr.fold` to walk through the expression, `||` and `ff` for Booleans, and `expr.is_constant_of` to check whether an expression is a constant. -/ #check @expr.fold #check @expr.is_constant_of meta def term_contains (e : expr) (nam : name) : bool := e.fold ff (λ x _ acc, x.is_constant_of nam || acc) /-! 3.2 (**optional**). Write a metafunction that checks whether an expression contains **all** constants in a list. You can use `list.band` (Boolean and). -/ #check list.band meta def term_contains_all (nams : list name) (e : expr) : bool := list.band $ nams.map (λ n, term_contains e n) /-! 3.3 (**optional**). Produce the list of all theorems that contain all constants `nams` in their statement. `environment.fold` allows you to walk over the list of declarations. With `declaration.type`, you get the type of a theorem, and with `declaration.to_name` you get the name. -/ #check @environment.fold #check declaration.type #check declaration.to_name meta def list_constants (nams : list name) (e : environment) : list name := e.fold [] (λ dec thms, if term_contains_all nams dec.type then dec.to_name :: thms else thms) /-! Finally, we develop a tactic that uses the above metafunctions to log all found theorems: -/ meta def find_constants (nams : list name) : tactic unit := do env ← tactic.get_env, list.mmap' tactic.trace (list_constants nams env) /-! We test the solution. -/ run_cmd find_constants [] -- lists all theorems run_cmd find_constants [`list.map, `function.comp] #check list.foldr_map #check list.filter_map_map end LoVe
bbbb27e25958e9938316406b19280401e496b478
9dc8cecdf3c4634764a18254e94d43da07142918
/src/number_theory/cyclotomic/basic.lean
a01087be87cca6d117ff37d8913bce3b7ae873d1
[ "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
27,275
lean
/- Copyright (c) 2021 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca -/ import ring_theory.polynomial.cyclotomic.basic import number_theory.number_field import algebra.char_p.algebra import field_theory.galois /-! # Cyclotomic extensions Let `A` and `B` be commutative rings with `algebra A B`. For `S : set ℕ+`, we define a class `is_cyclotomic_extension S A B` expressing the fact that `B` is obtained from `A` by adding `n`-th primitive roots of unity, for all `n ∈ S`. ## Main definitions * `is_cyclotomic_extension S A B` : means that `B` is obtained from `A` by adding `n`-th primitive roots of unity, for all `n ∈ S`. * `cyclotomic_field`: given `n : ℕ+` and a field `K`, we define `cyclotomic n K` as the splitting field of `cyclotomic n K`. If `n` is nonzero in `K`, it has the instance `is_cyclotomic_extension {n} K (cyclotomic_field n K)`. * `cyclotomic_ring` : if `A` is a domain with fraction field `K` and `n : ℕ+`, we define `cyclotomic_ring n A K` as the `A`-subalgebra of `cyclotomic_field n K` generated by the roots of `X ^ n - 1`. If `n` is nonzero in `A`, it has the instance `is_cyclotomic_extension {n} A (cyclotomic_ring n A K)`. ## Main results * `is_cyclotomic_extension.trans` : if `is_cyclotomic_extension S A B` and `is_cyclotomic_extension T B C`, then `is_cyclotomic_extension (S ∪ T) A C` if `no_zero_smul_divisors B C` and `nontrivial C`. * `is_cyclotomic_extension.union_right` : given `is_cyclotomic_extension (S ∪ T) A B`, then `is_cyclotomic_extension T (adjoin A { b : B | ∃ a : ℕ+, a ∈ S ∧ b ^ (a : ℕ) = 1 }) B`. * `is_cyclotomic_extension.union_right` : given `is_cyclotomic_extension T A B` and `S ⊆ T`, then `is_cyclotomic_extension S A (adjoin A { b : B | ∃ a : ℕ+, a ∈ S ∧ b ^ (a : ℕ) = 1 })`. * `is_cyclotomic_extension.finite` : if `S` is finite and `is_cyclotomic_extension S A B`, then `B` is a finite `A`-algebra. * `is_cyclotomic_extension.number_field` : a finite cyclotomic extension of a number field is a number field. * `is_cyclotomic_extension.splitting_field_X_pow_sub_one` : if `is_cyclotomic_extension {n} K L`, then `L` is the splitting field of `X ^ n - 1`. * `is_cyclotomic_extension.splitting_field_cyclotomic` : if `is_cyclotomic_extension {n} K L`, then `L` is the splitting field of `cyclotomic n K`. ## Implementation details Our definition of `is_cyclotomic_extension` is very general, to allow rings of any characteristic and infinite extensions, but it will mainly be used in the case `S = {n}` and for integral domains. All results are in the `is_cyclotomic_extension` namespace. Note that some results, for example `is_cyclotomic_extension.trans`, `is_cyclotomic_extension.finite`, `is_cyclotomic_extension.number_field`, `is_cyclotomic_extension.finite_dimensional`, `is_cyclotomic_extension.is_galois` and `cyclotomic_field.algebra_base` are lemmas, but they can be made local instances. Some of them are included in the `cyclotomic` locale. -/ open polynomial algebra finite_dimensional module set open_locale big_operators universes u v w z variables (n : ℕ+) (S T : set ℕ+) (A : Type u) (B : Type v) (K : Type w) (L : Type z) variables [comm_ring A] [comm_ring B] [algebra A B] variables [field K] [field L] [algebra K L] noncomputable theory /-- Given an `A`-algebra `B` and `S : set ℕ+`, we define `is_cyclotomic_extension S A B` requiring that there is a `a`-th primitive root of unity in `B` for all `a ∈ S` and that `B` is generated over `A` by the roots of `X ^ n - 1`. -/ @[mk_iff] class is_cyclotomic_extension : Prop := (exists_prim_root {a : ℕ+} (ha : a ∈ S) : ∃ r : B, is_primitive_root r a) (adjoin_roots : ∀ (x : B), x ∈ adjoin A { b : B | ∃ a : ℕ+, a ∈ S ∧ b ^ (a : ℕ) = 1 }) namespace is_cyclotomic_extension section basic /-- A reformulation of `is_cyclotomic_extension` that uses `⊤`. -/ lemma iff_adjoin_eq_top : is_cyclotomic_extension S A B ↔ (∀ (a : ℕ+), a ∈ S → ∃ r : B, is_primitive_root r a) ∧ (adjoin A { b : B | ∃ a : ℕ+, a ∈ S ∧ b ^ (a : ℕ) = 1 } = ⊤) := ⟨λ h, ⟨λ _, h.exists_prim_root, algebra.eq_top_iff.2 h.adjoin_roots⟩, λ h, ⟨h.1, algebra.eq_top_iff.1 h.2⟩⟩ /-- A reformulation of `is_cyclotomic_extension` in the case `S` is a singleton. -/ lemma iff_singleton : is_cyclotomic_extension {n} A B ↔ (∃ r : B, is_primitive_root r n) ∧ (∀ x, x ∈ adjoin A { b : B | b ^ (n : ℕ) = 1 }) := by simp [is_cyclotomic_extension_iff] /-- If `is_cyclotomic_extension ∅ A B`, then the image of `A` in `B` equals `B`. -/ lemma empty [h : is_cyclotomic_extension ∅ A B] : (⊥ : subalgebra A B) = ⊤ := by simpa [algebra.eq_top_iff, is_cyclotomic_extension_iff] using h /-- If `is_cyclotomic_extension {1} A B`, then the image of `A` in `B` equals `B`. -/ lemma singleton_one [h : is_cyclotomic_extension {1} A B] : (⊥ : subalgebra A B) = ⊤ := algebra.eq_top_iff.2 (λ x, by simpa [adjoin_singleton_one] using ((is_cyclotomic_extension_iff _ _ _).1 h).2 x) /-- Transitivity of cyclotomic extensions. -/ lemma trans (C : Type w) [comm_ring C] [nontrivial C] [algebra A C] [algebra B C] [is_scalar_tower A B C] [hS : is_cyclotomic_extension S A B] [hT : is_cyclotomic_extension T B C] [no_zero_smul_divisors B C] : is_cyclotomic_extension (S ∪ T) A C := begin refine ⟨λ n hn, _, λ x, _⟩, { cases hn, { obtain ⟨b, hb⟩ := ((is_cyclotomic_extension_iff _ _ _).1 hS).1 hn, refine ⟨algebra_map B C b, _⟩, exact hb.map_of_injective (no_zero_smul_divisors.algebra_map_injective B C) }, { exact ((is_cyclotomic_extension_iff _ _ _).1 hT).1 hn } }, { refine adjoin_induction (((is_cyclotomic_extension_iff _ _ _).1 hT).2 x) (λ c ⟨n, hn⟩, subset_adjoin ⟨n, or.inr hn.1, hn.2⟩) (λ b, _) (λ x y hx hy, subalgebra.add_mem _ hx hy) (λ x y hx hy, subalgebra.mul_mem _ hx hy), { let f := is_scalar_tower.to_alg_hom A B C, have hb : f b ∈ (adjoin A { b : B | ∃ (a : ℕ+), a ∈ S ∧ b ^ (a : ℕ) = 1 }).map f := ⟨b, ((is_cyclotomic_extension_iff _ _ _).1 hS).2 b, rfl⟩, rw [is_scalar_tower.to_alg_hom_apply, ← adjoin_image] at hb, refine adjoin_mono (λ y hy, _) hb, obtain ⟨b₁, ⟨⟨n, hn⟩, h₁⟩⟩ := hy, exact ⟨n, ⟨mem_union_left T hn.1, by rw [← h₁, ← alg_hom.map_pow, hn.2, alg_hom.map_one]⟩⟩ } } end @[nontriviality] lemma subsingleton_iff [subsingleton B] : is_cyclotomic_extension S A B ↔ S = {} ∨ S = {1} := begin split, { rintro ⟨hprim, -⟩, rw ←subset_singleton_iff_eq, intros t ht, obtain ⟨ζ, hζ⟩ := hprim ht, rw [mem_singleton_iff, ←pnat.coe_eq_one_iff], exact_mod_cast hζ.unique (is_primitive_root.of_subsingleton ζ) }, { rintro (rfl|rfl), { refine ⟨λ _ h, h.elim, λ x, by convert (mem_top : x ∈ ⊤)⟩ }, { rw iff_singleton, refine ⟨⟨0, is_primitive_root.of_subsingleton 0⟩, λ x, by convert (mem_top : x ∈ ⊤)⟩ } } end /-- If `B` is a cyclotomic extension of `A` given by roots of unity of order in `S ∪ T`, then `B` is a cyclotomic extension of `adjoin A { b : B | ∃ a : ℕ+, a ∈ S ∧ b ^ (a : ℕ) = 1 } ` given by roots of unity of order in `T`. -/ lemma union_right [h : is_cyclotomic_extension (S ∪ T) A B] : is_cyclotomic_extension T (adjoin A { b : B | ∃ a : ℕ+, a ∈ S ∧ b ^ (a : ℕ) = 1 }) B := begin have : { b : B | ∃ (n : ℕ+), n ∈ S ∪ T ∧ b ^ (n : ℕ) = 1 } = { b : B | ∃ (n : ℕ+), n ∈ S ∧ b ^ (n : ℕ) = 1 } ∪ { b : B | ∃ (n : ℕ+), n ∈ T ∧ b ^ (n : ℕ) = 1 }, { refine le_antisymm (λ x hx, _) (λ x hx, _), { rcases hx with ⟨n, hn₁ | hn₂, hnpow⟩, { left, exact ⟨n, hn₁, hnpow⟩ }, { right, exact ⟨n, hn₂, hnpow⟩ } }, { rcases hx with ⟨n, hn⟩ | ⟨n, hn⟩, { exact ⟨n, or.inl hn.1, hn.2⟩ }, { exact ⟨n, or.inr hn.1, hn.2⟩ } } }, refine ⟨λ n hn, ((is_cyclotomic_extension_iff _ _ _).1 h).1 (mem_union_right S hn), λ b, _⟩, replace h := ((is_cyclotomic_extension_iff _ _ _).1 h).2 b, rwa [this, adjoin_union_eq_adjoin_adjoin, subalgebra.mem_restrict_scalars] at h end /-- If `B` is a cyclotomic extension of `A` given by roots of unity of order in `T` and `S ⊆ T`, then `adjoin A { b : B | ∃ a : ℕ+, a ∈ S ∧ b ^ (a : ℕ) = 1 }` is a cyclotomic extension of `B` given by roots of unity of order in `S`. -/ lemma union_left [h : is_cyclotomic_extension T A B] (hS : S ⊆ T) : is_cyclotomic_extension S A (adjoin A { b : B | ∃ a : ℕ+, a ∈ S ∧ b ^ (a : ℕ) = 1 }) := begin refine ⟨λ n hn, _, λ b, _⟩, { obtain ⟨b, hb⟩ := ((is_cyclotomic_extension_iff _ _ _).1 h).1 (hS hn), refine ⟨⟨b, subset_adjoin ⟨n, hn, hb.pow_eq_one⟩⟩, _⟩, rwa [← is_primitive_root.coe_submonoid_class_iff, subtype.coe_mk] }, { convert mem_top, rw [← adjoin_adjoin_coe_preimage, preimage_set_of_eq], norm_cast } end @[protected] lemma ne_zero [h : is_cyclotomic_extension {n} A B] [is_domain B] : ne_zero ((n : ℕ) : B) := begin obtain ⟨⟨r, hr⟩, -⟩ := (iff_singleton n A B).1 h, exact hr.ne_zero' end @[protected] lemma ne_zero' [is_cyclotomic_extension {n} A B] [is_domain B] : ne_zero ((n : ℕ) : A) := begin apply ne_zero.nat_of_ne_zero (algebra_map A B), exact ne_zero n A B, end end basic section fintype lemma finite_of_singleton [is_domain B] [h : is_cyclotomic_extension {n} A B] : finite A B := begin classical, rw [module.finite_def, ← top_to_submodule, ← ((iff_adjoin_eq_top _ _ _).1 h).2], refine fg_adjoin_of_finite _ (λ b hb, _), { simp only [mem_singleton_iff, exists_eq_left], have : {b : B | b ^ (n : ℕ) = 1} = (nth_roots n (1 : B)).to_finset := set.ext (λ x, ⟨λ h, by simpa using h, λ h, by simpa using h⟩), rw [this], exact (nth_roots ↑n 1).to_finset.finite_to_set }, { simp only [mem_singleton_iff, exists_eq_left, mem_set_of_eq] at hb, refine ⟨X ^ (n : ℕ) - 1, ⟨monic_X_pow_sub_C _ n.pos.ne.symm, by simp [hb]⟩⟩ } end /-- If `S` is finite and `is_cyclotomic_extension S A B`, then `B` is a finite `A`-algebra. -/ lemma finite [is_domain B] [h₁ : fintype S] [h₂ : is_cyclotomic_extension S A B] : finite A B := begin unfreezingI {revert h₂ A B}, refine set.finite.induction_on (set.finite.intro h₁) (λ A B, _) (λ n S hn hS H A B, _), { introsI _ _ _ _ _, refine module.finite_def.2 ⟨({1} : finset B), _⟩, simp [← top_to_submodule, ← empty, to_submodule_bot] }, { introsI _ _ _ _ h, haveI : is_cyclotomic_extension S A (adjoin A { b : B | ∃ (n : ℕ+), n ∈ S ∧ b ^ (n : ℕ) = 1 }) := union_left _ (insert n S) _ _ (subset_insert n S), haveI := H A (adjoin A { b : B | ∃ (n : ℕ+), n ∈ S ∧ b ^ (n : ℕ) = 1 }), haveI : finite (adjoin A { b : B | ∃ (n : ℕ+), n ∈ S ∧ b ^ (n : ℕ) = 1 }) B, { rw [← union_singleton] at h, letI := @union_right S {n} A B _ _ _ h, exact finite_of_singleton n _ _ }, exact finite.trans (adjoin A { b : B | ∃ (n : ℕ+), n ∈ S ∧ b ^ (n : ℕ) = 1 }) _ } end /-- A cyclotomic finite extension of a number field is a number field. -/ lemma number_field [h : number_field K] [fintype S] [is_cyclotomic_extension S K L] : number_field L := { to_char_zero := char_zero_of_injective_algebra_map (algebra_map K L).injective, to_finite_dimensional := @finite.trans _ K L _ _ _ _ (@algebra_rat L _ (char_zero_of_injective_algebra_map (algebra_map K L).injective)) _ _ h.to_finite_dimensional (finite S K L) } localized "attribute [instance] is_cyclotomic_extension.number_field" in cyclotomic /-- A finite cyclotomic extension of an integral noetherian domain is integral -/ lemma integral [is_domain B] [is_noetherian_ring A] [fintype S] [is_cyclotomic_extension S A B] : algebra.is_integral A B := is_integral_of_noetherian $ is_noetherian_of_fg_of_noetherian' $ (finite S A B).out /-- If `S` is finite and `is_cyclotomic_extension S K A`, then `finite_dimensional K A`. -/ lemma finite_dimensional (C : Type z) [fintype S] [comm_ring C] [algebra K C] [is_domain C] [is_cyclotomic_extension S K C] : finite_dimensional K C := finite S K C localized "attribute [instance] is_cyclotomic_extension.finite_dimensional" in cyclotomic end fintype section variables {A B} lemma adjoin_roots_cyclotomic_eq_adjoin_nth_roots [decidable_eq B] [is_domain B] {ζ : B} {n : ℕ+} (hζ : is_primitive_root ζ n) : adjoin A ↑((map (algebra_map A B) (cyclotomic n A)).roots.to_finset) = adjoin A {b : B | ∃ (a : ℕ+), a ∈ ({n} : set ℕ+) ∧ b ^ (a : ℕ) = 1} := begin simp only [mem_singleton_iff, exists_eq_left, map_cyclotomic], refine le_antisymm (adjoin_mono (λ x hx, _)) (adjoin_le (λ x hx, _)), { simp only [multiset.mem_to_finset, finset.mem_coe, map_cyclotomic, mem_roots (cyclotomic_ne_zero n B)] at hx, simp only [mem_singleton_iff, exists_eq_left, mem_set_of_eq], rw is_root_of_unity_iff n.pos, exact ⟨n, nat.mem_divisors_self n n.ne_zero, hx⟩ }, { simp only [mem_singleton_iff, exists_eq_left, mem_set_of_eq] at hx, obtain ⟨i, hin, rfl⟩ := hζ.eq_pow_of_pow_eq_one hx n.pos, refine set_like.mem_coe.2 (subalgebra.pow_mem _ (subset_adjoin _) _), rwa [finset.mem_coe, multiset.mem_to_finset, mem_roots $ cyclotomic_ne_zero n B], exact hζ.is_root_cyclotomic n.pos } end lemma adjoin_roots_cyclotomic_eq_adjoin_root_cyclotomic {n : ℕ+} [decidable_eq B] [is_domain B] {ζ : B} (hζ : is_primitive_root ζ n) : adjoin A (((map (algebra_map A B) (cyclotomic n A)).roots.to_finset) : set B) = adjoin A ({ζ}) := begin refine le_antisymm (adjoin_le (λ x hx, _)) (adjoin_mono (λ x hx, _)), { suffices hx : x ^ ↑n = 1, obtain ⟨i, hin, rfl⟩ := hζ.eq_pow_of_pow_eq_one hx n.pos, exact set_like.mem_coe.2 (subalgebra.pow_mem _ (subset_adjoin $ mem_singleton ζ) _), rw is_root_of_unity_iff n.pos, refine ⟨n, nat.mem_divisors_self n n.ne_zero, _⟩, rwa [finset.mem_coe, multiset.mem_to_finset, map_cyclotomic, mem_roots $ cyclotomic_ne_zero n B] at hx }, { simp only [mem_singleton_iff, exists_eq_left, mem_set_of_eq] at hx, simpa only [hx, multiset.mem_to_finset, finset.mem_coe, map_cyclotomic, mem_roots (cyclotomic_ne_zero n B)] using hζ.is_root_cyclotomic n.pos } end lemma adjoin_primitive_root_eq_top {n : ℕ+} [is_domain B] [h : is_cyclotomic_extension {n} A B] {ζ : B} (hζ : is_primitive_root ζ n) : adjoin A ({ζ} : set B) = ⊤ := begin classical, rw ←adjoin_roots_cyclotomic_eq_adjoin_root_cyclotomic hζ, rw adjoin_roots_cyclotomic_eq_adjoin_nth_roots hζ, exact ((iff_adjoin_eq_top {n} A B).mp h).2, end variable (A) lemma _root_.is_primitive_root.adjoin_is_cyclotomic_extension {ζ : B} {n : ℕ+} (h : is_primitive_root ζ n) : is_cyclotomic_extension {n} A (adjoin A ({ζ} : set B)) := { exists_prim_root := λ i hi, begin rw [set.mem_singleton_iff] at hi, refine ⟨⟨ζ, subset_adjoin $ set.mem_singleton ζ⟩, _⟩, rwa [← is_primitive_root.coe_submonoid_class_iff, subtype.coe_mk, hi], end, adjoin_roots := λ x, begin refine adjoin_induction' (λ b hb, _) (λ a, _) (λ b₁ b₂ hb₁ hb₂, _) (λ b₁ b₂ hb₁ hb₂, _) x, { rw [set.mem_singleton_iff] at hb, refine subset_adjoin _, simp only [mem_singleton_iff, exists_eq_left, mem_set_of_eq, hb], rw [← subalgebra.coe_eq_one, subalgebra.coe_pow, set_like.coe_mk], exact ((is_primitive_root.iff_def ζ n).1 h).1 }, { exact subalgebra.algebra_map_mem _ _ }, { exact subalgebra.add_mem _ hb₁ hb₂ }, { exact subalgebra.mul_mem _ hb₁ hb₂ } end } end section field variables {n S} /-- A cyclotomic extension splits `X ^ n - 1` if `n ∈ S`.-/ lemma splits_X_pow_sub_one [H : is_cyclotomic_extension S K L] (hS : n ∈ S) : splits (algebra_map K L) (X ^ (n : ℕ) - 1) := begin rw [← splits_id_iff_splits, polynomial.map_sub, polynomial.map_one, polynomial.map_pow, polynomial.map_X], obtain ⟨z, hz⟩ := ((is_cyclotomic_extension_iff _ _ _).1 H).1 hS, exact X_pow_sub_one_splits hz, end /-- A cyclotomic extension splits `cyclotomic n K` if `n ∈ S` and `ne_zero (n : K)`.-/ lemma splits_cyclotomic [is_cyclotomic_extension S K L] (hS : n ∈ S) : splits (algebra_map K L) (cyclotomic n K) := begin refine splits_of_splits_of_dvd _ (X_pow_sub_C_ne_zero n.pos _) (splits_X_pow_sub_one K L hS) _, use (∏ (i : ℕ) in (n : ℕ).proper_divisors, polynomial.cyclotomic i K), rw [(eq_cyclotomic_iff n.pos _).1 rfl, ring_hom.map_one], end variables (n S) section singleton variables [is_cyclotomic_extension {n} K L] /-- If `is_cyclotomic_extension {n} K L`, then `L` is the splitting field of `X ^ n - 1`. -/ lemma splitting_field_X_pow_sub_one : is_splitting_field K L (X ^ (n : ℕ) - 1) := { splits := splits_X_pow_sub_one K L (mem_singleton n), adjoin_roots := begin rw [← ((iff_adjoin_eq_top {n} K L).1 infer_instance).2], congr, refine set.ext (λ x, _), simp only [polynomial.map_pow, mem_singleton_iff, multiset.mem_to_finset, exists_eq_left, mem_set_of_eq, polynomial.map_X, polynomial.map_one, finset.mem_coe, polynomial.map_sub], rwa [← ring_hom.map_one C, mem_roots (@X_pow_sub_C_ne_zero L _ _ _ n.pos _), is_root.def, eval_sub, eval_pow, eval_C, eval_X, sub_eq_zero] end } localized "attribute [instance] is_cyclotomic_extension.splitting_field_X_pow_sub_one" in cyclotomic include n lemma is_galois : is_galois K L := begin letI := splitting_field_X_pow_sub_one n K L, exact is_galois.of_separable_splitting_field (X_pow_sub_one_separable_iff.2 ((ne_zero' n K L).1)) end localized "attribute [instance] is_cyclotomic_extension.is_galois" in cyclotomic /-- If `is_cyclotomic_extension {n} K L`, then `L` is the splitting field of `cyclotomic n K`. -/ lemma splitting_field_cyclotomic : is_splitting_field K L (cyclotomic n K) := { splits := splits_cyclotomic K L (mem_singleton n), adjoin_roots := begin rw [← ((iff_adjoin_eq_top {n} K L).1 infer_instance).2], letI := classical.dec_eq L, obtain ⟨ζ, hζ⟩ := @is_cyclotomic_extension.exists_prim_root {n} K L _ _ _ _ _ (mem_singleton n), exact adjoin_roots_cyclotomic_eq_adjoin_nth_roots hζ end } localized "attribute [instance] is_cyclotomic_extension.splitting_field_cyclotomic" in cyclotomic end singleton end field end is_cyclotomic_extension section cyclotomic_field /-- Given `n : ℕ+` and a field `K`, we define `cyclotomic_field n K` as the splitting field of `cyclotomic n K`. If `n` is nonzero in `K`, it has the instance `is_cyclotomic_extension {n} K (cyclotomic_field n K)`. -/ @[derive [field, algebra K, inhabited]] def cyclotomic_field : Type w := (cyclotomic n K).splitting_field namespace cyclotomic_field instance [char_zero K] : char_zero (cyclotomic_field n K) := char_zero_of_injective_algebra_map ((algebra_map K _).injective) instance is_cyclotomic_extension [ne_zero ((n : ℕ) : K)] : is_cyclotomic_extension {n} K (cyclotomic_field n K) := { exists_prim_root := λ a han, begin rw mem_singleton_iff at han, subst a, obtain ⟨r, hr⟩ := exists_root_of_splits (algebra_map K (cyclotomic_field n K)) (splitting_field.splits _) (degree_cyclotomic_pos n K (n.pos)).ne', refine ⟨r, _⟩, haveI := ne_zero.of_no_zero_smul_divisors K (cyclotomic_field n K) n, rwa [← eval_map, ← is_root.def, map_cyclotomic, is_root_cyclotomic_iff] at hr end, adjoin_roots := begin rw [←algebra.eq_top_iff, ←splitting_field.adjoin_roots, eq_comm], letI := classical.dec_eq (cyclotomic_field n K), obtain ⟨ζ, hζ⟩ := exists_root_of_splits _ (splitting_field.splits (cyclotomic n K)) (degree_cyclotomic_pos n _ n.pos).ne', haveI : ne_zero ((n : ℕ) : (cyclotomic_field n K)) := ne_zero.nat_of_injective (algebra_map K _).injective, rw [eval₂_eq_eval_map, map_cyclotomic, ← is_root.def, is_root_cyclotomic_iff] at hζ, exact is_cyclotomic_extension.adjoin_roots_cyclotomic_eq_adjoin_nth_roots hζ, end } end cyclotomic_field end cyclotomic_field section is_domain variables [is_domain A] [algebra A K] [is_fraction_ring A K] section cyclotomic_ring /-- If `K` is the fraction field of `A`, the `A`-algebra structure on `cyclotomic_field n K`. This is not an instance since it causes diamonds when `A = ℤ`. -/ @[nolint unused_arguments] def cyclotomic_field.algebra_base : algebra A (cyclotomic_field n K) := ((algebra_map K (cyclotomic_field n K)).comp (algebra_map A K)).to_algebra local attribute [instance] cyclotomic_field.algebra_base instance cyclotomic_field.no_zero_smul_divisors : no_zero_smul_divisors A (cyclotomic_field n K) := no_zero_smul_divisors.of_algebra_map_injective $ function.injective.comp (no_zero_smul_divisors.algebra_map_injective _ _) $ is_fraction_ring.injective A K /-- If `A` is a domain with fraction field `K` and `n : ℕ+`, we define `cyclotomic_ring n A K` as the `A`-subalgebra of `cyclotomic_field n K` generated by the roots of `X ^ n - 1`. If `n` is nonzero in `A`, it has the instance `is_cyclotomic_extension {n} A (cyclotomic_ring n A K)`. -/ @[derive [comm_ring, is_domain, inhabited]] def cyclotomic_ring : Type w := adjoin A { b : (cyclotomic_field n K) | b ^ (n : ℕ) = 1 } namespace cyclotomic_ring /-- The `A`-algebra structure on `cyclotomic_ring n A K`. This is not an instance since it causes diamonds when `A = ℤ`. -/ def algebra_base : algebra A (cyclotomic_ring n A K) := (adjoin A _).algebra local attribute [instance] cyclotomic_ring.algebra_base instance : no_zero_smul_divisors A (cyclotomic_ring n A K) := (adjoin A _).no_zero_smul_divisors_bot lemma algebra_base_injective : function.injective $ algebra_map A (cyclotomic_ring n A K) := no_zero_smul_divisors.algebra_map_injective _ _ instance : algebra (cyclotomic_ring n A K) (cyclotomic_field n K) := (adjoin A _).to_algebra lemma adjoin_algebra_injective : function.injective $ algebra_map (cyclotomic_ring n A K) (cyclotomic_field n K) := subtype.val_injective instance : no_zero_smul_divisors (cyclotomic_ring n A K) (cyclotomic_field n K) := no_zero_smul_divisors.of_algebra_map_injective (adjoin_algebra_injective n A K) instance : is_scalar_tower A (cyclotomic_ring n A K) (cyclotomic_field n K) := is_scalar_tower.subalgebra' _ _ _ _ instance is_cyclotomic_extension [ne_zero ((n : ℕ) : A)] : is_cyclotomic_extension {n} A (cyclotomic_ring n A K) := { exists_prim_root := λ a han, begin rw mem_singleton_iff at han, subst a, haveI := ne_zero.of_no_zero_smul_divisors A K n, haveI := ne_zero.of_no_zero_smul_divisors A (cyclotomic_field n K) n, obtain ⟨μ, hμ⟩ := (cyclotomic_field.is_cyclotomic_extension n K).exists_prim_root (mem_singleton n), refine ⟨⟨μ, subset_adjoin _⟩, _⟩, { apply (is_root_of_unity_iff n.pos (cyclotomic_field n K)).mpr, refine ⟨n, nat.mem_divisors_self _ n.ne_zero, _⟩, rwa [← is_root_cyclotomic_iff] at hμ }, { rwa [← is_primitive_root.coe_submonoid_class_iff, subtype.coe_mk] } end, adjoin_roots := λ x, begin refine adjoin_induction' (λ y hy, _) (λ a, _) (λ y z hy hz, _) (λ y z hy hz, _) x, { refine subset_adjoin _, simp only [mem_singleton_iff, exists_eq_left, mem_set_of_eq], rwa [← subalgebra.coe_eq_one, subalgebra.coe_pow, subtype.coe_mk] }, { exact subalgebra.algebra_map_mem _ a }, { exact subalgebra.add_mem _ hy hz }, { exact subalgebra.mul_mem _ hy hz }, end } instance [ne_zero ((n : ℕ) : A)] : is_fraction_ring (cyclotomic_ring n A K) (cyclotomic_field n K) := { map_units := λ ⟨x, hx⟩, begin rw is_unit_iff_ne_zero, apply map_ne_zero_of_mem_non_zero_divisors, apply adjoin_algebra_injective, exact hx end, surj := λ x, begin letI : ne_zero ((n : ℕ) : K) := ne_zero.nat_of_injective (is_fraction_ring.injective A K), refine algebra.adjoin_induction (((is_cyclotomic_extension.iff_singleton n K _).1 (cyclotomic_field.is_cyclotomic_extension n K)).2 x) (λ y hy, _) (λ k, _) _ _, { exact ⟨⟨⟨y, subset_adjoin hy⟩, 1⟩, by simpa⟩ }, { have : is_localization (non_zero_divisors A) K := infer_instance, replace := this.surj, obtain ⟨⟨z, w⟩, hw⟩ := this k, refine ⟨⟨algebra_map A _ z, algebra_map A _ w, map_mem_non_zero_divisors _ (algebra_base_injective n A K) w.2⟩, _⟩, letI : is_scalar_tower A K (cyclotomic_field n K) := is_scalar_tower.of_algebra_map_eq (congr_fun rfl), rw [set_like.coe_mk, ← is_scalar_tower.algebra_map_apply, ← is_scalar_tower.algebra_map_apply, @is_scalar_tower.algebra_map_apply A K _ _ _ _ _ (_root_.cyclotomic_field.algebra n K) _ _ w, ← ring_hom.map_mul, hw, ← is_scalar_tower.algebra_map_apply] }, { rintro y z ⟨a, ha⟩ ⟨b, hb⟩, refine ⟨⟨a.1 * b.2 + b.1 * a.2, a.2 * b.2, mul_mem_non_zero_divisors.2 ⟨a.2.2, b.2.2⟩⟩, _⟩, rw [set_like.coe_mk, ring_hom.map_mul, add_mul, ← mul_assoc, ha, mul_comm ((algebra_map _ _) ↑a.2), ← mul_assoc, hb], simp only [map_add, map_mul] }, { rintro y z ⟨a, ha⟩ ⟨b, hb⟩, refine ⟨⟨a.1 * b.1, a.2 * b.2, mul_mem_non_zero_divisors.2 ⟨a.2.2, b.2.2⟩⟩, _⟩, rw [set_like.coe_mk, ring_hom.map_mul, mul_comm ((algebra_map _ _) ↑a.2), mul_assoc, ← mul_assoc z, hb, ← mul_comm ((algebra_map _ _) ↑a.2), ← mul_assoc, ha], simp only [map_mul] } end, eq_iff_exists := λ x y, ⟨λ h, ⟨1, by rw adjoin_algebra_injective n A K h⟩, λ ⟨c, hc⟩, by rw mul_right_cancel₀ (non_zero_divisors.ne_zero c.prop) hc⟩ } lemma eq_adjoin_primitive_root {μ : (cyclotomic_field n K)} (h : is_primitive_root μ n) : cyclotomic_ring n A K = adjoin A ({μ} : set ((cyclotomic_field n K))) := begin letI := classical.prop_decidable, rw [←is_cyclotomic_extension.adjoin_roots_cyclotomic_eq_adjoin_root_cyclotomic h, is_cyclotomic_extension.adjoin_roots_cyclotomic_eq_adjoin_nth_roots h], simp [cyclotomic_ring] end end cyclotomic_ring end cyclotomic_ring end is_domain section is_alg_closed variables [is_alg_closed K] /-- Algebraically closed fields are `S`-cyclotomic extensions over themselves if `ne_zero ((a : ℕ) : K))` for all `a ∈ S`. -/ lemma is_alg_closed.is_cyclotomic_extension (h : ∀ a ∈ S, ne_zero ((a : ℕ) : K)) : is_cyclotomic_extension S K K := begin refine ⟨λ a ha, _, algebra.eq_top_iff.mp $ subsingleton.elim _ _ ⟩, obtain ⟨r, hr⟩ := is_alg_closed.exists_aeval_eq_zero K _ (degree_cyclotomic_pos a K a.pos).ne', refine ⟨r, _⟩, haveI := h a ha, rwa [coe_aeval_eq_eval, ← is_root.def, is_root_cyclotomic_iff] at hr, end instance is_alg_closed_of_char_zero.is_cyclotomic_extension [char_zero K] : ∀ S, is_cyclotomic_extension S K K := λ S, is_alg_closed.is_cyclotomic_extension S K (λ a ha, infer_instance) end is_alg_closed
a2a9bff063c6f1a2c1d31f49361b157296c673df
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/group_theory/free_product.lean
9426a82491c5691d274f5f086dbebaa45bf45f28
[ "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
33,924
lean
/- Copyright (c) 2021 David Wärn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Wärn, Joachim Breitner -/ import algebra.free_monoid.basic import group_theory.congruence import group_theory.is_free_group import data.list.chain import set_theory.cardinal.ordinal import data.set.pointwise.smul /-! # The free product of groups or monoids > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Given an `ι`-indexed family `M` of monoids, we define their free product (categorical coproduct) `free_product M`. When `ι` and all `M i` have decidable equality, the free product bijects with the type `word M` of reduced words. This bijection is constructed by defining an action of `free_product M` on `word M`. When `M i` are all groups, `free_product M` is also a group (and the coproduct in the category of groups). ## Main definitions - `free_product M`: the free product, defined as a quotient of a free monoid. - `free_product.of {i} : M i →* free_product M`. - `free_product.lift : (Π {i}, M i →* N) ≃ (free_product M →* N)`: the universal property. - `free_product.word M`: the type of reduced words. - `free_product.word.equiv M : free_product M ≃ word M`. - `free_product.neword M i j`: an inductive description of non-empty words with first letter from `M i` and last letter from `M j`, together with an API (`singleton`, `append`, `head`, `tail`, `to_word`, `prod`, `inv`). Used in the proof of the Ping-Pong-lemma. - `free_product.lift_injective_of_ping_pong`: The Ping-Pong-lemma, proving injectivity of the `lift`. See the documentation of that theorem for more information. ## Remarks There are many answers to the question "what is the free product of a family `M` of monoids?", and they are all equivalent but not obviously equivalent. We provide two answers. The first, almost tautological answer is given by `free_product M`, which is a quotient of the type of words in the alphabet `Σ i, M i`. It's straightforward to define and easy to prove its universal property. But this answer is not completely satisfactory, because it's difficult to tell when two elements `x y : free_product M` are distinct since `free_product M` is defined as a quotient. The second, maximally efficient answer is given by `word M`. An element of `word M` is a word in the alphabet `Σ i, M i`, where the letter `⟨i, 1⟩` doesn't occur and no adjacent letters share an index `i`. Since we only work with reduced words, there is no need for quotienting, and it is easy to tell when two elements are distinct. However it's not obvious that this is even a monoid! We prove that every element of `free_product M` can be represented by a unique reduced word, i.e. `free_product M` and `word M` are equivalent types. This means that `word M` can be given a monoid structure, and it lets us tell when two elements of `free_product M` are distinct. There is also a completely tautological, maximally inefficient answer given by `algebra.category.Mon.colimits`. Whereas `free_product M` at least ensures that (any instance of) associativity holds by reflexivity, in this answer associativity holds because of quotienting. Yet another answer, which is constructively more satisfying, could be obtained by showing that `free_product.rel` is confluent. ## References [van der Waerden, *Free products of groups*][MR25465] -/ open set variables {ι : Type*} (M : Π i : ι, Type*) [Π i, monoid (M i)] /-- A relation on the free monoid on alphabet `Σ i, M i`, relating `⟨i, 1⟩` with `1` and `⟨i, x⟩ * ⟨i, y⟩` with `⟨i, x * y⟩`. -/ inductive free_product.rel : free_monoid (Σ i, M i) → free_monoid (Σ i, M i) → Prop | of_one (i : ι) : free_product.rel (free_monoid.of ⟨i, 1⟩) 1 | of_mul {i : ι} (x y : M i) : free_product.rel (free_monoid.of ⟨i, x⟩ * free_monoid.of ⟨i, y⟩) (free_monoid.of ⟨i, x * y⟩) /-- The free product (categorical coproduct) of an indexed family of monoids. -/ @[derive [monoid, inhabited]] def free_product : Type* := (con_gen (free_product.rel M)).quotient namespace free_product /-- The type of reduced words. A reduced word cannot contain a letter `1`, and no two adjacent letters can come from the same summand. -/ @[ext] structure word := (to_list : list (Σ i, M i)) (ne_one : ∀ l ∈ to_list, sigma.snd l ≠ 1) (chain_ne : to_list.chain' (λ l l', sigma.fst l ≠ sigma.fst l')) variable {M} /-- The inclusion of a summand into the free product. -/ def of {i : ι} : M i →* free_product M := { to_fun := λ x, con.mk' _ (free_monoid.of $ sigma.mk i x), map_one' := (con.eq _).mpr (con_gen.rel.of _ _ (free_product.rel.of_one i)), map_mul' := λ x y, eq.symm $ (con.eq _).mpr (con_gen.rel.of _ _ (free_product.rel.of_mul x y)) } lemma of_apply {i} (m : M i) : of m = con.mk' _ (free_monoid.of $ sigma.mk i m) := rfl variables {N : Type*} [monoid N] /-- See note [partially-applied ext lemmas]. -/ @[ext] lemma ext_hom (f g : free_product M →* N) (h : ∀ i, f.comp (of : M i →* _) = g.comp of) : f = g := (monoid_hom.cancel_right con.mk'_surjective).mp $ free_monoid.hom_eq $ λ ⟨i, x⟩, by rw [monoid_hom.comp_apply, monoid_hom.comp_apply, ←of_apply, ←monoid_hom.comp_apply, ←monoid_hom.comp_apply, h] /-- A map out of the free product corresponds to a family of maps out of the summands. This is the universal property of the free product, charaterizing it as a categorical coproduct. -/ @[simps symm_apply] def lift : (Π i, M i →* N) ≃ (free_product M →* N) := { to_fun := λ fi, con.lift _ (free_monoid.lift $ λ p : Σ i, M i, fi p.fst p.snd) $ con.con_gen_le begin simp_rw [con.rel_eq_coe, con.ker_rel], rintro _ _ (i | ⟨x, y⟩), { change free_monoid.lift _ (free_monoid.of _) = free_monoid.lift _ 1, simp only [monoid_hom.map_one, free_monoid.lift_eval_of], }, { change free_monoid.lift _ (free_monoid.of _ * free_monoid.of _) = free_monoid.lift _ (free_monoid.of _), simp only [monoid_hom.map_mul, free_monoid.lift_eval_of], } end, inv_fun := λ f i, f.comp of, left_inv := by { intro fi, ext i x, rw [monoid_hom.comp_apply, of_apply, con.lift_mk', free_monoid.lift_eval_of], }, right_inv := by { intro f, ext i x, simp only [monoid_hom.comp_apply, of_apply, con.lift_mk', free_monoid.lift_eval_of], } } @[simp] lemma lift_of {N} [monoid N] (fi : Π i, M i →* N) {i} (m : M i) : lift fi (of m) = fi i m := by conv_rhs { rw [←lift.symm_apply_apply fi, lift_symm_apply, monoid_hom.comp_apply] } @[elab_as_eliminator] lemma induction_on {C : free_product M → Prop} (m : free_product M) (h_one : C 1) (h_of : ∀ (i) (m : M i), C (of m)) (h_mul : ∀ (x y), C x → C y → C (x * y)) : C m := begin let S : submonoid (free_product M) := submonoid.mk (set_of C) h_mul h_one, convert subtype.prop (lift (λ i, of.cod_restrict S (h_of i)) m), change monoid_hom.id _ m = S.subtype.comp _ m, congr, ext, simp [monoid_hom.cod_restrict], end lemma of_left_inverse [decidable_eq ι] (i : ι) : function.left_inverse (lift $ pi.mul_single i (monoid_hom.id (M i))) of := λ x, by simp only [lift_of, pi.mul_single_eq_same, monoid_hom.id_apply] lemma of_injective (i : ι) : function.injective ⇑(of : M i →* _) := by { classical, exact (of_left_inverse i).injective } lemma lift_mrange_le {N} [monoid N] (f : Π i, M i →* N) {s : submonoid N} (h : ∀ i, (f i).mrange ≤ s) : (lift f).mrange ≤ s := begin rintros _ ⟨x, rfl⟩, induction x using free_product.induction_on with i x x y hx hy, { exact s.one_mem, }, { simp only [lift_of, set_like.mem_coe], exact h i (set.mem_range_self x), }, { simp only [map_mul, set_like.mem_coe], exact s.mul_mem hx hy, }, end lemma mrange_eq_supr {N} [monoid N] (f : Π i, M i →* N) : (lift f).mrange = ⨆ i, (f i).mrange := begin apply le_antisymm (lift_mrange_le f (λ i, le_supr _ i)), apply supr_le _, rintros i _ ⟨x, rfl⟩, exact ⟨of x, by simp only [lift_of]⟩ end section group variables (G : ι → Type*) [Π i, group (G i)] instance : has_inv (free_product G) := { inv := mul_opposite.unop ∘ lift (λ i, (of : G i →* _).op.comp (mul_equiv.inv' (G i)).to_monoid_hom) } lemma inv_def (x : free_product G) : x⁻¹ = mul_opposite.unop (lift (λ i, (of : G i →* _).op.comp (mul_equiv.inv' (G i)).to_monoid_hom) x) := rfl instance : group (free_product G) := { mul_left_inv := begin intro m, rw inv_def, apply m.induction_on, { rw [monoid_hom.map_one, mul_opposite.unop_one, one_mul], }, { intros i m, change of m⁻¹ * of m = 1, rw [←of.map_mul, mul_left_inv, of.map_one], }, { intros x y hx hy, rw [monoid_hom.map_mul, mul_opposite.unop_mul, mul_assoc, ← mul_assoc _ x y, hx, one_mul, hy], }, end, ..free_product.has_inv G, ..free_product.monoid G } lemma lift_range_le {N} [group N] (f : Π i, G i →* N) {s : subgroup N} (h : ∀ i, (f i).range ≤ s) : (lift f).range ≤ s := begin rintros _ ⟨x, rfl⟩, induction x using free_product.induction_on with i x x y hx hy, { exact s.one_mem, }, { simp only [lift_of, set_like.mem_coe], exact h i (set.mem_range_self x), }, { simp only [map_mul, set_like.mem_coe], exact s.mul_mem hx hy, }, end lemma range_eq_supr {N} [group N] (f : Π i, G i →* N) : (lift f).range = ⨆ i, (f i).range := begin apply le_antisymm (lift_range_le _ f (λ i, le_supr _ i)), apply supr_le _, rintros i _ ⟨x, rfl⟩, exact ⟨of x, by simp only [lift_of]⟩ end end group namespace word /-- The empty reduced word. -/ def empty : word M := { to_list := [], ne_one := λ _, false.elim, chain_ne := list.chain'_nil } instance : inhabited (word M) := ⟨empty⟩ /-- A reduced word determines an element of the free product, given by multiplication. -/ def prod (w : word M) : free_product M := list.prod (w.to_list.map $ λ l, of l.snd) @[simp] lemma prod_empty : prod (empty : word M) = 1 := rfl /-- `fst_idx w` is `some i` if the first letter of `w` is `⟨i, m⟩` with `m : M i`. If `w` is empty then it's `none`. -/ def fst_idx (w : word M) : option ι := w.to_list.head'.map sigma.fst lemma fst_idx_ne_iff {w : word M} {i} : fst_idx w ≠ some i ↔ ∀ l ∈ w.to_list.head', i ≠ sigma.fst l := not_iff_not.mp $ by simp [fst_idx] variable (M) /-- Given an index `i : ι`, `pair M i` is the type of pairs `(head, tail)` where `head : M i` and `tail : word M`, subject to the constraint that first letter of `tail` can't be `⟨i, m⟩`. By prepending `head` to `tail`, one obtains a new word. We'll show that any word can be uniquely obtained in this way. -/ @[ext] structure pair (i : ι) := (head : M i) (tail : word M) (fst_idx_ne : fst_idx tail ≠ some i) instance (i : ι) : inhabited (pair M i) := ⟨⟨1, empty, by tauto⟩⟩ variable {M} variables [∀ i, decidable_eq (M i)] /-- Given a pair `(head, tail)`, we can form a word by prepending `head` to `tail`, except if `head` is `1 : M i` then we have to just return `word` since we need the result to be reduced. -/ def rcons {i} (p : pair M i) : word M := if h : p.head = 1 then p.tail else { to_list := ⟨i, p.head⟩ :: p.tail.to_list, ne_one := by { rintros l (rfl | hl), exact h, exact p.tail.ne_one l hl }, chain_ne := p.tail.chain_ne.cons' (fst_idx_ne_iff.mp p.fst_idx_ne) } /-- Given a word of the form `⟨l :: ls, h1, h2⟩`, we can form a word of the form `⟨ls, _, _⟩`, dropping the first letter. -/ private def mk_aux {l} (ls : list (Σ i, M i)) (h1 : ∀ l' ∈ l :: ls, sigma.snd l' ≠ 1) (h2 : (l :: ls).chain' _) : word M := ⟨ls, λ l' hl, h1 _ (list.mem_cons_of_mem _ hl), h2.tail⟩ lemma cons_eq_rcons {i} {m : M i} {ls h1 h2} : word.mk (⟨i, m⟩ :: ls) h1 h2 = rcons ⟨m, mk_aux ls h1 h2, fst_idx_ne_iff.mpr h2.rel_head'⟩ := by { rw [rcons, dif_neg], refl, exact h1 ⟨i, m⟩ (ls.mem_cons_self _) } @[simp] lemma prod_rcons {i} (p : pair M i) : prod (rcons p) = of p.head * prod p.tail := if hm : p.head = 1 then by rw [rcons, dif_pos hm, hm, monoid_hom.map_one, one_mul] else by rw [rcons, dif_neg hm, prod, list.map_cons, list.prod_cons, prod] lemma rcons_inj {i} : function.injective (rcons : pair M i → word M) := begin rintros ⟨m, w, h⟩ ⟨m', w', h'⟩ he, by_cases hm : m = 1; by_cases hm' : m' = 1, { simp only [rcons, dif_pos hm, dif_pos hm'] at he, cc, }, { exfalso, simp only [rcons, dif_pos hm, dif_neg hm'] at he, rw he at h, exact h rfl }, { exfalso, simp only [rcons, dif_pos hm', dif_neg hm] at he, rw ←he at h', exact h' rfl, }, { have : m = m' ∧ w.to_list = w'.to_list, { simpa only [rcons, dif_neg hm, dif_neg hm', true_and, eq_self_iff_true, subtype.mk_eq_mk, heq_iff_eq, ←subtype.ext_iff_val] using he }, rcases this with ⟨rfl, h⟩, congr, exact word.ext _ _ h, } end variable [decidable_eq ι] /-- Given `i : ι`, any reduced word can be decomposed into a pair `p` such that `w = rcons p`. -/ -- This definition is computable but not very nice to look at. Thankfully we don't have to inspect -- it, since `rcons` is known to be injective. private def equiv_pair_aux (i) : Π w : word M, { p : pair M i // rcons p = w } | w@⟨[], _, _⟩ := ⟨⟨1, w, by rintro ⟨⟩⟩, dif_pos rfl⟩ | w@⟨⟨j, m⟩ :: ls, h1, h2⟩ := if ij : i = j then { val := { head := ij.symm.rec m, tail := mk_aux ls h1 h2, fst_idx_ne := by cases ij; exact fst_idx_ne_iff.mpr h2.rel_head' }, property := by cases ij; exact cons_eq_rcons.symm } else ⟨⟨1, w, (option.some_injective _).ne (ne.symm ij)⟩, dif_pos rfl⟩ /-- The equivalence between words and pairs. Given a word, it decomposes it as a pair by removing the first letter if it comes from `M i`. Given a pair, it prepends the head to the tail. -/ def equiv_pair (i) : word M ≃ pair M i := { to_fun := λ w, (equiv_pair_aux i w).val, inv_fun := rcons, left_inv := λ w, (equiv_pair_aux i w).property, right_inv := λ p, rcons_inj (equiv_pair_aux i _).property } lemma equiv_pair_symm (i) (p : pair M i) : (equiv_pair i).symm p = rcons p := rfl lemma equiv_pair_eq_of_fst_idx_ne {i} {w : word M} (h : fst_idx w ≠ some i) : equiv_pair i w = ⟨1, w, h⟩ := (equiv_pair i).apply_eq_iff_eq_symm_apply.mpr $ eq.symm (dif_pos rfl) instance summand_action (i) : mul_action (M i) (word M) := { smul := λ m w, rcons { head := m * (equiv_pair i w).head, ..equiv_pair i w }, one_smul := λ w, by { simp_rw [one_mul], apply (equiv_pair i).symm_apply_eq.mpr, ext; refl }, mul_smul := λ m m' w, by simp only [mul_assoc, ←equiv_pair_symm, equiv.apply_symm_apply], } instance : mul_action (free_product M) (word M) := mul_action.of_End_hom (lift (λ i, mul_action.to_End_hom)) lemma of_smul_def (i) (w : word M) (m : M i) : of m • w = rcons { head := m * (equiv_pair i w).head, ..equiv_pair i w } := rfl lemma cons_eq_smul {i} {m : M i} {ls h1 h2} : word.mk (⟨i, m⟩ :: ls) h1 h2 = of m • mk_aux ls h1 h2 := by rw [cons_eq_rcons, of_smul_def, equiv_pair_eq_of_fst_idx_ne _]; simp only [mul_one] lemma smul_induction {C : word M → Prop} (h_empty : C empty) (h_smul : ∀ i (m : M i) w, C w → C (of m • w)) (w : word M) : C w := begin cases w with ls h1 h2, induction ls with l ls ih, { exact h_empty }, cases l with i m, rw cons_eq_smul, exact h_smul _ _ _ (ih _ _), end @[simp] lemma prod_smul (m) : ∀ w : word M, prod (m • w) = m * prod w := begin apply m.induction_on, { intro, rw [one_smul, one_mul] }, { intros, rw [of_smul_def, prod_rcons, of.map_mul, mul_assoc, ←prod_rcons, ←equiv_pair_symm, equiv.symm_apply_apply] }, { intros x y hx hy w, rw [mul_smul, hx, hy, mul_assoc] }, end /-- Each element of the free product corresponds to a unique reduced word. -/ def equiv : free_product M ≃ word M := { to_fun := λ m, m • empty, inv_fun := λ w, prod w, left_inv := λ m, by dsimp only; rw [prod_smul, prod_empty, mul_one], right_inv := begin apply smul_induction, { dsimp only, rw [prod_empty, one_smul], }, { dsimp only, intros i m w ih, rw [prod_smul, mul_smul, ih], }, end } instance : decidable_eq (word M) := function.injective.decidable_eq word.ext instance : decidable_eq (free_product M) := word.equiv.decidable_eq end word variable (M) /-- A `neword M i j` is a representation of a non-empty reduced words where the first letter comes from `M i` and the last letter comes from `M j`. It can be constructed from singletons and via concatentation, and thus provides a useful induction principle. -/ @[nolint has_nonempty_instance] inductive neword : ι → ι → Type (max u_1 u_2) | singleton : ∀ {i} (x : M i) (hne1 : x ≠ 1), neword i i | append : ∀ {i j k l} (w₁ : neword i j) (hne : j ≠ k) (w₂ : neword k l), neword i l variable {M} namespace neword open word /-- The list represented by a given `neword` -/ @[simp] def to_list : Π {i j} (w : neword M i j), list (Σ i, M i) | i _ (singleton x hne1) := [⟨i, x⟩] | _ _ (append w₁ hne w₂) := w₁.to_list ++ w₂.to_list lemma to_list_ne_nil {i j} (w : neword M i j) : w.to_list ≠ list.nil := by { induction w, { rintros ⟨rfl⟩ }, { apply list.append_ne_nil_of_ne_nil_left, assumption } } /-- The first letter of a `neword` -/ @[simp] def head : Π {i j} (w : neword M i j), M i | i _ (singleton x hne1) := x | _ _ (append w₁ hne w₂) := w₁.head /-- The last letter of a `neword` -/ @[simp] def last : Π {i j} (w : neword M i j), M j | i _ (singleton x hne1) := x | _ _ (append w₁ hne w₂) := w₂.last @[simp] lemma to_list_head' {i j} (w : neword M i j) : w.to_list.head' = option.some ⟨i, w.head⟩ := begin rw ← option.mem_def, induction w, { rw option.mem_def, reflexivity, }, { exact list.head'_append w_ih_w₁, }, end @[simp] lemma to_list_last' {i j} (w : neword M i j) : w.to_list.last' = option.some ⟨j, w.last⟩ := begin rw ← option.mem_def, induction w, { rw option.mem_def, reflexivity, }, { exact list.last'_append w_ih_w₂, }, end /-- The `word M` represented by a `neword M i j` -/ def to_word {i j} (w : neword M i j) : word M := { to_list := w.to_list, ne_one := begin induction w, { rintros ⟨k,x⟩ ⟨rfl, rfl⟩, exact w_hne1, exfalso, apply H, }, { intros l h, simp only [to_list, list.mem_append] at h, cases h, { exact w_ih_w₁ _ h, }, { exact w_ih_w₂ _ h, }, }, end, chain_ne := begin induction w, { exact list.chain'_singleton _, }, { apply list.chain'.append w_ih_w₁ w_ih_w₂, intros x hx y hy, rw [w_w₁.to_list_last', option.mem_some_iff] at hx, rw [w_w₂.to_list_head', option.mem_some_iff] at hy, subst hx, subst hy, exact w_hne, }, end, } /-- Every nonempty `word M` can be constructed as a `neword M i j` -/ lemma of_word (w : word M) (h : w ≠ empty) : ∃ i j (w' : neword M i j), w'.to_word = w := begin rsuffices ⟨i, j, w, h⟩ : ∃ i j (w' : neword M i j), w'.to_word.to_list = w.to_list, { refine ⟨i, j, w, _⟩, ext, rw h, }, cases w with l hnot1 hchain, induction l with x l hi, { contradiction, }, { rw list.forall_mem_cons at hnot1, cases l with y l, { refine ⟨x.1, x.1, singleton x.2 hnot1.1, _ ⟩, simp [to_word], }, { rw list.chain'_cons at hchain, specialize hi hnot1.2 hchain.2 (by rintros ⟨rfl⟩), obtain ⟨i, j, w', hw' : w'.to_list = y :: l⟩ := hi, obtain rfl : y = ⟨i, w'.head⟩, by simpa [hw'] using w'.to_list_head', refine ⟨x.1, j, append (singleton x.2 hnot1.1) hchain.1 w', _⟩, { simpa [to_word] using hw', } } } end /-- A non-empty reduced word determines an element of the free product, given by multiplication. -/ def prod {i j} (w : neword M i j) := w.to_word.prod @[simp] lemma singleton_head {i} (x : M i) (hne_one : x ≠ 1) : (singleton x hne_one).head = x := rfl @[simp] lemma singleton_last {i} (x : M i) (hne_one : x ≠ 1) : (singleton x hne_one).last = x := rfl @[simp] lemma prod_singleton {i} (x : M i) (hne_one : x ≠ 1) : (singleton x hne_one).prod = of x := by simp [to_word, prod, word.prod] @[simp] lemma append_head {i j k l} {w₁ : neword M i j} {hne : j ≠ k} {w₂ : neword M k l} : (append w₁ hne w₂).head = w₁.head := rfl @[simp] lemma append_last {i j k l} {w₁ : neword M i j} {hne : j ≠ k} {w₂ : neword M k l} : (append w₁ hne w₂).last = w₂.last := rfl @[simp] lemma append_prod {i j k l} {w₁ : neword M i j} {hne : j ≠ k} {w₂ : neword M k l} : (append w₁ hne w₂).prod = w₁.prod * w₂.prod := by simp [to_word, prod, word.prod] /-- One can replace the first letter in a non-empty reduced word by an element of the same group -/ def replace_head : Π {i j : ι} (x : M i) (hnotone : x ≠ 1) (w : neword M i j), neword M i j | _ _ x h (singleton _ _) := singleton x h | _ _ x h (append w₁ hne w₂) := append (replace_head x h w₁) hne w₂ @[simp] lemma replace_head_head {i j : ι} (x : M i) (hnotone : x ≠ 1) (w : neword M i j) : (replace_head x hnotone w).head = x := by { induction w, refl, exact w_ih_w₁ _ _, } /-- One can multiply an element from the left to a non-empty reduced word if it does not cancel with the first element in the word. -/ def mul_head {i j : ι} (w : neword M i j) (x : M i) (hnotone : x * w.head ≠ 1) : neword M i j := replace_head (x * w.head) hnotone w @[simp] lemma mul_head_head {i j : ι} (w : neword M i j) (x : M i) (hnotone : x * w.head ≠ 1) : (mul_head w x hnotone).head = x * w.head := by { induction w, refl, exact w_ih_w₁ _ _, } @[simp] lemma mul_head_prod {i j : ι} (w : neword M i j) (x : M i) (hnotone : x * w.head ≠ 1) : (mul_head w x hnotone).prod = of x * w.prod := begin unfold mul_head, induction w, { simp [mul_head, replace_head], }, { specialize w_ih_w₁ _ hnotone, clear w_ih_w₂, simp [replace_head, ← mul_assoc] at *, congr' 1, } end section group variables {G : ι → Type*} [Π i, group (G i)] /-- The inverse of a non-empty reduced word -/ def inv : Π {i j} (w : neword G i j), neword G j i | _ _ (singleton x h) := singleton x⁻¹ (mt inv_eq_one.mp h) | _ _ (append w₁ h w₂) := append w₂.inv h.symm w₁.inv @[simp] lemma inv_prod {i j} (w : neword G i j) : w.inv.prod = w.prod⁻¹ := by induction w; simp [inv, *] @[simp] lemma inv_head {i j} (w : neword G i j) : w.inv.head = w.last⁻¹ := by induction w; simp [inv, *] @[simp] lemma inv_last {i j} (w : neword G i j) : w.inv.last = w.head⁻¹ := by induction w; simp [inv, *] end group end neword section ping_pong_lemma open_locale pointwise open_locale cardinal variables [hnontriv : nontrivial ι] variables {G : Type*} [group G] variables {H : ι → Type*} [∀ i, group (H i)] variables (f : Π i, H i →* G) -- We need many groups or one group with many elements variables (hcard : 3 ≤ # ι ∨ ∃ i, 3 ≤ # (H i)) -- A group action on α, and the ping-pong sets variables {α : Type*} [mul_action G α] variables (X : ι → set α) variables (hXnonempty : ∀ i, (X i).nonempty) variables (hXdisj : pairwise (λ i j, disjoint (X i) (X j))) variables (hpp : pairwise (λ i j, ∀ h : H i, h ≠ 1 → f i h • X j ⊆ X i)) include hpp lemma lift_word_ping_pong {i j k} (w : neword H i j) (hk : j ≠ k) : lift f w.prod • X k ⊆ X i := begin rename [i → i', j → j', k → m, hk → hm], induction w with i x hne_one i j k l w₁ hne w₂ hIw₁ hIw₂ generalizing m; clear i' j', { simpa using hpp hm _ hne_one, }, { calc lift f (neword.append w₁ hne w₂).prod • X m = lift f w₁.prod • lift f w₂.prod • X m : by simp [mul_action.mul_smul] ... ⊆ lift f w₁.prod • X k : set_smul_subset_set_smul_iff.mpr (hIw₂ hm) ... ⊆ X i : hIw₁ hne }, end include X hXnonempty hXdisj lemma lift_word_prod_nontrivial_of_other_i {i j k} (w : neword H i j) (hhead : k ≠ i) (hlast : k ≠ j) : lift f w.prod ≠ 1 := begin intro heq1, have : X k ⊆ X i, by simpa [heq1] using lift_word_ping_pong f X hpp w hlast.symm, obtain ⟨x, hx⟩ := hXnonempty k, exact (hXdisj hhead).le_bot ⟨hx, this hx⟩, end include hnontriv lemma lift_word_prod_nontrivial_of_head_eq_last {i} (w : neword H i i) : lift f w.prod ≠ 1 := begin obtain ⟨k, hk⟩ := exists_ne i, exact lift_word_prod_nontrivial_of_other_i f X hXnonempty hXdisj hpp w hk hk, end lemma lift_word_prod_nontrivial_of_head_card {i j} (w : neword H i j) (hcard : 3 ≤ # (H i)) (hheadtail : i ≠ j) : lift f w.prod ≠ 1 := begin obtain ⟨h, hn1, hnh⟩ := cardinal.three_le hcard 1 (w.head⁻¹), have hnot1 : h * w.head ≠ 1, by { rw ← div_inv_eq_mul, exact div_ne_one_of_ne hnh }, let w' : neword H i i := neword.append (neword.mul_head w h hnot1) hheadtail.symm (neword.singleton h⁻¹ (inv_ne_one.mpr hn1)), have hw' : lift f w'.prod ≠ 1 := lift_word_prod_nontrivial_of_head_eq_last f X hXnonempty hXdisj hpp w', intros heq1, apply hw', simp [w', heq1] end include hcard lemma lift_word_prod_nontrivial_of_not_empty {i j} (w : neword H i j) : lift f w.prod ≠ 1 := begin classical, cases hcard, { obtain ⟨i, h1, h2⟩ := cardinal.three_le hcard i j, exact lift_word_prod_nontrivial_of_other_i f X hXnonempty hXdisj hpp w h1 h2, }, { cases hcard with k hcard, by_cases hh : i = k; by_cases hl : j = k, { subst hh, subst hl, exact lift_word_prod_nontrivial_of_head_eq_last f X hXnonempty hXdisj hpp w, }, { subst hh, change j ≠ i at hl, exact lift_word_prod_nontrivial_of_head_card f X hXnonempty hXdisj hpp w hcard hl.symm, }, { subst hl, change i ≠ j at hh, have : lift f w.inv.prod ≠ 1 := lift_word_prod_nontrivial_of_head_card f X hXnonempty hXdisj hpp w.inv hcard hh.symm, intros heq, apply this, simpa using heq, }, { change i ≠ k at hh, change j ≠ k at hl, obtain ⟨h, hn1, -⟩ := cardinal.three_le hcard 1 1, let w' : neword H k k := neword.append (neword.append (neword.singleton h hn1) hh.symm w) hl (neword.singleton h⁻¹ (inv_ne_one.mpr hn1)) , have hw' : lift f w'.prod ≠ 1 := lift_word_prod_nontrivial_of_head_eq_last f X hXnonempty hXdisj hpp w', intros heq1, apply hw', simp [w', heq1], }, } end lemma empty_of_word_prod_eq_one {w : word H} (h : lift f w.prod = 1) : w = word.empty := begin by_contradiction hnotempty, obtain ⟨i, j, w, rfl⟩ := neword.of_word w hnotempty, exact lift_word_prod_nontrivial_of_not_empty f hcard X hXnonempty hXdisj hpp w h, end /-- The Ping-Pong-Lemma. Given a group action of `G` on `X` so that the `H i` acts in a specific way on disjoint subsets `X i` we can prove that `lift f` is injective, and thus the image of `lift f` is isomorphic to the free product of the `H i`. Often the Ping-Pong-Lemma is stated with regard to subgroups `H i` that generate the whole group; we generalize to arbitrary group homomorphisms `f i : H i →* G` and do not require the group to be generated by the images. Usually the Ping-Pong-Lemma requires that one group `H i` has at least three elements. This condition is only needed if `# ι = 2`, and we accept `3 ≤ # ι` as an alternative. -/ theorem lift_injective_of_ping_pong: function.injective (lift f) := begin classical, apply (injective_iff_map_eq_one (lift f)).mpr, rw (free_product.word.equiv : _ ≃ word H).forall_congr_left', { intros w Heq, dsimp [word.equiv] at *, { rw empty_of_word_prod_eq_one f hcard X hXnonempty hXdisj hpp Heq, reflexivity, }, }, end end ping_pong_lemma /-- The free product of free groups is itself a free group -/ @[simps] instance {ι : Type*} (G : ι → Type*) [∀ i, group (G i)] [hG : ∀ i, is_free_group (G i)] : is_free_group (free_product G) := { generators := Σ i, is_free_group.generators (G i), mul_equiv := monoid_hom.to_mul_equiv (free_group.lift (λ (x : Σ i, is_free_group.generators (G i)), free_product.of (is_free_group.of x.2 : G x.1))) (free_product.lift (λ (i : ι), (is_free_group.lift (λ (x : is_free_group.generators (G i)), free_group.of (⟨i, x⟩ : Σ i, is_free_group.generators (G i))) : G i →* (free_group (Σ i, is_free_group.generators (G i)))))) (by {ext, simp, }) (by {ext, simp, }) } /-- A free group is a free product of copies of the free_group over one generator. -/ -- NB: One might expect this theorem to be phrased with ℤ, but ℤ is an additive group, -- and using `multiplicative ℤ` runs into diamond issues. @[simps] def _root_.free_group_equiv_free_product {ι : Type u_1} : free_group ι ≃* free_product (λ (_ : ι), free_group unit) := begin refine monoid_hom.to_mul_equiv _ _ _ _, exact free_group.lift (λ i, @free_product.of ι _ _ i (free_group.of unit.star)), exact free_product.lift (λ i, free_group.lift (λ pstar, free_group.of i)), { ext i, refl, }, { ext i a, cases a, refl, }, end section ping_pong_lemma open_locale pointwise cardinal variables [nontrivial ι] variables {G : Type u_1} [group G] (a : ι → G) -- A group action on α, and the ping-pong sets variables {α : Type*} [mul_action G α] variables (X Y : ι → set α) variables (hXnonempty : ∀ i, (X i).nonempty) variables (hXdisj : pairwise (λ i j, disjoint (X i) (X j))) variables (hYdisj : pairwise (λ i j, disjoint (Y i) (Y j))) variables (hXYdisj : ∀ i j, disjoint (X i) (Y j)) variables (hX : ∀ i, a i • (Y i)ᶜ ⊆ X i) variables (hY : ∀ i, a⁻¹ i • (X i)ᶜ ⊆ Y i) include hXnonempty hXdisj hYdisj hXYdisj hX hY /-- The Ping-Pong-Lemma. Given a group action of `G` on `X` so that the generators of the free groups act in specific ways on disjoint subsets `X i` and `Y i` we can prove that `lift f` is injective, and thus the image of `lift f` is isomorphic to the free group. Often the Ping-Pong-Lemma is stated with regard to group elements that generate the whole group; we generalize to arbitrary group homomorphisms from the free group to `G` and do not require the group to be generated by the elements. -/ theorem _root_.free_group.injective_lift_of_ping_pong : function.injective (free_group.lift a) := begin -- Step one: express the free group lift via the free product lift have : free_group.lift a = (free_product.lift (λ i, free_group.lift (λ _, a i))).comp (((@free_group_equiv_free_product ι)).to_monoid_hom), { ext i, simp, }, rw this, clear this, refine function.injective.comp _ (mul_equiv.injective _), -- Step two: Invoke the ping-pong lemma for free products show function.injective (lift (λ (i : ι), free_group.lift (λ _, a i))), -- Prepare to instantiate lift_injective_of_ping_pong let H : ι → Type _ := λ i, free_group unit, let f : Π i, H i →* G := λ i, free_group.lift (λ _, a i), let X' : ι → set α := λ i, X i ∪ Y i, apply lift_injective_of_ping_pong f _ X', show _ ∨ ∃ i, 3 ≤ # (H i), { inhabit ι, right, use arbitrary ι, simp only [H], rw [free_group.free_group_unit_equiv_int.cardinal_eq, cardinal.mk_denumerable], apply le_of_lt, simp }, show ∀ i, (X' i).nonempty, { exact (λ i, set.nonempty.inl (hXnonempty i)), }, show pairwise (λ i j, disjoint (X' i) (X' j)), { intros i j hij, simp only [X'], apply disjoint.union_left; apply disjoint.union_right, { exact hXdisj hij, }, { exact hXYdisj i j, }, { exact (hXYdisj j i).symm, }, { exact hYdisj hij, }, }, show pairwise (λ i j, ∀ h : H i, h ≠ 1 → f i h • X' j ⊆ X' i), { rintros i j hij, -- use free_group unit ≃ ℤ refine free_group.free_group_unit_equiv_int.forall_congr_left'.mpr _, intros n hne1, change free_group.lift (λ _, a i) (free_group.of () ^ n) • X' j ⊆ X' i, simp only [map_zpow, free_group.lift.of], change a i ^ n • X' j ⊆ X' i, have hnne0 : n ≠ 0, { rintro rfl, apply hne1, simpa, }, clear hne1, simp only [X'], -- Positive and negative powers separately cases (lt_or_gt_of_ne hnne0).swap with hlt hgt, { have h1n : 1 ≤ n := hlt, calc a i ^ n • X' j ⊆ a i ^ n • (Y i)ᶜ : smul_set_mono ((hXYdisj j i).union_left $ hYdisj hij.symm).subset_compl_right ... ⊆ X i : begin refine int.le_induction _ _ _ h1n, { rw zpow_one, exact hX i, }, { intros n hle hi, calc (a i ^ (n + 1)) • (Y i)ᶜ = (a i ^ n * a i) • (Y i)ᶜ : by rw [zpow_add, zpow_one] ... = a i ^ n • (a i • (Y i)ᶜ) : mul_action.mul_smul _ _ _ ... ⊆ a i ^ n • X i : smul_set_mono $ hX i ... ⊆ a i ^ n • (Y i)ᶜ : smul_set_mono (hXYdisj i i).subset_compl_right ... ⊆ X i : hi, }, end ... ⊆ X' i : set.subset_union_left _ _, }, { have h1n : n ≤ -1, { apply int.le_of_lt_add_one, simpa using hgt, }, calc a i ^ n • X' j ⊆ a i ^ n • (X i)ᶜ : smul_set_mono ((hXdisj hij.symm).union_left (hXYdisj i j).symm).subset_compl_right ... ⊆ Y i : begin refine int.le_induction_down _ _ _ h1n, { rw [zpow_neg, zpow_one], exact hY i, }, { intros n hle hi, calc (a i ^ (n - 1)) • (X i)ᶜ = (a i ^ n * (a i)⁻¹) • (X i)ᶜ : by rw [zpow_sub, zpow_one] ... = a i ^ n • ((a i)⁻¹ • (X i)ᶜ) : mul_action.mul_smul _ _ _ ... ⊆ a i ^ n • Y i : smul_set_mono $ hY i ... ⊆ a i ^ n • (X i)ᶜ : smul_set_mono (hXYdisj i i).symm.subset_compl_right ... ⊆ Y i : hi, }, end ... ⊆ X' i : set.subset_union_right _ _, }, }, end end ping_pong_lemma end free_product
649e1adf4bd128dc53fd9693435176d4e6eded10
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/stage0/src/Lean/Util/CollectFVars.lean
ab0f438df64ea5f7aec6541dd49a0efb2fcf46bc
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
1,153
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Expr namespace Lean.CollectFVars structure State where visitedExpr : ExprSet := {} fvarSet : NameSet := {} deriving Inhabited abbrev Visitor := State → State @[inline] def visit (f : Expr → Visitor) (e : Expr) : Visitor := fun s => if !e.hasFVar || s.visitedExpr.contains e then s else f e { s with visitedExpr := s.visitedExpr.insert e } partial def main : Expr → Visitor | Expr.proj _ _ e _ => visit main e | Expr.forallE _ d b _ => visit main b ∘ visit main d | Expr.lam _ d b _ => visit main b ∘ visit main d | Expr.letE _ t v b _ => visit main b ∘ visit main v ∘ visit main t | Expr.app f a _ => visit main a ∘ visit main f | Expr.mdata _ b _ => visit main b | Expr.fvar fvarId _ => fun s => { s with fvarSet := s.fvarSet.insert fvarId } | _ => id end CollectFVars def collectFVars (s : CollectFVars.State) (e : Expr) : CollectFVars.State := CollectFVars.main e s end Lean
81c9e2bfb2806ac6dba9bfc7084ea735258e3fba
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/ring_theory/power_basis.lean
e12953217c41ec5e30271550479caea67553982b
[ "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
21,514
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 field_theory.adjoin import field_theory.minpoly import ring_theory.adjoin import ring_theory.adjoin_root import ring_theory.algebraic /-! # Power basis This file defines a structure `power_basis R S`, giving a basis of the `R`-algebra `S` as a finite list of powers `1, x, ..., x^n`. There are also constructors for `power_basis` when adjoining an algebraic element to a ring/field. ## Definitions * `power_basis R A`: a structure containing an `x` and an `n` such that `1, x, ..., x^n` is a basis for the `R`-algebra `A` (viewed as an `R`-module). * `findim (hf : f ≠ 0) : finite_dimensional.findim K (adjoin_root f) = f.nat_degree`, the dimension of `adjoin_root f` equals the degree of `f` * `power_basis.lift (pb : power_basis R S)`: if `y : S'` satisfies the same equations as `pb.gen`, this is the map `S →ₐ[R] S'` sending `pb.gen` to `y` * `power_basis.equiv`: if two power bases satisfy the same equations, they are equivalent as algebras ## Implementation notes Throughout this file, `R`, `S`, ... are `comm_ring`s, `A`, `B`, ... are `integral_domain`s and `K`, `L`, ... are `field`s. `S` is an `R`-algebra, `B` is an `A`-algebra, `L` is a `K`-algebra. ## Tags power basis, powerbasis -/ open polynomial variables {R S T : Type*} [comm_ring R] [comm_ring S] [comm_ring T] variables [algebra R S] [algebra S T] [algebra R T] [is_scalar_tower R S T] variables {A B : Type*} [integral_domain A] [integral_domain B] [algebra A B] variables {K L : Type*} [field K] [field L] [algebra K L] /-- `pb : power_basis R S` states that `1, pb.gen, ..., pb.gen ^ (pb.dim - 1)` is a basis for the `R`-algebra `S` (viewed as `R`-module). This is a structure, not a class, since the same algebra can have many power bases. For the common case where `S` is defined by adjoining an integral element to `R`, the canonical power basis is given by `{algebra,intermediate_field}.adjoin.power_basis`. -/ @[nolint has_inhabited_instance] structure power_basis (R S : Type*) [comm_ring R] [ring S] [algebra R S] := (gen : S) (dim : ℕ) (is_basis : is_basis R (λ (i : fin dim), gen ^ (i : ℕ))) namespace power_basis /-- Cannot be an instance because `power_basis` cannot be a class. -/ lemma finite_dimensional [algebra K S] (pb : power_basis K S) : finite_dimensional K S := finite_dimensional.of_fintype_basis pb.is_basis lemma findim [algebra K S] (pb : power_basis K S) : finite_dimensional.findim K S = pb.dim := by rw [finite_dimensional.findim_eq_card_basis pb.is_basis, fintype.card_fin] /-- TODO: this mixes `polynomial` and `finsupp`, we should hide this behind a new function `polynomial.of_finsupp`. -/ lemma polynomial.mem_supported_range {f : polynomial R} {d : ℕ} : (f : finsupp ℕ R) ∈ finsupp.supported R R (↑(finset.range d) : set ℕ) ↔ f.degree < d := by { simp_rw [finsupp.mem_supported', finset.mem_coe, finset.mem_range, not_lt, degree_lt_iff_coeff_zero], refl } lemma mem_span_pow' {x y : S} {d : ℕ} : y ∈ submodule.span R (set.range (λ (i : fin d), x ^ (i : ℕ))) ↔ ∃ f : polynomial R, f.degree < d ∧ y = aeval x f := begin have : set.range (λ (i : fin d), x ^ (i : ℕ)) = (λ (i : ℕ), x ^ i) '' ↑(finset.range d), { ext n, simp_rw [set.mem_range, set.mem_image, finset.mem_coe, finset.mem_range], exact ⟨λ ⟨⟨i, hi⟩, hy⟩, ⟨i, hi, hy⟩, λ ⟨i, hi, hy⟩, ⟨⟨i, hi⟩, hy⟩⟩ }, rw [this, finsupp.mem_span_iff_total], -- In the next line we use that `polynomial R := finsupp ℕ R`. -- It would be nice to have a function `polynomial.of_finsupp`. apply exists_congr, rintro (f : polynomial R), simp only [exists_prop, polynomial.mem_supported_range, eq_comm], apply and_congr iff.rfl, split; { rintro rfl; rw [finsupp.total_apply, aeval_def, eval₂_eq_sum, eq_comm], apply finset.sum_congr rfl, rintro i -, simp only [algebra.smul_def] } end lemma mem_span_pow {x y : S} {d : ℕ} (hd : d ≠ 0) : y ∈ submodule.span R (set.range (λ (i : fin d), x ^ (i : ℕ))) ↔ ∃ f : polynomial R, f.nat_degree < d ∧ y = aeval x f := begin rw mem_span_pow', split; { rintros ⟨f, h, hy⟩, refine ⟨f, _, hy⟩, by_cases hf : f = 0, { simp only [hf, nat_degree_zero, degree_zero] at h ⊢, exact lt_of_le_of_ne (nat.zero_le d) hd.symm <|> exact with_bot.bot_lt_some d }, simpa only [degree_eq_nat_degree hf, with_bot.coe_lt_coe] using h }, end lemma dim_ne_zero [nontrivial S] (pb : power_basis R S) : pb.dim ≠ 0 := λ h, one_ne_zero $ show (1 : S) = 0, by { rw [← pb.is_basis.total_repr 1, finsupp.total_apply, finsupp.sum_fintype], { refine finset.sum_eq_zero (λ x hx, _), cases x with x x_lt, rw h at x_lt, cases x_lt }, { simp } } lemma exists_eq_aeval [nontrivial S] (pb : power_basis R S) (y : S) : ∃ f : polynomial R, f.nat_degree < pb.dim ∧ y = aeval pb.gen f := (mem_span_pow pb.dim_ne_zero).mp (pb.is_basis.mem_span y) section minpoly open_locale big_operators variable [algebra A S] /-- `pb.minpoly_gen` is a minimal polynomial for `pb.gen`. If `A` is not a field, it might not necessarily be *the* minimal polynomial, however `nat_degree_minpoly` shows its degree is indeed minimal. -/ noncomputable def minpoly_gen (pb : power_basis A S) : polynomial A := X ^ pb.dim - ∑ (i : fin pb.dim), C (pb.is_basis.repr (pb.gen ^ pb.dim) i) * X ^ (i : ℕ) @[simp] lemma nat_degree_minpoly_gen (pb : power_basis A S) : nat_degree (minpoly_gen pb) = pb.dim := begin unfold minpoly_gen, apply nat_degree_eq_of_degree_eq_some, rw degree_sub_eq_left_of_degree_lt; rw degree_X_pow, apply degree_sum_fin_lt end lemma minpoly_gen_monic (pb : power_basis A S) : monic (minpoly_gen pb) := begin apply monic_sub_of_left (monic_pow (monic_X) _), rw degree_X_pow, exact degree_sum_fin_lt _ end @[simp] lemma aeval_minpoly_gen (pb : power_basis A S) : aeval pb.gen (minpoly_gen pb) = 0 := begin simp_rw [minpoly_gen, alg_hom.map_sub, alg_hom.map_sum, alg_hom.map_mul, alg_hom.map_pow, aeval_C, ← algebra.smul_def, aeval_X], refine sub_eq_zero.mpr ((pb.is_basis.total_repr (pb.gen ^ pb.dim)).symm.trans _), rw [finsupp.total_apply, finsupp.sum_fintype], intro i, rw zero_smul end lemma is_integral_gen (pb : power_basis A S) : is_integral A pb.gen := ⟨minpoly_gen pb, minpoly_gen_monic pb, aeval_minpoly_gen pb⟩ lemma dim_le_nat_degree_of_root (h : power_basis A S) {p : polynomial A} (ne_zero : p ≠ 0) (root : aeval h.gen p = 0) : h.dim ≤ p.nat_degree := begin refine le_of_not_lt (λ hlt, ne_zero _), let p_coeff : fin (h.dim) → A := λ i, p.coeff i, suffices : ∀ i, p_coeff i = 0, { ext i, by_cases hi : i < h.dim, { exact this ⟨i, hi⟩ }, exact coeff_eq_zero_of_nat_degree_lt (lt_of_lt_of_le hlt (le_of_not_gt hi)) }, intro i, refine linear_independent_iff'.mp h.is_basis.1 finset.univ _ _ i (finset.mem_univ _), rw aeval_eq_sum_range' hlt at root, rw finset.sum_fin_eq_sum_range, convert root, ext i, split_ifs with hi, { refl }, { rw [coeff_eq_zero_of_nat_degree_lt (lt_of_lt_of_le hlt (le_of_not_gt hi)), zero_smul] } end @[simp] lemma nat_degree_minpoly (pb : power_basis A S) : (minpoly A pb.gen).nat_degree = pb.dim := begin refine le_antisymm _ (dim_le_nat_degree_of_root pb (minpoly.ne_zero pb.is_integral_gen) (minpoly.aeval _ _)), rw ← nat_degree_minpoly_gen, apply nat_degree_le_of_degree_le, rw ← degree_eq_nat_degree (minpoly_gen_monic pb).ne_zero, exact minpoly.min _ _ (minpoly_gen_monic pb) (aeval_minpoly_gen pb) end end minpoly section equiv variables [algebra A S] {S' : Type*} [comm_ring S'] [algebra A S'] lemma nat_degree_lt_nat_degree {p q : polynomial R} (hp : p ≠ 0) (hpq : p.degree < q.degree) : p.nat_degree < q.nat_degree := begin by_cases hq : q = 0, { rw [hq, degree_zero] at hpq, have := not_lt_bot hpq, contradiction }, rwa [degree_eq_nat_degree hp, degree_eq_nat_degree hq, with_bot.coe_lt_coe] at hpq end lemma constr_pow_aeval (pb : power_basis A S) {y : S'} (hy : aeval y (minpoly A pb.gen) = 0) (f : polynomial A) : pb.is_basis.constr (λ i, y ^ (i : ℕ)) (aeval pb.gen f) = aeval y f := begin rw [← aeval_mod_by_monic_eq_self_of_root (minpoly.monic pb.is_integral_gen) (minpoly.aeval _ _), ← @aeval_mod_by_monic_eq_self_of_root _ _ _ _ _ f _ (minpoly.monic pb.is_integral_gen) y hy], by_cases hf : f %ₘ minpoly A pb.gen = 0, { simp only [hf, alg_hom.map_zero, linear_map.map_zero] }, have : (f %ₘ minpoly A pb.gen).nat_degree < pb.dim, { rw ← pb.nat_degree_minpoly, apply nat_degree_lt_nat_degree hf, exact degree_mod_by_monic_lt _ (minpoly.monic pb.is_integral_gen) (minpoly.ne_zero pb.is_integral_gen) }, rw [aeval_eq_sum_range' this, aeval_eq_sum_range' this, linear_map.map_sum], refine finset.sum_congr rfl (λ i (hi : i ∈ finset.range pb.dim), _), rw finset.mem_range at hi, rw linear_map.map_smul, congr, exact @constr_basis _ _ _ _ _ _ _ _ _ _ _ (⟨i, hi⟩ : fin pb.dim) pb.is_basis, end lemma constr_pow_gen (pb : power_basis A S) {y : S'} (hy : aeval y (minpoly A pb.gen) = 0) : pb.is_basis.constr (λ i, y ^ (i : ℕ)) pb.gen = y := by { convert pb.constr_pow_aeval hy X; rw aeval_X } lemma constr_pow_algebra_map (pb : power_basis A S) {y : S'} (hy : aeval y (minpoly A pb.gen) = 0) (x : A) : pb.is_basis.constr (λ i, y ^ (i : ℕ)) (algebra_map A S x) = algebra_map A S' x := by { convert pb.constr_pow_aeval hy (C x); rw aeval_C } lemma constr_pow_mul [nontrivial S] (pb : power_basis A S) {y : S'} (hy : aeval y (minpoly A pb.gen) = 0) (x x' : S) : pb.is_basis.constr (λ i, y ^ (i : ℕ)) (x * x') = pb.is_basis.constr (λ i, y ^ (i : ℕ)) x * pb.is_basis.constr (λ i, y ^ (i : ℕ)) x' := begin obtain ⟨f, hf, rfl⟩ := pb.exists_eq_aeval x, obtain ⟨g, hg, rfl⟩ := pb.exists_eq_aeval x', simp only [← aeval_mul, pb.constr_pow_aeval hy] end /-- `pb.lift y hy` is the algebra map sending `pb.gen` to `y`, where `hy` states the higher powers of `y` are the same as the higher powers of `pb.gen`. -/ noncomputable def lift [nontrivial S] (pb : power_basis A S) (y : S') (hy : aeval y (minpoly A pb.gen) = 0) : S →ₐ[A] S' := { map_one' := by { convert pb.constr_pow_algebra_map hy 1 using 2; rw ring_hom.map_one }, map_zero' := by { convert pb.constr_pow_algebra_map hy 0 using 2; rw ring_hom.map_zero }, map_mul' := pb.constr_pow_mul hy, commutes' := pb.constr_pow_algebra_map hy, .. pb.is_basis.constr (λ i, y ^ (i : ℕ)) } @[simp] lemma lift_gen [nontrivial S] (pb : power_basis A S) (y : S') (hy : aeval y (minpoly A pb.gen) = 0) : pb.lift y hy pb.gen = y := pb.constr_pow_gen hy @[simp] lemma lift_aeval [nontrivial S] (pb : power_basis A S) (y : S') (hy : aeval y (minpoly A pb.gen) = 0) (f : polynomial A) : pb.lift y hy (aeval pb.gen f) = aeval y f := pb.constr_pow_aeval hy f /-- `pb.equiv pb' h` is an equivalence of algebras with the same power basis. -/ noncomputable def equiv [nontrivial S] [nontrivial S'] (pb : power_basis A S) (pb' : power_basis A S') (h : minpoly A pb.gen = minpoly A pb'.gen) : S ≃ₐ[A] S' := alg_equiv.of_alg_hom (pb.lift pb'.gen (h.symm ▸ minpoly.aeval A pb'.gen)) (pb'.lift pb.gen (h ▸ minpoly.aeval A pb.gen)) (by { ext x, obtain ⟨f, hf, rfl⟩ := pb'.exists_eq_aeval x, simp }) (by { ext x, obtain ⟨f, hf, rfl⟩ := pb.exists_eq_aeval x, simp }) @[simp] lemma equiv_aeval [nontrivial S] [nontrivial S'] (pb : power_basis A S) (pb' : power_basis A S') (h : minpoly A pb.gen = minpoly A pb'.gen) (f : polynomial A) : pb.equiv pb' h (aeval pb.gen f) = aeval pb'.gen f := pb.lift_aeval _ (h.symm ▸ minpoly.aeval A _) _ @[simp] lemma equiv_gen [nontrivial S] [nontrivial S'] (pb : power_basis A S) (pb' : power_basis A S') (h : minpoly A pb.gen = minpoly A pb'.gen) : pb.equiv pb' h pb.gen = pb'.gen := pb.lift_gen _ (h.symm ▸ minpoly.aeval A _) local attribute [irreducible] power_basis.lift @[simp] lemma equiv_symm [nontrivial S] [nontrivial S'] (pb : power_basis A S) (pb' : power_basis A S') (h : minpoly A pb.gen = minpoly A pb'.gen) : (pb.equiv pb' h).symm = pb'.equiv pb h.symm := rfl end equiv end power_basis namespace algebra open power_basis lemma mem_span_power_basis [nontrivial R] {x y : S} (hx : _root_.is_integral R x) (hy : ∃ f : polynomial R, y = aeval x f) : y ∈ submodule.span R (set.range (λ (i : fin (minpoly R x).nat_degree), x ^ (i : ℕ))) := begin obtain ⟨f, rfl⟩ := hy, rw mem_span_pow', have := minpoly.monic hx, refine ⟨f.mod_by_monic (minpoly R x), lt_of_lt_of_le (degree_mod_by_monic_lt _ this (ne_zero_of_monic this)) degree_le_nat_degree, _⟩, conv_lhs { rw ← mod_by_monic_add_div f this }, simp only [add_zero, zero_mul, minpoly.aeval, aeval_add, alg_hom.map_mul] end lemma linear_independent_power_basis [algebra K S] {x : S} (hx : _root_.is_integral K x) : linear_independent K (λ (i : fin (minpoly K x).nat_degree), x ^ (i : ℕ)) := begin rw linear_independent_iff, intros p hp, let f : polynomial K := p.sum (λ i, monomial i), have f_def : ∀ (i : fin _), f.coeff i = p i, { intro i, -- TODO: how can we avoid unfolding here? change (p.sum (λ i pi, finsupp.single i pi) : ℕ →₀ K) i = p i, simp_rw [finsupp.sum_apply, finsupp.single_apply, finsupp.sum], rw [finset.sum_eq_single, if_pos rfl], { intros b _ hb, rw if_neg (mt (λ h, _) hb), exact fin.coe_injective h }, { intro hi, split_ifs; { exact finsupp.not_mem_support_iff.mp hi } } }, have f_def' : ∀ i, f.coeff i = if hi : i < _ then p ⟨i, hi⟩ else 0, { intro i, split_ifs with hi, { exact f_def ⟨i, hi⟩ }, -- TODO: how can we avoid unfolding here? change (p.sum (λ i pi, finsupp.single i pi) : ℕ →₀ K) i = 0, simp_rw [finsupp.sum_apply, finsupp.single_apply, finsupp.sum], apply finset.sum_eq_zero, rintro ⟨j, hj⟩ -, apply if_neg (mt _ hi), rintro rfl, exact hj }, suffices : f = 0, { ext i, rw [← f_def, this, coeff_zero, finsupp.zero_apply] }, contrapose hp with hf, intro h, have : (minpoly K x).degree ≤ f.degree, { apply minpoly.degree_le_of_ne_zero K x hf, convert h, rw [finsupp.total_apply, aeval_def, eval₂_eq_sum, finsupp.sum_sum_index], { apply finset.sum_congr rfl, rintro i -, simp only [algebra.smul_def, monomial, finsupp.lsingle_apply, zero_mul, ring_hom.map_zero, finsupp.sum_single_index] }, { intro, simp only [ring_hom.map_zero, zero_mul] }, { intros, simp only [ring_hom.map_add, add_mul] } }, have : ¬ (minpoly K x).degree ≤ f.degree, { apply not_le_of_lt, rw [degree_eq_nat_degree (minpoly.ne_zero hx), degree_lt_iff_coeff_zero], intros i hi, rw [f_def' i, dif_neg], exact not_lt_of_ge hi }, contradiction end lemma power_basis_is_basis [algebra K S] {x : S} (hx : _root_.is_integral K x) : is_basis K (λ (i : fin (minpoly K x).nat_degree), (⟨x, subset_adjoin (set.mem_singleton x)⟩ ^ (i : ℕ) : adjoin K ({x} : set S))) := begin have hST : function.injective (algebra_map (adjoin K ({x} : set S)) S) := subtype.coe_injective, have hx' : _root_.is_integral K (show adjoin K ({x} : set S), from ⟨x, subset_adjoin (set.mem_singleton x)⟩), { apply (is_integral_algebra_map_iff hST).mp, convert hx, apply_instance }, have minpoly_eq := minpoly.eq_of_algebra_map_eq hST hx' rfl, refine ⟨_, _root_.eq_top_iff.mpr _⟩, { have := linear_independent_power_basis hx', rwa minpoly_eq at this }, { rintros ⟨y, hy⟩ _, have := mem_span_power_basis hx', rw minpoly_eq at this, apply this, { rw [adjoin_singleton_eq_range] at hy, obtain ⟨f, rfl⟩ := (aeval x).mem_range.mp hy, use f, ext, exact (is_scalar_tower.algebra_map_aeval K (adjoin K {x}) S ⟨x, _⟩ _).symm } } end /-- The power basis `1, x, ..., x ^ (d - 1)` for `K[x]`, where `d` is the degree of the minimal polynomial of `x`. -/ noncomputable def adjoin.power_basis [algebra K S] {x : S} (hx : _root_.is_integral K x) : power_basis K (adjoin K ({x} : set S)) := { gen := ⟨x, subset_adjoin (set.mem_singleton x)⟩, dim := (minpoly K x).nat_degree, is_basis := power_basis_is_basis hx } end algebra namespace adjoin_root variables {f : polynomial K} lemma power_basis_is_basis (hf : f ≠ 0) : is_basis K (λ (i : fin f.nat_degree), (root f ^ i.val)) := begin set f' := f * C (f.leading_coeff⁻¹) with f'_def, have deg_f' : f'.nat_degree = f.nat_degree, { rw [nat_degree_mul hf, nat_degree_C, add_zero], { rwa [ne.def, C_eq_zero, inv_eq_zero, leading_coeff_eq_zero] } }, have f'_monic : monic f' := monic_mul_leading_coeff_inv hf, have aeval_f' : aeval (root f) f' = 0, { rw [f'_def, alg_hom.map_mul, aeval_eq, mk_self, zero_mul] }, have hx : is_integral K (root f) := ⟨f', f'_monic, aeval_f'⟩, have minpoly_eq : f' = minpoly K (root f), { apply minpoly.unique K _ f'_monic aeval_f', intros q q_monic q_aeval, have commutes : (lift (algebra_map K (adjoin_root f)) (root f) q_aeval).comp (mk q) = mk f, { ext, { simp only [ring_hom.comp_apply, mk_C, lift_of], refl }, { simp only [ring_hom.comp_apply, mk_X, lift_root] } }, rw [degree_eq_nat_degree f'_monic.ne_zero, degree_eq_nat_degree q_monic.ne_zero, with_bot.coe_le_coe, deg_f'], apply nat_degree_le_of_dvd, { rw [←ideal.mem_span_singleton, ←ideal.quotient.eq_zero_iff_mem], change mk f q = 0, rw [←commutes, ring_hom.comp_apply, mk_self, ring_hom.map_zero] }, { exact q_monic.ne_zero } }, refine ⟨_, eq_top_iff.mpr _⟩, { rw [←deg_f', minpoly_eq], exact algebra.linear_independent_power_basis hx, }, { rintros y -, rw [←deg_f', minpoly_eq], apply algebra.mem_span_power_basis hx, obtain ⟨g⟩ := y, use g, rw aeval_eq, refl } end /-- The power basis `1, root f, ..., root f ^ (d - 1)` for `adjoin_root f`, where `f` is an irreducible polynomial over a field of degree `d`. -/ noncomputable def power_basis (hf : f ≠ 0) : power_basis K (adjoin_root f) := { gen := root f, dim := f.nat_degree, is_basis := power_basis_is_basis hf } end adjoin_root namespace intermediate_field lemma power_basis_is_basis {x : L} (hx : is_integral K x) : is_basis K (λ (i : fin (minpoly K x).nat_degree), (adjoin_simple.gen K x ^ (i : ℕ))) := begin let ϕ := (adjoin_root_equiv_adjoin K hx).to_linear_equiv, have key : ϕ (adjoin_root.root (minpoly K x)) = adjoin_simple.gen K x, { exact intermediate_field.adjoin_root_equiv_adjoin_apply_root K hx }, suffices : ϕ ∘ (λ (i : fin (minpoly K x).nat_degree), adjoin_root.root (minpoly K x) ^ (i.val)) = (λ (i : fin (minpoly K x).nat_degree), (adjoin_simple.gen K x) ^ ↑i), { rw ← this, exact linear_equiv.is_basis (adjoin_root.power_basis_is_basis (minpoly.ne_zero hx)) ϕ }, ext y, rw [function.comp_app, fin.val_eq_coe, alg_equiv.to_linear_equiv_apply, alg_equiv.map_pow], rw intermediate_field.adjoin_root_equiv_adjoin_apply_root K hx, end /-- The power basis `1, x, ..., x ^ (d - 1)` for `K⟮x⟯`, where `d` is the degree of the minimal polynomial of `x`. -/ noncomputable def adjoin.power_basis {x : L} (hx : is_integral K x) : power_basis K K⟮x⟯ := { gen := adjoin_simple.gen K x, dim := (minpoly K x).nat_degree, is_basis := power_basis_is_basis hx } @[simp] lemma adjoin.power_basis.gen_eq {x : L} (hx : is_integral K x) : (adjoin.power_basis hx).gen = adjoin_simple.gen K x := rfl lemma adjoin.finite_dimensional {x : L} (hx : is_integral K x) : finite_dimensional K K⟮x⟯ := power_basis.finite_dimensional (adjoin.power_basis hx) lemma adjoin.findim {x : L} (hx : is_integral K x) : finite_dimensional.findim K K⟮x⟯ = (minpoly K x).nat_degree := begin rw power_basis.findim (adjoin.power_basis hx), refl, end end intermediate_field namespace power_basis open intermediate_field /-- `pb.equiv_adjoin_simple` is the equivalence between `K⟮pb.gen⟯` and `L` itself. -/ noncomputable def equiv_adjoin_simple (pb : power_basis K L) : K⟮pb.gen⟯ ≃ₐ[K] L := (adjoin.power_basis pb.is_integral_gen).equiv pb (minpoly.eq_of_algebra_map_eq (algebra_map K⟮pb.gen⟯ L).injective (adjoin.power_basis pb.is_integral_gen).is_integral_gen (by rw [adjoin.power_basis.gen_eq, adjoin_simple.algebra_map_gen])) @[simp] lemma equiv_adjoin_simple_aeval (pb : power_basis K L) (f : polynomial K) : pb.equiv_adjoin_simple (aeval (adjoin_simple.gen K pb.gen) f) = aeval pb.gen f := equiv_aeval _ pb _ f @[simp] lemma equiv_adjoin_simple_gen (pb : power_basis K L) : pb.equiv_adjoin_simple (adjoin_simple.gen K pb.gen) = pb.gen := equiv_gen _ pb _ @[simp] lemma equiv_adjoin_simple_symm_aeval (pb : power_basis K L) (f : polynomial K) : pb.equiv_adjoin_simple.symm (aeval pb.gen f) = aeval (adjoin_simple.gen K pb.gen) f := by rw [equiv_adjoin_simple, equiv_symm, equiv_aeval, adjoin.power_basis.gen_eq] @[simp] lemma equiv_adjoin_simple_symm_gen (pb : power_basis K L) : pb.equiv_adjoin_simple.symm pb.gen = (adjoin_simple.gen K pb.gen) := by rw [equiv_adjoin_simple, equiv_symm, equiv_gen, adjoin.power_basis.gen_eq] end power_basis
a5ecaf3be48bed26f5a470769afa3562f1e713f3
66a6486e19b71391cc438afee5f081a4257564ec
/cohomology/projective_space.hlean
14b691f4be219577376d9b768010740be39c471f
[ "Apache-2.0" ]
permissive
spiceghello/Spectral
c8ccd1e32d4b6a9132ccee20fcba44b477cd0331
20023aa3de27c22ab9f9b4a177f5a1efdec2b19f
refs/heads/master
1,611,263,374,078
1,523,349,717,000
1,523,349,717,000
92,312,239
0
0
null
1,495,642,470,000
1,495,642,470,000
null
UTF-8
Lean
false
false
5,571
hlean
/- A computation of the cohomology groups of K(ℤ,2) using the Serre spectral sequence Author: Floris van Doorn-/ import .serre open eq spectrum EM EM.ops int pointed cohomology left_module algebra group fiber is_equiv equiv prod is_trunc function namespace temp definition uH0_circle : uH^0[circle] ≃g gℤ := sorry definition uH1_circle : uH^1[circle] ≃g gℤ := sorry definition uH_circle_of_ge (n : ℤ) (h : n ≥ 2) : uH^n[circle] ≃g trivial_ab_group := sorry definition f : unit → K agℤ 2 := λx, pt definition fserre : (λn s, uoH^-(n-s)[K agℤ 2, H^-s[circle₊]]) ⟹ᵍ (λn, H^-n[unit₊]) := proof converges_to_g_isomorphism (serre_convergence_map_of_is_conn pt f (EM_spectrum agℤ) 0 (is_strunc_EM_spectrum agℤ) (is_conn_EM agℤ 2)) begin intro n s, apply unreduced_ordinary_cohomology_isomorphism_right, apply unreduced_cohomology_isomorphism, symmetry, refine !fiber_const_equiv ⬝e _, refine loop_EM _ 1 ⬝e _, exact EM_pequiv_circle end begin intro n, reflexivity end qed section local notation `X` := converges_to.X fserre local notation `E∞` := convergence_theorem.Einf (converges_to.HH fserre) local notation `E∞d` := convergence_theorem.Einfdiag (converges_to.HH fserre) local notation `E` := exact_couple.E X definition fbuilt (n : ℤ) : is_built_from (LeftModule_int_of_AbGroup (H^-n[unit₊])) (E∞d (n, 0)) := is_built_from_of_converges_to fserre n definition fEinf0 : E∞ (0, 0) ≃lm LeftModule_int_of_AbGroup agℤ := isomorphism_zero_of_is_built_from (fbuilt 0) (by reflexivity) ⬝lm lm_iso_int.mk (cohomology_change_int _ _ neg_zero ⬝g cohomology_isomorphism pbool_pequiv_add_point_unit _ _ ⬝g ordinary_cohomology_pbool _) definition fEinfd (n : ℤ) (m : ℕ) (p : n ≠ 0) : is_contr (E∞d (n, 0) m) := have p' : -n ≠ 0, from λH, p (eq_zero_of_neg_eq_zero H), is_contr_quotients (fbuilt n) (@(is_trunc_equiv_closed_rev -2 (group.equiv_of_isomorphism (cohomology_isomorphism pbool_pequiv_add_point_unit _ _))) (EM_dimension' _ _ p')) _ definition fEinf (n : ℤ) (m : ℕ) (p : n ≠ 0) : is_contr (E∞ (n, -m)) := transport (is_contr ∘ E∞) begin induction m with m q, reflexivity, refine ap (deg (exact_couple.i X)) q ⬝ _, exact prod_eq idp (neg_add m 1)⁻¹ end (fEinfd n m p) definition is_contr_fD (n s : ℤ) (p : s > 0) : is_contr (E (n, s)) := have is_contr H^-s[circle₊], from is_contr_ordinary_cohomology_of_neg _ _ (neg_neg_of_pos p), have is_contr (uoH^-(n-s)[K agℤ 2, H^-s[circle₊]]), from is_contr_unreduced_ordinary_cohomology _ _ _ _, @(is_contr_equiv_closed (left_module.equiv_of_isomorphism (converges_to.e fserre (n, s))⁻¹ˡᵐ)) this definition is_contr_fD2 (n s : ℤ) (p : n > s) : is_contr (E (n, s)) := have -(n-s) < 0, from neg_neg_of_pos (sub_pos_of_lt p), @(is_contr_equiv_closed (left_module.equiv_of_isomorphism (converges_to.e fserre (n, s))⁻¹ˡᵐ)) (is_contr_ordinary_cohomology_of_neg _ _ this) definition is_contr_fD3 (n s : ℤ) (p : s ≤ - 2) : is_contr (E (n, s)) := have -s ≥ 2, from sorry, --from neg_neg_of_pos (sub_pos_of_lt p), @(is_contr_equiv_closed (group.equiv_of_isomorphism (unreduced_ordinary_cohomology_isomorphism_right _ (uH_circle_of_ge _ this)⁻¹ᵍ _) ⬝e left_module.equiv_of_isomorphism (converges_to.e fserre (n, s))⁻¹ˡᵐ)) (is_contr_ordinary_cohomology _ _ _ !is_contr_unit) --(unreduced_ordinary_cohomology_isomorphism_right _ _ _) --(is_contr_ordinary_cohomology_of_neg _ _ this) --(is_contr_ordinary_cohomology_of_neg _ _ this) definition fE00 : E (0,0) ≃lm LeftModule_int_of_AbGroup agℤ := begin refine (Einf_isomorphism fserre 0 _ _)⁻¹ˡᵐ ⬝lm fEinf0, intro r H, apply is_contr_fD2, exact sub_nat_lt 0 (r+1), intro r H, apply is_contr_fD, change 0 + (r + 1) >[ℤ] 0, apply of_nat_lt_of_nat_of_lt, apply nat.zero_lt_succ, end definition Ex0 (n : ℕ) : AddGroup_of_AddAbGroup (E (-n,0)) ≃g uH^n[K agℤ 2] := begin refine group_isomorphism_of_lm_isomorphism_int (converges_to.e fserre (-n,0)) ⬝g _, refine cohomology_change_int _ _ (ap neg !sub_zero ⬝ !neg_neg) ⬝g unreduced_ordinary_cohomology_isomorphism_right _ uH0_circle _, end definition Ex1 (n : ℕ) : AddGroup_of_AddAbGroup (E (-(n+1),- 1)) ≃g uH^n[K agℤ 2] := begin refine group_isomorphism_of_lm_isomorphism_int (converges_to.e fserre (-(n+1),- 1)) ⬝g _, refine cohomology_change_int _ _ (ap neg _ ⬝ !neg_neg) ⬝g unreduced_ordinary_cohomology_isomorphism_right _ !uH1_circle _, exact ap (λx, x - - 1) !neg_add ⬝ !add_sub_cancel end definition uH0 : uH^0[K agℤ 2] ≃g gℤ := (Ex0 0)⁻¹ᵍ ⬝g group_isomorphism_of_lm_isomorphism_int fE00 definition fE10 : is_contr (E (- 1,0)) := begin refine @(is_trunc_equiv_closed _ _) (fEinf (- 1) 0 dec_star), apply equiv_of_isomorphism, refine Einf_isomorphism fserre 0 _ _, intro r H, exact sorry, exact sorry --apply is_contr_fD2, change (- 1) - (- 1) >[ℤ] (- 0) - (r + 1), -- apply is_contr_fD, change (-0) - (r + 1) >[ℤ] 0, --exact sub_nat_lt 0 r, -- intro r H, apply is_contr_fD, change 0 + (r + 1) >[ℤ] 0, -- apply of_nat_lt_of_nat_of_lt, -- apply nat.zero_lt_succ, end definition uH1 : is_contr (uH^1[K agℤ 2]) := begin refine @(is_trunc_equiv_closed -2 (group.equiv_of_isomorphism !Ex0)) fE10, end end end temp
348afe4ce51e84a74cea5ff24d236fdf0c81602f
10834b3de906c60d1989336d7506a00ee5e52c08
/library/init/data/nat/lemmas.lean
08b2bf4b885049c455fe870b8fd43ab356d26f59
[ "Apache-2.0" ]
permissive
Jack-Pumpkinhead/lean
16657b5ad7f5316f007842fa2426b7f91212eae8
81cabd7b5a8f789633639f5fba64b45d31e37259
refs/heads/master
1,621,358,983,310
1,585,070,616,000
1,585,070,616,000
251,335,905
0
0
Apache-2.0
1,585,579,683,000
1,585,579,682,000
null
UTF-8
Lean
false
false
49,640
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, Jeremy Avigad -/ prelude import init.data.nat.basic init.data.nat.div init.meta init.algebra.functions universes u namespace nat attribute [pre_smt] nat_zero_eq_zero protected lemma add_comm : ∀ n m : ℕ, n + m = m + n | n 0 := eq.symm (nat.zero_add n) | n (m+1) := suffices succ (n + m) = succ (m + n), from eq.symm (succ_add m n) ▸ this, congr_arg succ (add_comm n m) protected lemma add_assoc : ∀ n m k : ℕ, (n + m) + k = n + (m + k) | n m 0 := rfl | n m (succ k) := by rw [add_succ, add_succ, add_assoc] protected lemma add_left_comm : ∀ (n m k : ℕ), n + (m + k) = m + (n + k) := left_comm nat.add nat.add_comm nat.add_assoc protected lemma add_left_cancel : ∀ {n m k : ℕ}, n + m = n + k → m = k | 0 m k := by simp [nat.zero_add] {contextual := tt} | (succ n) m k := λ h, have n+m = n+k, by { simp [succ_add] at h, assumption }, add_left_cancel this protected lemma add_right_cancel {n m k : ℕ} (h : n + m = k + m) : n = k := have m + n = m + k, by rwa [nat.add_comm n m, nat.add_comm k m] at h, nat.add_left_cancel this lemma succ_ne_zero (n : ℕ) : succ n ≠ 0 := assume h, nat.no_confusion h lemma succ_ne_self : ∀ n : ℕ, succ n ≠ n | 0 h := absurd h (nat.succ_ne_zero 0) | (n+1) h := succ_ne_self n (nat.no_confusion h (λ h, h)) protected lemma one_ne_zero : 1 ≠ (0 : ℕ) := assume h, nat.no_confusion h protected lemma zero_ne_one : 0 ≠ (1 : ℕ) := assume h, nat.no_confusion h instance : zero_ne_one_class ℕ := { zero := 0, one := 1, zero_ne_one := nat.zero_ne_one } lemma eq_zero_of_add_eq_zero_right : ∀ {n m : ℕ}, n + m = 0 → n = 0 | 0 m := by simp [nat.zero_add] | (n+1) m := λ h, begin exfalso, rw [add_one, succ_add] at h, apply succ_ne_zero _ h end lemma eq_zero_of_add_eq_zero_left {n m : ℕ} (h : n + m = 0) : m = 0 := @eq_zero_of_add_eq_zero_right m n (nat.add_comm n m ▸ h) @[simp] lemma pred_zero : pred 0 = 0 := rfl @[simp] lemma pred_succ (n : ℕ) : pred (succ n) = n := rfl protected lemma mul_zero (n : ℕ) : n * 0 = 0 := rfl lemma mul_succ (n m : ℕ) : n * succ m = n * m + n := rfl protected theorem zero_mul : ∀ (n : ℕ), 0 * n = 0 | 0 := rfl | (succ n) := by rw [mul_succ, zero_mul] private meta def sort_add := `[simp [nat.add_assoc, nat.add_comm, nat.add_left_comm]] lemma succ_mul : ∀ (n m : ℕ), (succ n) * m = (n * m) + m | n 0 := rfl | n (succ m) := begin simp [mul_succ, add_succ, succ_mul n m], sort_add end protected lemma right_distrib : ∀ (n m k : ℕ), (n + m) * k = n * k + m * k | n m 0 := rfl | n m (succ k) := begin simp [mul_succ, right_distrib n m k], sort_add end protected lemma left_distrib : ∀ (n m k : ℕ), n * (m + k) = n * m + n * k | 0 m k := by simp [nat.zero_mul] | (succ n) m k := begin simp [succ_mul, left_distrib n m k], sort_add end protected lemma mul_comm : ∀ (n m : ℕ), n * m = m * n | n 0 := by rw [nat.zero_mul, nat.mul_zero] | n (succ m) := by simp [mul_succ, succ_mul, mul_comm n m] protected lemma mul_assoc : ∀ (n m k : ℕ), (n * m) * k = n * (m * k) | n m 0 := rfl | n m (succ k) := by simp [mul_succ, nat.left_distrib, mul_assoc n m k] protected lemma mul_one : ∀ (n : ℕ), n * 1 = n := nat.zero_add protected lemma one_mul (n : ℕ) : 1 * n = n := by rw [nat.mul_comm, nat.mul_one] instance : comm_semiring nat := {add := nat.add, add_assoc := nat.add_assoc, zero := nat.zero, zero_add := nat.zero_add, add_zero := nat.add_zero, add_comm := nat.add_comm, mul := nat.mul, mul_assoc := nat.mul_assoc, one := nat.succ nat.zero, one_mul := nat.one_mul, mul_one := nat.mul_one, left_distrib := nat.left_distrib, right_distrib := nat.right_distrib, zero_mul := nat.zero_mul, mul_zero := nat.mul_zero, mul_comm := nat.mul_comm} /- properties of inequality -/ protected lemma le_of_eq {n m : ℕ} (p : n = m) : n ≤ m := p ▸ less_than_or_equal.refl n lemma le_succ_of_le {n m : ℕ} (h : n ≤ m) : n ≤ succ m := nat.le_trans h (le_succ m) lemma le_of_succ_le {n m : ℕ} (h : succ n ≤ m) : n ≤ m := nat.le_trans (le_succ n) h protected lemma le_of_lt {n m : ℕ} (h : n < m) : n ≤ m := le_of_succ_le h def lt.step {n m : ℕ} : n < m → n < succ m := less_than_or_equal.step lemma eq_zero_or_pos (n : ℕ) : n = 0 ∨ n > 0 := by {cases n, exact or.inl rfl, exact or.inr (succ_pos _)} protected lemma pos_of_ne_zero {n : nat} : n ≠ 0 → n > 0 := or.resolve_left (eq_zero_or_pos n) protected lemma lt_trans {n m k : ℕ} (h₁ : n < m) : m < k → n < k := nat.le_trans (less_than_or_equal.step h₁) protected lemma lt_of_le_of_lt {n m k : ℕ} (h₁ : n ≤ m) : m < k → n < k := nat.le_trans (succ_le_succ h₁) def lt.base (n : ℕ) : n < succ n := nat.le_refl (succ n) lemma lt_succ_self (n : ℕ) : n < succ n := lt.base n protected lemma le_antisymm {n m : ℕ} (h₁ : n ≤ m) : m ≤ n → n = m := less_than_or_equal.cases_on h₁ (λ a, rfl) (λ a b c, absurd (nat.lt_of_le_of_lt b c) (nat.lt_irrefl n)) protected lemma lt_or_ge : ∀ (a b : ℕ), a < b ∨ a ≥ b | a 0 := or.inr (zero_le a) | a (b+1) := match lt_or_ge a b with | or.inl h := or.inl (le_succ_of_le h) | or.inr h := match nat.eq_or_lt_of_le h with | or.inl h1 := or.inl (h1 ▸ lt_succ_self b) | or.inr h1 := or.inr h1 end end protected lemma le_total {m n : ℕ} : m ≤ n ∨ n ≤ m := or.imp_left nat.le_of_lt (nat.lt_or_ge m n) protected lemma lt_of_le_and_ne {m n : ℕ} (h1 : m ≤ n) : m ≠ n → m < n := or.resolve_right (or.swap (nat.eq_or_lt_of_le h1)) protected lemma lt_iff_le_not_le {m n : ℕ} : m < n ↔ (m ≤ n ∧ ¬ n ≤ m) := ⟨λ hmn, ⟨nat.le_of_lt hmn, λ hnm, nat.lt_irrefl _ (nat.lt_of_le_of_lt hnm hmn)⟩, λ ⟨hmn, hnm⟩, nat.lt_of_le_and_ne hmn (λ heq, hnm (heq ▸ nat.le_refl _))⟩ instance : linear_order ℕ := { le := nat.less_than_or_equal, le_refl := @nat.le_refl, le_trans := @nat.le_trans, le_antisymm := @nat.le_antisymm, le_total := @nat.le_total, lt := nat.lt, lt_iff_le_not_le := @nat.lt_iff_le_not_le } lemma eq_zero_of_le_zero {n : nat} (h : n ≤ 0) : n = 0 := le_antisymm h (zero_le _) lemma succ_lt_succ {a b : ℕ} : a < b → succ a < succ b := succ_le_succ lemma lt_of_succ_lt {a b : ℕ} : succ a < b → a < b := le_of_succ_le lemma lt_of_succ_lt_succ {a b : ℕ} : succ a < succ b → a < b := le_of_succ_le_succ lemma pred_lt_pred : ∀ {n m : ℕ}, n ≠ 0 → n < m → pred n < pred m | 0 _ h₁ h := absurd rfl h₁ | _ 0 h₁ h := absurd h (not_lt_zero _) | (succ n) (succ m) _ h := lt_of_succ_lt_succ h lemma lt_of_succ_le {a b : ℕ} (h : succ a ≤ b) : a < b := h lemma succ_le_of_lt {a b : ℕ} (h : a < b) : succ a ≤ b := h lemma le_add_right : ∀ (n k : ℕ), n ≤ n + k | n 0 := nat.le_refl n | n (k+1) := le_succ_of_le (le_add_right n k) lemma le_add_left (n m : ℕ): n ≤ m + n := nat.add_comm n m ▸ le_add_right n m lemma le.dest : ∀ {n m : ℕ}, n ≤ m → ∃ k, n + k = m | n ._ (less_than_or_equal.refl ._) := ⟨0, rfl⟩ | n ._ (@less_than_or_equal.step ._ m h) := match le.dest h with | ⟨w, hw⟩ := ⟨succ w, hw ▸ add_succ n w⟩ end lemma le.intro {n m k : ℕ} (h : n + k = m) : n ≤ m := h ▸ le_add_right n k protected lemma add_le_add_left {n m : ℕ} (h : n ≤ m) (k : ℕ) : k + n ≤ k + m := match le.dest h with | ⟨w, hw⟩ := @le.intro _ _ w begin rw [nat.add_assoc, hw] end end protected lemma add_le_add_right {n m : ℕ} (h : n ≤ m) (k : ℕ) : n + k ≤ m + k := begin rw [nat.add_comm n k, nat.add_comm m k], apply nat.add_le_add_left h end protected lemma le_of_add_le_add_left {k n m : ℕ} (h : k + n ≤ k + m) : n ≤ m := match le.dest h with | ⟨w, hw⟩ := @le.intro _ _ w begin rw [nat.add_assoc] at hw, apply nat.add_left_cancel hw end end protected lemma le_of_add_le_add_right {k n m : ℕ} : n + k ≤ m + k → n ≤ m := begin rw [nat.add_comm _ k, nat.add_comm _ k], apply nat.le_of_add_le_add_left end protected lemma add_le_add_iff_le_right (k n m : ℕ) : n + k ≤ m + k ↔ n ≤ m := ⟨ nat.le_of_add_le_add_right , assume h, nat.add_le_add_right h _ ⟩ protected theorem lt_of_add_lt_add_left {k n m : ℕ} (h : k + n < k + m) : n < m := let h' := nat.le_of_lt h in nat.lt_of_le_and_ne (nat.le_of_add_le_add_left h') (λ heq, nat.lt_irrefl (k + m) begin rw heq at h, assumption end) protected lemma add_lt_add_left {n m : ℕ} (h : n < m) (k : ℕ) : k + n < k + m := lt_of_succ_le (add_succ k n ▸ nat.add_le_add_left (succ_le_of_lt h) k) protected lemma add_lt_add_right {n m : ℕ} (h : n < m) (k : ℕ) : n + k < m + k := nat.add_comm k m ▸ nat.add_comm k n ▸ nat.add_lt_add_left h k protected lemma lt_add_of_pos_right {n k : ℕ} (h : k > 0) : n < n + k := nat.add_lt_add_left h n protected lemma lt_add_of_pos_left {n k : ℕ} (h : k > 0) : n < k + n := by rw add_comm; exact nat.lt_add_of_pos_right h protected lemma zero_lt_one : 0 < (1:nat) := zero_lt_succ 0 lemma mul_le_mul_left {n m : ℕ} (k : ℕ) (h : n ≤ m) : k * n ≤ k * m := match le.dest h with | ⟨l, hl⟩ := have k * n + k * l = k * m, by rw [← left_distrib, hl], le.intro this end lemma mul_le_mul_right {n m : ℕ} (k : ℕ) (h : n ≤ m) : n * k ≤ m * k := mul_comm k m ▸ mul_comm k n ▸ mul_le_mul_left k h protected lemma mul_lt_mul_of_pos_left {n m k : ℕ} (h : n < m) (hk : k > 0) : k * n < k * m := nat.lt_of_lt_of_le (nat.lt_add_of_pos_right hk) (mul_succ k n ▸ nat.mul_le_mul_left k (succ_le_of_lt h)) protected lemma mul_lt_mul_of_pos_right {n m k : ℕ} (h : n < m) (hk : k > 0) : n * k < m * k := mul_comm k m ▸ mul_comm k n ▸ nat.mul_lt_mul_of_pos_left h hk instance : decidable_linear_ordered_semiring nat := { add_left_cancel := @nat.add_left_cancel, add_right_cancel := @nat.add_right_cancel, lt := nat.lt, le := nat.le, le_refl := nat.le_refl, le_trans := @nat.le_trans, le_antisymm := @nat.le_antisymm, le_total := @nat.le_total, lt_iff_le_not_le := @lt_iff_le_not_le _ _, add_le_add_left := @nat.add_le_add_left, le_of_add_le_add_left := @nat.le_of_add_le_add_left, zero_lt_one := zero_lt_succ 0, mul_le_mul_of_nonneg_left := assume a b c h₁ h₂, nat.mul_le_mul_left c h₁, mul_le_mul_of_nonneg_right := assume a b c h₁ h₂, nat.mul_le_mul_right c h₁, mul_lt_mul_of_pos_left := @nat.mul_lt_mul_of_pos_left, mul_lt_mul_of_pos_right := @nat.mul_lt_mul_of_pos_right, decidable_lt := nat.decidable_lt, decidable_le := nat.decidable_le, decidable_eq := nat.decidable_eq, ..nat.comm_semiring } -- all the fields are already included in the decidable_linear_ordered_semiring instance instance : decidable_linear_ordered_cancel_comm_monoid ℕ := { add_left_cancel := @nat.add_left_cancel, ..nat.decidable_linear_ordered_semiring } lemma le_of_lt_succ {m n : nat} : m < succ n → m ≤ n := le_of_succ_le_succ theorem eq_of_mul_eq_mul_left {m k n : ℕ} (Hn : n > 0) (H : n * m = n * k) : m = k := le_antisymm (le_of_mul_le_mul_left (le_of_eq H) Hn) (le_of_mul_le_mul_left (le_of_eq H.symm) Hn) theorem eq_of_mul_eq_mul_right {n m k : ℕ} (Hm : m > 0) (H : n * m = k * m) : n = k := by rw [mul_comm n m, mul_comm k m] at H; exact eq_of_mul_eq_mul_left Hm H /- sub properties -/ @[simp] protected lemma zero_sub : ∀ a : ℕ, 0 - a = 0 | 0 := rfl | (a+1) := congr_arg pred (zero_sub a) lemma sub_lt_succ (a b : ℕ) : a - b < succ a := lt_succ_of_le (sub_le a b) protected theorem sub_le_sub_right {n m : ℕ} (h : n ≤ m) : ∀ k, n - k ≤ m - k | 0 := h | (succ z) := pred_le_pred (sub_le_sub_right z) /- bit0/bit1 properties -/ protected lemma bit1_eq_succ_bit0 (n : ℕ) : bit1 n = succ (bit0 n) := rfl protected lemma bit1_succ_eq (n : ℕ) : bit1 (succ n) = succ (succ (bit1 n)) := eq.trans (nat.bit1_eq_succ_bit0 (succ n)) (congr_arg succ (nat.bit0_succ_eq n)) protected lemma bit1_ne_one : ∀ {n : ℕ}, n ≠ 0 → bit1 n ≠ 1 | 0 h h1 := absurd rfl h | (n+1) h h1 := nat.no_confusion h1 (λ h2, absurd h2 (succ_ne_zero _)) protected lemma bit0_ne_one : ∀ n : ℕ, bit0 n ≠ 1 | 0 h := absurd h (ne.symm nat.one_ne_zero) | (n+1) h := have h1 : succ (succ (n + n)) = 1, from succ_add n n ▸ h, nat.no_confusion h1 (λ h2, absurd h2 (succ_ne_zero (n + n))) protected lemma add_self_ne_one : ∀ (n : ℕ), n + n ≠ 1 | 0 h := nat.no_confusion h | (n+1) h := have h1 : succ (succ (n + n)) = 1, from succ_add n n ▸ h, nat.no_confusion h1 (λ h2, absurd h2 (nat.succ_ne_zero (n + n))) protected lemma bit1_ne_bit0 : ∀ (n m : ℕ), bit1 n ≠ bit0 m | 0 m h := absurd h (ne.symm (nat.add_self_ne_one m)) | (n+1) 0 h := have h1 : succ (bit0 (succ n)) = 0, from h, absurd h1 (nat.succ_ne_zero _) | (n+1) (m+1) h := have h1 : succ (succ (bit1 n)) = succ (succ (bit0 m)), from nat.bit0_succ_eq m ▸ nat.bit1_succ_eq n ▸ h, have h2 : bit1 n = bit0 m, from nat.no_confusion h1 (λ h2', nat.no_confusion h2' (λ h2'', h2'')), absurd h2 (bit1_ne_bit0 n m) protected lemma bit0_ne_bit1 : ∀ (n m : ℕ), bit0 n ≠ bit1 m := λ n m : nat, ne.symm (nat.bit1_ne_bit0 m n) protected lemma bit0_inj : ∀ {n m : ℕ}, bit0 n = bit0 m → n = m | 0 0 h := rfl | 0 (m+1) h := by contradiction | (n+1) 0 h := by contradiction | (n+1) (m+1) h := have succ (succ (n + n)) = succ (succ (m + m)), begin unfold bit0 at h, simp [add_one, add_succ, succ_add] at h, rw h end, have n + n = m + m, by iterate { injection this with this }, have n = m, from bit0_inj this, by rw this protected lemma bit1_inj : ∀ {n m : ℕ}, bit1 n = bit1 m → n = m := λ n m h, have succ (bit0 n) = succ (bit0 m), begin simp [nat.bit1_eq_succ_bit0] at h, rw h end, have bit0 n = bit0 m, by injection this, nat.bit0_inj this protected lemma bit0_ne {n m : ℕ} : n ≠ m → bit0 n ≠ bit0 m := λ h₁ h₂, absurd (nat.bit0_inj h₂) h₁ protected lemma bit1_ne {n m : ℕ} : n ≠ m → bit1 n ≠ bit1 m := λ h₁ h₂, absurd (nat.bit1_inj h₂) h₁ protected lemma zero_ne_bit0 {n : ℕ} : n ≠ 0 → 0 ≠ bit0 n := λ h, ne.symm (nat.bit0_ne_zero h) protected lemma zero_ne_bit1 (n : ℕ) : 0 ≠ bit1 n := ne.symm (nat.bit1_ne_zero n) protected lemma one_ne_bit0 (n : ℕ) : 1 ≠ bit0 n := ne.symm (nat.bit0_ne_one n) protected lemma one_ne_bit1 {n : ℕ} : n ≠ 0 → 1 ≠ bit1 n := λ h, ne.symm (nat.bit1_ne_one h) protected lemma one_lt_bit1 : ∀ {n : nat}, n ≠ 0 → 1 < bit1 n | 0 h := by contradiction | (succ n) h := begin rw nat.bit1_succ_eq, apply succ_lt_succ, apply zero_lt_succ end protected lemma one_lt_bit0 : ∀ {n : nat}, n ≠ 0 → 1 < bit0 n | 0 h := by contradiction | (succ n) h := begin rw nat.bit0_succ_eq, apply succ_lt_succ, apply zero_lt_succ end protected lemma bit0_lt {n m : nat} (h : n < m) : bit0 n < bit0 m := add_lt_add h h protected lemma bit1_lt {n m : nat} (h : n < m) : bit1 n < bit1 m := succ_lt_succ (add_lt_add h h) protected lemma bit0_lt_bit1 {n m : nat} (h : n ≤ m) : bit0 n < bit1 m := lt_succ_of_le (add_le_add h h) protected lemma bit1_lt_bit0 : ∀ {n m : nat}, n < m → bit1 n < bit0 m | n 0 h := absurd h (not_lt_zero _) | n (succ m) h := have n ≤ m, from le_of_lt_succ h, have succ (n + n) ≤ succ (m + m), from succ_le_succ (add_le_add this this), have succ (n + n) ≤ succ m + m, {rw succ_add, assumption}, show succ (n + n) < succ (succ m + m), from lt_succ_of_le this protected lemma one_le_bit1 (n : ℕ) : 1 ≤ bit1 n := show 1 ≤ succ (bit0 n), from succ_le_succ (zero_le (bit0 n)) protected lemma one_le_bit0 : ∀ (n : ℕ), n ≠ 0 → 1 ≤ bit0 n | 0 h := absurd rfl h | (n+1) h := suffices 1 ≤ succ (succ (bit0 n)), from eq.symm (nat.bit0_succ_eq n) ▸ this, succ_le_succ (zero_le (succ (bit0 n))) /- Extra instances to short-circuit type class resolution -/ instance : add_comm_monoid nat := by apply_instance instance : add_monoid nat := by apply_instance instance : monoid nat := by apply_instance instance : comm_monoid nat := by apply_instance instance : comm_semigroup nat := by apply_instance instance : semigroup nat := by apply_instance instance : add_comm_semigroup nat := by apply_instance instance : add_semigroup nat := by apply_instance instance : distrib nat := by apply_instance instance : semiring nat := by apply_instance instance : ordered_semiring nat := by apply_instance /- subtraction -/ @[simp] protected theorem sub_zero (n : ℕ) : n - 0 = n := rfl theorem sub_succ (n m : ℕ) : n - succ m = pred (n - m) := rfl theorem succ_sub_succ (n m : ℕ) : succ n - succ m = n - m := succ_sub_succ_eq_sub n m protected theorem sub_self : ∀ (n : ℕ), n - n = 0 | 0 := by rw nat.sub_zero | (succ n) := by rw [succ_sub_succ, sub_self n] /- TODO(Leo): remove the following ematch annotations as soon as we have arithmetic theory in the smt_stactic -/ @[ematch_lhs] protected theorem add_sub_add_right : ∀ (n k m : ℕ), (n + k) - (m + k) = n - m | n 0 m := by rw [add_zero, add_zero] | n (succ k) m := by rw [add_succ, add_succ, succ_sub_succ, add_sub_add_right n k m] @[ematch_lhs] protected theorem add_sub_add_left (k n m : ℕ) : (k + n) - (k + m) = n - m := by rw [add_comm k n, add_comm k m, nat.add_sub_add_right] @[ematch_lhs] protected theorem add_sub_cancel (n m : ℕ) : n + m - m = n := suffices n + m - (0 + m) = n, from by rwa [zero_add] at this, by rw [nat.add_sub_add_right, nat.sub_zero] @[ematch_lhs] protected theorem add_sub_cancel_left (n m : ℕ) : n + m - n = m := show n + m - (n + 0) = m, from by rw [nat.add_sub_add_left, nat.sub_zero] protected theorem sub_sub : ∀ (n m k : ℕ), n - m - k = n - (m + k) | n m 0 := by rw [add_zero, nat.sub_zero] | n m (succ k) := by rw [add_succ, nat.sub_succ, nat.sub_succ, sub_sub n m k] theorem le_of_le_of_sub_le_sub_right {n m k : ℕ} (h₀ : k ≤ m) (h₁ : n - k ≤ m - k) : n ≤ m := begin revert k m, induction n with n ; intros k m h₀ h₁, { apply zero_le }, { cases k with k, { apply h₁ }, cases m with m, { cases not_succ_le_zero _ h₀ }, { simp [succ_sub_succ] at h₁, apply succ_le_succ, apply n_ih _ h₁, apply le_of_succ_le_succ h₀ }, } end protected theorem sub_le_sub_right_iff (n m k : ℕ) (h : k ≤ m) : n - k ≤ m - k ↔ n ≤ m := ⟨ le_of_le_of_sub_le_sub_right h , assume h, nat.sub_le_sub_right h k ⟩ theorem sub_self_add (n m : ℕ) : n - (n + m) = 0 := show (n + 0) - (n + m) = 0, from by rw [nat.add_sub_add_left, nat.zero_sub] theorem add_le_to_le_sub (x : ℕ) {y k : ℕ} (h : k ≤ y) : x + k ≤ y ↔ x ≤ y - k := by rw [← nat.add_sub_cancel x k, nat.sub_le_sub_right_iff _ _ _ h, nat.add_sub_cancel] lemma sub_lt_of_pos_le (a b : ℕ) (h₀ : 0 < a) (h₁ : a ≤ b) : b - a < b := begin apply sub_lt _ h₀, apply lt_of_lt_of_le h₀ h₁ end theorem sub_one (n : ℕ) : n - 1 = pred n := rfl theorem succ_sub_one (n : ℕ) : succ n - 1 = n := rfl theorem succ_pred_eq_of_pos : ∀ {n : ℕ}, n > 0 → succ (pred n) = n | 0 h := absurd h (lt_irrefl 0) | (succ k) h := rfl theorem sub_eq_zero_of_le {n m : ℕ} (h : n ≤ m) : n - m = 0 := exists.elim (nat.le.dest h) (assume k, assume hk : n + k = m, by rw [← hk, sub_self_add]) protected theorem le_of_sub_eq_zero : ∀{n m : ℕ}, n - m = 0 → n ≤ m | n 0 H := begin rw [nat.sub_zero] at H, simp [H] end | 0 (m+1) H := zero_le _ | (n+1) (m+1) H := add_le_add_right (le_of_sub_eq_zero begin simp [nat.add_sub_add_right] at H, exact H end) _ protected theorem sub_eq_zero_iff_le {n m : ℕ} : n - m = 0 ↔ n ≤ m := ⟨nat.le_of_sub_eq_zero, nat.sub_eq_zero_of_le⟩ theorem add_sub_of_le {n m : ℕ} (h : n ≤ m) : n + (m - n) = m := exists.elim (nat.le.dest h) (assume k, assume hk : n + k = m, by rw [← hk, nat.add_sub_cancel_left]) protected theorem sub_add_cancel {n m : ℕ} (h : n ≥ m) : n - m + m = n := by rw [add_comm, add_sub_of_le h] protected theorem add_sub_assoc {m k : ℕ} (h : k ≤ m) (n : ℕ) : n + m - k = n + (m - k) := exists.elim (nat.le.dest h) (assume l, assume hl : k + l = m, by rw [← hl, nat.add_sub_cancel_left, add_comm k, ← add_assoc, nat.add_sub_cancel]) protected lemma sub_eq_iff_eq_add {a b c : ℕ} (ab : b ≤ a) : a - b = c ↔ a = c + b := ⟨assume c_eq, begin rw [c_eq.symm, nat.sub_add_cancel ab] end, assume a_eq, begin rw [a_eq, nat.add_sub_cancel] end⟩ protected lemma lt_of_sub_eq_succ {m n l : ℕ} (H : m - n = nat.succ l) : n < m := lt_of_not_ge (assume (H' : n ≥ m), begin simp [nat.sub_eq_zero_of_le H'] at H, contradiction end) @[simp] lemma zero_min (a : ℕ) : min 0 a = 0 := min_eq_left (zero_le a) @[simp] lemma min_zero (a : ℕ) : min a 0 = 0 := min_eq_right (zero_le a) -- Distribute succ over min theorem min_succ_succ (x y : ℕ) : min (succ x) (succ y) = succ (min x y) := have f : x ≤ y → min (succ x) (succ y) = succ (min x y), from λp, calc min (succ x) (succ y) = succ x : if_pos (succ_le_succ p) ... = succ (min x y) : congr_arg succ (eq.symm (if_pos p)), have g : ¬ (x ≤ y) → min (succ x) (succ y) = succ (min x y), from λp, calc min (succ x) (succ y) = succ y : if_neg (λeq, p (pred_le_pred eq)) ... = succ (min x y) : congr_arg succ (eq.symm (if_neg p)), decidable.by_cases f g theorem sub_eq_sub_min (n m : ℕ) : n - m = n - min n m := if h : n ≥ m then by rewrite [min_eq_right h] else by rewrite [sub_eq_zero_of_le (le_of_not_ge h), min_eq_left (le_of_not_ge h), nat.sub_self] @[simp] theorem sub_add_min_cancel (n m : ℕ) : n - m + min n m = n := by rw [sub_eq_sub_min, nat.sub_add_cancel (min_le_left n m)] /- TODO(Leo): sub + inequalities -/ protected def strong_rec_on {p : nat → Sort u} (n : nat) (h : ∀ n, (∀ m, m < n → p m) → p n) : p n := suffices ∀ n m, m < n → p m, from this (succ n) n (lt_succ_self _), begin intros n, induction n with n ih, {intros m h₁, exact absurd h₁ (not_lt_zero _)}, {intros m h₁, apply or.by_cases (lt_or_eq_of_le (le_of_lt_succ h₁)), {intros, apply ih, assumption}, {intros, subst m, apply h _ ih}} end protected lemma strong_induction_on {p : nat → Prop} (n : nat) (h : ∀ n, (∀ m, m < n → p m) → p n) : p n := nat.strong_rec_on n h protected lemma case_strong_induction_on {p : nat → Prop} (a : nat) (hz : p 0) (hi : ∀ n, (∀ m, m ≤ n → p m) → p (succ n)) : p a := nat.strong_induction_on a $ λ n, match n with | 0 := λ _, hz | (n+1) := λ h₁, hi n (λ m h₂, h₁ _ (lt_succ_of_le h₂)) end /- mod -/ lemma mod_def (x y : nat) : x % y = if 0 < y ∧ y ≤ x then (x - y) % y else x := by have h := mod_def_aux x y; rwa [dif_eq_if] at h @[simp] lemma mod_zero (a : nat) : a % 0 = a := begin rw mod_def, have h : ¬ (0 < 0 ∧ 0 ≤ a), simp [lt_irrefl], simp [if_neg, h] end lemma mod_eq_of_lt {a b : nat} (h : a < b) : a % b = a := begin rw mod_def, have h' : ¬(0 < b ∧ b ≤ a), simp [not_le_of_gt h], simp [if_neg, h'] end @[simp] lemma zero_mod (b : nat) : 0 % b = 0 := begin rw mod_def, have h : ¬(0 < b ∧ b ≤ 0), {intro hn, cases hn with l r, exact absurd (lt_of_lt_of_le l r) (lt_irrefl 0)}, simp [if_neg, h] end lemma mod_eq_sub_mod {a b : nat} (h : a ≥ b) : a % b = (a - b) % b := or.elim (eq_zero_or_pos b) (λb0, by rw [b0, nat.sub_zero]) (λh₂, by rw [mod_def, if_pos (and.intro h₂ h)]) lemma mod_lt (x : nat) {y : nat} (h : y > 0) : x % y < y := begin induction x using nat.case_strong_induction_on with x ih, {rw zero_mod, assumption}, {apply or.elim (decidable.em (succ x < y)), {intro h₁, rwa [mod_eq_of_lt h₁]}, {intro h₁, have h₁ : succ x % y = (succ x - y) % y, {exact mod_eq_sub_mod (le_of_not_gt h₁)}, have this : succ x - y ≤ x, {exact le_of_lt_succ (sub_lt (succ_pos x) h)}, have h₂ : (succ x - y) % y < y, {exact ih _ this}, rwa [← h₁] at h₂}} end @[simp] theorem mod_self (n : nat) : n % n = 0 := by rw [mod_eq_sub_mod (le_refl _), nat.sub_self, zero_mod] @[simp] lemma mod_one (n : ℕ) : n % 1 = 0 := have n % 1 < 1, from (mod_lt n) (succ_pos 0), eq_zero_of_le_zero (le_of_lt_succ this) lemma mod_two_eq_zero_or_one (n : ℕ) : n % 2 = 0 ∨ n % 2 = 1 := match n % 2, @nat.mod_lt n 2 dec_trivial with | 0, _ := or.inl rfl | 1, _ := or.inr rfl | k+2, h := absurd h dec_trivial end /- div & mod -/ lemma div_def (x y : nat) : x / y = if 0 < y ∧ y ≤ x then (x - y) / y + 1 else 0 := by have h := div_def_aux x y; rwa dif_eq_if at h lemma mod_add_div (m k : ℕ) : m % k + k * (m / k) = m := begin apply nat.strong_induction_on m, clear m, intros m IH, cases decidable.em (0 < k ∧ k ≤ m) with h h', -- 0 < k ∧ k ≤ m { have h' : m - k < m, { apply nat.sub_lt _ h.left, apply lt_of_lt_of_le h.left h.right }, rw [div_def, mod_def, if_pos h, if_pos h], simp [left_distrib, IH _ h', add_comm, add_left_comm], rw [← nat.add_sub_assoc h.right, nat.add_sub_cancel_left] }, -- ¬ (0 < k ∧ k ≤ m) { rw [div_def, mod_def, if_neg h', if_neg h'], simp }, end /- div -/ @[simp] protected lemma div_one (n : ℕ) : n / 1 = n := have n % 1 + 1 * (n / 1) = n, from mod_add_div _ _, by simp [mod_one] at this; assumption @[simp] protected lemma div_zero (n : ℕ) : n / 0 = 0 := begin rw [div_def], simp [lt_irrefl] end @[simp] protected lemma zero_div (b : ℕ) : 0 / b = 0 := eq.trans (div_def 0 b) $ if_neg (and.rec not_le_of_gt) protected lemma div_le_of_le_mul {m n : ℕ} : ∀ {k}, m ≤ k * n → m / k ≤ n | 0 h := by simp [nat.div_zero]; apply zero_le | (succ k) h := suffices succ k * (m / succ k) ≤ succ k * n, from le_of_mul_le_mul_left this (zero_lt_succ _), calc succ k * (m / succ k) ≤ m % succ k + succ k * (m / succ k) : le_add_left _ _ ... = m : by rw mod_add_div ... ≤ succ k * n : h protected lemma div_le_self : ∀ (m n : ℕ), m / n ≤ m | m 0 := by simp [nat.div_zero]; apply zero_le | m (succ n) := have m ≤ succ n * m, from calc m = 1 * m : by simp ... ≤ succ n * m : mul_le_mul_right _ (succ_le_succ (zero_le _)), nat.div_le_of_le_mul this lemma div_eq_sub_div {a b : nat} (h₁ : b > 0) (h₂ : a ≥ b) : a / b = (a - b) / b + 1 := begin rw [div_def a, if_pos], split ; assumption end lemma div_eq_of_lt {a b : ℕ} (h₀ : a < b) : a / b = 0 := begin rw [div_def a, if_neg], intro h₁, apply not_le_of_gt h₀ h₁.right end -- this is a Galois connection -- f x ≤ y ↔ x ≤ g y -- with -- f x = x * k -- g y = y / k theorem le_div_iff_mul_le (x y : ℕ) {k : ℕ} (Hk : k > 0) : x ≤ y / k ↔ x * k ≤ y := begin -- Hk is needed because, despite div being made total, y / 0 := 0 -- x * 0 ≤ y ↔ x ≤ y / 0 -- ↔ 0 ≤ y ↔ x ≤ 0 -- ↔ true ↔ x = 0 -- ↔ x = 0 revert x, apply nat.strong_induction_on y _, clear y, intros y IH x, cases lt_or_ge y k with h h, -- base case: y < k { rw [div_eq_of_lt h], cases x with x, { simp [zero_mul, zero_le] }, { simp [succ_mul, not_succ_le_zero, add_comm], apply not_le_of_gt, apply lt_of_lt_of_le h, apply le_add_right } }, -- step: k ≤ y { rw [div_eq_sub_div Hk h], cases x with x, { simp [zero_mul, zero_le] }, { have Hlt : y - k < y, { apply sub_lt_of_pos_le ; assumption }, rw [ ← add_one , nat.add_le_add_iff_le_right , IH (y - k) Hlt x , add_one , succ_mul, add_le_to_le_sub _ h ] } } end theorem div_lt_iff_lt_mul (x y : ℕ) {k : ℕ} (Hk : k > 0) : x / k < y ↔ x < y * k := begin simp [lt_iff_not_ge], apply not_iff_not_of_iff, apply le_div_iff_mul_le _ _ Hk end def iterate {α : Sort u} (op : α → α) : ℕ → α → α | 0 a := a | (succ k) a := iterate k (op a) notation f`^[`n`]` := iterate f n /- successor and predecessor -/ theorem add_one_ne_zero (n : ℕ) : n + 1 ≠ 0 := succ_ne_zero _ theorem eq_zero_or_eq_succ_pred (n : ℕ) : n = 0 ∨ n = succ (pred n) := by cases n; simp theorem exists_eq_succ_of_ne_zero {n : ℕ} (H : n ≠ 0) : ∃k : ℕ, n = succ k := ⟨_, (eq_zero_or_eq_succ_pred _).resolve_left H⟩ theorem succ_inj {n m : ℕ} (H : succ n = succ m) : n = m := nat.succ.inj_arrow H id theorem discriminate {B : Sort u} {n : ℕ} (H1: n = 0 → B) (H2 : ∀m, n = succ m → B) : B := by induction h : n; [exact H1 h, exact H2 _ h] theorem one_succ_zero : 1 = succ 0 := rfl theorem two_step_induction {P : ℕ → Sort u} (H1 : P 0) (H2 : P 1) (H3 : ∀ (n : ℕ) (IH1 : P n) (IH2 : P (succ n)), P (succ (succ n))) : Π (a : ℕ), P a | 0 := H1 | 1 := H2 | (succ (succ n)) := H3 _ (two_step_induction _) (two_step_induction _) theorem sub_induction {P : ℕ → ℕ → Sort u} (H1 : ∀m, P 0 m) (H2 : ∀n, P (succ n) 0) (H3 : ∀n m, P n m → P (succ n) (succ m)) : Π (n m : ℕ), P n m | 0 m := H1 _ | (succ n) 0 := H2 _ | (succ n) (succ m) := H3 _ _ (sub_induction n m) /- addition -/ theorem succ_add_eq_succ_add (n m : ℕ) : succ n + m = n + succ m := by simp [succ_add, add_succ] theorem one_add (n : ℕ) : 1 + n = succ n := by simp [add_comm] protected theorem add_right_comm : ∀ (n m k : ℕ), n + m + k = n + k + m := right_comm nat.add nat.add_comm nat.add_assoc theorem eq_zero_of_add_eq_zero {n m : ℕ} (H : n + m = 0) : n = 0 ∧ m = 0 := ⟨nat.eq_zero_of_add_eq_zero_right H, nat.eq_zero_of_add_eq_zero_left H⟩ theorem eq_zero_of_mul_eq_zero : ∀ {n m : ℕ}, n * m = 0 → n = 0 ∨ m = 0 | 0 m := λ h, or.inl rfl | (succ n) m := begin rw succ_mul, intro h, exact or.inr (eq_zero_of_add_eq_zero_left h) end /- properties of inequality -/ theorem le_succ_of_pred_le {n m : ℕ} : pred n ≤ m → n ≤ succ m := nat.cases_on n less_than_or_equal.step (λ a, succ_le_succ) theorem le_lt_antisymm {n m : ℕ} (h₁ : n ≤ m) (h₂ : m < n) : false := nat.lt_irrefl n (nat.lt_of_le_of_lt h₁ h₂) theorem lt_le_antisymm {n m : ℕ} (h₁ : n < m) (h₂ : m ≤ n) : false := le_lt_antisymm h₂ h₁ protected theorem nat.lt_asymm {n m : ℕ} (h₁ : n < m) : ¬ m < n := le_lt_antisymm (nat.le_of_lt h₁) protected def lt_ge_by_cases {a b : ℕ} {C : Sort u} (h₁ : a < b → C) (h₂ : a ≥ b → C) : C := decidable.by_cases h₁ (λ h, h₂ (or.elim (nat.lt_or_ge a b) (λ a, absurd a h) (λ a, a))) protected def lt_by_cases {a b : ℕ} {C : Sort u} (h₁ : a < b → C) (h₂ : a = b → C) (h₃ : b < a → C) : C := nat.lt_ge_by_cases h₁ (λ h₁, nat.lt_ge_by_cases h₃ (λ h, h₂ (nat.le_antisymm h h₁))) protected theorem lt_trichotomy (a b : ℕ) : a < b ∨ a = b ∨ b < a := nat.lt_by_cases (λ h, or.inl h) (λ h, or.inr (or.inl h)) (λ h, or.inr (or.inr h)) protected theorem eq_or_lt_of_not_lt {a b : ℕ} (hnlt : ¬ a < b) : a = b ∨ b < a := (nat.lt_trichotomy a b).resolve_left hnlt theorem lt_succ_of_lt {a b : nat} (h : a < b) : a < succ b := le_succ_of_le h def one_pos := nat.zero_lt_one theorem mul_self_le_mul_self {n m : ℕ} (h : n ≤ m) : n * n ≤ m * m := mul_le_mul h h (zero_le _) (zero_le _) theorem mul_self_lt_mul_self : Π {n m : ℕ}, n < m → n * n < m * m | 0 m h := mul_pos h h | (succ n) m h := mul_lt_mul h (le_of_lt h) (succ_pos _) (zero_le _) theorem mul_self_le_mul_self_iff {n m : ℕ} : n ≤ m ↔ n * n ≤ m * m := ⟨mul_self_le_mul_self, λh, decidable.by_contradiction $ λhn, not_lt_of_ge h $ mul_self_lt_mul_self $ lt_of_not_ge hn⟩ theorem mul_self_lt_mul_self_iff {n m : ℕ} : n < m ↔ n * n < m * m := iff.trans (lt_iff_not_ge _ _) $ iff.trans (not_iff_not_of_iff mul_self_le_mul_self_iff) $ iff.symm (lt_iff_not_ge _ _) theorem le_mul_self : Π (n : ℕ), n ≤ n * n | 0 := le_refl _ | (n+1) := let t := mul_le_mul_left (n+1) (succ_pos n) in by simp at t; exact t /- subtraction -/ protected theorem sub_le_sub_left {n m : ℕ} (k) (h : n ≤ m) : k - m ≤ k - n := by induction h; [refl, exact le_trans (pred_le _) h_ih] theorem succ_sub_sub_succ (n m k : ℕ) : succ n - m - succ k = n - m - k := by rw [nat.sub_sub, nat.sub_sub, add_succ, succ_sub_succ] protected theorem sub.right_comm (m n k : ℕ) : m - n - k = m - k - n := by rw [nat.sub_sub, nat.sub_sub, add_comm] theorem mul_pred_left : ∀ (n m : ℕ), pred n * m = n * m - m | 0 m := by simp [nat.zero_sub, pred_zero, zero_mul] | (succ n) m := by rw [pred_succ, succ_mul, nat.add_sub_cancel] theorem mul_pred_right (n m : ℕ) : n * pred m = n * m - n := by rw [mul_comm, mul_pred_left, mul_comm] protected theorem mul_sub_right_distrib : ∀ (n m k : ℕ), (n - m) * k = n * k - m * k | n 0 k := by simp [nat.sub_zero] | n (succ m) k := by rw [nat.sub_succ, mul_pred_left, mul_sub_right_distrib, succ_mul, nat.sub_sub] protected theorem mul_sub_left_distrib (n m k : ℕ) : n * (m - k) = n * m - n * k := by rw [mul_comm, nat.mul_sub_right_distrib, mul_comm m n, mul_comm n k] protected theorem mul_self_sub_mul_self_eq (a b : nat) : a * a - b * b = (a + b) * (a - b) := by rw [nat.mul_sub_left_distrib, right_distrib, right_distrib, mul_comm b a, add_comm (a*a) (a*b), nat.add_sub_add_left] theorem succ_mul_succ_eq (a b : nat) : succ a * succ b = a*b + a + b + 1 := begin rw [← add_one, ← add_one], simp [right_distrib, left_distrib, add_left_comm] end theorem succ_sub {m n : ℕ} (h : m ≥ n) : succ m - n = succ (m - n) := exists.elim (nat.le.dest h) (assume k, assume hk : n + k = m, by rw [← hk, nat.add_sub_cancel_left, ← add_succ, nat.add_sub_cancel_left]) protected theorem sub_pos_of_lt {m n : ℕ} (h : m < n) : n - m > 0 := have 0 + m < n - m + m, begin rw [zero_add, nat.sub_add_cancel (le_of_lt h)], exact h end, lt_of_add_lt_add_right this protected theorem sub_sub_self {n m : ℕ} (h : m ≤ n) : n - (n - m) = m := (nat.sub_eq_iff_eq_add (nat.sub_le _ _)).2 (eq.symm (add_sub_of_le h)) protected theorem sub_add_comm {n m k : ℕ} (h : k ≤ n) : n + m - k = n - k + m := (nat.sub_eq_iff_eq_add (nat.le_trans h (nat.le_add_right _ _))).2 (by rwa [nat.add_right_comm, nat.sub_add_cancel]) theorem sub_one_sub_lt {n i} (h : i < n) : n - 1 - i < n := begin rw nat.sub_sub, apply nat.sub_lt, apply lt_of_lt_of_le (nat.zero_lt_succ _) h, rw add_comm, apply nat.zero_lt_succ end theorem pred_inj : ∀ {a b : nat}, a > 0 → b > 0 → nat.pred a = nat.pred b → a = b | (succ a) (succ b) ha hb h := have a = b, from h, by rw this | (succ a) 0 ha hb h := absurd hb (lt_irrefl _) | 0 (succ b) ha hb h := absurd ha (lt_irrefl _) | 0 0 ha hb h := rfl /- find -/ section find parameter {p : ℕ → Prop} private def lbp (m n : ℕ) : Prop := m = n + 1 ∧ ∀ k ≤ n, ¬p k parameters [decidable_pred p] (H : ∃n, p n) private def wf_lbp : well_founded lbp := ⟨let ⟨n, pn⟩ := H in suffices ∀m k, n ≤ k + m → acc lbp k, from λa, this _ _ (nat.le_add_left _ _), λm, nat.rec_on m (λk kn, ⟨_, λy r, match y, r with ._, ⟨rfl, a⟩ := absurd pn (a _ kn) end⟩) (λm IH k kn, ⟨_, λy r, match y, r with ._, ⟨rfl, a⟩ := IH _ (by rw nat.add_right_comm; exact kn) end⟩)⟩ protected def find_x : {n // p n ∧ ∀m < n, ¬p m} := @well_founded.fix _ (λk, (∀n < k, ¬p n) → {n // p n ∧ ∀m < n, ¬p m}) lbp wf_lbp (λm IH al, if pm : p m then ⟨m, pm, al⟩ else have ∀ n ≤ m, ¬p n, from λn h, or.elim (lt_or_eq_of_le h) (al n) (λe, by rw e; exact pm), IH _ ⟨rfl, this⟩ (λn h, this n $ nat.le_of_succ_le_succ h)) 0 (λn h, absurd h (nat.not_lt_zero _)) protected def find : ℕ := nat.find_x.1 protected theorem find_spec : p nat.find := nat.find_x.2.left protected theorem find_min : ∀ {m : ℕ}, m < nat.find → ¬p m := nat.find_x.2.right protected theorem find_min' {m : ℕ} (h : p m) : nat.find ≤ m := le_of_not_gt (λ l, find_min l h) end find /- mod -/ theorem mod_le (x y : ℕ) : x % y ≤ x := or.elim (lt_or_ge x y) (λxlty, by rw mod_eq_of_lt xlty; refl) (λylex, or.elim (eq_zero_or_pos y) (λy0, by rw [y0, mod_zero]; refl) (λypos, le_trans (le_of_lt (mod_lt _ ypos)) ylex)) @[simp] theorem add_mod_right (x z : ℕ) : (x + z) % z = x % z := by rw [mod_eq_sub_mod (nat.le_add_left _ _), nat.add_sub_cancel] @[simp] theorem add_mod_left (x z : ℕ) : (x + z) % x = z % x := by rw [add_comm, add_mod_right] @[simp] theorem add_mul_mod_self_left (x y z : ℕ) : (x + y * z) % y = x % y := by {induction z with z ih, simp, rw[mul_succ, ← add_assoc, add_mod_right, ih]} @[simp] theorem add_mul_mod_self_right (x y z : ℕ) : (x + y * z) % z = x % z := by rw [mul_comm, add_mul_mod_self_left] @[simp] theorem mul_mod_right (m n : ℕ) : (m * n) % m = 0 := by rw [← zero_add (m*n), add_mul_mod_self_left, zero_mod] @[simp] theorem mul_mod_left (m n : ℕ) : (m * n) % n = 0 := by rw [mul_comm, mul_mod_right] theorem mul_mod_mul_left (z x y : ℕ) : (z * x) % (z * y) = z * (x % y) := if y0 : y = 0 then by rw [y0, mul_zero, mod_zero, mod_zero] else if z0 : z = 0 then by rw [z0, zero_mul, zero_mul, zero_mul, mod_zero] else x.strong_induction_on $ λn IH, have y0 : y > 0, from nat.pos_of_ne_zero y0, have z0 : z > 0, from nat.pos_of_ne_zero z0, or.elim (le_or_gt y n) (λyn, by rw [ mod_eq_sub_mod yn, mod_eq_sub_mod (mul_le_mul_left z yn), ← nat.mul_sub_left_distrib]; exact IH _ (sub_lt (lt_of_lt_of_le y0 yn) y0)) (λyn, by rw [mod_eq_of_lt yn, mod_eq_of_lt (mul_lt_mul_of_pos_left yn z0)]) theorem mul_mod_mul_right (z x y : ℕ) : (x * z) % (y * z) = (x % y) * z := by rw [mul_comm x z, mul_comm y z, mul_comm (x % y) z]; apply mul_mod_mul_left theorem cond_to_bool_mod_two (x : ℕ) [d : decidable (x % 2 = 1)] : cond (@to_bool (x % 2 = 1) d) 1 0 = x % 2 := begin by_cases h : x % 2 = 1, { simp! [*] }, { cases mod_two_eq_zero_or_one x; simp! [*] } end theorem sub_mul_mod (x k n : ℕ) (h₁ : n*k ≤ x) : (x - n*k) % n = x % n := begin induction k with k, { simp }, { have h₂ : n * k ≤ x, { rw [mul_succ] at h₁, apply nat.le_trans _ h₁, apply le_add_right _ n }, have h₄ : x - n * k ≥ n, { apply @nat.le_of_add_le_add_right (n*k), rw [nat.sub_add_cancel h₂], simp [mul_succ, add_comm] at h₁, simp [h₁] }, rw [mul_succ, ← nat.sub_sub, ← mod_eq_sub_mod h₄, k_ih h₂] } end /- div -/ theorem sub_mul_div (x n p : ℕ) (h₁ : n*p ≤ x) : (x - n*p) / n = x / n - p := begin cases eq_zero_or_pos n with h₀ h₀, { rw [h₀, nat.div_zero, nat.div_zero, nat.zero_sub] }, { induction p with p, { simp }, { have h₂ : n*p ≤ x, { transitivity, { apply nat.mul_le_mul_left, apply le_succ }, { apply h₁ } }, have h₃ : x - n * p ≥ n, { apply le_of_add_le_add_right, rw [nat.sub_add_cancel h₂, add_comm], rw [mul_succ] at h₁, apply h₁ }, rw [sub_succ, ← p_ih h₂], rw [@div_eq_sub_div (x - n*p) _ h₀ h₃], simp [add_one, pred_succ, mul_succ, nat.sub_sub] } } end theorem div_mul_le_self : ∀ (m n : ℕ), m / n * n ≤ m | m 0 := by simp; apply zero_le | m (succ n) := (le_div_iff_mul_le _ _ (nat.succ_pos _)).1 (le_refl _) @[simp] theorem add_div_right (x : ℕ) {z : ℕ} (H : z > 0) : (x + z) / z = succ (x / z) := by rw [div_eq_sub_div H (nat.le_add_left _ _), nat.add_sub_cancel] @[simp] theorem add_div_left (x : ℕ) {z : ℕ} (H : z > 0) : (z + x) / z = succ (x / z) := by rw [add_comm, add_div_right x H] @[simp] theorem mul_div_right (n : ℕ) {m : ℕ} (H : m > 0) : m * n / m = n := by {induction n; simp [*, mul_succ, -mul_comm]} @[simp] theorem mul_div_left (m : ℕ) {n : ℕ} (H : n > 0) : m * n / n = m := by rw [mul_comm, mul_div_right _ H] protected theorem div_self {n : ℕ} (H : n > 0) : n / n = 1 := let t := add_div_right 0 H in by rwa [zero_add, nat.zero_div] at t theorem add_mul_div_left (x z : ℕ) {y : ℕ} (H : y > 0) : (x + y * z) / y = x / y + z := by {induction z with z ih, simp, rw [mul_succ, ← add_assoc, add_div_right _ H, ih]} theorem add_mul_div_right (x y : ℕ) {z : ℕ} (H : z > 0) : (x + y * z) / z = x / z + y := by rw [mul_comm, add_mul_div_left _ _ H] protected theorem mul_div_cancel (m : ℕ) {n : ℕ} (H : n > 0) : m * n / n = m := let t := add_mul_div_right 0 m H in by rwa [zero_add, nat.zero_div, zero_add] at t protected theorem mul_div_cancel_left (m : ℕ) {n : ℕ} (H : n > 0) : n * m / n = m := by rw [mul_comm, nat.mul_div_cancel _ H] protected theorem div_eq_of_eq_mul_left {m n k : ℕ} (H1 : n > 0) (H2 : m = k * n) : m / n = k := by rw [H2, nat.mul_div_cancel _ H1] protected theorem div_eq_of_eq_mul_right {m n k : ℕ} (H1 : n > 0) (H2 : m = n * k) : m / n = k := by rw [H2, nat.mul_div_cancel_left _ H1] protected theorem div_eq_of_lt_le {m n k : ℕ} (lo : k * n ≤ m) (hi : m < succ k * n) : m / n = k := have npos : n > 0, from (eq_zero_or_pos _).resolve_left $ λ hn, by rw [hn, mul_zero] at hi lo; exact absurd lo (not_le_of_gt hi), le_antisymm (le_of_lt_succ ((nat.div_lt_iff_lt_mul _ _ npos).2 hi)) ((nat.le_div_iff_mul_le _ _ npos).2 lo) theorem mul_sub_div (x n p : ℕ) (h₁ : x < n*p) : (n * p - succ x) / n = p - succ (x / n) := begin have npos : n > 0 := (eq_zero_or_pos _).resolve_left (λ n0, by rw [n0, zero_mul] at h₁; exact not_lt_zero _ h₁), apply nat.div_eq_of_lt_le, { rw [nat.mul_sub_right_distrib, mul_comm], apply nat.sub_le_sub_left, exact (div_lt_iff_lt_mul _ _ npos).1 (lt_succ_self _) }, { change succ (pred (n * p - x)) ≤ (succ (pred (p - x / n))) * n, rw [succ_pred_eq_of_pos (nat.sub_pos_of_lt h₁), succ_pred_eq_of_pos (nat.sub_pos_of_lt _)], { rw [nat.mul_sub_right_distrib, mul_comm], apply nat.sub_le_sub_left, apply div_mul_le_self }, { apply (div_lt_iff_lt_mul _ _ npos).2, rwa mul_comm } } end protected theorem div_div_eq_div_mul (m n k : ℕ) : m / n / k = m / (n * k) := begin cases eq_zero_or_pos k with k0 kpos, {rw [k0, mul_zero, nat.div_zero, nat.div_zero]}, cases eq_zero_or_pos n with n0 npos, {rw [n0, zero_mul, nat.div_zero, nat.zero_div]}, apply le_antisymm, { apply (le_div_iff_mul_le _ _ (mul_pos npos kpos)).2, rw [mul_comm n k, ← mul_assoc], apply (le_div_iff_mul_le _ _ npos).1, apply (le_div_iff_mul_le _ _ kpos).1, refl }, { apply (le_div_iff_mul_le _ _ kpos).2, apply (le_div_iff_mul_le _ _ npos).2, rw [mul_assoc, mul_comm n k], apply (le_div_iff_mul_le _ _ (mul_pos kpos npos)).1, refl } end protected theorem mul_div_mul {m : ℕ} (n k : ℕ) (H : m > 0) : m * n / (m * k) = n / k := by rw [← nat.div_div_eq_div_mul, nat.mul_div_cancel_left _ H] /- dvd -/ protected theorem dvd_add_iff_right {k m n : ℕ} (h : k ∣ m) : k ∣ n ↔ k ∣ m + n := ⟨dvd_add h, dvd.elim h $ λd hd, match m, hd with | ._, rfl := λh₂, dvd.elim h₂ $ λe he, ⟨e - d, by rw [nat.mul_sub_left_distrib, ← he, nat.add_sub_cancel_left]⟩ end⟩ protected theorem dvd_add_iff_left {k m n : ℕ} (h : k ∣ n) : k ∣ m ↔ k ∣ m + n := by rw add_comm; exact nat.dvd_add_iff_right h theorem dvd_sub {k m n : ℕ} (H : n ≤ m) (h₁ : k ∣ m) (h₂ : k ∣ n) : k ∣ m - n := (nat.dvd_add_iff_left h₂).2 $ by rw nat.sub_add_cancel H; exact h₁ theorem dvd_mod_iff {k m n : ℕ} (h : k ∣ n) : k ∣ m % n ↔ k ∣ m := let t := @nat.dvd_add_iff_left _ (m % n) _ (dvd_trans h (dvd_mul_right n (m / n))) in by rwa mod_add_div at t theorem le_of_dvd {m n : ℕ} (h : n > 0) : m ∣ n → m ≤ n := λ⟨k, e⟩, by { revert h, rw e, refine k.cases_on _ _, exact λhn, absurd hn (lt_irrefl _), exact λk _, let t := mul_le_mul_left m (succ_pos k) in by rwa mul_one at t } theorem dvd_antisymm : Π {m n : ℕ}, m ∣ n → n ∣ m → m = n | m 0 h₁ h₂ := eq_zero_of_zero_dvd h₂ | 0 n h₁ h₂ := (eq_zero_of_zero_dvd h₁).symm | (succ m) (succ n) h₁ h₂ := le_antisymm (le_of_dvd (succ_pos _) h₁) (le_of_dvd (succ_pos _) h₂) theorem pos_of_dvd_of_pos {m n : ℕ} (H1 : m ∣ n) (H2 : n > 0) : m > 0 := nat.pos_of_ne_zero $ λm0, by rw m0 at H1; rw eq_zero_of_zero_dvd H1 at H2; exact lt_irrefl _ H2 theorem eq_one_of_dvd_one {n : ℕ} (H : n ∣ 1) : n = 1 := le_antisymm (le_of_dvd dec_trivial H) (pos_of_dvd_of_pos H dec_trivial) theorem dvd_of_mod_eq_zero {m n : ℕ} (H : n % m = 0) : m ∣ n := dvd.intro (n / m) $ let t := mod_add_div n m in by simp [H] at t; exact t theorem mod_eq_zero_of_dvd {m n : ℕ} (H : m ∣ n) : n % m = 0 := dvd.elim H (λ z H1, by rw [H1, mul_mod_right]) theorem dvd_iff_mod_eq_zero (m n : ℕ) : m ∣ n ↔ n % m = 0 := ⟨mod_eq_zero_of_dvd, dvd_of_mod_eq_zero⟩ instance decidable_dvd : @decidable_rel ℕ (∣) := λm n, decidable_of_decidable_of_iff (by apply_instance) (dvd_iff_mod_eq_zero _ _).symm protected theorem mul_div_cancel' {m n : ℕ} (H : n ∣ m) : n * (m / n) = m := let t := mod_add_div m n in by rwa [mod_eq_zero_of_dvd H, zero_add] at t protected theorem div_mul_cancel {m n : ℕ} (H : n ∣ m) : m / n * n = m := by rw [mul_comm, nat.mul_div_cancel' H] protected theorem mul_div_assoc (m : ℕ) {n k : ℕ} (H : k ∣ n) : m * n / k = m * (n / k) := or.elim (eq_zero_or_pos k) (λh, by rw [h, nat.div_zero, nat.div_zero, mul_zero]) (λh, have m * n / k = m * (n / k * k) / k, by rw nat.div_mul_cancel H, by rw[this, ← mul_assoc, nat.mul_div_cancel _ h]) theorem dvd_of_mul_dvd_mul_left {m n k : ℕ} (kpos : k > 0) (H : k * m ∣ k * n) : m ∣ n := dvd.elim H (λl H1, by rw mul_assoc at H1; exact ⟨_, eq_of_mul_eq_mul_left kpos H1⟩) theorem dvd_of_mul_dvd_mul_right {m n k : ℕ} (kpos : k > 0) (H : m * k ∣ n * k) : m ∣ n := by rw [mul_comm m k, mul_comm n k] at H; exact dvd_of_mul_dvd_mul_left kpos H /- pow -/ @[simp] theorem pow_one (b : ℕ) : b^1 = b := by simp [pow_succ] theorem pow_le_pow_of_le_left {x y : ℕ} (H : x ≤ y) : ∀ i : ℕ, x^i ≤ y^i | 0 := le_refl _ | (succ i) := mul_le_mul (pow_le_pow_of_le_left i) H (zero_le _) (zero_le _) theorem pow_le_pow_of_le_right {x : ℕ} (H : x > 0) {i : ℕ} : ∀ {j}, i ≤ j → x^i ≤ x^j | 0 h := by rw eq_zero_of_le_zero h; apply le_refl | (succ j) h := (lt_or_eq_of_le h).elim (λhl, by rw [pow_succ, ← mul_one (x^i)]; exact mul_le_mul (pow_le_pow_of_le_right $ le_of_lt_succ hl) H (zero_le _) (zero_le _)) (λe, by rw e; refl) theorem pos_pow_of_pos {b : ℕ} (n : ℕ) (h : 0 < b) : 0 < b^n := pow_le_pow_of_le_right h (zero_le _) theorem zero_pow {n : ℕ} (h : 0 < n) : 0^n = 0 := by rw [← succ_pred_eq_of_pos h, pow_succ, mul_zero] theorem pow_lt_pow_of_lt_left {x y : ℕ} (H : x < y) {i} (h : i > 0) : x^i < y^i := begin cases i with i, { exact absurd h (not_lt_zero _) }, rw [pow_succ, pow_succ], exact mul_lt_mul' (pow_le_pow_of_le_left (le_of_lt H) _) H (zero_le _) (pos_pow_of_pos _ $ lt_of_le_of_lt (zero_le _) H) end theorem pow_lt_pow_of_lt_right {x : ℕ} (H : x > 1) {i j : ℕ} (h : i < j) : x^i < x^j := begin have xpos := lt_of_succ_lt H, refine lt_of_lt_of_le _ (pow_le_pow_of_le_right xpos h), rw [← mul_one (x^i), pow_succ], exact nat.mul_lt_mul_of_pos_left H (pos_pow_of_pos _ xpos) end /- mod / div / pow -/ local attribute [simp] mul_comm theorem mod_pow_succ {b : ℕ} (b_pos : b > 0) (w m : ℕ) : m % (b^succ w) = b * (m/b % b^w) + m % b := begin apply nat.strong_induction_on m, clear m, intros p IH, cases lt_or_ge p (b^succ w) with h₁ h₁, -- base case: p < b^succ w { have h₂ : p / b < b^w, { rw [div_lt_iff_lt_mul p _ b_pos], simp [pow_succ] at h₁, simp [h₁] }, rw [mod_eq_of_lt h₁, mod_eq_of_lt h₂], simp [mod_add_div, add_comm] }, -- step: p ≥ b^succ w { -- Generate condiition for induction principal have h₂ : p - b^succ w < p, { apply sub_lt_of_pos_le _ _ (pos_pow_of_pos _ b_pos) h₁ }, -- Apply induction rw [mod_eq_sub_mod h₁, IH _ h₂], -- Normalize goal and h1 simp [pow_succ], simp [ge, pow_succ] at h₁, -- Pull subtraction outside mod and div rw [sub_mul_mod _ _ _ h₁, sub_mul_div _ _ _ h₁], -- Cancel subtraction inside mod b^w have p_b_ge : b^w ≤ p / b, { rw [le_div_iff_mul_le _ _ b_pos], simp [h₁] }, rw [eq.symm (mod_eq_sub_mod p_b_ge)] } end lemma div_lt_self {n m : nat} : n > 0 → m > 1 → n / m < n := begin intros h₁ h₂, have m_pos : m > 0, { apply lt_trans _ h₂, comp_val }, suffices : 1 * n < m * n, { simp at this, exact iff.mpr (div_lt_iff_lt_mul n n m_pos) this }, exact mul_lt_mul h₂ (le_refl _) h₁ (nat.zero_le _) end end nat
b6686f37686ba389bb02e5a8f8b0ded73ee7f943
9995dfaf2c112e67489d4a6be1858e7b3c67ded6
/proofs2.lean
46ee28b194b4fd88ce46b16f8dbb5aebe332c9ea
[]
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
1,366
lean
def proper_subset : ∀ { α : Type }, set α → set α → Prop := λ α x y, forall (e : α), (e ∈ x → e ∈ y) ∧ (∃ f, f ∈ y ∧ f ∉ x) example : ∀ a b c : ℕ, a = b → b = c → a = c := begin intros a b c, assume ab bc, rewrite ab, rw bc, -- shorthand -- and rw does rfl for us end example : ∀ a b c : ℕ, a = b → b = c → a = c := begin intros a b c, assume ab bc, rewrite ←bc, rw ←ab, end example : ∀ n : ℕ, true := begin assume n, cases n, -- whoa, that's cool trivial, trivial, end example : ∀ P Q : Prop, P ∨ Q → true := begin intros P Q, assume h, cases h, -- whoa, now I get it! trivial, trivial end example : 4 = 5 → 0 = 1 := begin assume four_equals_five, cases four_equals_five, --whoa! end example : proper_subset { 1, 3 } { n | ∃ m, n = 2 * m + 1 } := begin unfold proper_subset, intro o, split, assume h, cases h, apply exists.intro 1, assumption, cases h, apply exists.intro 0, assumption, cases h, apply exists.intro 5, split, apply exists.intro 2, exact rfl, intro h, cases h, cases h, cases h, cases h, cases h, end lemma quiz : proper_subset { 1, 2 } { n : nat | true } := begin unfold proper_subset, assume n, split, assume f, trivial, apply exists.intro 5, split, trivial, assume fn12, cases fn12, cases fn12, cases fn12, cases fn12, cases fn12, end
eb302eba6b55fa03d0de03b105046e6dd3b60121
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/continued_fractions/continuants_recurrence.lean
0b18d9baff7514ce08afd6f2cb13feca0679ff08
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
3,650
lean
/- Copyright (c) 2019 Kevin Kappelmann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Kappelmann -/ import algebra.continued_fractions.translations /-! # Recurrence Lemmas for the `continuants` Function of Continued Fractions. ## Summary Given a generalized continued fraction `g`, for all `n ≥ 1`, we prove that the `continuants` function indeed satisfies the following recurrences: - `Aₙ = bₙ * Aₙ₋₁ + aₙ * Aₙ₋₂`, and - `Bₙ = bₙ * Bₙ₋₁ + aₙ * Bₙ₋₂`. -/ namespace generalized_continued_fraction variables {K : Type*} {g : generalized_continued_fraction K} {n : ℕ} [division_ring K] lemma continuants_aux_recurrence {gp ppred pred : pair K} (nth_s_eq : g.s.nth n = some gp) (nth_conts_aux_eq : g.continuants_aux n = ppred) (succ_nth_conts_aux_eq : g.continuants_aux (n + 1) = pred) : g.continuants_aux (n + 2) = ⟨gp.b * pred.a + gp.a * ppred.a, gp.b * pred.b + gp.a * ppred.b⟩ := by simp [*, continuants_aux, next_continuants, next_denominator, next_numerator] lemma continuants_recurrence_aux {gp ppred pred : pair K} (nth_s_eq : g.s.nth n = some gp) (nth_conts_aux_eq : g.continuants_aux n = ppred) (succ_nth_conts_aux_eq : g.continuants_aux (n + 1) = pred) : g.continuants (n + 1) = ⟨gp.b * pred.a + gp.a * ppred.a, gp.b * pred.b + gp.a * ppred.b⟩ := by simp [nth_cont_eq_succ_nth_cont_aux, (continuants_aux_recurrence nth_s_eq nth_conts_aux_eq succ_nth_conts_aux_eq)] /-- Shows that `Aₙ = bₙ * Aₙ₋₁ + aₙ * Aₙ₋₂` and `Bₙ = bₙ * Bₙ₋₁ + aₙ * Bₙ₋₂`. -/ theorem continuants_recurrence {gp ppred pred : pair K} (succ_nth_s_eq : g.s.nth (n + 1) = some gp) (nth_conts_eq : g.continuants n = ppred) (succ_nth_conts_eq : g.continuants (n + 1) = pred) : g.continuants (n + 2) = ⟨gp.b * pred.a + gp.a * ppred.a, gp.b * pred.b + gp.a * ppred.b⟩ := begin rw [nth_cont_eq_succ_nth_cont_aux] at nth_conts_eq succ_nth_conts_eq, exact (continuants_recurrence_aux succ_nth_s_eq nth_conts_eq succ_nth_conts_eq) end /-- Shows that `Aₙ = bₙ * Aₙ₋₁ + aₙ * Aₙ₋₂`. -/ lemma numerators_recurrence {gp : pair K} {ppredA predA : K} (succ_nth_s_eq : g.s.nth (n + 1) = some gp) (nth_num_eq : g.numerators n = ppredA) (succ_nth_num_eq : g.numerators (n + 1) = predA) : g.numerators (n + 2) = gp.b * predA + gp.a * ppredA := begin obtain ⟨ppredConts, nth_conts_eq, ⟨rfl⟩⟩ : ∃ conts, g.continuants n = conts ∧ conts.a = ppredA, from exists_conts_a_of_num nth_num_eq, obtain ⟨predConts, succ_nth_conts_eq, ⟨rfl⟩⟩ : ∃ conts, g.continuants (n + 1) = conts ∧ conts.a = predA, from exists_conts_a_of_num succ_nth_num_eq, rw [num_eq_conts_a, (continuants_recurrence succ_nth_s_eq nth_conts_eq succ_nth_conts_eq)] end /-- Shows that `Bₙ = bₙ * Bₙ₋₁ + aₙ * Bₙ₋₂`. -/ lemma denominators_recurrence {gp : pair K} {ppredB predB : K} (succ_nth_s_eq : g.s.nth (n + 1) = some gp) (nth_denom_eq : g.denominators n = ppredB) (succ_nth_denom_eq : g.denominators (n + 1) = predB) : g.denominators (n + 2) = gp.b * predB + gp.a * ppredB := begin obtain ⟨ppredConts, nth_conts_eq, ⟨rfl⟩⟩ : ∃ conts, g.continuants n = conts ∧ conts.b = ppredB, from exists_conts_b_of_denom nth_denom_eq, obtain ⟨predConts, succ_nth_conts_eq, ⟨rfl⟩⟩ : ∃ conts, g.continuants (n + 1) = conts ∧ conts.b = predB, from exists_conts_b_of_denom succ_nth_denom_eq, rw [denom_eq_conts_b, (continuants_recurrence succ_nth_s_eq nth_conts_eq succ_nth_conts_eq)] end end generalized_continued_fraction
2e3a3f4ab3f20645dee2672ad909d95b9abff5b9
ac60dab17014edd769c9618cc1569ce8c960a6a5
/src/hpp.lean
67188460a9aaca094b280dde636184e48a46654c
[ "MIT" ]
permissive
frankSil/CAExtensions
20e1f856b3ad775d5e8dc8877614dbcd58c77901
f5c74fd9a806696c73497d9abd45b7315f45379f
refs/heads/master
1,608,706,941,607
1,586,193,337,000
1,586,193,337,000
237,077,434
0
0
null
null
null
null
UTF-8
Lean
false
false
12,003
lean
import cautomaton utils data.list.perm open utils namespace hpp section hpp inductive cellT | X | N | W | E | S | NW | NE | NS | WS | WE | ES | NWE | NWS | NES | WES | NWSE inductive cardinal | CN | CW | CE | CS open cellT cardinal def cellT_str : cellT → string | N := "↑" | W := "←" | E := "→" | S := "↓" | NW := "↖" | NE := "↗" | NS := "↕" | WS := "↙" | WE := "↔" | ES := "↙" | NWE := "⊥" | NWS := "⊣" | NES := "⊢" | WES := "⊤" | NWSE := "+" | X := " " def num_particles : cellT → ℕ | N := 1 | W := 1 | E := 1 | S := 1 | NW := 2 | NE := 2 | NS := 2 | WS := 2 | WE := 2 | ES := 2 | NWE := 3 | NWS := 3 | NES := 3 | WES := 3 | NWSE := 4 | X := 0 instance cellT_to_str : has_to_string cellT := ⟨cellT_str⟩ instance cellT_repr : has_repr cellT := ⟨cellT_str⟩ instance cellT_deceq : decidable_eq cellT := λl r, by cases l; cases r; try {exact is_true rfl}; apply is_false; trivial attribute [reducible] def hpp := cautomaton cellT def has_cardinal : cellT → cardinal → bool | N CN := tt | N _ := ff | W CW := tt | W _ := ff | E CE := tt | E _ := ff | S CS := tt | S _ := ff | NW CN := tt | NW CW := tt | NW _ := ff | NE CN := tt | NE CE := tt | NE _ := ff | NS CW := tt | NS CE := tt | NS _ := ff | WS CW := tt | WS CS := tt | WS _ := ff | WE CS := tt | WE CN := tt | WE _ := ff | ES CE := tt | ES CS := tt | ES _ := ff | NWE CN := tt | NWE CW := tt | NWE CE := tt | NWE _ := ff | NWS CN := tt | NWS CW := tt | NWS CS := tt | NWS _ := ff | NES CN := tt | NES CE := tt | NES CS := tt | NES _ := ff | WES CW := tt | WES CE := tt | WES CS := tt | WES _ := ff | NWSE _ := tt | X _ := ff def collision : cellT → cellT | NS := WE | WE := NS | x := x def translation' : bool → bool → bool → bool → cellT | tt tt tt tt := NWSE | tt tt tt ff := WES | tt tt ff tt := NES | tt tt ff ff := ES | tt ff tt tt := NWS | tt ff tt ff := WS | tt ff ff tt := NS | tt ff ff ff := S | ff tt tt tt := NWE | ff tt tt ff := WE | ff tt ff tt := NE | ff tt ff ff := E | ff ff tt tt := NW | ff ff tt ff := W | ff ff ff tt := N | ff ff ff ff := X def translation (neigh : list cellT) : cellT := let north := list.nth neigh 0 in let west := list.nth neigh 1 in let east := list.nth neigh 2 in let south := list.nth neigh 3 in match north with | none := X | (some n) := match west with | none := X | (some w) := match east with | none := X | (some e) := match south with | none := X | (some s) := translation' (has_cardinal n CS) (has_cardinal w CE) (has_cardinal e CW) (has_cardinal s CN) end end end end lemma translation_eq_translation' {neigh : list cellT} (h : list.length neigh = 4) : translation neigh = let n := list.nth_le neigh 0 $ by simp [h]; exact dec_trivial in let w := list.nth_le neigh 1 $ by simp [h]; exact dec_trivial in let e := list.nth_le neigh 2 $ by simp [h]; exact dec_trivial in let s := list.nth_le neigh 3 $ by simp [h]; exact dec_trivial in translation' (has_cardinal n CS) (has_cardinal w CE) (has_cardinal e CW) (has_cardinal s CN) := begin cases neigh with x₁ xs₁, cases h, cases xs₁ with x₂ xs₂, cases h, cases xs₂ with x₃ xs₃, cases h, cases xs₃ with x₄ xs₄, cases h, cases xs₄ with x₅ xs₅, swap 2, cases h, unfold translation, simp, delta translation, simp end def mk_hpp (g : vec_grid₀ cellT) : hpp := ⟨g, X, cautomatons.neumann, sum.inl cautomatons.ext_one, (λ_ neigh, translation neigh)⟩ def hpp_g := vec_grid₀.mk ⟨11, 11, dec_trivial, ⟨[X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, WE, X, X, X, S, X, E, X, X, X, E, X, W, X, X, N, N, X, X, X, X, X, N, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X], rfl⟩⟩ ⟨0, 0⟩ def simple := mk_hpp hpp_g #eval step_n simple 8 def hpp_g' := vec_grid₀.mk ⟨11, 11, dec_trivial, ⟨[X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X], rfl⟩⟩ ⟨0, 0⟩ def test_simple := mk_hpp hpp_g' def count_particles (a : hpp) : ℕ := list.sum ℘(num_particles <$> a.g) def count_particles' (a : hpp) : ℕ := count a N + count a W + count a S + count a E + 2 * count a NW + 2 * count a NE + 2 * count a NS + 2 * count a WS + 2 * count a WE + 2 * count a ES + 3 * count a NWE + 3 * count a NWS + 3 * count a NES + 3 * count a WES + 4 * count a NWSE def option_coerce : option cellT → cellT | option.none := X | (option.some c) := c instance : has_coe (option cellT) cellT := ⟨option_coerce⟩ set_option pp.binder_types false open list lemma count_particles_split_dir {g} (a : hpp) (h : a = mk_hpp g) : count_particles' a = count_particles a := begin subst h, simp [mk_hpp], simp [count_particles, count_particles', _root_.count, count_grid], rw ← map_generate_map_v₀, repeat { rw generate_eq_data }, rcases g with ⟨⟨r, c, h, ⟨data, hdata⟩⟩, o⟩, simp, clear hdata, induction data with hd tl ih, {simp [list.count]}, { by_cases eq₁ : hd = E; simp [eq₁], { rw @count_cons_self _ _ E, repeat { rw @count_cons_of_ne _ _ _ E _ tl }; try { trivial }, unfold num_particles, rw ← ih, rw nat.succ_add, rw nat.one_add }, { by_cases eq₂ : hd = N, { subst eq₂, rw @count_cons_self _ _ N, repeat { rw @count_cons_of_ne _ _ _ N _ tl }; try { trivial }, unfold num_particles, rw ← ih, rw nat.succ_add, rw nat.one_add }, { by_cases eq₃ : hd = S, { subst eq₃, rw @count_cons_self _ _ S, repeat { rw @count_cons_of_ne _ _ _ S _ tl }; try { trivial }, unfold num_particles, rw ← ih, rw nat.succ_add, rw nat.one_add, ring }, { by_cases eq₄ : hd = W, { subst eq₄, rw @count_cons_self _ _ W, repeat { rw @count_cons_of_ne _ _ _ W _ tl }; try { trivial }, unfold num_particles, rw ← ih, rw nat.succ_add, rw nat.one_add, ring }, { by_cases eq₅ : hd = ES, { subst eq₅, unfold num_particles, rw @count_cons_self _ _ ES, repeat { rw ← nat.one_add }, repeat { rw @count_cons_of_ne _ _ _ ES _ tl }; try { trivial }, rw ← ih, ring }, { by_cases eq₆ : hd = NE, { subst eq₆, unfold num_particles, rw @count_cons_self _ _ NE, repeat { rw ← nat.one_add }, repeat { rw @count_cons_of_ne _ _ _ NE _ tl }; try { trivial }, rw ← ih, ring }, { by_cases eq₇ : hd = NS, { subst eq₇, unfold num_particles, rw @count_cons_self _ _ NS, repeat { rw ← nat.one_add }, repeat { rw @count_cons_of_ne _ _ _ NS _ tl }; try { trivial }, rw ← ih, ring }, { by_cases eq₈ : hd = NW, { subst eq₈, unfold num_particles, rw @count_cons_self _ _ NW, repeat { rw ← nat.one_add }, repeat { rw @count_cons_of_ne _ _ _ NW _ tl }; try { trivial }, rw ← ih, ring }, { by_cases eq₉ : hd = WE, { subst eq₉, unfold num_particles, rw @count_cons_self _ _ WE, repeat { rw ← nat.one_add }, repeat { rw @count_cons_of_ne _ _ _ WE _ tl }; try { trivial }, rw ← ih, ring }, { by_cases eq₁₀ : hd = NES, { subst eq₁₀, unfold num_particles, rw @count_cons_self _ _ NES, repeat { rw ← nat.one_add }, repeat { rw @count_cons_of_ne _ _ _ NES _ tl }; try { trivial }, rw ← ih, ring }, { by_cases eq₁₁ : hd = NWE, { subst eq₁₁, unfold num_particles, rw @count_cons_self _ _ NWE, repeat { rw ← nat.one_add }, repeat { rw @count_cons_of_ne _ _ _ NWE _ tl }; try { trivial }, rw ← ih, ring }, { by_cases eq₁₂ : hd = NWS, { subst eq₁₂, unfold num_particles, rw @count_cons_self _ _ NWS, repeat { rw ← nat.one_add }, repeat { rw @count_cons_of_ne _ _ _ NWS _ tl }; try { trivial }, rw ← ih, ring }, { by_cases eq₁₃ : hd = WES, { subst eq₁₃, unfold num_particles, rw @count_cons_self _ _ WES, repeat { rw ← nat.one_add }, repeat { rw @count_cons_of_ne _ _ _ WES _ tl }; try { trivial }, rw ← ih, ring }, { by_cases eq₁₄ : hd = NWSE, { subst eq₁₄, unfold num_particles, rw @count_cons_self _ _ NWSE, repeat { rw ← nat.one_add }, repeat { rw @count_cons_of_ne _ _ _ NWSE _ tl }; try { trivial }, rw ← ih, ring }, { by_cases eq₁₅ : hd = WS, { subst eq₁₅, unfold num_particles, rw @count_cons_self _ _ WS, repeat { rw ← nat.one_add }, repeat { rw @count_cons_of_ne _ _ _ WS _ tl }; try { trivial }, rw ← ih, ring }, { have : hd = X, { cases hd; try { trivial } }, subst this, repeat { rw @count_cons_of_ne _ _ _ X _ tl }; try { trivial }, unfold num_particles, rw zero_add, rw ← ih, }}}}}}}}}}}}}}} } end theorem canonical_pres_count {g} (a : hpp) (h : a = mk_hpp g) : count_particles a = count_particles (make_canonical a) := begin rw ← count_particles_split_dir _ h, rw ← count_particles_split_dir, have h₁ : a.empty = X, by finish, unfold count_particles', repeat { rw ← count_nonempty_make_canonical }, all_goals { try { rw h₁; trivial } }, swap 2, exact (make_canonical a).g, simp [mk_hpp], simp [make_canonical], subst h, simp [mk_hpp] end lemma next_gen_ext_one_gbl_y {a : hpp} (h : a.bound = sum.inl cautomatons.ext_one) : (grid.bl (ext_aut a).g).y = (grid.bl a.g).y - 1 := begin simp [ext_aut, h, grid.bl], unfold_coes, simp [vec_grid₀_of_fgrid₀_o, cautomatons.bl_ext_one, grid_bounds, grid.bl] end lemma next_gen_ext_one_gbl_x {a : hpp} (h : a.bound = sum.inl cautomatons.ext_one) : (grid.bl (ext_aut a).g).x = (grid.bl a.g).x - 1 := begin simp [ext_aut, h, grid.bl], unfold_coes, simp [vec_grid₀_of_fgrid₀_o, cautomatons.bl_ext_one, grid_bounds, grid.bl] end lemma next_gen_ext_one_gtr_y {a : hpp} (h : a.bound = sum.inl cautomatons.ext_one) : (gtr ((ext_aut a).g)).y = (gtr a.g).y + 1 := begin simp [ext_aut, h, expand_gtr, grid.bl], unfold_coes, simp [vec_grid₀_of_fgrid₀_o, vec_grid₀_of_fgrid₀, relative_grid.rows], simp [cautomatons.bl_ext_one, cautomatons.rows_of_box_ext_one, rows_of_box, cautomatons.tr_ext_one, grid_bounds, grid.bl, expand_gtr, relative_grid.rows], rw int.nat_abs_of_nonneg, ring, simp end end hpp end hpp
a7673aa0d415c629010461c4cae23ced737d36c2
1a61aba1b67cddccce19532a9596efe44be4285f
/tests/lean/626b.hlean
993e4c37bb20ea3a2f590e8f4db216386ed670cd
[ "Apache-2.0" ]
permissive
eigengrau/lean
07986a0f2548688c13ba36231f6cdbee82abf4c6
f8a773be1112015e2d232661ce616d23f12874d0
refs/heads/master
1,610,939,198,566
1,441,352,386,000
1,441,352,494,000
41,903,576
0
0
null
1,441,352,210,000
1,441,352,210,000
null
UTF-8
Lean
false
false
84
hlean
import hit.circle open circle definition f (x : S¹) : bool := circle.rec_on x _ _