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
8abae453c471deed169cc249d13a2f75fd4a1be0
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/lean/run/111.lean
4b3689b086daa3a75fb7e5642eb67127d5ea406d
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
230
lean
import Init.Lean new_frontend open Lean #check mkNullNode -- Lean.Syntax #check mkNullNode #[] -- Lean.Syntax #check @mkNullNode #check let f : Array Syntax → Syntax := @mkNullNode; f #[] #check let f := @mkNullNode; f #[]
898aa01db5a2c2e9713255bc9d93e348f44a5662
4fa161becb8ce7378a709f5992a594764699e268
/src/ring_theory/localization.lean
3729e936d704b6cf103969e292a7933a3b9b0c68
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
33,946
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro, Johan Commelin, Amelia Livingston -/ import data.equiv.ring import tactic.ring_exp import ring_theory.ideal_operations import group_theory.monoid_localization /-! # Localizations of commutative rings We characterize the localization of a commutative ring `R` at a submonoid `M` up to isomorphism; that is, a commutative ring `S` is the localization of `R` at `M` iff we can find a ring homomorphism `f : R →+* S` satisfying 3 properties: 1. For all `y ∈ M`, `f y` is a unit; 2. For all `z : S`, there exists `(x, y) : R × M` such that `z * f y = f x`; 3. For all `x, y : R`, `f x = f y` iff there exists `c ∈ M` such that `x * c = y * c`. Given such a localization map `f : R →+* S`, we can define the surjection `localization_map.mk'` sending `(x, y) : R × M` to `f x * (f y)⁻¹`, and `localization_map.lift`, the homomorphism from `S` induced by a homomorphism from `R` which maps elements of `M` to invertible elements of the codomain. Similarly, given commutative rings `P, Q`, a submonoid `T` of `P` and a localization map for `T` from `P` to `Q`, then a homomorphism `g : R →+* P` such that `g(M) ⊆ T` induces a homomorphism of localizations, `localization_map.map`, from `S` to `Q`. We show the localization as a quotient type, defined in `group_theory.monoid_localization` as `submonoid.localization`, is a `comm_ring` and that the natural ring hom `of : R →+* localization M` is a localization map. We prove some lemmas about the `R`-algebra structure of `S`. When `R` is an integral domain, we define `fraction_map R K` as an abbreviation for `localization (non_zero_divisors R) K`, the natural map to `R`'s field of fractions. We show that a `comm_ring` `K` which is the localization of an integral domain `R` at `R \ {0}` is a field. We use this to show the field of fractions as a quotient type, `fraction_ring`, is a field. ## Implementation notes In maths it is natural to reason up to isomorphism, but in Lean we cannot naturally `rewrite` one structure with an isomorphic one; one way around this is to isolate a predicate characterizing a structure up to isomorphism, and reason about things that satisfy the predicate. A ring localization map is defined to be a localization map of the underlying `comm_monoid` (a `submonoid.localization_map`) which is also a ring hom. To prove most lemmas about a `localization_map` `f` in this file we invoke the corresponding proof for the underlying `comm_monoid` localization map `f.to_localization_map`, which can be found in `group_theory.monoid_localization` and the namespace `submonoid.localization_map`. To apply a localization map `f` as a function, we use `f.to_map`, as coercions don't work well for this structure. To reason about the localization as a quotient type, use `mk_eq_of_mk'` and associated lemmas. These show the quotient map `mk : R → M → localization M` equals the surjection `localization_map.mk'` induced by the map `of : localization_map M (localization M)` (where `of` establishes the localization as a quotient type satisfies the characteristic predicate). The lemma `mk_eq_of_mk'` hence gives you access to the results in the rest of the file, which are about the `localization_map.mk'` induced by any localization map. We use a copy of the localization map `f`'s codomain `S` carrying the data of `f` so that the `R`-algebra instance on `S` can 'know' the map needed to induce the `R`-algebra structure. The proof that "a `comm_ring` `K` which is the localization of an integral domain `R` at `R \ {0}` is a field" is a `def` rather than an `instance`, so if you want to reason about a field of fractions `K`, assume `[field K]` instead of just `[comm_ring K]`. ## Tags localization, ring localization, commutative ring localization, characteristic predicate, commutative ring, field of fractions -/ variables {R : Type*} [comm_ring R] (M : submonoid R) (S : Type*) [comm_ring S] {P : Type*} [comm_ring P] open function set_option old_structure_cmd true /-- The type of ring homomorphisms satisfying the characteristic predicate: if `f : R →+* S` satisfies this predicate, then `S` is isomorphic to the localization of `R` at `M`. We later define an instance coercing a localization map `f` to its codomain `S` so that the `R`-algebra instance on `S` can 'know' the map needed to induce the `R`-algebra structure. -/ @[nolint has_inhabited_instance] structure localization_map extends ring_hom R S, submonoid.localization_map M S /-- The ring hom underlying a `localization_map`. -/ add_decl_doc localization_map.to_ring_hom /-- The `comm_monoid` `localization_map` underlying a `comm_ring` `localization_map`. See `group_theory.monoid_localization` for its definition. -/ add_decl_doc localization_map.to_localization_map variables {M S} namespace ring_hom /-- Makes a localization map from a `comm_ring` hom satisfying the characteristic predicate. -/ def to_localization_map (f : R →+* S) (H1 : ∀ y : M, is_unit (f y)) (H2 : ∀ z, ∃ x : R × M, z * f x.2 = f x.1) (H3 : ∀ x y, f x = f y ↔ ∃ c : M, x * c = y * c) : localization_map M S := { map_units' := H1, surj' := H2, eq_iff_exists' := H3, .. f } end ring_hom /-- Makes a `comm_ring` localization map from an additive `comm_monoid` localization map of `comm_ring`s. -/ def submonoid.localization_map.to_ring_localization (f : submonoid.localization_map M S) (h : ∀ x y, f.to_map (x + y) = f.to_map x + f.to_map y) : localization_map M S := { ..ring_hom.mk' f.to_monoid_hom h, ..f } namespace localization_map variables (f : localization_map M S) /-- Short for `to_ring_hom`; used for applying a localization map as a function. -/ abbreviation to_map := f.to_ring_hom lemma map_units (y : M) : is_unit (f.to_map y) := f.6 y lemma surj (z) : ∃ x : R × M, z * f.to_map x.2 = f.to_map x.1 := f.7 z lemma eq_iff_exists {x y} : f.to_map x = f.to_map y ↔ ∃ c : M, x * c = y * c := f.8 x y @[ext] lemma ext {f g : localization_map M S} (h : ∀ x, f.to_map x = g.to_map x) : f = g := begin cases f, cases g, simp only [] at *, exact funext h end lemma ext_iff {f g : localization_map M S} : f = g ↔ ∀ x, f.to_map x = g.to_map x := ⟨λ h x, h ▸ rfl, ext⟩ lemma to_map_injective : injective (@localization_map.to_map _ _ M S _) := λ _ _ h, ext $ ring_hom.ext_iff.1 h /-- Given `a : S`, `S` a localization of `R`, `is_integer a` iff `a` is in the image of the localization map from `R` to `S`. -/ def is_integer (a : S) : Prop := a ∈ set.range f.to_map variables {f} lemma is_integer_add {a b} (ha : f.is_integer a) (hb : f.is_integer b) : f.is_integer (a + b) := begin rcases ha with ⟨a', ha⟩, rcases hb with ⟨b', hb⟩, use a' + b', rw [f.to_map.map_add, ha, hb] end lemma is_integer_mul {a b} (ha : f.is_integer a) (hb : f.is_integer b) : f.is_integer (a * b) := begin rcases ha with ⟨a', ha⟩, rcases hb with ⟨b', hb⟩, use a' * b', rw [f.to_map.map_mul, ha, hb] end lemma is_integer_smul {a : R} {b} (hb : f.is_integer b) : f.is_integer (f.to_map a * b) := begin rcases hb with ⟨b', hb⟩, use a * b', rw [←hb, f.to_map.map_mul] end variables (f) /-- Each element `a : S` has an `M`-multiple which is an integer. This version multiplies `a` on the right, matching the argument order in `localization_map.surj`. -/ lemma exists_integer_multiple' (a : S) : ∃ (b : M), is_integer f (a * f.to_map b) := let ⟨⟨num, denom⟩, h⟩ := f.surj a in ⟨denom, set.mem_range.mpr ⟨num, h.symm⟩⟩ /-- Each element `a : S` has an `M`-multiple which is an integer. This version multiplies `a` on the left, matching the argument order in the `has_scalar` instance. -/ lemma exists_integer_multiple (a : S) : ∃ (b : M), is_integer f (f.to_map b * a) := by { simp_rw mul_comm _ a, apply exists_integer_multiple' } /-- Given `z : S`, `f.to_localization_map.sec z` is defined to be a pair `(x, y) : R × M` such that `z * f y = f x` (so this lemma is true by definition). -/ lemma sec_spec {f : localization_map M S} (z : S) : z * f.to_map (f.to_localization_map.sec z).2 = f.to_map (f.to_localization_map.sec z).1 := classical.some_spec $ f.surj z /-- Given `z : S`, `f.to_localization_map.sec z` is defined to be a pair `(x, y) : R × M` such that `z * f y = f x`, so this lemma is just an application of `S`'s commutativity. -/ lemma sec_spec' {f : localization_map M S} (z : S) : f.to_map (f.to_localization_map.sec z).1 = f.to_map (f.to_localization_map.sec z).2 * z := by rw [mul_comm, sec_spec] lemma map_right_cancel {x y} {c : M} (h : f.to_map (c * x) = f.to_map (c * y)) : f.to_map x = f.to_map y := f.to_localization_map.map_right_cancel h lemma map_left_cancel {x y} {c : M} (h : f.to_map (x * c) = f.to_map (y * c)) : f.to_map x = f.to_map y := f.to_localization_map.map_left_cancel h lemma eq_zero_of_fst_eq_zero {z x} {y : M} (h : z * f.to_map y = f.to_map x) (hx : x = 0) : z = 0 := by rw [hx, f.to_map.map_zero] at h; exact (is_unit.mul_left_eq_zero_iff_eq_zero (f.map_units y)).1 h /-- Given a localization map `f : R →+* S`, the surjection sending `(x, y) : R × M` to `f x * (f y)⁻¹`. -/ noncomputable def mk' (f : localization_map M S) (x : R) (y : M) : S := f.to_localization_map.mk' x y @[simp] lemma mk'_sec (z : S) : f.mk' (f.to_localization_map.sec z).1 (f.to_localization_map.sec z).2 = z := f.to_localization_map.mk'_sec _ lemma mk'_mul (x₁ x₂ : R) (y₁ y₂ : M) : f.mk' (x₁ * x₂) (y₁ * y₂) = f.mk' x₁ y₁ * f.mk' x₂ y₂ := f.to_localization_map.mk'_mul _ _ _ _ lemma mk'_one (x) : f.mk' x (1 : M) = f.to_map x := f.to_localization_map.mk'_one _ lemma mk'_spec (x) (y : M) : f.mk' x y * f.to_map y = f.to_map x := f.to_localization_map.mk'_spec _ _ lemma mk'_spec' (x) (y : M) : f.to_map y * f.mk' x y = f.to_map x := f.to_localization_map.mk'_spec' _ _ theorem eq_mk'_iff_mul_eq {x} {y : M} {z} : z = f.mk' x y ↔ z * f.to_map y = f.to_map x := f.to_localization_map.eq_mk'_iff_mul_eq theorem mk'_eq_iff_eq_mul {x} {y : M} {z} : f.mk' x y = z ↔ f.to_map x = z * f.to_map y := f.to_localization_map.mk'_eq_iff_eq_mul lemma mk'_eq_iff_eq {x₁ x₂} {y₁ y₂ : M} : f.mk' x₁ y₁ = f.mk' x₂ y₂ ↔ f.to_map (x₁ * y₂) = f.to_map (x₂ * y₁) := f.to_localization_map.mk'_eq_iff_eq protected lemma eq {a₁ b₁} {a₂ b₂ : M} : f.mk' a₁ a₂ = f.mk' b₁ b₂ ↔ ∃ c : M, a₁ * b₂ * c = b₁ * a₂ * c := f.to_localization_map.eq lemma eq_iff_eq (g : localization_map M P) {x y} : f.to_map x = f.to_map y ↔ g.to_map x = g.to_map y := f.to_localization_map.eq_iff_eq g.to_localization_map lemma mk'_eq_iff_mk'_eq (g : localization_map M P) {x₁ x₂} {y₁ y₂ : M} : f.mk' x₁ y₁ = f.mk' x₂ y₂ ↔ g.mk' x₁ y₁ = g.mk' x₂ y₂ := f.to_localization_map.mk'_eq_iff_mk'_eq g.to_localization_map lemma mk'_eq_of_eq {a₁ b₁ : R} {a₂ b₂ : M} (H : b₁ * a₂ = a₁ * b₂) : f.mk' a₁ a₂ = f.mk' b₁ b₂ := f.to_localization_map.mk'_eq_of_eq H @[simp] lemma mk'_self {x : R} {hx : x ∈ M} : f.mk' x ⟨x, hx⟩ = 1 := f.to_localization_map.mk'_self' _ hx @[simp] lemma mk'_self' {x : M} : f.mk' x x = 1 := f.to_localization_map.mk'_self _ @[simp] lemma mk'_self'' {x : M} : f.mk' x.1 x = 1 := f.mk'_self' lemma mul_mk'_eq_mk'_of_mul (x y : R) (z : M) : f.to_map x * f.mk' y z = f.mk' (x * y) z := f.to_localization_map.mul_mk'_eq_mk'_of_mul _ _ _ lemma mk'_eq_mul_mk'_one (x : R) (y : M) : f.mk' x y = f.to_map x * f.mk' 1 y := (f.to_localization_map.mul_mk'_one_eq_mk' _ _).symm @[simp] lemma mk'_mul_cancel_left (x : R) (y : M) : f.mk' (y * x) y = f.to_map x := f.to_localization_map.mk'_mul_cancel_left _ _ lemma mk'_mul_cancel_right (x : R) (y : M) : f.mk' (x * y) y = f.to_map x := f.to_localization_map.mk'_mul_cancel_right _ _ lemma is_unit_comp (j : S →+* P) (y : M) : is_unit (j.comp f.to_map y) := f.to_localization_map.is_unit_comp j.to_monoid_hom _ /-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_ring`s `g : R →+* P` such that `g(M) ⊆ units P`, `f x = f y → g x = g y` for all `x y : R`. -/ lemma eq_of_eq {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) {x y} (h : f.to_map x = f.to_map y) : g x = g y := @submonoid.localization_map.eq_of_eq _ _ _ _ _ _ _ f.to_localization_map g.to_monoid_hom hg _ _ h lemma mk'_add (x₁ x₂ : R) (y₁ y₂ : M) : f.mk' (x₁ * y₂ + x₂ * y₁) (y₁ * y₂) = f.mk' x₁ y₁ + f.mk' x₂ y₂ := f.mk'_eq_iff_eq_mul.2 $ eq.symm begin rw [mul_comm (_ + _), mul_add, mul_mk'_eq_mk'_of_mul, ←eq_sub_iff_add_eq, mk'_eq_iff_eq_mul, mul_comm _ (f.to_map _), mul_sub, eq_sub_iff_add_eq, ←eq_sub_iff_add_eq', ←mul_assoc, ←f.to_map.map_mul, mul_mk'_eq_mk'_of_mul, mk'_eq_iff_eq_mul], simp only [f.to_map.map_add, submonoid.coe_mul, f.to_map.map_mul], ring_exp, end /-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_ring`s `g : R →+* P` such that `g y` is invertible for all `y : M`, the homomorphism induced from `S` to `P` sending `z : S` to `g x * (g y)⁻¹`, where `(x, y) : R × M` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def lift {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) : S →+* P := ring_hom.mk' (@submonoid.localization_map.lift _ _ _ _ _ _ _ f.to_localization_map g.to_monoid_hom hg) $ begin intros x y, rw [f.to_localization_map.lift_spec, mul_comm, add_mul, ←sub_eq_iff_eq_add, eq_comm, f.to_localization_map.lift_spec_mul, mul_comm _ (_ - _), sub_mul, eq_sub_iff_add_eq', ←eq_sub_iff_add_eq, mul_assoc, f.to_localization_map.lift_spec_mul], show g _ * (g _ * g _) = g _ * (g _ * g _ - g _ * g _), repeat {rw ←g.map_mul}, rw [←g.map_sub, ←g.map_mul], apply f.eq_of_eq hg, erw [f.to_map.map_mul, sec_spec', mul_sub, f.to_map.map_sub], simp only [f.to_map.map_mul, sec_spec'], ring_exp, end variables {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) /-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_ring`s `g : R →* P` such that `g y` is invertible for all `y : M`, the homomorphism induced from `S` to `P` maps `f x * (f y)⁻¹` to `g x * (g y)⁻¹` for all `x : R, y ∈ M`. -/ lemma lift_mk' (x y) : f.lift hg (f.mk' x y) = g x * ↑(is_unit.lift_right (g.to_monoid_hom.mrestrict M) hg y)⁻¹ := f.to_localization_map.lift_mk' _ _ _ lemma lift_mk'_spec (x v) (y : M) : f.lift hg (f.mk' x y) = v ↔ g x = g y * v := f.to_localization_map.lift_mk'_spec _ _ _ _ @[simp] lemma lift_eq (x : R) : f.lift hg (f.to_map x) = g x := f.to_localization_map.lift_eq _ _ lemma lift_eq_iff {x y : R × M} : f.lift hg (f.mk' x.1 x.2) = f.lift hg (f.mk' y.1 y.2) ↔ g (x.1 * y.2) = g (y.1 * x.2) := f.to_localization_map.lift_eq_iff _ @[simp] lemma lift_comp : (f.lift hg).comp f.to_map = g := ring_hom.ext $ monoid_hom.ext_iff.1 $ f.to_localization_map.lift_comp _ @[simp] lemma lift_of_comp (j : S →+* P) : f.lift (f.is_unit_comp j) = j := ring_hom.ext $ monoid_hom.ext_iff.1 $ f.to_localization_map.lift_of_comp j.to_monoid_hom lemma epic_of_localization_map {j k : S →+* P} (h : ∀ a, j.comp f.to_map a = k.comp f.to_map a) : j = k := ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.epic_of_localization_map _ _ _ _ _ _ _ f.to_localization_map j.to_monoid_hom k.to_monoid_hom h lemma lift_unique {j : S →+* P} (hj : ∀ x, j (f.to_map x) = g x) : f.lift hg = j := ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.lift_unique _ _ _ _ _ _ _ f.to_localization_map g.to_monoid_hom hg j.to_monoid_hom hj @[simp] lemma lift_id (x) : f.lift f.map_units x = x := f.to_localization_map.lift_id _ /-- Given two localization maps `f : R →+* S, k : R →+* P` for a submonoid `M ⊆ R`, the hom from `P` to `S` induced by `f` is left inverse to the hom from `S` to `P` induced by `k`. -/ @[simp] lemma lift_left_inverse {k : localization_map M S} (z : S) : k.lift f.map_units (f.lift k.map_units z) = z := f.to_localization_map.lift_left_inverse _ lemma lift_surjective_iff : surjective (f.lift hg) ↔ ∀ v : P, ∃ x : R × M, v * g x.2 = g x.1 := f.to_localization_map.lift_surjective_iff hg lemma lift_injective_iff : injective (f.lift hg) ↔ ∀ x y, f.to_map x = f.to_map y ↔ g x = g y := f.to_localization_map.lift_injective_iff hg variables {T : submonoid P} (hy : ∀ y : M, g y ∈ T) {Q : Type*} [comm_ring Q] (k : localization_map T Q) /-- Given a `comm_ring` homomorphism `g : R →+* P` where for submonoids `M ⊆ R, T ⊆ P` we have `g(M) ⊆ T`, the induced ring homomorphism from the localization of `R` at `M` to the localization of `P` at `T`: if `f : R →+* S` and `k : P →+* Q` are localization maps for `M` and `T` respectively, we send `z : S` to `k (g x) * (k (g y))⁻¹`, where `(x, y) : R × M` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def map : S →+* Q := @lift _ _ _ _ _ _ _ f (k.to_map.comp g) $ λ y, k.map_units ⟨g y, hy y⟩ variables {k} lemma map_eq (x) : f.map hy k (f.to_map x) = k.to_map (g x) := f.lift_eq (λ y, k.map_units ⟨g y, hy y⟩) x @[simp] lemma map_comp : (f.map hy k).comp f.to_map = k.to_map.comp g := f.lift_comp $ λ y, k.map_units ⟨g y, hy y⟩ lemma map_mk' (x) (y : M) : f.map hy k (f.mk' x y) = k.mk' (g x) ⟨g y, hy y⟩ := @submonoid.localization_map.map_mk' _ _ _ _ _ _ _ f.to_localization_map g.to_monoid_hom _ hy _ _ k.to_localization_map _ _ @[simp] lemma map_id (z : S) : f.map (λ y, show ring_hom.id R y ∈ M, from y.2) f z = z := f.lift_id _ /-- If `comm_ring` homs `g : R →+* P, l : P →+* A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`. -/ lemma map_comp_map {A : Type*} [comm_ring A] {U : submonoid A} {W} [comm_ring W] (j : localization_map U W) {l : P →+* A} (hl : ∀ w : T, l w ∈ U) : (k.map hl j).comp (f.map hy k) = f.map (λ x, show l.comp g x ∈ U, from hl ⟨g x, hy x⟩) j := ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.map_comp_map _ _ _ _ _ _ _ f.to_localization_map g.to_monoid_hom _ hy _ _ k.to_localization_map _ _ _ _ _ j.to_localization_map l.to_monoid_hom hl /-- If `comm_ring` homs `g : R →+* P, l : P →+* A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`. -/ lemma map_map {A : Type*} [comm_ring A] {U : submonoid A} {W} [comm_ring W] (j : localization_map U W) {l : P →+* A} (hl : ∀ w : T, l w ∈ U) (x) : k.map hl j (f.map hy k x) = f.map (λ x, show l.comp g x ∈ U, from hl ⟨g x, hy x⟩) j x := by rw ←f.map_comp_map hy j hl; refl /-- Given localization maps `f : R →+* S, k : P →+* Q` for submonoids `M, T` respectively, an isomorphism `j : R ≃+* P` such that `j(M) = T` induces an isomorphism of localizations `S ≃+* Q`. -/ noncomputable def ring_equiv_of_ring_equiv (k : localization_map T Q) (h : R ≃+* P) (H : M.map h.to_monoid_hom = T) : S ≃+* Q := (f.to_localization_map.mul_equiv_of_mul_equiv k.to_localization_map H).to_ring_equiv $ (@lift _ _ _ _ _ _ _ f (k.to_map.comp h.to_ring_hom) (λ y, k.map_units ⟨(h y), H ▸ set.mem_image_of_mem h y.2⟩)).map_add @[simp] lemma ring_equiv_of_ring_equiv_eq_map_apply {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x) : f.ring_equiv_of_ring_equiv k j H x = f.map (λ y : M, show j.to_monoid_hom y ∈ T, from H ▸ set.mem_image_of_mem j y.2) k x := rfl lemma ring_equiv_of_ring_equiv_eq_map {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) : (f.ring_equiv_of_ring_equiv k j H).to_monoid_hom = f.map (λ y : M, show j.to_monoid_hom y ∈ T, from H ▸ set.mem_image_of_mem j y.2) k := rfl @[simp] lemma ring_equiv_of_ring_equiv_eq {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x) : f.ring_equiv_of_ring_equiv k j H (f.to_map x) = k.to_map (j x) := f.to_localization_map.mul_equiv_of_mul_equiv_eq H _ lemma ring_equiv_of_ring_equiv_mk' {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x y) : f.ring_equiv_of_ring_equiv k j H (f.mk' x y) = k.mk' (j x) ⟨j y, H ▸ set.mem_image_of_mem j y.2⟩ := f.to_localization_map.mul_equiv_of_mul_equiv_mk' H _ _ end localization_map namespace localization variables {M} instance : has_add (localization M) := ⟨λ z w, con.lift_on₂ z w (λ x y : R × M, mk ((x.2 : R) * y.1 + y.2 * x.1) (x.2 * y.2)) $ λ r1 r2 r3 r4 h1 h2, (con.eq _).2 begin rw r_eq_r' at h1 h2 ⊢, cases h1 with t₅ ht₅, cases h2 with t₆ ht₆, use t₆ * t₅, calc ((r1.2 : R) * r2.1 + r2.2 * r1.1) * (r3.2 * r4.2) * (t₆ * t₅) = (r2.1 * r4.2 * t₆) * (r1.2 * r3.2 * t₅) + (r1.1 * r3.2 * t₅) * (r2.2 * r4.2 * t₆) : by ring ... = (r3.2 * r4.1 + r4.2 * r3.1) * (r1.2 * r2.2) * (t₆ * t₅) : by rw [ht₆, ht₅]; ring end⟩ instance : has_neg (localization M) := ⟨λ z, con.lift_on z (λ x : R × M, mk (-x.1) x.2) $ λ r1 r2 h, (con.eq _).2 begin rw r_eq_r' at h ⊢, cases h with t ht, use t, rw [neg_mul_eq_neg_mul_symm, neg_mul_eq_neg_mul_symm, ht], ring, end⟩ instance : has_zero (localization M) := ⟨mk 0 1⟩ private meta def tac := `[{ intros, refine quotient.sound' (r_of_eq _), simp only [prod.snd_mul, prod.fst_mul, submonoid.coe_mul], ring }] instance : comm_ring (localization M) := { zero := 0, one := 1, add := (+), mul := (*), add_assoc := λ m n k, quotient.induction_on₃' m n k (by tac), zero_add := λ y, quotient.induction_on' y (by tac), add_zero := λ y, quotient.induction_on' y (by tac), neg := has_neg.neg, add_left_neg := λ y, quotient.induction_on' y (by tac), add_comm := λ y z, quotient.induction_on₂' z y (by tac), left_distrib := λ m n k, quotient.induction_on₃' m n k (by tac), right_distrib := λ m n k, quotient.induction_on₃' m n k (by tac), ..localization.comm_monoid M } variables (M) /-- Natural hom sending `x : R`, `R` a `comm_ring`, to the equivalence class of `(x, 1)` in the localization of `R` at a submonoid. -/ def of : localization_map M (localization M) := (localization.monoid_of M).to_ring_localization $ λ x y, (con.eq _).2 $ r_of_eq $ by simp [add_comm] variables {M} lemma monoid_of_eq_of (x) : (monoid_of M).to_map x = (of M).to_map x := rfl lemma mk_one_eq_of (x) : mk x 1 = (of M).to_map x := rfl lemma mk_eq_mk'_apply (x y) : mk x y = (of M).mk' x y := mk_eq_monoid_of_mk'_apply _ _ @[simp] lemma mk_eq_mk' : mk = (of M).mk' := mk_eq_monoid_of_mk' variables (f : localization_map M S) /-- Given a localization map `f : R →+* S` for a submonoid `M`, we get an isomorphism between the localization of `R` at `M` as a quotient type and `S`. -/ noncomputable def ring_equiv_of_quotient : localization M ≃+* S := (mul_equiv_of_quotient f.to_localization_map).to_ring_equiv $ ((of M).lift f.map_units).map_add variables {f} @[simp] lemma ring_equiv_of_quotient_apply (x) : ring_equiv_of_quotient f x = (of M).lift f.map_units x := rfl @[simp] lemma ring_equiv_of_quotient_mk' (x y) : ring_equiv_of_quotient f ((of M).mk' x y) = f.mk' x y := mul_equiv_of_quotient_mk' _ _ lemma ring_equiv_of_quotient_mk (x y) : ring_equiv_of_quotient f (mk x y) = f.mk' x y := mul_equiv_of_quotient_mk _ _ @[simp] lemma ring_equiv_of_quotient_of (x) : ring_equiv_of_quotient f ((of M).to_map x) = f.to_map x := mul_equiv_of_quotient_monoid_of _ @[simp] lemma ring_equiv_of_quotient_symm_mk' (x y) : (ring_equiv_of_quotient f).symm (f.mk' x y) = (of M).mk' x y := mul_equiv_of_quotient_symm_mk' _ _ lemma ring_equiv_of_quotient_symm_mk (x y) : (ring_equiv_of_quotient f).symm (f.mk' x y) = mk x y := mul_equiv_of_quotient_symm_mk _ _ @[simp] lemma ring_equiv_of_quotient_symm_of (x) : (ring_equiv_of_quotient f).symm (f.to_map x) = (of M).to_map x := mul_equiv_of_quotient_symm_monoid_of _ end localization variables {M} namespace localization_map /-! ### `algebra` section Defines the `R`-algebra instance on a copy of `S` carrying the data of the localization map `f` needed to induce the `R`-algebra structure. -/ variables (f : localization_map M S) /-- We define a copy of the localization map `f`'s codomain `S` carrying the data of `f` so that the `R`-algebra instance on `S` can 'know' the map needed to induce the `R`-algebra structure. -/ @[reducible, nolint unused_arguments] def codomain (f : localization_map M S) := S /-- We use a copy of the localization map `f`'s codomain `S` carrying the data of `f` so that the `R`-algebra instance on `S` can 'know' the map needed to induce the `R`-algebra structure. -/ instance : algebra R f.codomain := f.to_map.to_algebra @[simp] lemma of_id (a : R) : (algebra.of_id R f.codomain) a = f.to_map a := rfl variables (f) /-- Localization map `f` from `R` to `S` as an `R`-linear map. -/ def lin_coe : R →ₗ[R] f.codomain := { to_fun := f.to_map, map_add' := f.to_map.map_add, map_smul' := f.to_map.map_mul } variables {f} instance coe_submodules : has_coe (ideal R) (submodule R f.codomain) := ⟨λ I, submodule.map f.lin_coe I⟩ lemma mem_coe (I : ideal R) {x : S} : x ∈ (I : submodule R f.codomain) ↔ ∃ y : R, y ∈ I ∧ f.to_map y = x := iff.rfl @[simp] lemma lin_coe_apply {x} : f.lin_coe x = f.to_map x := rfl end localization_map variables (R) /-- The submonoid of non-zero-divisors of a `comm_ring` `R`. -/ def non_zero_divisors : submonoid R := { carrier := {x | ∀ z, z * x = 0 → z = 0}, one_mem' := λ z hz, by rwa mul_one at hz, mul_mem' := λ x₁ x₂ hx₁ hx₂ z hz, have z * x₁ * x₂ = 0, by rwa mul_assoc, hx₁ z $ hx₂ (z * x₁) this } variables {A : Type*} [integral_domain A] lemma eq_zero_of_ne_zero_of_mul_eq_zero {x y : A} (hnx : x ≠ 0) (hxy : y * x = 0) : y = 0 := or.resolve_right (eq_zero_or_eq_zero_of_mul_eq_zero hxy) hnx lemma mem_non_zero_divisors_iff_ne_zero {x : A} : x ∈ non_zero_divisors A ↔ x ≠ 0 := ⟨λ hm hz, zero_ne_one (hm 1 $ by rw [hz, one_mul]).symm, λ hnx z, eq_zero_of_ne_zero_of_mul_eq_zero hnx⟩ lemma map_ne_zero_of_mem_non_zero_divisors {B : Type*} [ring B] {g : A →+* B} (hg : injective g) {x : non_zero_divisors A} : g x ≠ 0 := λ h0, mem_non_zero_divisors_iff_ne_zero.1 x.2 $ g.injective_iff.1 hg x h0 lemma map_mem_non_zero_divisors {B : Type*} [integral_domain B] {g : A →+* B} (hg : injective g) {x : non_zero_divisors A} : g x ∈ non_zero_divisors B := λ z hz, eq_zero_of_ne_zero_of_mul_eq_zero (map_ne_zero_of_mem_non_zero_divisors hg) hz variables (K : Type*) /-- Localization map from an integral domain `R` to its field of fractions. -/ @[reducible] def fraction_map [comm_ring K] := localization_map (non_zero_divisors R) K namespace fraction_map open localization_map variables {R K} lemma to_map_eq_zero_iff [comm_ring K] (φ : fraction_map R K) {x : R} : x = 0 ↔ φ.to_map x = 0 := begin rw ← φ.to_map.map_zero, split; intro h, { rw h }, { cases φ.eq_iff_exists.mp h with c hc, rw zero_mul at hc, exact c.2 x hc } end protected theorem injective [comm_ring K] (φ : fraction_map R K) : injective φ.to_map := φ.to_map.injective_iff.2 (λ _ h, φ.to_map_eq_zero_iff.mpr h) local attribute [instance] classical.dec_eq /-- A `comm_ring` `K` which is the localization of an integral domain `R` at `R - {0}` is an integral domain. -/ def to_integral_domain [comm_ring K] (φ : fraction_map A K) : integral_domain K := { eq_zero_or_eq_zero_of_mul_eq_zero := begin intros z w h, cases φ.surj z with x hx, cases φ.surj w with y hy, have : z * w * φ.to_map y.2 * φ.to_map x.2 = φ.to_map x.1 * φ.to_map y.1, by rw [mul_assoc z, hy, ←hx]; ac_refl, erw h at this, rw [zero_mul, zero_mul, ←φ.to_map.map_mul] at this, cases eq_zero_or_eq_zero_of_mul_eq_zero (φ.to_map_eq_zero_iff.mpr this.symm) with H H, { exact or.inl (φ.eq_zero_of_fst_eq_zero hx H) }, { exact or.inr (φ.eq_zero_of_fst_eq_zero hy H) }, end, zero_ne_one := by erw [←φ.to_map.map_zero, ←φ.to_map.map_one]; exact λ h, zero_ne_one (φ.injective h), ..(infer_instance : comm_ring K) } /-- The inverse of an element in the field of fractions of an integral domain. -/ protected noncomputable def inv [comm_ring K] (φ : fraction_map A K) (z : K) : K := if h : z = 0 then 0 else φ.mk' (φ.to_localization_map.sec z).2 ⟨(φ.to_localization_map.sec z).1, mem_non_zero_divisors_iff_ne_zero.2 $ λ h0, h $ φ.eq_zero_of_fst_eq_zero (sec_spec z) h0⟩ protected lemma mul_inv_cancel [comm_ring K] (φ : fraction_map A K) (x : K) (hx : x ≠ 0) : x * φ.inv x = 1 := show x * dite _ _ _ = 1, by rw [dif_neg hx, ←is_unit.mul_left_inj (φ.map_units ⟨(φ.to_localization_map.sec x).1, mem_non_zero_divisors_iff_ne_zero.2 $ λ h0, hx $ φ.eq_zero_of_fst_eq_zero (sec_spec x) h0⟩), one_mul, mul_assoc, mk'_spec, ←eq_mk'_iff_mul_eq]; exact (φ.mk'_sec x).symm /-- A `comm_ring` `K` which is the localization of an integral domain `R` at `R - {0}` is a field. -/ noncomputable def to_field [comm_ring K] (φ : fraction_map A K) : field K := { inv := φ.inv, mul_inv_cancel := φ.mul_inv_cancel, inv_zero := dif_pos rfl, ..φ.to_integral_domain } variables {B : Type*} [integral_domain B] [field K] {L : Type*} [field L] (f : fraction_map A K) {g : A →+* L} lemma mk'_eq_div {r s} : f.mk' r s = f.to_map r / f.to_map s := f.mk'_eq_iff_eq_mul.2 $ (div_mul_cancel _ (map_ne_zero_of_mem_non_zero_divisors f.injective)).symm lemma is_unit_map_of_injective (hg : injective g) (y : non_zero_divisors A) : is_unit (g y) := is_unit.mk0 (g y) $ map_ne_zero_of_mem_non_zero_divisors hg /-- Given an integral domain `A`, a localization map to its fields of fractions `f : A →+* K`, and an injective ring hom `g : A →+* L` where `L` is a field, we get a field hom sending `z : K` to `g x * (g y)⁻¹`, where `(x, y) : A × (non_zero_divisors A)` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def lift (hg : injective g) : K →+* L := f.lift $ is_unit_map_of_injective hg /-- Given an integral domain `A`, a localization map to its fields of fractions `f : A →+* K`, and an injective ring hom `g : A →+* L` where `L` is a field, field hom induced from `K` to `L` maps `f x / f y` to `g x / g y` for all `x : A, y ∈ non_zero_divisors A`. -/ @[simp] lemma lift_mk' (hg : injective g) (x y) : f.lift hg (f.mk' x y) = g x / g y := begin erw f.lift_mk' (is_unit_map_of_injective hg), erw submonoid.localization_map.mul_inv_left (λ y : non_zero_divisors A, show is_unit (g.to_monoid_hom y), from is_unit_map_of_injective hg y), exact (mul_div_cancel' _ (map_ne_zero_of_mem_non_zero_divisors hg)).symm, end /-- Given integral domains `A, B` and localization maps to their fields of fractions `f : A →+* K, g : B →+* L` and an injective ring hom `j : A →+* B`, we get a field hom sending `z : K` to `g (j x) * (g (j y))⁻¹`, where `(x, y) : A × (non_zero_divisors A)` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def map (g : fraction_map B L) {j : A →+* B} (hj : injective j) : K →+* L := f.map (λ y, mem_non_zero_divisors_iff_ne_zero.2 $ map_ne_zero_of_mem_non_zero_divisors hj) g /-- Given integral domains `A, B` and localization maps to their fields of fractions `f : A →+* K, g : B →+* L`, an isomorphism `j : A ≃+* B` induces an isomorphism of fields of fractions `K ≃+* L`. -/ noncomputable def field_equiv_of_ring_equiv (g : fraction_map B L) (h : A ≃+* B) : K ≃+* L := f.ring_equiv_of_ring_equiv g h begin ext b, show b ∈ h.to_equiv '' _ ↔ _, erw [h.to_equiv.image_eq_preimage, set.preimage, set.mem_set_of_eq, mem_non_zero_divisors_iff_ne_zero, mem_non_zero_divisors_iff_ne_zero], exact h.symm.map_ne_zero_iff end /-- The cast from `int` to `rat` as a `fraction_map`. -/ def int.fraction_map : fraction_map ℤ ℚ := { to_fun := coe, map_units' := begin rintro ⟨x, hx⟩, rw [submonoid.mem_carrier, mem_non_zero_divisors_iff_ne_zero] at hx, simpa only [is_unit_iff_ne_zero, int.cast_eq_zero, ne.def, subtype.coe_mk] using hx, end, surj' := begin rintro ⟨n, d, hd, h⟩, refine ⟨⟨n, ⟨d, _⟩⟩, rat.mul_denom_eq_num⟩, rwa [submonoid.mem_carrier, mem_non_zero_divisors_iff_ne_zero, int.coe_nat_ne_zero_iff_pos] end, eq_iff_exists' := begin intros x y, rw [int.cast_inj], refine ⟨by { rintro rfl, use 1 }, _⟩, rintro ⟨⟨c, hc⟩, h⟩, apply int.eq_of_mul_eq_mul_right _ h, rwa [submonoid.mem_carrier, mem_non_zero_divisors_iff_ne_zero] at hc, end, ..int.cast_ring_hom ℚ } end fraction_map variables (A) /-- The fraction field of an integral domain as a quotient type. -/ @[reducible] def fraction_ring := localization (non_zero_divisors A) /-- Natural hom sending `x : A`, `A` an integral domain, to the equivalence class of `(x, 1)` in the field of fractions of `A`. -/ def of : fraction_map A (localization (non_zero_divisors A)) := localization.of (non_zero_divisors A) namespace fraction_ring variables {A} noncomputable instance : field (fraction_ring A) := (of A).to_field @[simp] lemma mk_eq_div {r s} : (localization.mk r s : fraction_ring A) = ((of A).to_map r / (of A).to_map s : fraction_ring A) := by erw [localization.mk_eq_mk', (of A).mk'_eq_div] /-- Given an integral domain `A` and a localization map to a field of fractions `f : A →+* K`, we get an isomorphism between the field of fractions of `A` as a quotient type and `K`. -/ noncomputable def field_equiv_of_quotient {K : Type*} [field K] (f : fraction_map A K) : fraction_ring A ≃+* K := localization.ring_equiv_of_quotient f end fraction_ring
18fb277b5513aa23680d7cb7eceed1b3446c3f83
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/category/Compactum_auto.lean
4078d12bbfe0c4fc2e71798c23a0e3c389387fb8
[]
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
10,478
lean
/- Copyright (c) 2020 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.monad.types import Mathlib.category_theory.monad.limits import Mathlib.category_theory.equivalence import Mathlib.topology.category.CompHaus import Mathlib.data.set.constructions import Mathlib.PostPort universes u_1 u_2 namespace Mathlib /-! # Compacta and Compact Hausdorff Spaces Recall that, given a monad `M` on `Type*`, an *algebra* for `M` consists of the following data: - A type `X : Type*` - A "structure" map `M X → X`. This data must also satisfy a distributivity and unit axiom, and algebras for `M` form a category in an evident way. See the file `category_theory.monad.algebra` for a general version, as well as the following link. https://ncatlab.org/nlab/show/monad This file proves the equivalence between the category of *compact Hausdorff topological spaces* and the category of algebras for the *ultrafilter monad*. ## Notation: Here are the main objects introduced in this file. - `Compactum` is the type of compacta, which we define as algebras for the ultrafilter monad. - `Compactum_to_CompHaus` is the functor `Compactum ⥤ CompHaus`. Here `CompHaus` is the usual category of compact Hausdorff spaces. - `Compactum_to_CompHaus.is_equivalence` is a term of type `is_equivalence Compactum_to_CompHaus`. The proof of this equivalence is a bit technical. But the idea is quite simply that the structure map `ultrafilter X → X` for an algebra `X` of the ultrafilter monad should be considered as the map sending an ultrafilter to its limit in `X`. The topology on `X` is then defined by mimicking the characterization of open sets in terms of ultrafilters. Any `X : Compactum` is endowed with a coercion to `Type*`, as well as the following instances: - `topological_space X`. - `compact_space X`. - `t2_space X`. Any morphism `f : X ⟶ Y` of is endowed with a coercion to a function `X → Y`, which is shown to be continuous in `continuous_of_hom`. The function `Compactum.of_topological_space` can be used to construct a `Compactum` from a topological space which satisfies `compact_space` and `t2_space`. We also add wrappers around structures which already exist. Here are the main ones, all in the `Compactum` namespace: - `forget : Compactum ⥤ Type*` is the forgetful functor, which induces a `concrete_category` instance for `Compactum`. - `free : Type* ⥤ Compactum` is the left adjoint to `forget`, and the adjunction is in `adj`. - `str : ultrafilter X → X` is the structure map for `X : Compactum`. The notation `X.str` is preferred. - `join : ultrafilter (ultrafilter X) → ultrafilter X` is the monadic join for `X : Compactum`. Again, the notation `X.join` is preferred. - `incl : X → ultrafilter X` is the unit for `X : Compactum`. The notation `X.incl` is preferred. ## References - E. Manes, Algebraic Theories, Graduate Texts in Mathematics 26, Springer-Verlag, 1976. - https://ncatlab.org/nlab/show/ultrafilter -/ /-- The type `Compactum` of Compacta, defined as algebras for the ultrafilter monad. -/ def Compactum := category_theory.monad.algebra (category_theory.of_type_functor ultrafilter) namespace Compactum /-- The forgetful functor to Type* -/ def forget : Compactum ⥤ Type u_1 := category_theory.monad.forget (category_theory.of_type_functor ultrafilter) /-- The "free" Compactum functor. -/ def free : Type u_1 ⥤ Compactum := category_theory.monad.free (category_theory.of_type_functor ultrafilter) /-- The adjunction between `free` and `forget`. -/ def adj : free ⊣ forget := category_theory.monad.adj (category_theory.of_type_functor ultrafilter) -- Basic instances protected instance category_theory.concrete_category : category_theory.concrete_category Compactum := category_theory.concrete_category.mk forget protected instance has_coe_to_sort : has_coe_to_sort Compactum := has_coe_to_sort.mk (Type u_1) (category_theory.functor.obj forget) protected instance category_theory.has_hom.hom.has_coe_to_fun {X : Compactum} {Y : Compactum} : has_coe_to_fun (X ⟶ Y) := has_coe_to_fun.mk (fun (f : X ⟶ Y) => ↥X → ↥Y) fun (f : X ⟶ Y) => category_theory.monad.algebra.hom.f f protected instance category_theory.limits.has_limits : category_theory.limits.has_limits Compactum := category_theory.has_limits_of_has_limits_creates_limits forget /-- The structure map for a compactum, essentially sending an ultrafilter to its limit. -/ def str (X : Compactum) : ultrafilter ↥X → ↥X := category_theory.monad.algebra.a X /-- The monadic join. -/ def join (X : Compactum) : ultrafilter (ultrafilter ↥X) → ultrafilter ↥X := category_theory.nat_trans.app μ_ ↥X /-- The inclusion of `X` into `ultrafilter X`. -/ def incl (X : Compactum) : ↥X → ultrafilter ↥X := category_theory.nat_trans.app η_ (category_theory.functor.obj forget X) @[simp] theorem str_incl (X : Compactum) (x : ↥X) : str X (incl X x) = x := sorry @[simp] theorem str_hom_commute (X : Compactum) (Y : Compactum) (f : X ⟶ Y) (xs : ultrafilter ↥X) : coe_fn f (str X xs) = str Y (ultrafilter.map (⇑f) xs) := sorry @[simp] theorem join_distrib (X : Compactum) (uux : ultrafilter (ultrafilter ↥X)) : str X (join X uux) = str X (ultrafilter.map (str X) uux) := sorry protected instance topological_space {X : Compactum} : topological_space ↥X := topological_space.mk (fun (U : set ↥X) => ∀ (F : ultrafilter ↥X), str X F ∈ U → U ∈ F) sorry sorry sorry theorem is_closed_iff {X : Compactum} (S : set ↥X) : is_closed S ↔ ∀ (F : ultrafilter ↥X), S ∈ F → str X F ∈ S := sorry protected instance compact_space {X : Compactum} : compact_space ↥X := compact_space.mk (eq.mpr (id (Eq._oldrec (Eq.refl (is_compact set.univ)) (propext compact_iff_ultrafilter_le_nhds))) fun (F : ultrafilter ↥X) (h : ↑F ≤ filter.principal set.univ) => Exists.intro (str X F) (Exists.intro trivial (eq.mpr (id (Eq._oldrec (Eq.refl (↑F ≤ nhds (str X F))) (propext le_nhds_iff))) fun (S : set ↥X) (h1 : str X F ∈ S) (h2 : is_open S) => h2 F h1))) /-- A local definition used only in the proofs. -/ /-- A local definition used only in the proofs. -/ theorem is_closed_cl {X : Compactum} (A : set ↥X) : is_closed (cl A) := eq.mpr (id (Eq._oldrec (Eq.refl (is_closed (cl A))) (propext (is_closed_iff (cl A))))) fun (F : ultrafilter ↥X) (hF : cl A ∈ F) => cl_cl A (Exists.intro F { left := hF, right := rfl }) theorem str_eq_of_le_nhds {X : Compactum} (F : ultrafilter ↥X) (x : ↥X) : ↑F ≤ nhds x → str X F = x := sorry theorem le_nhds_of_str_eq {X : Compactum} (F : ultrafilter ↥X) (x : ↥X) : str X F = x → ↑F ≤ nhds x := fun (h : str X F = x) => iff.mpr le_nhds_iff fun (s : set ↥X) (hx : x ∈ s) (hs : is_open s) => hs F (eq.mpr (id (Eq._oldrec (Eq.refl (str X F ∈ s)) h)) hx) -- All the hard work above boils down to this t2_space instance. protected instance t2_space {X : Compactum} : t2_space ↥X := eq.mpr (id (Eq._oldrec (Eq.refl (t2_space ↥X)) (propext t2_iff_ultrafilter))) fun (x y : ↥X) (F : ultrafilter ↥X) (hx : ↑F ≤ nhds x) (hy : ↑F ≤ nhds y) => eq.mpr (id (Eq._oldrec (Eq.refl (x = y)) (Eq.symm (str_eq_of_le_nhds F x hx)))) (eq.mpr (id (Eq._oldrec (Eq.refl (str X F = y)) (Eq.symm (str_eq_of_le_nhds F y hy)))) (Eq.refl (str X F))) /-- The structure map of a compactum actually computes limits. -/ theorem Lim_eq_str {X : Compactum} (F : ultrafilter ↥X) : ultrafilter.Lim F = str X F := eq.mpr (id (Eq._oldrec (Eq.refl (ultrafilter.Lim F = str X F)) (propext ultrafilter.Lim_eq_iff_le_nhds))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑F ≤ nhds (str X F))) (propext le_nhds_iff))) fun (s : set ↥X) (ᾰ : str X F ∈ s) (ᾰ_1 : is_open s) => ᾰ_1 F ᾰ) theorem cl_eq_closure {X : Compactum} (A : set ↥X) : cl A = closure A := sorry /-- Any morphism of compacta is continuous. -/ theorem continuous_of_hom {X : Compactum} {Y : Compactum} (f : X ⟶ Y) : continuous ⇑f := sorry /-- Given any compact Hausdorff space, we construct a Compactum. -/ def of_topological_space (X : Type u_1) [topological_space X] [compact_space X] [t2_space X] : Compactum := category_theory.monad.algebra.mk X ultrafilter.Lim /-- Any continuous map between Compacta is a morphism of compacta. -/ def hom_of_continuous {X : Compactum} {Y : Compactum} (f : ↥X → ↥Y) (cont : continuous f) : X ⟶ Y := category_theory.monad.algebra.hom.mk f end Compactum /-- The functor functor from Compactum to CompHaus. -/ def Compactum_to_CompHaus : Compactum ⥤ CompHaus := category_theory.functor.mk (fun (X : Compactum) => CompHaus.mk (category_theory.bundled.mk ↥X)) fun (X Y : Compactum) (f : X ⟶ Y) => continuous_map.mk ⇑f namespace Compactum_to_CompHaus /-- The functor Compactum_to_CompHaus is full. -/ def full : category_theory.full Compactum_to_CompHaus := category_theory.full.mk fun (X Y : Compactum) (f : category_theory.functor.obj Compactum_to_CompHaus X ⟶ category_theory.functor.obj Compactum_to_CompHaus Y) => Compactum.hom_of_continuous (continuous_map.to_fun f) sorry /-- The functor Compactum_to_CompHaus is faithful. -/ theorem faithful : category_theory.faithful Compactum_to_CompHaus := category_theory.faithful.mk /-- This definition is used to prove essential surjectivity of Compactum_to_CompHaus. -/ def iso_of_topological_space {D : CompHaus} : category_theory.functor.obj Compactum_to_CompHaus (Compactum.of_topological_space ↥D) ≅ D := category_theory.iso.mk (continuous_map.mk id) (continuous_map.mk id) /-- The functor Compactum_to_CompHaus is essentially surjective. -/ theorem ess_surj : category_theory.ess_surj Compactum_to_CompHaus := category_theory.ess_surj.mk fun (X : CompHaus) => Exists.intro (Compactum.of_topological_space ↥X) (Nonempty.intro iso_of_topological_space) /-- The functor Compactum_to_CompHaus is an equivalence of categories. -/ def is_equivalence : category_theory.is_equivalence Compactum_to_CompHaus := category_theory.equivalence.equivalence_of_fully_faithfully_ess_surj Compactum_to_CompHaus end Mathlib
9d5ea0884490dc80f3bfdec6eacc1a9a936533c3
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/real/sign.lean
34f156eb1119a7e2053447c83d28b0bfd38acc00
[ "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
3,850
lean
/- Copyright (c) 2021 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying, Eric Wieser -/ import data.real.basic /-! # Real sign function > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file introduces and contains some results about `real.sign` which maps negative real numbers to -1, positive real numbers to 1, and 0 to 0. ## Main definitions * `real.sign r` is $\begin{cases} -1 & \text{if } r < 0, \\ ~~\, 0 & \text{if } r = 0, \\ ~~\, 1 & \text{if } r > 0. \end{cases}$ ## Tags sign function -/ namespace real /-- The sign function that maps negative real numbers to -1, positive numbers to 1, and 0 otherwise. -/ noncomputable def sign (r : ℝ) : ℝ := if r < 0 then -1 else if 0 < r then 1 else 0 lemma sign_of_neg {r : ℝ} (hr : r < 0) : sign r = -1 := by rw [sign, if_pos hr] lemma sign_of_pos {r : ℝ} (hr : 0 < r) : sign r = 1 := by rw [sign, if_pos hr, if_neg hr.not_lt] @[simp] lemma sign_zero : sign 0 = 0 := by rw [sign, if_neg (lt_irrefl _), if_neg (lt_irrefl _)] @[simp] lemma sign_one : sign 1 = 1 := sign_of_pos $ by norm_num lemma sign_apply_eq (r : ℝ) : sign r = -1 ∨ sign r = 0 ∨ sign r = 1 := begin obtain hn | rfl | hp := lt_trichotomy r (0 : ℝ), { exact (or.inl $ sign_of_neg hn) }, { exact (or.inr $ or.inl $ sign_zero) }, { exact (or.inr $ or.inr $ sign_of_pos hp) }, end /-- This lemma is useful for working with `ℝˣ` -/ lemma sign_apply_eq_of_ne_zero (r : ℝ) (h : r ≠ 0) : sign r = -1 ∨ sign r = 1 := begin obtain hn | rfl | hp := lt_trichotomy r (0 : ℝ), { exact (or.inl $ sign_of_neg hn) }, { exact (h rfl).elim }, { exact (or.inr $ sign_of_pos hp) }, end @[simp] lemma sign_eq_zero_iff {r : ℝ} : sign r = 0 ↔ r = 0 := begin refine ⟨λ h, _, λ h, h.symm ▸ sign_zero⟩, obtain hn | rfl | hp := lt_trichotomy r (0 : ℝ), { rw [sign_of_neg hn, neg_eq_zero] at h, exact (one_ne_zero h).elim }, { refl }, { rw sign_of_pos hp at h, exact (one_ne_zero h).elim }, end lemma sign_int_cast (z : ℤ) : sign (z : ℝ) = ↑(int.sign z) := begin obtain hn | rfl | hp := lt_trichotomy z (0 : ℤ), { rw [sign_of_neg (int.cast_lt_zero.mpr hn), int.sign_eq_neg_one_of_neg hn, int.cast_neg, int.cast_one], }, { rw [int.cast_zero, sign_zero, int.sign_zero, int.cast_zero], }, { rw [sign_of_pos (int.cast_pos.mpr hp), int.sign_eq_one_of_pos hp, int.cast_one] } end lemma sign_neg {r : ℝ} : sign (-r) = - sign r := begin obtain hn | rfl | hp := lt_trichotomy r (0 : ℝ), { rw [sign_of_neg hn, sign_of_pos (neg_pos.mpr hn), neg_neg] }, { rw [sign_zero, neg_zero, sign_zero] }, { rw [sign_of_pos hp, sign_of_neg (neg_lt_zero.mpr hp)] }, end lemma sign_mul_nonneg (r : ℝ) : 0 ≤ sign r * r := begin obtain hn | rfl | hp := lt_trichotomy r (0 : ℝ), { rw sign_of_neg hn, exact mul_nonneg_of_nonpos_of_nonpos (by norm_num) hn.le }, { rw mul_zero, }, { rw [sign_of_pos hp, one_mul], exact hp.le } end lemma sign_mul_pos_of_ne_zero (r : ℝ) (hr : r ≠ 0) : 0 < sign r * r := begin refine lt_of_le_of_ne (sign_mul_nonneg r) (λ h, hr _), have hs0 := (zero_eq_mul.mp h).resolve_right hr, exact sign_eq_zero_iff.mp hs0, end @[simp] lemma inv_sign (r : ℝ) : (sign r)⁻¹ = sign r := begin obtain (hn | hz | hp) := sign_apply_eq r, { rw hn, norm_num }, { rw hz, exact inv_zero }, { rw hp, exact inv_one } end @[simp] lemma sign_inv (r : ℝ) : sign r⁻¹ = sign r := begin obtain hn | rfl | hp := lt_trichotomy r (0 : ℝ), { rw [sign_of_neg hn, sign_of_neg (inv_lt_zero.mpr hn)] }, { rw [sign_zero, inv_zero, sign_zero] }, { rw [sign_of_pos hp, sign_of_pos (inv_pos.mpr hp)] }, end end real
b7743317cddd7362d921e7d3bd0fff2cfe0664bb
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/category/Top/limits_auto.lean
ac92a8138d37265df666d89704841954e7754332
[]
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,080
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Scott Morrison, Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.category.Top.basic import Mathlib.category_theory.limits.types import Mathlib.category_theory.limits.preserves.basic import Mathlib.PostPort universes u namespace Mathlib namespace Top /-- A choice of limit cone for a functor `F : J ⥤ Top`. Generally you should just use `limit.cone F`, unless you need the actual definition (which is in terms of `types.limit_cone`). -/ def limit_cone {J : Type u} [category_theory.small_category J] (F : J ⥤ Top) : category_theory.limits.cone F := category_theory.limits.cone.mk (category_theory.bundled.mk (category_theory.limits.cone.X (category_theory.limits.types.limit_cone (F ⋙ category_theory.forget Top)))) (category_theory.nat_trans.mk fun (j : J) => continuous_map.mk (category_theory.nat_trans.app (category_theory.limits.cone.π (category_theory.limits.types.limit_cone (F ⋙ category_theory.forget Top))) j)) /-- The chosen cone `Top.limit_cone F` for a functor `F : J ⥤ Top` is a limit cone. Generally you should just use `limit.is_limit F`, unless you need the actual definition (which is in terms of `types.limit_cone_is_limit`). -/ def limit_cone_is_limit {J : Type u} [category_theory.small_category J] (F : J ⥤ Top) : category_theory.limits.is_limit (limit_cone F) := category_theory.limits.is_limit.of_faithful (category_theory.forget Top) (category_theory.limits.types.limit_cone_is_limit (F ⋙ category_theory.forget Top)) (fun (s : category_theory.limits.cone F) => continuous_map.mk fun (v : category_theory.limits.cone.X (category_theory.functor.map_cone (category_theory.forget Top) s)) => { val := fun (j : J) => category_theory.nat_trans.app (category_theory.limits.cone.π (category_theory.functor.map_cone (category_theory.forget Top) s)) j v, property := sorry }) sorry protected instance Top_has_limits : category_theory.limits.has_limits Top := category_theory.limits.has_limits.mk fun (J : Type u) (𝒥 : category_theory.small_category J) => category_theory.limits.has_limits_of_shape.mk fun (F : J ⥤ Top) => category_theory.limits.has_limit.mk (category_theory.limits.limit_cone.mk (limit_cone F) (limit_cone_is_limit F)) protected instance forget_preserves_limits : category_theory.limits.preserves_limits (category_theory.forget Top) := category_theory.limits.preserves_limits.mk fun (J : Type u) (𝒥 : category_theory.small_category J) => category_theory.limits.preserves_limits_of_shape.mk fun (F : J ⥤ Top) => category_theory.limits.preserves_limit_of_preserves_limit_cone (limit_cone_is_limit F) (category_theory.limits.types.limit_cone_is_limit (F ⋙ category_theory.forget Top)) /-- A choice of colimit cocone for a functor `F : J ⥤ Top`. Generally you should just use `colimit.coone F`, unless you need the actual definition (which is in terms of `types.colimit_cocone`). -/ def colimit_cocone {J : Type u} [category_theory.small_category J] (F : J ⥤ Top) : category_theory.limits.cocone F := category_theory.limits.cocone.mk (category_theory.bundled.mk (category_theory.limits.cocone.X (category_theory.limits.types.colimit_cocone (F ⋙ category_theory.forget Top)))) (category_theory.nat_trans.mk fun (j : J) => continuous_map.mk (category_theory.nat_trans.app (category_theory.limits.cocone.ι (category_theory.limits.types.colimit_cocone (F ⋙ category_theory.forget Top))) j)) /-- The chosen cocone `Top.colimit_cocone F` for a functor `F : J ⥤ Top` is a colimit cocone. Generally you should just use `colimit.is_colimit F`, unless you need the actual definition (which is in terms of `types.colimit_cocone_is_colimit`). -/ def colimit_cocone_is_colimit {J : Type u} [category_theory.small_category J] (F : J ⥤ Top) : category_theory.limits.is_colimit (colimit_cocone F) := category_theory.limits.is_colimit.of_faithful (category_theory.forget Top) (category_theory.limits.types.colimit_cocone_is_colimit (F ⋙ category_theory.forget Top)) (fun (s : category_theory.limits.cocone F) => continuous_map.mk (Quot.lift (fun (p : sigma fun (j : J) => category_theory.functor.obj (F ⋙ category_theory.forget Top) j) => category_theory.nat_trans.app (category_theory.limits.cocone.ι (category_theory.functor.map_cocone (category_theory.forget Top) s)) (sigma.fst p) (sigma.snd p)) sorry)) sorry protected instance Top_has_colimits : category_theory.limits.has_colimits Top := category_theory.limits.has_colimits.mk fun (J : Type u) (𝒥 : category_theory.small_category J) => category_theory.limits.has_colimits_of_shape.mk fun (F : J ⥤ Top) => category_theory.limits.has_colimit.mk (category_theory.limits.colimit_cocone.mk (colimit_cocone F) (colimit_cocone_is_colimit F)) protected instance forget_preserves_colimits : category_theory.limits.preserves_colimits (category_theory.forget Top) := category_theory.limits.preserves_colimits.mk fun (J : Type u) (𝒥 : category_theory.small_category J) => category_theory.limits.preserves_colimits_of_shape.mk fun (F : J ⥤ Top) => category_theory.limits.preserves_colimit_of_preserves_colimit_cocone (colimit_cocone_is_colimit F) (category_theory.limits.types.colimit_cocone_is_colimit (F ⋙ category_theory.forget Top)) end Mathlib
47faae5a158d4df074951fb9d5fd6dfddb90c6cc
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/number_theory/dioph.lean
bbed466e2190d06d47ab1abd905d5b88615b5a77
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
27,947
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.fin.fin2 import data.pfun import data.vector3 import number_theory.pell /-! # Diophantine functions and Matiyasevic's theorem Hilbert's tenth problem asked whether there exists an algorithm which for a given integer polynomial determines whether this polynomial has integer solutions. It was answered in the negative in 1970, the final step being completed by Matiyasevic who showed that the power function is Diophantine. Here a function is called Diophantine if its graph is Diophantine as a set. A subset `S ⊆ ℕ ^ α` in turn is called Diophantine if there exists an integer polynomial on `α ⊕ β` such that `v ∈ S` iff there exists `t : ℕ^β` with `p (v, t) = 0`. ## Main definitions * `is_poly`: a predicate stating that a function is a multivariate integer polynomial. * `poly`: the type of multivariate integer polynomial functions. * `dioph`: a predicate stating that a set `S ⊆ ℕ^α` is Diophantine, i.e. that * `dioph_fn`: a predicate on a function stating that it is Diophantine in the sense that its graph is Diophantine as a set. ## Main statements * `pell_dioph` states that solutions to Pell's equation form a Diophantine set. * `pow_dioph` states that the power function is Diophantine, a version of Matiyasevic's theorem. ## References * [M. Carneiro, _A Lean formalization of Matiyasevic's theorem_][carneiro2018matiyasevic] * [M. Davis, _Hilbert's tenth problem is unsolvable_][MR317916] ## Tags Matiyasevic's theorem, Hilbert's tenth problem ## TODO * Finish the solution of Hilbert's tenth problem. * Connect `poly` to `mv_polynomial` -/ universe u open nat function namespace int lemma eq_nat_abs_iff_mul (x n) : nat_abs x = n ↔ (x - n) * (x + n) = 0 := begin refine iff.trans _ mul_eq_zero.symm, refine iff.trans _ (or_congr sub_eq_zero add_eq_zero_iff_eq_neg).symm, exact ⟨λe, by rw ← e; apply nat_abs_eq, λo, by cases o; subst x; simp [nat_abs_of_nat]⟩ end end int open fin2 /-- `list_all p l` is equivalent to `∀ a ∈ l, p a`, but unfolds directly to a conjunction, i.e. `list_all p [0, 1, 2] = p 0 ∧ p 1 ∧ p 2`. -/ @[simp] def list_all {α} (p : α → Prop) : list α → Prop | [] := true | (x :: []) := p x | (x :: l) := p x ∧ list_all l @[simp] theorem list_all_cons {α} (p : α → Prop) (x : α) : ∀ (l : list α), list_all p (x :: l) ↔ p x ∧ list_all p l | [] := (and_true _).symm | (x :: l) := iff.rfl theorem list_all_iff_forall {α} (p : α → Prop) : ∀ (l : list α), list_all p l ↔ ∀ x ∈ l, p x | [] := (iff_true_intro $ list.ball_nil _).symm | (x :: l) := by rw [list.ball_cons, ← list_all_iff_forall l]; simp theorem list_all.imp {α} {p q : α → Prop} (h : ∀ x, p x → q x) : ∀ {l : list α}, list_all p l → list_all q l | [] := id | (x :: l) := by simpa using and.imp (h x) list_all.imp @[simp] theorem list_all_map {α β} {p : β → Prop} (f : α → β) {l : list α} : list_all p (l.map f) ↔ list_all (p ∘ f) l := by induction l; simp * theorem list_all_congr {α} {p q : α → Prop} (h : ∀ x, p x ↔ q x) {l : list α} : list_all p l ↔ list_all q l := ⟨list_all.imp (λx, (h x).1), list_all.imp (λx, (h x).2)⟩ instance decidable_list_all {α} (p : α → Prop) [decidable_pred p] (l : list α) : decidable (list_all p l) := decidable_of_decidable_of_iff (by apply_instance) (list_all_iff_forall _ _).symm /- poly -/ /-- A predicate asserting that a function is a multivariate integer polynomial. (We are being a bit lazy here by allowing many representations for multiplication, rather than only allowing monomials and addition, but the definition is equivalent and this is easier to use.) -/ inductive is_poly {α} : ((α → ℕ) → ℤ) → Prop | proj : ∀ i, is_poly (λx : α → ℕ, x i) | const : Π (n : ℤ), is_poly (λx : α → ℕ, n) | sub : Π {f g : (α → ℕ) → ℤ}, is_poly f → is_poly g → is_poly (λx, f x - g x) | mul : Π {f g : (α → ℕ) → ℤ}, is_poly f → is_poly g → is_poly (λx, f x * g x) /-- The type of multivariate integer polynomials -/ def poly (α : Type u) := {f : (α → ℕ) → ℤ // is_poly f} namespace poly section parameter {α : Type u} instance : has_coe_to_fun (poly α) := ⟨_, λ f, f.1⟩ /-- The underlying function of a `poly` is a polynomial -/ lemma isp (f : poly α) : is_poly f := f.2 /-- Extensionality for `poly α` -/ lemma ext {f g : poly α} (e : ∀x, f x = g x) : f = g := subtype.eq (funext e) /-- Construct a `poly` given an extensionally equivalent `poly`. -/ def subst (f : poly α) (g : (α → ℕ) → ℤ) (e : ∀x, f x = g x) : poly α := ⟨g, by rw ← (funext e : coe_fn f = g); exact f.isp⟩ @[simp] theorem subst_eval (f g e x) : subst f g e x = g x := rfl /-- The `i`th projection function, `x_i`. -/ def proj (i) : poly α := ⟨_, is_poly.proj i⟩ @[simp] theorem proj_eval (i x) : proj i x = x i := rfl /-- The constant function with value `n : ℤ`. -/ def const (n) : poly α := ⟨_, is_poly.const n⟩ @[simp] theorem const_eval (n x) : const n x = n := rfl /-- The zero polynomial -/ def zero : poly α := const 0 instance : has_zero (poly α) := ⟨poly.zero⟩ @[simp] theorem zero_eval (x) : (0 : poly α) x = 0 := rfl /-- The zero polynomial -/ def one : poly α := const 1 instance : has_one (poly α) := ⟨poly.one⟩ @[simp] theorem one_eval (x) : (1 : poly α) x = 1 := rfl /-- Subtraction of polynomials -/ def sub : poly α → poly α → poly α | ⟨f, pf⟩ ⟨g, pg⟩ := ⟨_, is_poly.sub pf pg⟩ instance : has_sub (poly α) := ⟨poly.sub⟩ @[simp] theorem sub_eval : Π (f g x), (f - g : poly α) x = f x - g x | ⟨f, pf⟩ ⟨g, pg⟩ x := rfl /-- Negation of a polynomial -/ def neg (f : poly α) : poly α := 0 - f instance : has_neg (poly α) := ⟨poly.neg⟩ @[simp] theorem neg_eval (f x) : (-f : poly α) x = -f x := show (0-f) x = _, by simp /-- Addition of polynomials -/ def add : poly α → poly α → poly α | ⟨f, pf⟩ ⟨g, pg⟩ := subst (⟨f, pf⟩ - -⟨g, pg⟩) _ (λx, show f x - (0 - g x) = f x + g x, by simp) instance : has_add (poly α) := ⟨poly.add⟩ @[simp] theorem add_eval : Π (f g x), (f + g : poly α) x = f x + g x | ⟨f, pf⟩ ⟨g, pg⟩ x := rfl /-- Multiplication of polynomials -/ def mul : poly α → poly α → poly α | ⟨f, pf⟩ ⟨g, pg⟩ := ⟨_, is_poly.mul pf pg⟩ instance : has_mul (poly α) := ⟨poly.mul⟩ @[simp] theorem mul_eval : Π (f g x), (f * g : poly α) x = f x * g x | ⟨f, pf⟩ ⟨g, pg⟩ x := rfl instance : comm_ring (poly α) := by refine_struct { add := (+), zero := (0 : poly α), neg := has_neg.neg, mul := (*), one := 1, sub := has_sub.sub, npow := @npow_rec _ ⟨1⟩ ⟨(*)⟩, nsmul := @nsmul_rec _ ⟨0⟩ ⟨(+)⟩, gsmul := @gsmul_rec _ ⟨0⟩ ⟨(+)⟩ ⟨neg⟩ }; intros; try { refl }; refine ext (λ _, _); simp [sub_eq_add_neg, mul_add, mul_left_comm, mul_comm, add_comm, add_assoc] lemma induction {C : poly α → Prop} (H1 : ∀i, C (proj i)) (H2 : ∀n, C (const n)) (H3 : ∀f g, C f → C g → C (f - g)) (H4 : ∀f g, C f → C g → C (f * g)) (f : poly α) : C f := begin cases f with f pf, induction pf with i n f g pf pg ihf ihg f g pf pg ihf ihg, apply H1, apply H2, apply H3 _ _ ihf ihg, apply H4 _ _ ihf ihg end /-- The sum of squares of a list of polynomials. This is relevant for Diophantine equations, because it means that a list of equations can be encoded as a single equation: `x = 0 ∧ y = 0 ∧ z = 0` is equivalent to `x^2 + y^2 + z^2 = 0`. -/ def sumsq : list (poly α) → poly α | [] := 0 | (p::ps) := p*p + sumsq ps theorem sumsq_nonneg (x) : ∀ l, 0 ≤ sumsq l x | [] := le_refl 0 | (p::ps) := by rw sumsq; simp [-add_comm]; exact add_nonneg (mul_self_nonneg _) (sumsq_nonneg ps) theorem sumsq_eq_zero (x) : ∀ l, sumsq l x = 0 ↔ list_all (λa : poly α, a x = 0) l | [] := eq_self_iff_true _ | (p::ps) := by rw [list_all_cons, ← sumsq_eq_zero ps]; rw sumsq; simp [-add_comm]; exact ⟨λ(h : p x * p x + sumsq ps x = 0), have p x = 0, from eq_zero_of_mul_self_eq_zero $ le_antisymm (by rw ← h; have t := add_le_add_left (sumsq_nonneg x ps) (p x * p x); rwa [add_zero] at t) (mul_self_nonneg _), ⟨this, by simp [this] at h; exact h⟩, λ⟨h1, h2⟩, by rw [h1, h2]; refl⟩ end /-- Map the index set of variables, replacing `x_i` with `x_(f i)`. -/ def remap {α β} (f : α → β) (g : poly α) : poly β := ⟨λv, g $ v ∘ f, g.induction (λi, by simp; apply is_poly.proj) (λn, by simp; apply is_poly.const) (λf g pf pg, by simp; apply is_poly.sub pf pg) (λf g pf pg, by simp; apply is_poly.mul pf pg)⟩ @[simp] theorem remap_eval {α β} (f : α → β) (g : poly α) (v) : remap f g v = g (v ∘ f) := rfl end poly namespace sum /-- combine two functions into a function on the disjoint union -/ def join {α β γ} (f : α → γ) (g : β → γ) : α ⊕ β → γ := by {refine sum.rec _ _, exacts [f, g]} end sum local infixr ` ⊗ `:65 := sum.join open sum namespace option /-- Functions from `option` can be combined similarly to `vector.cons` -/ def cons {α β} (a : β) (v : α → β) : option α → β := by {refine option.rec _ _, exacts [a, v]} notation a :: b := cons a b @[simp] theorem cons_head_tail {α β} (v : option α → β) : v none :: v ∘ some = v := funext $ λo, by cases o; refl end option /- dioph -/ /-- A set `S ⊆ ℕ^α` is Diophantine if there exists a polynomial on `α ⊕ β` such that `v ∈ S` iff there exists `t : ℕ^β` with `p (v, t) = 0`. -/ def dioph {α : Type u} (S : set (α → ℕ)) : Prop := ∃ {β : Type u} (p : poly (α ⊕ β)), ∀ (v : α → ℕ), S v ↔ ∃t, p (v ⊗ t) = 0 namespace dioph section variables {α β γ : Type u} theorem ext {S S' : set (α → ℕ)} (d : dioph S) (H : ∀v, S v ↔ S' v) : dioph S' := eq.rec d $ show S = S', from set.ext H theorem of_no_dummies (S : set (α → ℕ)) (p : poly α) (h : ∀ (v : α → ℕ), S v ↔ p v = 0) : dioph S := ⟨ulift empty, p.remap inl, λv, (h v).trans ⟨λh, ⟨λt, empty.rec _ t.down, by simp; rw [ show (v ⊗ λt:ulift empty, empty.rec _ t.down) ∘ inl = v, from rfl, h]⟩, λ⟨t, ht⟩, by simp at ht; rwa [show (v ⊗ t) ∘ inl = v, from rfl] at ht⟩⟩ lemma inject_dummies_lem (f : β → γ) (g : γ → option β) (inv : ∀ x, g (f x) = some x) (p : poly (α ⊕ β)) (v : α → ℕ) : (∃t, p (v ⊗ t) = 0) ↔ (∃t, p.remap (inl ⊗ (inr ∘ f)) (v ⊗ t) = 0) := begin simp, refine ⟨λt, _, λt, _⟩; cases t with t ht, { have : (v ⊗ (0 :: t) ∘ g) ∘ (inl ⊗ inr ∘ f) = v ⊗ t := funext (λs, by cases s with a b; dsimp [join, (∘)]; try {rw inv}; refl), exact ⟨(0 :: t) ∘ g, by rwa this⟩ }, { have : v ⊗ t ∘ f = (v ⊗ t) ∘ (inl ⊗ inr ∘ f) := funext (λs, by cases s with a b; refl), exact ⟨t ∘ f, by rwa this⟩ } end theorem inject_dummies {S : set (α → ℕ)} (f : β → γ) (g : γ → option β) (inv : ∀ x, g (f x) = some x) (p : poly (α ⊕ β)) (h : ∀ (v : α → ℕ), S v ↔ ∃t, p (v ⊗ t) = 0) : ∃ q : poly (α ⊕ γ), ∀ (v : α → ℕ), S v ↔ ∃t, q (v ⊗ t) = 0 := ⟨p.remap (inl ⊗ (inr ∘ f)), λv, (h v).trans $ inject_dummies_lem f g inv _ _⟩ theorem reindex_dioph {S : set (α → ℕ)} : Π (d : dioph S) (f : α → β), dioph (λv, S (v ∘ f)) | ⟨γ, p, pe⟩ f := ⟨γ, p.remap ((inl ∘ f) ⊗ inr), λv, (pe _).trans $ exists_congr $ λt, suffices v ∘ f ⊗ t = (v ⊗ t) ∘ (inl ∘ f ⊗ inr), by simp [this], funext $ λs, by cases s with a b; refl⟩ theorem dioph_list_all (l) (d : list_all dioph l) : dioph (λv, list_all (λS : set (α → ℕ), S v) l) := suffices ∃ β (pl : list (poly (α ⊕ β))), ∀ v, list_all (λS : set _, S v) l ↔ ∃t, list_all (λp : poly (α ⊕ β), p (v ⊗ t) = 0) pl, from let ⟨β, pl, h⟩ := this in ⟨β, poly.sumsq pl, λv, (h v).trans $ exists_congr $ λt, (poly.sumsq_eq_zero _ _).symm⟩, begin induction l with S l IH, exact ⟨ulift empty, [], λv, by simp; exact ⟨λ⟨t⟩, empty.rec _ t, trivial⟩⟩, simp at d, exact let ⟨⟨β, p, pe⟩, dl⟩ := d, ⟨γ, pl, ple⟩ := IH dl in ⟨β ⊕ γ, p.remap (inl ⊗ inr ∘ inl) :: pl.map (λq, q.remap (inl ⊗ (inr ∘ inr))), λv, by simp; exact iff.trans (and_congr (pe v) (ple v)) ⟨λ⟨⟨m, hm⟩, ⟨n, hn⟩⟩, ⟨m ⊗ n, by rw [ show (v ⊗ m ⊗ n) ∘ (inl ⊗ inr ∘ inl) = v ⊗ m, from funext $ λs, by cases s with a b; refl]; exact hm, by { refine list_all.imp (λq hq, _) hn, dsimp [(∘)], rw [show (λ (x : α ⊕ γ), (v ⊗ m ⊗ n) ((inl ⊗ λ (x : γ), inr (inr x)) x)) = v ⊗ n, from funext $ λs, by cases s with a b; refl]; exact hq }⟩, λ⟨t, hl, hr⟩, ⟨⟨t ∘ inl, by rwa [ show (v ⊗ t) ∘ (inl ⊗ inr ∘ inl) = v ⊗ t ∘ inl, from funext $ λs, by cases s with a b; refl] at hl⟩, ⟨t ∘ inr, by { refine list_all.imp (λq hq, _) hr, dsimp [(∘)] at hq, rwa [show (λ (x : α ⊕ γ), (v ⊗ t) ((inl ⊗ λ (x : γ), inr (inr x)) x)) = v ⊗ t ∘ inr, from funext $ λs, by cases s with a b; refl] at hq }⟩⟩⟩⟩ end theorem and_dioph {S S' : set (α → ℕ)} (d : dioph S) (d' : dioph S') : dioph (λv, S v ∧ S' v) := dioph_list_all [S, S'] ⟨d, d'⟩ theorem or_dioph {S S' : set (α → ℕ)} : ∀ (d : dioph S) (d' : dioph S'), dioph (λv, S v ∨ S' v) | ⟨β, p, pe⟩ ⟨γ, q, qe⟩ := ⟨β ⊕ γ, p.remap (inl ⊗ inr ∘ inl) * q.remap (inl ⊗ inr ∘ inr), λv, begin refine iff.trans (or_congr ((pe v).trans _) ((qe v).trans _)) (exists_or_distrib.symm.trans (exists_congr $ λt, (@mul_eq_zero _ _ _ (p ((v ⊗ t) ∘ (inl ⊗ inr ∘ inl))) (q ((v ⊗ t) ∘ (inl ⊗ inr ∘ inr)))).symm)), exact inject_dummies_lem _ (some ⊗ (λ_, none)) (λx, rfl) _ _, exact inject_dummies_lem _ ((λ_, none) ⊗ some) (λx, rfl) _ _, end⟩ /-- A partial function is Diophantine if its graph is Diophantine. -/ def dioph_pfun (f : (α → ℕ) →. ℕ) := dioph (λv : option α → ℕ, f.graph (v ∘ some, v none)) /-- A function is Diophantine if its graph is Diophantine. -/ def dioph_fn (f : (α → ℕ) → ℕ) := dioph (λv : option α → ℕ, f (v ∘ some) = v none) theorem reindex_dioph_fn {f : (α → ℕ) → ℕ} (d : dioph_fn f) (g : α → β) : dioph_fn (λv, f (v ∘ g)) := reindex_dioph d (functor.map g) theorem ex_dioph {S : set (α ⊕ β → ℕ)} : dioph S → dioph (λv, ∃x, S (v ⊗ x)) | ⟨γ, p, pe⟩ := ⟨β ⊕ γ, p.remap ((inl ⊗ inr ∘ inl) ⊗ inr ∘ inr), λv, ⟨λ⟨x, hx⟩, let ⟨t, ht⟩ := (pe _).1 hx in ⟨x ⊗ t, by simp; rw [ show (v ⊗ x ⊗ t) ∘ ((inl ⊗ inr ∘ inl) ⊗ inr ∘ inr) = (v ⊗ x) ⊗ t, from funext $ λs, by cases s with a b; try {cases a}; refl]; exact ht⟩, λ⟨t, ht⟩, ⟨t ∘ inl, (pe _).2 ⟨t ∘ inr, by simp at ht; rwa [ show (v ⊗ t) ∘ ((inl ⊗ inr ∘ inl) ⊗ inr ∘ inr) = (v ⊗ t ∘ inl) ⊗ t ∘ inr, from funext $ λs, by cases s with a b; try {cases a}; refl] at ht⟩⟩⟩⟩ theorem ex1_dioph {S : set (option α → ℕ)} : dioph S → dioph (λv, ∃x, S (x :: v)) | ⟨β, p, pe⟩ := ⟨option β, p.remap (inr none :: inl ⊗ inr ∘ some), λv, ⟨λ⟨x, hx⟩, let ⟨t, ht⟩ := (pe _).1 hx in ⟨x :: t, by simp; rw [ show (v ⊗ x :: t) ∘ (inr none :: inl ⊗ inr ∘ some) = x :: v ⊗ t, from funext $ λs, by cases s with a b; try {cases a}; refl]; exact ht⟩, λ⟨t, ht⟩, ⟨t none, (pe _).2 ⟨t ∘ some, by simp at ht; rwa [ show (v ⊗ t) ∘ (inr none :: inl ⊗ inr ∘ some) = t none :: v ⊗ t ∘ some, from funext $ λs, by cases s with a b; try {cases a}; refl] at ht⟩⟩⟩⟩ theorem dom_dioph {f : (α → ℕ) →. ℕ} (d : dioph_pfun f) : dioph f.dom := cast (congr_arg dioph $ set.ext $ λv, (pfun.dom_iff_graph _ _).symm) (ex1_dioph d) theorem dioph_fn_iff_pfun (f : (α → ℕ) → ℕ) : dioph_fn f = @dioph_pfun α f := by refine congr_arg dioph (set.ext $ λv, _); exact pfun.lift_graph.symm theorem abs_poly_dioph (p : poly α) : dioph_fn (λv, (p v).nat_abs) := by refine of_no_dummies _ ((p.remap some - poly.proj none) * (p.remap some + poly.proj none)) (λv, _); apply int.eq_nat_abs_iff_mul theorem proj_dioph (i : α) : dioph_fn (λv, v i) := abs_poly_dioph (poly.proj i) theorem dioph_pfun_comp1 {S : set (option α → ℕ)} (d : dioph S) {f} (df : dioph_pfun f) : dioph (λv : α → ℕ, ∃ h : f.dom v, S (f.fn v h :: v)) := ext (ex1_dioph (and_dioph d df)) $ λv, ⟨λ⟨x, hS, (h: Exists _)⟩, by rw [show (x :: v) ∘ some = v, from funext $ λs, rfl] at h; cases h with hf h; refine ⟨hf, _⟩; rw [pfun.fn, h]; exact hS, λ⟨x, hS⟩, ⟨f.fn v x, hS, show Exists _, by rw [show (f.fn v x :: v) ∘ some = v, from funext $ λs, rfl]; exact ⟨x, rfl⟩⟩⟩ theorem dioph_fn_comp1 {S : set (option α → ℕ)} (d : dioph S) {f : (α → ℕ) → ℕ} (df : dioph_fn f) : dioph (λv : α → ℕ, S (f v :: v)) := ext (dioph_pfun_comp1 d (cast (dioph_fn_iff_pfun f) df)) $ λv, ⟨λ⟨_, h⟩, h, λh, ⟨trivial, h⟩⟩ end section variables {α β γ : Type} open vector3 open_locale vector3 theorem dioph_fn_vec_comp1 {n} {S : set (vector3 ℕ (succ n))} (d : dioph S) {f : (vector3 ℕ n) → ℕ} (df : dioph_fn f) : dioph (λv : vector3 ℕ n, S (cons (f v) v)) := ext (dioph_fn_comp1 (reindex_dioph d (none :: some)) df) $ λv, by rw [ show option.cons (f v) v ∘ (cons none some) = f v :: v, from funext $ λs, by cases s with a b; refl] theorem vec_ex1_dioph (n) {S : set (vector3 ℕ (succ n))} (d : dioph S) : dioph (λv : vector3 ℕ n, ∃x, S (x :: v)) := ext (ex1_dioph $ reindex_dioph d (none :: some)) $ λv, exists_congr $ λx, by rw [ show (option.cons x v) ∘ (cons none some) = x :: v, from funext $ λs, by cases s with a b; refl] theorem dioph_fn_vec {n} (f : vector3 ℕ n → ℕ) : dioph_fn f ↔ dioph (λv : vector3 ℕ (succ n), f (v ∘ fs) = v fz) := ⟨λh, reindex_dioph h (fz :: fs), λh, reindex_dioph h (none :: some)⟩ theorem dioph_pfun_vec {n} (f : vector3 ℕ n →. ℕ) : dioph_pfun f ↔ dioph (λv : vector3 ℕ (succ n), f.graph (v ∘ fs, v fz)) := ⟨λh, reindex_dioph h (fz :: fs), λh, reindex_dioph h (none :: some)⟩ theorem dioph_fn_compn {α : Type} : ∀ {n} {S : set (α ⊕ fin2 n → ℕ)} (d : dioph S) {f : vector3 ((α → ℕ) → ℕ) n} (df : vector_allp dioph_fn f), dioph (λv : α → ℕ, S (v ⊗ λi, f i v)) | 0 S d f := λdf, ext (reindex_dioph d (id ⊗ fin2.elim0)) $ λv, by refine eq.to_iff (congr_arg S $ funext $ λs, _); {cases s with a b, refl, cases b} | (succ n) S d f := f.cons_elim $ λf fl, by simp; exact λ df dfl, have dioph (λv, S (v ∘ inl ⊗ f (v ∘ inl) :: v ∘ inr)), from ext (dioph_fn_comp1 (reindex_dioph d (some ∘ inl ⊗ none :: some ∘ inr)) (reindex_dioph_fn df inl)) $ λv, by {refine eq.to_iff (congr_arg S $ funext $ λs, _); cases s with a b, refl, cases b; refl}, have dioph (λv, S (v ⊗ f v :: λ (i : fin2 n), fl i v)), from @dioph_fn_compn n (λv, S (v ∘ inl ⊗ f (v ∘ inl) :: v ∘ inr)) this _ dfl, ext this $ λv, by rw [ show cons (f v) (λ (i : fin2 n), fl i v) = λ (i : fin2 (succ n)), (f :: fl) i v, from funext $ λs, by cases s with a b; refl] theorem dioph_comp {n} {S : set (vector3 ℕ n)} (d : dioph S) (f : vector3 ((α → ℕ) → ℕ) n) (df : vector_allp dioph_fn f) : dioph (λv, S (λi, f i v)) := dioph_fn_compn (reindex_dioph d inr) df theorem dioph_fn_comp {n} {f : vector3 ℕ n → ℕ} (df : dioph_fn f) (g : vector3 ((α → ℕ) → ℕ) n) (dg : vector_allp dioph_fn g) : dioph_fn (λv, f (λi, g i v)) := dioph_comp ((dioph_fn_vec _).1 df) ((λv, v none) :: λi v, g i (v ∘ some)) $ by simp; exact ⟨proj_dioph none, (vector_allp_iff_forall _ _).2 $ λi, reindex_dioph_fn ((vector_allp_iff_forall _ _).1 dg _) _⟩ localized "notation x ` D∧ `:35 y := dioph.and_dioph x y" in dioph localized "notation x ` D∨ `:35 y := dioph.or_dioph x y" in dioph localized "notation `D∃`:30 := dioph.vec_ex1_dioph" in dioph localized "prefix `&`:max := of_nat'" in dioph theorem proj_dioph_of_nat {n : ℕ} (m : ℕ) [is_lt m n] : dioph_fn (λv : vector3 ℕ n, v &m) := proj_dioph &m localized "prefix `D&`:100 := dioph.proj_dioph_of_nat" in dioph theorem const_dioph (n : ℕ) : dioph_fn (const (α → ℕ) n) := abs_poly_dioph (poly.const n) localized "prefix `D.`:100 := dioph.const_dioph" in dioph variables {f g : (α → ℕ) → ℕ} (df : dioph_fn f) (dg : dioph_fn g) include df dg theorem dioph_comp2 {S : ℕ → ℕ → Prop} (d : dioph (λv:vector3 ℕ 2, S (v &0) (v &1))) : dioph (λv, S (f v) (g v)) := dioph_comp d [f, g] (by exact ⟨df, dg⟩) theorem dioph_fn_comp2 {h : ℕ → ℕ → ℕ} (d : dioph_fn (λv:vector3 ℕ 2, h (v &0) (v &1))) : dioph_fn (λv, h (f v) (g v)) := dioph_fn_comp d [f, g] (by exact ⟨df, dg⟩) theorem eq_dioph : dioph (λv, f v = g v) := dioph_comp2 df dg $ of_no_dummies _ (poly.proj &0 - poly.proj &1) (λv, (int.coe_nat_eq_coe_nat_iff _ _).symm.trans ⟨@sub_eq_zero_of_eq ℤ _ (v &0) (v &1), eq_of_sub_eq_zero⟩) localized "infix ` D= `:50 := dioph.eq_dioph" in dioph theorem add_dioph : dioph_fn (λv, f v + g v) := dioph_fn_comp2 df dg $ abs_poly_dioph (poly.proj &0 + poly.proj &1) localized "infix ` D+ `:80 := dioph.add_dioph" in dioph theorem mul_dioph : dioph_fn (λv, f v * g v) := dioph_fn_comp2 df dg $ abs_poly_dioph (poly.proj &0 * poly.proj &1) localized "infix ` D* `:90 := dioph.mul_dioph" in dioph theorem le_dioph : dioph (λv, f v ≤ g v) := dioph_comp2 df dg $ ext (D∃2 $ D&1 D+ D&0 D= D&2) (λv, ⟨λ⟨x, hx⟩, le.intro hx, le.dest⟩) localized "infix ` D≤ `:50 := dioph.le_dioph" in dioph theorem lt_dioph : dioph (λv, f v < g v) := df D+ (D. 1) D≤ dg localized "infix ` D< `:50 := dioph.lt_dioph" in dioph theorem ne_dioph : dioph (λv, f v ≠ g v) := ext (df D< dg D∨ dg D< df) $ λv, ne_iff_lt_or_gt.symm localized "infix ` D≠ `:50 := dioph.ne_dioph" in dioph theorem sub_dioph : dioph_fn (λv, f v - g v) := dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ ext (D&1 D= D&0 D+ D&2 D∨ D&1 D≤ D&2 D∧ D&0 D= D.0) $ (vector_all_iff_forall _).1 $ λx y z, show (y = x + z ∨ y ≤ z ∧ x = 0) ↔ y - z = x, from ⟨λo, begin rcases o with ae | ⟨yz, x0⟩, { rw [ae, nat.add_sub_cancel] }, { rw [x0, nat.sub_eq_zero_of_le yz] } end, λh, begin subst x, cases le_total y z with yz zy, { exact or.inr ⟨yz, nat.sub_eq_zero_of_le yz⟩ }, { exact or.inl (nat.sub_add_cancel zy).symm }, end⟩ localized "infix ` D- `:80 := dioph.sub_dioph" in dioph theorem dvd_dioph : dioph (λv, f v ∣ g v) := dioph_comp (D∃2 $ D&2 D= D&1 D* D&0) [f, g] (by exact ⟨df, dg⟩) localized "infix ` D∣ `:50 := dioph.dvd_dioph" in dioph theorem mod_dioph : dioph_fn (λv, f v % g v) := have dioph (λv : vector3 ℕ 3, (v &2 = 0 ∨ v &0 < v &2) ∧ ∃ (x : ℕ), v &0 + v &2 * x = v &1), from (D&2 D= D.0 D∨ D&0 D< D&2) D∧ (D∃3 $ D&1 D+ D&3 D* D&0 D= D&2), dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ ext this $ (vector_all_iff_forall _).1 $ λz x y, show ((y = 0 ∨ z < y) ∧ ∃ c, z + y * c = x) ↔ x % y = z, from ⟨λ⟨h, c, hc⟩, begin rw ← hc; simp; cases h with x0 hl, rw [x0, mod_zero], exact mod_eq_of_lt hl end, λe, by rw ← e; exact ⟨or_iff_not_imp_left.2 $ λh, mod_lt _ (nat.pos_of_ne_zero h), x / y, mod_add_div _ _⟩⟩ localized "infix ` D% `:80 := dioph.mod_dioph" in dioph theorem modeq_dioph {h : (α → ℕ) → ℕ} (dh : dioph_fn h) : dioph (λv, f v ≡ g v [MOD h v]) := df D% dh D= dg D% dh localized "notation `D≡` := dioph.modeq_dioph" in dioph theorem div_dioph : dioph_fn (λv, f v / g v) := have dioph (λv : vector3 ℕ 3, v &2 = 0 ∧ v &0 = 0 ∨ v &0 * v &2 ≤ v &1 ∧ v &1 < (v &0 + 1) * v &2), from (D&2 D= D.0 D∧ D&0 D= D.0) D∨ D&0 D* D&2 D≤ D&1 D∧ D&1 D< (D&0 D+ D.1) D* D&2, dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ ext this $ (vector_all_iff_forall _).1 $ λz x y, show y = 0 ∧ z = 0 ∨ z * y ≤ x ∧ x < (z + 1) * y ↔ x / y = z, by refine iff.trans _ eq_comm; exact y.eq_zero_or_pos.elim (λy0, by rw [y0, nat.div_zero]; exact ⟨λo, (o.resolve_right $ λ⟨_, h2⟩, nat.not_lt_zero _ h2).right, λz0, or.inl ⟨rfl, z0⟩⟩) (λypos, iff.trans ⟨λo, o.resolve_left $ λ⟨h1, _⟩, ne_of_gt ypos h1, or.inr⟩ (le_antisymm_iff.trans $ and_congr (nat.le_div_iff_mul_le _ _ ypos) $ iff.trans ⟨lt_succ_of_le, le_of_lt_succ⟩ (div_lt_iff_lt_mul _ _ ypos)).symm) localized "infix ` D/ `:80 := dioph.div_dioph" in dioph omit df dg open pell theorem pell_dioph : dioph (λv:vector3 ℕ 4, ∃ h : 1 < v &0, xn h (v &1) = v &2 ∧ yn h (v &1) = v &3) := have dioph {v : vector3 ℕ 4 | 1 < v &0 ∧ v &1 ≤ v &3 ∧ (v &2 = 1 ∧ v &3 = 0 ∨ ∃ (u w s t b : ℕ), v &2 * v &2 - (v &0 * v &0 - 1) * v &3 * v &3 = 1 ∧ u * u - (v &0 * v &0 - 1) * w * w = 1 ∧ s * s - (b * b - 1) * t * t = 1 ∧ 1 < b ∧ (b ≡ 1 [MOD 4 * v &3]) ∧ (b ≡ v &0 [MOD u]) ∧ 0 < w ∧ v &3 * v &3 ∣ w ∧ (s ≡ v &2 [MOD u]) ∧ (t ≡ v &1 [MOD 4 * v &3]))}, from D.1 D< D&0 D∧ D&1 D≤ D&3 D∧ ((D&2 D= D.1 D∧ D&3 D= D.0) D∨ (D∃4 $ D∃5 $ D∃6 $ D∃7 $ D∃8 $ D&7 D* D&7 D- (D&5 D* D&5 D- D.1) D* D&8 D* D&8 D= D.1 D∧ D&4 D* D&4 D- (D&5 D* D&5 D- D.1) D* D&3 D* D&3 D= D.1 D∧ D&2 D* D&2 D- (D&0 D* D&0 D- D.1) D* D&1 D* D&1 D= D.1 D∧ D.1 D< D&0 D∧ (D≡ (D&0) (D.1) (D.4 D* D&8)) D∧ (D≡ (D&0) (D&5) D&4) D∧ D.0 D< D&3 D∧ D&8 D* D&8 D∣ D&3 D∧ (D≡ (D&2) (D&7) D&4) D∧ (D≡ (D&1) (D&6) (D.4 D* D&8)))), dioph.ext this $ λv, matiyasevic.symm theorem xn_dioph : dioph_pfun (λv:vector3 ℕ 2, ⟨1 < v &0, λh, xn h (v &1)⟩) := have dioph (λv:vector3 ℕ 3, ∃ y, ∃ h : 1 < v &1, xn h (v &2) = v &0 ∧ yn h (v &2) = y), from let D_pell := @reindex_dioph _ (fin2 4) _ pell_dioph [&2, &3, &1, &0] in D∃3 D_pell, (dioph_pfun_vec _).2 $ dioph.ext this $ λv, ⟨λ⟨y, h, xe, ye⟩, ⟨h, xe⟩, λ⟨h, xe⟩, ⟨_, h, xe, rfl⟩⟩ include df dg /-- A version of **Matiyasevic's theorem** -/ theorem pow_dioph : dioph_fn (λv, f v ^ g v) := have dioph {v : vector3 ℕ 3 | v &2 = 0 ∧ v &0 = 1 ∨ 0 < v &2 ∧ (v &1 = 0 ∧ v &0 = 0 ∨ 0 < v &1 ∧ ∃ (w a t z x y : ℕ), (∃ (a1 : 1 < a), xn a1 (v &2) = x ∧ yn a1 (v &2) = y) ∧ (x ≡ y * (a - v &1) + v &0 [MOD t]) ∧ 2 * a * v &1 = t + (v &1 * v &1 + 1) ∧ v &0 < t ∧ v &1 ≤ w ∧ v &2 ≤ w ∧ a * a - ((w + 1) * (w + 1) - 1) * (w * z) * (w * z) = 1)}, from let D_pell := @reindex_dioph _ (fin2 9) _ pell_dioph [&4, &8, &1, &0] in (D&2 D= D.0 D∧ D&0 D= D.1) D∨ (D.0 D< D&2 D∧ ((D&1 D= D.0 D∧ D&0 D= D.0) D∨ (D.0 D< D&1 D∧ (D∃3 $ D∃4 $ D∃5 $ D∃6 $ D∃7 $ D∃8 $ D_pell D∧ (D≡ (D&1) (D&0 D* (D&4 D- D&7) D+ D&6) (D&3)) D∧ D.2 D* D&4 D* D&7 D= D&3 D+ (D&7 D* D&7 D+ D.1) D∧ D&6 D< D&3 D∧ D&7 D≤ D&5 D∧ D&8 D≤ D&5 D∧ D&4 D* D&4 D- ((D&5 D+ D.1) D* (D&5 D+ D.1) D- D.1) D* (D&5 D* D&2) D* (D&5 D* D&2) D= D.1)))), dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ dioph.ext this $ λv, iff.symm $ eq_pow_of_pell.trans $ or_congr iff.rfl $ and_congr iff.rfl $ or_congr iff.rfl $ and_congr iff.rfl $ ⟨λ⟨w, a, t, z, a1, h⟩, ⟨w, a, t, z, _, _, ⟨a1, rfl, rfl⟩, h⟩, λ⟨w, a, t, z, ._, ._, ⟨a1, rfl, rfl⟩, h⟩, ⟨w, a, t, z, a1, h⟩⟩ end end dioph
d0f8da0b76ca9d7800489a345467df2e529e1a1f
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Compiler/IR.lean
3e6c51ebf4a894704d674ae982b1cd46090024f6
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
2,948
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.Compiler.IR.Basic import Lean.Compiler.IR.Format import Lean.Compiler.IR.CompilerM import Lean.Compiler.IR.PushProj import Lean.Compiler.IR.ElimDeadVars import Lean.Compiler.IR.SimpCase import Lean.Compiler.IR.ResetReuse import Lean.Compiler.IR.NormIds import Lean.Compiler.IR.Checker import Lean.Compiler.IR.Borrow import Lean.Compiler.IR.Boxing import Lean.Compiler.IR.RC import Lean.Compiler.IR.ExpandResetReuse import Lean.Compiler.IR.UnboxResult import Lean.Compiler.IR.ElimDeadBranches import Lean.Compiler.IR.EmitC import Lean.Compiler.IR.CtorLayout import Lean.Compiler.IR.Sorry namespace Lean.IR register_builtin_option compiler.reuse : Bool := { defValue := true descr := "heuristically insert reset/reuse instruction pairs" } private def compileAux (decls : Array Decl) : CompilerM Unit := do logDecls `init decls checkDecls decls let mut decls ← elimDeadBranches decls logDecls `elim_dead_branches decls decls := decls.map Decl.pushProj logDecls `push_proj decls if compiler.reuse.get (← read) then decls := decls.map Decl.insertResetReuse logDecls `reset_reuse decls decls := decls.map Decl.elimDead logDecls `elim_dead decls decls := decls.map Decl.simpCase logDecls `simp_case decls decls := decls.map Decl.normalizeIds decls ← inferBorrow decls logDecls `borrow decls decls ← explicitBoxing decls logDecls `boxing decls decls ← explicitRC decls logDecls `rc decls if compiler.reuse.get (← read) then decls := decls.map Decl.expandResetReuse logDecls `expand_reset_reuse decls decls := decls.map Decl.pushProj logDecls `push_proj decls decls ← updateSorryDep decls logDecls `result decls checkDecls decls addDecls decls @[export lean_ir_compile] def compile (env : Environment) (opts : Options) (decls : Array Decl) : Log × (Except String Environment) := match (compileAux decls opts).run { env := env } with | EStateM.Result.ok _ s => (s.log, Except.ok s.env) | EStateM.Result.error msg s => (s.log, Except.error msg) def addBoxedVersionAux (decl : Decl) : CompilerM Unit := do let env ← getEnv if !ExplicitBoxing.requiresBoxedVersion env decl then pure () else let decl := ExplicitBoxing.mkBoxedVersion decl let decls : Array Decl := #[decl] let decls ← explicitRC decls decls.forM fun decl => modifyEnv $ fun env => addDeclAux env decl pure () -- Remark: we are ignoring the `Log` here. This should be fine. @[export lean_ir_add_boxed_version] def addBoxedVersion (env : Environment) (decl : Decl) : Except String Environment := match (addBoxedVersionAux decl Options.empty).run { env := env } with | EStateM.Result.ok _ s => Except.ok s.env | EStateM.Result.error msg s => Except.error msg end Lean.IR
78564142de3686912e0e1023a5508e300be3f09e
367134ba5a65885e863bdc4507601606690974c1
/src/topology/category/TopCommRing.lean
035577994bbdfaaddbbd9148076d5cbd847bbc00
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
3,562
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 algebra.category.CommRing.basic import topology.category.Top.basic import topology.algebra.ring /-! # Category of topological commutative rings We introduce the category `TopCommRing` of topological commutative rings together with the relevant forgetful functors to topological spaces and commutative rings. -/ universes u open category_theory /-- A bundled topological commutative ring. -/ structure TopCommRing := (α : Type u) [is_comm_ring : comm_ring α] [is_topological_space : topological_space α] [is_topological_ring : topological_ring α] namespace TopCommRing instance : has_coe_to_sort TopCommRing := { S := Type u, coe := TopCommRing.α } attribute [instance] is_comm_ring is_topological_space is_topological_ring instance : category TopCommRing.{u} := { hom := λ R S, {f : R →+* S // continuous f }, id := λ R, ⟨ring_hom.id R, by obviously⟩, -- TODO remove obviously? comp := λ R S T f g, ⟨g.val.comp f.val, begin -- TODO automate cases f, cases g, dsimp, apply continuous.comp ; assumption end⟩ } instance : concrete_category TopCommRing.{u} := { forget := { obj := λ R, R, map := λ R S f, f.val }, forget_faithful := { } } /-- Construct a bundled `TopCommRing` from the underlying type and the appropriate typeclasses. -/ def of (X : Type u) [comm_ring X] [topological_space X] [topological_ring X] : TopCommRing := ⟨X⟩ @[simp] lemma coe_of (X : Type u) [comm_ring X] [topological_space X] [topological_ring X] : (of X : Type u) = X := rfl instance forget_topological_space (R : TopCommRing) : topological_space ((forget TopCommRing).obj R) := R.is_topological_space instance forget_comm_ring (R : TopCommRing) : comm_ring ((forget TopCommRing).obj R) := R.is_comm_ring instance forget_topological_ring (R : TopCommRing) : topological_ring ((forget TopCommRing).obj R) := R.is_topological_ring instance has_forget_to_CommRing : has_forget₂ TopCommRing CommRing := has_forget₂.mk' (λ R, CommRing.of R) (λ x, rfl) (λ R S f, f.val) (λ R S f, heq.rfl) instance forget_to_CommRing_topological_space (R : TopCommRing) : topological_space ((forget₂ TopCommRing CommRing).obj R) := R.is_topological_space /-- The forgetful functor to Top. -/ instance has_forget_to_Top : has_forget₂ TopCommRing Top := has_forget₂.mk' (λ R, Top.of R) (λ x, rfl) (λ R S f, ⟨⇑f.1, f.2⟩) (λ R S f, heq.rfl) instance forget_to_Top_comm_ring (R : TopCommRing) : comm_ring ((forget₂ TopCommRing Top).obj R) := R.is_comm_ring instance forget_to_Top_topological_ring (R : TopCommRing) : topological_ring ((forget₂ TopCommRing Top).obj R) := R.is_topological_ring /-- The forgetful functors to `Type` do not reflect isomorphisms, but the forgetful functor from `TopCommRing` to `Top` does. -/ instance : reflects_isomorphisms (forget₂ TopCommRing Top) := { reflects := λ X Y f _, begin resetI, -- We have an isomorphism in `Top`, let i_Top := as_iso ((forget₂ TopCommRing Top).map f), -- and a `ring_equiv`. let e_Ring : X ≃+* Y := { ..f.1, ..((forget Top).map_iso i_Top).to_equiv }, -- Putting these together we obtain the isomorphism we're after: exact { inv := ⟨e_Ring.symm, i_Top.inv.2⟩, hom_inv_id' := by { ext x, exact e_Ring.left_inv x, }, inv_hom_id' := by { ext x, exact e_Ring.right_inv x, }, }, end } end TopCommRing
ca6810dc151e6af2173892d8282a4c6cc657ed5e
efce24474b28579aba3272fdb77177dc2b11d7aa
/src/homotopy_theory/topological_spaces/interval_endpoints.lean
dcff1e18298382ad2174a5f93fbb515ee63f50aa
[ "Apache-2.0" ]
permissive
rwbarton/lean-homotopy-theory
cff499f24268d60e1c546e7c86c33f58c62888ed
39e1b4ea1ed1b0eca2f68bc64162dde6a6396dee
refs/heads/lean-3.4.2
1,622,711,883,224
1,598,550,958,000
1,598,550,958,000
136,023,667
12
6
Apache-2.0
1,573,187,573,000
1,528,116,262,000
Lean
UTF-8
Lean
false
false
3,216
lean
import category_theory.isomorphism import .category import .colimits import .cylinder import .distrib import .homeomorphism noncomputable theory open set open category_theory namespace homotopy_theory.topological_spaces open homotopy_theory.topological_spaces.Top local notation `Top` := Top.{0} -- The set of endpoints of the unit interval, as a space. def I01_endpoints : Top := Top.mk_ob ({0, 1} : set I01) instance I01_endpoints.has_zero : has_zero I01_endpoints := ⟨⟨0, by simp⟩⟩ instance I01_endpoints.has_one : has_one I01_endpoints := ⟨⟨1, by simp⟩⟩ instance Top.point.discrete_topology : discrete_topology Top.point := ⟨eq_bot_of_singletons_open (λ ⟨⟩, by convert is_open_univ; ext p; cases p; simp)⟩ def two_endpoints : homeomorphism (* ⊔ *) I01_endpoints := let j : * ⊔ * ⟶ I01 := coprod.induced (Top.mk_hom (λ _, 0) (by continuity)) (Top.mk_hom (λ _, 1) (by continuity)) in have rj : range j = ({0, 1} : set I01), begin -- FIXME annotation should be unnecessary ext p, split, { intro h, rcases h with ⟨⟨⟨⟩⟩|⟨⟨⟩⟩, rfl⟩, { change (0 : I01) ∈ _, simp }, { change (1 : I01) ∈ _, simp } }, { intro h, have : p = 0 ∨ p = 1, by simp at h; exact h, cases this, { subst this, exact ⟨sum.inl punit.star, rfl⟩ }, { subst this, exact ⟨sum.inr punit.star, rfl⟩ } } end, have function.injective j, begin intros a b h, rcases a with ⟨⟨⟩⟩|⟨⟨⟩⟩; rcases b with ⟨⟨⟩⟩|⟨⟨⟩⟩, any_goals { refl }, { change (0 : I01) = 1 at h, have h' : (0 : ℝ) = 1 := congr_arg subtype.val h, simpa using h' }, { change (1 : I01) = 0 at h, have h' : (1 : ℝ) = 0 := congr_arg subtype.val h, simpa using h' } end, have embedding j, begin refine ⟨⟨_⟩, this⟩, change sum.topological_space = _, refine sum.discrete_topology.eq_bot.trans _, symmetry, apply eq_bot_of_singletons_open, intro e, rcases e with ⟨⟨⟩⟩|⟨⟨⟩⟩, { refine ⟨{t : I01 | t.val < 1}, is_open_lt continuous_subtype_val continuous_const, _⟩, ext p, split, { intro h, rcases p with ⟨⟨⟩⟩|⟨⟨⟩⟩, { simp }, { change (1 : ℝ) < 1 at h, have : ¬((1 : ℝ) < 1), by norm_num, contradiction } }, { intro h, simp at h, subst p, change (0 : ℝ) < 1, norm_num } }, { refine ⟨{t : I01 | t.val > 0}, is_open_lt continuous_const continuous_subtype_val, _⟩, ext p, split, { intro h, rcases p with ⟨⟨⟩⟩|⟨⟨⟩⟩, { change (0 : ℝ) > 0 at h, have : ¬((0 : ℝ) > 0), by norm_num, contradiction }, { simp } }, { intro h, simp at h, subst p, change (1 : ℝ) > 0, norm_num } } end, (homeomorphism_to_image_of_embedding this).trans (subspace_equiv_subspace rj) def prod_doubleton {X : Top} : homeomorphism (∂I.obj X) (Top.prod X I01_endpoints) := calc ∂I.obj X ≅ ∂I.obj (Top.prod X Top.point) : (∂I).map_iso (prod_singleton (by refl)) ... ≅ Top.prod X Top.point ⊔ Top.prod X Top.point : by refl ... ≅ Top.prod X (* ⊔ *) : Top.prod.distrib ... ≅ Top.prod X I01_endpoints : two_endpoints.prod_congr_right end homotopy_theory.topological_spaces
0ec412c57dd18c2aa0f383ca34a4d1628171fb27
359199d7253811b032ab92108191da7336eba86e
/src/mywork/work.lean
ede56c488034bc9a1aa18a992e90bb9af62c010f
[]
no_license
arte-et-marte/my_cs2120f21
0bc6215cb5018a3b7c90d9d399a173233f587064
91609c3609ad81fda895bee8b97cc76813241e17
refs/heads/main
1,693,298,928,348
1,634,931,202,000
1,634,931,202,000
399,946,705
0
0
null
null
null
null
UTF-8
Lean
false
false
190
lean
axiom P : ∀ ( P : Prop ), ¬(P ∧ ¬P) -- "No proposition can be both true and false." -- "For any proposition P, P is either true or not true." P ∨ ¬P -- axiom of the excluded middle
35517b45410ba6dc1ca5cbeebf084f8fe4c0c060
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/category_theory/preadditive/default.lean
cf257c117d85b9829f23ab2cd0d8720d2149838b
[ "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
9,620
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import algebra.group.hom import category_theory.limits.shapes.kernels import algebra.big_operators.basic import algebra.module.basic import category_theory.endomorphism /-! # Preadditive categories A preadditive category is a category in which `X ⟶ Y` is an abelian group in such a way that composition of morphisms is linear in both variables. This file contains a definition of preadditive category that directly encodes the definition given above. The definition could also be phrased as follows: A preadditive category is a category enriched over the category of Abelian groups. Once the general framework to state this in Lean is available, the contents of this file should become obsolete. ## Main results * Definition of preadditive categories and basic properties * In a preadditive category, `f : Q ⟶ R` is mono if and only if `g ≫ f = 0 → g = 0` for all composable `g`. * A preadditive category with kernels has equalizers. ## Implementation notes The simp normal form for negation and composition is to push negations as far as possible to the outside. For example, `f ≫ (-g)` and `(-f) ≫ g` both become `-(f ≫ g)`, and `(-f) ≫ (-g)` is simplified to `f ≫ g`. ## References * [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2] ## Tags additive, preadditive, Hom group, Ab-category, Ab-enriched -/ universes v u open category_theory.limits open_locale big_operators namespace category_theory variables (C : Type u) [category.{v} C] /-- A category is called preadditive if `P ⟶ Q` is an abelian group such that composition is linear in both variables. -/ class preadditive := (hom_group : Π P Q : C, add_comm_group (P ⟶ Q) . tactic.apply_instance) (add_comp' : ∀ (P Q R : C) (f f' : P ⟶ Q) (g : Q ⟶ R), (f + f') ≫ g = f ≫ g + f' ≫ g . obviously) (comp_add' : ∀ (P Q R : C) (f : P ⟶ Q) (g g' : Q ⟶ R), f ≫ (g + g') = f ≫ g + f ≫ g' . obviously) attribute [instance] preadditive.hom_group restate_axiom preadditive.add_comp' restate_axiom preadditive.comp_add' attribute [simp,reassoc] preadditive.add_comp attribute [reassoc] preadditive.comp_add -- (the linter doesn't like `simp` on this lemma) attribute [simp] preadditive.comp_add end category_theory open category_theory namespace category_theory namespace preadditive section preadditive open add_monoid_hom variables {C : Type u} [category.{v} C] [preadditive C] section induced_category universes u' variables {C} {D : Type u'} (F : D → C) instance induced_category.category : preadditive.{v} (induced_category C F) := { hom_group := λ P Q, @preadditive.hom_group C _ _ (F P) (F Q), add_comp' := λ P Q R f f' g, add_comp' _ _ _ _ _ _, comp_add' := λ P Q R f g g', comp_add' _ _ _ _ _ _, } end induced_category instance (X : C) : add_comm_group (End X) := by { dsimp [End], apply_instance, } instance (X : C) : ring (End X) := { left_distrib := λ f g h, preadditive.add_comp X X X g h f, right_distrib := λ f g h, preadditive.comp_add X X X h f g, ..(infer_instance : add_comm_group (End X)), ..(infer_instance : monoid (End X)) } /-- Composition by a fixed left argument as a group homomorphism -/ def left_comp {P Q : C} (R : C) (f : P ⟶ Q) : (Q ⟶ R) →+ (P ⟶ R) := mk' (λ g, f ≫ g) $ λ g g', by simp /-- Composition by a fixed right argument as a group homomorphism -/ def right_comp (P : C) {Q R : C} (g : Q ⟶ R) : (P ⟶ Q) →+ (P ⟶ R) := mk' (λ f, f ≫ g) $ λ f f', by simp variables {P Q R : C} (f f' : P ⟶ Q) (g g' : Q ⟶ R) /-- Composition as a bilinear group homomorphism -/ def comp_hom : (P ⟶ Q) →+ (Q ⟶ R) →+ (P ⟶ R) := add_monoid_hom.mk' (λ f, left_comp _ f) $ λ f₁ f₂, add_monoid_hom.ext $ λ g, (right_comp _ g).map_add f₁ f₂ @[simp, reassoc] lemma sub_comp : (f - f') ≫ g = f ≫ g - f' ≫ g := map_sub (right_comp P g) f f' -- The redundant simp lemma linter says that simp can prove the reassoc version of this lemma. @[reassoc, simp] lemma comp_sub : f ≫ (g - g') = f ≫ g - f ≫ g' := map_sub (left_comp R f) g g' @[simp, reassoc] lemma neg_comp : (-f) ≫ g = -(f ≫ g) := map_neg (right_comp P g) f /- The redundant simp lemma linter says that simp can prove the reassoc version of this lemma. -/ @[reassoc, simp] lemma comp_neg : f ≫ (-g) = -(f ≫ g) := map_neg (left_comp R f) g @[reassoc] lemma neg_comp_neg : (-f) ≫ (-g) = f ≫ g := by simp lemma nsmul_comp (n : ℕ) : (n • f) ≫ g = n • (f ≫ g) := map_nsmul (right_comp P g) f n lemma comp_nsmul (n : ℕ) : f ≫ (n • g) = n • (f ≫ g) := map_nsmul (left_comp R f) g n lemma zsmul_comp (n : ℤ) : (n • f) ≫ g = n • (f ≫ g) := map_zsmul (right_comp P g) f n lemma comp_zsmul (n : ℤ) : f ≫ (n • g) = n • (f ≫ g) := map_zsmul (left_comp R f) g n @[reassoc] lemma comp_sum {P Q R : C} {J : Type*} (s : finset J) (f : P ⟶ Q) (g : J → (Q ⟶ R)) : f ≫ ∑ j in s, g j = ∑ j in s, f ≫ g j := map_sum (left_comp R f) _ _ @[reassoc] lemma sum_comp {P Q R : C} {J : Type*} (s : finset J) (f : J → (P ⟶ Q)) (g : Q ⟶ R) : (∑ j in s, f j) ≫ g = ∑ j in s, f j ≫ g := map_sum (right_comp P g) _ _ instance {P Q : C} {f : P ⟶ Q} [epi f] : epi (-f) := ⟨λ R g g' H, by rwa [neg_comp, neg_comp, ←comp_neg, ←comp_neg, cancel_epi, neg_inj] at H⟩ instance {P Q : C} {f : P ⟶ Q} [mono f] : mono (-f) := ⟨λ R g g' H, by rwa [comp_neg, comp_neg, ←neg_comp, ←neg_comp, cancel_mono, neg_inj] at H⟩ @[priority 100] instance preadditive_has_zero_morphisms : has_zero_morphisms C := { has_zero := infer_instance, comp_zero' := λ P Q f R, show left_comp R f 0 = 0, from map_zero _, zero_comp' := λ P Q R f, show right_comp P f 0 = 0, from map_zero _ } instance module_End_right {X Y : C} : module (End Y) (X ⟶ Y) := { smul_add := λ r f g, add_comp _ _ _ _ _ _, smul_zero := λ r, zero_comp, add_smul := λ r s f, comp_add _ _ _ _ _ _, zero_smul := λ r, comp_zero } lemma mono_of_cancel_zero {Q R : C} (f : Q ⟶ R) (h : ∀ {P : C} (g : P ⟶ Q), g ≫ f = 0 → g = 0) : mono f := ⟨λ P g g' hg, sub_eq_zero.1 $ h _ $ (map_sub (right_comp P f) g g').trans $ sub_eq_zero.2 hg⟩ lemma mono_iff_cancel_zero {Q R : C} (f : Q ⟶ R) : mono f ↔ ∀ (P : C) (g : P ⟶ Q), g ≫ f = 0 → g = 0 := ⟨λ m P g, by exactI zero_of_comp_mono _, mono_of_cancel_zero f⟩ lemma mono_of_kernel_zero {X Y : C} {f : X ⟶ Y} [has_limit (parallel_pair f 0)] (w : kernel.ι f = 0) : mono f := mono_of_cancel_zero f (λ P g h, by rw [←kernel.lift_ι f g h, w, limits.comp_zero]) lemma epi_of_cancel_zero {P Q : C} (f : P ⟶ Q) (h : ∀ {R : C} (g : Q ⟶ R), f ≫ g = 0 → g = 0) : epi f := ⟨λ R g g' hg, sub_eq_zero.1 $ h _ $ (map_sub (left_comp R f) g g').trans $ sub_eq_zero.2 hg⟩ lemma epi_iff_cancel_zero {P Q : C} (f : P ⟶ Q) : epi f ↔ ∀ (R : C) (g : Q ⟶ R), f ≫ g = 0 → g = 0 := ⟨λ e R g, by exactI zero_of_epi_comp _, epi_of_cancel_zero f⟩ lemma epi_of_cokernel_zero {X Y : C} {f : X ⟶ Y} [has_colimit (parallel_pair f 0 )] (w : cokernel.π f = 0) : epi f := epi_of_cancel_zero f (λ P g h, by rw [←cokernel.π_desc f g h, w, limits.zero_comp]) open_locale zero_object variables [has_zero_object C] lemma mono_of_kernel_iso_zero {X Y : C} {f : X ⟶ Y} [has_limit (parallel_pair f 0)] (w : kernel f ≅ 0) : mono f := mono_of_kernel_zero (zero_of_source_iso_zero _ w) lemma epi_of_cokernel_iso_zero {X Y : C} {f : X ⟶ Y} [has_colimit (parallel_pair f 0)] (w : cokernel f ≅ 0) : epi f := epi_of_cokernel_zero (zero_of_target_iso_zero _ w) end preadditive section equalizers variables {C : Type u} [category.{v} C] [preadditive C] section variables {X Y : C} (f : X ⟶ Y) (g : X ⟶ Y) /-- A kernel of `f - g` is an equalizer of `f` and `g`. -/ lemma has_limit_parallel_pair [has_kernel (f - g)] : has_limit (parallel_pair f g) := has_limit.mk { cone := fork.of_ι (kernel.ι (f - g)) (sub_eq_zero.1 $ by { rw ←comp_sub, exact kernel.condition _ }), is_limit := fork.is_limit.mk _ (λ s, kernel.lift (f - g) (fork.ι s) $ by { rw comp_sub, apply sub_eq_zero.2, exact fork.condition _ }) (λ s, by simp) (λ s m h, by { ext, simpa using h walking_parallel_pair.zero }) } end section /-- If a preadditive category has all kernels, then it also has all equalizers. -/ lemma has_equalizers_of_has_kernels [has_kernels C] : has_equalizers C := @has_equalizers_of_has_limit_parallel_pair _ _ (λ _ _ f g, has_limit_parallel_pair f g) end section variables {X Y : C} (f : X ⟶ Y) (g : X ⟶ Y) /-- A cokernel of `f - g` is a coequalizer of `f` and `g`. -/ lemma has_colimit_parallel_pair [has_cokernel (f - g)] : has_colimit (parallel_pair f g) := has_colimit.mk { cocone := cofork.of_π (cokernel.π (f - g)) (sub_eq_zero.1 $ by { rw ←sub_comp, exact cokernel.condition _ }), is_colimit := cofork.is_colimit.mk _ (λ s, cokernel.desc (f - g) (cofork.π s) $ by { rw sub_comp, apply sub_eq_zero.2, exact cofork.condition _ }) (λ s, by simp) (λ s m h, by { ext, simpa using h walking_parallel_pair.one }) } end section /-- If a preadditive category has all cokernels, then it also has all coequalizers. -/ lemma has_coequalizers_of_has_cokernels [has_cokernels C] : has_coequalizers C := @has_coequalizers_of_has_colimit_parallel_pair _ _ (λ _ _ f g, has_colimit_parallel_pair f g) end end equalizers end preadditive end category_theory
85ada4f7e7d9f234ec0e0ca861b48c5756a21296
46ee5dc7248ccc9ee615639c0c003c05f58975cd
/src/modelgraphs.lean
a06075fe3c97d6b9055f3df94e883090388a75bc
[ "Apache-2.0" ]
permissive
m4lvin/tablean
e61d593b4dde6512245192c577edeb36c48f63c0
836202612fc2bfacb5545696412e7d27f7704141
refs/heads/main
1,685,613,112,076
1,676,755,678,000
1,676,755,678,000
454,064,275
8
1
null
null
null
null
UTF-8
Lean
false
false
4,433
lean
-- MODELGRAPHS import syntax import semantics open formula -- Definition 18, page 31 def saturated : finset formula → Prop | X := ∀ P Q : formula, ( ~~P ∈ X → P ∈ X ) ∧ ( P⋏Q ∈ X → P ∈ X ∧ Q ∈ X ) ∧ ( ~(P⋏Q) ∈ X → ~P ∈ X ∨ ~Q ∈ X ) -- TODO: closure for program combinators! -- Definition 19, page 31 -- TODO: change [] to [A] later @[simp] def modelGraph ( Worlds : finset (finset formula) ) := let W := subtype (λ x, x ∈ Worlds), i := ∀ X : W, saturated X.val ∧ ⊥ ∉ X.val ∧ (∀ P, P ∈ X.val → ~P ∉ X.val), ii := λ M : kripkeModel W, (∀ (X : W) pp, ((·pp) ∈ X.val ↔ M.val X pp)), -- Note: Borzechowski only has → in ii. We follow BRV, Def 4.18 and 4.84. iii := λ M : kripkeModel W, ∀ (X Y : W) P, M.rel X Y → □P ∈ X.val → P ∈ Y.val, iv := λ M : kripkeModel W, ∀ (X : W) P, ~□P ∈ X.val → ∃ Y, M.rel X Y ∧ ~P ∈ Y.val in subtype ( λ M : kripkeModel W , i ∧ ii M ∧ iii M ∧ iv M ) -- Lemma 9, page 32 lemma truthLemma { Worlds : finset (finset formula) } (MG : modelGraph Worlds) : ∀ X : Worlds, ∀ P, P ∈ X.val → evaluate (MG.val,X) P := begin intros X P, cases MG with M M_prop, rcases M_prop with ⟨ i, ii, iii, iv ⟩, -- induction loading!! let plus := λ P (X : Worlds), P ∈ X.val → evaluate (M,X) P, let minus := λ P (X : Worlds), ~P ∈ X.val → ¬ evaluate (M,X) P, let oh := λ P (X : Worlds), □P ∈ X.val → ∀ Y, M.rel X Y → P ∈ Y.val, have claim : ∀ P X, plus P X ∧ minus P X ∧ oh P X, { intro P, induction P, all_goals { intro X, }, case bottom : { specialize i X, rcases i with ⟨_, bot_not_in_X, _ ⟩, repeat { split }, { intro P_in_X, apply absurd P_in_X bot_not_in_X, }, { intro notP_in_X, tauto, }, { intros boxBot_in_X Y X_rel_Y, exact iii X Y ⊥ X_rel_Y boxBot_in_X }, }, case atom_prop : pp { repeat { split }, { intro P_in_X, unfold evaluate, rw (ii X pp) at P_in_X, exact P_in_X, }, { intro notP_in_X, unfold evaluate, rw ← ii X pp, rcases i X with ⟨ _, _, P_in_then_notP_not_in ⟩, specialize P_in_then_notP_not_in (· pp), tauto, }, { intros boxPp_in_X Y X_rel_Y, exact iii X Y (· pp) X_rel_Y boxPp_in_X, }, }, case neg : P IH { rcases IH X with ⟨ plus_IH, minus_IH, oh_OH ⟩, repeat { split }, { intro notP_in_X, unfold evaluate, exact minus_IH notP_in_X, }, { intro notnotP_in_X, rcases i X with ⟨X_saturated, _, _ ⟩, cases X_saturated P ⊥ with doubleNeg, -- ⊥ is unused! unfold evaluate, simp, exact plus_IH (doubleNeg notnotP_in_X), }, { intros notPp_in_X Y X_rel_Y, exact iii X Y (~P) X_rel_Y notPp_in_X, }, }, case and : P Q IH_P IH_Q { rcases IH_P X with ⟨ plus_IH_P, minus_IH_P, oh_P ⟩, rcases IH_Q X with ⟨ plus_IH_Q, minus_IH_Q, oh_Q ⟩, rcases i X with ⟨X_saturated, _, _ ⟩, unfold saturated at X_saturated, rcases X_saturated P Q with ⟨ doubleNeg, andSplit, notAndSplit ⟩, repeat { split }, { intro PandQ_in_X, specialize andSplit PandQ_in_X, cases andSplit with P_in_X Q_in_X, unfold evaluate, split, { exact plus_IH_P P_in_X }, { exact plus_IH_Q Q_in_X, } }, { intro notPandQ_in_X, unfold evaluate, rw not_and_distrib, specialize notAndSplit notPandQ_in_X, cases notAndSplit with notP_in_X notQ_in_X, { left, exact minus_IH_P notP_in_X }, { right, exact minus_IH_Q notQ_in_X, }, }, { intros PandQ_in_X Y X_rel_Y, exact iii X Y (P ⋏ Q) X_rel_Y PandQ_in_X, } }, case box : P IH { repeat { split }, { intro boxP_in_X, unfold evaluate, intros Y X_rel_Y, rcases IH Y with ⟨ plus_IH_Y, _, _ ⟩, apply plus_IH_Y, rcases IH X with ⟨ _, _, oh_IH_X ⟩, exact oh_IH_X boxP_in_X Y X_rel_Y, }, { intro notBoxP_in_X, unfold evaluate, push_neg, rcases iv X P notBoxP_in_X with ⟨ Y, X_rel_Y, notP_in_Y ⟩, use Y, split, exact X_rel_Y, rcases IH Y with ⟨ _, minus_IH_Y, _ ⟩, exact minus_IH_Y notP_in_Y, }, { intros boxBoxP_in_X Y X_rel_Y, exact iii X Y (□P) X_rel_Y boxBoxP_in_X, } }, }, apply (claim P X).left, end
6827788d7516a5349137ae46d02cc512fde152d3
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/order/filter/extr.lean
2bb6a8b75f4470183d824e3856b3422e6e7a0b1c
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
21,252
lean
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import order.filter.basic /-! # Minimum and maximum w.r.t. a filter and on a aet ## Main Definitions This file defines six predicates of the form `is_A_B`, where `A` is `min`, `max`, or `extr`, and `B` is `filter` or `on`. * `is_min_filter f l a` means that `f a ≤ f x` in some `l`-neighborhood of `a`; * `is_max_filter f l a` means that `f x ≤ f a` in some `l`-neighborhood of `a`; * `is_extr_filter f l a` means `is_min_filter f l a` or `is_max_filter f l a`. Similar predicates with `_on` suffix are particular cases for `l = 𝓟 s`. ## Main statements ### Change of the filter (set) argument * `is_*_filter.filter_mono` : replace the filter with a smaller one; * `is_*_filter.filter_inf` : replace a filter `l` with `l ⊓ l'`; * `is_*_on.on_subset` : restrict to a smaller set; * `is_*_on.inter` : replace a set `s` wtih `s ∩ t`. ### Composition * `is_*_*.comp_mono` : if `x` is an extremum for `f` and `g` is a monotone function, then `x` is an extremum for `g ∘ f`; * `is_*_*.comp_antimono` : similarly for the case of monotonically decreasing `g`; * `is_*_*.bicomp_mono` : if `x` is an extremum of the same type for `f` and `g` and a binary operation `op` is monotone in both arguments, then `x` is an extremum of the same type for `λ x, op (f x) (g x)`. * `is_*_filter.comp_tendsto` : if `g x` is an extremum for `f` w.r.t. `l'` and `tendsto g l l'`, then `x` is an extremum for `f ∘ g` w.r.t. `l`. * `is_*_on.on_preimage` : if `g x` is an extremum for `f` on `s`, then `x` is an extremum for `f ∘ g` on `g ⁻¹' s`. ### Algebraic operations * `is_*_*.add` : if `x` is an extremum of the same type for two functions, then it is an extremum of the same type for their sum; * `is_*_*.neg` : if `x` is an extremum for `f`, then it is an extremum of the opposite type for `-f`; * `is_*_*.sub` : if `x` is an a minimum for `f` and a maximum for `g`, then it is a minimum for `f - g` and a maximum for `g - f`; * `is_*_*.max`, `is_*_*.min`, `is_*_*.sup`, `is_*_*.inf` : similarly for `is_*_*.add` for pointwise `max`, `min`, `sup`, `inf`, respectively. ### Miscellaneous definitions * `is_*_*_const` : any point is both a minimum and maximum for a constant function; * `is_min/max_*.is_ext` : any minimum/maximum point is an extremum; * `is_*_*.dual`, `is_*_*.undual`: conversion between codomains `α` and `dual α`; ## Missing features (TODO) * Multiplication and division; * `is_*_*.bicompl` : if `x` is a minimum for `f`, `y` is a minimum for `g`, and `op` is a monotone binary operation, then `(x, y)` is a minimum for `uncurry (bicompl op f g)`. From this point of view, `is_*_*.bicomp` is a composition * It would be nice to have a tactic that specializes `comp_(anti)mono` or `bicomp_mono` based on a proof of monotonicity of a given (binary) function. The tactic should maintain a `meta` list of known (anti)monotone (binary) functions with their names, as well as a list of special types of filters, and define the missing lemmas once one of these two lists grows. -/ universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} open set filter open_locale filter section preorder variables [preorder β] [preorder γ] variables (f : α → β) (s : set α) (l : filter α) (a : α) /-! ### Definitions -/ /-- `is_min_filter f l a` means that `f a ≤ f x` in some `l`-neighborhood of `a` -/ def is_min_filter : Prop := ∀ᶠ x in l, f a ≤ f x /-- `is_max_filter f l a` means that `f x ≤ f a` in some `l`-neighborhood of `a` -/ def is_max_filter : Prop := ∀ᶠ x in l, f x ≤ f a /-- `is_extr_filter f l a` means `is_min_filter f l a` or `is_max_filter f l a` -/ def is_extr_filter : Prop := is_min_filter f l a ∨ is_max_filter f l a /-- `is_min_on f s a` means that `f a ≤ f x` for all `x ∈ a`. Note that we do not assume `a ∈ s`. -/ def is_min_on := is_min_filter f (𝓟 s) a /-- `is_max_on f s a` means that `f x ≤ f a` for all `x ∈ a`. Note that we do not assume `a ∈ s`. -/ def is_max_on := is_max_filter f (𝓟 s) a /-- `is_extr_on f s a` means `is_min_on f s a` or `is_max_on f s a` -/ def is_extr_on : Prop := is_extr_filter f (𝓟 s) a variables {f s a l} {t : set α} {l' : filter α} lemma is_extr_on.elim {p : Prop} : is_extr_on f s a → (is_min_on f s a → p) → (is_max_on f s a → p) → p := or.elim lemma is_min_on_iff : is_min_on f s a ↔ ∀ x ∈ s, f a ≤ f x := iff.rfl lemma is_max_on_iff : is_max_on f s a ↔ ∀ x ∈ s, f x ≤ f a := iff.rfl lemma is_min_on_univ_iff : is_min_on f univ a ↔ ∀ x, f a ≤ f x := univ_subset_iff.trans eq_univ_iff_forall lemma is_max_on_univ_iff : is_max_on f univ a ↔ ∀ x, f x ≤ f a := univ_subset_iff.trans eq_univ_iff_forall lemma is_min_filter.tendsto_principal_Ici (h : is_min_filter f l a) : tendsto f l (𝓟 $ Ici (f a)) := tendsto_principal.2 h lemma is_max_filter.tendsto_principal_Iic (h : is_max_filter f l a) : tendsto f l (𝓟 $ Iic (f a)) := tendsto_principal.2 h /-! ### Conversion to `is_extr_*` -/ lemma is_min_filter.is_extr : is_min_filter f l a → is_extr_filter f l a := or.inl lemma is_max_filter.is_extr : is_max_filter f l a → is_extr_filter f l a := or.inr lemma is_min_on.is_extr (h : is_min_on f s a) : is_extr_on f s a := h.is_extr lemma is_max_on.is_extr (h : is_max_on f s a) : is_extr_on f s a := h.is_extr /-! ### Constant function -/ lemma is_min_filter_const {b : β} : is_min_filter (λ _, b) l a := univ_mem' $ λ _, le_refl _ lemma is_max_filter_const {b : β} : is_max_filter (λ _, b) l a := univ_mem' $ λ _, le_refl _ lemma is_extr_filter_const {b : β} : is_extr_filter (λ _, b) l a := is_min_filter_const.is_extr lemma is_min_on_const {b : β} : is_min_on (λ _, b) s a := is_min_filter_const lemma is_max_on_const {b : β} : is_max_on (λ _, b) s a := is_max_filter_const lemma is_extr_on_const {b : β} : is_extr_on (λ _, b) s a := is_extr_filter_const /-! ### Order dual -/ lemma is_min_filter_dual_iff : @is_min_filter α (order_dual β) _ f l a ↔ is_max_filter f l a := iff.rfl lemma is_max_filter_dual_iff : @is_max_filter α (order_dual β) _ f l a ↔ is_min_filter f l a := iff.rfl lemma is_extr_filter_dual_iff : @is_extr_filter α (order_dual β) _ f l a ↔ is_extr_filter f l a := or_comm _ _ alias is_min_filter_dual_iff ↔ is_min_filter.undual is_max_filter.dual alias is_max_filter_dual_iff ↔ is_max_filter.undual is_min_filter.dual alias is_extr_filter_dual_iff ↔ is_extr_filter.undual is_extr_filter.dual lemma is_min_on_dual_iff : @is_min_on α (order_dual β) _ f s a ↔ is_max_on f s a := iff.rfl lemma is_max_on_dual_iff : @is_max_on α (order_dual β) _ f s a ↔ is_min_on f s a := iff.rfl lemma is_extr_on_dual_iff : @is_extr_on α (order_dual β) _ f s a ↔ is_extr_on f s a := or_comm _ _ alias is_min_on_dual_iff ↔ is_min_on.undual is_max_on.dual alias is_max_on_dual_iff ↔ is_max_on.undual is_min_on.dual alias is_extr_on_dual_iff ↔ is_extr_on.undual is_extr_on.dual /-! ### Operations on the filter/set -/ lemma is_min_filter.filter_mono (h : is_min_filter f l a) (hl : l' ≤ l) : is_min_filter f l' a := hl h lemma is_max_filter.filter_mono (h : is_max_filter f l a) (hl : l' ≤ l) : is_max_filter f l' a := hl h lemma is_extr_filter.filter_mono (h : is_extr_filter f l a) (hl : l' ≤ l) : is_extr_filter f l' a := h.elim (λ h, (h.filter_mono hl).is_extr) (λ h, (h.filter_mono hl).is_extr) lemma is_min_filter.filter_inf (h : is_min_filter f l a) (l') : is_min_filter f (l ⊓ l') a := h.filter_mono inf_le_left lemma is_max_filter.filter_inf (h : is_max_filter f l a) (l') : is_max_filter f (l ⊓ l') a := h.filter_mono inf_le_left lemma is_extr_filter.filter_inf (h : is_extr_filter f l a) (l') : is_extr_filter f (l ⊓ l') a := h.filter_mono inf_le_left lemma is_min_on.on_subset (hf : is_min_on f t a) (h : s ⊆ t) : is_min_on f s a := hf.filter_mono $ principal_mono.2 h lemma is_max_on.on_subset (hf : is_max_on f t a) (h : s ⊆ t) : is_max_on f s a := hf.filter_mono $ principal_mono.2 h lemma is_extr_on.on_subset (hf : is_extr_on f t a) (h : s ⊆ t) : is_extr_on f s a := hf.filter_mono $ principal_mono.2 h lemma is_min_on.inter (hf : is_min_on f s a) (t) : is_min_on f (s ∩ t) a := hf.on_subset (inter_subset_left s t) lemma is_max_on.inter (hf : is_max_on f s a) (t) : is_max_on f (s ∩ t) a := hf.on_subset (inter_subset_left s t) lemma is_extr_on.inter (hf : is_extr_on f s a) (t) : is_extr_on f (s ∩ t) a := hf.on_subset (inter_subset_left s t) /-! ### Composition with (anti)monotone functions -/ lemma is_min_filter.comp_mono (hf : is_min_filter f l a) {g : β → γ} (hg : monotone g) : is_min_filter (g ∘ f) l a := mem_of_superset hf $ λ x hx, hg hx lemma is_max_filter.comp_mono (hf : is_max_filter f l a) {g : β → γ} (hg : monotone g) : is_max_filter (g ∘ f) l a := mem_of_superset hf $ λ x hx, hg hx lemma is_extr_filter.comp_mono (hf : is_extr_filter f l a) {g : β → γ} (hg : monotone g) : is_extr_filter (g ∘ f) l a := hf.elim (λ hf, (hf.comp_mono hg).is_extr) (λ hf, (hf.comp_mono hg).is_extr) lemma is_min_filter.comp_antimono (hf : is_min_filter f l a) {g : β → γ} (hg : ∀ ⦃x y⦄, x ≤ y → g y ≤ g x) : is_max_filter (g ∘ f) l a := hf.dual.comp_mono (λ x y h, hg h) lemma is_max_filter.comp_antimono (hf : is_max_filter f l a) {g : β → γ} (hg : ∀ ⦃x y⦄, x ≤ y → g y ≤ g x) : is_min_filter (g ∘ f) l a := hf.dual.comp_mono (λ x y h, hg h) lemma is_extr_filter.comp_antimono (hf : is_extr_filter f l a) {g : β → γ} (hg : ∀ ⦃x y⦄, x ≤ y → g y ≤ g x) : is_extr_filter (g ∘ f) l a := hf.dual.comp_mono (λ x y h, hg h) lemma is_min_on.comp_mono (hf : is_min_on f s a) {g : β → γ} (hg : monotone g) : is_min_on (g ∘ f) s a := hf.comp_mono hg lemma is_max_on.comp_mono (hf : is_max_on f s a) {g : β → γ} (hg : monotone g) : is_max_on (g ∘ f) s a := hf.comp_mono hg lemma is_extr_on.comp_mono (hf : is_extr_on f s a) {g : β → γ} (hg : monotone g) : is_extr_on (g ∘ f) s a := hf.comp_mono hg lemma is_min_on.comp_antimono (hf : is_min_on f s a) {g : β → γ} (hg : ∀ ⦃x y⦄, x ≤ y → g y ≤ g x) : is_max_on (g ∘ f) s a := hf.comp_antimono hg lemma is_max_on.comp_antimono (hf : is_max_on f s a) {g : β → γ} (hg : ∀ ⦃x y⦄, x ≤ y → g y ≤ g x) : is_min_on (g ∘ f) s a := hf.comp_antimono hg lemma is_extr_on.comp_antimono (hf : is_extr_on f s a) {g : β → γ} (hg : ∀ ⦃x y⦄, x ≤ y → g y ≤ g x) : is_extr_on (g ∘ f) s a := hf.comp_antimono hg lemma is_min_filter.bicomp_mono [preorder δ] {op : β → γ → δ} (hop : ((≤) ⇒ (≤) ⇒ (≤)) op op) (hf : is_min_filter f l a) {g : α → γ} (hg : is_min_filter g l a) : is_min_filter (λ x, op (f x) (g x)) l a := mem_of_superset (inter_mem hf hg) $ λ x ⟨hfx, hgx⟩, hop hfx hgx lemma is_max_filter.bicomp_mono [preorder δ] {op : β → γ → δ} (hop : ((≤) ⇒ (≤) ⇒ (≤)) op op) (hf : is_max_filter f l a) {g : α → γ} (hg : is_max_filter g l a) : is_max_filter (λ x, op (f x) (g x)) l a := mem_of_superset (inter_mem hf hg) $ λ x ⟨hfx, hgx⟩, hop hfx hgx -- No `extr` version because we need `hf` and `hg` to be of the same kind lemma is_min_on.bicomp_mono [preorder δ] {op : β → γ → δ} (hop : ((≤) ⇒ (≤) ⇒ (≤)) op op) (hf : is_min_on f s a) {g : α → γ} (hg : is_min_on g s a) : is_min_on (λ x, op (f x) (g x)) s a := hf.bicomp_mono hop hg lemma is_max_on.bicomp_mono [preorder δ] {op : β → γ → δ} (hop : ((≤) ⇒ (≤) ⇒ (≤)) op op) (hf : is_max_on f s a) {g : α → γ} (hg : is_max_on g s a) : is_max_on (λ x, op (f x) (g x)) s a := hf.bicomp_mono hop hg /-! ### Composition with `tendsto` -/ lemma is_min_filter.comp_tendsto {g : δ → α} {l' : filter δ} {b : δ} (hf : is_min_filter f l (g b)) (hg : tendsto g l' l) : is_min_filter (f ∘ g) l' b := hg hf lemma is_max_filter.comp_tendsto {g : δ → α} {l' : filter δ} {b : δ} (hf : is_max_filter f l (g b)) (hg : tendsto g l' l) : is_max_filter (f ∘ g) l' b := hg hf lemma is_extr_filter.comp_tendsto {g : δ → α} {l' : filter δ} {b : δ} (hf : is_extr_filter f l (g b)) (hg : tendsto g l' l) : is_extr_filter (f ∘ g) l' b := hf.elim (λ hf, (hf.comp_tendsto hg).is_extr) (λ hf, (hf.comp_tendsto hg).is_extr) lemma is_min_on.on_preimage (g : δ → α) {b : δ} (hf : is_min_on f s (g b)) : is_min_on (f ∘ g) (g ⁻¹' s) b := hf.comp_tendsto (tendsto_principal_principal.mpr $ subset.refl _) lemma is_max_on.on_preimage (g : δ → α) {b : δ} (hf : is_max_on f s (g b)) : is_max_on (f ∘ g) (g ⁻¹' s) b := hf.comp_tendsto (tendsto_principal_principal.mpr $ subset.refl _) lemma is_extr_on.on_preimage (g : δ → α) {b : δ} (hf : is_extr_on f s (g b)) : is_extr_on (f ∘ g) (g ⁻¹' s) b := hf.elim (λ hf, (hf.on_preimage g).is_extr) (λ hf, (hf.on_preimage g).is_extr) end preorder /-! ### Pointwise addition -/ section ordered_add_comm_monoid variables [ordered_add_comm_monoid β] {f g : α → β} {a : α} {s : set α} {l : filter α} lemma is_min_filter.add (hf : is_min_filter f l a) (hg : is_min_filter g l a) : is_min_filter (λ x, f x + g x) l a := show is_min_filter (λ x, f x + g x) l a, from hf.bicomp_mono (λ x x' hx y y' hy, add_le_add hx hy) hg lemma is_max_filter.add (hf : is_max_filter f l a) (hg : is_max_filter g l a) : is_max_filter (λ x, f x + g x) l a := show is_max_filter (λ x, f x + g x) l a, from hf.bicomp_mono (λ x x' hx y y' hy, add_le_add hx hy) hg lemma is_min_on.add (hf : is_min_on f s a) (hg : is_min_on g s a) : is_min_on (λ x, f x + g x) s a := hf.add hg lemma is_max_on.add (hf : is_max_on f s a) (hg : is_max_on g s a) : is_max_on (λ x, f x + g x) s a := hf.add hg end ordered_add_comm_monoid /-! ### Pointwise negation and subtraction -/ section ordered_add_comm_group variables [ordered_add_comm_group β] {f g : α → β} {a : α} {s : set α} {l : filter α} lemma is_min_filter.neg (hf : is_min_filter f l a) : is_max_filter (λ x, -f x) l a := hf.comp_antimono (λ x y hx, neg_le_neg hx) lemma is_max_filter.neg (hf : is_max_filter f l a) : is_min_filter (λ x, -f x) l a := hf.comp_antimono (λ x y hx, neg_le_neg hx) lemma is_extr_filter.neg (hf : is_extr_filter f l a) : is_extr_filter (λ x, -f x) l a := hf.elim (λ hf, hf.neg.is_extr) (λ hf, hf.neg.is_extr) lemma is_min_on.neg (hf : is_min_on f s a) : is_max_on (λ x, -f x) s a := hf.comp_antimono (λ x y hx, neg_le_neg hx) lemma is_max_on.neg (hf : is_max_on f s a) : is_min_on (λ x, -f x) s a := hf.comp_antimono (λ x y hx, neg_le_neg hx) lemma is_extr_on.neg (hf : is_extr_on f s a) : is_extr_on (λ x, -f x) s a := hf.elim (λ hf, hf.neg.is_extr) (λ hf, hf.neg.is_extr) lemma is_min_filter.sub (hf : is_min_filter f l a) (hg : is_max_filter g l a) : is_min_filter (λ x, f x - g x) l a := by simpa only [sub_eq_add_neg] using hf.add hg.neg lemma is_max_filter.sub (hf : is_max_filter f l a) (hg : is_min_filter g l a) : is_max_filter (λ x, f x - g x) l a := by simpa only [sub_eq_add_neg] using hf.add hg.neg lemma is_min_on.sub (hf : is_min_on f s a) (hg : is_max_on g s a) : is_min_on (λ x, f x - g x) s a := by simpa only [sub_eq_add_neg] using hf.add hg.neg lemma is_max_on.sub (hf : is_max_on f s a) (hg : is_min_on g s a) : is_max_on (λ x, f x - g x) s a := by simpa only [sub_eq_add_neg] using hf.add hg.neg end ordered_add_comm_group /-! ### Pointwise `sup`/`inf` -/ section semilattice_sup variables [semilattice_sup β] {f g : α → β} {a : α} {s : set α} {l : filter α} lemma is_min_filter.sup (hf : is_min_filter f l a) (hg : is_min_filter g l a) : is_min_filter (λ x, f x ⊔ g x) l a := show is_min_filter (λ x, f x ⊔ g x) l a, from hf.bicomp_mono (λ x x' hx y y' hy, sup_le_sup hx hy) hg lemma is_max_filter.sup (hf : is_max_filter f l a) (hg : is_max_filter g l a) : is_max_filter (λ x, f x ⊔ g x) l a := show is_max_filter (λ x, f x ⊔ g x) l a, from hf.bicomp_mono (λ x x' hx y y' hy, sup_le_sup hx hy) hg lemma is_min_on.sup (hf : is_min_on f s a) (hg : is_min_on g s a) : is_min_on (λ x, f x ⊔ g x) s a := hf.sup hg lemma is_max_on.sup (hf : is_max_on f s a) (hg : is_max_on g s a) : is_max_on (λ x, f x ⊔ g x) s a := hf.sup hg end semilattice_sup section semilattice_inf variables [semilattice_inf β] {f g : α → β} {a : α} {s : set α} {l : filter α} lemma is_min_filter.inf (hf : is_min_filter f l a) (hg : is_min_filter g l a) : is_min_filter (λ x, f x ⊓ g x) l a := show is_min_filter (λ x, f x ⊓ g x) l a, from hf.bicomp_mono (λ x x' hx y y' hy, inf_le_inf hx hy) hg lemma is_max_filter.inf (hf : is_max_filter f l a) (hg : is_max_filter g l a) : is_max_filter (λ x, f x ⊓ g x) l a := show is_max_filter (λ x, f x ⊓ g x) l a, from hf.bicomp_mono (λ x x' hx y y' hy, inf_le_inf hx hy) hg lemma is_min_on.inf (hf : is_min_on f s a) (hg : is_min_on g s a) : is_min_on (λ x, f x ⊓ g x) s a := hf.inf hg lemma is_max_on.inf (hf : is_max_on f s a) (hg : is_max_on g s a) : is_max_on (λ x, f x ⊓ g x) s a := hf.inf hg end semilattice_inf /-! ### Pointwise `min`/`max` -/ section linear_order variables [linear_order β] {f g : α → β} {a : α} {s : set α} {l : filter α} lemma is_min_filter.min (hf : is_min_filter f l a) (hg : is_min_filter g l a) : is_min_filter (λ x, min (f x) (g x)) l a := show is_min_filter (λ x, min (f x) (g x)) l a, from hf.bicomp_mono (λ x x' hx y y' hy, min_le_min hx hy) hg lemma is_max_filter.min (hf : is_max_filter f l a) (hg : is_max_filter g l a) : is_max_filter (λ x, min (f x) (g x)) l a := show is_max_filter (λ x, min (f x) (g x)) l a, from hf.bicomp_mono (λ x x' hx y y' hy, min_le_min hx hy) hg lemma is_min_on.min (hf : is_min_on f s a) (hg : is_min_on g s a) : is_min_on (λ x, min (f x) (g x)) s a := hf.min hg lemma is_max_on.min (hf : is_max_on f s a) (hg : is_max_on g s a) : is_max_on (λ x, min (f x) (g x)) s a := hf.min hg lemma is_min_filter.max (hf : is_min_filter f l a) (hg : is_min_filter g l a) : is_min_filter (λ x, max (f x) (g x)) l a := show is_min_filter (λ x, max (f x) (g x)) l a, from hf.bicomp_mono (λ x x' hx y y' hy, max_le_max hx hy) hg lemma is_max_filter.max (hf : is_max_filter f l a) (hg : is_max_filter g l a) : is_max_filter (λ x, max (f x) (g x)) l a := show is_max_filter (λ x, max (f x) (g x)) l a, from hf.bicomp_mono (λ x x' hx y y' hy, max_le_max hx hy) hg lemma is_min_on.max (hf : is_min_on f s a) (hg : is_min_on g s a) : is_min_on (λ x, max (f x) (g x)) s a := hf.max hg lemma is_max_on.max (hf : is_max_on f s a) (hg : is_max_on g s a) : is_max_on (λ x, max (f x) (g x)) s a := hf.max hg end linear_order section eventually /-! ### Relation with `eventually` comparisons of two functions -/ lemma filter.eventually_le.is_max_filter {α β : Type*} [preorder β] {f g : α → β} {a : α} {l : filter α} (hle : g ≤ᶠ[l] f) (hfga : f a = g a) (h : is_max_filter f l a) : is_max_filter g l a := begin refine hle.mp (h.mono $ λ x hf hgf, _), rw ← hfga, exact le_trans hgf hf end lemma is_max_filter.congr {α β : Type*} [preorder β] {f g : α → β} {a : α} {l : filter α} (h : is_max_filter f l a) (heq : f =ᶠ[l] g) (hfga : f a = g a) : is_max_filter g l a := heq.symm.le.is_max_filter hfga h lemma filter.eventually_eq.is_max_filter_iff {α β : Type*} [preorder β] {f g : α → β} {a : α} {l : filter α} (heq : f =ᶠ[l] g) (hfga : f a = g a) : is_max_filter f l a ↔ is_max_filter g l a := ⟨λ h, h.congr heq hfga, λ h, h.congr heq.symm hfga.symm⟩ lemma filter.eventually_le.is_min_filter {α β : Type*} [preorder β] {f g : α → β} {a : α} {l : filter α} (hle : f ≤ᶠ[l] g) (hfga : f a = g a) (h : is_min_filter f l a) : is_min_filter g l a := @filter.eventually_le.is_max_filter _ (order_dual β) _ _ _ _ _ hle hfga h lemma is_min_filter.congr {α β : Type*} [preorder β] {f g : α → β} {a : α} {l : filter α} (h : is_min_filter f l a) (heq : f =ᶠ[l] g) (hfga : f a = g a) : is_min_filter g l a := heq.le.is_min_filter hfga h lemma filter.eventually_eq.is_min_filter_iff {α β : Type*} [preorder β] {f g : α → β} {a : α} {l : filter α} (heq : f =ᶠ[l] g) (hfga : f a = g a) : is_min_filter f l a ↔ is_min_filter g l a := ⟨λ h, h.congr heq hfga, λ h, h.congr heq.symm hfga.symm⟩ lemma is_extr_filter.congr {α β : Type*} [preorder β] {f g : α → β} {a : α} {l : filter α} (h : is_extr_filter f l a) (heq : f =ᶠ[l] g) (hfga : f a = g a) : is_extr_filter g l a := begin rw is_extr_filter at *, rwa [← heq.is_max_filter_iff hfga, ← heq.is_min_filter_iff hfga], end lemma filter.eventually_eq.is_extr_filter_iff {α β : Type*} [preorder β] {f g : α → β} {a : α} {l : filter α} (heq : f =ᶠ[l] g) (hfga : f a = g a) : is_extr_filter f l a ↔ is_extr_filter g l a := ⟨λ h, h.congr heq hfga, λ h, h.congr heq.symm hfga.symm⟩ end eventually
881985a568697949a17b1e4551247a9a75648115
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/unfold_cases.lean
0c258e189b88ef8217a1ffa7650d4eabb3f8549c
[ "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
3,052
lean
/- Copyright (c) 2020 Dany Fabian. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Dany Fabian -/ import tactic.unfold_cases open tactic variable {α : Type*} inductive color | red | black inductive node (α) | leaf {} : node | tree {} (color : color) (left : node) (val : α) (right : node) : node /-- this function creates 122 cases as opposed to the 5 we see here. -/ def balance_eqn_compiler {α} : color → node α → α → node α → node α | color.black (node.tree color.red (node.tree color.red a x b) y c) z d := node.tree color.red (node.tree color.black a x b) y (node.tree color.black c z d) | color.black (node.tree color.red a x (node.tree color.red b y c)) z d := node.tree color.red (node.tree color.black a x b) y (node.tree color.black c z d) | color.black a x (node.tree color.red (node.tree color.red b y c) z d) := node.tree color.red (node.tree color.black a x b) y (node.tree color.black c z d) | color.black a x (node.tree color.red b y (node.tree color.red c z d)) := node.tree color.red (node.tree color.black a x b) y (node.tree color.black c z d) | color a x b := node.tree color a x b example : ∀ a (x:α) b y c z d, balance_eqn_compiler color.black (node.tree color.red (node.tree color.red a x b) y c) z d = node.tree color.red (node.tree color.black a x b) y (node.tree color.black c z d) := begin unfold_cases { refl }, end /-- this function creates 122 cases as opposed to the 5 we see here. -/ def balance_match {α} (c:color) (l:node α) (v:α) (r:node α) : node α := match c, l, v, r with | color.black, node.tree color.red (node.tree color.red a x b) y c, z, d := node.tree color.red (node.tree color.black a x b) y (node.tree color.black c z d) | color.black, node.tree color.red a x (node.tree color.red b y c), z, d := node.tree color.red (node.tree color.black a x b) y (node.tree color.black c z d) | color.black, a, x, node.tree color.red (node.tree color.red b y c) z d := node.tree color.red (node.tree color.black a x b) y (node.tree color.black c z d) | color.black, a, x, node.tree color.red b y (node.tree color.red c z d) := node.tree color.red (node.tree color.black a x b) y (node.tree color.black c z d) | color, a, x, b := node.tree color a x b end example : ∀ a (x:α) b y c z d, balance_match color.black (node.tree color.red (node.tree color.red a x b) y c) z d = node.tree color.red (node.tree color.black a x b) y (node.tree color.black c z d) := begin unfold_cases { refl }, end def foo : ℕ → ℕ → ℕ | 0 0 := 17 | (n+2) 17 := 17 | 1 0 := 23 | 0 (n+18) := 15 | 0 17 := 17 | 1 17 := 17 | _ (n+18) := 27 | _ _ := 15 example : ∀ x, foo x 17 = 17 := begin unfold_cases { refl }, end def bar : ℕ → ℕ | 17 := 17 | 9 := 17 | n := 17 example : ∀ x, bar x = 17 := begin unfold_cases { refl } end def baz : ℕ → ℕ → Prop | 0 0 := false | 0 n := true | n 0 := false | n m := n < m example : ∀ x, baz x 0 = false := begin unfold_cases { refl }, end
b961067a7e256b83f7834dd7507095bb3b3d0360
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/algebra/continuous_monoid_hom.lean
d35b9e98677b798630e962d5603b3cfe1f21a245
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
11,740
lean
/- Copyright (c) 2022 Thomas Browning. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning -/ import analysis.complex.circle import topology.continuous_function.algebra /-! # Continuous Monoid Homs This file defines the space of continuous homomorphisms between two topological groups. ## Main definitions * `continuous_monoid_hom A B`: The continuous homomorphisms `A →* B`. * `continuous_add_monoid_hom α β`: The continuous additive homomorphisms `α →+ β`. -/ open_locale pointwise open function variables {F α β : Type*} (A B C D E : Type*) [monoid A] [monoid B] [monoid C] [monoid D] [comm_group E] [topological_space A] [topological_space B] [topological_space C] [topological_space D] [topological_space E] [topological_group E] /-- The type of continuous additive monoid homomorphisms from `α` to `β`. When possible, instead of parametrizing results over `(f : continuous_add_monoid_hom α β)`, you should parametrize over `(F : Type*) [continuous_add_monoid_hom_class F α β] (f : F)`. When you extend this structure, make sure to extend `continuous_add_monoid_hom_class`. -/ structure continuous_add_monoid_hom (A B : Type*) [add_monoid A] [add_monoid B] [topological_space A] [topological_space B] extends A →+ B := (continuous_to_fun : continuous to_fun) /-- The type of continuous monoid homomorphisms from `α` to `β`. When possible, instead of parametrizing results over `(f : continuous_monoid_hom α β)`, you should parametrize over `(F : Type*) [continuous_monoid_hom_class F α β] (f : F)`. When you extend this structure, make sure to extend `continuous_add_monoid_hom_class`. -/ @[to_additive] structure continuous_monoid_hom extends A →* B := (continuous_to_fun : continuous to_fun) /-- `continuous_add_monoid_hom_class F α β` states that `F` is a type of continuous additive monoid homomorphisms. You should also extend this typeclass when you extend `continuous_add_monoid_hom`. -/ class continuous_add_monoid_hom_class (F α β : Type*) [add_monoid α] [add_monoid β] [topological_space α] [topological_space β] extends add_monoid_hom_class F α β := (map_continuous (f : F) : continuous f) /-- `continuous_monoid_hom_class F α β` states that `F` is a type of continuous additive monoid homomorphisms. You should also extend this typeclass when you extend `continuous_monoid_hom`. -/ @[to_additive] class continuous_monoid_hom_class (F α β : Type*) [monoid α] [monoid β] [topological_space α] [topological_space β] extends monoid_hom_class F α β := (map_continuous (f : F) : continuous f) /-- Reinterpret a `continuous_monoid_hom` as a `monoid_hom`. -/ add_decl_doc continuous_monoid_hom.to_monoid_hom /-- Reinterpret a `continuous_add_monoid_hom` as an `add_monoid_hom`. -/ add_decl_doc continuous_add_monoid_hom.to_add_monoid_hom @[priority 100, to_additive] -- See note [lower instance priority] instance continuous_monoid_hom_class.to_continuous_map_class [monoid α] [monoid β] [topological_space α] [topological_space β] [continuous_monoid_hom_class F α β] : continuous_map_class F α β := { .. ‹continuous_monoid_hom_class F α β› } namespace continuous_monoid_hom variables {A B C D E} [monoid α] [monoid β] [topological_space α] [topological_space β] @[to_additive] instance : continuous_monoid_hom_class (continuous_monoid_hom α β) α β := { coe := λ f, f.to_fun, coe_injective' := λ f g h, by { obtain ⟨⟨_, _⟩, _⟩ := f, obtain ⟨⟨_, _⟩, _⟩ := g, congr' }, map_mul := λ f, f.map_mul', map_one := λ f, f.map_one', map_continuous := λ f, f.continuous_to_fun } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ @[to_additive] instance : has_coe_to_fun (continuous_monoid_hom A B) (λ _, A → B) := fun_like.has_coe_to_fun @[to_additive] lemma ext {f g : continuous_monoid_hom A B} (h : ∀ x, f x = g x) : f = g := fun_like.ext _ _ h /-- Reinterpret a `continuous_monoid_hom` as a `continuous_map`. -/ @[to_additive "Reinterpret a `continuous_add_monoid_hom` as a `continuous_map`."] def to_continuous_map (f : continuous_monoid_hom α β) : C(α, β) := { .. f} @[to_additive] lemma to_continuous_map_injective : injective (to_continuous_map : _ → C(α, β)) := λ f g h, ext $ by convert fun_like.ext_iff.1 h /-- Construct a `continuous_monoid_hom` from a `continuous` `monoid_hom`. -/ @[to_additive "Construct a `continuous_add_monoid_hom` from a `continuous` `add_monoid_hom`.", simps] def mk' (f : A →* B) (hf : continuous f) : continuous_monoid_hom A B := { continuous_to_fun := hf, .. f } /-- Composition of two continuous homomorphisms. -/ @[to_additive "Composition of two continuous homomorphisms.", simps] def comp (g : continuous_monoid_hom B C) (f : continuous_monoid_hom A B) : continuous_monoid_hom A C := mk' (g.to_monoid_hom.comp f.to_monoid_hom) (g.continuous_to_fun.comp f.continuous_to_fun) /-- Product of two continuous homomorphisms on the same space. -/ @[to_additive "Product of two continuous homomorphisms on the same space.", simps] def prod (f : continuous_monoid_hom A B) (g : continuous_monoid_hom A C) : continuous_monoid_hom A (B × C) := mk' (f.to_monoid_hom.prod g.to_monoid_hom) (f.continuous_to_fun.prod_mk g.continuous_to_fun) /-- Product of two continuous homomorphisms on different spaces. -/ @[to_additive "Product of two continuous homomorphisms on different spaces.", simps] def prod_map (f : continuous_monoid_hom A C) (g : continuous_monoid_hom B D) : continuous_monoid_hom (A × B) (C × D) := mk' (f.to_monoid_hom.prod_map g.to_monoid_hom) (f.continuous_to_fun.prod_map g.continuous_to_fun) variables (A B C D E) /-- The trivial continuous homomorphism. -/ @[to_additive "The trivial continuous homomorphism.", simps] def one : continuous_monoid_hom A B := mk' 1 continuous_const @[to_additive] instance : inhabited (continuous_monoid_hom A B) := ⟨one A B⟩ /-- The identity continuous homomorphism. -/ @[to_additive "The identity continuous homomorphism.", simps] def id : continuous_monoid_hom A A := mk' (monoid_hom.id A) continuous_id /-- The continuous homomorphism given by projection onto the first factor. -/ @[to_additive "The continuous homomorphism given by projection onto the first factor.", simps] def fst : continuous_monoid_hom (A × B) A := mk' (monoid_hom.fst A B) continuous_fst /-- The continuous homomorphism given by projection onto the second factor. -/ @[to_additive "The continuous homomorphism given by projection onto the second factor.", simps] def snd : continuous_monoid_hom (A × B) B := mk' (monoid_hom.snd A B) continuous_snd /-- The continuous homomorphism given by inclusion of the first factor. -/ @[to_additive "The continuous homomorphism given by inclusion of the first factor.", simps] def inl : continuous_monoid_hom A (A × B) := prod (id A) (one A B) /-- The continuous homomorphism given by inclusion of the second factor. -/ @[to_additive "The continuous homomorphism given by inclusion of the second factor.", simps] def inr : continuous_monoid_hom B (A × B) := prod (one B A) (id B) /-- The continuous homomorphism given by the diagonal embedding. -/ @[to_additive "The continuous homomorphism given by the diagonal embedding.", simps] def diag : continuous_monoid_hom A (A × A) := prod (id A) (id A) /-- The continuous homomorphism given by swapping components. -/ @[to_additive "The continuous homomorphism given by swapping components.", simps] def swap : continuous_monoid_hom (A × B) (B × A) := prod (snd A B) (fst A B) /-- The continuous homomorphism given by multiplication. -/ @[to_additive "The continuous homomorphism given by addition.", simps] def mul : continuous_monoid_hom (E × E) E := mk' mul_monoid_hom continuous_mul /-- The continuous homomorphism given by inversion. -/ @[to_additive "The continuous homomorphism given by negation.", simps] def inv : continuous_monoid_hom E E := mk' comm_group.inv_monoid_hom continuous_inv variables {A B C D E} /-- Coproduct of two continuous homomorphisms to the same space. -/ @[to_additive "Coproduct of two continuous homomorphisms to the same space.", simps] def coprod (f : continuous_monoid_hom A E) (g : continuous_monoid_hom B E) : continuous_monoid_hom (A × B) E := (mul E).comp (f.prod_map g) @[to_additive] instance : comm_group (continuous_monoid_hom A E) := { mul := λ f g, (mul E).comp (f.prod g), mul_comm := λ f g, ext (λ x, mul_comm (f x) (g x)), mul_assoc := λ f g h, ext (λ x, mul_assoc (f x) (g x) (h x)), one := one A E, one_mul := λ f, ext (λ x, one_mul (f x)), mul_one := λ f, ext (λ x, mul_one (f x)), inv := λ f, (inv E).comp f, mul_left_inv := λ f, ext (λ x, mul_left_inv (f x)) } instance : topological_space (continuous_monoid_hom A B) := topological_space.induced to_continuous_map continuous_map.compact_open variables (A B C D E) lemma is_inducing : inducing (to_continuous_map : continuous_monoid_hom A B → C(A, B)) := ⟨rfl⟩ lemma is_embedding : embedding (to_continuous_map : continuous_monoid_hom A B → C(A, B)) := ⟨is_inducing A B, to_continuous_map_injective⟩ lemma is_closed_embedding [has_continuous_mul B] [t2_space B] : closed_embedding (to_continuous_map : continuous_monoid_hom A B → C(A, B)) := ⟨is_embedding A B, ⟨begin suffices : (set.range (to_continuous_map : continuous_monoid_hom A B → C(A, B))) = ({f | f '' {1} ⊆ {1}ᶜ} ∪ ⋃ (x y) (U V W) (hU : is_open U) (hV : is_open V) (hW : is_open W) (h : disjoint (U * V) W), {f | f '' {x} ⊆ U} ∩ {f | f '' {y} ⊆ V} ∩ {f | f '' {x * y} ⊆ W})ᶜ, { rw [this, compl_compl], refine (continuous_map.is_open_gen is_compact_singleton is_open_compl_singleton).union _, repeat { apply is_open_Union, intro, }, repeat { apply is_open.inter }, all_goals { apply continuous_map.is_open_gen is_compact_singleton, assumption } }, simp_rw [set.compl_union, set.compl_Union, set.image_singleton, set.singleton_subset_iff, set.ext_iff, set.mem_inter_iff, set.mem_Inter, set.mem_compl_iff], refine λ f, ⟨_, _⟩, { rintros ⟨f, rfl⟩, exact ⟨λ h, h (map_one f), λ x y U V W hU hV hW h ⟨⟨hfU, hfV⟩, hfW⟩, h ⟨set.mul_mem_mul hfU hfV, (congr_arg (∈ W) (map_mul f x y)).mp hfW⟩⟩ }, { rintros ⟨hf1, hf2⟩, suffices : ∀ x y, f (x * y) = f x * f y, { refine ⟨({ map_one' := of_not_not hf1, map_mul' := this, .. f } : continuous_monoid_hom A B), continuous_map.ext (λ _, rfl)⟩, }, intros x y, contrapose! hf2, obtain ⟨UV, W, hUV, hW, hfUV, hfW, h⟩ := t2_separation hf2.symm, have hB := @continuous_mul B _ _ _, obtain ⟨U, V, hU, hV, hfU, hfV, h'⟩ := is_open_prod_iff.mp (hUV.preimage hB) (f x) (f y) hfUV, refine ⟨x, y, U, V, W, hU, hV, hW, ((disjoint_iff.mpr h).mono_left _), ⟨hfU, hfV⟩, hfW⟩, rintros _ ⟨x, y, hx : (x, y).1 ∈ U, hy : (x, y).2 ∈ V, rfl⟩, exact h' ⟨hx, hy⟩ }, end⟩⟩ variables {A B C D E} instance [t2_space B] : t2_space (continuous_monoid_hom A B) := (is_embedding A B).t2_space instance : topological_group (continuous_monoid_hom A E) := let hi := is_inducing A E, hc := hi.continuous in { continuous_mul := hi.continuous_iff.mpr (continuous_mul.comp (continuous.prod_map hc hc)), continuous_inv := hi.continuous_iff.mpr (continuous_inv.comp hc) } end continuous_monoid_hom /-- The Pontryagin dual of `G` is the group of continuous homomorphism `G → circle`. -/ @[derive [topological_space, t2_space, comm_group, topological_group, inhabited]] def pontryagin_dual (G : Type*) [monoid G] [topological_space G] := continuous_monoid_hom G circle
2dbb896f099db761296f5f1c90bc27a43357df72
c3f2fcd060adfa2ca29f924839d2d925e8f2c685
/hott/algebra/precategory/functor.hlean
147698ccb5c3abba739274be116c9874d5a29b18
[ "Apache-2.0" ]
permissive
respu/lean
6582d19a2f2838a28ecd2b3c6f81c32d07b5341d
8c76419c60b63d0d9f7bc04ebb0b99812d0ec654
refs/heads/master
1,610,882,451,231
1,427,747,084,000
1,427,747,429,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,494
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: algebra.precategory.functor Authors: Floris van Doorn, Jakob von Raumer -/ import .basic types.pi .iso open function category eq prod equiv is_equiv sigma sigma.ops is_trunc funext iso open pi structure functor (C D : Precategory) : Type := (to_fun_ob : C → D) (to_fun_hom : Π ⦃a b : C⦄, hom a b → hom (to_fun_ob a) (to_fun_ob b)) (respect_id : Π (a : C), to_fun_hom (ID a) = ID (to_fun_ob a)) (respect_comp : Π {a b c : C} (g : hom b c) (f : hom a b), to_fun_hom (g ∘ f) = to_fun_hom g ∘ to_fun_hom f) namespace functor infixl `⇒`:25 := functor variables {A B C D E : Precategory} attribute to_fun_ob [coercion] attribute to_fun_hom [coercion] -- The following lemmas will later be used to prove that the type of -- precategories forms a precategory itself protected definition compose [reducible] (G : functor D E) (F : functor C D) : functor C E := functor.mk (λ x, G (F x)) (λ a b f, G (F f)) (λ a, calc G (F (ID a)) = G (ID (F a)) : by rewrite respect_id ... = ID (G (F a)) : by rewrite respect_id) (λ a b c g f, calc G (F (g ∘ f)) = G (F g ∘ F f) : by rewrite respect_comp ... = G (F g) ∘ G (F f) : by rewrite respect_comp) infixr `∘f`:60 := compose protected definition id [reducible] {C : Precategory} : functor C C := mk (λa, a) (λ a b f, f) (λ a, idp) (λ a b c f g, idp) protected definition ID [reducible] (C : Precategory) : functor C C := id definition functor_mk_eq' {F₁ F₂ : C → D} {H₁ : Π(a b : C), hom a b → hom (F₁ a) (F₁ b)} {H₂ : Π(a b : C), hom a b → hom (F₂ a) (F₂ b)} (id₁ id₂ comp₁ comp₂) (pF : F₁ = F₂) (pH : pF ▹ H₁ = H₂) : functor.mk F₁ H₁ id₁ comp₁ = functor.mk F₂ H₂ id₂ comp₂ := apD01111 functor.mk pF pH !is_hprop.elim !is_hprop.elim definition functor_eq' {F₁ F₂ : C ⇒ D} : Π(p : to_fun_ob F₁ = to_fun_ob F₂), (transport (λx, Πa b f, hom (x a) (x b)) p (to_fun_hom F₁) = to_fun_hom F₂) → F₁ = F₂ := functor.rec_on F₁ (λO₁ H₁ id₁ comp₁, functor.rec_on F₂ (λO₂ H₂ id₂ comp₂ p, !functor_mk_eq')) definition functor_mk_eq {F₁ F₂ : C → D} {H₁ : Π(a b : C), hom a b → hom (F₁ a) (F₁ b)} {H₂ : Π(a b : C), hom a b → hom (F₂ a) (F₂ b)} (id₁ id₂ comp₁ comp₂) (pF : F₁ ∼ F₂) (pH : Π(a b : C) (f : hom a b), hom_of_eq (pF b) ∘ H₁ a b f ∘ inv_of_eq (pF a) = H₂ a b f) : functor.mk F₁ H₁ id₁ comp₁ = functor.mk F₂ H₂ id₂ comp₂ := functor_mk_eq' id₁ id₂ comp₁ comp₂ (eq_of_homotopy pF) (eq_of_homotopy (λc, eq_of_homotopy (λc', eq_of_homotopy (λf, begin apply concat, rotate_left 1, exact (pH c c' f), apply concat, rotate_left 1, apply transport_hom, apply concat, rotate_left 1, exact (pi_transport_constant (eq_of_homotopy pF) (H₁ c c') f), apply (apD10' f), apply concat, rotate_left 1, exact (pi_transport_constant (eq_of_homotopy pF) (H₁ c) c'), apply (apD10' c'), apply concat, rotate_left 1, exact (pi_transport_constant (eq_of_homotopy pF) H₁ c), apply idp end)))) definition functor_eq {F₁ F₂ : C ⇒ D} : Π(p : to_fun_ob F₁ ∼ to_fun_ob F₂), (Π(a b : C) (f : hom a b), hom_of_eq (p b) ∘ F₁ f ∘ inv_of_eq (p a) = F₂ f) → F₁ = F₂ := functor.rec_on F₁ (λO₁ H₁ id₁ comp₁, functor.rec_on F₂ (λO₂ H₂ id₂ comp₂ p, !functor_mk_eq)) definition functor_mk_eq_constant {F : C → D} {H₁ : Π(a b : C), hom a b → hom (F a) (F b)} {H₂ : Π(a b : C), hom a b → hom (F a) (F b)} (id₁ id₂ comp₁ comp₂) (pH : Π(a b : C) (f : hom a b), H₁ a b f = H₂ a b f) : functor.mk F H₁ id₁ comp₁ = functor.mk F H₂ id₂ comp₂ := functor_eq (λc, idp) (λa b f, !id_leftright ⬝ !pH) protected definition preserve_iso (F : C ⇒ D) {a b : C} (f : hom a b) [H : is_iso f] : is_iso (F f) := begin fapply @is_iso.mk, apply (F (f⁻¹)), repeat (apply concat ; apply inverse ; apply (respect_comp F) ; apply concat ; apply (ap (λ x, to_fun_hom F x)) ; [apply left_inverse | apply right_inverse] ; apply (respect_id F) ), end attribute preserve_iso [instance] protected definition respect_inv (F : C ⇒ D) {a b : C} (f : hom a b) [H : is_iso f] [H' : is_iso (F f)] : F (f⁻¹) = (F f)⁻¹ := begin fapply @left_inverse_eq_right_inverse, apply (F f), apply concat, apply inverse, apply (respect_comp F), apply concat, apply (ap (λ x, to_fun_hom F x)), apply left_inverse, apply respect_id, apply right_inverse, end protected definition assoc (H : C ⇒ D) (G : B ⇒ C) (F : A ⇒ B) : H ∘f (G ∘f F) = (H ∘f G) ∘f F := !functor_mk_eq_constant (λa b f, idp) protected definition id_left (F : C ⇒ D) : id ∘f F = F := functor.rec_on F (λF1 F2 F3 F4, !functor_mk_eq_constant (λa b f, idp)) protected definition id_right (F : C ⇒ D) : F ∘f id = F := functor.rec_on F (λF1 F2 F3 F4, !functor_mk_eq_constant (λa b f, idp)) protected definition comp_id_eq_id_comp (F : C ⇒ D) : F ∘f functor.id = functor.id ∘f F := !functor.id_right ⬝ !functor.id_left⁻¹ -- "functor C D" is equivalent to a certain sigma type protected definition sigma_char : (Σ (to_fun_ob : C → D) (to_fun_hom : Π ⦃a b : C⦄, hom a b → hom (to_fun_ob a) (to_fun_ob b)), (Π (a : C), to_fun_hom (ID a) = ID (to_fun_ob a)) × (Π {a b c : C} (g : hom b c) (f : hom a b), to_fun_hom (g ∘ f) = to_fun_hom g ∘ to_fun_hom f)) ≃ (functor C D) := begin fapply equiv.MK, {intro S, fapply functor.mk, exact (S.1), exact (S.2.1), exact (pr₁ S.2.2), exact (pr₂ S.2.2)}, {intro F, cases F with [d1, d2, d3, d4], exact ⟨d1, d2, (d3, @d4)⟩}, {intro F, cases F, apply idp}, {intro S, cases S with [d1, S2], cases S2 with [d2, P1], cases P1, apply idp}, end set_option apply.class_instance false protected definition is_hset_functor [HD : is_hset D] : is_hset (functor C D) := begin apply is_trunc_is_equiv_closed, apply equiv.to_is_equiv, apply sigma_char, apply is_trunc_sigma, apply is_trunc_pi, intros, exact HD, intro F, apply is_trunc_sigma, apply is_trunc_pi, intro a, {apply is_trunc_pi, intro b, apply is_trunc_pi, intro c, apply !homH}, intro H, apply is_trunc_prod, {apply is_trunc_pi, intro a, apply is_trunc_eq, apply is_trunc_succ, apply !homH}, {repeat (apply is_trunc_pi; intros), apply is_trunc_eq, apply is_trunc_succ, apply !homH}, end definition functor_mk_eq'_idp (F : C → D) (H : Π(a b : C), hom a b → hom (F a) (F b)) (id comp) : functor_mk_eq' id id comp comp (idpath F) (idpath H) = idp := begin fapply (apD011 (apD01111 functor.mk idp idp)), apply is_hset.elim, apply is_hset.elim end definition functor_eq'_idp (F : C ⇒ D) : functor_eq' idp idp = (idpath F) := by (cases F; apply functor_mk_eq'_idp) definition functor_eq_eta' {F₁ F₂ : C ⇒ D} (p : F₁ = F₂) : functor_eq' (ap to_fun_ob p) (!transport_compose⁻¹ ⬝ apD to_fun_hom p) = p := begin cases p, cases F₁, apply concat, rotate_left 1, apply functor_eq'_idp, apply (ap (functor_eq' idp)), apply idp_con, end definition functor_eq2' {F₁ F₂ : C ⇒ D} {p₁ p₂ : to_fun_ob F₁ = to_fun_ob F₂} (q₁ q₂) (r : p₁ = p₂) : functor_eq' p₁ q₁ = functor_eq' p₂ q₂ := by cases r; apply (ap (functor_eq' p₂)); apply is_hprop.elim definition functor_eq2 {F₁ F₂ : C ⇒ D} (p q : F₁ = F₂) (r : ap010 to_fun_ob p ∼ ap010 to_fun_ob q) : p = q := begin cases F₁ with [ob₁, hom₁, id₁, comp₁], cases F₂ with [ob₂, hom₂, id₂, comp₂], rewrite [-functor_eq_eta' p, -functor_eq_eta' q], apply functor_eq2', apply ap_eq_ap_of_homotopy, exact r, end -- definition ap010_functor_eq_mk' {F₁ F₂ : C ⇒ D} (p : to_fun_ob F₁ = to_fun_ob F₂) -- (q : p ▹ F₁ = F₂) (c : C) : -- ap to_fun_ob (functor_eq_mk (apD10 p) (λa b f, _)) = p := sorry -- begin -- cases F₂, revert q, apply (homotopy.rec_on p), clear p, esimp, intros (p, q), -- cases p, clears (e_1, e_2), -- end -- TODO: remove sorry definition ap010_functor_eq {F₁ F₂ : C ⇒ D} (p : to_fun_ob F₁ ∼ to_fun_ob F₂) (q : (λ(a b : C) (f : hom a b), hom_of_eq (p b) ∘ F₁ f ∘ inv_of_eq (p a)) ∼3 to_fun_hom F₂) (c : C) : ap010 to_fun_ob (functor_eq p q) c = p c := begin cases F₂, revert q, apply (homotopy.rec_on p), clear p, esimp, intros [p, q], apply sorry, --apply (homotopy3.rec_on q), clear q, intro q, --cases p, --TODO: report: this fails end definition ap010_functor_mk_eq_constant {F : C → D} {H₁ : Π(a b : C), hom a b → hom (F a) (F b)} {H₂ : Π(a b : C), hom a b → hom (F a) (F b)} {id₁ id₂ comp₁ comp₂} (pH : Π(a b : C) (f : hom a b), H₁ a b f = H₂ a b f) (c : C) : ap010 to_fun_ob (functor_mk_eq_constant id₁ id₂ comp₁ comp₂ pH) c = idp := !ap010_functor_eq --do we need this theorem? definition compose_pentagon (K : D ⇒ E) (H : C ⇒ D) (G : B ⇒ C) (F : A ⇒ B) : (calc K ∘f H ∘f G ∘f F = (K ∘f H) ∘f G ∘f F : functor.assoc ... = ((K ∘f H) ∘f G) ∘f F : functor.assoc) = (calc K ∘f H ∘f G ∘f F = K ∘f (H ∘f G) ∘f F : ap (λx, K ∘f x) !functor.assoc ... = (K ∘f H ∘f G) ∘f F : functor.assoc ... = ((K ∘f H) ∘f G) ∘f F : ap (λx, x ∘f F) !functor.assoc) := sorry -- begin -- apply functor_eq2, -- intro a, -- rewrite +ap010_con, -- -- rewrite +ap010_ap, -- -- apply sorry -- /-to prove this we need a stronger ap010-lemma, something like -- ap010 (λy, to_fun_ob (f y)) (functor_mk_eq_constant ...) c = idp -- or something another way of getting ap out of ap010 -- -/ -- --rewrite +ap010_ap, -- --unfold functor.assoc, -- --rewrite ap010_functor_mk_eq_constant, -- end end functor
1998fe07180fb69debc7c06b9c2d2a002fd190e8
df561f413cfe0a88b1056655515399c546ff32a5
/4-power-world/l6.lean
4dfa059e73406c801d596ef0b15911ccacdb9952
[]
no_license
nicholaspun/natural-number-game-solutions
31d5158415c6f582694680044c5c6469032c2a06
1e2aed86d2e76a3f4a275c6d99e795ad30cf6df0
refs/heads/main
1,675,123,625,012
1,607,633,548,000
1,607,633,548,000
318,933,860
3
1
null
null
null
null
UTF-8
Lean
false
false
298
lean
lemma mul_pow (a b n : mynat) : (a * b) ^ n = a ^ n * b ^ n := begin induction n with k Pk, repeat { rw pow_zero }, rw one_mul, refl, rw pow_succ a, rw mul_assoc (a^k) _ _, rw mul_left_comm, rw pow_succ b, rw ← mul_assoc (a^k) _ _, rw ← Pk, rw ← mul_left_comm, exact pow_succ (a * b) k, end
1631a3a143dab140b8695049af63fec4ab6266f3
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/field_theory/primitive_element.lean
7abeba5f481e849a2451c3fc41c1fde7934fc4da
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
3,317
lean
/- Copyright (c) 2020 Thomas Browning and Patrick Lutz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning and Patrick Lutz -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.field_theory.adjoin import Mathlib.field_theory.separable import Mathlib.PostPort universes u_1 u_2 namespace Mathlib /-! # Primitive Element Theorem In this file we prove the primitive element theorem. ## Main results - `exists_primitive_element`: a finite separable extension `E / F` has a primitive element, i.e. there is an `α : E` such that `F⟮α⟯ = (⊤ : subalgebra F E)`. ## Implementation notes In declaration names, `primitive_element` abbreviates `adjoin_simple_eq_top`: it stands for the statement `F⟮α⟯ = (⊤ : subalgebra F E)`. We did not add an extra declaration `is_primitive_element F α := F⟮α⟯ = (⊤ : subalgebra F E)` because this requires more unfolding without much obvious benefit. ## Tags primitive element, separable field extension, separable extension, intermediate field, adjoin, exists_adjoin_simple_eq_top -/ namespace field /-! ### Primitive element theorem for finite fields -/ /-- Primitive element theorem assuming E is finite. -/ theorem exists_primitive_element_of_fintype_top (F : Type u_1) [field F] (E : Type u_2) [field E] [algebra F E] [fintype E] : ∃ (α : E), intermediate_field.adjoin F (intermediate_field.insert.insert ∅ α) = ⊤ := sorry /-- Primitive element theorem for finite dimensional extension of a finite field. -/ theorem exists_primitive_element_of_fintype_bot (F : Type u_1) [field F] (E : Type u_2) [field E] [algebra F E] [fintype F] [finite_dimensional F E] : ∃ (α : E), intermediate_field.adjoin F (intermediate_field.insert.insert ∅ α) = ⊤ := exists_primitive_element_of_fintype_top F E /-! ### Primitive element theorem for infinite fields -/ theorem primitive_element_inf_aux_exists_c {F : Type u_1} [field F] [infinite F] {E : Type u_2} [field E] (ϕ : F →+* E) (α : E) (β : E) (f : polynomial F) (g : polynomial F) : ∃ (c : F), ∀ (α' : E), α' ∈ polynomial.roots (polynomial.map ϕ f) → ∀ (β' : E), β' ∈ polynomial.roots (polynomial.map ϕ g) → -(α' - α) / (β' - β) ≠ coe_fn ϕ c := sorry -- This is the heart of the proof of the primitive element theorem. It shows that if `F` is -- infinite and `α` and `β` are separable over `F` then `F⟮α, β⟯` is generated by a single element. theorem primitive_element_inf_aux {F : Type u_1} [field F] [infinite F] {E : Type u_2} [field E] (α : E) (β : E) [algebra F E] (F_sep : is_separable F E) : ∃ (γ : E), intermediate_field.adjoin F (intermediate_field.insert.insert (intermediate_field.insert.insert ∅ β) α) = intermediate_field.adjoin F (intermediate_field.insert.insert ∅ γ) := sorry /-- Primitive element theorem: a finite separable field extension `E` of `F` has a primitive element, i.e. there is an `α ∈ E` such that `F⟮α⟯ = (⊤ : subalgebra F E)`.-/ theorem exists_primitive_element {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] [finite_dimensional F E] (F_sep : is_separable F E) : ∃ (α : E), intermediate_field.adjoin F (intermediate_field.insert.insert ∅ α) = ⊤ := sorry
81a954b380a07eaadb187849996420a274e12329
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/blast_cc11.lean
9242952a914f4df137764cbc489df03fb99ca837
[ "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
849
lean
import data.list set_option blast.strategy "cc" definition t1 (a b : nat) : (a = b) ↔ (b = a) := by blast print t1 definition t2 (a b : nat) : (a = b) = (b = a) := by blast print t2 definition t3 (a b : nat) : (a = b) == (b = a) := by blast print t3 open perm definition t4 (a b : list nat) : (a ~ b) ↔ (b ~ a) := by blast definition t5 (a b : list nat) : (a ~ b) = (b ~ a) := by blast definition t6 (a b : list nat) : (a ~ b) == (b ~ a) := by blast definition t7 (p : Prop) (a b : nat) : a = b → b ≠ a → p := by blast definition t8 (a b : Prop) : (a ↔ b) → ((b ↔ a) ↔ (a ↔ b)) := by blast definition t9 (a b c : nat) : b = c → (a = b ↔ c = a) := by blast definition t10 (a b c : list nat) : b ~ c → (a ~ b ↔ c ~ a) := by blast definition t11 (a b c : list nat) : b ~ c → ((a ~ b) = (c ~ a)) := by blast
0e3ccff07c27f164c170947e04f46767cb78c9e1
2f8bf12144551bc7d8087a6320990c4621741f3d
/library/init/lean/parser/syntax.lean
3c30ea752bb4a6c7d7c5f09c5736dd1b39362447
[ "Apache-2.0" ]
permissive
jesse-michael-han/lean4
eb63a12960e69823749edceb4f23fd33fa2253ce
fa16920a6a7700cabc567aa629ce4ae2478a2f40
refs/heads/master
1,589,935,810,594
1,557,177,860,000
1,557,177,860,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,448
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sebastian Ullrich -/ prelude import init.lean.name init.lean.parser.parsec namespace Lean namespace Parser --TODO(Sebastian): move structure Substring := (start : String.OldIterator) (stop : String.OldIterator) structure SourceInfo := /- Will be inferred after parsing by `Syntax.updateLeading`. During parsing, it is not at all clear what the preceding token was, especially with backtracking. -/ (leading : Substring) (pos : Parsec.Position) (trailing : Substring) structure SyntaxAtom := (info : Option SourceInfo := none) (val : String) /-- A simple wrapper that should remind you to use the static Declaration instead of hard-coding the Node Name. -/ structure SyntaxNodeKind := -- should be equal to the Name of the Declaration this structure instance was bound to (name : Name) /-- Signifies ambiguous Syntax to be disambiguated by the Elaborator. Should have at least two children. This Node kind is special-cased by `Syntax.reprint` since its children's outputs should not be concatenated. -/ @[pattern] def choice : SyntaxNodeKind := ⟨`Lean.Parser.choice⟩ /-- A nondescriptive kind that can be used for merely grouping Syntax trees into a Node. This Node kind is special-cased by `Syntax.Format` to be printed as brackets `[...]` without a Node kind. -/ @[pattern] def noKind : SyntaxNodeKind := ⟨`Lean.Parser.noKind⟩ /-- A hygiene marker introduced by a macro expansion. -/ @[derive DecidableEq HasFormat] def MacroScope := Nat abbrev macroScopes := List MacroScope /- Parsers create `SyntaxNode`'s with the following properties (see implementation of `Combinators.Node`): - If `args` contains a `Syntax.missing`, then all subsequent elements are also `Syntax.missing`. - The first argument in `args` is not `Syntax.missing` Remark: We do create `SyntaxNode`'s with an Empty `args` field (e.g. for representing `Option.none`). -/ structure SyntaxNode (Syntax : Type) := (kind : SyntaxNodeKind) (args : List Syntax) -- Lazily propagated scopes. Scopes are pushed inwards when a Node is destructed via `Syntax.asNode`, -- until an ident or an atom (in which the scopes vanish) is reached. -- Scopes are stored in a stack with the most recent Scope at the top. (scopes : macroScopes := []) structure SyntaxIdent := (info : Option SourceInfo := none) (rawVal : Substring) (val : Name) /- A List of overloaded, global names that this identifier could have referred to in the lexical context where it was parsed. If the identifier does not resolve to a local binding, it should instead resolve to one of these preresolved constants. -/ (preresolved : List Name := []) (scopes : macroScopes := []) inductive Syntax | atom (val : SyntaxAtom) | ident (val : SyntaxIdent) -- note: use `Syntax.asNode` instead of matching against this Constructor so that -- macro scopes are propagated | rawNode (val : SyntaxNode Syntax) | missing instance : Inhabited Syntax := ⟨Syntax.missing⟩ def Substring.toString (s : Substring) : String := s.start.extract s.stop def Substring.ofString (s : String) : Substring := ⟨s.mkOldIterator, s.mkOldIterator.toEnd⟩ instance Substring.HasToString : HasToString Substring := ⟨Substring.toString⟩ -- TODO(Sebastian): exhaustively argue why (if?) this is correct -- The basic idea is List concatenation with elimination of adjacent identical scopes def macroScopes.flip : macroScopes → macroScopes → macroScopes | ys (x::xs) := match macroScopes.flip ys xs with | y::ys := if x = y then ys else x::y::ys | [] := [x] | ys [] := ys namespace Syntax open Lean.Format def flipScopes (scopes : macroScopes) : Syntax → Syntax | (Syntax.ident n) := Syntax.ident {n with scopes := n.scopes.flip scopes} | (Syntax.rawNode n) := Syntax.rawNode {n with scopes := n.scopes.flip scopes} | stx := stx def mkNode (kind : SyntaxNodeKind) (args : List Syntax) := Syntax.rawNode { kind := kind, args := args } /-- Match against `Syntax.rawNode`, propagating lazy macro scopes. -/ def asNode : Syntax → Option (SyntaxNode Syntax) | (Syntax.rawNode n) := some {n with args := n.args.map (flipScopes n.scopes), scopes := []} | _ := none protected def list (args : List Syntax) := mkNode noKind args def kind : Syntax → Option SyntaxNodeKind | (Syntax.rawNode n) := some n.kind | _ := none def isOfKind (k : SyntaxNodeKind) : Syntax → Bool | (Syntax.rawNode n) := k.name = n.kind.name | _ := false section variables {m : Type → Type} [Monad m] (r : Syntax → m (Option Syntax)) local attribute [instance] monadInhabited partial def mreplace : Syntax → m Syntax | stx@(rawNode n) := do o ← r stx, match o with | some stx' := pure stx' | none := do args' ← n.args.mmap mreplace, pure $ rawNode {n with args := args'} | stx := do o ← r stx, pure $ o.getOrElse stx def replace := @mreplace Id _ end /- Remark: the State `String.Iterator` is the `SourceInfo.trailing.stop` of the previous token, or the beginning of the String. -/ private def updateLeadingAux : Syntax → State String.OldIterator (Option Syntax) | (atom a@{info := some info, ..}) := do last ← get, set info.trailing.stop, pure $ some $ atom {a with info := some {info with leading := ⟨last, last.nextn (info.pos - last.offset)⟩}} | (ident id@{info := some info, ..}) := do last ← get, set info.trailing.stop, pure $ some $ ident {id with info := some {info with leading := ⟨last, last.nextn (info.pos - last.offset)⟩}} | _ := pure none /-- Set `SourceInfo.leading` according to the trailing stop of the preceding token. The Result is a round-tripping Syntax tree IF, in the input Syntax tree, * all leading stops, atom contents, and trailing starts are correct * trailing stops are between the trailing start and the next leading stop. Remark: after parsing all `SourceInfo.leading` fields are Empty. The Syntax argument is the output produced by the Parser for `source`. This Function "fixes" the `source.leanding` field. Note that, the `SourceInfo.trailing` fields are correct. The implementation of this Function relies on this property. -/ def updateLeading (source : String) : Syntax → Syntax := λ stx, Prod.fst $ (mreplace updateLeadingAux stx).run source.mkOldIterator /-- Retrieve the left-most leaf's info in the Syntax tree. -/ partial def getHeadInfo : Syntax → Option SourceInfo | (atom a) := a.info | (ident id) := id.info | (rawNode n) := n.args.foldr (λ s r, getHeadInfo s <|> r) none | _ := none def getPos (stx : Syntax) : Option Parsec.Position := do i ← stx.getHeadInfo, pure i.pos def reprintAtom : SyntaxAtom → String | ⟨some info, s⟩ := info.leading.toString ++ s ++ info.trailing.toString | ⟨none, s⟩ := s partial def reprint : Syntax → Option String | (atom ⟨some info, s⟩) := pure $ info.leading.toString ++ s ++ info.trailing.toString | (atom ⟨none, s⟩) := pure s | (ident id@{info := some info, ..}) := pure $ info.leading.toString ++ id.rawVal.toString ++ info.trailing.toString | (ident id@{info := none, ..}) := pure id.rawVal.toString | (rawNode n) := if n.kind.name = choice.name then match n.args with -- should never happen | [] := failure -- check that every choice prints the same | n::ns := do s ← reprint n, ss ← ns.mmap reprint, guard $ ss.all (= s), pure s else String.join <$> n.args.mmap reprint | missing := "" protected partial def format : Syntax → Format | (atom ⟨_, s⟩) := fmt $ repr s | (ident id) := let scopes := id.preresolved.map fmt ++ id.scopes.reverse.map fmt in let scopes := match scopes with [] := fmt "" | _ := bracket "{" (joinSep scopes ", ") "}" in fmt "`" ++ fmt id.val ++ scopes | stx@(rawNode n) := let scopes := match n.scopes with [] := fmt "" | _ := bracket "{" (joinSep n.scopes.reverse ", ") "}" in if n.kind.name = `Lean.Parser.noKind then sbracket $ scopes ++ joinSep (n.args.map format) line else let shorterName := n.kind.name.replacePrefix `Lean.Parser Name.anonymous in paren $ joinSep ((fmt shorterName ++ scopes) :: n.args.map format) line | missing := "<missing>" instance : HasFormat Syntax := ⟨Syntax.format⟩ instance : HasToString Syntax := ⟨toString ∘ fmt⟩ end Syntax end Parser end Lean
11a1777d0e31c9ae1a1c7180e93b64b5e0f0219d
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/algebra/localization.lean
5f93bac5c3e1e10ef5b899d99651ccea104e12e4
[ "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
1,257
lean
/- Copyright (c) 2021 María Inés de Frutos-Fernández. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: María Inés de Frutos-Fernández -/ import ring_theory.localization.basic import topology.algebra.ring /-! # Localization of topological rings The topological localization of a topological commutative ring `R` at a submonoid `M` is the ring `localization M` endowed with the final ring topology of the natural homomorphism sending `x : R` to the equivalence class of `(x, 1)` in the localization of `R` at a `M`. ## Main Results - `localization.topological_ring`: The localization of a topological commutative ring at a submonoid is a topological ring. -/ variables {R : Type*} [comm_ring R] [topological_space R] {M : submonoid R} /-- The ring topology on `localization M` coinduced from the natural homomorphism sending `x : R` to the equivalence class of `(x, 1)`. -/ def localization.ring_topology : ring_topology (localization M) := ring_topology.coinduced (localization.monoid_of M).to_fun instance : topological_space (localization M) := localization.ring_topology.to_topological_space instance : topological_ring (localization M) := localization.ring_topology.to_topological_ring
b6faae008f182ce003d411f931482808c5e4cf85
78269ad0b3c342b20786f60690708b6e328132b0
/src/library_dev/data/nat/sub.lean
230e4854170f92e25472532fca95635f0f685301
[]
no_license
dselsam/library_dev
e74f46010fee9c7b66eaa704654cad0fcd2eefca
1b4e34e7fb067ea5211714d6d3ecef5132fc8218
refs/heads/master
1,610,372,841,675
1,497,014,421,000
1,497,014,421,000
86,526,137
0
0
null
1,490,752,133,000
1,490,752,132,000
null
UTF-8
Lean
false
false
6,428
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 Subtraction on the natural numbers, as well as min, max, and distance. -/ namespace nat /- interaction with inequalities -/ protected theorem le_sub_add (n m : ℕ) : n ≤ n - m + m := or.elim (le_total n m) (suppose n ≤ m, begin rw [sub_eq_zero_of_le this, zero_add], exact this end) (suppose m ≤ n, begin rw (nat.sub_add_cancel this) end) protected theorem sub_eq_of_eq_add {n m k : ℕ} (h : k = n + m) : k - n = m := begin rw [h, nat.add_sub_cancel_left] end protected theorem sub_le_sub_left {n m : ℕ} (h : n ≤ m) (k : ℕ) : k - m ≤ k - n := begin cases le.dest h with l hl, rw [-hl, -nat.sub_sub], apply sub_le end protected theorem lt_of_sub_pos {m n : ℕ} (h : n - m > 0) : m < n := lt_of_not_ge (suppose m ≥ n, have n - m = 0, from sub_eq_zero_of_le this, begin rw this at h, exact lt_irrefl _ h end) protected theorem lt_of_sub_lt_sub_right {n m k : ℕ} (h : n - k < m - k) : n < m := lt_of_not_ge (suppose m ≤ n, have m - k ≤ n - k, from nat.sub_le_sub_right this _, not_le_of_gt h this) protected theorem lt_of_sub_lt_sub_left {n m k : ℕ} (h : n - m < n - k) : k < m := lt_of_not_ge (suppose m ≤ k, have n - k ≤ n - m, from nat.sub_le_sub_left this _, not_le_of_gt h this) protected theorem sub_lt_self {m n : ℕ} (h₁ : m > 0) (h₂ : n > 0) : m - n < m := calc m - n = succ (pred m) - succ (pred n) : by rw [succ_pred_eq_of_pos h₁, succ_pred_eq_of_pos h₂] ... = pred m - pred n : by rw succ_sub_succ ... ≤ pred m : sub_le _ _ ... < succ (pred m) : lt_succ_self _ ... = m : succ_pred_eq_of_pos h₁ protected theorem le_sub_of_add_le {m n k : ℕ} (h : m + k ≤ n) : m ≤ n - k := calc m = m + k - k : by rw nat.add_sub_cancel ... ≤ n - k : nat.sub_le_sub_right h k protected theorem lt_sub_of_add_lt {m n k : ℕ} (h : m + k < n) : m < n - k := lt_of_succ_le (nat.le_sub_of_add_le (calc succ m + k = succ (m + k) : by rw succ_add ... ≤ n : succ_le_of_lt h)) protected theorem add_lt_of_lt_sub {m n k : ℕ} (h : m < n - k) : m + k < n := @nat.lt_of_sub_lt_sub_right _ _ k (by rwa nat.add_sub_cancel) protected theorem sub_lt_of_lt_add {k n m : nat} (h₁ : k < n + m) (h₂ : n ≤ k) : k - n < m := have succ k ≤ n + m, from succ_le_of_lt h₁, have succ (k - n) ≤ m, from calc succ (k - n) = succ k - n : by rw (succ_sub h₂) ... ≤ n + m - n : nat.sub_le_sub_right this n ... = m : by rw nat.add_sub_cancel_left, lt_of_succ_le this /- distance -/ definition dist (n m : ℕ) := (n - m) + (m - n) theorem dist.def (n m : ℕ) : dist n m = (n - m) + (m - n) := rfl @[simp] theorem dist_comm (n m : ℕ) : dist n m = dist m n := by simp [dist.def] @[simp] theorem dist_self (n : ℕ) : dist n n = 0 := by simp [dist.def, nat.sub_self] theorem eq_of_dist_eq_zero {n m : ℕ} (h : dist n m = 0) : n = m := have n - m = 0, from eq_zero_of_add_eq_zero_right h, have n ≤ m, from nat.le_of_sub_eq_zero this, have m - n = 0, from eq_zero_of_add_eq_zero_left h, have m ≤ n, from nat.le_of_sub_eq_zero this, le_antisymm ‹n ≤ m› ‹m ≤ n› theorem dist_eq_zero {n m : ℕ} (h : n = m) : dist n m = 0 := begin rw [h, dist_self] end theorem dist_eq_sub_of_le {n m : ℕ} (h : n ≤ m) : dist n m = m - n := begin rw [dist.def, sub_eq_zero_of_le h, zero_add] end theorem dist_eq_sub_of_ge {n m : ℕ} (h : n ≥ m) : dist n m = n - m := begin rw [dist_comm], apply dist_eq_sub_of_le h end theorem dist_zero_right (n : ℕ) : dist n 0 = n := eq.trans (dist_eq_sub_of_ge (zero_le n)) (nat.sub_zero n) theorem dist_zero_left (n : ℕ) : dist 0 n = n := eq.trans (dist_eq_sub_of_le (zero_le n)) (nat.sub_zero n) theorem dist_add_add_right (n k m : ℕ) : dist (n + k) (m + k) = dist n m := calc dist (n + k) (m + k) = ((n + k) - (m + k)) + ((m + k)-(n + k)) : rfl ... = (n - m) + ((m + k) - (n + k)) : by rw nat.add_sub_add_right ... = (n - m) + (m - n) : by rw nat.add_sub_add_right theorem dist_add_add_left (k n m : ℕ) : dist (k + n) (k + m) = dist n m := begin rw [add_comm k n, add_comm k m], apply dist_add_add_right end theorem dist_eq_intro {n m k l : ℕ} (h : n + m = k + l) : dist n k = dist l m := calc dist n k = dist (n + m) (k + m) : by rw dist_add_add_right ... = dist (k + l) (k + m) : by rw h ... = dist l m : by rw dist_add_add_left protected theorem sub_lt_sub_add_sub (n m k : ℕ) : n - k ≤ (n - m) + (m - k) := or.elim (le_total k m) (suppose k ≤ m, begin rw -nat.add_sub_assoc this, apply nat.sub_le_sub_right, apply nat.le_sub_add end) (suppose k ≥ m, begin rw [sub_eq_zero_of_le this, add_zero], apply nat.sub_le_sub_left, exact this end) theorem dist.triangle_inequality (n m k : ℕ) : dist n k ≤ dist n m + dist m k := have dist n m + dist m k = (n - m) + (m - k) + ((k - m) + (m - n)), by simp [dist.def], begin rw [this, dist.def], apply add_le_add, repeat { apply nat.sub_lt_sub_add_sub } end theorem dist_mul_right (n k m : ℕ) : dist (n * k) (m * k) = dist n m * k := by rw [dist.def, dist.def, right_distrib, nat.mul_sub_right_distrib, nat.mul_sub_right_distrib] theorem dist_mul_left (k n m : ℕ) : dist (k * n) (k * m) = k * dist n m := by rw [mul_comm k n, mul_comm k m, dist_mul_right, mul_comm] -- TODO(Jeremy): do when we have max and minx --lemma dist_eq_max_sub_min {i j : nat} : dist i j = (max i j) - min i j := --sorry /- or.elim (lt_or_ge i j) (suppose i < j, by rw [max_eq_right_of_lt this, min_eq_left_of_lt this, dist_eq_sub_of_lt this]) (suppose i ≥ j, by rw [max_eq_left this , min_eq_right this, dist_eq_sub_of_ge this]) -/ lemma dist_succ_succ {i j : nat} : dist (succ i) (succ j) = dist i j := by simp [dist.def, succ_sub_succ] lemma dist_pos_of_ne {i j : nat} : i ≠ j → dist i j > 0 := assume hne, nat.lt_by_cases (suppose i < j, begin rw [dist_eq_sub_of_le (le_of_lt this)], apply nat.sub_pos_of_lt this end) (suppose i = j, by contradiction) (suppose i > j, begin rw [dist_eq_sub_of_ge (le_of_lt this)], apply nat.sub_pos_of_lt this end) end nat
92858adb3a0034d19c435be2d2b40118efd6a14d
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/category/Kleisli.lean
e62b3eeda7bb4d221562ee4538b77a0e2c405853
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
1,245
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon The Kleisli construction on the Type category TODO: generalise this to work with category_theory.monad -/ import category_theory.category universes u v namespace category_theory def Kleisli (m) [monad.{u v} m] := Type u def Kleisli.mk (m) [monad.{u v} m] (α : Type u) : Kleisli m := α instance Kleisli.category_struct {m} [monad m] : category_struct (Kleisli m) := { hom := λ α β, α → m β, id := λ α x, (pure x : m α), comp := λ X Y Z f g, f >=> g } instance Kleisli.category {m} [monad m] [is_lawful_monad m] : category (Kleisli m) := by refine { hom := λ α β, α → m β, id := λ α x, (pure x : m α), comp := λ X Y Z f g, f >=> g, id_comp' := _, comp_id' := _, assoc' := _ }; intros; ext; simp only [(>=>)] with functor_norm @[simp] lemma Kleisli.id_def {m} [monad m] [is_lawful_monad m] (α : Kleisli m) : 𝟙 α = @pure m _ α := rfl lemma Kleisli.comp_def {m} [monad m] [is_lawful_monad m] (α β γ : Kleisli m) (xs : α ⟶ β) (ys : β ⟶ γ) (a : α) : (xs ≫ ys) a = xs a >>= ys := rfl end category_theory
0e59a6ac976e8457958848e1a7aa391ff7bad466
4727251e0cd73359b15b664c3170e5d754078599
/src/order/filter/modeq.lean
94fee945148c6c8e2c83d108ec9cb638fa131162
[ "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
1,098
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import data.nat.parity import order.filter.at_top_bot /-! # Numbers are frequently modeq to fixed numbers In this file we prove that `m ≡ d [MOD n]` frequently as `m → ∞`. -/ open filter namespace nat /-- Infinitely many natural numbers are equal to `d` mod `n`. -/ lemma frequently_modeq {n : ℕ} (h : n ≠ 0) (d : ℕ) : ∃ᶠ m in at_top, m ≡ d [MOD n] := ((tendsto_add_at_top_nat d).comp (tendsto_id.nsmul_at_top h.bot_lt)).frequently $ frequently_of_forall $ λ m, by { simp [nat.modeq_iff_dvd, ← sub_sub] } lemma frequently_mod_eq {d n : ℕ} (h : d < n) : ∃ᶠ m in at_top, m % n = d := by simpa only [nat.modeq, mod_eq_of_lt h] using frequently_modeq h.ne_bot d lemma frequently_even : ∃ᶠ m : ℕ in at_top, even m := by simpa only [even_iff] using frequently_mod_eq zero_lt_two lemma frequently_odd : ∃ᶠ m : ℕ in at_top, odd m := by simpa only [odd_iff] using frequently_mod_eq one_lt_two end nat
1f01ca21e1ec5740638b543a1757c45570d779dc
aa5a655c05e5359a70646b7154e7cac59f0b4132
/src/Lean/Meta/Tactic/Simp/Rewrite.lean
a23165e9399cf6a4cc86831135f039d7a5c508ba
[ "Apache-2.0" ]
permissive
lambdaxymox/lean4
ae943c960a42247e06eff25c35338268d07454cb
278d47c77270664ef29715faab467feac8a0f446
refs/heads/master
1,677,891,867,340
1,612,500,005,000
1,612,500,005,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,114
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.SynthInstance import Lean.Meta.Tactic.Simp.Types namespace Lean.Meta.Simp /- Remark: the parameter tag is used for creating trace messages. It is irrelevant otherwise. -/ def rewrite (e : Expr) (s : DiscrTree SimpLemma) (discharge? : Expr → SimpM (Option Expr)) (tag : String) : SimpM Result := do let lemmas ← s.getMatch e if lemmas.isEmpty then trace[Meta.Tactic.simp]! "no lemmas found for {tag}-rewriting {e}" return { expr := e } else let lemmas := lemmas.insertionSort fun e₁ e₂ => e₁.priority < e₂.priority for lemma in lemmas do if let some result ← tryLemma? lemma then return result return { expr := e } where getLHS (kind : SimpLemmaKind) (type : Expr) : MetaM Expr := match kind with | SimpLemmaKind.pos => return type | SimpLemmaKind.neg => return type.appArg! | SimpLemmaKind.eq => return type.appFn!.appArg! | SimpLemmaKind.iff => return type.appFn!.appArg! getRHS (kind : SimpLemmaKind) (type : Expr) : MetaM Expr := match kind with | SimpLemmaKind.pos => return mkConst `True | SimpLemmaKind.neg => return mkConst `False | SimpLemmaKind.eq => return type.appArg! | SimpLemmaKind.iff => return type.appArg! synthesizeArgs (lemma : SimpLemma) (xs : Array Expr) (bis : Array BinderInfo) : SimpM Bool := do for x in xs, bi in bis do let type ← inferType x if bi.isInstImplicit then match ← trySynthInstance type with | LOption.some val => unless (← isDefEq x val) do trace[Meta.Tactic.simp.discharge]! "{lemma}, failed to assign instance{indentExpr type}" return false | _ => trace[Meta.Tactic.simp.discharge]! "{lemma}, failed to synthesize instance{indentExpr type}" return false else if (← isProp type <&&> (← instantiateMVars x).isMVar) then match ← discharge? type with | some proof => unless (← isDefEq x proof) do trace[Meta.Tactic.simp.discharge]! "{lemma}, failed to assign proof{indentExpr type}" return false | none => trace[Meta.Tactic.simp.discharge]! "{lemma}, failed to discharge hypotheses{indentExpr type}" return false return true finalizeProof (kind : SimpLemmaKind) (proof : Expr) : MetaM Expr := match kind with | SimpLemmaKind.eq => return proof | SimpLemmaKind.iff => mkPropExt proof | SimpLemmaKind.pos => mkEqTrue proof | SimpLemmaKind.neg => mkEqFalse proof tryLemma? (lemma : SimpLemma) : SimpM (Option Result) := withNewMCtxDepth do let val ← lemma.getValue let type ← inferType val let (xs, bis, type) ← forallMetaTelescopeReducing type let lhs ← getLHS lemma.kind type if (← isDefEq lhs e) then unless (← synthesizeArgs lemma xs bis) do return none let proof ← instantiateMVars (mkAppN val xs) if ← hasAssignableMVar proof then return none let rhs ← instantiateMVars (← getRHS lemma.kind type) if lemma.perm && !Expr.lt rhs e then trace[Meta.Tactic.simp.unify]! "{lemma}, perm rejected {e} ==> {rhs}" return none let proof ← finalizeProof lemma.kind proof trace[Meta.Tactic.simp.rewrite]! "{lemma}, {e} ==> {rhs}" return some { expr := rhs, proof? := proof } else trace[Meta.Tactic.simp.unify]! "{lemma}, failed to unify {lhs} with {e}" return none def preDefault (e : Expr) (discharge? : Expr → SimpM (Option Expr)) : SimpM Step := do let lemmas ← (← read).simpLemmas return Step.visit (← rewrite e lemmas.pre discharge? (tag := "pre")) def postDefault (e : Expr) (discharge? : Expr → SimpM (Option Expr)) : SimpM Step := do let lemmas ← (← read).simpLemmas return Step.visit (← rewrite e lemmas.post discharge? (tag := "post")) end Lean.Meta.Simp
421e5279deae1947849c051848f6cc66a837d4ba
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/lean/run/typeclass_diamond.lean
391e2b6c7b8d17336d35608386647f1756727c9e
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
1,775
lean
class Top₁ (n : Nat) : Type := (u : Unit := ()) class Bot₁ (n : Nat) : Type := (u : Unit := ()) class Left₁ (n : Nat) : Type := (u : Unit := ()) class Right₁ (n : Nat) : Type := (u : Unit := ()) instance Bot₁Inst : Bot₁ Nat.zero := {} instance Left₁ToBot₁ (n : Nat) [Left₁ n] : Bot₁ n := {} instance Right₁ToBot₁ (n : Nat) [Right₁ n] : Bot₁ n := {} instance Top₁ToLeft₁ (n : Nat) [Top₁ n] : Left₁ n := {} instance Top₁ToRight₁ (n : Nat) [Top₁ n] : Right₁ n := {} instance Bot₁ToTopSucc (n : Nat) [Bot₁ n] : Top₁ n.succ := {} class Top₂ (n : Nat) : Type := (u : Unit := ()) class Bot₂ (n : Nat) : Type := (u : Unit := ()) class Left₂ (n : Nat) : Type := (u : Unit := ()) class Right₂ (n : Nat) : Type := (u : Unit := ()) instance Left₂ToBot₂ (n : Nat) [Left₂ n] : Bot₂ n := {} instance Right₂ToBot₂ (n : Nat) [Right₂ n] : Bot₂ n := {} instance Top₂ToLeft₂ (n : Nat) [Top₂ n] : Left₂ n := {} instance Top₂ToRight₂ (n : Nat) [Top₂ n] : Right₂ n := {} instance Bot₂ToTopSucc (n : Nat) [Bot₂ n] : Top₂ n.succ := {} class Top (n : Nat) : Type := (u : Unit := ()) instance Top₁ToTop (n : Nat) [Top₁ n] : Top n := {} instance Top₂ToTop (n : Nat) [Top₂ n] : Top n := {} new_frontend set_option ppOld false #synth Top Nat.zero.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ def tst : Top Nat.zero.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ := inferInstance
ae1d5238c59d0917c0f4dfbf53157ccf4f649085
64874bd1010548c7f5a6e3e8902efa63baaff785
/tests/lean/K_bug.lean
e0743cd33ad73022a61573f38df85ad52afab596
[ "Apache-2.0" ]
permissive
tjiaqi/lean
4634d729795c164664d10d093f3545287c76628f
d0ce4cf62f4246b0600c07e074d86e51f2195e30
refs/heads/master
1,622,323,796,480
1,422,643,069,000
1,422,643,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
378
lean
open eq.ops inductive Nat : Type := zero : Nat, succ : Nat → Nat namespace Nat definition pred (n : Nat) := Nat.rec zero (fun m x, m) n theorem pred_succ (n : Nat) : pred (succ n) = n := rfl theorem succ_inj {n m : Nat} (H : succ n = succ m) : n = m := calc n = pred (succ n) : pred_succ n⁻¹ ... = pred (succ m) : {H} ... = m : pred_succ m end Nat
2c745d2ea7245d1bc9f7baddf71ad0e46592b19c
01ae0d022f2e2fefdaaa898938c1ac1fbce3b3ab
/categories/examples/graphs.lean
734eeeb791890f16c94246081a91ed40c690bc97
[]
no_license
PatrickMassot/lean-category-theory
0f56a83464396a253c28a42dece16c93baf8ad74
ef239978e91f2e1c3b8e88b6e9c64c155dc56c99
refs/heads/master
1,629,739,187,316
1,512,422,659,000
1,512,422,659,000
113,098,786
0
0
null
1,512,424,022,000
1,512,424,022,000
null
UTF-8
Lean
false
false
1,429
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import ..category open categories open categories.graphs namespace categories.examples.graphs @[applicable] private lemma {u1 v1 u2 v2} GraphHomomorphisms_pointwise_equal { C : Graph.{u1 v1} } { D : Graph.{u2 v2} } { F G : GraphHomomorphism C D } ( objectWitness : ∀ X : C.Obj, F.onObjects X = G.onObjects X ) ( morphismWitness : ∀ X Y : C.Obj, ∀ f : C.Hom X Y, ⟦ F.onMorphisms f ⟧ = G.onMorphisms f ) : F = G := begin induction F with F_onObjects F_onMorphisms, induction G with G_onObjects G_onMorphisms, have h_objects : F_onObjects = G_onObjects, exact funext objectWitness, subst h_objects, have h_morphisms : @F_onMorphisms = @G_onMorphisms, apply funext, intro X, apply funext, intro Y, apply funext, intro f, exact morphismWitness X Y f, subst h_morphisms end definition CategoryOfGraphs : Category := { Obj := Graph, Hom := GraphHomomorphism, identity := λ G, { onObjects := id, onMorphisms := λ _ _ f, f }, compose := λ _ _ _ f g, { onObjects := λ x, g.onObjects (f.onObjects x), onMorphisms := λ _ _ e, g.onMorphisms (f.onMorphisms e) }, right_identity := ♯, left_identity := ♯, associativity := ♯ } end categories.examples.graphs
84990c633dec80b3a66a17de3454e42afdaa5c5a
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/algebra/semigroup.lean
c5ebed196f39244a10022326a7ce3b4c03c14089
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
4,812
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 -/ import topology.separation /-! # Idempotents in topological semigroups > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file provides a sufficient condition for a semigroup `M` to contain an idempotent (i.e. an element `m` such that `m * m = m `), namely that `M` is a nonempty compact Hausdorff space where right-multiplication by constants is continuous. We also state a corresponding lemma guaranteeing that a subset of `M` contains an idempotent. -/ /-- Any nonempty compact Hausdorff semigroup where right-multiplication is continuous contains an idempotent, i.e. an `m` such that `m * m = m`. -/ @[to_additive "Any nonempty compact Hausdorff additive semigroup where right-addition is continuous contains an idempotent, i.e. an `m` such that `m + m = m`"] lemma exists_idempotent_of_compact_t2_of_continuous_mul_left {M} [nonempty M] [semigroup M] [topological_space M] [compact_space M] [t2_space M] (continuous_mul_left : ∀ r : M, continuous (* r)) : ∃ m : M, m * m = m := begin /- We apply Zorn's lemma to the poset of nonempty closed subsemigroups of `M`. It will turn out that any minimal element is `{m}` for an idempotent `m : M`. -/ let S : set (set M) := {N | is_closed N ∧ N.nonempty ∧ ∀ m m' ∈ N, m * m' ∈ N}, rsuffices ⟨N, ⟨N_closed, ⟨m, hm⟩, N_mul⟩, N_minimal⟩ : ∃ N ∈ S, ∀ N' ∈ S, N' ⊆ N → N' = N, { use m, /- We now have an element `m : M` of a minimal subsemigroup `N`, and want to show `m + m = m`. We first show that every element of `N` is of the form `m' + m`.-/ have scaling_eq_self : (* m) '' N = N, { apply N_minimal, { refine ⟨(continuous_mul_left m).is_closed_map _ N_closed, ⟨_, ⟨m, hm, rfl⟩⟩, _⟩, rintros _ ⟨m'', hm'', rfl⟩ _ ⟨m', hm', rfl⟩, refine ⟨m'' * m * m', N_mul _ (N_mul _ hm'' _ hm) _ hm', mul_assoc _ _ _⟩ }, { rintros _ ⟨m', hm', rfl⟩, exact N_mul _ hm' _ hm } }, /- In particular, this means that `m' * m = m` for some `m'`. We now use minimality again to show that this holds for all `m' ∈ N`. -/ have absorbing_eq_self : N ∩ {m' | m' * m = m} = N, { apply N_minimal, { refine ⟨N_closed.inter ((t1_space.t1 m).preimage (continuous_mul_left m)), _, _⟩, { rwa ←scaling_eq_self at hm }, { rintros m'' ⟨mem'', eq'' : _ = m⟩ m' ⟨mem', eq' : _ = m⟩, refine ⟨N_mul _ mem'' _ mem', _⟩, rw [set.mem_set_of_eq, mul_assoc, eq', eq''] } }, apply set.inter_subset_left }, /- Thus `m * m = m` as desired. -/ rw ←absorbing_eq_self at hm, exact hm.2 }, refine zorn_superset _ (λ c hcs hc, _), refine ⟨⋂₀ c, ⟨is_closed_sInter $ λ t ht, (hcs ht).1, _, λ m hm m' hm', _⟩, λ s hs, set.sInter_subset_of_mem hs⟩, { obtain rfl | hcnemp := c.eq_empty_or_nonempty, { rw set.sInter_empty, apply set.univ_nonempty }, convert @is_compact.nonempty_Inter_of_directed_nonempty_compact_closed _ _ _ hcnemp.coe_sort (coe : c → set M) _ _ _ _, { simp only [subtype.range_coe_subtype, set.set_of_mem_eq] } , { refine directed_on.directed_coe (is_chain.directed_on hc.symm) }, exacts [λ i, (hcs i.prop).2.1, λ i, (hcs i.prop).1.is_compact, λ i, (hcs i.prop).1] }, { rw set.mem_sInter, exact λ t ht, (hcs ht).2.2 m (set.mem_sInter.mp hm t ht) m' (set.mem_sInter.mp hm' t ht) }, end /-- A version of `exists_idempotent_of_compact_t2_of_continuous_mul_left` where the idempotent lies in some specified nonempty compact subsemigroup. -/ @[to_additive exists_idempotent_in_compact_add_subsemigroup "A version of `exists_idempotent_of_compact_t2_of_continuous_add_left` where the idempotent lies in some specified nonempty compact additive subsemigroup."] lemma exists_idempotent_in_compact_subsemigroup {M} [semigroup M] [topological_space M] [t2_space M] (continuous_mul_left : ∀ r : M, continuous (* r)) (s : set M) (snemp : s.nonempty) (s_compact : is_compact s) (s_add : ∀ x y ∈ s, x * y ∈ s) : ∃ m ∈ s, m * m = m := begin let M' := {m // m ∈ s}, letI : semigroup M' := { mul := λ p q, ⟨p.1 * q.1, s_add _ p.2 _ q.2⟩, mul_assoc := λ p q r, subtype.eq (mul_assoc _ _ _) }, haveI : compact_space M' := is_compact_iff_compact_space.mp s_compact, haveI : nonempty M' := nonempty_subtype.mpr snemp, have : ∀ p : M', continuous (* p) := λ p, ((continuous_mul_left p.1).comp continuous_subtype_val).subtype_mk _, obtain ⟨⟨m, hm⟩, idem⟩ := exists_idempotent_of_compact_t2_of_continuous_mul_left this, exact ⟨m, hm, subtype.ext_iff.mp idem⟩ end
4263f2e1d42472680fcf020c766b52c1c13430e9
a4673261e60b025e2c8c825dfa4ab9108246c32e
/src/Lean/Data/OpenDecl.lean
b340867cbca7e0ec44e1493963b020a01fee388d
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
761
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Data.Name namespace Lean inductive OpenDecl := | simple (ns : Name) (except : List Name) | explicit (id : Name) (declName : Name) namespace OpenDecl instance : Inhabited OpenDecl := ⟨simple Name.anonymous []⟩ instance : ToString OpenDecl := ⟨fun decl => match decl with | explicit id decl => toString id ++ " → " ++ toString decl | simple ns ex => toString ns ++ (if ex == [] then "" else " hiding " ++ toString ex)⟩ end OpenDecl def rootNamespace := `_root_ def removeRoot (n : Name) : Name := n.replacePrefix rootNamespace Name.anonymous end Lean
42848c52aef786ca0bca00d95a03a0edeea24cb4
947b78d97130d56365ae2ec264df196ce769371a
/src/Lean/Elab/Tactic/Basic.lean
edf36d51291ceafa62dcf371d04e18cff6b7e4d7
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
16,140
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Util.CollectMVars import Lean.Meta.Tactic.Assumption import Lean.Meta.Tactic.Intro import Lean.Meta.Tactic.Clear import Lean.Meta.Tactic.Revert import Lean.Meta.Tactic.Subst import Lean.Elab.Util import Lean.Elab.Term import Lean.Elab.Binders namespace Lean namespace Elab open Meta def goalsToMessageData (goals : List MVarId) : MessageData := MessageData.joinSep (goals.map $ MessageData.ofGoal) (Format.line ++ Format.line) def Term.reportUnsolvedGoals (goals : List MVarId) : TermElabM Unit := do throwError $ "unsolved goals" ++ Format.line ++ goalsToMessageData goals namespace Tactic structure Context := (main : MVarId) structure State := (goals : List MVarId) instance State.inhabited : Inhabited State := ⟨{ goals := [] }⟩ structure BacktrackableState := (env : Environment) (mctx : MetavarContext) (goals : List MVarId) abbrev TacticM := ReaderT Context $ StateRefT State $ TermElabM abbrev Tactic := Syntax → TacticM Unit def saveBacktrackableState : TacticM BacktrackableState := do env ← getEnv; mctx ← getMCtx; s ← get; pure { env := env, mctx := mctx, goals := s.goals } def BacktrackableState.restore (b : BacktrackableState) : TacticM Unit := do setEnv b.env; setMCtx b.mctx; modify fun s => { s with goals := b.goals } @[inline] protected def catch {α} (x : TacticM α) (h : Exception → TacticM α) : TacticM α := do b ← saveBacktrackableState; catch x (fun ex => do b.restore; h ex) @[inline] protected def orelse {α} (x y : TacticM α) : TacticM α := do catch x (fun _ => y) instance monadExcept : MonadExcept Exception TacticM := { throw := fun _ => throw, catch := fun _ x h => Tactic.catch x h } instance hasOrElse {α} : HasOrelse (TacticM α) := ⟨Tactic.orelse⟩ structure SavedState := (core : Core.State) (meta : Meta.State) (term : Term.State) (tactic : State) instance SavedState.inhabited : Inhabited SavedState := ⟨⟨arbitrary _, arbitrary _, arbitrary _, arbitrary _⟩⟩ def saveAllState : TacticM SavedState := do core ← getThe Core.State; meta ← getThe Meta.State; term ← getThe Term.State; tactic ← get; pure { core := core, meta := meta, term := term, tactic := tactic } def SavedState.restore (s : SavedState) : TacticM Unit := do set s.core; set s.meta; set s.term; set s.tactic @[inline] def liftTermElabM {α} (x : TermElabM α) : TacticM α := liftM x @[inline] def liftMetaM {α} (x : MetaM α) : TacticM α := liftTermElabM $ Term.liftMetaM x def ensureHasType (expectedType? : Option Expr) (e : Expr) : TacticM Expr := liftTermElabM $ Term.ensureHasType expectedType? e def reportUnsolvedGoals (goals : List MVarId) : TacticM Unit := liftTermElabM $ Term.reportUnsolvedGoals goals protected def getCurrMacroScope : TacticM MacroScope := do ctx ← readThe Term.Context; pure ctx.currMacroScope protected def getMainModule : TacticM Name := do env ← getEnv; pure env.mainModule unsafe def mkTacticAttribute : IO (KeyedDeclsAttribute Tactic) := mkElabAttribute Tactic `Lean.Elab.Tactic.tacticElabAttribute `builtinTactic `tactic `Lean.Parser.Tactic `Lean.Elab.Tactic.Tactic "tactic" @[init mkTacticAttribute] constant tacticElabAttribute : KeyedDeclsAttribute Tactic := arbitrary _ private def evalTacticUsing (s : SavedState) (stx : Syntax) : List Tactic → TacticM Unit | [] => do throwErrorAt stx ("unexpected syntax" ++ MessageData.nest 2 (Format.line ++ stx)) | (evalFn::evalFns) => catch (evalFn stx) (fun ex => match ex with | Exception.error _ _ => match evalFns with | [] => throw ex | _ => do s.restore; evalTacticUsing evalFns | Exception.internal id => if id == unsupportedSyntaxExceptionId then do s.restore; evalTacticUsing evalFns else throw ex) /- Elaborate `x` with `stx` on the macro stack -/ @[inline] def withMacroExpansion {α} (beforeStx afterStx : Syntax) (x : TacticM α) : TacticM α := adaptTheReader Term.Context (fun ctx => { ctx with macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack }) x @[specialize] private def expandTacticMacroFns (evalTactic : Syntax → TacticM Unit) (stx : Syntax) : List Macro → TacticM Unit | [] => throwErrorAt stx ("tactic '" ++ toString stx.getKind ++ "' has not been implemented") | m::ms => do scp ← getCurrMacroScope; catch (do stx' ← adaptMacro m stx; evalTactic stx') (fun ex => match ms with | [] => throw ex | _ => expandTacticMacroFns ms) @[inline] def expandTacticMacro (evalTactic : Syntax → TacticM Unit) (stx : Syntax) : TacticM Unit := do env ← getEnv; let k := stx.getKind; let table := (macroAttribute.ext.getState env).table; let macroFns := (table.find? k).getD []; expandTacticMacroFns evalTactic stx macroFns partial def evalTactic : Syntax → TacticM Unit | stx => withRef stx $ withIncRecDepth $ withFreshMacroScope $ match stx with | Syntax.node k args => if k == nullKind then -- Macro writers create a sequence of tactics `t₁ ... tₙ` using `mkNullNode #[t₁, ..., tₙ]` stx.getArgs.forM evalTactic else do trace `Elab.step fun _ => stx; env ← getEnv; s ← saveAllState; let table := (tacticElabAttribute.ext.getState env).table; let k := stx.getKind; match table.find? k with | some evalFns => evalTacticUsing s stx evalFns | none => expandTacticMacro evalTactic stx | _ => throwError "unexpected command" /-- Adapt a syntax transformation to a regular tactic evaluator. -/ def adaptExpander (exp : Syntax → TacticM Syntax) : Tactic := fun stx => do stx' ← exp stx; withMacroExpansion stx stx' $ evalTactic stx' def getGoals : TacticM (List MVarId) := do s ← get; pure s.goals def setGoals (gs : List MVarId) : TacticM Unit := modify $ fun s => { s with goals := gs } def appendGoals (gs : List MVarId) : TacticM Unit := modify $ fun s => { s with goals := s.goals ++ gs } def pruneSolvedGoals : TacticM Unit := do gs ← getGoals; gs ← gs.filterM $ fun g => not <$> isExprMVarAssigned g; setGoals gs def getUnsolvedGoals : TacticM (List MVarId) := do pruneSolvedGoals; getGoals def getMainGoal : TacticM (MVarId × List MVarId) := do (g::gs) ← getUnsolvedGoals | throwError "no goals to be solved"; pure (g, gs) def getMainTag : TacticM Name := do (g, _) ← getMainGoal; mvarDecl ← getMVarDecl g; pure mvarDecl.userName def ensureHasNoMVars (e : Expr) : TacticM Unit := do e ← instantiateMVars e; pendingMVars ← getMVars e; liftM $ Term.logUnassignedUsingErrorInfos pendingMVars; when e.hasExprMVar $ throwError ("tactic failed, resulting expression contains metavariables" ++ indentExpr e) def withMainMVarContext {α} (x : TacticM α) : TacticM α := do (mvarId, _) ← getMainGoal; withMVarContext mvarId x @[inline] def liftMetaMAtMain {α} (x : MVarId → MetaM α) : TacticM α := do (g, _) ← getMainGoal; withMVarContext g $ liftMetaM $ x g @[inline] def liftMetaTacticAux {α} (tactic : MVarId → MetaM (α × List MVarId)) : TacticM α := do (g, gs) ← getMainGoal; withMVarContext g $ do (a, gs') ← liftMetaM $ tactic g; setGoals (gs' ++ gs); pure a @[inline] def liftMetaTactic (tactic : MVarId → MetaM (List MVarId)) : TacticM Unit := liftMetaTacticAux (fun mvarId => do gs ← tactic mvarId; pure ((), gs)) def done : TacticM Unit := do gs ← getUnsolvedGoals; unless gs.isEmpty $ reportUnsolvedGoals gs @[builtinTactic Lean.Parser.Tactic.«done»] def evalDone : Tactic := fun _ => done def focusAux {α} (tactic : TacticM α) : TacticM α := do (g, gs) ← getMainGoal; setGoals [g]; a ← tactic; gs' ← getGoals; setGoals (gs' ++ gs); pure a def focus {α} (tactic : TacticM α) : TacticM α := focusAux (do a ← tactic; done; pure a) def try? {α} (tactic : TacticM α) : TacticM (Option α) := catch (do a ← tactic; pure (some a)) (fun _ => pure none) def try {α} (tactic : TacticM α) : TacticM Bool := catch (do tactic; pure true) (fun _ => pure false) /-- Use `parentTag` to tag untagged goals at `newGoals`. If there are multiple new untagged goals, they are named using `<parentTag>.<newSuffix>_<idx>` where `idx > 0`. If there is only one new untagged goal, then we just use `parentTag` -/ def tagUntaggedGoals (parentTag : Name) (newSuffix : Name) (newGoals : List MVarId) : TacticM Unit := do mctx ← getMCtx; let numAnonymous := newGoals.foldl (fun n g => if mctx.isAnonymousMVar g then n + 1 else n) 0; modifyMCtx fun mctx => let (mctx, _) := newGoals.foldl (fun (acc : MetavarContext × Nat) (g : MVarId) => let (mctx, idx) := acc; if mctx.isAnonymousMVar g then if numAnonymous == 1 then (mctx.renameMVar g parentTag, idx+1) else (mctx.renameMVar g (parentTag ++ newSuffix.appendIndexAfter idx), idx+1) else acc) (mctx, 1); mctx def evalSeq : Tactic := fun stx => (stx.getArg 0).forSepArgsM evalTactic @[builtinTactic seq1] def evalSeq1 : Tactic := evalSeq @[builtinTactic tacticSeq1Indented] def evalTacticSeq1Indented : Tactic := evalSeq @[builtinTactic tacticSeqBracketed] def evalTacticSeqBracketed : Tactic := fun stx => withRef (stx.getArg 2) $ focus $ (stx.getArg 1).forSepArgsM evalTactic @[builtinTactic Parser.Tactic.focus] def evalFocus : Tactic := fun stx => focus $ evalTactic (stx.getArg 1) @[builtinTactic paren] def evalParen : Tactic := fun stx => evalSeq1 (stx.getArg 1) @[builtinTactic tacticSeq] def evalTacticSeq : Tactic := fun stx => evalTactic (stx.getArg 0) partial def evalChoiceAux (tactics : Array Syntax) : Nat → TacticM Unit | i => if h : i < tactics.size then let tactic := tactics.get ⟨i, h⟩; catchInternalId unsupportedSyntaxExceptionId (evalTactic tactic) (fun _ => evalChoiceAux (i+1)) else throwUnsupportedSyntax @[builtinTactic choice] def evalChoice : Tactic := fun stx => evalChoiceAux stx.getArgs 0 @[builtinTactic skip] def evalSkip : Tactic := fun stx => pure () @[builtinTactic failIfSuccess] def evalFailIfSuccess : Tactic := fun stx => let tactic := stx.getArg 1; whenM (catch (do evalTactic tactic; pure true) (fun _ => pure false)) (throwError ("tactic succeeded")) @[builtinTactic traceState] def evalTraceState : Tactic := fun stx => do gs ← getUnsolvedGoals; logInfo (goalsToMessageData gs) @[builtinTactic Lean.Parser.Tactic.assumption] def evalAssumption : Tactic := fun stx => liftMetaTactic $ fun mvarId => do Meta.assumption mvarId; pure [] private def introStep (n : Name) : TacticM Unit := liftMetaTactic $ fun mvarId => do (_, mvarId) ← Meta.intro mvarId n; pure [mvarId] @[builtinTactic Lean.Parser.Tactic.intro] def evalIntro : Tactic := fun stx => match_syntax stx with | `(tactic| intro) => liftMetaTactic $ fun mvarId => do (_, mvarId) ← Meta.intro1 mvarId; pure [mvarId] | `(tactic| intro $h:ident) => introStep h.getId | `(tactic| intro _) => introStep `_ | `(tactic| intro $pat:term) => do stxNew ← `(tactic| intro h; match h with | $pat:term => _; clear h); withMacroExpansion stx stxNew $ evalTactic stxNew | `(tactic| intro $hs:term*) => do let h0 := hs.get! 0; let hs := hs.extract 1 hs.size; stxNew ← `(tactic| intro $h0:term; intro $hs:term*); withMacroExpansion stx stxNew $ evalTactic stxNew | _ => throwUnsupportedSyntax @[builtinTactic Lean.Parser.Tactic.introMatch] def evalIntroMatch : Tactic := fun stx => do let matchAlts := stx.getArg 1; stxNew ← liftMacroM $ Term.expandMatchAltsIntoMatchTactic stx matchAlts; withMacroExpansion stx stxNew $ evalTactic stxNew private def getIntrosSize : Expr → Nat | Expr.forallE _ _ b _ => getIntrosSize b + 1 | Expr.letE _ _ _ b _ => getIntrosSize b + 1 | _ => 0 @[builtinTactic «intros»] def evalIntros : Tactic := fun stx => match_syntax stx with | `(tactic| intros) => liftMetaTactic $ fun mvarId => do type ← Meta.getMVarType mvarId; type ← instantiateMVars type; let n := getIntrosSize type; (_, mvarId) ← Meta.introN mvarId n; pure [mvarId] | `(tactic| intros $ids*) => liftMetaTactic $ fun mvarId => do (_, mvarId) ← Meta.introN mvarId ids.size (ids.map Syntax.getId).toList; pure [mvarId] | _ => throwUnsupportedSyntax def getFVarId (id : Syntax) : TacticM FVarId := withRef id do fvar? ← liftTermElabM $ Term.isLocalIdent? id; match fvar? with | some fvar => pure fvar.fvarId! | none => throwError ("unknown variable '" ++ toString id.getId ++ "'") def getFVarIds (ids : Array Syntax) : TacticM (Array FVarId) := do withMainMVarContext $ ids.mapM getFVarId @[builtinTactic Lean.Parser.Tactic.revert] def evalRevert : Tactic := fun stx => match_syntax stx with | `(tactic| revert $hs*) => do (g, gs) ← getMainGoal; fvarIds ← getFVarIds hs; (_, g) ← liftMetaM $ Meta.revert g fvarIds; setGoals (g :: gs) | _ => throwUnsupportedSyntax /- Sort free variables using an order `x < y` iff `x` was defined after `y` -/ private def sortFVarIds (fvarIds : Array FVarId) : TacticM (Array FVarId) := withMainMVarContext do lctx ← getLCtx; pure $ fvarIds.qsort fun fvarId₁ fvarId₂ => match lctx.find? fvarId₁, lctx.find? fvarId₂ with | some d₁, some d₂ => d₁.index > d₂.index | some _, none => false | none, some _ => true | none, none => Name.quickLt fvarId₁ fvarId₂ @[builtinTactic Lean.Parser.Tactic.clear] def evalClear : Tactic := fun stx => match_syntax stx with | `(tactic| clear $hs*) => do fvarIds ← getFVarIds hs; fvarIds ← sortFVarIds fvarIds; fvarIds.forM fun fvarId => do (g, gs) ← getMainGoal; withMVarContext g do g ← liftMetaM $ clear g fvarId; setGoals (g :: gs) | _ => throwUnsupportedSyntax def forEachVar (hs : Array Syntax) (tac : MVarId → FVarId → MetaM MVarId) : TacticM Unit := hs.forM $ fun h => do (g, gs) ← getMainGoal; withMVarContext g do fvarId ← getFVarId h; g ← liftMetaM $ tac g fvarId; setGoals (g :: gs) @[builtinTactic Lean.Parser.Tactic.subst] def evalSubst : Tactic := fun stx => match_syntax stx with | `(tactic| subst $hs*) => forEachVar hs Meta.subst | _ => throwUnsupportedSyntax /-- First method searches for a metavariable `g` s.t. `tag` is a suffix of its name. If none is found, then it searches for a metavariable `g` s.t. `tag` is a prefix of its name. -/ private def findTag? (gs : List MVarId) (tag : Name) : TacticM (Option MVarId) := do g? ← gs.findM? (fun g => do mvarDecl ← getMVarDecl g; pure $ tag.isSuffixOf mvarDecl.userName); match g? with | some g => pure g | none => gs.findM? (fun g => do mvarDecl ← getMVarDecl g; pure $ tag.isPrefixOf mvarDecl.userName) @[builtinTactic «case»] def evalCase : Tactic := fun stx => match_syntax stx with | `(tactic| case $tag => $tac:tacticSeq) => do let tag := tag.getId; gs ← getUnsolvedGoals; some g ← findTag? gs tag | throwError "tag not found"; let gs := gs.erase g; setGoals [g]; savedTag ← liftM $ getMVarTag g; liftM $ setMVarTag g Name.anonymous; finally (evalTactic tac) (liftM $ setMVarTag g savedTag); done; setGoals gs | _ => throwUnsupportedSyntax @[builtinTactic «orelse»] def evalOrelse : Tactic := fun stx => match_syntax stx with | `(tactic| $tac1 <|> $tac2) => evalTactic tac1 <|> evalTactic tac2 | _ => throwUnsupportedSyntax @[init] private def regTraceClasses : IO Unit := do registerTraceClass `Elab.tactic; pure () @[inline] def TacticM.run {α} (x : TacticM α) (ctx : Context) (s : State) : TermElabM (α × State) := (x.run ctx).run s @[inline] def TacticM.run' {α} (x : TacticM α) (ctx : Context) (s : State) : TermElabM α := Prod.fst <$> x.run ctx s end Tactic end Elab end Lean
37a53c7096cf771474bb290e96ad501b096d5df0
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/stage0/src/Lean/Elab/StructInst.lean
d18bdd351994a038dba728b52a4d73aa1f2ee162
[ "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
34,674
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.Util.FindExpr import Lean.Parser.Term import Lean.Elab.App import Lean.Elab.Binders namespace Lean.Elab.Term.StructInst open Std (HashMap) open Meta /- Structure instances are of the form: "{" >> optional (atomic (termParser >> " with ")) >> manyIndent (group ((structInstFieldAbbrev <|> structInstField) >> optional ", ")) >> optEllipsis >> optional (" : " >> termParser) >> " }" -/ @[builtinMacro Lean.Parser.Term.structInst] def expandStructInstExpectedType : Macro := fun stx => let expectedArg := stx[4] if expectedArg.isNone then Macro.throwUnsupported else let expected := expectedArg[1] let stxNew := stx.setArg 4 mkNullNode `(($stxNew : $expected)) /- If `stx` is of the form `{ s with ... }` and `s` is not a local variable, expand into `let src := s; { src with ... }`. Note that this one is not a `Macro` because we need to access the local context. -/ private def expandNonAtomicExplicitSource (stx : Syntax) : TermElabM (Option Syntax) := withFreshMacroScope do let sourceOpt := stx[1] if sourceOpt.isNone then pure none else let source := sourceOpt[0] match (← isLocalIdent? source) with | some _ => pure none | none => if source.isMissing then throwAbortTerm else let src ← `(src) let sourceOpt := sourceOpt.setArg 0 src let stxNew := stx.setArg 1 sourceOpt `(let src := $source; $stxNew) inductive Source where | none -- structure instance source has not been provieded | implicit (stx : Syntax) -- `..` | explicit (stx : Syntax) (src : Expr) -- `src with` deriving Inhabited def Source.isNone : Source → Bool | Source.none => true | _ => false def setStructSourceSyntax (structStx : Syntax) : Source → Syntax | Source.none => (structStx.setArg 1 mkNullNode).setArg 3 mkNullNode | Source.implicit stx => (structStx.setArg 1 mkNullNode).setArg 3 stx | Source.explicit stx _ => (structStx.setArg 1 stx).setArg 3 mkNullNode private def getStructSource (stx : Syntax) : TermElabM Source := withRef stx do let explicitSource := stx[1] let implicitSource := stx[3] if explicitSource.isNone && implicitSource[0].isNone then return Source.none else if explicitSource.isNone then return Source.implicit implicitSource else if implicitSource[0].isNone then let fvar? ← isLocalIdent? explicitSource[0] match fvar? with | none => unreachable! -- expandNonAtomicExplicitSource must have been used when we get here | some src => return Source.explicit explicitSource src else throwError "invalid structure instance `with` and `..` cannot be used together" /- We say a `{ ... }` notation is a `modifyOp` if it contains only one ``` def structInstArrayRef := leading_parser "[" >> termParser >>"]" ``` -/ private def isModifyOp? (stx : Syntax) : TermElabM (Option Syntax) := do let s? ← stx[2].getArgs.foldlM (init := none) fun s? p => /- p is of the form `(group ((structInstFieldAbbrev <|> structInstField) >> optional ", "))` -/ let arg := p[0] if arg.getKind == ``Lean.Parser.Term.structInstField then /- Remark: the syntax for `structInstField` is ``` def structInstLVal := leading_parser (ident <|> numLit <|> structInstArrayRef) >> many (group ("." >> (ident <|> numLit)) <|> structInstArrayRef) def structInstField := leading_parser structInstLVal >> " := " >> termParser ``` -/ let lval := arg[0] let k := lval[0].getKind if k == ``Lean.Parser.Term.structInstArrayRef then match s? with | none => pure (some arg) | some s => if s.getKind == ``Lean.Parser.Term.structInstArrayRef then throwErrorAt arg "invalid \{...} notation, at most one `[..]` at a given level" else throwErrorAt arg "invalid \{...} notation, can't mix field and `[..]` at a given level" else match s? with | none => pure (some arg) | some s => if s.getKind == ``Lean.Parser.Term.structInstArrayRef then throwErrorAt arg "invalid \{...} notation, can't mix field and `[..]` at a given level" else pure s? else pure s? match s? with | none => pure none | some s => if s[0][0].getKind == ``Lean.Parser.Term.structInstArrayRef then pure s? else pure none private def elabModifyOp (stx modifyOp source : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do let cont (val : Syntax) : TermElabM Expr := do let lval := modifyOp[0][0] let idx := lval[1] let self := source[0] let stxNew ← `($(self).modifyOp (idx := $idx) (fun s => $val)) trace[Elab.struct.modifyOp] "{stx}\n===>\n{stxNew}" withMacroExpansion stx stxNew <| elabTerm stxNew expectedType? trace[Elab.struct.modifyOp] "{modifyOp}\nSource: {source}" let rest := modifyOp[0][1] if rest.isNone then cont modifyOp[2] else let s ← `(s) let valFirst := rest[0] let valFirst := if valFirst.getKind == ``Lean.Parser.Term.structInstArrayRef then valFirst else valFirst[1] let restArgs := rest.getArgs let valRest := mkNullNode restArgs[1:restArgs.size] let valField := modifyOp.setArg 0 <| Syntax.node ``Parser.Term.structInstLVal #[valFirst, valRest] let valSource := source.modifyArg 0 fun _ => s let val := stx.setArg 1 valSource let val := val.setArg 2 <| mkNullNode #[mkNullNode #[valField, mkNullNode]] trace[Elab.struct.modifyOp] "{stx}\nval: {val}" cont val /- Get structure name and elaborate explicit source (if available) -/ private def getStructName (stx : Syntax) (expectedType? : Option Expr) (sourceView : Source) : TermElabM (Name × Expr) := do tryPostponeIfNoneOrMVar expectedType? let useSource : Unit → TermElabM (Name × Expr) := fun _ => match sourceView, expectedType? with | Source.explicit _ src, _ => do let srcType ← inferType src let srcType ← whnf srcType tryPostponeIfMVar srcType match srcType.getAppFn with | Expr.const constName _ _ => return (constName, srcType) | _ => throwUnexpectedExpectedType srcType "source" | _, some expectedType => throwUnexpectedExpectedType expectedType | _, none => throwUnknownExpectedType match expectedType? with | none => useSource () | some expectedType => let expectedType ← whnf expectedType match expectedType.getAppFn with | Expr.const constName _ _ => return (constName, expectedType) | _ => useSource () where throwUnknownExpectedType := throwError "invalid \{...} notation, expected type is not known" throwUnexpectedExpectedType type (kind := "expected") := do let type ← instantiateMVars type if type.getAppFn.isMVar then throwUnknownExpectedType else throwError "invalid \{...} notation, {kind} type is not of the form (C ...){indentExpr type}" inductive FieldLHS where | fieldName (ref : Syntax) (name : Name) | fieldIndex (ref : Syntax) (idx : Nat) | modifyOp (ref : Syntax) (index : Syntax) deriving Inhabited instance : ToFormat FieldLHS := ⟨fun lhs => match lhs with | FieldLHS.fieldName _ n => fmt n | FieldLHS.fieldIndex _ i => fmt i | FieldLHS.modifyOp _ i => "[" ++ i.prettyPrint ++ "]"⟩ inductive FieldVal (σ : Type) where | term (stx : Syntax) : FieldVal σ | nested (s : σ) : FieldVal σ | default : FieldVal σ -- mark that field must be synthesized using default value deriving Inhabited structure Field (σ : Type) where ref : Syntax lhs : List FieldLHS val : FieldVal σ expr? : Option Expr := none deriving Inhabited def Field.isSimple {σ} : Field σ → Bool | { lhs := [_], .. } => true | _ => false inductive Struct where | mk (ref : Syntax) (structName : Name) (fields : List (Field Struct)) (source : Source) deriving Inhabited abbrev Fields := List (Field Struct) /- true if all fields of the given structure are marked as `default` -/ partial def Struct.allDefault : Struct → Bool | ⟨_, _, fields, _⟩ => fields.all fun ⟨_, _, val, _⟩ => match val with | FieldVal.term _ => false | FieldVal.default => true | FieldVal.nested s => allDefault s def Struct.ref : Struct → Syntax | ⟨ref, _, _, _⟩ => ref def Struct.structName : Struct → Name | ⟨_, structName, _, _⟩ => structName def Struct.fields : Struct → Fields | ⟨_, _, fields, _⟩ => fields def Struct.source : Struct → Source | ⟨_, _, _, s⟩ => s def formatField (formatStruct : Struct → Format) (field : Field Struct) : Format := Format.joinSep field.lhs " . " ++ " := " ++ match field.val with | FieldVal.term v => v.prettyPrint | FieldVal.nested s => formatStruct s | FieldVal.default => "<default>" partial def formatStruct : Struct → Format | ⟨_, structName, fields, source⟩ => let fieldsFmt := Format.joinSep (fields.map (formatField formatStruct)) ", " match source with | Source.none => "{" ++ fieldsFmt ++ "}" | Source.implicit _ => "{" ++ fieldsFmt ++ " .. }" | Source.explicit _ src => "{" ++ format src ++ " with " ++ fieldsFmt ++ "}" instance : ToFormat Struct := ⟨formatStruct⟩ instance : ToString Struct := ⟨toString ∘ format⟩ instance : ToFormat (Field Struct) := ⟨formatField formatStruct⟩ instance : ToString (Field Struct) := ⟨toString ∘ format⟩ /- Recall that `structInstField` elements have the form ``` def structInstField := leading_parser structInstLVal >> " := " >> termParser def structInstLVal := leading_parser (ident <|> numLit <|> structInstArrayRef) >> many (("." >> (ident <|> numLit)) <|> structInstArrayRef) def structInstArrayRef := leading_parser "[" >> termParser >>"]" ``` -/ -- Remark: this code relies on the fact that `expandStruct` only transforms `fieldLHS.fieldName` def FieldLHS.toSyntax (first : Bool) : FieldLHS → Syntax | FieldLHS.modifyOp stx _ => stx | FieldLHS.fieldName stx name => if first then mkIdentFrom stx name else mkGroupNode #[mkAtomFrom stx ".", mkIdentFrom stx name] | FieldLHS.fieldIndex stx _ => if first then stx else mkGroupNode #[mkAtomFrom stx ".", stx] def FieldVal.toSyntax : FieldVal Struct → Syntax | FieldVal.term stx => stx | _ => unreachable! def Field.toSyntax : Field Struct → Syntax | field => let stx := field.ref let stx := stx.setArg 2 field.val.toSyntax match field.lhs with | first::rest => stx.setArg 0 <| mkNullNode #[first.toSyntax true, mkNullNode <| rest.toArray.map (FieldLHS.toSyntax false) ] | _ => unreachable! private def toFieldLHS (stx : Syntax) : MacroM FieldLHS := if stx.getKind == ``Lean.Parser.Term.structInstArrayRef then return FieldLHS.modifyOp stx stx[1] else -- Note that the representation of the first field is different. let stx := if stx.getKind == groupKind then stx[1] else stx if stx.isIdent then return FieldLHS.fieldName stx stx.getId.eraseMacroScopes else match stx.isFieldIdx? with | some idx => return FieldLHS.fieldIndex stx idx | none => Macro.throwError "unexpected structure syntax" private def mkStructView (stx : Syntax) (structName : Name) (source : Source) : MacroM Struct := do /- Recall that `stx` is of the form ``` leading_parser "{" >> optional (atomic (termParser >> " with ")) >> manyIndent (group ((structInstFieldAbbrev <|> structInstField) >> optional ", ")) >> optional ".." >> optional (" : " >> termParser) >> " }" ``` -/ let fieldsStx ← stx[2].getArgs.mapM fun stx => let stx := stx[0] if stx.getKind == ``Lean.Parser.Term.structInstField then return stx else let id := stx[0] `(Lean.Parser.Term.structInstField| $id:ident := $id:ident) let fields ← fieldsStx.toList.mapM fun fieldStx => do let val := fieldStx[2] let first ← toFieldLHS fieldStx[0][0] let rest ← fieldStx[0][1].getArgs.toList.mapM toFieldLHS pure { ref := fieldStx, lhs := first :: rest, val := FieldVal.term val : Field Struct } pure ⟨stx, structName, fields, source⟩ def Struct.modifyFieldsM {m : Type → Type} [Monad m] (s : Struct) (f : Fields → m Fields) : m Struct := match s with | ⟨ref, structName, fields, source⟩ => return ⟨ref, structName, (← f fields), source⟩ def Struct.modifyFields (s : Struct) (f : Fields → Fields) : Struct := Id.run <| s.modifyFieldsM f def Struct.setFields (s : Struct) (fields : Fields) : Struct := s.modifyFields fun _ => fields private def expandCompositeFields (s : Struct) : Struct := s.modifyFields fun fields => fields.map fun field => match field with | { lhs := FieldLHS.fieldName ref (Name.str Name.anonymous _ _) :: rest, .. } => field | { lhs := FieldLHS.fieldName ref n@(Name.str _ _ _) :: rest, .. } => let newEntries := n.components.map <| FieldLHS.fieldName ref { field with lhs := newEntries ++ rest } | _ => field private def expandNumLitFields (s : Struct) : TermElabM Struct := s.modifyFieldsM fun fields => do let env ← getEnv let fieldNames := getStructureFields env s.structName fields.mapM fun field => match field with | { lhs := FieldLHS.fieldIndex ref idx :: rest, .. } => if idx == 0 then throwErrorAt ref "invalid field index, index must be greater than 0" else if idx > fieldNames.size then throwErrorAt ref "invalid field index, structure has only #{fieldNames.size} fields" else pure { field with lhs := FieldLHS.fieldName ref fieldNames[idx - 1] :: rest } | _ => pure field /- For example, consider the following structures: ``` structure A where x : Nat structure B extends A where y : Nat structure C extends B where z : Bool ``` This method expands parent structure fields using the path to the parent structure. For example, ``` { x := 0, y := 0, z := true : C } ``` is expanded into ``` { toB.toA.x := 0, toB.y := 0, z := true : C } ``` -/ private def expandParentFields (s : Struct) : TermElabM Struct := do let env ← getEnv s.modifyFieldsM fun fields => fields.mapM fun field => match field with | { lhs := FieldLHS.fieldName ref fieldName :: rest, .. } => match findField? env s.structName fieldName with | none => throwErrorAt ref "'{fieldName}' is not a field of structure '{s.structName}'" | some baseStructName => if baseStructName == s.structName then pure field else match getPathToBaseStructure? env baseStructName s.structName with | some path => do let path := path.map fun funName => match funName with | Name.str _ s _ => FieldLHS.fieldName ref (Name.mkSimple s) | _ => unreachable! pure { field with lhs := path ++ field.lhs } | _ => throwErrorAt ref "failed to access field '{fieldName}' in parent structure" | _ => pure field private abbrev FieldMap := HashMap Name Fields private def mkFieldMap (fields : Fields) : TermElabM FieldMap := fields.foldlM (init := {}) fun fieldMap field => match field.lhs with | FieldLHS.fieldName _ fieldName :: rest => match fieldMap.find? fieldName with | some (prevField::restFields) => if field.isSimple || prevField.isSimple then throwErrorAt field.ref "field '{fieldName}' has already beed specified" else return fieldMap.insert fieldName (field::prevField::restFields) | _ => return fieldMap.insert fieldName [field] | _ => unreachable! private def isSimpleField? : Fields → Option (Field Struct) | [field] => if field.isSimple then some field else none | _ => none private def getFieldIdx (structName : Name) (fieldNames : Array Name) (fieldName : Name) : TermElabM Nat := do match fieldNames.findIdx? fun n => n == fieldName with | some idx => pure idx | none => throwError "field '{fieldName}' is not a valid field of '{structName}'" private def mkProjStx (s : Syntax) (fieldName : Name) : Syntax := Syntax.node ``Lean.Parser.Term.proj #[s, mkAtomFrom s ".", mkIdentFrom s fieldName] private def mkSubstructSource (structName : Name) (fieldNames : Array Name) (fieldName : Name) (src : Source) : TermElabM Source := match src with | Source.explicit stx src => do let idx ← getFieldIdx structName fieldNames fieldName let stx := stx.modifyArg 0 fun stx => mkProjStx stx fieldName return Source.explicit stx (mkProj structName idx src) | s => return s private def groupFields (expandStruct : Struct → TermElabM Struct) (s : Struct) : TermElabM Struct := do let env ← getEnv let fieldNames := getStructureFields env s.structName withRef s.ref do s.modifyFieldsM fun fields => do let fieldMap ← mkFieldMap fields fieldMap.toList.mapM fun ⟨fieldName, fields⟩ => do match isSimpleField? fields with | some field => pure field | none => let substructFields := fields.map fun field => { field with lhs := field.lhs.tail! } let substructSource ← mkSubstructSource s.structName fieldNames fieldName s.source let field := fields.head! match Lean.isSubobjectField? env s.structName fieldName with | some substructName => let substruct := Struct.mk s.ref substructName substructFields substructSource let substruct ← expandStruct substruct pure { field with lhs := [field.lhs.head!], val := FieldVal.nested substruct } | none => do -- It is not a substructure field. Thus, we wrap fields using `Syntax`, and use `elabTerm` to process them. let valStx := s.ref -- construct substructure syntax using s.ref as template let valStx := valStx.setArg 4 mkNullNode -- erase optional expected type let args := substructFields.toArray.map fun field => mkNullNode #[field.toSyntax, mkNullNode] let valStx := valStx.setArg 2 (mkNullNode args) let valStx := setStructSourceSyntax valStx substructSource pure { field with lhs := [field.lhs.head!], val := FieldVal.term valStx } def findField? (fields : Fields) (fieldName : Name) : Option (Field Struct) := fields.find? fun field => match field.lhs with | [FieldLHS.fieldName _ n] => n == fieldName | _ => false private def addMissingFields (expandStruct : Struct → TermElabM Struct) (s : Struct) : TermElabM Struct := do let env ← getEnv let fieldNames := getStructureFields env s.structName let ref := s.ref withRef ref do let fields ← fieldNames.foldlM (init := []) fun fields fieldName => do match findField? s.fields fieldName with | some field => return field::fields | none => let addField (val : FieldVal Struct) : TermElabM Fields := do return { ref := s.ref, lhs := [FieldLHS.fieldName s.ref fieldName], val := val } :: fields match Lean.isSubobjectField? env s.structName fieldName with | some substructName => do let substructSource ← mkSubstructSource s.structName fieldNames fieldName s.source let substruct := Struct.mk s.ref substructName [] substructSource let substruct ← expandStruct substruct addField (FieldVal.nested substruct) | none => match s.source with | Source.none => addField FieldVal.default | Source.implicit _ => addField (FieldVal.term (mkHole s.ref)) | Source.explicit stx _ => -- stx is of the form `optional (try (termParser >> "with"))` let src := stx[0] let val := mkProjStx src fieldName addField (FieldVal.term val) return s.setFields fields.reverse private partial def expandStruct (s : Struct) : TermElabM Struct := do let s := expandCompositeFields s let s ← expandNumLitFields s let s ← expandParentFields s let s ← groupFields expandStruct s addMissingFields expandStruct s structure CtorHeaderResult where ctorFn : Expr ctorFnType : Expr instMVars : Array MVarId := #[] private def mkCtorHeaderAux : Nat → Expr → Expr → Array MVarId → TermElabM CtorHeaderResult | 0, type, ctorFn, instMVars => pure { ctorFn := ctorFn, ctorFnType := type, instMVars := instMVars } | n+1, type, ctorFn, instMVars => do let type ← whnfForall type match type with | Expr.forallE _ d b c => match c.binderInfo with | BinderInfo.instImplicit => let a ← mkFreshExprMVar d MetavarKind.synthetic mkCtorHeaderAux n (b.instantiate1 a) (mkApp ctorFn a) (instMVars.push a.mvarId!) | _ => let a ← mkFreshExprMVar d mkCtorHeaderAux n (b.instantiate1 a) (mkApp ctorFn a) instMVars | _ => throwError "unexpected constructor type" private partial def getForallBody : Nat → Expr → Option Expr | i+1, Expr.forallE _ _ b _ => getForallBody i b | i+1, _ => none | 0, type => type private def propagateExpectedType (type : Expr) (numFields : Nat) (expectedType? : Option Expr) : TermElabM Unit := match expectedType? with | none => pure () | some expectedType => do match getForallBody numFields type with | none => pure () | some typeBody => unless typeBody.hasLooseBVars do discard <| isDefEq expectedType typeBody private def mkCtorHeader (ctorVal : ConstructorVal) (expectedType? : Option Expr) : TermElabM CtorHeaderResult := do let us ← mkFreshLevelMVars ctorVal.levelParams.length let val := Lean.mkConst ctorVal.name us let type := (ConstantInfo.ctorInfo ctorVal).instantiateTypeLevelParams us let r ← mkCtorHeaderAux ctorVal.numParams type val #[] propagateExpectedType r.ctorFnType ctorVal.numFields expectedType? synthesizeAppInstMVars r.instMVars pure r def markDefaultMissing (e : Expr) : Expr := mkAnnotation `structInstDefault e def defaultMissing? (e : Expr) : Option Expr := annotation? `structInstDefault e def throwFailedToElabField {α} (fieldName : Name) (structName : Name) (msgData : MessageData) : TermElabM α := throwError "failed to elaborate field '{fieldName}' of '{structName}, {msgData}" def trySynthStructInstance? (s : Struct) (expectedType : Expr) : TermElabM (Option Expr) := do if !s.allDefault then pure none else try synthInstance? expectedType catch _ => pure none private partial def elabStruct (s : Struct) (expectedType? : Option Expr) : TermElabM (Expr × Struct) := withRef s.ref do let env ← getEnv let ctorVal := getStructureCtor env s.structName let { ctorFn := ctorFn, ctorFnType := ctorFnType, .. } ← mkCtorHeader ctorVal expectedType? let (e, _, fields) ← s.fields.foldlM (init := (ctorFn, ctorFnType, [])) fun (e, type, fields) field => match field.lhs with | [FieldLHS.fieldName ref fieldName] => do let type ← whnfForall type match type with | Expr.forallE _ d b c => let cont (val : Expr) (field : Field Struct) : TermElabM (Expr × Expr × Fields) := do pushInfoTree <| InfoTree.node (children := {}) <| Info.ofFieldInfo { lctx := (← getLCtx), val := val, name := fieldName, stx := ref } let e := mkApp e val let type := b.instantiate1 val let field := { field with expr? := some val } pure (e, type, field::fields) match field.val with | FieldVal.term stx => cont (← elabTermEnsuringType stx d) field | FieldVal.nested s => do -- if all fields of `s` are marked as `default`, then try to synthesize instance match (← trySynthStructInstance? s d) with | some val => cont val { field with val := FieldVal.term (mkHole field.ref) } | none => do let (val, sNew) ← elabStruct s (some d); let val ← ensureHasType d val; cont val { field with val := FieldVal.nested sNew } | FieldVal.default => do let val ← withRef field.ref <| mkFreshExprMVar (some d); cont (markDefaultMissing val) field | _ => withRef field.ref <| throwFailedToElabField fieldName s.structName m!"unexpected constructor type{indentExpr type}" | _ => throwErrorAt field.ref "unexpected unexpanded structure field" pure (e, s.setFields fields.reverse) namespace DefaultFields structure Context where -- We must search for default values overriden in derived structures structs : Array Struct := #[] allStructNames : Array Name := #[] /-- Consider the following example: ``` structure A where x : Nat := 1 structure B extends A where y : Nat := x + 1 x := y + 1 structure C extends B where z : Nat := 2*y x := z + 3 ``` And we are trying to elaborate a structure instance for `C`. There are default values for `x` at `A`, `B`, and `C`. We say the default value at `C` has distance 0, the one at `B` distance 1, and the one at `A` distance 2. The field `maxDistance` specifies the maximum distance considered in a round of Default field computation. Remark: since `C` does not set a default value of `y`, the default value at `B` is at distance 0. The fixpoint for setting default values works in the following way. - Keep computing default values using `maxDistance == 0`. - We increase `maxDistance` whenever we failed to compute a new default value in a round. - If `maxDistance > 0`, then we interrupt a round as soon as we compute some default value. We use depth-first search. - We sign an error if no progress is made when `maxDistance` == structure hierarchy depth (2 in the example above). -/ maxDistance : Nat := 0 structure State where progress : Bool := false partial def collectStructNames (struct : Struct) (names : Array Name) : Array Name := let names := names.push struct.structName struct.fields.foldl (init := names) fun names field => match field.val with | FieldVal.nested struct => collectStructNames struct names | _ => names partial def getHierarchyDepth (struct : Struct) : Nat := struct.fields.foldl (init := 0) fun max field => match field.val with | FieldVal.nested struct => Nat.max max (getHierarchyDepth struct + 1) | _ => max partial def findDefaultMissing? (mctx : MetavarContext) (struct : Struct) : Option (Field Struct) := struct.fields.findSome? fun field => match field.val with | FieldVal.nested struct => findDefaultMissing? mctx struct | _ => match field.expr? with | none => unreachable! | some expr => match defaultMissing? expr with | some (Expr.mvar mvarId _) => if mctx.isExprAssigned mvarId then none else some field | _ => none def getFieldName (field : Field Struct) : Name := match field.lhs with | [FieldLHS.fieldName _ fieldName] => fieldName | _ => unreachable! abbrev M := ReaderT Context (StateRefT State TermElabM) def isRoundDone : M Bool := do return (← get).progress && (← read).maxDistance > 0 def getFieldValue? (struct : Struct) (fieldName : Name) : Option Expr := struct.fields.findSome? fun field => if getFieldName field == fieldName then field.expr? else none partial def mkDefaultValueAux? (struct : Struct) : Expr → TermElabM (Option Expr) | Expr.lam n d b c => withRef struct.ref do if c.binderInfo.isExplicit then let fieldName := n match getFieldValue? struct fieldName with | none => pure none | some val => let valType ← inferType val if (← isDefEq valType d) then mkDefaultValueAux? struct (b.instantiate1 val) else pure none else let arg ← mkFreshExprMVar d mkDefaultValueAux? struct (b.instantiate1 arg) | e => if e.isAppOfArity ``id 2 then pure (some e.appArg!) else pure (some e) def mkDefaultValue? (struct : Struct) (cinfo : ConstantInfo) : TermElabM (Option Expr) := withRef struct.ref do let us ← mkFreshLevelMVarsFor cinfo mkDefaultValueAux? struct (cinfo.instantiateValueLevelParams us) /-- If `e` is a projection function of one of the given structures, then reduce it -/ def reduceProjOf? (structNames : Array Name) (e : Expr) : MetaM (Option Expr) := do if !e.isApp then pure none else match e.getAppFn with | Expr.const name _ _ => do let env ← getEnv match env.getProjectionStructureName? name with | some structName => if structNames.contains structName then Meta.unfoldDefinition? e else pure none | none => pure none | _ => pure none /-- Reduce default value. It performs beta reduction and projections of the given structures. -/ partial def reduce (structNames : Array Name) : Expr → MetaM Expr | e@(Expr.lam _ _ _ _) => lambdaLetTelescope e fun xs b => do mkLambdaFVars xs (← reduce structNames b) | e@(Expr.forallE _ _ _ _) => forallTelescope e fun xs b => do mkForallFVars xs (← reduce structNames b) | e@(Expr.letE _ _ _ _ _) => lambdaLetTelescope e fun xs b => do mkLetFVars xs (← reduce structNames b) | e@(Expr.proj _ i b _) => do match (← Meta.project? b i) with | some r => reduce structNames r | none => return e.updateProj! (← reduce structNames b) | e@(Expr.app f _ _) => do match (← reduceProjOf? structNames e) with | some r => reduce structNames r | none => let f := f.getAppFn let f' ← reduce structNames f if f'.isLambda then let revArgs := e.getAppRevArgs reduce structNames (f'.betaRev revArgs) else let args ← e.getAppArgs.mapM (reduce structNames) return (mkAppN f' args) | e@(Expr.mdata _ b _) => do let b ← reduce structNames b if (defaultMissing? e).isSome && !b.isMVar then return b else return e.updateMData! b | e@(Expr.mvar mvarId _) => do match (← getExprMVarAssignment? mvarId) with | some val => if val.isMVar then reduce structNames val else pure val | none => return e | e => return e partial def tryToSynthesizeDefault (structs : Array Struct) (allStructNames : Array Name) (maxDistance : Nat) (fieldName : Name) (mvarId : MVarId) : TermElabM Bool := let rec loop (i : Nat) (dist : Nat) := do if dist > maxDistance then pure false else if h : i < structs.size then do let struct := structs.get ⟨i, h⟩ let defaultName := struct.structName ++ fieldName ++ `_default let env ← getEnv match env.find? defaultName with | some cinfo@(ConstantInfo.defnInfo defVal) => do let mctx ← getMCtx let val? ← mkDefaultValue? struct cinfo match val? with | none => do setMCtx mctx; loop (i+1) (dist+1) | some val => do let val ← reduce allStructNames val match val.find? fun e => (defaultMissing? e).isSome with | some _ => setMCtx mctx; loop (i+1) (dist+1) | none => let mvarDecl ← getMVarDecl mvarId let val ← ensureHasType mvarDecl.type val assignExprMVar mvarId val pure true | _ => loop (i+1) dist else pure false loop 0 0 partial def step (struct : Struct) : M Unit := unless (← isRoundDone) do withReader (fun ctx => { ctx with structs := ctx.structs.push struct }) do for field in struct.fields do match field.val with | FieldVal.nested struct => step struct | _ => match field.expr? with | none => unreachable! | some expr => match defaultMissing? expr with | some (Expr.mvar mvarId _) => unless (← isExprMVarAssigned mvarId) do let ctx ← read if (← withRef field.ref <| tryToSynthesizeDefault ctx.structs ctx.allStructNames ctx.maxDistance (getFieldName field) mvarId) then modify fun s => { s with progress := true } | _ => pure () partial def propagateLoop (hierarchyDepth : Nat) (d : Nat) (struct : Struct) : M Unit := do match findDefaultMissing? (← getMCtx) struct with | none => pure () -- Done | some field => if d > hierarchyDepth then throwErrorAt field.ref "field '{getFieldName field}' is missing" else withReader (fun ctx => { ctx with maxDistance := d }) do modify fun s => { s with progress := false } step struct if (← get).progress then do propagateLoop hierarchyDepth 0 struct else propagateLoop hierarchyDepth (d+1) struct def propagate (struct : Struct) : TermElabM Unit := let hierarchyDepth := getHierarchyDepth struct let structNames := collectStructNames struct #[] (propagateLoop hierarchyDepth 0 struct { allStructNames := structNames }).run' {} end DefaultFields private def elabStructInstAux (stx : Syntax) (expectedType? : Option Expr) (source : Source) : TermElabM Expr := do let (structName, structType) ← getStructName stx expectedType? source unless isStructureLike (← getEnv) structName do throwError "invalid \{...} notation, structure type expected{indentExpr structType}" let struct ← liftMacroM <| mkStructView stx structName source let struct ← expandStruct struct trace[Elab.struct] "{struct}" let (r, struct) ← elabStruct struct expectedType? DefaultFields.propagate struct return r @[builtinTermElab structInst] def elabStructInst : TermElab := fun stx expectedType? => do match (← expandNonAtomicExplicitSource stx) with | some stxNew => withMacroExpansion stx stxNew <| elabTerm stxNew expectedType? | none => let sourceView ← getStructSource stx match (← isModifyOp? stx), sourceView with | some modifyOp, Source.explicit source _ => elabModifyOp stx modifyOp source expectedType? | some _, _ => throwError "invalid \{...} notation, explicit source is required when using '[<index>] := <value>'" | _, _ => elabStructInstAux stx expectedType? sourceView builtin_initialize registerTraceClass `Elab.struct end Lean.Elab.Term.StructInst
385321be13c279435aebb5f404d26b98d1a5f194
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/monoid_algebra/to_direct_sum.lean
4f43e85416d37758d71dee7685109c3583d755cb
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
7,819
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import algebra.direct_sum.algebra import algebra.monoid_algebra.basic import data.finsupp.to_dfinsupp /-! # Conversion between `add_monoid_algebra` and homogenous `direct_sum` This module provides conversions between `add_monoid_algebra` and `direct_sum`. The latter is essentially a dependent version of the former. Note that since `direct_sum.has_mul` combines indices additively, there is no equivalent to `monoid_algebra`. ## Main definitions * `add_monoid_algebra.to_direct_sum : add_monoid_algebra M ι → (⨁ i : ι, M)` * `direct_sum.to_add_monoid_algebra : (⨁ i : ι, M) → add_monoid_algebra M ι` * Bundled equiv versions of the above: * `add_monoid_algebra_equiv_direct_sum : add_monoid_algebra M ι ≃ (⨁ i : ι, M)` * `add_monoid_algebra_add_equiv_direct_sum : add_monoid_algebra M ι ≃+ (⨁ i : ι, M)` * `add_monoid_algebra_ring_equiv_direct_sum R : add_monoid_algebra M ι ≃+* (⨁ i : ι, M)` * `add_monoid_algebra_alg_equiv_direct_sum R : add_monoid_algebra A ι ≃ₐ[R] (⨁ i : ι, A)` ## Theorems The defining feature of these operations is that they map `finsupp.single` to `direct_sum.of` and vice versa: * `add_monoid_algebra.to_direct_sum_single` * `direct_sum.to_add_monoid_algebra_of` as well as preserving arithmetic operations. For the bundled equivalences, we provide lemmas that they reduce to `add_monoid_algebra.to_direct_sum`: * `add_monoid_algebra_add_equiv_direct_sum_apply` * `add_monoid_algebra_lequiv_direct_sum_apply` * `add_monoid_algebra_add_equiv_direct_sum_symm_apply` * `add_monoid_algebra_lequiv_direct_sum_symm_apply` ## Implementation notes This file largely just copies the API of `data/finsupp/to_dfinsupp`, and reuses the proofs. Recall that `add_monoid_algebra M ι` is defeq to `ι →₀ M` and `⨁ i : ι, M` is defeq to `Π₀ i : ι, M`. Note that there is no `add_monoid_algebra` equivalent to `finsupp.single`, so many statements still involve this definition. -/ variables {ι : Type*} {R : Type*} {M : Type*} {A : Type*} open_locale direct_sum /-! ### Basic definitions and lemmas -/ section defs /-- Interpret a `add_monoid_algebra` as a homogenous `direct_sum`. -/ def add_monoid_algebra.to_direct_sum [semiring M] (f : add_monoid_algebra M ι) : ⨁ i : ι, M := finsupp.to_dfinsupp f section variables [decidable_eq ι] [semiring M] @[simp] lemma add_monoid_algebra.to_direct_sum_single (i : ι) (m : M) : add_monoid_algebra.to_direct_sum (finsupp.single i m) = direct_sum.of _ i m := finsupp.to_dfinsupp_single i m variables [Π m : M, decidable (m ≠ 0)] /-- Interpret a homogenous `direct_sum` as a `add_monoid_algebra`. -/ def direct_sum.to_add_monoid_algebra (f : ⨁ i : ι, M) : add_monoid_algebra M ι := dfinsupp.to_finsupp f @[simp] lemma direct_sum.to_add_monoid_algebra_of (i : ι) (m : M) : (direct_sum.of _ i m : ⨁ i : ι, M).to_add_monoid_algebra = finsupp.single i m := dfinsupp.to_finsupp_single i m @[simp] lemma add_monoid_algebra.to_direct_sum_to_add_monoid_algebra (f : add_monoid_algebra M ι) : f.to_direct_sum.to_add_monoid_algebra = f := finsupp.to_dfinsupp_to_finsupp f @[simp] lemma direct_sum.to_add_monoid_algebra_to_direct_sum (f : ⨁ i : ι, M) : f.to_add_monoid_algebra.to_direct_sum = f := dfinsupp.to_finsupp_to_dfinsupp f end end defs /-! ### Lemmas about arithmetic operations -/ section lemmas namespace add_monoid_algebra @[simp] lemma to_direct_sum_zero [semiring M] : (0 : add_monoid_algebra M ι).to_direct_sum = 0 := finsupp.to_dfinsupp_zero @[simp] lemma to_direct_sum_add [semiring M] (f g : add_monoid_algebra M ι) : (f + g).to_direct_sum = f.to_direct_sum + g.to_direct_sum := finsupp.to_dfinsupp_add _ _ @[simp] lemma to_direct_sum_mul [decidable_eq ι] [add_monoid ι] [semiring M] (f g : add_monoid_algebra M ι) : (f * g).to_direct_sum = f.to_direct_sum * g.to_direct_sum := begin let to_hom : add_monoid_algebra M ι →+ (⨁ i : ι, M) := ⟨to_direct_sum, to_direct_sum_zero, to_direct_sum_add⟩, show to_hom (f * g) = to_hom f * to_hom g, revert f g, rw add_monoid_hom.map_mul_iff, ext xi xv yi yv : 4, dsimp only [add_monoid_hom.comp_apply, add_monoid_hom.compl₂_apply, add_monoid_hom.compr₂_apply, add_monoid_hom.mul_apply, add_equiv.coe_to_add_monoid_hom, finsupp.single_add_hom_apply], simp only [add_monoid_algebra.single_mul_single, to_hom, add_monoid_hom.coe_mk, add_monoid_algebra.to_direct_sum_single, direct_sum.of_mul_of, has_mul.ghas_mul_mul] end end add_monoid_algebra namespace direct_sum variables [decidable_eq ι] @[simp] lemma to_add_monoid_algebra_zero [semiring M] [Π m : M, decidable (m ≠ 0)] : to_add_monoid_algebra 0 = (0 : add_monoid_algebra M ι) := dfinsupp.to_finsupp_zero @[simp] lemma to_add_monoid_algebra_add [semiring M] [Π m : M, decidable (m ≠ 0)] (f g : ⨁ i : ι, M) : (f + g).to_add_monoid_algebra = to_add_monoid_algebra f + to_add_monoid_algebra g := dfinsupp.to_finsupp_add _ _ @[simp] lemma to_add_monoid_algebra_mul [add_monoid ι] [semiring M] [Π m : M, decidable (m ≠ 0)] (f g : ⨁ i : ι, M) : (f * g).to_add_monoid_algebra = to_add_monoid_algebra f * to_add_monoid_algebra g := begin apply_fun add_monoid_algebra.to_direct_sum, { simp }, { apply function.left_inverse.injective, apply add_monoid_algebra.to_direct_sum_to_add_monoid_algebra } end end direct_sum end lemmas /-! ### Bundled `equiv`s -/ section equivs /-- `add_monoid_algebra.to_direct_sum` and `direct_sum.to_add_monoid_algebra` together form an equiv. -/ @[simps {fully_applied := ff}] def add_monoid_algebra_equiv_direct_sum [decidable_eq ι] [semiring M] [Π m : M, decidable (m ≠ 0)] : add_monoid_algebra M ι ≃ (⨁ i : ι, M) := { to_fun := add_monoid_algebra.to_direct_sum, inv_fun := direct_sum.to_add_monoid_algebra, ..finsupp_equiv_dfinsupp } /-- The additive version of `add_monoid_algebra.to_add_monoid_algebra`. Note that this is `noncomputable` because `add_monoid_algebra.has_add` is noncomputable. -/ @[simps {fully_applied := ff}] def add_monoid_algebra_add_equiv_direct_sum [decidable_eq ι] [semiring M] [Π m : M, decidable (m ≠ 0)] : add_monoid_algebra M ι ≃+ (⨁ i : ι, M) := { to_fun := add_monoid_algebra.to_direct_sum, inv_fun := direct_sum.to_add_monoid_algebra, map_add' := add_monoid_algebra.to_direct_sum_add, .. add_monoid_algebra_equiv_direct_sum} /-- The ring version of `add_monoid_algebra.to_add_monoid_algebra`. Note that this is `noncomputable` because `add_monoid_algebra.has_add` is noncomputable. -/ @[simps {fully_applied := ff}] def add_monoid_algebra_ring_equiv_direct_sum [decidable_eq ι] [add_monoid ι] [semiring M] [Π m : M, decidable (m ≠ 0)] : add_monoid_algebra M ι ≃+* ⨁ i : ι, M := { to_fun := add_monoid_algebra.to_direct_sum, inv_fun := direct_sum.to_add_monoid_algebra, map_mul' := add_monoid_algebra.to_direct_sum_mul, ..(add_monoid_algebra_add_equiv_direct_sum : add_monoid_algebra M ι ≃+ ⨁ i : ι, M) } /-- The algebra version of `add_monoid_algebra.to_add_monoid_algebra`. Note that this is `noncomputable` because `add_monoid_algebra.has_add` is noncomputable. -/ @[simps {fully_applied := ff}] def add_monoid_algebra_alg_equiv_direct_sum [decidable_eq ι] [add_monoid ι] [comm_semiring R] [semiring A] [algebra R A] [Π m : A, decidable (m ≠ 0)] : add_monoid_algebra A ι ≃ₐ[R] ⨁ i : ι, A := { to_fun := add_monoid_algebra.to_direct_sum, inv_fun := direct_sum.to_add_monoid_algebra, commutes' := λ r, add_monoid_algebra.to_direct_sum_single _ _, ..(add_monoid_algebra_ring_equiv_direct_sum : add_monoid_algebra A ι ≃+* ⨁ i : ι, A) } end equivs
3d5c670aa9951028138db8977a932a4dd0deb002
46125763b4dbf50619e8846a1371029346f4c3db
/src/tactic/rename.lean
2da46f18948740be56ed1dd8ca70daaae7a136c3
[ "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
3,511
lean
/- Copyright (c) 2020 Jannis Limperg. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jannis Limperg -/ import tactic.core /-! # Better `rename` tactic This module defines a variant of the standard `rename` tactic, with the following improvements: * You can rename multiple hypotheses at the same time. * Renaming a hypothesis does not change its location in the context. -/ open lean lean.parser interactive native namespace tactic /-- Get the revertible part of the local context. These are the hypotheses that appear after the last frozen local instance in the local context. We call them revertible because `revert` can revert them, unlike those hypotheses which occur before a frozen instance. -/ meta def revertible_local_context : tactic (list expr) := do ctx ← local_context, frozen ← frozen_local_instances, pure $ match frozen with | none := ctx | some [] := ctx | some (h :: _) := ctx.after (eq h) end /-- Rename local hypotheses according to the given `name_map`. The `name_map` contains as keys those hypotheses that should be renamed; the associated values are the new names. This tactic can only rename hypotheses which occur after the last frozen local instance. If you need to rename earlier hypotheses, try `unfreeze_local_instances`. If `strict` is true, we fail if `name_map` refers to hypotheses that do not appear in the local context or that appear before a frozen local instance. Conversely, if `strict` is false, some entries of `name_map` may be silently ignored. Note that we allow shadowing, so renamed hypotheses may have the same name as other hypotheses in the context. -/ meta def rename' (renames : name_map name) (strict := tt) : tactic unit := do ctx ← revertible_local_context, when strict (do let ctx_names := rb_map.set_of_list (ctx.map expr.local_pp_name), let invalid_renames := (renames.to_list.map prod.fst).filter (λ h, ¬ ctx_names.contains h), when ¬ invalid_renames.empty $ fail $ format.join [ "Cannot rename these hypotheses:\n" , format.intercalate ", " (invalid_renames.map to_fmt) , format.line , "This is because these hypotheses either do not occur in the\n" , "context or they occur before a frozen local instance.\n" , "In the latter case, try `tactic.unfreeze_local_instances`." ]), let new_name := λ current_name, (renames.find current_name).get_or_else current_name, let intro_names := list.map (new_name ∘ expr.local_pp_name) ctx, revert_lst ctx, intro_lst intro_names, pure () end tactic namespace tactic.interactive /-- Parse a current name and new name for `rename'`. -/ meta def rename'_arg_parser : parser (name × name) := prod.mk <$> ident <*> (optional (tk "->") *> ident) /-- Parse the arguments of `rename'`. -/ meta def rename'_args_parser : parser (list (name × name)) := (functor.map (λ x, [x]) rename'_arg_parser) <|> (tk "[" *> sep_by (tk ",") rename'_arg_parser <* tk "]") /-- Rename one or more local hypotheses. The renamings are given as follows: ``` rename' x y -- rename x to y rename' x → y -- ditto rename' [x y, a b] -- rename x to y and a to b rename' [x → y, a → b] -- ditto ``` Brackets are necessary if multiple hypotheses should be renamed in parallel. -/ meta def rename' (renames : parse rename'_args_parser) : tactic unit := tactic.rename' (rb_map.of_list renames) end tactic.interactive
49a0d16d8ef1e2cd7a91ffd2e0829e4983ebf483
a9fe717b93ccfa4b2e64faeb24f96dfefb390240
/int/main.lean
a57994b6489dd7ea218e05bd5031cd4aed5ffd91
[]
no_license
skbaek/omega
ab1f4a6daadfc8c855f14c39d9459ab841527141
715e384ed14e8eb177a326700066e7c98269e078
refs/heads/master
1,588,000,876,352
1,552,645,917,000
1,552,645,917,000
174,442,914
1
0
null
null
null
null
UTF-8
Lean
false
false
1,109
lean
import algebra.group order.basic ..logic .rev .form .dnf .reify ..expr_of_unsat namespace int open tactic run_cmd mk_simp_attr `sugar attribute [sugar] not_le not_lt int.lt_iff_add_one_le or_false false_or and_true true_and ge gt mul_add add_mul mul_comm sub_eq_add_neg classical.imp_iff_not_or classical.iff_iff meta def desugar := `[try {simp only with sugar}] lemma uniclo_of_unsat_clausify (m : nat) (p : form) : clauses.unsat (dnf (¬*p)) → uniclo p (λ x, 0) m | h1 := begin apply uniclo_of_valid, apply valid_of_unsat_not, apply unsat_of_clauses_unsat, exact h1 end /- Given a p : form, return the expr of a term t : p.uniclo -/ meta def expr_of_uniclo (m : nat) (p : form) : tactic expr := do x ← expr_of_unsats (dnf (¬*p)), return `(uniclo_of_unsat_clausify %%`(m) %%`(p) %%x) --meta def expr_of_lia : tactic expr := --target >>= to_form >>= expr_of_uniclo meta def expr_of_lia : tactic expr := do (p,m) ← target >>= to_form 0, expr_of_uniclo m p meta def omega : tactic unit := do rev, desugar, expr_of_lia >>= apply, skip end int
f9662f575dc7e6a399d0136aefb78971bf1928ae
94e33a31faa76775069b071adea97e86e218a8ee
/src/category_theory/limits/shapes/comm_sq.lean
30d7bc3df50ec6e85aaf290f15d03484b864920a
[ "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
19,813
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.limits.preserves.shapes.pullbacks import category_theory.limits.shapes.zero_morphisms import category_theory.limits.constructions.binary_products /-! # Pullback and pushout squares We provide another API for pullbacks and pushouts. `is_pullback fst snd f g` is the proposition that ``` P --fst--> X | | snd f | | v v Y ---g---> Z ``` is a pullback square. (And similarly for `is_pushout`.) We provide the glue to go back and forth to the usual `is_limit` API for pullbacks, and prove `is_pullback (pullback.fst : pullback f g ⟶ X) (pullback.snd : pullback f g ⟶ Y) f g` for the usual `pullback f g` provided by the `has_limit` API. We don't attempt to restate everything we know about pullbacks in this language, but do restate the pasting lemmas. ## Future work Bicartesian squares, and show that the pullback and pushout squares for a biproduct are bicartesian. -/ noncomputable theory open category_theory open category_theory.limits universes v₁ v₂ u₁ u₂ namespace category_theory variables {C : Type u₁} [category.{v₁} C] /-- The proposition that a square ``` W ---f---> X | | g h | | v v Y ---i---> Z ``` is a commuting square. -/ structure comm_sq {W X Y Z : C} (f : W ⟶ X) (g : W ⟶ Y) (h : X ⟶ Z) (i : Y ⟶ Z) : Prop := (w : f ≫ h = g ≫ i) attribute [reassoc] comm_sq.w namespace comm_sq variables {W X Y Z : C} {f : W ⟶ X} {g : W ⟶ Y} {h : X ⟶ Z} {i : Y ⟶ Z} lemma flip (p : comm_sq f g h i) : comm_sq g f i h := ⟨p.w.symm⟩ lemma of_arrow {f g : arrow C} (h : f ⟶ g) : comm_sq f.hom h.left h.right g.hom := ⟨h.w.symm⟩ /-- The (not necessarily limiting) `pullback_cone h i` implicit in the statement that we have `comm_sq f g h i`. -/ def cone (s : comm_sq f g h i) : pullback_cone h i := pullback_cone.mk _ _ s.w /-- The (not necessarily limiting) `pushout_cocone f g` implicit in the statement that we have `comm_sq f g h i`. -/ def cocone (s : comm_sq f g h i) : pushout_cocone f g := pushout_cocone.mk _ _ s.w end comm_sq /-- The proposition that a square ``` P --fst--> X | | snd f | | v v Y ---g---> Z ``` is a pullback square. -/ structure is_pullback {P X Y Z : C} (fst : P ⟶ X) (snd : P ⟶ Y) (f : X ⟶ Z) (g : Y ⟶ Z) extends comm_sq fst snd f g : Prop := (is_limit' : nonempty (is_limit (pullback_cone.mk _ _ w))) /-- The proposition that a square ``` Z ---f---> X | | g inl | | v v Y --inr--> P ``` is a pushout square. -/ structure is_pushout {Z X Y P : C} (f : Z ⟶ X) (g : Z ⟶ Y) (inl : X ⟶ P) (inr : Y ⟶ P) extends comm_sq f g inl inr : Prop := (is_colimit' : nonempty (is_colimit (pushout_cocone.mk _ _ w))) /-! We begin by providing some glue between `is_pullback` and the `is_limit` and `has_limit` APIs. (And similarly for `is_pushout`.) -/ namespace is_pullback variables {P X Y Z : C} {fst : P ⟶ X} {snd : P ⟶ Y} {f : X ⟶ Z} {g : Y ⟶ Z} /-- The (limiting) `pullback_cone f g` implicit in the statement that we have a `is_pullback fst snd f g`. -/ def cone (h : is_pullback fst snd f g) : pullback_cone f g := h.to_comm_sq.cone /-- The cone obtained from `is_pullback fst snd f g` is a limit cone. -/ noncomputable def is_limit (h : is_pullback fst snd f g) : is_limit h.cone := h.is_limit'.some /-- If `c` is a limiting pullback cone, then we have a `is_pullback c.fst c.snd f g`. -/ lemma of_is_limit {c : pullback_cone f g} (h : limits.is_limit c) : is_pullback c.fst c.snd f g := { w := c.condition, is_limit' := ⟨is_limit.of_iso_limit h (limits.pullback_cone.ext (iso.refl _) (by tidy) (by tidy))⟩, } /-- A variant of `of_is_limit` that is more useful with `apply`. -/ lemma of_is_limit' (w : comm_sq fst snd f g) (h : limits.is_limit w.cone) : is_pullback fst snd f g := of_is_limit h /-- The pullback provided by `has_pullback f g` fits into a `is_pullback`. -/ lemma of_has_pullback (f : X ⟶ Z) (g : Y ⟶ Z) [has_pullback f g] : is_pullback (pullback.fst : pullback f g ⟶ X) (pullback.snd : pullback f g ⟶ Y) f g := of_is_limit (limit.is_limit (cospan f g)) /-- If `c` is a limiting binary product cone, and we have a terminal object, then we have `is_pullback c.fst c.snd 0 0` (where each `0` is the unique morphism to the terminal object). -/ lemma of_is_product {c : binary_fan X Y} (h : limits.is_limit c) (t : is_terminal Z) : is_pullback c.fst c.snd (t.from _) (t.from _) := of_is_limit (is_pullback_of_is_terminal_is_product _ _ _ _ t (is_limit.of_iso_limit h (limits.cones.ext (iso.refl c.X) (by rintro ⟨⟨⟩⟩; { dsimp, simp, })))) variables (X Y) lemma of_has_binary_product' [has_binary_product X Y] [has_terminal C] : is_pullback limits.prod.fst limits.prod.snd (terminal.from X) (terminal.from Y) := of_is_product (limit.is_limit _) terminal_is_terminal open_locale zero_object lemma of_has_binary_product [has_binary_product X Y] [has_zero_object C] [has_zero_morphisms C] : is_pullback limits.prod.fst limits.prod.snd (0 : X ⟶ 0) (0 : Y ⟶ 0) := by convert of_is_product (limit.is_limit _) has_zero_object.zero_is_terminal variables {X Y} /-- Any object at the top left of a pullback square is isomorphic to the pullback provided by the `has_limit` API. -/ noncomputable def iso_pullback (h : is_pullback fst snd f g) [has_pullback f g] : P ≅ pullback f g := (limit.iso_limit_cone ⟨_, h.is_limit⟩).symm @[simp] lemma iso_pullback_hom_fst (h : is_pullback fst snd f g) [has_pullback f g] : h.iso_pullback.hom ≫ pullback.fst = fst := by { dsimp [iso_pullback, cone, comm_sq.cone], simp, } @[simp] lemma iso_pullback_hom_snd (h : is_pullback fst snd f g) [has_pullback f g] : h.iso_pullback.hom ≫ pullback.snd = snd := by { dsimp [iso_pullback, cone, comm_sq.cone], simp, } @[simp] lemma iso_pullback_inv_fst (h : is_pullback fst snd f g) [has_pullback f g] : h.iso_pullback.inv ≫ fst = pullback.fst := by simp [iso.inv_comp_eq] @[simp] lemma iso_pullback_inv_snd (h : is_pullback fst snd f g) [has_pullback f g] : h.iso_pullback.inv ≫ snd = pullback.snd := by simp [iso.inv_comp_eq] lemma of_iso_pullback (h : comm_sq fst snd f g) [has_pullback f g] (i : P ≅ pullback f g) (w₁ : i.hom ≫ pullback.fst = fst) (w₂ : i.hom ≫ pullback.snd = snd) : is_pullback fst snd f g := of_is_limit' h (limits.is_limit.of_iso_limit (limit.is_limit _) (@pullback_cone.ext _ _ _ _ _ _ _ (pullback_cone.mk _ _ _) _ i w₁.symm w₂.symm).symm) end is_pullback namespace is_pushout variables {Z X Y P : C} {f : Z ⟶ X} {g : Z ⟶ Y} {inl : X ⟶ P} {inr : Y ⟶ P} /-- The (colimiting) `pushout_cocone f g` implicit in the statement that we have a `is_pushout f g inl inr`. -/ def cocone (h : is_pushout f g inl inr) : pushout_cocone f g := h.to_comm_sq.cocone /-- The cocone obtained from `is_pushout f g inl inr` is a colimit cocone. -/ noncomputable def is_colimit (h : is_pushout f g inl inr) : is_colimit h.cocone := h.is_colimit'.some /-- If `c` is a colimiting pushout cocone, then we have a `is_pushout f g c.inl c.inr`. -/ lemma of_is_colimit {c : pushout_cocone f g} (h : limits.is_colimit c) : is_pushout f g c.inl c.inr := { w := c.condition, is_colimit' := ⟨is_colimit.of_iso_colimit h (limits.pushout_cocone.ext (iso.refl _) (by tidy) (by tidy))⟩, } /-- A variant of `of_is_colimit` that is more useful with `apply`. -/ lemma of_is_colimit' (w : comm_sq f g inl inr) (h : limits.is_colimit w.cocone) : is_pushout f g inl inr := of_is_colimit h /-- The pushout provided by `has_pushout f g` fits into a `is_pushout`. -/ lemma of_has_pushout (f : Z ⟶ X) (g : Z ⟶ Y) [has_pushout f g] : is_pushout f g (pushout.inl : X ⟶ pushout f g) (pushout.inr : Y ⟶ pushout f g) := of_is_colimit (colimit.is_colimit (span f g)) /-- If `c` is a colimiting binary coproduct cocone, and we have an initial object, then we have `is_pushout 0 0 c.inl c.inr` (where each `0` is the unique morphism from the initial object). -/ lemma of_is_coproduct {c : binary_cofan X Y} (h : limits.is_colimit c) (t : is_initial Z) : is_pushout (t.to _) (t.to _) c.inl c.inr := of_is_colimit (is_pushout_of_is_initial_is_coproduct _ _ _ _ t (is_colimit.of_iso_colimit h (limits.cocones.ext (iso.refl c.X) (by rintro ⟨⟨⟩⟩; { dsimp, simp, })))) variables (X Y) lemma of_has_binary_coproduct' [has_binary_coproduct X Y] [has_initial C] : is_pushout (initial.to _) (initial.to _) (coprod.inl : X ⟶ _) (coprod.inr : Y ⟶ _) := of_is_coproduct (colimit.is_colimit _) initial_is_initial open_locale zero_object lemma of_has_binary_coproduct [has_binary_coproduct X Y] [has_zero_object C] [has_zero_morphisms C] : is_pushout (0 : 0 ⟶ X) (0 : 0 ⟶ Y) coprod.inl coprod.inr := by convert of_is_coproduct (colimit.is_colimit _) has_zero_object.zero_is_initial variables {X Y} /-- Any object at the top left of a pullback square is isomorphic to the pullback provided by the `has_limit` API. -/ noncomputable def iso_pushout (h : is_pushout f g inl inr) [has_pushout f g] : P ≅ pushout f g := (colimit.iso_colimit_cocone ⟨_, h.is_colimit⟩).symm @[simp] lemma inl_iso_pushout_inv (h : is_pushout f g inl inr) [has_pushout f g] : pushout.inl ≫ h.iso_pushout.inv = inl := by { dsimp [iso_pushout, cocone, comm_sq.cocone], simp, } @[simp] lemma inr_iso_pushout_inv (h : is_pushout f g inl inr) [has_pushout f g] : pushout.inr ≫ h.iso_pushout.inv = inr := by { dsimp [iso_pushout, cocone, comm_sq.cocone], simp, } @[simp] lemma inl_iso_pushout_hom (h : is_pushout f g inl inr) [has_pushout f g] : inl ≫ h.iso_pushout.hom = pushout.inl := by simp [←iso.eq_comp_inv] @[simp] lemma inr_iso_pushout_hom (h : is_pushout f g inl inr) [has_pushout f g] : inr ≫ h.iso_pushout.hom = pushout.inr := by simp [←iso.eq_comp_inv] lemma of_iso_pushout (h : comm_sq f g inl inr) [has_pushout f g] (i : P ≅ pushout f g) (w₁ : inl ≫ i.hom = pushout.inl) (w₂ : inr ≫ i.hom = pushout.inr) : is_pushout f g inl inr := of_is_colimit' h (limits.is_colimit.of_iso_colimit (colimit.is_colimit _) (@pushout_cocone.ext _ _ _ _ _ _ _ (pushout_cocone.mk _ _ _) _ i w₁ w₂).symm) end is_pushout namespace is_pullback variables {P X Y Z : C} {fst : P ⟶ X} {snd : P ⟶ Y} {f : X ⟶ Z} {g : Y ⟶ Z} lemma flip (h : is_pullback fst snd f g) : is_pullback snd fst g f := of_is_limit (@pullback_cone.flip_is_limit _ _ _ _ _ _ _ _ _ _ h.w.symm h.is_limit) section variables [has_zero_object C] [has_zero_morphisms C] open_locale zero_object /-- The square with `0 : 0 ⟶ 0` on the left and `𝟙 X` on the right is a pullback square. -/ lemma zero_left (X : C) : is_pullback (0 : 0 ⟶ X) (0 : 0 ⟶ 0) (𝟙 X) (0 : 0 ⟶ X) := { w := by simp, is_limit' := ⟨{ lift := λ s, 0, fac' := λ s, by simpa using @pullback_cone.equalizer_ext _ _ _ _ _ _ _ s _ 0 (𝟙 _) (by simpa using (pullback_cone.condition s).symm), }⟩ } /-- The square with `0 : 0 ⟶ 0` on the top and `𝟙 X` on the bottom is a pullback square. -/ lemma zero_top (X : C) : is_pullback (0 : 0 ⟶ 0) (0 : 0 ⟶ X) (0 : 0 ⟶ X) (𝟙 X) := (zero_left X).flip end /-- Paste two pullback squares "vertically" to obtain another pullback square. -/ -- Objects here are arranged in a 3x2 grid, and indexed by their xy coordinates. -- Morphisms are named `hᵢⱼ` for a horizontal morphism starting at `(i,j)`, -- and `vᵢⱼ` for a vertical morphism starting at `(i,j)`. lemma paste_vert {X₁₁ X₁₂ X₂₁ X₂₂ X₃₁ X₃₂ : C} {h₁₁ : X₁₁ ⟶ X₁₂} {h₂₁ : X₂₁ ⟶ X₂₂} {h₃₁ : X₃₁ ⟶ X₃₂} {v₁₁ : X₁₁ ⟶ X₂₁} {v₁₂ : X₁₂ ⟶ X₂₂} {v₂₁ : X₂₁ ⟶ X₃₁} {v₂₂ : X₂₂ ⟶ X₃₂} (s : is_pullback h₁₁ v₁₁ v₁₂ h₂₁) (t : is_pullback h₂₁ v₂₁ v₂₂ h₃₁) : is_pullback h₁₁ (v₁₁ ≫ v₂₁) (v₁₂ ≫ v₂₂) h₃₁ := (of_is_limit (big_square_is_pullback _ _ _ _ _ _ _ s.w t.w t.is_limit s.is_limit)) /-- Paste two pullback squares "horizontally" to obtain another pullback square. -/ lemma paste_horiz {X₁₁ X₁₂ X₁₃ X₂₁ X₂₂ X₂₃ : C} {h₁₁ : X₁₁ ⟶ X₁₂} {h₁₂ : X₁₂ ⟶ X₁₃} {h₂₁ : X₂₁ ⟶ X₂₂} {h₂₂ : X₂₂ ⟶ X₂₃} {v₁₁ : X₁₁ ⟶ X₂₁} {v₁₂ : X₁₂ ⟶ X₂₂} {v₁₃ : X₁₃ ⟶ X₂₃} (s : is_pullback h₁₁ v₁₁ v₁₂ h₂₁) (t : is_pullback h₁₂ v₁₂ v₁₃ h₂₂) : is_pullback (h₁₁ ≫ h₁₂) v₁₁ v₁₃ (h₂₁ ≫ h₂₂) := (paste_vert s.flip t.flip).flip /-- Given a pullback square assembled from a commuting square on the top and a pullback square on the bottom, the top square is a pullback square. -/ lemma of_bot {X₁₁ X₁₂ X₂₁ X₂₂ X₃₁ X₃₂ : C} {h₁₁ : X₁₁ ⟶ X₁₂} {h₂₁ : X₂₁ ⟶ X₂₂} {h₃₁ : X₃₁ ⟶ X₃₂} {v₁₁ : X₁₁ ⟶ X₂₁} {v₁₂ : X₁₂ ⟶ X₂₂} {v₂₁ : X₂₁ ⟶ X₃₁} {v₂₂ : X₂₂ ⟶ X₃₂} (s : is_pullback h₁₁ (v₁₁ ≫ v₂₁) (v₁₂ ≫ v₂₂) h₃₁) (p : h₁₁ ≫ v₁₂ = v₁₁ ≫ h₂₁) (t : is_pullback h₂₁ v₂₁ v₂₂ h₃₁) : is_pullback h₁₁ v₁₁ v₁₂ h₂₁ := of_is_limit (left_square_is_pullback _ _ _ _ _ _ _ p _ t.is_limit s.is_limit) /-- Given a pullback square assembled from a commuting square on the left and a pullback square on the right, the left square is a pullback square. -/ lemma of_right {X₁₁ X₁₂ X₁₃ X₂₁ X₂₂ X₂₃ : C} {h₁₁ : X₁₁ ⟶ X₁₂} {h₁₂ : X₁₂ ⟶ X₁₃} {h₂₁ : X₂₁ ⟶ X₂₂} {h₂₂ : X₂₂ ⟶ X₂₃} {v₁₁ : X₁₁ ⟶ X₂₁} {v₁₂ : X₁₂ ⟶ X₂₂} {v₁₃ : X₁₃ ⟶ X₂₃} (s : is_pullback (h₁₁ ≫ h₁₂) v₁₁ v₁₃ (h₂₁ ≫ h₂₂)) (p : h₁₁ ≫ v₁₂ = v₁₁ ≫ h₂₁) (t : is_pullback h₁₂ v₁₂ v₁₃ h₂₂) : is_pullback h₁₁ v₁₁ v₁₂ h₂₁ := (of_bot s.flip p.symm t.flip).flip end is_pullback namespace is_pushout variables {Z X Y P : C} {f : Z ⟶ X} {g : Z ⟶ Y} {inl : X ⟶ P} {inr : Y ⟶ P} lemma flip (h : is_pushout f g inl inr) : is_pushout g f inr inl := of_is_colimit (@pushout_cocone.flip_is_colimit _ _ _ _ _ _ _ _ _ _ h.w.symm h.is_colimit) section variables [has_zero_object C] [has_zero_morphisms C] open_locale zero_object /-- The square with `0 : 0 ⟶ 0` on the right and `𝟙 X` on the left is a pushout square. -/ lemma zero_right (X : C) : is_pushout (0 : X ⟶ 0) (𝟙 X) (0 : 0 ⟶ 0) (0 : X ⟶ 0) := { w := by simp, is_colimit' := ⟨{ desc := λ s, 0, fac' := λ s, begin have c := @pushout_cocone.coequalizer_ext _ _ _ _ _ _ _ s _ 0 (𝟙 _) (by simp) (by simpa using (pushout_cocone.condition s)), dsimp at c, simpa using c, end }⟩ } /-- The square with `0 : 0 ⟶ 0` on the bottom and `𝟙 X` on the top is a pushout square. -/ lemma zero_bot (X : C) : is_pushout (𝟙 X) (0 : X ⟶ 0) (0 : X ⟶ 0) (0 : 0 ⟶ 0) := (zero_right X).flip end /-- Paste two pushout squares "vertically" to obtain another pushout square. -/ -- Objects here are arranged in a 3x2 grid, and indexed by their xy coordinates. -- Morphisms are named `hᵢⱼ` for a horizontal morphism starting at `(i,j)`, -- and `vᵢⱼ` for a vertical morphism starting at `(i,j)`. lemma paste_vert {X₁₁ X₁₂ X₂₁ X₂₂ X₃₁ X₃₂ : C} {h₁₁ : X₁₁ ⟶ X₁₂} {h₂₁ : X₂₁ ⟶ X₂₂} {h₃₁ : X₃₁ ⟶ X₃₂} {v₁₁ : X₁₁ ⟶ X₂₁} {v₁₂ : X₁₂ ⟶ X₂₂} {v₂₁ : X₂₁ ⟶ X₃₁} {v₂₂ : X₂₂ ⟶ X₃₂} (s : is_pushout h₁₁ v₁₁ v₁₂ h₂₁) (t : is_pushout h₂₁ v₂₁ v₂₂ h₃₁) : is_pushout h₁₁ (v₁₁ ≫ v₂₁) (v₁₂ ≫ v₂₂) h₃₁ := (of_is_colimit (big_square_is_pushout _ _ _ _ _ _ _ s.w t.w t.is_colimit s.is_colimit)) /-- Paste two pushout squares "horizontally" to obtain another pushout square. -/ lemma paste_horiz {X₁₁ X₁₂ X₁₃ X₂₁ X₂₂ X₂₃ : C} {h₁₁ : X₁₁ ⟶ X₁₂} {h₁₂ : X₁₂ ⟶ X₁₃} {h₂₁ : X₂₁ ⟶ X₂₂} {h₂₂ : X₂₂ ⟶ X₂₃} {v₁₁ : X₁₁ ⟶ X₂₁} {v₁₂ : X₁₂ ⟶ X₂₂} {v₁₃ : X₁₃ ⟶ X₂₃} (s : is_pushout h₁₁ v₁₁ v₁₂ h₂₁) (t : is_pushout h₁₂ v₁₂ v₁₃ h₂₂) : is_pushout (h₁₁ ≫ h₁₂) v₁₁ v₁₃ (h₂₁ ≫ h₂₂) := (paste_vert s.flip t.flip).flip /-- Given a pushout square assembled from a pushout square on the top and a commuting square on the bottom, the bottom square is a pushout square. -/ lemma of_bot {X₁₁ X₁₂ X₂₁ X₂₂ X₃₁ X₃₂ : C} {h₁₁ : X₁₁ ⟶ X₁₂} {h₂₁ : X₂₁ ⟶ X₂₂} {h₃₁ : X₃₁ ⟶ X₃₂} {v₁₁ : X₁₁ ⟶ X₂₁} {v₁₂ : X₁₂ ⟶ X₂₂} {v₂₁ : X₂₁ ⟶ X₃₁} {v₂₂ : X₂₂ ⟶ X₃₂} (s : is_pushout h₁₁ (v₁₁ ≫ v₂₁) (v₁₂ ≫ v₂₂) h₃₁) (p : h₂₁ ≫ v₂₂ = v₂₁ ≫ h₃₁) (t : is_pushout h₁₁ v₁₁ v₁₂ h₂₁) : is_pushout h₂₁ v₂₁ v₂₂ h₃₁ := of_is_colimit (right_square_is_pushout _ _ _ _ _ _ _ _ p t.is_colimit s.is_colimit) /-- Given a pushout square assembled from a pushout square on the left and a commuting square on the right, the right square is a pushout square. -/ lemma of_right {X₁₁ X₁₂ X₁₃ X₂₁ X₂₂ X₂₃ : C} {h₁₁ : X₁₁ ⟶ X₁₂} {h₁₂ : X₁₂ ⟶ X₁₃} {h₂₁ : X₂₁ ⟶ X₂₂} {h₂₂ : X₂₂ ⟶ X₂₃} {v₁₁ : X₁₁ ⟶ X₂₁} {v₁₂ : X₁₂ ⟶ X₂₂} {v₁₃ : X₁₃ ⟶ X₂₃} (s : is_pushout (h₁₁ ≫ h₁₂) v₁₁ v₁₃ (h₂₁ ≫ h₂₂)) (p : h₁₂ ≫ v₁₃ = v₁₂ ≫ h₂₂) (t : is_pushout h₁₁ v₁₁ v₁₂ h₂₁) : is_pushout h₁₂ v₁₂ v₁₃ h₂₂ := (of_bot s.flip p.symm t.flip).flip end is_pushout namespace functor variables {D : Type u₂} [category.{v₂} D] variables (F : C ⥤ D) {W X Y Z : C} {f : W ⟶ X} {g : W ⟶ Y} {h : X ⟶ Z} {i : Y ⟶ Z} lemma map_comm_sq (s : comm_sq f g h i) : comm_sq (F.map f) (F.map g) (F.map h) (F.map i) := ⟨by simpa using congr_arg (λ k : W ⟶ Z, F.map k) s.w⟩ lemma map_is_pullback [preserves_limit (cospan h i) F] (s : is_pullback f g h i) : is_pullback (F.map f) (F.map g) (F.map h) (F.map i) := -- This is made slightly awkward because `C` and `D` have different universes, -- and so the relevant `walking_cospan` diagrams live in different universes too! begin refine is_pullback.of_is_limit' (F.map_comm_sq s.to_comm_sq) (is_limit.equiv_of_nat_iso_of_iso (cospan_comp_iso F h i) _ _ (walking_cospan.ext _ _ _) (is_limit_of_preserves F s.is_limit)), { refl, }, { dsimp, simp, refl, }, { dsimp, simp, refl, }, end lemma map_is_pushout [preserves_colimit (span f g) F] (s : is_pushout f g h i) : is_pushout (F.map f) (F.map g) (F.map h) (F.map i) := begin refine is_pushout.of_is_colimit' (F.map_comm_sq s.to_comm_sq) (is_colimit.equiv_of_nat_iso_of_iso (span_comp_iso F f g) _ _ (walking_span.ext _ _ _) (is_colimit_of_preserves F s.is_colimit)), { refl, }, { dsimp, simp, refl, }, { dsimp, simp, refl, }, end end functor alias functor.map_comm_sq ← comm_sq.map alias functor.map_is_pullback ← is_pullback.map alias functor.map_is_pushout ← is_pushout.map end category_theory
6960ec8c5805361243252b7b78ba8b9aacfba111
b70447c014d9e71cf619ebc9f539b262c19c2e0b
/hott/types/nat/hott.hlean
f4bcf4460f42fa5e2ef1b165ad212a85828942b0
[ "Apache-2.0" ]
permissive
ia0/lean2
c20d8da69657f94b1d161f9590a4c635f8dc87f3
d86284da630acb78fa5dc3b0b106153c50ffccd0
refs/heads/master
1,611,399,322,751
1,495,751,007,000
1,495,751,007,000
93,104,167
0
0
null
1,496,355,488,000
1,496,355,487,000
null
UTF-8
Lean
false
false
7,936
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Theorems about the natural numbers specific to HoTT -/ import .order types.pointed open is_trunc unit empty eq equiv algebra pointed namespace nat definition is_prop_le [instance] (n m : ℕ) : is_prop (n ≤ m) := begin have lem : Π{n m : ℕ} (p : n ≤ m) (q : n = m), p = q ▸ le.refl n, begin intros, cases p, { have H' : q = idp, by apply is_set.elim, cases H', reflexivity}, { cases q, exfalso, apply not_succ_le_self a} end, apply is_prop.mk, intro H1 H2, induction H2, { apply lem}, { cases H1, { exfalso, apply not_succ_le_self a}, { exact ap le.step !v_0}}, end definition is_prop_lt [instance] (n m : ℕ) : is_prop (n < m) := !is_prop_le definition le_equiv_succ_le_succ (n m : ℕ) : (n ≤ m) ≃ (succ n ≤ succ m) := equiv_of_is_prop succ_le_succ le_of_succ_le_succ definition le_succ_equiv_pred_le (n m : ℕ) : (n ≤ succ m) ≃ (pred n ≤ m) := equiv_of_is_prop pred_le_pred le_succ_of_pred_le theorem lt_by_cases_lt {a b : ℕ} {P : Type} (H1 : a < b → P) (H2 : a = b → P) (H3 : a > b → P) (H : a < b) : lt.by_cases H1 H2 H3 = H1 H := begin unfold lt.by_cases, induction (lt.trichotomy a b) with H' H', { esimp, exact ap H1 !is_prop.elim}, { exfalso, cases H' with H' H', apply lt.irrefl, exact H' ▸ H, exact lt.asymm H H'} end theorem lt_by_cases_eq {a b : ℕ} {P : Type} (H1 : a < b → P) (H2 : a = b → P) (H3 : a > b → P) (H : a = b) : lt.by_cases H1 H2 H3 = H2 H := begin unfold lt.by_cases, induction (lt.trichotomy a b) with H' H', { exfalso, apply lt.irrefl, exact H ▸ H'}, { cases H' with H' H', esimp, exact ap H2 !is_prop.elim, exfalso, apply lt.irrefl, exact H ▸ H'} end theorem lt_by_cases_ge {a b : ℕ} {P : Type} (H1 : a < b → P) (H2 : a = b → P) (H3 : a > b → P) (H : a > b) : lt.by_cases H1 H2 H3 = H3 H := begin unfold lt.by_cases, induction (lt.trichotomy a b) with H' H', { exfalso, exact lt.asymm H H'}, { cases H' with H' H', exfalso, apply lt.irrefl, exact H' ▸ H, esimp, exact ap H3 !is_prop.elim} end theorem lt_ge_by_cases_lt {n m : ℕ} {P : Type} (H1 : n < m → P) (H2 : n ≥ m → P) (H : n < m) : lt_ge_by_cases H1 H2 = H1 H := by apply lt_by_cases_lt theorem lt_ge_by_cases_ge {n m : ℕ} {P : Type} (H1 : n < m → P) (H2 : n ≥ m → P) (H : n ≥ m) : lt_ge_by_cases H1 H2 = H2 H := begin unfold [lt_ge_by_cases,lt.by_cases], induction (lt.trichotomy n m) with H' H', { exfalso, apply lt.irrefl, exact lt_of_le_of_lt H H'}, { cases H' with H' H'; all_goals (esimp; apply ap H2 !is_prop.elim)} end theorem lt_ge_by_cases_le {n m : ℕ} {P : Type} {H1 : n ≤ m → P} {H2 : n ≥ m → P} (H : n ≤ m) (Heq : Π(p : n = m), H1 (le_of_eq p) = H2 (le_of_eq p⁻¹)) : lt_ge_by_cases (λH', H1 (le_of_lt H')) H2 = H1 H := begin unfold [lt_ge_by_cases,lt.by_cases], induction (lt.trichotomy n m) with H' H', { esimp, apply ap H1 !is_prop.elim}, { cases H' with H' H', { esimp, induction H', esimp, symmetry, exact ap H1 !is_prop.elim ⬝ Heq idp ⬝ ap H2 !is_prop.elim}, { exfalso, apply lt.irrefl, apply lt_of_le_of_lt H H'}} end protected definition code [reducible] [unfold 1 2] : ℕ → ℕ → Type₀ | code 0 0 := unit | code 0 (succ m) := empty | code (succ n) 0 := empty | code (succ n) (succ m) := code n m protected definition refl : Πn, nat.code n n | refl 0 := star | refl (succ n) := refl n protected definition encode [unfold 3] {n m : ℕ} (p : n = m) : nat.code n m := p ▸ nat.refl n protected definition decode : Π(n m : ℕ), nat.code n m → n = m | decode 0 0 := λc, idp | decode 0 (succ l) := λc, empty.elim c _ | decode (succ k) 0 := λc, empty.elim c _ | decode (succ k) (succ l) := λc, ap succ (decode k l c) definition nat_eq_equiv (n m : ℕ) : (n = m) ≃ nat.code n m := equiv.MK nat.encode !nat.decode begin revert m, induction n, all_goals (intro m;induction m;all_goals intro c), all_goals try contradiction, induction c, reflexivity, xrewrite [↑nat.decode,-tr_compose,v_0], end begin intro p, induction p, esimp, induction n, reflexivity, rewrite [↑nat.decode,↑nat.refl,v_0] end definition pointed_nat [instance] [constructor] : pointed ℕ := pointed.mk 0 open sigma sum definition eq_even_or_eq_odd (n : ℕ) : (Σk, 2 * k = n) ⊎ (Σk, 2 * k + 1 = n) := begin induction n with n IH, { exact inl ⟨0, idp⟩}, { induction IH with H H: induction H with k p: induction p, { exact inr ⟨k, idp⟩}, { refine inl ⟨k+1, idp⟩}} end definition rec_on_even_odd {P : ℕ → Type} (n : ℕ) (H : Πk, P (2 * k)) (H2 : Πk, P (2 * k + 1)) : P n := begin cases eq_even_or_eq_odd n with v v: induction v with k p: induction p, { exact H k}, { exact H2 k} end /- this inequality comes up a couple of times when using the freudenthal suspension theorem -/ definition add_mul_le_mul_add (n m k : ℕ) : n + (succ m) * k ≤ (succ m) * (n + k) := calc n + (succ m) * k ≤ (m * n + n) + (succ m) * k : add_le_add_right !le_add_left _ ... = (succ m) * n + (succ m) * k : by rewrite -succ_mul ... = (succ m) * (n + k) : !left_distrib⁻¹ /- Some operations work only for successors. For example fin (succ n) has a 0 and a 1, but fin 0 doesn't. However, we want a bit more, because sometimes we want a zero of (fin a) where a is either - equal to a successor, but not definitionally a successor (e.g. (0 : fin (3 + n))) - definitionally equal to a successor, but not in a way that type class inference can infer. (e.g. (0 : fin 4). Note that 4 is bit0 (bit0 one), but (bit0 x) (defined as x + x), is not always a successor) To solve this we use an auxillary class `is_succ` which can solve whether a number is a successor. -/ inductive is_succ [class] : ℕ → Type := | mk : Π(n : ℕ), is_succ (succ n) attribute is_succ.mk [instance] definition is_succ_add_right [instance] [constructor] (n m : ℕ) [H : is_succ m] : is_succ (n+m) := by induction H with m; constructor definition is_succ_add_left [instance] [constructor] (n m : ℕ) [H : is_succ n] : is_succ (n+m) := by induction H with n; cases m with m: constructor definition is_succ_bit0 [constructor] (n : ℕ) [H : is_succ n] : is_succ (bit0 n) := by exact _ -- level 2 is useful for abelian homotopy groups, which only exist at level 2 and higher inductive is_at_least_two [class] : ℕ → Type := | mk : Π(n : ℕ), is_at_least_two (succ (succ n)) attribute is_at_least_two.mk [instance] definition is_at_least_two_add_right [instance] [constructor] (n m : ℕ) [H : is_at_least_two m] : is_at_least_two (n+m) := by induction H with m; constructor definition is_at_least_two_add_left [instance] [constructor] (n m : ℕ) [H : is_at_least_two n] : is_at_least_two (n+m) := by induction H with n; cases m with m: try cases m with m: constructor definition is_at_least_two_add_both [instance] [priority 900] [constructor] (n m : ℕ) [H : is_succ n] [K : is_succ m] : is_at_least_two (n+m) := by induction H with n; induction K with m; cases m with m: constructor definition is_at_least_two_bit0 [constructor] (n : ℕ) [H : is_succ n] : is_at_least_two (bit0 n) := by exact _ definition is_at_least_two_bit1 [constructor] (n : ℕ) [H : is_succ n] : is_at_least_two (bit1 n) := by exact _ end nat
bdcf67c95e2230d06d02cca079655db3ab14403a
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/lua1.lean
b72bb68e3af2f214c555a04aff5863dc0be134dc
[ "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
84
lean
import Int. variable x : Int (* print("hello world from Lua") *) variable y : Int
940811146312045f18d91eafbef1eea4101bac3b
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/eq_mpr_def_issue.lean
c9383d33d6ef2489f45770b609bbbabe811da316
[ "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
179
lean
open function instance decidable_uncurry_pred{α} (p : α → α → Prop) [decidable_rel p] : decidable_pred (uncurry p) := λ a, by { cases a; simp [uncurry]; apply_instance }
309c23185924215346742ab968645806e09bf7b7
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/number_theory/primorial.lean
e78be6ffa179d92e78d73ff5c0a7819d3fd2cabc
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
7,341
lean
/- Copyright (c) 2020 Patrick Stevens. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Stevens -/ import tactic.ring_exp import data.nat.parity import data.nat.choose.sum /-! # Primorial This file defines the primorial function (the product of primes less than or equal to some bound), and proves that `primorial n ≤ 4 ^ n`. ## Notations We use the local notation `n#` for the primorial of `n`: that is, the product of the primes less than or equal to `n`. -/ open finset open nat open_locale big_operators /-- The primorial `n#` of `n` is the product of the primes less than or equal to `n`. -/ def primorial (n : ℕ) : ℕ := ∏ p in (filter prime (range (n + 1))), p local notation x`#` := primorial x lemma primorial_succ {n : ℕ} (n_big : 1 < n) (r : n % 2 = 1) : (n + 1)# = n# := begin have not_prime : ¬prime (n + 1), { intros is_prime, cases (prime.eq_two_or_odd is_prime) with _ n_even, { linarith, }, { exfalso, rw ←not_even_iff at n_even r, have e : even (n + 1 - n), exact (even_sub (le_of_lt (lt_add_one n))).2 (iff_of_false n_even r), simp only [nat.add_sub_cancel_left, not_even_one] at e, exact e, }, }, apply finset.prod_congr, { rw [@range_succ (n + 1), filter_insert, if_neg not_prime], }, { exact λ _ _, rfl, }, end lemma dvd_choose_of_middling_prime (p : ℕ) (is_prime : prime p) (m : ℕ) (p_big : m + 1 < p) (p_small : p ≤ 2 * m + 1) : p ∣ choose (2 * m + 1) (m + 1) := begin have m_size : m + 1 ≤ 2 * m + 1 := le_of_lt (lt_of_lt_of_le p_big p_small), have expanded : choose (2 * m + 1) (m + 1) * fact (m + 1) * fact (2 * m + 1 - (m + 1)) = fact (2 * m + 1) := @choose_mul_fact_mul_fact (2 * m + 1) (m + 1) m_size, have p_div_big_fact : p ∣ fact (2 * m + 1) := (prime.dvd_fact is_prime).mpr p_small, rw [←expanded, mul_assoc] at p_div_big_fact, have s : ¬(p ∣ fact (m + 1)), { intros p_div_fact, have p_le_succ_m : p ≤ m + 1 := (prime.dvd_fact is_prime).mp p_div_fact, linarith, }, have t : ¬(p ∣ fact (2 * m + 1 - (m + 1))), { intros p_div_fact, have p_small : p ≤ 2 * m + 1 - (m + 1) := (prime.dvd_fact is_prime).mp p_div_fact, have t : 2 * m + 1 - (m + 1) = m, by { norm_num, rw two_mul m, exact nat.add_sub_cancel m m, }, rw t at p_small, obtain p_lt_m | rfl | m_lt_p : _ := lt_trichotomy p m, { have r : m < m + 1 := lt_add_one m, linarith, }, { linarith, }, { linarith, }, }, obtain p_div_choose | p_div_facts : p ∣ choose (2 * m + 1) (m + 1) ∨ p ∣ fact _ * fact _ := (prime.dvd_mul is_prime).1 p_div_big_fact, { exact p_div_choose, }, cases (prime.dvd_mul is_prime).1 p_div_facts, cc, cc, end lemma prod_primes_dvd {s : finset ℕ} : ∀ (n : ℕ) (h : ∀ a ∈ s, prime a) (div : ∀ a ∈ s, a ∣ n), (∏ p in s, p) ∣ n := begin apply finset.induction_on s, { simp, }, { intros a s a_not_in_s induct n primes divs, rw finset.prod_insert a_not_in_s, obtain ⟨k, rfl⟩ : a ∣ n, by exact divs a (finset.mem_insert_self a s), have step : ∏ p in s, p ∣ k, { apply induct k, { intros b b_in_s, exact primes b (finset.mem_insert_of_mem b_in_s), }, { intros b b_in_s, have b_div_n, by exact divs b (finset.mem_insert_of_mem b_in_s), have a_prime : prime a, { exact primes a (finset.mem_insert_self a s), }, have b_prime : prime b, { exact primes b (finset.mem_insert_of_mem b_in_s), }, obtain b_div_a | b_div_k : b ∣ a ∨ b ∣ k, exact (prime.dvd_mul b_prime).mp b_div_n, { exfalso, have b_eq_a : b = a, { cases (nat.dvd_prime a_prime).1 b_div_a with b_eq_1 b_eq_a, { subst b_eq_1, exfalso, exact prime.ne_one b_prime rfl, }, { exact b_eq_a } }, subst b_eq_a, exact a_not_in_s b_in_s, }, { exact b_div_k } } }, exact mul_dvd_mul_left a step, } end lemma primorial_le_4_pow : ∀ (n : ℕ), n# ≤ 4 ^ n | 0 := le_refl _ | 1 := le_of_inf_eq rfl | (n + 2) := match nat.mod_two_eq_zero_or_one (n + 1) with | or.inl n_odd := match nat.even_iff.2 n_odd with | ⟨m, twice_m⟩ := let recurse : m + 1 < n + 2 := by linarith in begin calc (n + 2)# = ∏ i in filter prime (range (2 * m + 2)), i : by simpa [←twice_m] ... = ∏ i in filter prime (finset.Ico (m + 2) (2 * m + 2) ∪ range (m + 2)), i : begin rw [range_eq_Ico, range_eq_Ico, finset.union_comm, finset.Ico.union_consecutive], exact bot_le, simp only [add_le_add_iff_right], linarith, end ... = ∏ i in (filter prime (finset.Ico (m + 2) (2 * m + 2)) ∪ (filter prime (range (m + 2)))), i : by rw filter_union ... = (∏ i in filter prime (finset.Ico (m + 2) (2 * m + 2)), i) * (∏ i in filter prime (range (m + 2)), i) : begin apply finset.prod_union, have disj : disjoint (finset.Ico (m + 2) (2 * m + 2)) (range (m + 2)), { simp only [finset.disjoint_left, and_imp, finset.Ico.mem, not_lt, finset.mem_range], intros _ pr _, exact pr, }, exact finset.disjoint_filter_filter disj, end ... ≤ (∏ i in filter prime (finset.Ico (m + 2) (2 * m + 2)), i) * 4 ^ (m + 1) : by exact nat.mul_le_mul_left _ (primorial_le_4_pow (m + 1)) ... ≤ (choose (2 * m + 1) (m + 1)) * 4 ^ (m + 1) : begin have s : ∏ i in filter prime (finset.Ico (m + 2) (2 * m + 2)), i ∣ choose (2 * m + 1) (m + 1), { refine prod_primes_dvd (choose (2 * m + 1) (m + 1)) _ _, { intros a, rw finset.mem_filter, cc, }, { intros a, rw finset.mem_filter, intros pr, rcases pr with ⟨ size, is_prime ⟩, simp only [finset.Ico.mem] at size, rcases size with ⟨ a_big , a_small ⟩, exact dvd_choose_of_middling_prime a is_prime m a_big (nat.lt_succ_iff.mp a_small), }, }, have r : ∏ i in filter prime (finset.Ico (m + 2) (2 * m + 2)), i ≤ choose (2 * m + 1) (m + 1), { refine @nat.le_of_dvd _ _ _ s, exact @choose_pos (2 * m + 1) (m + 1) (by linarith), }, exact nat.mul_le_mul_right _ r, end ... = (choose (2 * m + 1) m) * 4 ^ (m + 1) : by rw choose_symm_half m ... ≤ 4 ^ m * 4 ^ (m + 1) : nat.mul_le_mul_right _ (choose_middle_le_pow m) ... = 4 ^ (2 * m + 1) : by ring_exp ... = 4 ^ (n + 2) : by rw ←twice_m, end end | or.inr n_even := begin obtain one_lt_n | n_le_one : 1 < n + 1 ∨ n + 1 ≤ 1 := lt_or_le 1 (n + 1), { rw primorial_succ (by linarith) n_even, calc (n + 1)# ≤ 4 ^ n.succ : primorial_le_4_pow (n + 1) ... ≤ 4 ^ (n + 2) : pow_le_pow (by norm_num) (nat.le_succ _), }, { cases lt_or_le 0 n with _ n_le_zero, { linarith, }, { have n_zero : n = 0 := eq_bot_iff.mpr n_le_zero, norm_num [n_zero], exact sup_eq_left.mp rfl, }, }, end end
abe61070cba62103da23c723af96892284d50bb1
5bf112cf7101c6c6303dc3fd0b3179c860e61e56
/lean/background/number.lean
15c930d93f5c98feeba59a8d20e74f4dd8c79e80
[ "Apache-2.0" ]
permissive
fredfeng/formal-encoding
7ab645f49a553dfad2af03fcb4289e40fc679759
024efcf58672ac6b817caa10dfe8cd9708b07f1b
refs/heads/master
1,597,236,551,123
1,568,832,149,000
1,568,832,149,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,687
lean
import .util namespace IMOGrandChallenge notation `ℕ` := Nat notation `ℕgt0` := { n : ℕ // n > 0 } notation `ℤ` := Int notation `ℤgt0` := { z : ℤ // z > 0 } notation `ℤge0` := { z : ℤ // z ≥ 0 } axiom Rat : Type notation `ℚ` := Rat namespace Rat noncomputable instance : HasZero ℚ := ⟨SKIP⟩ noncomputable instance : HasOne ℚ := ⟨SKIP⟩ noncomputable instance : HasAdd ℚ := ⟨SKIP⟩ noncomputable instance : HasMul ℚ := ⟨SKIP⟩ noncomputable instance : HasNeg ℚ := ⟨SKIP⟩ noncomputable instance : HasSub ℚ := ⟨SKIP⟩ noncomputable instance : HasDiv ℚ := ⟨SKIP⟩ noncomputable instance : HasPow ℚ ℚ := ⟨SKIP⟩ noncomputable instance : HasLess ℚ := ⟨SKIP⟩ notation `ℚgt0` := { r : ℚ // r > 0 } notation `ℚge0` := { r : ℚ // r ≥ 0 } axiom isInt : ℚ → Prop end Rat axiom Nat.toRat : ℕ → ℚ axiom Real : Type notation `ℝ` := Real namespace Real noncomputable instance : HasZero ℝ := ⟨SKIP⟩ noncomputable instance : HasOne ℝ := ⟨SKIP⟩ noncomputable instance : HasAdd ℝ := ⟨SKIP⟩ noncomputable instance : HasMul ℝ := ⟨SKIP⟩ noncomputable instance : HasNeg ℝ := ⟨SKIP⟩ noncomputable instance : HasSub ℝ := ⟨SKIP⟩ noncomputable instance : HasDiv ℝ := ⟨SKIP⟩ noncomputable instance HasPowℝℕ : HasPow ℝ ℕ := ⟨SKIP⟩ noncomputable instance HasPowℝℝ : HasPow ℝ ℝ := ⟨SKIP⟩ noncomputable instance : HasLess ℝ := ⟨SKIP⟩ notation `ℝgt0` := { x : ℝ // x > 0 } notation `ℝge0` := { x : ℝ // x ≥ 0 } axiom e : ℝ axiom pi : ℝ noncomputable def sqrt (x : Real) : Real := pow x (1/2) end Real end IMOGrandChallenge
f936d10af3b015aaa79ba4608bef4c51f1ec400e
367134ba5a65885e863bdc4507601606690974c1
/src/data/vector2.lean
06a048fe9ca0703b72ffe1e32d1447b2d7dedf57
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
16,312
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.vector import data.list.nodup import data.list.of_fn import control.applicative /-! # Additional theorems about the `vector` type This file introduces the infix notation `::ᵥ` for `vector.cons`. -/ universes u variables {n : ℕ} namespace vector variables {α : Type*} infixr `::ᵥ`:67 := vector.cons attribute [simp] head_cons tail_cons instance [inhabited α] : inhabited (vector α n) := ⟨of_fn (λ _, default α)⟩ theorem to_list_injective : function.injective (@to_list α n) := subtype.val_injective /-- Two `v w : vector α n` are equal iff they are equal at every single index. -/ @[ext] theorem ext : ∀ {v w : vector α n} (h : ∀ m : fin n, vector.nth v m = vector.nth w m), v = w | ⟨v, hv⟩ ⟨w, hw⟩ h := subtype.eq (list.ext_le (by rw [hv, hw]) (λ m hm hn, h ⟨m, hv ▸ hm⟩)) /-- The empty `vector` is a `subsingleton`. -/ instance zero_subsingleton : subsingleton (vector α 0) := ⟨λ _ _, vector.ext (λ m, fin.elim0 m)⟩ @[simp] theorem cons_val (a : α) : ∀ (v : vector α n), (a ::ᵥ v).val = a :: v.val | ⟨_, _⟩ := rfl @[simp] theorem cons_head (a : α) : ∀ (v : vector α n), (a ::ᵥ v).head = a | ⟨_, _⟩ := rfl @[simp] theorem cons_tail (a : α) : ∀ (v : vector α n), (a ::ᵥ v).tail = v | ⟨_, _⟩ := rfl @[simp] theorem to_list_of_fn : ∀ {n} (f : fin n → α), to_list (of_fn f) = list.of_fn f | 0 f := rfl | (n+1) f := by rw [of_fn, list.of_fn_succ, to_list_cons, to_list_of_fn] @[simp] theorem mk_to_list : ∀ (v : vector α n) h, (⟨to_list v, h⟩ : vector α n) = v | ⟨l, h₁⟩ h₂ := rfl @[simp] lemma to_list_map {β : Type*} (v : vector α n) (f : α → β) : (v.map f).to_list = v.to_list.map f := by cases v; refl theorem nth_eq_nth_le : ∀ (v : vector α n) (i), nth v i = v.to_list.nth_le i.1 (by rw to_list_length; exact i.2) | ⟨l, h⟩ i := rfl @[simp] lemma nth_map {β : Type*} (v : vector α n) (f : α → β) (i : fin n) : (v.map f).nth i = f (v.nth i) := by simp [nth_eq_nth_le] @[simp] theorem nth_of_fn {n} (f : fin n → α) (i) : nth (of_fn f) i = f i := by rw [nth_eq_nth_le, ← list.nth_le_of_fn f]; congr; apply to_list_of_fn @[simp] theorem of_fn_nth (v : vector α n) : of_fn (nth v) = v := begin rcases v with ⟨l, rfl⟩, apply to_list_injective, change nth ⟨l, eq.refl _⟩ with λ i, nth ⟨l, rfl⟩ i, simpa only [to_list_of_fn] using list.of_fn_nth_le _ end @[simp] theorem nth_tail : ∀ (v : vector α n.succ) (i : fin n), nth (tail v) i = nth v i.succ | ⟨a::l, e⟩ ⟨i, h⟩ := by simp [nth_eq_nth_le]; refl @[simp] theorem tail_val : ∀ (v : vector α n.succ), v.tail.val = v.val.tail | ⟨a::l, e⟩ := rfl /-- The `tail` of a `nil` vector is `nil`. -/ @[simp] lemma tail_nil : (@nil α).tail = nil := rfl /-- The `tail` of a vector made up of one element is `nil`. -/ @[simp] lemma singleton_tail (v : vector α 1) : v.tail = vector.nil := by simp only [←cons_head_tail, eq_iff_true_of_subsingleton] @[simp] theorem tail_of_fn {n : ℕ} (f : fin n.succ → α) : tail (of_fn f) = of_fn (λ i, f i.succ) := (of_fn_nth _).symm.trans $ by congr; funext i; simp /-- The list that makes up a `vector` made up of a single element, retrieved via `to_list`, is equal to the list of that single element. -/ @[simp] lemma to_list_singleton (v : vector α 1) : v.to_list = [v.head] := begin rw ←v.cons_head_tail, simp only [to_list_cons, to_list_nil, cons_head, eq_self_iff_true, and_self, singleton_tail] end /-- Mapping under `id` does not change a vector. -/ @[simp] lemma map_id {n : ℕ} (v : vector α n) : vector.map id v = v := vector.eq _ _ (by simp only [list.map_id, vector.to_list_map]) lemma mem_iff_nth {a : α} {v : vector α n} : a ∈ v.to_list ↔ ∃ i, v.nth i = a := by simp only [list.mem_iff_nth_le, fin.exists_iff, vector.nth_eq_nth_le]; exact ⟨λ ⟨i, hi, h⟩, ⟨i, by rwa to_list_length at hi, h⟩, λ ⟨i, hi, h⟩, ⟨i, by rwa to_list_length, h⟩⟩ lemma nodup_iff_nth_inj {v : vector α n} : v.to_list.nodup ↔ function.injective v.nth := begin cases v with l hl, subst hl, simp only [list.nodup_iff_nth_le_inj], split, { intros h i j hij, cases i, cases j, ext, apply h, simpa }, { intros h i j hi hj hij, have := @h ⟨i, hi⟩ ⟨j, hj⟩, simp [nth_eq_nth_le] at *, tauto } end @[simp] lemma nth_mem (i : fin n) (v : vector α n) : v.nth i ∈ v.to_list := by rw [nth_eq_nth_le]; exact list.nth_le_mem _ _ _ theorem head'_to_list : ∀ (v : vector α n.succ), (to_list v).head' = some (head v) | ⟨a::l, e⟩ := rfl def reverse (v : vector α n) : vector α n := ⟨v.to_list.reverse, by simp⟩ /-- The `list` of a vector after a `reverse`, retrieved by `to_list` is equal to the `list.reverse` after retrieving a vector's `to_list`. -/ lemma to_list_reverse {v : vector α n} : v.reverse.to_list = v.to_list.reverse := rfl @[simp] theorem nth_zero : ∀ (v : vector α n.succ), nth v 0 = head v | ⟨a::l, e⟩ := rfl @[simp] theorem head_of_fn {n : ℕ} (f : fin n.succ → α) : head (of_fn f) = f 0 := by rw [← nth_zero, nth_of_fn] @[simp] theorem nth_cons_zero (a : α) (v : vector α n) : nth (a ::ᵥ v) 0 = a := by simp [nth_zero] /-- Accessing the `nth` element of a vector made up of one element `x : α` is `x` itself. -/ @[simp] lemma nth_cons_nil {ix : fin 1} (x : α) : nth (x ::ᵥ nil) ix = x := by convert nth_cons_zero x nil @[simp] theorem nth_cons_succ (a : α) (v : vector α n) (i : fin n) : nth (a ::ᵥ v) i.succ = nth v i := by rw [← nth_tail, tail_cons] /-- The last element of a `vector`, given that the vector is at least one element. -/ def last (v : vector α (n + 1)) : α := v.nth (fin.last n) /-- The last element of a `vector`, given that the vector is at least one element. -/ lemma last_def {v : vector α (n + 1)} : v.last = v.nth (fin.last n) := rfl /-- The `last` element of a vector is the `head` of the `reverse` vector. -/ lemma reverse_nth_zero {v : vector α (n + 1)} : v.reverse.head = v.last := begin have : 0 = v.to_list.length - 1 - n, { simp only [nat.add_succ_sub_one, add_zero, to_list_length, nat.sub_self, list.length_reverse] }, rw [←nth_zero, last_def, nth_eq_nth_le, nth_eq_nth_le], simp_rw [to_list_reverse, fin.val_eq_coe, fin.coe_last, fin.coe_zero, this], rw list.nth_le_reverse, end section scan variables {β : Type*} variables (f : β → α → β) (b : β) variables (v : vector α n) /-- Construct a `vector β (n + 1)` from a `vector α n` by scanning `f : β → α → β` from the "left", that is, from 0 to `fin.last n`, using `b : β` as the starting value. -/ def scanl : vector β (n + 1) := ⟨list.scanl f b v.to_list, by rw [list.length_scanl, to_list_length]⟩ /-- Providing an empty vector to `scanl` gives the starting value `b : β`. -/ @[simp] lemma scanl_nil : scanl f b nil = b ::ᵥ nil := rfl /-- The recursive step of `scanl` splits a vector `x ::ᵥ v : vector α (n + 1)` into the provided starting value `b : β` and the recursed `scanl` `f b x : β` as the starting value. This lemma is the `cons` version of `scanl_nth`. -/ @[simp] lemma scanl_cons (x : α) : scanl f b (x ::ᵥ v) = b ::ᵥ scanl f (f b x) v := by simpa only [scanl, to_list_cons] /-- The underlying `list` of a `vector` after a `scanl` is the `list.scanl` of the underlying `list` of the original `vector`. -/ @[simp] lemma scanl_val : ∀ {v : vector α n}, (scanl f b v).val = list.scanl f b v.val | ⟨l, hl⟩ := rfl /-- The `to_list` of a `vector` after a `scanl` is the `list.scanl` of the `to_list` of the original `vector`. -/ @[simp] lemma to_list_scanl : (scanl f b v).to_list = list.scanl f b v.to_list := rfl /-- The recursive step of `scanl` splits a vector made up of a single element `x ::ᵥ nil : vector α 1` into a `vector` of the provided starting value `b : β` and the mapped `f b x : β` as the last value. -/ @[simp] lemma scanl_singleton (v : vector α 1) : scanl f b v = b ::ᵥ f b v.head ::ᵥ nil := begin rw [←cons_head_tail v], simp only [scanl_cons, scanl_nil, cons_head, singleton_tail] end /-- The first element of `scanl` of a vector `v : vector α n`, retrieved via `head`, is the starting value `b : β`. -/ @[simp] lemma scanl_head : (scanl f b v).head = b := begin cases n, { have : v = nil := by simp only [eq_iff_true_of_subsingleton], simp only [this, scanl_nil, cons_head] }, { rw ←cons_head_tail v, simp only [←nth_zero, nth_eq_nth_le, to_list_scanl, to_list_cons, list.scanl, fin.val_zero', list.nth_le] } end /-- For an index `i : fin n`, the `nth` element of `scanl` of a vector `v : vector α n` at `i.succ`, is equal to the application function `f : β → α → β` of the `i.cast_succ` element of `scanl f b v` and `nth v i`. This lemma is the `nth` version of `scanl_cons`. -/ @[simp] lemma scanl_nth (i : fin n) : (scanl f b v).nth i.succ = f ((scanl f b v).nth i.cast_succ) (v.nth i) := begin cases n, { exact fin_zero_elim i }, induction n with n hn generalizing b, { have i0 : i = 0 := by simp only [eq_iff_true_of_subsingleton], simpa only [scanl_singleton, i0, nth_zero] }, { rw [←cons_head_tail v, scanl_cons, nth_cons_succ], refine fin.cases _ _ i, { simp only [nth_zero, scanl_head, fin.cast_succ_zero, cons_head] }, { intro i', simp only [hn, fin.cast_succ_fin_succ, nth_cons_succ] } } end end scan def m_of_fn {m} [monad m] {α : Type u} : ∀ {n}, (fin n → m α) → m (vector α n) | 0 f := pure nil | (n+1) f := do a ← f 0, v ← m_of_fn (λi, f i.succ), pure (a ::ᵥ v) theorem m_of_fn_pure {m} [monad m] [is_lawful_monad m] {α} : ∀ {n} (f : fin n → α), @m_of_fn m _ _ _ (λ i, pure (f i)) = pure (of_fn f) | 0 f := rfl | (n+1) f := by simp [m_of_fn, @m_of_fn_pure n, of_fn] def mmap {m} [monad m] {α} {β : Type u} (f : α → m β) : ∀ {n}, vector α n → m (vector β n) | _ ⟨[], rfl⟩ := pure nil | _ ⟨a::l, rfl⟩ := do h' ← f a, t' ← mmap ⟨l, rfl⟩, pure (h' ::ᵥ t') @[simp] theorem mmap_nil {m} [monad m] {α β} (f : α → m β) : mmap f nil = pure nil := rfl @[simp] theorem mmap_cons {m} [monad m] {α β} (f : α → m β) (a) : ∀ {n} (v : vector α n), mmap f (a ::ᵥ v) = do h' ← f a, t' ← mmap f v, pure (h' ::ᵥ t') | _ ⟨l, rfl⟩ := rfl /-- Define `C v` by induction on `v : vector α (n + 1)`, a vector of at least one element. This function has two arguments: `h0` handles the base case on `C nil`, and `hs` defines the inductive step using `∀ x : α, C v → C (x ::ᵥ v)`. -/ @[elab_as_eliminator] def induction_on {α : Type*} {n : ℕ} {C : Π {n : ℕ}, vector α n → Sort*} (v : vector α (n + 1)) (h0 : C nil) (hs : ∀ {n : ℕ} {x : α} {w : vector α n}, C w → C (x ::ᵥ w)) : C v := begin induction n with n hn, { rw ←v.cons_head_tail, convert hs h0 }, { rw ←v.cons_head_tail, apply hs, apply hn } end def to_array : vector α n → array n α | ⟨xs, h⟩ := cast (by rw h) xs.to_array section insert_nth variable {a : α} def insert_nth (a : α) (i : fin (n+1)) (v : vector α n) : vector α (n+1) := ⟨v.1.insert_nth i a, begin rw [list.length_insert_nth, v.2], rw [v.2, ← nat.succ_le_succ_iff], exact i.2 end⟩ lemma insert_nth_val {i : fin (n+1)} {v : vector α n} : (v.insert_nth a i).val = v.val.insert_nth i.1 a := rfl @[simp] lemma remove_nth_val {i : fin n} : ∀{v : vector α n}, (remove_nth i v).val = v.val.remove_nth i | ⟨l, hl⟩ := rfl lemma remove_nth_insert_nth {v : vector α n} {i : fin (n+1)} : remove_nth i (insert_nth a i v) = v := subtype.eq $ list.remove_nth_insert_nth i.1 v.1 lemma remove_nth_insert_nth' {v : vector α (n+1)} : ∀{i : fin (n+1)} {j : fin (n+2)}, remove_nth (j.succ_above i) (insert_nth a j v) = insert_nth a (i.pred_above j) (remove_nth i v) | ⟨i, hi⟩ ⟨j, hj⟩ := begin dsimp [insert_nth, remove_nth, fin.succ_above, fin.pred_above], simp only [subtype.mk_eq_mk], split_ifs, { convert (list.insert_nth_remove_nth_of_ge i (j-1) _ _ _).symm, { convert (nat.succ_pred_eq_of_pos _).symm, exact lt_of_le_of_lt (zero_le _) h, }, { apply remove_nth_val, }, { convert hi, exact v.2, }, { exact nat.le_pred_of_lt h, }, }, { convert (list.insert_nth_remove_nth_of_le i j _ _ _).symm, { apply remove_nth_val, }, { convert hi, exact v.2, }, { simpa using h, }, } end lemma insert_nth_comm (a b : α) (i j : fin (n+1)) (h : i ≤ j) : ∀(v : vector α n), (v.insert_nth a i).insert_nth b j.succ = (v.insert_nth b j).insert_nth a i.cast_succ | ⟨l, hl⟩ := begin refine subtype.eq _, simp only [insert_nth_val, fin.coe_succ, fin.cast_succ, fin.val_eq_coe, fin.coe_cast_add], apply list.insert_nth_comm, { assumption }, { rw hl, exact nat.le_of_succ_le_succ j.2 } end end insert_nth section update_nth /-- `update_nth v n a` replaces the `n`th element of `v` with `a` -/ def update_nth (v : vector α n) (i : fin n) (a : α) : vector α n := ⟨v.1.update_nth i.1 a, by rw [list.update_nth_length, v.2]⟩ @[simp] lemma nth_update_nth_same (v : vector α n) (i : fin n) (a : α) : (v.update_nth i a).nth i = a := by cases v; cases i; simp [vector.update_nth, vector.nth_eq_nth_le] lemma nth_update_nth_of_ne {v : vector α n} {i j : fin n} (h : i ≠ j) (a : α) : (v.update_nth i a).nth j = v.nth j := by cases v; cases i; cases j; simp [vector.update_nth, vector.nth_eq_nth_le, list.nth_le_update_nth_of_ne (fin.vne_of_ne h)] lemma nth_update_nth_eq_if {v : vector α n} {i j : fin n} (a : α) : (v.update_nth i a).nth j = if i = j then a else v.nth j := by split_ifs; try {simp *}; try {rw nth_update_nth_of_ne}; assumption end update_nth end vector namespace vector section traverse variables {F G : Type u → Type u} variables [applicative F] [applicative G] open applicative functor open list (cons) nat private def traverse_aux {α β : Type u} (f : α → F β) : Π (x : list α), F (vector β x.length) | [] := pure vector.nil | (x::xs) := vector.cons <$> f x <*> traverse_aux xs protected def traverse {α β : Type u} (f : α → F β) : vector α n → F (vector β n) | ⟨v, Hv⟩ := cast (by rw Hv) $ traverse_aux f v variables [is_lawful_applicative F] [is_lawful_applicative G] variables {α β γ : Type u} @[simp] protected lemma traverse_def (f : α → F β) (x : α) : ∀ (xs : vector α n), (x ::ᵥ xs).traverse f = cons <$> f x <*> xs.traverse f := by rintro ⟨xs, rfl⟩; refl protected lemma id_traverse : ∀ (x : vector α n), x.traverse id.mk = x := begin rintro ⟨x, rfl⟩, dsimp [vector.traverse, cast], induction x with x xs IH, {refl}, simp! [IH], refl end open function protected lemma comp_traverse (f : β → F γ) (g : α → G β) : ∀ (x : vector α n), vector.traverse (comp.mk ∘ functor.map f ∘ g) x = comp.mk (vector.traverse f <$> vector.traverse g x) := by rintro ⟨x, rfl⟩; dsimp [vector.traverse, cast]; induction x with x xs; simp! [cast, *] with functor_norm; [refl, simp [(∘)]] protected lemma traverse_eq_map_id {α β} (f : α → β) : ∀ (x : vector α n), x.traverse (id.mk ∘ f) = id.mk (map f x) := by rintro ⟨x, rfl⟩; simp!; induction x; simp! * with functor_norm; refl variable (η : applicative_transformation F G) protected lemma naturality {α β : Type*} (f : α → F β) : ∀ (x : vector α n), η (x.traverse f) = x.traverse (@η _ ∘ f) := by rintro ⟨x, rfl⟩; simp! [cast]; induction x with x xs IH; simp! * with functor_norm end traverse instance : traversable.{u} (flip vector n) := { traverse := @vector.traverse n, map := λ α β, @vector.map.{u u} α β n } instance : is_lawful_traversable.{u} (flip vector n) := { id_traverse := @vector.id_traverse n, comp_traverse := @vector.comp_traverse n, traverse_eq_map_id := @vector.traverse_eq_map_id n, naturality := @vector.naturality n, id_map := by intros; cases x; simp! [(<$>)], comp_map := by intros; cases x; simp! [(<$>)] } end vector
d48cb8fbfcf69772aa35d353513e24cf5b2b4606
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/multiset/nodup.lean
1b2d7d382837f5ccd3808b98f683accaa9df04b8
[ "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
9,883
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.multiset.bind import data.multiset.powerset import data.multiset.range /-! # The `nodup` predicate for multisets without duplicate elements. -/ namespace multiset open function list variables {α β γ : Type*} {r : α → α → Prop} {s t : multiset α} {a : α} /- nodup -/ /-- `nodup s` means that `s` has no duplicates, i.e. the multiplicity of any element is at most 1. -/ def nodup (s : multiset α) : Prop := quot.lift_on s nodup (λ s t p, propext p.nodup_iff) @[simp] theorem coe_nodup {l : list α} : @nodup α l ↔ l.nodup := iff.rfl @[simp] theorem nodup_zero : @nodup α 0 := pairwise.nil @[simp] theorem nodup_cons {a : α} {s : multiset α} : nodup (a ::ₘ s) ↔ a ∉ s ∧ nodup s := quot.induction_on s $ λ l, nodup_cons lemma nodup.cons (m : a ∉ s) (n : nodup s) : nodup (a ::ₘ s) := nodup_cons.2 ⟨m, n⟩ @[simp] theorem nodup_singleton : ∀ a : α, nodup ({a} : multiset α) := nodup_singleton lemma nodup.of_cons (h : nodup (a ::ₘ s)) : nodup s := (nodup_cons.1 h).2 theorem nodup.not_mem (h : nodup (a ::ₘ s)) : a ∉ s := (nodup_cons.1 h).1 theorem nodup_of_le {s t : multiset α} (h : s ≤ t) : nodup t → nodup s := le_induction_on h $ λ l₁ l₂, nodup.sublist theorem not_nodup_pair : ∀ a : α, ¬ nodup (a ::ₘ a ::ₘ 0) := not_nodup_pair theorem nodup_iff_le {s : multiset α} : nodup s ↔ ∀ a : α, ¬ a ::ₘ a ::ₘ 0 ≤ s := quot.induction_on s $ λ l, nodup_iff_sublist.trans $ forall_congr $ λ a, not_congr (@repeat_le_coe _ a 2 _).symm lemma nodup_iff_ne_cons_cons {s : multiset α} : s.nodup ↔ ∀ a t, s ≠ a ::ₘ a ::ₘ t := nodup_iff_le.trans ⟨λ h a t s_eq, h a (s_eq.symm ▸ cons_le_cons a (cons_le_cons a (zero_le _))), λ h a le, let ⟨t, s_eq⟩ := le_iff_exists_add.mp le in h a t (by rwa [cons_add, cons_add, zero_add] at s_eq )⟩ theorem nodup_iff_count_le_one [decidable_eq α] {s : multiset α} : nodup s ↔ ∀ a, count a s ≤ 1 := quot.induction_on s $ λ l, nodup_iff_count_le_one @[simp] theorem count_eq_one_of_mem [decidable_eq α] {a : α} {s : multiset α} (d : nodup s) (h : a ∈ s) : count a s = 1 := le_antisymm (nodup_iff_count_le_one.1 d a) (count_pos.2 h) lemma count_eq_of_nodup [decidable_eq α] {a : α} {s : multiset α} (d : nodup s) : count a s = if a ∈ s then 1 else 0 := begin split_ifs with h, { exact count_eq_one_of_mem d h }, { exact count_eq_zero_of_not_mem h }, end lemma nodup_iff_pairwise {α} {s : multiset α} : nodup s ↔ pairwise (≠) s := quotient.induction_on s $ λ l, (pairwise_coe_iff_pairwise (by exact λ a b, ne.symm)).symm protected lemma nodup.pairwise : (∀ a ∈ s, ∀ b ∈ s, a ≠ b → r a b) → nodup s → pairwise r s := quotient.induction_on s $ assume l h hl, ⟨l, rfl, hl.imp_of_mem $ assume a b ha hb, h a ha b hb⟩ lemma pairwise.forall (H : symmetric r) (hs : pairwise r s) : ∀ ⦃a⦄, a ∈ s → ∀ ⦃b⦄, b ∈ s → a ≠ b → r a b := let ⟨l, hl₁, hl₂⟩ := hs in hl₁.symm ▸ hl₂.forall H theorem nodup_add {s t : multiset α} : nodup (s + t) ↔ nodup s ∧ nodup t ∧ disjoint s t := quotient.induction_on₂ s t $ λ l₁ l₂, nodup_append theorem disjoint_of_nodup_add {s t : multiset α} (d : nodup (s + t)) : disjoint s t := (nodup_add.1 d).2.2 lemma nodup.add_iff (d₁ : nodup s) (d₂ : nodup t) : nodup (s + t) ↔ disjoint s t := by simp [nodup_add, d₁, d₂] lemma nodup.of_map (f : α → β) : nodup (map f s) → nodup s := quot.induction_on s $ λ l, nodup.of_map f lemma nodup.map_on {f : α → β} : (∀ x ∈ s, ∀ y ∈ s, f x = f y → x = y) → nodup s → nodup (map f s) := quot.induction_on s $ λ l, nodup.map_on lemma nodup.map {f : α → β} {s : multiset α} (hf : injective f) : nodup s → nodup (map f s) := nodup.map_on (λ x _ y _ h, hf h) theorem inj_on_of_nodup_map {f : α → β} {s : multiset α} : nodup (map f s) → ∀ (x ∈ s) (y ∈ s), f x = f y → x = y := quot.induction_on s $ λ l, inj_on_of_nodup_map theorem nodup_map_iff_inj_on {f : α → β} {s : multiset α} (d : nodup s) : nodup (map f s) ↔ (∀ (x ∈ s) (y ∈ s), f x = f y → x = y) := ⟨inj_on_of_nodup_map, λ h, d.map_on h⟩ lemma nodup.filter (p : α → Prop) [decidable_pred p] {s} : nodup s → nodup (filter p s) := quot.induction_on s $ λ l, nodup.filter p @[simp] theorem nodup_attach {s : multiset α} : nodup (attach s) ↔ nodup s := quot.induction_on s $ λ l, nodup_attach lemma nodup.pmap {p : α → Prop} {f : Π a, p a → β} {s : multiset α} {H} (hf : ∀ a ha b hb, f a ha = f b hb → a = b) : nodup s → nodup (pmap f s H) := quot.induction_on s (λ l H, nodup.pmap hf) H instance nodup_decidable [decidable_eq α] (s : multiset α) : decidable (nodup s) := quotient.rec_on_subsingleton s $ λ l, l.nodup_decidable lemma nodup.erase_eq_filter [decidable_eq α] (a : α) {s} : nodup s → s.erase a = filter (≠ a) s := quot.induction_on s $ λ l d, congr_arg coe $ d.erase_eq_filter a lemma nodup.erase [decidable_eq α] (a : α) {l} : nodup l → nodup (l.erase a) := nodup_of_le (erase_le _ _) lemma nodup.mem_erase_iff [decidable_eq α] {a b : α} {l} (d : nodup l) : a ∈ l.erase b ↔ a ≠ b ∧ a ∈ l := by rw [d.erase_eq_filter b, mem_filter, and_comm] lemma nodup.not_mem_erase [decidable_eq α] {a : α} {s} (h : nodup s) : a ∉ s.erase a := λ ha, (h.mem_erase_iff.1 ha).1 rfl protected lemma nodup.product {t : multiset β} : nodup s → nodup t → nodup (product s t) := quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, by simp [d₁.product d₂] protected lemma nodup.sigma {σ : α → Type*} {t : Π a, multiset (σ a)} : nodup s → (∀ a, nodup (t a)) → nodup (s.sigma t) := quot.induction_on s $ assume l₁, begin choose f hf using assume a, quotient.exists_rep (t a), rw show t = λ a, f a, from (eq.symm $ funext $ λ a, hf a), simpa using nodup.sigma end protected lemma nodup.filter_map (f : α → option β) (H : ∀ a a' b, b ∈ f a → b ∈ f a' → a = a') : nodup s → nodup (filter_map f s) := quot.induction_on s $ λ l, nodup.filter_map H theorem nodup_range (n : ℕ) : nodup (range n) := nodup_range _ lemma nodup.inter_left [decidable_eq α] (t) : nodup s → nodup (s ∩ t) := nodup_of_le $ inter_le_left _ _ lemma nodup.inter_right [decidable_eq α] (s) : nodup t → nodup (s ∩ t) := nodup_of_le $ inter_le_right _ _ @[simp] theorem nodup_union [decidable_eq α] {s t : multiset α} : nodup (s ∪ t) ↔ nodup s ∧ nodup t := ⟨λ h, ⟨nodup_of_le (le_union_left _ _) h, nodup_of_le (le_union_right _ _) h⟩, λ ⟨h₁, h₂⟩, nodup_iff_count_le_one.2 $ λ a, by rw [count_union]; exact max_le (nodup_iff_count_le_one.1 h₁ a) (nodup_iff_count_le_one.1 h₂ a)⟩ @[simp] theorem nodup_powerset {s : multiset α} : nodup (powerset s) ↔ nodup s := ⟨λ h, (nodup_of_le (map_single_le_powerset _) h).of_map _, quotient.induction_on s $ λ l h, by simp; refine (nodup_sublists'.2 h).map_on _ ; exact λ x sx y sy e, (h.sublist_ext (mem_sublists'.1 sx) (mem_sublists'.1 sy)).1 (quotient.exact e)⟩ alias nodup_powerset ↔ nodup.of_powerset nodup.powerset protected lemma nodup.powerset_len {n : ℕ} (h : nodup s) : nodup (powerset_len n s) := nodup_of_le (powerset_len_le_powerset _ _) (nodup_powerset.2 h) @[simp] lemma nodup_bind {s : multiset α} {t : α → multiset β} : nodup (bind s t) ↔ ((∀a∈s, nodup (t a)) ∧ (s.pairwise (λa b, disjoint (t a) (t b)))) := have h₁ : ∀a, ∃l:list β, t a = l, from assume a, quot.induction_on (t a) $ assume l, ⟨l, rfl⟩, let ⟨t', h'⟩ := classical.axiom_of_choice h₁ in have t = λa, t' a, from funext h', have hd : symmetric (λa b, list.disjoint (t' a) (t' b)), from assume a b h, h.symm, quot.induction_on s $ by simp [this, list.nodup_bind, pairwise_coe_iff_pairwise hd] lemma nodup.ext {s t : multiset α} : nodup s → nodup t → (s = t ↔ ∀ a, a ∈ s ↔ a ∈ t) := quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, quotient.eq.trans $ perm_ext d₁ d₂ theorem le_iff_subset {s t : multiset α} : nodup s → (s ≤ t ↔ s ⊆ t) := quotient.induction_on₂ s t $ λ l₁ l₂ d, ⟨subset_of_le, d.subperm⟩ theorem range_le {m n : ℕ} : range m ≤ range n ↔ m ≤ n := (le_iff_subset (nodup_range _)).trans range_subset theorem mem_sub_of_nodup [decidable_eq α] {a : α} {s t : multiset α} (d : nodup s) : a ∈ s - t ↔ a ∈ s ∧ a ∉ t := ⟨λ h, ⟨mem_of_le tsub_le_self h, λ h', by refine count_eq_zero.1 _ h; rw [count_sub a s t, tsub_eq_zero_iff_le]; exact le_trans (nodup_iff_count_le_one.1 d _) (count_pos.2 h')⟩, λ ⟨h₁, h₂⟩, or.resolve_right (mem_add.1 $ mem_of_le le_tsub_add h₁) h₂⟩ lemma map_eq_map_of_bij_of_nodup (f : α → γ) (g : β → γ) {s : multiset α} {t : multiset β} (hs : s.nodup) (ht : t.nodup) (i : Πa∈s, β) (hi : ∀a ha, i a ha ∈ t) (h : ∀a ha, f a = g (i a ha)) (i_inj : ∀a₁ a₂ ha₁ ha₂, i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂) (i_surj : ∀b∈t, ∃a ha, b = i a ha) : s.map f = t.map g := have t = s.attach.map (λ x, i x.1 x.2), from (ht.ext $ (nodup_attach.2 hs).map $ show injective (λ x : {x // x ∈ s}, i x.1 x.2), from λ x y hxy, subtype.eq $ i_inj x.1 y.1 x.2 y.2 hxy).2 (λ x, by simp only [mem_map, true_and, subtype.exists, eq_comm, mem_attach]; exact ⟨i_surj _, λ ⟨y, hy⟩, hy.snd.symm ▸ hi _ _⟩), calc s.map f = s.pmap (λ x _, f x) (λ _, id) : by rw [pmap_eq_map] ... = s.attach.map (λ x, f x.1) : by rw [pmap_eq_map_attach] ... = t.map g : by rw [this, multiset.map_map]; exact map_congr rfl (λ x _, h _ _) end multiset
7de7a1cf2b227eb9b3ab9791964ef136eec82fc0
6b7c9c6393bac7cb1c64582a1c62597e24f5bb80
/src/basic/control.lean
443ad35d85cb4a2cc3550da216972a17321dae3a
[ "Apache-2.0" ]
permissive
alreadydone/lean-gptf
56a7d9cbd9400af72fb143d60c8774b8cfbc09cb
b4ab1eb2da0178f3dcdc49771d9fed6b50e35d98
refs/heads/master
1,679,371,993,063
1,614,479,778,000
1,614,479,778,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,401
lean
/- Author: E.W.Ayers © 2019. Some helpers for dealing with monads etc. -/ import control.monad.writer control.fold universes u v section /- Having a writer with append is really useful! -/ def writer_m (ω : Type) (α : Type) := ω × α variables {ω : Type} [has_append ω] [has_emptyc ω] {α : Type} instance writer_m.is_monad : monad (writer_m ω) := { pure := λ α a, (∅, a) , bind := λ α β ⟨w,a⟩ f, let ⟨w₂,b⟩ := f a in ⟨w ++ w₂, b⟩ } def writer_m.tell : ω → writer_m ω unit | x := (x, ()) def writer_m.run : writer_m ω α → ω × α := id end namespace writer_t variables {ω : Type u} {m : Type u → Type v} [monad m] {α β : Type u} [has_emptyc ω] [has_append ω] instance monad_of_append : monad (writer_t ω m) := @writer_t.monad ω m _ ⟨∅⟩ ⟨(++)⟩ instance lift_of_empty : has_monad_lift m (writer_t ω m) := ⟨λ α, @writer_t.lift _ _ _ _ ⟨∅⟩⟩ end writer_t def list_writer_t (σ : Type u) := writer_t (free_monoid σ) namespace list_writer_t local attribute [reducible] list_writer_t free_monoid variables {σ : Type u} {m : Type u → Type v} [monad m] instance : monad (list_writer_t σ m) := by apply_instance instance : monad_writer (list σ) (list_writer_t σ m) := by apply_instance end list_writer_t namespace alternative section variables {T S : Type u → Type u} [applicative T] [alternative S] instance : alternative (T ∘ S) := { pure := λ α x, (pure (pure x) : T (S _)), failure := λ x, (pure $ failure : T (S _)), seq := λ α β f x, show T(S β), from pure (<*>) <*> f <*> x, orelse := λ α a b, show T(S α), from pure (<|>) <*> a <*> b } end variables {T : Type u → Type v} [alternative T] {α β : Type u} def returnopt : option α → T α | none := failure | (some x) := pure x def optreturn : T α → T (option α) | t := (some <$> t) <|> (pure none) def is_ok {T : Type → Type v} [alternative T] {α : Type}: T α → T (bool) | t := (t *> pure (tt)) <|> pure (ff) def mguard {T : Type → Type v} [alternative T] [monad T]: T bool → T unit | c := do b ← c, if b then pure () else failure variables [monad T] meta def repeat (t : T α) : T (list α) := (pure list.cons <*> t <*> (pure punit.star >>= λ _, repeat)) <|> pure [] end alternative def except.flip {ε : Type u} {α : Type v} : except ε α → except α ε | e := except.rec except.ok except.error e instance monad_except.of_statet {ε σ} {m : Type → Type} [monad m] [monad_except ε m] : monad_except ε (state_t σ m) := { throw := λ α e, state_t.lift $ throw e , catch := λ α S e, ⟨λ s, catch (state_t.run S s) (λ x, state_t.run (e x) s)⟩ -- [note] alternatively, you could propagate the state. } instance monad_except.alt {ε} [inhabited ε] {m : Type → Type} [monad m] [monad_except ε m] : alternative m := { failure := λ α,throw $ inhabited.default ε , orelse := λ α x y, monad_except.orelse x y } def monad_state.hypothetically {m : Type → Type} [monad m] {σ α : Type} [monad_state σ m] : m α → m α | m := do s ← get, a ← m, put s, pure a notation `⍐` := monad_lift namespace interaction_monad namespace result variables {σ α β : Type} protected meta def map (f : α → β) : interaction_monad.result σ α → interaction_monad.result σ β | (success b s) := success (f b) s | (exception m p s) := exception m p s meta def map_state {τ : Type} (f : σ → τ) : result σ α → result τ α | (success a s) := success a (f s) | (exception m p s) := exception m p (f s) meta def state : result σ α → σ | (success b s) := s | (exception m p s) := s meta def get : result σ α → option α | (success b _) := some b | (exception _ _ _) := none meta def as_success : result σ α → option (α × σ) | (success b s) := some (b,s) | _ := none meta def as_exception : result σ α → option (option (unit → format) × option pos × σ) | (success b s) := none | (exception m p s) := (m,p,s) meta def as_except : result σ α → except (option (unit → format) × option pos) α | (success b s) := except.ok b | (exception m p s) := except.error $ (m, p) meta instance {σ} : functor (result σ) := {map := @result.map σ} end result meta instance {σ} : monad_state σ (interaction_monad σ) := {lift := λ α s x, let ⟨a,x⟩ := s.run x in result.success a x } meta instance {σ} : alternative (interaction_monad σ) := { failure := @interaction_monad.failed _, orelse := @interaction_monad_orelse _ } meta def lift_of_lens {τ σ} (get : τ → σ) (put : σ → τ → τ) : Π {α}, (interaction_monad σ α) → (interaction_monad τ α) | α s t := result.map_state (function.swap put $ t) $ s $ get t meta def has_monad_lift_of_lens {τ σ} (get : τ → σ) (put : σ → τ → τ) : has_monad_lift (interaction_monad σ) (interaction_monad τ) := ⟨λ α, lift_of_lens get put⟩ /-- Perform the given tactic but then just keep the result and throw away the state. -/ meta def hypothetically {σ α} : interaction_monad σ α → interaction_monad σ α | t s := result.map_state (λ _, s) $ t s meta def get_state_after {σ α}: interaction_monad σ α → interaction_monad σ σ | t s := let s := result.state $ t s in result.success s s meta def return_except {ε σ α} [has_to_format ε] : except ε α → interaction_monad σ α | (except.ok a) := pure a | (except.error e) := interaction_monad.fail e meta def run_simple {σ α}: interaction_monad σ α → σ → option (α × σ) | m s := result.as_success $ m s /-- If the given tactic fails, trace the failure message. -/ meta def trace_fail {σ α} (tr : format → interaction_monad σ unit) (t : interaction_monad σ α) : (interaction_monad σ α) | s := match t s with |(interaction_monad.result.exception msg pos _) := let msg := ("Exception: ":format) ++ (option.rec_on msg (to_fmt "silent") ($ ())) in ((tr msg) >> t) s |r := r end -- meta def lift_state_except {σ} : Π {α}, interaction_monad σ α → state_t σ (except_t (option (unit → format) × option pos) id) α -- | m := do -- s ← get, -- match m s with -- | (success b s) := put s *> pure b -- | (exception m p s) := put s *> throw (m,p) -- end end interaction_monad
0f5f3a64c121591cf5152604dc61195b2d734e50
5ca7b1b12d14c4742e29366312ba2c2ef8201b21
/src/game/world8/level10.lean
2c4930bfb333ce819bd954dc8389e71dd8fd1462
[ "Apache-2.0" ]
permissive
MatthiasHu/natural_number_game
2e464482ef3001863430b0336133b6697b275ba3
2d764f72669ae30861f6a1057fce0257f3e466c4
refs/heads/master
1,609,719,110,419
1,576,345,737,000
1,576,345,737,000
240,296,314
0
0
Apache-2.0
1,581,608,357,000
1,581,608,356,000
null
UTF-8
Lean
false
false
1,989
lean
import game.world8.level9 -- hide namespace mynat -- hide /- # Advanced Addition World ## Level 10: `add_left_eq_zero` ## Important: the definition of `≠` In Lean, `a ≠ b` is *defined to mean* `(a = b) → false`. This means that if you see `a ≠ b` you can *literally treat it as saying* `(a = b) → false`. Computer scientists would say that these two terms are *definitionally equal*. The following lemma, $a+b=0\implies b=0$, will be useful in inequality world. Let me go through the proof, because it introduces several new concepts: * `cases b` with `b : mynat` * `exfalso` * `apply succ_ne_zero` We're going to prove $a+b=0\implies b=0$. Here is the strategy. Each natural number is either `0` or `succ(d)` for some other natural number `d`. So we can start the proof with `cases b with d,` and then we have two goals, the case `b = 0` (which you can solve easily) and the case `b = succ(d)`, which looks like this: ``` a d : mynat, H : a + succ d = 0 ⊢ succ d = 0 ``` Our goal is impossible to prove. However our hypothesis `H` is also impossible, meaning that we still have a chance! First let's see why `H` is impossible. We can `rw add_succ at H,` to turn `H` into `H : succ (a + d) = 0`. Because `succ_ne_zero (a + d)` is a proof that `succ (a + d) ≠ 0`, it is also a proof of the implication `succ (a + d) = 0 → false`. Hence `succ_ne_zero (a + d) H` is a proof of `false`! Unfortunately our goal is not `false`, it's a generic false statement. Recall however that the `exfalso` command turns any goal into `false` (it's logically OK because `false` implies every proposition, true or false). You can probably take it from here. -/ /- Lemma If $a$ and $b$ are natural numbers such that $$ a + b = 0, $$ then $b = 0$. -/ lemma add_left_eq_zero (a b : mynat) (H : a + b = 0) : b = 0 := begin [nat_num_game] cases b with d, { refl}, { rw add_succ at H, exfalso, apply succ_ne_zero (a + d), exact H, }, end end mynat -- hide
e49b67ccc6b7fa580976a58ffb9a40f8eba876eb
94e33a31faa76775069b071adea97e86e218a8ee
/src/linear_algebra/projective_space/basic.lean
4be3ed2e0e4a049a9a67161a6b72a93c8ee73530
[ "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
8,248
lean
/- Copyright (c) 2022 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz -/ import linear_algebra.finite_dimensional /-! # Projective Spaces This file contains the definition of the projectivization of a vector space over a field, as well as the bijection between said projectivization and the collection of all one dimensional subspaces of the vector space. ## Notation `ℙ K V` is notation for `projectivization K V`, the projectivization of a `K`-vector space `V`. ## Constructing terms of `ℙ K V`. We have three ways to construct terms of `ℙ K V`: - `projectivization.mk K v hv` where `v : V` and `hv : v ≠ 0`. - `projectivization.mk' K v` where `v : { w : V // w ≠ 0 }`. - `projectivization.mk'' H h` where `H : submodule K V` and `h : finrank H = 1`. ## Other definitions - For `v : ℙ K V`, `v.submodule` gives the corresponding submodule of `V`. - `projectivization.equiv_submodule` is the equivalence between `ℙ K V` and `{ H : submodule K V // finrank H = 1 }`. - For `v : ℙ K V`, `v.rep : V` is a representative of `v`. ## Projects Everything in this file can be done for `division_ring`s instead of `field`s, but this would require a significant refactor of the results from `linear_algebra.finite_dimensional` and its imports. -/ variables (K V : Type*) [field K] [add_comm_group V] [module K V] /-- The setoid whose quotient is the projectivization of `V`. -/ def projectivization_setoid : setoid { v : V // v ≠ 0 } := (mul_action.orbit_rel Kˣ V).comap coe /-- The projectivization of the `K`-vector space `V`. The notation `ℙ K V` is preferred. -/ @[nolint has_inhabited_instance] def projectivization := quotient (projectivization_setoid K V) notation `ℙ` := projectivization namespace projectivization variables {V} /-- Construct an element of the projectivization from a nonzero vector. -/ def mk (v : V) (hv : v ≠ 0) : ℙ K V := quotient.mk' ⟨v,hv⟩ /-- A variant of `projectivization.mk` in terms of a subtype. `mk` is preferred. -/ def mk' (v : { v : V // v ≠ 0 }) : ℙ K V := quotient.mk' v @[simp] lemma mk'_eq_mk (v : { v : V // v ≠ 0}) : mk' K v = mk K v v.2 := by { dsimp [mk, mk'], congr' 1, simp } instance [nontrivial V] : nonempty (ℙ K V) := let ⟨v, hv⟩ := exists_ne (0 : V) in ⟨mk K v hv⟩ variable {K} /-- Choose a representative of `v : projectivization K V` in `V`. -/ protected noncomputable def rep (v : ℙ K V) : V := v.out' lemma rep_nonzero (v : ℙ K V) : v.rep ≠ 0 := v.out'.2 @[simp] lemma mk_rep (v : ℙ K V) : mk K v.rep v.rep_nonzero = v := by { dsimp [mk, projectivization.rep], simp } open finite_dimensional /-- Consider an element of the projectivization as a submodule of `V`. -/ protected def submodule (v : ℙ K V) : submodule K V := quotient.lift_on' v (λ v, K ∙ (v : V)) $ begin rintro ⟨a, ha⟩ ⟨b, hb⟩ ⟨x, (rfl : x • b = a)⟩, exact (submodule.span_singleton_group_smul_eq _ x _), end variable (K) lemma mk_eq_mk_iff (v w : V) (hv : v ≠ 0) (hw : w ≠ 0) : mk K v hv = mk K w hw ↔ ∃ (a : Kˣ), a • w = v := quotient.eq' /-- Two nonzero vectors go to the same point in projective space if and only if one is a scalar multiple of the other. -/ lemma mk_eq_mk_iff' (v w : V) (hv : v ≠ 0) (hw : w ≠ 0) : mk K v hv = mk K w hw ↔ ∃ (a : K), a • w = v := begin rw mk_eq_mk_iff K v w hv hw, split, { rintro ⟨a, ha⟩, exact ⟨a, ha⟩ }, { rintro ⟨a, ha⟩, refine ⟨units.mk0 a (λ c, hv.symm _), ha⟩, rwa [c, zero_smul] at ha } end lemma exists_smul_eq_mk_rep (v : V) (hv : v ≠ 0) : ∃ (a : Kˣ), a • v = (mk K v hv).rep := show (projectivization_setoid K V).rel _ _, from quotient.mk_out' ⟨v, hv⟩ variable {K} /-- An induction principle for `projectivization`. Use as `induction v using projectivization.ind`. -/ @[elab_as_eliminator] lemma ind {P : ℙ K V → Prop} (h : ∀ (v : V) (h : v ≠ 0), P (mk K v h)) : ∀ p, P p := quotient.ind' $ subtype.rec $ by exact h @[simp] lemma submodule_mk (v : V) (hv : v ≠ 0) : (mk K v hv).submodule = K ∙ v := rfl lemma submodule_eq (v : ℙ K V) : v.submodule = K ∙ v.rep := by { conv_lhs { rw ← v.mk_rep }, refl } lemma finrank_submodule (v : ℙ K V) : finrank K v.submodule = 1 := begin rw submodule_eq, exact finrank_span_singleton v.rep_nonzero, end instance (v : ℙ K V) : finite_dimensional K v.submodule := by { rw ← v.mk_rep, change finite_dimensional K (K ∙ v.rep), apply_instance } lemma submodule_injective : function.injective (projectivization.submodule : ℙ K V → submodule K V) := begin intros u v h, replace h := le_of_eq h, simp only [submodule_eq] at h, rw submodule.le_span_singleton_iff at h, rw [← mk_rep v, ← mk_rep u], apply quotient.sound', obtain ⟨a,ha⟩ := h u.rep (submodule.mem_span_singleton_self _), have : a ≠ 0 := λ c, u.rep_nonzero (by simpa [c] using ha.symm), use [units.mk0 a this, ha], end variables (K V) /-- The equivalence between the projectivization and the collection of subspaces of dimension 1. -/ noncomputable def equiv_submodule : ℙ K V ≃ { H : submodule K V // finrank K H = 1 } := equiv.of_bijective (λ v, ⟨v.submodule, v.finrank_submodule⟩) begin split, { intros u v h, apply_fun (λ e, e.val) at h, apply submodule_injective h }, { rintros ⟨H, h⟩, rw finrank_eq_one_iff' at h, obtain ⟨v, hv, h⟩ := h, have : (v : V) ≠ 0 := λ c, hv (subtype.coe_injective c), use mk K v this, symmetry, ext x, revert x, erw ← set.ext_iff, ext x, dsimp [-set_like.mem_coe], rw [submodule.span_singleton_eq_range], refine ⟨λ hh, _, _⟩, { obtain ⟨c,hc⟩ := h ⟨x,hh⟩, exact ⟨c, congr_arg coe hc⟩ }, { rintros ⟨c,rfl⟩, refine submodule.smul_mem _ _ v.2 } } end variables {K V} /-- Construct an element of the projectivization from a subspace of dimension 1. -/ noncomputable def mk'' (H : _root_.submodule K V) (h : finrank K H = 1) : ℙ K V := (equiv_submodule K V).symm ⟨H,h⟩ @[simp] lemma submodule_mk'' (H : _root_.submodule K V) (h : finrank K H = 1) : (mk'' H h).submodule = H := begin suffices : (equiv_submodule K V) (mk'' H h) = ⟨H,h⟩, by exact congr_arg coe this, dsimp [mk''], simp end @[simp] lemma mk''_submodule (v : ℙ K V) : mk'' v.submodule v.finrank_submodule = v := show (equiv_submodule K V).symm (equiv_submodule K V _) = _, by simp section map variables {L W : Type*} [field L] [add_comm_group W] [module L W] /-- An injective semilinear map of vector spaces induces a map on projective spaces. -/ def map {σ : K →+* L} (f : V →ₛₗ[σ] W) (hf : function.injective f) : ℙ K V → ℙ L W := quotient.map' (λ v, ⟨f v, λ c, v.2 (hf (by simp [c]))⟩) begin rintros ⟨u,hu⟩ ⟨v,hv⟩ ⟨a,ha⟩, use units.map σ.to_monoid_hom a, dsimp at ⊢ ha, erw [← f.map_smulₛₗ, ha], end /-- Mapping with respect to a semilinear map over an isomorphism of fields yields an injective map on projective spaces. -/ lemma map_injective {σ : K →+* L} {τ : L →+* K} [ring_hom_inv_pair σ τ] (f : V →ₛₗ[σ] W) (hf : function.injective f) : function.injective (map f hf) := begin intros u v h, rw [← u.mk_rep, ← v.mk_rep] at *, apply quotient.sound', dsimp [map, mk] at h, simp only [quotient.eq'] at h, obtain ⟨a,ha⟩ := h, use units.map τ.to_monoid_hom a, dsimp at ⊢ ha, have : (a : L) = σ (τ a), by rw ring_hom_inv_pair.comp_apply_eq₂, change (a : L) • f v.rep = f u.rep at ha, rw [this, ← f.map_smulₛₗ] at ha, exact hf ha, end @[simp] lemma map_id : map (linear_map.id : V →ₗ[K] V) (linear_equiv.refl K V).injective = id := by { ext v, induction v using projectivization.ind, refl } @[simp] lemma map_comp {F U : Type*} [field F] [add_comm_group U] [module F U] {σ : K →+* L} {τ : L →+* F} {γ : K →+* F} [ring_hom_comp_triple σ τ γ] (f : V →ₛₗ[σ] W) (hf : function.injective f) (g : W →ₛₗ[τ] U) (hg : function.injective g) : map (g.comp f) (hg.comp hf) = map g hg ∘ map f hf := by { ext v, induction v using projectivization.ind, refl } end map end projectivization
ec8c338d6a9ad668ef5e6fcd92f5e7201f285d45
7490bf5d40d31857a58062614642bb5a41c36154
/predicate_logic/intro_and_elim_rules/exists.lean
b7bd5d37de61f45bf0700a54468df542ef5d3bba
[]
no_license
reesegrayallen/Lean-Discrete-Mathematics
9f1d6fe1c814cc9264ce868a67adcf5a82566e22
00c875284613ea12e0a729f519738aab8599456b
refs/heads/main
1,674,181,372,629
1,606,801,004,000
1,606,801,004,000
317,387,970
0
0
null
null
null
null
UTF-8
Lean
false
false
5,152
lean
/- To prove that (∃ (p : P), Q) we show that there is a specific value, p, in the context of which we can prove Q. -/ /- Here's a silly example. We want to show that we can pick some natural number in the context of which we can construct a proof of 1=1. Of course it doesn't matter what number we pick because 1=1 is true in any case. So in the following example, we pick 524. But any value will do. -/ lemma silly : ∃ (n : ℕ), 1 = 1 := exists.intro 524 rfl /- The identifier, silly, is now bound to a proof of ∃ (n : ℕ), 1 = 1, and we can see that this proof is actually an ordered pair, labelled by the exists.intro constructor, the first element of which is a specific value of type P and the second of which is a proof of Q. -/ #reduce silly /- In practice, Q will almost always be a predicate taking a value of type P. In this case, ∃ (p : P), Q p asserts that there is some value, p : P, that makes the predicate, Q p true. In other words, ∃ (p : P), Q p asserts that there is some p with propery Q. -/ axiom Ball : Type -- assume there are Balls axioms b1 b2 : Ball -- b1 and b2 are balls axiom Blue : Ball → Prop -- Blue is a property axiom b1_is_blue : Blue b1 -- b1 is blue -- Prove there exists a blue ball example : ∃ (b : Ball), Blue b := -- use exists.intro exists.intro b1 -- here's the ball we picked b1_is_blue -- here's a proof it's Blue /- Here's another example. We'll define ev to be a predicate specifying a property of natural numbers of "being even". Then we'll show that there exists a number that has this property. -/ def even : ℕ → bool := λ n, n%2 = 0 example : exists (n : ℕ), even n := exists.intro 6 rfl /- The elimination rule for ∃ tells us what we can do with a a proof of an existentially quanitified proposition. Suppose for example that we're given a proof that there exists an even natural number. What can we deduce from this fact? We can deduce two things: first, there is a specific number and *we can give it a name*, such as n, for which, second, there is a proof, that we can also name, e.g., pf, that *that specific n* is even. This is the elimination rule. It sounds complicated but it's not really. Compare exists.intro and exists.elim to and.intro and and.elim. The and.intro rule takes two proofs and forms a pair. The and elimination rule takes such a pair and lets us get back (and give names to) the component proofs. Similarly, exists.intro forms a pair, of a value and a proof (usually a proof that that specific value has some property); and the exists.elimination rule, given a proof that such a value exists, let's us then give names to that value and the associated proof. *We can then use those two values in building other proofs*. And, as you might expect, we bind names to the component elements of a proof of ∃ (p : P), Q by case analysis, and specifically by pattern matching. -/ /- Example: Assume there are people and a binary predicate/relation called Likes. -/ axiom Person : Prop axiom Likes : Person → Person → Prop /- Show that if there exists someone everyone likes then everyone likes someone. -/ example : (∃ (p : Person), ∀ (q : Person), Likes q p) → (∀ (p : Person), ∃ (q : Person), Likes p q):= λ h : (∃ (p : Person), ∀ (q : Person), Likes q p), -- assume proof of ∃ (n : ℕ), even n match h with -- destructure this proof -- there's only one constructor, exists.intro -- give names to arguments to which it must have been applied | exists.intro beloved liked_by_all := -- now use *these* (now named) values to constructed needed proof λ anyone, exists.intro beloved (liked_by_all beloved) end example : (∃ (p : Person), ∀ (q : Person), Likes q p) → (∀ (p : Person), ∃ (q : Person), Likes p q):= λ person_exists_that_everyone_likes, match person_exists_that_everyone_likes with | exists.intro beloved loved_by_all := λ anyone, _ end -- exists.intro beloved (loved_by_all beloved ) -- end /- Here it is in plain English. Suppose there's someone everyone likes. Show that everyone likes someone. Proof: From the fact that there exists someone that everyone likes, we can deduce that (1) there is a specific person, who everyone likes; let's call that person "beloved"; and (2) it is the case that everyone likes beloved. Now we must show that everyone likes someone. Pick an arbitrary but specific person, call this person "anyone". We must show that there is someone that "anyone" likes. But everyone likes beloved, so "anyone", in particular, likes "beloved". Note: "anyone" might or might not like other people, but we can be sure that "anyone" likes beloved, and all we needed to show was that there is someone that "anyone" likes. QED. -/ /- In Lean, if you already have a proof of some existentially quantified proposition in your context, do case analysis on it to assign names to its two components: first a value and then a proof that that value makes the rest of the proposition true. By the way, we call such a value a "witness" to the given proposition. -/
16d50fe8b59fe87ed11bfab82770a954bbc2e32e
63abd62053d479eae5abf4951554e1064a4c45b4
/src/number_theory/pythagorean_triples.lean
e7296de04249790d04532e105ef6024d4e9bbcbc
[ "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
26,067
lean
/- Copyright (c) 2020 Paul van Wamelen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Paul van Wamelen. -/ import algebra.field import ring_theory.int.basic import algebra.group_with_zero_power import tactic.ring import tactic.ring_exp /-! # Pythagorean Triples The main result is the classification of pythagorean triples. The final result is for general pythagorean triples. It follows from the more interesting relatively prime case. We use the "rational parametrization of the circle" method for the proof. The parametrization maps the point `(x / z, y / z)` to the slope of the line through `(-1 , 0)` and `(x / z, y / z)`. This quickly shows that `(x / z, y / z) = (2 * m * n / (m ^ 2 + n ^ 2), (m ^ 2 - n ^ 2) / (m ^ 2 + n ^ 2))` where `m / n` is the slope. In order to identify numerators and denominators we now need results showing that these are coprime. This is easy except for the prime 2. In order to deal with that we have to analyze the parity of `x`, `y`, `m` and `n` and eliminate all the impossible cases. This takes up the bulk of the proof below. -/ noncomputable theory open_locale classical /-- Three integers `x`, `y`, and `z` form a Pythagorean triple if `x * x + y * y = z * z`. -/ def pythagorean_triple (x y z : ℤ) : Prop := x * x + y * y = z * z /-- Pythagorean triples are interchangable, i.e `x * x + y * y = y * y + x * x = z * z`. This comes from additive commutativity. -/ lemma pythagorean_triple_comm {x y z : ℤ} : (pythagorean_triple x y z) ↔ (pythagorean_triple y x z) := by { delta pythagorean_triple, rw add_comm } /-- The zeroth Pythagorean triple is all zeros. -/ lemma pythagorean_triple.zero : pythagorean_triple 0 0 0 := by simp only [pythagorean_triple, zero_mul, zero_add] namespace pythagorean_triple variables {x y z : ℤ} (h : pythagorean_triple x y z) include h lemma eq : x * x + y * y = z * z := h @[symm] lemma symm : pythagorean_triple y x z := by rwa [pythagorean_triple_comm] /-- A triple is still a triple if you multiply `x`, `y` and `z` by a constant `k`. -/ lemma mul (k : ℤ) : pythagorean_triple (k * x) (k * y) (k * z) := begin by_cases hk : k = 0, { simp only [pythagorean_triple, hk, zero_mul, zero_add], }, { calc (k * x) * (k * x) + (k * y) * (k * y) = k ^ 2 * (x * x + y * y) : by ring ... = k ^ 2 * (z * z) : by rw h.eq ... = (k * z) * (k * z) : by ring } end omit h /-- `(k*x, k*y, k*z)` is a Pythagorean triple if and only if `(x, y, z)` is also a triple. -/ lemma mul_iff (k : ℤ) (hk : k ≠ 0) : pythagorean_triple (k * x) (k * y) (k * z) ↔ pythagorean_triple x y z := begin refine ⟨_, λ h, h.mul k⟩, simp only [pythagorean_triple], intro h, rw ← mul_left_inj' (mul_ne_zero hk hk), convert h using 1; ring, end include h /-- A pythogorean triple `x, y, z` is “classified” if there exist integers `k, m, n` such that either * `x = k * (m ^ 2 - n ^ 2)` and `y = k * (2 * m * n)`, or * `x = k * (2 * m * n)` and `y = k * (m ^ 2 - n ^ 2)`. -/ @[nolint unused_arguments] def is_classified := ∃ (k m n : ℤ), ((x = k * (m ^ 2 - n ^ 2) ∧ y = k * (2 * m * n)) ∨ (x = k * (2 * m * n) ∧ y = k * (m ^ 2 - n ^ 2))) ∧ int.gcd m n = 1 /-- A primitive pythogorean triple `x, y, z` is a pythagorean triple with `x` and `y` coprime. Such a triple is “primitively classified” if there exist coprime integers `m, n` such that either * `x = m ^ 2 - n ^ 2` and `y = 2 * m * n`, or * `x = 2 * m * n` and `y = m ^ 2 - n ^ 2`. -/ @[nolint unused_arguments] def is_primitive_classified := ∃ (m n : ℤ), ((x = m ^ 2 - n ^ 2 ∧ y = 2 * m * n) ∨ (x = 2 * m * n ∧ y = m ^ 2 - n ^ 2)) ∧ int.gcd m n = 1 ∧ ((m % 2 = 0 ∧ n % 2 = 1) ∨ (m % 2 = 1 ∧ n % 2 = 0)) lemma mul_is_classified (k : ℤ) (hc : h.is_classified) : (h.mul k).is_classified := begin obtain ⟨l, m, n, ⟨⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, co⟩⟩ := hc, { use [k * l, m, n], apply and.intro _ co, left, split; ring }, { use [k * l, m, n], apply and.intro _ co, right, split; ring }, end lemma even_odd_of_coprime (hc : int.gcd x y = 1) : (x % 2 = 0 ∧ y % 2 = 1) ∨ (x % 2 = 1 ∧ y % 2 = 0) := begin cases int.mod_two_eq_zero_or_one x with hx hx; cases int.mod_two_eq_zero_or_one y with hy hy, { -- x even, y even exfalso, apply nat.not_coprime_of_dvd_of_dvd (dec_trivial : 1 < 2) _ _ hc, { apply int.dvd_nat_abs_of_of_nat_dvd, apply int.dvd_of_mod_eq_zero hx }, { apply int.dvd_nat_abs_of_of_nat_dvd, apply int.dvd_of_mod_eq_zero hy } }, { left, exact ⟨hx, hy⟩ }, -- x even, y odd { right, exact ⟨hx, hy⟩ }, -- x odd, y even { -- x odd, y odd exfalso, obtain ⟨x0, y0, rfl, rfl⟩ : ∃ x0 y0, x = x0* 2 + 1 ∧ y = y0 * 2 + 1, { cases exists_eq_mul_left_of_dvd (int.dvd_sub_of_mod_eq hx) with x0 hx2, cases exists_eq_mul_left_of_dvd (int.dvd_sub_of_mod_eq hy) with y0 hy2, rw sub_eq_iff_eq_add at hx2 hy2, exact ⟨x0, y0, hx2, hy2⟩ }, have hz : (z * z) % 4 = 2, { rw show z * z = 4 * (x0 * x0 + x0 + y0 * y0 + y0) + 2, by { rw ← h.eq, ring }, simp only [int.add_mod, int.mul_mod_right, int.mod_mod, zero_add], refl }, have : ∀ (k : ℤ), 0 ≤ k → k < 4 → k * k % 4 ≠ 2 := dec_trivial, have h4 : (4 : ℤ) ≠ 0 := dec_trivial, apply this (z % 4) (int.mod_nonneg z h4) (int.mod_lt z h4), rwa [← int.mul_mod] }, end lemma gcd_dvd : (int.gcd x y : ℤ) ∣ z := begin by_cases h0 : int.gcd x y = 0, { have hx : x = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_left h0 }, have hy : y = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_right h0 }, have hz : z = 0, { simpa only [pythagorean_triple, hx, hy, add_zero, zero_eq_mul, mul_zero, or_self] using h }, simp only [hz, dvd_zero], }, obtain ⟨k, x0, y0, k0, h2, rfl, rfl⟩ : ∃ (k : ℕ) x0 y0, 0 < k ∧ int.gcd x0 y0 = 1 ∧ x = x0 * k ∧ y = y0 * k := int.exists_gcd_one' (nat.pos_of_ne_zero h0), rw [int.gcd_mul_right, h2, int.nat_abs_of_nat, one_mul], rw [← int.pow_dvd_pow_iff (dec_trivial : 0 < 2), pow_two z, ← h.eq], rw (by ring : x0 * k * (x0 * k) + y0 * k * (y0 * k) = k ^ 2 * (x0 * x0 + y0 * y0)), exact dvd_mul_right _ _ end lemma normalize : pythagorean_triple (x / int.gcd x y) (y / int.gcd x y) (z / int.gcd x y) := begin by_cases h0 : int.gcd x y = 0, { have hx : x = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_left h0 }, have hy : y = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_right h0 }, have hz : z = 0, { simpa only [pythagorean_triple, hx, hy, add_zero, zero_eq_mul, mul_zero, or_self] using h }, simp only [hx, hy, hz, int.zero_div], exact zero }, rcases h.gcd_dvd with ⟨z0, rfl⟩, obtain ⟨k, x0, y0, k0, h2, rfl, rfl⟩ : ∃ (k : ℕ) x0 y0, 0 < k ∧ int.gcd x0 y0 = 1 ∧ x = x0 * k ∧ y = y0 * k := int.exists_gcd_one' (nat.pos_of_ne_zero h0), have hk : (k : ℤ) ≠ 0, { norm_cast, rwa nat.pos_iff_ne_zero at k0 }, rw [int.gcd_mul_right, h2, int.nat_abs_of_nat, one_mul] at h ⊢, rw [mul_comm x0, mul_comm y0, mul_iff k hk] at h, rwa [int.mul_div_cancel _ hk, int.mul_div_cancel _ hk, int.mul_div_cancel_left _ hk], end lemma is_classified_of_is_primitive_classified (hp : h.is_primitive_classified) : h.is_classified := begin obtain ⟨m, n, H⟩ := hp, use [1, m, n], rcases H with ⟨⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, co, pp⟩; { apply and.intro _ co, rw one_mul, rw one_mul, tauto } end lemma is_classified_of_normalize_is_primitive_classified (hc : h.normalize.is_primitive_classified) : h.is_classified := begin convert h.normalize.mul_is_classified (int.gcd x y) (is_classified_of_is_primitive_classified h.normalize hc); rw int.mul_div_cancel', { exact int.gcd_dvd_left x y }, { exact int.gcd_dvd_right x y }, { exact h.gcd_dvd } end lemma ne_zero_of_coprime (hc : int.gcd x y = 1) : z ≠ 0 := begin suffices : 0 < z * z, { rintro rfl, norm_num at this }, rw [← h.eq, ← pow_two, ← pow_two], have hc' : int.gcd x y ≠ 0, { rw hc, exact one_ne_zero }, cases int.ne_zero_of_gcd hc' with hxz hyz, { apply lt_add_of_pos_of_le (pow_two_pos_of_ne_zero x hxz) (pow_two_nonneg y) }, { apply lt_add_of_le_of_pos (pow_two_nonneg x) (pow_two_pos_of_ne_zero y hyz) } end lemma is_primitive_classified_of_coprime_of_zero_left (hc : int.gcd x y = 1) (hx : x = 0) : h.is_primitive_classified := begin subst x, change nat.gcd 0 (int.nat_abs y) = 1 at hc, rw [nat.gcd_zero_left (int.nat_abs y)] at hc, cases int.nat_abs_eq y with hy hy, { use [1, 0], rw [hy, hc, int.gcd_zero_right], norm_num }, { use [0, 1], rw [hy, hc, int.gcd_zero_left], norm_num } end lemma coprime_of_coprime (hc : int.gcd x y = 1) : int.gcd y z = 1 := begin by_contradiction H, obtain ⟨p, hp, hpy, hpz⟩ := nat.prime.not_coprime_iff_dvd.mp H, apply hp.not_dvd_one, rw [← hc], apply nat.dvd_gcd (int.prime.dvd_nat_abs_of_coe_dvd_pow_two hp _ _) hpy, rw [pow_two, eq_sub_of_add_eq h], rw [← int.coe_nat_dvd_left] at hpy hpz, exact dvd_sub (dvd_mul_of_dvd_left (hpz) _) (dvd_mul_of_dvd_left (hpy) _), end end pythagorean_triple section circle_equiv_gen /-! ### A parametrization of the unit circle For the classification of pythogorean triples, we will use a parametrization of the unit circle. -/ variables {K : Type*} [field K] /-- A parameterization of the unit circle that is useful for classifying Pythagorean triples. (To be applied in the case where `K = ℚ`.) -/ def circle_equiv_gen (hk : ∀ x : K, 1 + x^2 ≠ 0) : K ≃ {p : K × K // p.1^2 + p.2^2 = 1 ∧ p.2 ≠ -1} := { to_fun := λ x, ⟨⟨2 * x / (1 + x^2), (1 - x^2) / (1 + x^2)⟩, by { field_simp [hk x, div_pow], ring }, begin simp only [ne.def, div_eq_iff (hk x), ←neg_mul_eq_neg_mul, one_mul, neg_add, sub_eq_add_neg, add_left_inj], simpa only [eq_neg_iff_add_eq_zero, one_pow] using hk 1, end⟩, inv_fun := λ p, (p : K × K).1 / ((p : K × K).2 + 1), left_inv := λ x, begin have h2 : (1 + 1 : K) = 2 := rfl, have h3 : (2 : K) ≠ 0, { convert hk 1, rw [one_pow 2, h2] }, field_simp [hk x, h2, h3, add_assoc, add_comm, add_sub_cancel'_right, mul_comm], end, right_inv := λ ⟨⟨x, y⟩, hxy, hy⟩, begin change x ^ 2 + y ^ 2 = 1 at hxy, have h2 : y + 1 ≠ 0, { apply mt eq_neg_of_add_eq_zero, exact hy }, have h3 : (y + 1) ^ 2 + x ^ 2 = 2 * (y + 1), { rw [(add_neg_eq_iff_eq_add.mpr hxy.symm).symm], ring }, have h4 : (2 : K) ≠ 0, { convert hk 1, rw one_pow 2, refl }, simp only [prod.mk.inj_iff, subtype.mk_eq_mk], split, { field_simp [h2, h3, h4], ring }, { field_simp [h2, h3, h4], rw [← add_neg_eq_iff_eq_add.mpr hxy.symm], ring } end } @[simp] lemma circle_equiv_apply (hk : ∀ x : K, 1 + x^2 ≠ 0) (x : K) : (circle_equiv_gen hk x : K × K) = ⟨2 * x / (1 + x^2), (1 - x^2) / (1 + x^2)⟩ := rfl @[simp] lemma circle_equiv_symm_apply (hk : ∀ x : K, 1 + x^2 ≠ 0) (v : {p : K × K // p.1^2 + p.2^2 = 1 ∧ p.2 ≠ -1}) : (circle_equiv_gen hk).symm v = (v : K × K).1 / ((v : K × K).2 + 1) := rfl end circle_equiv_gen private lemma coprime_pow_two_sub_pow_two_add_of_even_odd {m n : ℤ} (h : int.gcd m n = 1) (hm : m % 2 = 0) (hn : n % 2 = 1) : int.gcd (m ^ 2 - n ^ 2) (m ^ 2 + n ^ 2) = 1 := begin by_contradiction H, obtain ⟨p, hp, hp1, hp2⟩ := nat.prime.not_coprime_iff_dvd.mp H, rw ← int.coe_nat_dvd_left at hp1 hp2, have h2m : (p : ℤ) ∣ 2 * m ^ 2, { convert dvd_add hp2 hp1, ring }, have h2n : (p : ℤ) ∣ 2 * n ^ 2, { convert dvd_sub hp2 hp1, ring }, have hmc : p = 2 ∨ p ∣ int.nat_abs m, { exact prime_two_or_dvd_of_dvd_two_mul_pow_self_two hp h2m }, have hnc : p = 2 ∨ p ∣ int.nat_abs n, { exact prime_two_or_dvd_of_dvd_two_mul_pow_self_two hp h2n }, by_cases h2 : p = 2, { have h3 : (m ^ 2 + n ^ 2) % 2 = 1, { norm_num [pow_two, int.add_mod, int.mul_mod, hm, hn] }, have h4 : (m ^ 2 + n ^ 2) % 2 = 0, { apply int.mod_eq_zero_of_dvd, rwa h2 at hp2 }, rw h4 at h3, exact zero_ne_one h3 }, { apply hp.not_dvd_one, rw ← h, exact nat.dvd_gcd (or.resolve_left hmc h2) (or.resolve_left hnc h2), } end private lemma coprime_pow_two_sub_pow_two_add_of_odd_even {m n : ℤ} (h : int.gcd m n = 1) (hm : m % 2 = 1) (hn : n % 2 = 0): int.gcd (m ^ 2 - n ^ 2) (m ^ 2 + n ^ 2) = 1 := begin rw [int.gcd, ← int.nat_abs_neg (m ^ 2 - n ^ 2)], rw [(by ring : -(m ^ 2 - n ^ 2) = n ^ 2 - m ^ 2), add_comm], apply coprime_pow_two_sub_pow_two_add_of_even_odd _ hn hm, rwa [int.gcd_comm], end private lemma coprime_pow_two_sub_mul_of_even_odd {m n : ℤ} (h : int.gcd m n = 1) (hm : m % 2 = 0) (hn : n % 2 = 1) : int.gcd (m ^ 2 - n ^ 2) (2 * m * n) = 1 := begin by_contradiction H, obtain ⟨p, hp, hp1, hp2⟩ := nat.prime.not_coprime_iff_dvd.mp H, rw ← int.coe_nat_dvd_left at hp1 hp2, have hnp : ¬ (p : ℤ) ∣ int.gcd m n, { rw h, norm_cast, exact mt nat.dvd_one.mp (nat.prime.ne_one hp) }, cases int.prime.dvd_mul hp hp2 with hp2m hpn, { rw int.nat_abs_mul at hp2m, cases (nat.prime.dvd_mul hp).mp hp2m with hp2 hpm, { have hp2' : p = 2, { exact le_antisymm (nat.le_of_dvd zero_lt_two hp2) (nat.prime.two_le hp) }, revert hp1, rw hp2', apply mt int.mod_eq_zero_of_dvd, norm_num [pow_two, int.sub_mod, int.mul_mod, hm, hn], }, apply mt (int.dvd_gcd (int.coe_nat_dvd_left.mpr hpm)) hnp, apply (or_self _).mp, apply int.prime.dvd_mul' hp, rw (by ring : n * n = - (m ^ 2 - n ^ 2) + m * m), apply dvd_add (dvd_neg_of_dvd hp1), exact dvd_mul_of_dvd_left (int.coe_nat_dvd_left.mpr hpm) m }, rw int.gcd_comm at hnp, apply mt (int.dvd_gcd (int.coe_nat_dvd_left.mpr hpn)) hnp, apply (or_self _).mp, apply int.prime.dvd_mul' hp, rw (by ring : m * m = (m ^ 2 - n ^ 2) + n * n), apply dvd_add hp1, exact dvd_mul_of_dvd_left (int.coe_nat_dvd_left.mpr hpn) n end private lemma coprime_pow_two_sub_mul_of_odd_even {m n : ℤ} (h : int.gcd m n = 1) (hm : m % 2 = 1) (hn : n % 2 = 0) : int.gcd (m ^ 2 - n ^ 2) (2 * m * n) = 1 := begin rw [int.gcd, ← int.nat_abs_neg (m ^ 2 - n ^ 2)], rw [(by ring : 2 * m * n = 2 * n * m), (by ring : -(m ^ 2 - n ^ 2) = n ^ 2 - m ^ 2)], apply coprime_pow_two_sub_mul_of_even_odd _ hn hm, rwa [int.gcd_comm] end private lemma coprime_pow_two_sub_mul {m n : ℤ} (h : int.gcd m n = 1) (hmn : (m % 2 = 0 ∧ n % 2 = 1) ∨ (m % 2 = 1 ∧ n % 2 = 0)) : int.gcd (m ^ 2 - n ^ 2) (2 * m * n) = 1 := begin cases hmn with h1 h2, { exact coprime_pow_two_sub_mul_of_even_odd h h1.left h1.right }, { exact coprime_pow_two_sub_mul_of_odd_even h h2.left h2.right } end private lemma coprime_pow_two_sub_pow_two_sum_of_odd_odd {m n : ℤ} (h : int.gcd m n = 1) (hm : m % 2 = 1) (hn : n % 2 = 1) : 2 ∣ m ^ 2 + n ^ 2 ∧ 2 ∣ m ^ 2 - n ^ 2 ∧ ((m ^ 2 - n ^ 2) / 2) % 2 = 0 ∧ int.gcd ((m ^ 2 - n ^ 2) / 2) ((m ^ 2 + n ^ 2) / 2) = 1 := begin cases exists_eq_mul_left_of_dvd (int.dvd_sub_of_mod_eq hm) with m0 hm2, cases exists_eq_mul_left_of_dvd (int.dvd_sub_of_mod_eq hn) with n0 hn2, rw sub_eq_iff_eq_add at hm2 hn2, subst m, subst n, have h1 : (m0 * 2 + 1) ^ 2 + (n0 * 2 + 1) ^ 2 = 2 * (2 * (m0 ^ 2 + n0 ^ 2 + m0 + n0) + 1), by ring_exp, have h2 : (m0 * 2 + 1) ^ 2 - (n0 * 2 + 1) ^ 2 = 2 * (2 * (m0 ^ 2 - n0 ^ 2 + m0 - n0)), by ring_exp, have h3 : ((m0 * 2 + 1) ^ 2 - (n0 * 2 + 1) ^ 2) / 2 % 2 = 0, { rw [h2, int.mul_div_cancel_left, int.mul_mod_right], exact dec_trivial }, refine ⟨⟨_, h1⟩, ⟨_, h2⟩, h3, _⟩, have h20 : (2:ℤ) ≠ 0 := dec_trivial, rw [h1, h2, int.mul_div_cancel_left _ h20, int.mul_div_cancel_left _ h20], by_contra h4, obtain ⟨p, hp, hp1, hp2⟩ := nat.prime.not_coprime_iff_dvd.mp h4, apply hp.not_dvd_one, rw ← h, rw ← int.coe_nat_dvd_left at hp1 hp2, apply nat.dvd_gcd, { apply int.prime.dvd_nat_abs_of_coe_dvd_pow_two hp, convert dvd_add hp1 hp2, ring_exp }, { apply int.prime.dvd_nat_abs_of_coe_dvd_pow_two hp, convert dvd_sub hp2 hp1, ring_exp }, end namespace pythagorean_triple variables {x y z : ℤ} (h : pythagorean_triple x y z) include h lemma is_primitive_classified_aux (hc : x.gcd y = 1) (hzpos : 0 < z) {m n : ℤ} (hm2n2 : 0 < m ^ 2 + n ^ 2) (hv2 : (x : ℚ) / z = 2 * m * n / (m ^ 2 + n ^ 2)) (hw2 : (y : ℚ) / z = (m ^ 2 - n ^ 2) / (m ^ 2 + n ^ 2)) (H : int.gcd (m ^ 2 - n ^ 2) (m ^ 2 + n ^ 2) = 1) (co : int.gcd m n = 1) (pp : (m % 2 = 0 ∧ n % 2 = 1) ∨ (m % 2 = 1 ∧ n % 2 = 0)): h.is_primitive_classified := begin have hz : z ≠ 0, apply ne_of_gt hzpos, have h2 : y = m ^ 2 - n ^ 2 ∧ z = m ^ 2 + n ^ 2, { apply rat.div_int_inj hzpos hm2n2 (h.coprime_of_coprime hc) H, rw [hw2], norm_cast }, use [m, n], apply and.intro _ (and.intro co pp), right, refine ⟨_, h2.left⟩, rw [← rat.coe_int_inj _ _, ← div_left_inj' ((mt (rat.coe_int_inj z 0).mp) hz), hv2, h2.right], norm_cast end theorem is_primitive_classified_of_coprime_of_odd_of_pos (hc : int.gcd x y = 1) (hyo : y % 2 = 1) (hzpos : 0 < z) : h.is_primitive_classified := begin by_cases h0 : x = 0, { exact h.is_primitive_classified_of_coprime_of_zero_left hc h0 }, let v := (x : ℚ) / z, let w := (y : ℚ) / z, have hz : z ≠ 0, apply ne_of_gt hzpos, have hq : v ^ 2 + w ^ 2 = 1, { field_simp [hz, pow_two], norm_cast, exact h }, have hvz : v ≠ 0, { field_simp [hz], exact h0 }, have hw1 : w ≠ -1, { contrapose! hvz with hw1, rw [hw1, neg_square, one_pow, add_left_eq_self] at hq, exact pow_eq_zero hq, }, have hQ : ∀ x : ℚ, 1 + x^2 ≠ 0, { intro q, apply ne_of_gt, exact lt_add_of_pos_of_le zero_lt_one (pow_two_nonneg q) }, have hp : (⟨v, w⟩ : ℚ × ℚ) ∈ {p : ℚ × ℚ | p.1^2 + p.2^2 = 1 ∧ p.2 ≠ -1} := ⟨hq, hw1⟩, let q := (circle_equiv_gen hQ).symm ⟨⟨v, w⟩, hp⟩, have ht4 : v = 2 * q / (1 + q ^ 2) ∧ w = (1 - q ^ 2) / (1 + q ^ 2), { apply prod.mk.inj, have := ((circle_equiv_gen hQ).apply_symm_apply ⟨⟨v, w⟩, hp⟩).symm, exact congr_arg subtype.val this, }, let m := (q.denom : ℤ), let n := q.num, have hm0 : m ≠ 0, { norm_cast, apply rat.denom_ne_zero q }, have hq2 : q = n / m, { rw [int.cast_coe_nat], exact (rat.cast_id q).symm }, have hm2n2 : 0 < m ^ 2 + n ^ 2, { apply lt_add_of_pos_of_le _ (pow_two_nonneg n), exact lt_of_le_of_ne (pow_two_nonneg m) (ne.symm (pow_ne_zero 2 hm0)) }, have hw2 : w = (m ^ 2 - n ^ 2) / (m ^ 2 + n ^ 2), { rw [ht4.2, hq2], field_simp [hm2n2, (rat.denom_ne_zero q)] }, have hm2n20 : (m : ℚ) ^ 2 + (n : ℚ) ^ 2 ≠ 0, { norm_cast, simpa only [int.coe_nat_pow] using ne_of_gt hm2n2 }, have hv2 : v = 2 * m * n / (m ^ 2 + n ^ 2), { apply eq.symm, apply (div_eq_iff hm2n20).mpr, rw [ht4.1], field_simp [hQ q], rw [hq2] {occs := occurrences.pos [2, 3]}, field_simp [rat.denom_ne_zero q], ring }, have hnmcp : int.gcd n m = 1 := q.cop, have hmncp : int.gcd m n = 1, { rw int.gcd_comm, exact hnmcp }, cases int.mod_two_eq_zero_or_one m with hm2 hm2; cases int.mod_two_eq_zero_or_one n with hn2 hn2, { -- m even, n even exfalso, have h1 : 2 ∣ (int.gcd n m : ℤ), { exact int.dvd_gcd (int.dvd_of_mod_eq_zero hn2) (int.dvd_of_mod_eq_zero hm2) }, rw hnmcp at h1, revert h1, norm_num }, { -- m even, n odd apply h.is_primitive_classified_aux hc hzpos hm2n2 hv2 hw2 _ hmncp, { apply or.intro_left, exact and.intro hm2 hn2 }, { apply coprime_pow_two_sub_pow_two_add_of_even_odd hmncp hm2 hn2 } }, { -- m odd, n even apply h.is_primitive_classified_aux hc hzpos hm2n2 hv2 hw2 _ hmncp, { apply or.intro_right, exact and.intro hm2 hn2 }, apply coprime_pow_two_sub_pow_two_add_of_odd_even hmncp hm2 hn2 }, { -- m odd, n odd exfalso, have h1 : 2 ∣ m ^ 2 + n ^ 2 ∧ 2 ∣ m ^ 2 - n ^ 2 ∧ ((m ^ 2 - n ^ 2) / 2) % 2 = 0 ∧ int.gcd ((m ^ 2 - n ^ 2) / 2) ((m ^ 2 + n ^ 2) / 2) = 1, { exact coprime_pow_two_sub_pow_two_sum_of_odd_odd hmncp hm2 hn2 }, have h2 : y = (m ^ 2 - n ^ 2) / 2 ∧ z = (m ^ 2 + n ^ 2) / 2, { apply rat.div_int_inj hzpos _ (h.coprime_of_coprime hc) h1.2.2.2, { show w = _, rw [←rat.mk_eq_div, ←(rat.div_mk_div_cancel_left (by norm_num : (2 : ℤ) ≠ 0))], rw [int.div_mul_cancel h1.1, int.div_mul_cancel h1.2.1, hw2], norm_cast }, { apply (mul_lt_mul_right (by norm_num : 0 < (2 : ℤ))).mp, rw [int.div_mul_cancel h1.1, zero_mul], exact hm2n2 } }, rw [h2.1, h1.2.2.1] at hyo, revert hyo, norm_num } end theorem is_primitive_classified_of_coprime_of_pos (hc : int.gcd x y = 1) (hzpos : 0 < z): h.is_primitive_classified := begin cases h.even_odd_of_coprime hc with h1 h2, { exact (h.is_primitive_classified_of_coprime_of_odd_of_pos hc h1.right hzpos) }, rw int.gcd_comm at hc, obtain ⟨m, n, H⟩ := (h.symm.is_primitive_classified_of_coprime_of_odd_of_pos hc h2.left hzpos), use [m, n], tauto end theorem is_primitive_classified_of_coprime (hc : int.gcd x y = 1) : h.is_primitive_classified := begin by_cases hz : 0 < z, { exact h.is_primitive_classified_of_coprime_of_pos hc hz }, have h' : pythagorean_triple x y (-z), { simpa [pythagorean_triple, neg_mul_neg] using h.eq, }, apply h'.is_primitive_classified_of_coprime_of_pos hc, apply lt_of_le_of_ne _ (h'.ne_zero_of_coprime hc).symm, exact le_neg.mp (not_lt.mp hz) end theorem classified : h.is_classified := begin by_cases h0 : int.gcd x y = 0, { have hx : x = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_left h0 }, have hy : y = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_right h0 }, use [0, 1, 0], norm_num [hx, hy], }, apply h.is_classified_of_normalize_is_primitive_classified, apply h.normalize.is_primitive_classified_of_coprime, apply int.gcd_div_gcd_div_gcd (nat.pos_of_ne_zero h0), end omit h theorem coprime_classification : pythagorean_triple x y z ∧ int.gcd x y = 1 ↔ ∃ m n, ((x = m ^ 2 - n ^ 2 ∧ y = 2 * m * n) ∨ (x = 2 * m * n ∧ y = m ^ 2 - n ^ 2)) ∧ (z = m ^ 2 + n ^ 2 ∨ z = - (m ^ 2 + n ^ 2)) ∧ int.gcd m n = 1 ∧ ((m % 2 = 0 ∧ n % 2 = 1) ∨ (m % 2 = 1 ∧ n % 2 = 0)) := begin split, { intro h, obtain ⟨m, n, H⟩ := h.left.is_primitive_classified_of_coprime h.right, use [m, n], rcases H with ⟨⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, co, pp⟩, { refine ⟨or.inl ⟨rfl, rfl⟩, _, co, pp⟩, have : z ^ 2 = (m ^ 2 + n ^ 2) ^ 2, { rw [pow_two, ← h.left.eq], ring }, simpa using eq_or_eq_neg_of_pow_two_eq_pow_two _ _ this }, { refine ⟨or.inr ⟨rfl, rfl⟩, _, co, pp⟩, have : z ^ 2 = (m ^ 2 + n ^ 2) ^ 2, { rw [pow_two, ← h.left.eq], ring }, simpa using eq_or_eq_neg_of_pow_two_eq_pow_two _ _ this } }, { delta pythagorean_triple, rintro ⟨m, n, ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, rfl | rfl, co, pp⟩; { split, { ring }, exact coprime_pow_two_sub_mul co pp } <|> { split, { ring }, rw int.gcd_comm, exact coprime_pow_two_sub_mul co pp } } end /-- by assuming `x` is odd and `z` is positive we get a slightly more precise classification of the pythagorean triple `x ^ 2 + y ^ 2 = z ^ 2`-/ theorem coprime_classification' {x y z : ℤ} (h : pythagorean_triple x y z) (h_coprime : int.gcd x y = 1) (h_parity : x % 2 = 1) (h_pos : 0 < z) : ∃ m n, x = m ^ 2 - n ^ 2 ∧ y = 2 * m * n ∧ z = m ^ 2 + n ^ 2 ∧ int.gcd m n = 1 ∧ ((m % 2 = 0 ∧ n % 2 = 1) ∨ (m % 2 = 1 ∧ n % 2 = 0)) ∧ 0 ≤ m := begin obtain ⟨m, n, ht1, ht2, ht3, ht4⟩ := pythagorean_triple.coprime_classification.mp (and.intro h h_coprime), cases le_or_lt 0 m with hm hm, { use [m, n], cases ht1 with h_odd h_even, { apply and.intro h_odd.1, apply and.intro h_odd.2, cases ht2 with h_pos h_neg, { apply and.intro h_pos (and.intro ht3 (and.intro ht4 hm)) }, { exfalso, revert h_pos, rw h_neg, exact imp_false.mpr (not_lt.mpr (neg_nonpos.mpr (add_nonneg (pow_two_nonneg m) (pow_two_nonneg n)))) } }, exfalso, rcases h_even with ⟨rfl, -⟩, rw [mul_assoc, int.mul_mod_right] at h_parity, exact zero_ne_one h_parity }, { use [-m, -n], cases ht1 with h_odd h_even, { rw [neg_square m], rw [neg_square n], apply and.intro h_odd.1, split, { rw h_odd.2, ring }, cases ht2 with h_pos h_neg, { apply and.intro h_pos, split, { delta int.gcd, rw [int.nat_abs_neg, int.nat_abs_neg], exact ht3 }, { rw [int.neg_mod_two, int.neg_mod_two], apply and.intro ht4, linarith } }, { exfalso, revert h_pos, rw h_neg, exact imp_false.mpr (not_lt.mpr (neg_nonpos.mpr (add_nonneg (pow_two_nonneg m) (pow_two_nonneg n)))) } }, exfalso, rcases h_even with ⟨rfl, -⟩, rw [mul_assoc, int.mul_mod_right] at h_parity, exact zero_ne_one h_parity } end theorem classification : pythagorean_triple x y z ↔ ∃ k m n, ((x = k * (m ^ 2 - n ^ 2) ∧ y = k * (2 * m * n)) ∨ (x = k * (2 * m * n) ∧ y = k * (m ^ 2 - n ^ 2))) ∧ (z = k * (m ^ 2 + n ^ 2) ∨ z = - k * (m ^ 2 + n ^ 2)) := begin split, { intro h, obtain ⟨k, m, n, H⟩ := h.classified, use [k, m, n], rcases H with ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, { refine ⟨or.inl ⟨rfl, rfl⟩, _⟩, have : z ^ 2 = (k * (m ^ 2 + n ^ 2)) ^ 2, { rw [pow_two, ← h.eq], ring }, simpa using eq_or_eq_neg_of_pow_two_eq_pow_two _ _ this }, { refine ⟨or.inr ⟨rfl, rfl⟩, _⟩, have : z ^ 2 = (k * (m ^ 2 + n ^ 2)) ^ 2, { rw [pow_two, ← h.eq], ring }, simpa using eq_or_eq_neg_of_pow_two_eq_pow_two _ _ this } }, { rintro ⟨k, m, n, ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, rfl | rfl⟩; delta pythagorean_triple; ring } end end pythagorean_triple
8983dbe863d9b7e677c67a64b801a79409509183
9dc8cecdf3c4634764a18254e94d43da07142918
/src/measure_theory/integral/interval_average.lean
635fb91aefdba7150481216f3f8756b2c3cff63b
[ "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
1,987
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 analysis.convex.integral import measure_theory.integral.interval_integral /-! # Integral average over an interval In this file we introduce notation `⨍ x in a..b, f x` for the average `⨍ x in Ι a b, f x` of `f` over the interval `Ι a b = set.Ioc (min a b) (max a b)` w.r.t. the Lebesgue measure, then prove formulas for this average: * `interval_average_eq`: `⨍ x in a..b, f x = (b - a)⁻¹ • ∫ x in a..b, f x`; * `interval_average_eq_div`: `⨍ x in a..b, f x = (∫ x in a..b, f x) / (b - a)`. We also prove that `⨍ x in a..b, f x = ⨍ x in b..a, f x`, see `interval_average_symm`. ## Notation `⨍ x in a..b, f x`: average of `f` over the interval `Ι a b` w.r.t. the Lebesgue measure. -/ open measure_theory set topological_space open_locale interval variables {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [complete_space E] notation `⨍` binders ` in ` a `..` b `, ` r:(scoped:60 f, average (measure.restrict volume (Ι a b)) f) := r lemma interval_average_symm (f : ℝ → E) (a b : ℝ) : ⨍ x in a..b, f x = ⨍ x in b..a, f x := by rw [set_average_eq, set_average_eq, interval_oc_swap] lemma interval_average_eq (f : ℝ → E) (a b : ℝ) : ⨍ x in a..b, f x = (b - a)⁻¹ • ∫ x in a..b, f x := begin cases le_or_lt a b with h h, { rw [set_average_eq, interval_oc_of_le h, real.volume_Ioc, interval_integral.integral_of_le h, ennreal.to_real_of_real (sub_nonneg.2 h)] }, { rw [set_average_eq, interval_oc_of_lt h, real.volume_Ioc, interval_integral.integral_of_ge h.le, ennreal.to_real_of_real (sub_nonneg.2 h.le), smul_neg, ← neg_smul, ← inv_neg, neg_sub] } end lemma interval_average_eq_div (f : ℝ → ℝ) (a b : ℝ) : ⨍ x in a..b, f x = (∫ x in a..b, f x) / (b - a) := by rw [interval_average_eq, smul_eq_mul, div_eq_inv_mul]
ce8a7c2c9409098fa53c4506cc9b1a814d5725b2
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/tests/lean/run/newfrontend1.lean
5e4c3a1af9d94167296910ff29229f0939f116b2
[ "Apache-2.0" ]
permissive
dupuisf/lean4
d082d13b01243e1de29ae680eefb476961221eef
6a39c65bd28eb0e28c3870188f348c8914502718
refs/heads/master
1,676,948,755,391
1,610,665,114,000
1,610,665,114,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,777
lean
def x := 1 #check x variables {α : Type} def f (a : α) : α := a def tst (xs : List Nat) : Nat := xs.foldl (init := 10) (· + ·) #check tst [1, 2, 3] #check fun x y : Nat => x + y #check tst #check (fun stx => if True then let e := stx; Pure.pure e else Pure.pure stx : Nat → Id Nat) #check let x : Nat := 1; x def foo (a : Nat) (b : Nat := 10) (c : Bool := Bool.true) : Nat := a + b set_option pp.all true #check foo 1 #check foo 3 (c := false) def Nat.boo (a : Nat) := succ a -- succ here is resolved as `Nat.succ`. #check Nat.boo #check true -- apply is still a valid identifier name def apply := "hello" #check apply theorem simple1 (x y : Nat) (h : x = y) : x = y := by { assumption } theorem simple2 (x y : Nat) : x = y → x = y := by { intro h; assumption } syntax "intro2" : tactic macro_rules | `(tactic| intro2) => `(tactic| intro; intro ) theorem simple3 (x y : Nat) : x = x → x = y → x = y := by { intro2; assumption } macro "intro3" : tactic => `(intro; intro; intro) macro "check2" x:term : command => `(#check $x #check $x) macro "foo" x:term "," y:term : term => `($x + $y + $x) set_option pp.all false check2 0+1 check2 foo 0,1 theorem simple4 (x y : Nat) : y = y → x = x → x = y → x = y := by { intro3; assumption } theorem simple5 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intro h1; intro _; intro h3; exact Eq.trans h3 h1 } theorem simple6 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intro h1; intro _; intro h3; refine Eq.trans ?_ h1; assumption } theorem simple7 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intro h1; intro _; intro h3; refine! Eq.trans ?pre ?post; exact y; { exact h3 } { exact h1 } } theorem simple8 (x y z : Nat) : y = z → x = x → x = y → x = z := by intro h1; intro _; intro h3 refine! Eq.trans ?pre ?post case post => exact h1 case pre => exact h3 theorem simple9 (x y z : Nat) : y = z → x = x → x = y → x = z := by intros h1 _ h3 traceState focus refine! Eq.trans ?pre ?post first | exact h1 assumption | exact y exact h3 assumption theorem simple9b (x y z : Nat) : y = z → x = x → x = y → x = z := by intros h1 _ h3 traceState focus refine! Eq.trans ?pre ?post first | exact h1 | exact y; exact h3 assumption theorem simple9c (x y z : Nat) : y = z → x = x → x = y → x = z := by intros h1 _ h3 solve | exact h1 | refine! Eq.trans ?pre ?post; exact y; exact h3; assumption | exact h3 theorem simple9d (x y z : Nat) : y = z → x = x → x = y → x = z := by intros h1 _ h3 refine! Eq.trans ?pre ?post solve | exact h1 | exact y | exact h3 solve | exact h1 | exact h3 solve | exact h1 | assumption namespace Foo def Prod.mk := 1 #check (⟨2, 3⟩ : Prod _ _) end Foo theorem simple10 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intro h1; intro h2; intro h3; skip; apply Eq.trans; exact h3; assumption } theorem simple11 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intro h1; intro h2; intro h3; apply @Eq.trans; traceState; exact h3; assumption } theorem simple12 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intro h1; intro h2; intro h3; apply @Eq.trans; try exact h1; -- `exact h1` fails traceState; try exact h3; traceState; try exact h1; } theorem simple13 (x y z : Nat) : y = z → x = x → x = y → x = z := by intros h1 h2 h3 traceState apply @Eq.trans case b => exact y traceState repeat assumption theorem simple13b (x y z : Nat) : y = z → x = x → x = y → x = z := by { intros h1 h2 h3; traceState; apply @Eq.trans; case b => exact y; traceState; repeat assumption } theorem simple14 (x y z : Nat) : y = z → x = x → x = y → x = z := by intros apply @Eq.trans case b => exact y repeat assumption theorem simple15 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intros h1 h2 h3; revert y; intros y h1 h3; apply Eq.trans; exact h3; exact h1 } theorem simple16 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intros h1 h2 h3; try clear x; -- should fail clear h2; traceState; apply Eq.trans; exact h3; exact h1 } macro "blabla" : tactic => `(assumption) -- Tactic head symbols do not become reserved words def blabla := 100 #check blabla theorem simple17 (x : Nat) (h : x = 0) : x = 0 := by blabla theorem simple18 (x : Nat) (h : x = 0) : x = 0 := by blabla theorem simple19 (x y : Nat) (h₁ : x = 0) (h₂ : x = y) : y = 0 := by subst x; subst y; exact rfl theorem tstprec1 (x y z : Nat) : x + y * z = x + (y * z) := rfl theorem tstprec2 (x y z : Nat) : y * z + x = (y * z) + x := rfl set_option pp.all true #check fun {α} (a : α) => a #check @(fun α (a : α) => a) #check let myid := fun {α} (a : α) => a; myid [myid 1] -- In the following example, we need `@` otherwise we will try to insert mvars for α and [Add α], -- and will fail to generate instance for [Add α] #check @(fun α (s : Add α) (a : α) => a + a) def g1 {α} (a₁ a₂ : α) {β} (b : β) : α × α × β := (a₁, a₂, b) def id1 : {α : Type} → α → α := fun x => x def listId : List ({α : Type} → α → α) := (fun x => x) :: [] def id2 : {α : Type} → α → α := @(fun α (x : α) => id1 x) def id3 : {α : Type} → α → α := @(fun α x => id1 x) def id4 : {α : Type} → α → α := fun x => id1 x def id5 : {α : Type} → α → α := fun {α} x => id1 x def id6 : {α : Type} → α → α := @(fun {α} x => id1 x) def id7 : {α : Type} → α → α := fun {α} x => @id α x def id8 : {α : Type} → α → α := fun {α} x => id (@id α x) def altTst1 {m σ} [Alternative m] [Monad m] : Alternative (StateT σ m) := ⟨StateT.failure, StateT.orElse⟩ def altTst2 {m σ} [Alternative m] [Monad m] : Alternative (StateT σ m) := ⟨@(fun α => StateT.failure), @(fun α => StateT.orElse)⟩ def altTst3 {m σ} [Alternative m] [Monad m] : Alternative (StateT σ m) := ⟨fun {α} => StateT.failure, fun {α} => StateT.orElse⟩ #check_failure 1 + true /- universes u v /- MonadFunctorT.{u ?M_1 v} (λ (β : Type u), m α) (λ (β : Type u), m' α) n n' -/ set_option pp.raw.maxDepth 100 set_option trace.Elab true def adapt {m m' σ σ'} {n n' : Type → Type} [MonadFunctor m m' n n'] [MonadStateAdapter σ σ' m m'] : MonadStateAdapter σ σ' n n' := ⟨fun split join => monadMap (adaptState split join : m α → m' α)⟩ -/ syntax "fn" (term:max)+ "=>" term : term macro_rules | `(fn $xs* => $b) => `(fun $xs* => $b) set_option pp.all false #check fn x => x+1 #check fn α (a : α) => a def tst1 : {α : Type} → α → α := @(fn α a => a) #check @tst1 syntax ident "==>" term : term syntax "{" ident "}" "==>" term : term macro_rules | `($x:ident ==> $b) => `(fn $x => $b) | `({$x:ident} ==> $b) => `(fun {$x:ident} => $b) #check x ==> x+1 def tst2a : {α : Type} → α → α := @(α ==> a ==> a) def tst2b : {α : Type} → α → α := {α} ==> a ==> a #check @tst2a #check @tst2b def tst3a : {α : Type} → {β : Type} → α → β → α × β := @(α ==> @(β ==> a ==> b ==> (a, b))) def tst3b : {α : Type} → {β : Type} → α → β → α × β := {α} ==> {β} ==> a ==> b ==> (a, b) syntax "function" (term:max)+ "=>" term : term macro_rules | `(function $xs* => $b) => `(@(fun $xs* => $b)) def tst4 : {α : Type} → {β : Type} → α → β → α × β := function α β a b => (a, b) theorem simple20 (x y z : Nat) : y = z → x = x → x = y → x = z := by intros h1 h2 h3; try clear x; -- should fail clear h2; traceState; apply Eq.trans; exact h3; exact h1 theorem simple21 (x y z : Nat) : y = z → x = x → y = x → x = z := fun h1 _ h3 => have x = y from by { apply Eq.symm; assumption }; Eq.trans this (by assumption) theorem simple22 (x y z : Nat) : y = z → y = x → id (x = z + 0) := fun h1 h2 => show x = z + 0 by apply Eq.trans exact h2.symm assumption skip theorem simple23 (x y z : Nat) : y = z → x = x → y = x → x = z := fun h1 _ h3 => have x = y by apply Eq.symm; assumption Eq.trans this (by assumption) theorem simple24 (x y z : Nat) : y = z → x = x → y = x → x = z := fun h1 _ h3 => have h : x = y by apply Eq.symm; assumption Eq.trans h (by assumption) def f1 (x : Nat) : Nat := let double x := x + x let rec loop x := match x with | 0 => 0 | x+1 => loop x + double x loop x #eval f1 5 def f2 (x : Nat) : String := let bad x : String := toString x bad x def f3 x y := x + y + 1 theorem f3eq x y : f3 x y = x + y + 1 := rfl def f4 (x y : Nat) : String := if x > y + 1 then "hello" else "world"
817690ad0843585ce39e5c7ba37966e0881fdcc5
38aa1f7792ba7c73b43619c5d089e15d69cd32eb
/sokoban.lean
2bfdc27620d97c341b2ba9184f2fd3bb604fbc5b
[]
no_license
mirefek/my-lean-experiments
f8ec3efa4013285b80cd45c219a7bc8b6294b8cc
1218fecbf568669ac123256d430a151a900f67b3
refs/heads/master
1,679,449,694,211
1,616,190,468,000
1,616,190,468,000
154,370,734
1
0
null
null
null
null
UTF-8
Lean
false
false
7,475
lean
import tactic import data.list.func universe u def list2d (α : Type u) := list (list α) namespace list2d open list.func variables {α : Type} {β : Type} variables [inhabited α] [inhabited β] @[simp] def get2d (xy : ℕ × ℕ) (l : list2d α) : α := let (x,y) := xy in get x (get y l) @[simp] def set2d (a : α) (l : list2d α) (xy : ℕ × ℕ) : list2d α := let (x,y) := xy in set (set a (get y l) x) l y @[simp] def dfzip2d (l1 : list2d α) (l2 : list2d β) : list2d (α × β) := (pointwise (pointwise prod.mk) l1 l2) @[simp] def add_to_line1 (a : α) : list2d α -> list2d α | [] := [[a]] | (h::t) := (a::h)::t @[simp] def transpose : list2d α → list2d α := (list.foldr (pointwise list.cons)) [] instance [has_repr α] : has_repr (list2d α) := ⟨λ l, list.repr (l : list (list α))⟩ #eval transpose [[1, 2], [3, 4, 5], [6]] end list2d inductive direction : Type | up | down | left | right namespace direction def opposite : direction -> direction | up := down | down := up | left := right | right := left def shift : direction -> (ℕ × ℕ) -> option (ℕ × ℕ) | up (_, 0) := none | up (x, y+1) := some (x, y) | down (x, y) := some (x, y+1) | left (0, _) := none | left (x+1, y) := some (x, y) | right (x, y) := some (x+1, y) end direction structure sokoban := (available : list2d bool) (boxes : list2d bool) (storages : list2d bool) (storekeeper : ℕ × ℕ) namespace sokoban open list2d instance : inhabited sokoban := ⟨{ available := [[tt]], boxes := [], storages := [], storekeeper := (0,0) }⟩ def move (d : direction) (s : sokoban) : sokoban := match (d.shift s.storekeeper) with none := s | some sk2 := if get2d sk2 s.available = false then s else if get2d sk2 s.boxes = false then { storekeeper := sk2, ..s} else match (d.shift sk2) with none := s | some box2 := if (get2d box2 s.available = false) ∨ (get2d box2 s.boxes = true) then s else { boxes := (s.boxes.set2d ff sk2).set2d tt box2, storekeeper := sk2, ..s } end end def move_up := move direction.up def move_down := move direction.down def move_left := move direction.left def move_right := move direction.right def add_newline (s : sokoban) : sokoban := { available := []::s.available, boxes := []::s.boxes, storages := []::s.storages, storekeeper := match s.storekeeper with (x,y) := (x,y+1) end } def add_newsquare (av box stor sk : bool) (s : sokoban) : sokoban := { available := add_to_line1 av s.available, boxes := add_to_line1 box s.boxes, storages := add_to_line1 stor s.storages, storekeeper := if sk then (0, 0) else match s.storekeeper with | (x,0) := (x+1,0) | xy := xy end } def from_string_aux : list char → option (sokoban × bool) | [] := some (sokoban.mk [] [] [] (0,0), ff) | (c::str) := match (from_string_aux str), c with | none, _ := none | (some (s, sk_set)), '\n' := some (add_newline s, sk_set) | (some (s, sk_set)), ' ' := some (add_newsquare tt ff ff ff s, sk_set) | (some (s, sk_set)), '#' := some (add_newsquare ff ff ff ff s, sk_set) | (some (s, sk_set)), '.' := some (add_newsquare tt ff tt ff s, sk_set) | (some (s, sk_set)), '$' := some (add_newsquare tt tt ff ff s, sk_set) | (some (s, sk_set)), '*' := some (add_newsquare tt tt tt ff s, sk_set) | (some (s, ff)), '@' := some (add_newsquare tt ff ff tt s, tt) | (some (s, ff)), '+' := some (add_newsquare tt ff tt tt s, tt) | (some _), _ := none end def from_string (str : string) : sokoban := match (from_string_aux str.to_list) with | none := default sokoban | some (_, ff) := default sokoban | some (level, tt) := level end def square_to_char : bool → bool → bool → bool → char | tt ff ff ff := ' ' | ff ff ff ff := '#' | tt ff tt ff := '.' | tt tt ff ff := '$' | tt tt tt ff := '*' | tt ff ff tt := '@' | tt ff tt tt := '+' | _ _ _ _ := '?' def to_string_aux1 (str : list char) : list (bool × bool × bool × bool) → list char | [] := str | ((av,box,stor,sk)::t) := (square_to_char av box stor sk)::(to_string_aux1 t) def to_string_aux2 : list2d (bool × bool × bool × bool) → list char | [] := [] | (h::t) := to_string_aux1 ('\n'::(to_string_aux2 t)) h instance : has_to_string sokoban := ⟨λ s, list.as_string (to_string_aux2 (dfzip2d s.available (dfzip2d s.boxes (dfzip2d s.storages (set2d true [] s.storekeeper))))) ⟩ instance : has_repr sokoban := ⟨λ s, (string.append (string.append "sokoban.from_string \"" (to_string s)) "\"")⟩ inductive solvable : sokoban -> Prop | solved (s : sokoban) (H : s.boxes = s.storages) : solvable s | move (d : direction) (s : sokoban) (H : solvable (s.move d)) : solvable s def solvable.move_up := solvable.move direction.up def solvable.move_down := solvable.move direction.down def solvable.move_left := solvable.move direction.left def solvable.move_right := solvable.move direction.right meta def soko_simp_root (e : expr) : tactic unit := do soko ← tactic.eval_expr sokoban e, tactic.trace (to_string soko), let p : pexpr := ``(%%e = sokoban.mk %%soko.available %%soko.boxes %%soko.storages %%soko.storekeeper), eq ← tactic.to_expr p, name ← tactic.get_unused_name, H ← tactic.assert name eq, tactic.reflexivity, tactic.rewrite_target H, tactic.clear H meta def soko_simp_expr : expr → tactic unit := assume e : expr, soko_simp_root e <|> match e with | expr.app e1 e2 := soko_simp_expr e1 >> soko_simp_expr e2 | _ := return () end meta def soko_simp : tactic unit := do goal ← tactic.target, soko_simp_expr goal #check tactic.apply meta def solve_up : tactic unit := tactic.apply `(solvable.move_up) >> soko_simp meta def solve_down : tactic unit := tactic.apply `(solvable.move_down) >> soko_simp meta def solve_left : tactic unit := tactic.apply `(solvable.move_left) >> soko_simp meta def solve_right : tactic unit := tactic.apply `(solvable.move_right) >> soko_simp meta def solve_finish : tactic unit := tactic.apply `(sokoban.solvable.solved) >> tactic.reflexivity end sokoban def soko_level := sokoban.from_string " ####### #. . .# # $$$ # #.$@$.# # $$$ # #. . .# ####### " example : soko_level.solvable := begin sokoban.soko_simp, sokoban.solve_up, sokoban.solve_left, sokoban.solve_right, sokoban.solve_right, sokoban.solve_left, sokoban.solve_down, sokoban.solve_down, sokoban.solve_left, sokoban.solve_right, sokoban.solve_right, sokoban.solve_up, sokoban.solve_right, sokoban.solve_up, sokoban.solve_down, sokoban.solve_left, sokoban.solve_left, sokoban.solve_up, sokoban.solve_left, sokoban.solve_down, sokoban.solve_left, sokoban.solve_down, sokoban.solve_right, sokoban.solve_up, sokoban.solve_up, sokoban.solve_up, sokoban.solve_left, sokoban.solve_down, sokoban.solve_right, sokoban.solve_down, sokoban.solve_right, sokoban.solve_right, sokoban.solve_right, sokoban.solve_up, sokoban.solve_left, sokoban.solve_down, sokoban.solve_down, sokoban.solve_down, sokoban.solve_right, sokoban.solve_up, sokoban.solve_left, sokoban.solve_up, sokoban.solve_up, sokoban.solve_up, sokoban.solve_left, sokoban.solve_left, sokoban.solve_down, sokoban.solve_down, sokoban.solve_down, sokoban.solve_down, sokoban.solve_right, sokoban.solve_right, sokoban.solve_up, sokoban.solve_up, sokoban.solve_left, sokoban.solve_down, sokoban.solve_up, sokoban.solve_up, sokoban.solve_finish end
ee37c3ef14d16567bbf344d0e47a7eb89c93bd23
4727251e0cd73359b15b664c3170e5d754078599
/archive/imo/imo2011_q5.lean
92d259f5d184f6175964d53c5c993a77c6d821fc
[ "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
2,094
lean
/- Copyright (c) 2021 Alain Verberkmoes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alain Verberkmoes -/ import data.int.basic /-! # IMO 2011 Q5 Let `f` be a function from the set of integers to the set of positive integers. Suppose that, for any two integers `m` and `n`, the difference `f(m) - f(n)` is divisible by `f(m - n)`. Prove that, for all integers `m` and `n` with `f(m) ≤ f(n)`, the number `f(n)` is divisible by `f(m)`. -/ open int theorem imo2011_q5 (f : ℤ → ℤ) (hpos : ∀ n : ℤ, 0 < f n) (hdvd : ∀ m n : ℤ, f (m - n) ∣ f m - f n) : ∀ m n : ℤ, f m ≤ f n → f m ∣ f n := begin intros m n h_fm_le_fn, cases lt_or_eq_of_le h_fm_le_fn with h_fm_lt_fn h_fm_eq_fn, { -- m < n let d := f m - f (m - n), have h_fn_dvd_d : f n ∣ d, { rw ←sub_sub_self m n, exact hdvd m (m - n) }, have h_d_lt_fn : d < f n, { calc d < f m : sub_lt_self _ (hpos (m - n)) ... < f n : h_fm_lt_fn }, have h_neg_d_lt_fn : -d < f n, { calc -d = f (m - n) - f m : neg_sub _ _ ... < f (m - n) : sub_lt_self _ (hpos m) ... ≤ f n - f m : le_of_dvd (sub_pos.mpr h_fm_lt_fn) _ ... < f n : sub_lt_self _ (hpos m), -- ⊢ f (m - n) ∣ f n - f m rw [←dvd_neg, neg_sub], exact hdvd m n }, have h_d_eq_zero : d = 0, { obtain (hd | hd | hd) : d > 0 ∨ d = 0 ∨ d < 0 := trichotomous d 0, { -- d > 0 have h₁ : f n ≤ d, from le_of_dvd hd h_fn_dvd_d, have h₂ : ¬ f n ≤ d, from not_le.mpr h_d_lt_fn, contradiction }, { -- d = 0 exact hd }, { -- d < 0 have h₁ : f n ≤ -d, from le_of_dvd (neg_pos.mpr hd) ((dvd_neg _ _).mpr h_fn_dvd_d), have h₂ : ¬ f n ≤ -d, from not_le.mpr h_neg_d_lt_fn, contradiction } }, have h₁ : f m = f (m - n), from sub_eq_zero.mp h_d_eq_zero, have h₂ : f (m - n) ∣ f m - f n, from hdvd m n, rw ←h₁ at h₂, exact (dvd_iff_dvd_of_dvd_sub h₂).mp dvd_rfl }, { -- m = n rw h_fm_eq_fn } end
cc6ce7a8a77f66e2e5b05ddf785cb47983fbfa09
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/tactic/simpa.lean
82f1d6140474bf7841d1c6adfbf9747fcc1b3699
[ "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
2,399
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import tactic.doc_commands namespace tactic namespace interactive open interactive interactive.types expr lean.parser local postfix `?`:9001 := optional /-- This is a "finishing" tactic modification of `simp`. It has two forms. * `simpa [rules, ...] using e` will simplify the goal and the type of `e` using `rules`, then try to close the goal using `e`. Simplifying the type of `e` makes it more likely to match the goal (which has also been simplified). This construction also tends to be more robust under changes to the simp lemma set. * `simpa [rules, ...]` will simplify the goal and the type of a hypothesis `this` if present in the context, then try to close the goal using the `assumption` tactic. -/ meta def simpa (use_iota_eqn : parse $ (tk "!")?) (trace_lemmas : parse $ (tk "?")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (tgt : parse (tk "using" *> texpr)?) (cfg : simp_config_ext := {}) : tactic unit := let simp_at lc (close_tac : tactic unit) := focus1 $ simp use_iota_eqn trace_lemmas no_dflt hs attr_names (loc.ns lc) {fail_if_unchanged := ff, ..cfg} >> (((close_tac <|> trivial) >> done) <|> fail "simpa failed") in match tgt with | none := get_local `this >> simp_at [some `this, none] assumption <|> simp_at [none] assumption | some e := focus1 $ do e ← i_to_expr e <|> do { ty ← target, -- for positional error messages, we don't care about the result e ← i_to_expr_strict ``(%%e : %%ty), pty ← pp ty, ptgt ← pp e, -- Fail deliberately, to advise regarding `simp; exact` usage fail ("simpa failed, 'using' expression type not directly " ++ "inferrable. Try:\n\nsimpa ... using\nshow " ++ to_fmt pty ++ ",\nfrom " ++ ptgt : format) }, match e with | local_const _ lc _ _ := simp_at [some lc, none] (get_local lc >>= tactic.exact) | e := do t ← infer_type e, assertv `this t e, simp_at [some `this, none] (get_local `this >>= tactic.exact), all_goals (try apply_instance) end end add_tactic_doc { name := "simpa", category := doc_category.tactic, decl_names := [`tactic.interactive.simpa], tags := ["simplification"] } end interactive end tactic
3930c1f9a4e887f062af211e101d88808329962f
618003631150032a5676f229d13a079ac875ff77
/src/category_theory/monad/basic.lean
0f5c9b32929b36b14a99829eaca8c519989d2943
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
2,109
lean
/- Copyright (c) 2019 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.functor_category namespace category_theory open category universes v₁ u₁ -- declare the `v`'s first; see `category_theory.category` for an explanation variables {C : Type u₁} [category.{v₁} C] /-- The data of a monad on C consists of an endofunctor T together with natural transformations η : 𝟭 C ⟶ T and μ : T ⋙ T ⟶ T satisfying three equations: - T μ_X ≫ μ_X = μ_(TX) ≫ μ_X (associativity) - η_(TX) ≫ μ_X = 1_X (left unit) - Tη_X ≫ μ_X = 1_X (right unit) -/ class monad (T : C ⥤ C) := (η [] : 𝟭 _ ⟶ T) (μ [] : T ⋙ T ⟶ T) (assoc' : ∀ X : C, T.map (nat_trans.app μ X) ≫ μ.app _ = μ.app (T.obj X) ≫ μ.app _ . obviously) (left_unit' : ∀ X : C, η.app (T.obj X) ≫ μ.app _ = 𝟙 _ . obviously) (right_unit' : ∀ X : C, T.map (η.app X) ≫ μ.app _ = 𝟙 _ . obviously) restate_axiom monad.assoc' restate_axiom monad.left_unit' restate_axiom monad.right_unit' attribute [simp] monad.left_unit monad.right_unit notation `η_` := monad.η notation `μ_` := monad.μ /-- The data of a comonad on C consists of an endofunctor G together with natural transformations ε : G ⟶ 𝟭 C and δ : G ⟶ G ⋙ G satisfying three equations: - δ_X ≫ G δ_X = δ_X ≫ δ_(GX) (coassociativity) - δ_X ≫ ε_(GX) = 1_X (left counit) - δ_X ≫ G ε_X = 1_X (right counit) -/ class comonad (G : C ⥤ C) := (ε [] : G ⟶ 𝟭 _) (δ [] : G ⟶ (G ⋙ G)) (coassoc' : ∀ X : C, nat_trans.app δ _ ≫ G.map (δ.app X) = δ.app _ ≫ δ.app _ . obviously) (left_counit' : ∀ X : C, δ.app X ≫ ε.app (G.obj X) = 𝟙 _ . obviously) (right_counit' : ∀ X : C, δ.app X ≫ G.map (ε.app X) = 𝟙 _ . obviously) restate_axiom comonad.coassoc' restate_axiom comonad.left_counit' restate_axiom comonad.right_counit' attribute [simp] comonad.left_counit comonad.right_counit notation `ε_` := comonad.ε notation `δ_` := comonad.δ end category_theory
58cf7242f50fe7ce31555441a18f5e865fe9a9c8
7b89826c26634aa18c0110f1634f73027851edfe
/natural-number-game/src/main.lean
c0fd1a4770afe71fc9f4b2247e1e88964cb799d4
[ "MIT" ]
permissive
marcofavorito/leanings
b7642344d8c9012a1cec74a804c5884297880c4d
581b83be66ff4f8dd946fb6a1bb045d2ddf91076
refs/heads/master
1,672,310,991,244
1,603,031,766,000
1,603,031,766,000
279,163,004
1
0
null
null
null
null
UTF-8
Lean
false
false
307
lean
import mynat.definition -- imports the natural numbers {0,1,2,3,4,...}. import mynat.add -- imports definition of addition on the natural numbers. import mynat.mul -- imports definition of multiplication on the natural numbers. lemma example1 (x y z : mynat) : x * y + z = x * y + z := begin refl, end
0470436539416339c5384bc4f839aca8def7cf2a
e898bfefd5cb60a60220830c5eba68cab8d02c79
/uexp/src/uexp/rules/transitiveInferenceJoin.lean
83cb35f5b393e7c63241552aeb3dbe4754ff2520
[ "BSD-2-Clause" ]
permissive
kkpapa/Cosette
9ed09e2dc4c1ecdef815c30b5501f64a7383a2ce
fda8fdbbf0de6c1be9b4104b87bbb06cede46329
refs/heads/master
1,584,573,128,049
1,526,370,422,000
1,526,370,422,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,261
lean
import ..sql import ..tactics import ..u_semiring import ..extra_constants import ..ucongr import ..TDP set_option profiler true open Expr open Proj open Pred open SQL open tree notation `int` := datatypes.int variable integer_1: const datatypes.int variable integer_7: const datatypes.int theorem rule: forall ( Γ scm_t scm_account scm_bonus scm_dept scm_emp: Schema) (rel_t: relation scm_t) (rel_account: relation scm_account) (rel_bonus: relation scm_bonus) (rel_dept: relation scm_dept) (rel_emp: relation scm_emp) (t_k0 : Column int scm_t) (t_c1 : Column int scm_t) (t_f1_a0 : Column int scm_t) (t_f2_a0 : Column int scm_t) (t_f0_c0 : Column int scm_t) (t_f1_c0 : Column int scm_t) (t_f0_c1 : Column int scm_t) (t_f1_c2 : Column int scm_t) (t_f2_c3 : Column int scm_t) (account_acctno : Column int scm_account) (account_type : Column int scm_account) (account_balance : Column int scm_account) (bonus_ename : Column int scm_bonus) (bonus_job : Column int scm_bonus) (bonus_sal : Column int scm_bonus) (bonus_comm : Column int scm_bonus) (dept_deptno : Column int scm_dept) (dept_name : Column int scm_dept) (emp_empno : Column int scm_emp) (emp_ename : Column int scm_emp) (emp_job : Column int scm_emp) (emp_mgr : Column int scm_emp) (emp_hiredate : Column int scm_emp) (emp_comm : Column int scm_emp) (emp_sal : Column int scm_emp) (emp_deptno : Column int scm_emp) (emp_slacker : Column int scm_emp), denoteSQL ((SELECT1 (e2p (constantExpr integer_1)) FROM1 (product (table rel_emp) ((SELECT * FROM1 (table rel_emp) WHERE (castPred (combine (right⋅emp_deptno) (e2p (constantExpr integer_7)) ) predicates.gt)))) WHERE (equal (uvariable (right⋅left⋅emp_deptno)) (uvariable (right⋅right⋅emp_deptno)))) :SQL Γ _) = denoteSQL ((SELECT1 (e2p (constantExpr integer_1)) FROM1 (product ((SELECT * FROM1 (table rel_emp) WHERE (castPred (combine (right⋅emp_deptno) (e2p (constantExpr integer_7)) ) predicates.gt))) ((SELECT * FROM1 (table rel_emp) WHERE (castPred (combine (right⋅emp_deptno) (e2p (constantExpr integer_7)) ) predicates.gt)))) WHERE (equal (uvariable (right⋅left⋅emp_deptno)) (uvariable (right⋅right⋅emp_deptno)))) :SQL Γ _) := begin intros, unfold_all_denotations, funext, try {simp}, print_size, TDP end
dddb403a2e901a7744fe32f67331d21b68906fdd
0c1546a496eccfb56620165cad015f88d56190c5
/library/data/set/basic.lean
4fab1bbcfed9ff6ea1bafd47dda401cfc3ea78b2
[ "Apache-2.0" ]
permissive
Solertis/lean
491e0939957486f664498fbfb02546e042699958
84188c5aa1673fdf37a082b2de8562dddf53df3f
refs/heads/master
1,610,174,257,606
1,486,263,620,000
1,486,263,620,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,715
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad, Leonardo de Moura -/ namespace set universe variable u variable {α : Type u} lemma ext {a b : set α} (h : ∀ x, x ∈ a ↔ x ∈ b) : a = b := funext (take x, propext (h x)) lemma subset.refl (a : set α) : a ⊆ a := take x, assume H, H lemma subset.trans {a b c : set α} (subab : a ⊆ b) (subbc : b ⊆ c) : a ⊆ c := take x, assume ax, subbc (subab ax) lemma subset.antisymm {a b : set α} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b := ext (λ x, iff.intro (λ ina, h₁ ina) (λ inb, h₂ inb)) -- an alterantive name lemma eq_of_subset_of_subset {a b : set α} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b := subset.antisymm h₁ h₂ lemma mem_of_subset_of_mem {s₁ s₂ : set α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := assume h₁ h₂, h₁ h₂ lemma not_mem_empty (x : α) : ¬ (x ∈ (∅ : set α)) := assume h : x ∈ ∅, h lemma mem_empty_eq (x : α) : x ∈ (∅ : set α) = false := rfl lemma eq_empty_of_forall_not_mem {s : set α} (h : ∀ x, x ∉ s) : s = ∅ := ext (take x, iff.intro (assume xs, absurd xs (h x)) (assume xe, absurd xe (not_mem_empty _))) lemma ne_empty_of_mem {s : set α} {x : α} (h : x ∈ s) : s ≠ ∅ := begin intro hs, rewrite hs at h, apply not_mem_empty _ h end lemma empty_subset (s : set α) : ∅ ⊆ s := take x, assume h, false.elim h lemma eq_empty_of_subset_empty {s : set α} (h : s ⊆ ∅) : s = ∅ := subset.antisymm h (empty_subset s) lemma union_comm (a b : set α) : a ∪ b = b ∪ a := ext (take x, or.comm) lemma union_assoc (a b c : set α) : (a ∪ b) ∪ c = a ∪ (b ∪ c) := ext (take x, or.assoc) instance union_is_assoc : is_associative (set α) union := ⟨union_assoc⟩ instance union_is_comm : is_commutative (set α) union := ⟨union_comm⟩ lemma union_self (a : set α) : a ∪ a = a := ext (take x, or_self _) lemma union_empty (a : set α) : a ∪ ∅ = a := ext (take x, or_false _) lemma empty_union (a : set α) : ∅ ∪ a = a := ext (take x, false_or _) lemma inter_comm (a b : set α) : a ∩ b = b ∩ a := ext (take x, and.comm) lemma inter_assoc (a b c : set α) : (a ∩ b) ∩ c = a ∩ (b ∩ c) := ext (take x, and.assoc) instance inter_is_assoc : is_associative (set α) inter := ⟨inter_assoc⟩ instance inter_is_comm : is_commutative (set α) union := ⟨union_comm⟩ lemma inter_self (a : set α) : a ∩ a = a := ext (take x, and_self _) lemma inter_empty (a : set α) : a ∩ ∅ = ∅ := ext (take x, and_false _) lemma empty_inter (a : set α) : ∅ ∩ a = ∅ := ext (take x, false_and _) end set
7ccd78c705f5938ddadd881b9a59796fd2d5b5da
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/number_theory/fermat4.lean
b9fc62467ee9d025d38b7215dde8e50efada1559
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
11,786
lean
/- Copyright (c) 2020 Paul van Wamelen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Paul van Wamelen -/ import number_theory.pythagorean_triples import ring_theory.coprime.lemmas import tactic.linear_combination /-! # Fermat's Last Theorem for the case n = 4 There are no non-zero integers `a`, `b` and `c` such that `a ^ 4 + b ^ 4 = c ^ 4`. -/ noncomputable theory open_locale classical /-- Shorthand for three non-zero integers `a`, `b`, and `c` satisfying `a ^ 4 + b ^ 4 = c ^ 2`. We will show that no integers satisfy this equation. Clearly Fermat's Last theorem for n = 4 follows. -/ def fermat_42 (a b c : ℤ) : Prop := a ≠ 0 ∧ b ≠ 0 ∧ a ^ 4 + b ^ 4 = c ^ 2 namespace fermat_42 lemma comm {a b c : ℤ} : (fermat_42 a b c) ↔ (fermat_42 b a c) := by { delta fermat_42, rw add_comm, tauto } lemma mul {a b c k : ℤ} (hk0 : k ≠ 0) : fermat_42 a b c ↔ fermat_42 (k * a) (k * b) (k ^ 2 * c) := begin delta fermat_42, split, { intro f42, split, { exact mul_ne_zero hk0 f42.1 }, split, { exact mul_ne_zero hk0 f42.2.1 }, { have H : a ^ 4 + b ^ 4 = c ^ 2 := f42.2.2, linear_combination k ^ 4 * H } }, { intro f42, split, { exact right_ne_zero_of_mul f42.1 }, split, { exact right_ne_zero_of_mul f42.2.1 }, apply (mul_right_inj' (pow_ne_zero 4 hk0)).mp, linear_combination f42.2.2 } end lemma ne_zero {a b c : ℤ} (h : fermat_42 a b c) : c ≠ 0 := begin apply ne_zero_pow two_ne_zero _, apply ne_of_gt, rw [← h.2.2, (by ring : a ^ 4 + b ^ 4 = (a ^ 2) ^ 2 + (b ^ 2) ^ 2)], exact add_pos (sq_pos_of_ne_zero _ (pow_ne_zero 2 h.1)) (sq_pos_of_ne_zero _ (pow_ne_zero 2 h.2.1)) end /-- We say a solution to `a ^ 4 + b ^ 4 = c ^ 2` is minimal if there is no other solution with a smaller `c` (in absolute value). -/ def minimal (a b c : ℤ) : Prop := (fermat_42 a b c) ∧ ∀ (a1 b1 c1 : ℤ), (fermat_42 a1 b1 c1) → int.nat_abs c ≤ int.nat_abs c1 /-- if we have a solution to `a ^ 4 + b ^ 4 = c ^ 2` then there must be a minimal one. -/ lemma exists_minimal {a b c : ℤ} (h : fermat_42 a b c) : ∃ (a0 b0 c0), (minimal a0 b0 c0) := begin let S : set ℕ := { n | ∃ (s : ℤ × ℤ × ℤ), fermat_42 s.1 s.2.1 s.2.2 ∧ n = int.nat_abs s.2.2}, have S_nonempty : S.nonempty, { use int.nat_abs c, rw set.mem_set_of_eq, use ⟨a, ⟨b, c⟩⟩, tauto }, let m : ℕ := nat.find S_nonempty, have m_mem : m ∈ S := nat.find_spec S_nonempty, rcases m_mem with ⟨s0, hs0, hs1⟩, use [s0.1, s0.2.1, s0.2.2, hs0], intros a1 b1 c1 h1, rw ← hs1, apply nat.find_min', use ⟨a1, ⟨b1, c1⟩⟩, tauto end /-- a minimal solution to `a ^ 4 + b ^ 4 = c ^ 2` must have `a` and `b` coprime. -/ lemma coprime_of_minimal {a b c : ℤ} (h : minimal a b c) : is_coprime a b := begin apply int.gcd_eq_one_iff_coprime.mp, by_contradiction hab, obtain ⟨p, hp, hpa, hpb⟩ := nat.prime.not_coprime_iff_dvd.mp hab, obtain ⟨a1, rfl⟩ := (int.coe_nat_dvd_left.mpr hpa), obtain ⟨b1, rfl⟩ := (int.coe_nat_dvd_left.mpr hpb), have hpc : (p : ℤ) ^ 2 ∣ c, { rw [←int.pow_dvd_pow_iff zero_lt_two, ←h.1.2.2], apply dvd.intro (a1 ^ 4 + b1 ^ 4), ring }, obtain ⟨c1, rfl⟩ := hpc, have hf : fermat_42 a1 b1 c1, exact (fermat_42.mul (int.coe_nat_ne_zero.mpr (nat.prime.ne_zero hp))).mpr h.1, apply nat.le_lt_antisymm (h.2 _ _ _ hf), rw [int.nat_abs_mul, lt_mul_iff_one_lt_left, int.nat_abs_pow, int.nat_abs_of_nat], { exact nat.one_lt_pow _ _ zero_lt_two (nat.prime.one_lt hp) }, { exact (nat.pos_of_ne_zero (int.nat_abs_ne_zero_of_ne_zero (ne_zero hf))) }, end /-- We can swap `a` and `b` in a minimal solution to `a ^ 4 + b ^ 4 = c ^ 2`. -/ lemma minimal_comm {a b c : ℤ} : (minimal a b c) → (minimal b a c) := λ ⟨h1, h2⟩, ⟨fermat_42.comm.mp h1, h2⟩ /-- We can assume that a minimal solution to `a ^ 4 + b ^ 4 = c ^ 2` has positive `c`. -/ lemma neg_of_minimal {a b c : ℤ} : (minimal a b c) → (minimal a b (-c)) := begin rintros ⟨⟨ha, hb, heq⟩, h2⟩, split, { apply and.intro ha (and.intro hb _), rw heq, exact (neg_sq c).symm }, rwa (int.nat_abs_neg c), end /-- We can assume that a minimal solution to `a ^ 4 + b ^ 4 = c ^ 2` has `a` odd. -/ lemma exists_odd_minimal {a b c : ℤ} (h : fermat_42 a b c) : ∃ (a0 b0 c0), (minimal a0 b0 c0) ∧ a0 % 2 = 1 := begin obtain ⟨a0, b0, c0, hf⟩ := exists_minimal h, cases int.mod_two_eq_zero_or_one a0 with hap hap, { cases int.mod_two_eq_zero_or_one b0 with hbp hbp, { exfalso, have h1 : 2 ∣ (int.gcd a0 b0 : ℤ), { exact int.dvd_gcd (int.dvd_of_mod_eq_zero hap) (int.dvd_of_mod_eq_zero hbp) }, rw int.gcd_eq_one_iff_coprime.mpr (coprime_of_minimal hf) at h1, revert h1, norm_num }, { exact ⟨b0, ⟨a0, ⟨c0, minimal_comm hf, hbp⟩⟩⟩ } }, exact ⟨a0, ⟨b0, ⟨c0 , hf, hap⟩⟩⟩, end /-- We can assume that a minimal solution to `a ^ 4 + b ^ 4 = c ^ 2` has `a` odd and `c` positive. -/ lemma exists_pos_odd_minimal {a b c : ℤ} (h : fermat_42 a b c) : ∃ (a0 b0 c0), (minimal a0 b0 c0) ∧ a0 % 2 = 1 ∧ 0 < c0 := begin obtain ⟨a0, b0, c0, hf, hc⟩ := exists_odd_minimal h, rcases lt_trichotomy 0 c0 with (h1 | rfl | h1), { use [a0, b0, c0], tauto }, { exfalso, exact ne_zero hf.1 rfl}, { use [a0, b0, -c0, neg_of_minimal hf, hc], exact neg_pos.mpr h1 }, end end fermat_42 lemma int.coprime_of_sq_sum {r s : ℤ} (h2 : is_coprime s r) : is_coprime (r ^ 2 + s ^ 2) r := begin rw [sq, sq], exact (is_coprime.mul_left h2 h2).mul_add_left_left r end lemma int.coprime_of_sq_sum' {r s : ℤ} (h : is_coprime r s) : is_coprime (r ^ 2 + s ^ 2) (r * s) := begin apply is_coprime.mul_right (int.coprime_of_sq_sum (is_coprime_comm.mp h)), rw add_comm, apply int.coprime_of_sq_sum h end namespace fermat_42 -- If we have a solution to a ^ 4 + b ^ 4 = c ^ 2, we can construct a smaller one. This -- implies there can't be a smallest solution. lemma not_minimal {a b c : ℤ} (h : minimal a b c) (ha2 : a % 2 = 1) (hc : 0 < c) : false := begin -- Use the fact that a ^ 2, b ^ 2, c form a pythagorean triple to obtain m and n such that -- a ^ 2 = m ^ 2 - n ^ 2, b ^ 2 = 2 * m * n and c = m ^ 2 + n ^ 2 -- first the formula: have ht : pythagorean_triple (a ^ 2) (b ^ 2) c, { delta pythagorean_triple, linear_combination h.1.2.2 }, -- coprime requirement: have h2 : int.gcd (a ^ 2) (b ^ 2) = 1 := int.gcd_eq_one_iff_coprime.mpr (coprime_of_minimal h).pow, -- in order to reduce the possibilities we get from the classification of pythagorean triples -- it helps if we know the parity of a ^ 2 (and the sign of c): have ha22 : a ^ 2 % 2 = 1, { rw [sq, int.mul_mod, ha2], norm_num }, obtain ⟨m, n, ht1, ht2, ht3, ht4, ht5, ht6⟩ := ht.coprime_classification' h2 ha22 hc, -- Now a, n, m form a pythagorean triple and so we can obtain r and s such that -- a = r ^ 2 - s ^ 2, n = 2 * r * s and m = r ^ 2 + s ^ 2 -- formula: have htt : pythagorean_triple a n m, { delta pythagorean_triple, linear_combination (ht1) }, -- a and n are coprime, because a ^ 2 = m ^ 2 - n ^ 2 and m and n are coprime. have h3 : int.gcd a n = 1, { apply int.gcd_eq_one_iff_coprime.mpr, apply @is_coprime.of_mul_left_left _ _ _ a, rw [← sq, ht1, (by ring : m ^ 2 - n ^ 2 = m ^ 2 + (-n) * n)], exact (int.gcd_eq_one_iff_coprime.mp ht4).pow_left.add_mul_right_left (-n) }, -- m is positive because b is non-zero and b ^ 2 = 2 * m * n and we already have 0 ≤ m. have hb20 : b ^ 2 ≠ 0 := mt pow_eq_zero h.1.2.1, have h4 : 0 < m, { apply lt_of_le_of_ne ht6, rintro rfl, revert hb20, rw ht2, simp }, obtain ⟨r, s, htt1, htt2, htt3, htt4, htt5, htt6⟩ := htt.coprime_classification' h3 ha2 h4, -- Now use the fact that (b / 2) ^ 2 = m * r * s, and m, r and s are pairwise coprime to obtain -- i, j and k such that m = i ^ 2, r = j ^ 2 and s = k ^ 2. -- m and r * s are coprime because m = r ^ 2 + s ^ 2 and r and s are coprime. have hcp : int.gcd m (r * s) = 1, { rw htt3, exact int.gcd_eq_one_iff_coprime.mpr (int.coprime_of_sq_sum' (int.gcd_eq_one_iff_coprime.mp htt4)) }, -- b is even because b ^ 2 = 2 * m * n. have hb2 : 2 ∣ b, { apply @int.prime.dvd_pow' _ 2 _ (by norm_num : nat.prime 2), rw [ht2, mul_assoc], exact dvd_mul_right 2 (m * n) }, cases hb2 with b' hb2', have hs : b' ^ 2 = m * (r * s), { apply (mul_right_inj' (by norm_num : (4 : ℤ) ≠ 0)).mp, linear_combination (- b - 2 * b') * hb2' + ht2 + 2 * m * htt2 }, have hrsz : r * s ≠ 0, -- because b ^ 2 is not zero and (b / 2) ^ 2 = m * (r * s) { by_contradiction hrsz, revert hb20, rw [ht2, htt2, mul_assoc, @mul_assoc _ _ _ r s, hrsz], simp }, have h2b0 : b' ≠ 0, { apply ne_zero_pow two_ne_zero, rw hs, apply mul_ne_zero, { exact ne_of_gt h4}, { exact hrsz } }, obtain ⟨i, hi⟩ := int.sq_of_gcd_eq_one hcp hs.symm, -- use m is positive to exclude m = - i ^ 2 have hi' : ¬ m = - i ^ 2, { by_contradiction h1, have hit : - i ^ 2 ≤ 0, apply neg_nonpos.mpr (sq_nonneg i), rw ← h1 at hit, apply absurd h4 (not_lt.mpr hit) }, replace hi : m = i ^ 2, { apply or.resolve_right hi hi' }, rw mul_comm at hs, rw [int.gcd_comm] at hcp, -- obtain d such that r * s = d ^ 2 obtain ⟨d, hd⟩ := int.sq_of_gcd_eq_one hcp hs.symm, -- (b / 2) ^ 2 and m are positive so r * s is positive have hd' : ¬ r * s = - d ^ 2, { by_contradiction h1, rw h1 at hs, have h2 : b' ^ 2 ≤ 0, { rw [hs, (by ring : - d ^ 2 * m = - (d ^ 2 * m))], exact neg_nonpos.mpr ((zero_le_mul_right h4).mpr (sq_nonneg d)) }, have h2' : 0 ≤ b' ^ 2, { apply sq_nonneg b' }, exact absurd (lt_of_le_of_ne h2' (ne.symm (pow_ne_zero _ h2b0))) (not_lt.mpr h2) }, replace hd : r * s = d ^ 2, { apply or.resolve_right hd hd' }, -- r = +/- j ^ 2 obtain ⟨j, hj⟩ := int.sq_of_gcd_eq_one htt4 hd, have hj0 : j ≠ 0, { intro h0, rw [h0, zero_pow zero_lt_two, neg_zero, or_self] at hj, apply left_ne_zero_of_mul hrsz hj }, rw mul_comm at hd, rw [int.gcd_comm] at htt4, -- s = +/- k ^ 2 obtain ⟨k, hk⟩ := int.sq_of_gcd_eq_one htt4 hd, have hk0 : k ≠ 0, { intro h0, rw [h0, zero_pow zero_lt_two, neg_zero, or_self] at hk, apply right_ne_zero_of_mul hrsz hk }, have hj2 : r ^ 2 = j ^ 4, { cases hj with hjp hjp; { rw hjp, ring } }, have hk2 : s ^ 2 = k ^ 4, { cases hk with hkp hkp; { rw hkp, ring } }, -- from m = r ^ 2 + s ^ 2 we now get a new solution to a ^ 4 + b ^ 4 = c ^ 2: have hh : i ^ 2 = j ^ 4 + k ^ 4, { rw [← hi, htt3, hj2, hk2] }, have hn : n ≠ 0, { rw ht2 at hb20, apply right_ne_zero_of_mul hb20 }, -- and it has a smaller c: from c = m ^ 2 + n ^ 2 we see that m is smaller than c, and i ^ 2 = m. have hic : int.nat_abs i < int.nat_abs c, { apply int.coe_nat_lt.mp, rw ← (int.eq_nat_abs_of_zero_le (le_of_lt hc)), apply gt_of_gt_of_ge _ (int.abs_le_self_sq i), rw [← hi, ht3], apply gt_of_gt_of_ge _ (int.le_self_sq m), exact lt_add_of_pos_right (m ^ 2) (sq_pos_of_ne_zero n hn) }, have hic' : int.nat_abs c ≤ int.nat_abs i, { apply (h.2 j k i), exact ⟨hj0, hk0, hh.symm⟩ }, apply absurd (not_le_of_lt hic) (not_not.mpr hic') end end fermat_42 lemma not_fermat_42 {a b c : ℤ} (ha : a ≠ 0) (hb : b ≠ 0) : a ^ 4 + b ^ 4 ≠ c ^ 2 := begin intro h, obtain ⟨a0, b0, c0, ⟨hf, h2, hp⟩⟩ := fermat_42.exists_pos_odd_minimal (and.intro ha (and.intro hb h)), apply fermat_42.not_minimal hf h2 hp end theorem not_fermat_4 {a b c : ℤ} (ha : a ≠ 0) (hb : b ≠ 0) : a ^ 4 + b ^ 4 ≠ c ^ 4 := begin intro heq, apply @not_fermat_42 _ _ (c ^ 2) ha hb, rw heq, ring end
4004893ed35bee0f94f9a676a9f4b8d7dd11871e
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/library/tools/super/selection.lean
c60f8129976381542602f8e809c576f60ac98265
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,005
lean
/- Copyright (c) 2016 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import .prover_state namespace super meta def simple_selection_strategy (f : (expr → expr → bool) → clause → list ℕ) : selection_strategy := take dc, do gt ← get_term_order, return $ if dc^.selected^.empty ∧ dc^.c^.num_lits > 0 then { dc with selected := f gt dc^.c } else dc meta def dumb_selection : selection_strategy := simple_selection_strategy $ λgt c, match c^.lits_where clause.literal.is_neg with | [] := list.range c^.num_lits | neg_lit::_ := [neg_lit] end meta def selection21 : selection_strategy := simple_selection_strategy $ λgt c, let maximal_lits := list.filter_maximal (λi j, gt (c^.get_lit i)^.formula (c^.get_lit j)^.formula) (list.range c^.num_lits) in if list.length maximal_lits = 1 then maximal_lits else let neg_lits := list.filter (λi, (c^.get_lit i)^.is_neg) (list.range c^.num_lits), maximal_neg_lits := list.filter_maximal (λi j, gt (c^.get_lit i)^.formula (c^.get_lit j)^.formula) neg_lits in if ¬maximal_neg_lits^.empty then list.taken 1 maximal_neg_lits else maximal_lits meta def selection22 : selection_strategy := simple_selection_strategy $ λgt c, let maximal_lits := list.filter_maximal (λi j, gt (c^.get_lit i)^.formula (c^.get_lit j)^.formula) (list.range c^.num_lits), maximal_lits_neg := list.filter (λi, (c^.get_lit i)^.is_neg) maximal_lits in if ¬maximal_lits_neg^.empty then list.taken 1 maximal_lits_neg else maximal_lits meta def clause_weight (c : derived_clause) : nat := (c^.c^.get_lits^.for (λl, expr_size l^.formula + if l^.is_pos then 10 else 1))^.sum meta def find_minimal_by (passive : rb_map clause_id derived_clause) {A} [has_ordering A] (f : derived_clause → A) : clause_id := match rb_map.min $ rb_map.of_list $ passive^.values^.for $ λc, (f c, c^.id) with | some id := id | none := nat.zero end meta def age_of_clause_id : name → ℕ | (name.mk_numeral i _) := unsigned.to_nat i | _ := 0 meta def find_minimal_weight (passive : rb_map clause_id derived_clause) : clause_id := find_minimal_by passive $ λc, (c^.sc^.priority, clause_weight c + c^.sc^.cost, c^.sc^.age, c^.id) meta def find_minimal_age (passive : rb_map clause_id derived_clause) : clause_id := find_minimal_by passive $ λc, (c^.sc^.priority, c^.sc^.age, c^.id) meta def weight_clause_selection : clause_selection_strategy := take iter, do state ← state_t.read, return $ find_minimal_weight state^.passive meta def oldest_clause_selection : clause_selection_strategy := take iter, do state ← state_t.read, return $ find_minimal_age state^.passive meta def age_weight_clause_selection (thr mod : ℕ) : clause_selection_strategy := take iter, if iter % mod < thr then weight_clause_selection iter else oldest_clause_selection iter end super
fc6304e066bb3cb5bb0bc003228146c430f494d8
d642a6b1261b2cbe691e53561ac777b924751b63
/src/topology/metric_space/closeds.lean
48536248e23620a8505af2cfad8af4899bd6885b
[ "Apache-2.0" ]
permissive
cipher1024/mathlib
fee56b9954e969721715e45fea8bcb95f9dc03fe
d077887141000fefa5a264e30fa57520e9f03522
refs/heads/master
1,651,806,490,504
1,573,508,694,000
1,573,508,694,000
107,216,176
0
0
Apache-2.0
1,647,363,136,000
1,508,213,014,000
Lean
UTF-8
Lean
false
false
24,033
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sébastien Gouëzel The metric and emetric space structure on the types of closed subsets and nonempty compact subsets of a metric or emetric space The Hausdorff distance induces an emetric space structure on the type of closed subsets of an emetric space, called `closeds`. Its completeness, resp. compactness, resp. second-countability, follow from the corresponding properties of the original space. In a metric space, the type of nonempty compact subsets (called `nonempty_compacts`) also inherits a metric space structure from the Hausdorff distance, as the Hausdorff edistance is always finite in this context. -/ import topology.metric_space.hausdorff_distance topology.opens noncomputable theory open_locale classical universe u open classical lattice set function topological_space filter namespace emetric section variables {α : Type u} [emetric_space α] {s : set α} /-- In emetric spaces, the Hausdorff edistance defines an emetric space structure on the type of closed subsets -/ instance closeds.emetric_space : emetric_space (closeds α) := { edist := λs t, Hausdorff_edist s.val t.val, edist_self := λs, Hausdorff_edist_self, edist_comm := λs t, Hausdorff_edist_comm, edist_triangle := λs t u, Hausdorff_edist_triangle, eq_of_edist_eq_zero := λs t h, subtype.eq ((Hausdorff_edist_zero_iff_eq_of_closed s.property t.property).1 h) } /-- The edistance to a closed set depends continuously on the point and the set -/ lemma continuous_inf_edist_Hausdorff_edist : continuous (λp : α × (closeds α), inf_edist p.1 (p.2).val) := begin refine continuous_of_le_add_edist 2 (by simp) _, rintros ⟨x, s⟩ ⟨y, t⟩, calc inf_edist x (s.val) ≤ inf_edist x (t.val) + Hausdorff_edist (t.val) (s.val) : inf_edist_le_inf_edist_add_Hausdorff_edist ... ≤ (inf_edist y (t.val) + edist x y) + Hausdorff_edist (t.val) (s.val) : add_le_add_right' inf_edist_le_inf_edist_add_edist ... = inf_edist y (t.val) + (edist x y + Hausdorff_edist (s.val) (t.val)) : by simp [add_comm, Hausdorff_edist_comm] ... ≤ inf_edist y (t.val) + (edist (x, s) (y, t) + edist (x, s) (y, t)) : add_le_add_left' (add_le_add' (by simp [edist, le_refl]) (by simp [edist, le_refl])) ... = inf_edist y (t.val) + 2 * edist (x, s) (y, t) : by rw [← mul_two, mul_comm] end /-- Subsets of a given closed subset form a closed set -/ lemma is_closed_subsets_of_is_closed (hs : is_closed s) : is_closed {t : closeds α | t.val ⊆ s} := begin refine is_closed_of_closure_subset (λt ht x hx, _), -- t : closeds α, ht : t ∈ closure {t : closeds α | t.val ⊆ s}, -- x : α, hx : x ∈ t.val -- goal : x ∈ s have : x ∈ closure s, { refine mem_closure_iff'.2 (λε εpos, _), rcases mem_closure_iff'.1 ht ε εpos with ⟨u, hu, Dtu⟩, -- u : closeds α, hu : u ∈ {t : closeds α | t.val ⊆ s}, hu' : edist t u < ε rcases exists_edist_lt_of_Hausdorff_edist_lt hx Dtu with ⟨y, hy, Dxy⟩, -- y : α, hy : y ∈ u.val, Dxy : edist x y < ε exact ⟨y, hu hy, Dxy⟩ }, rwa closure_eq_of_is_closed hs at this, end /-- By definition, the edistance on `closeds α` is given by the Hausdorff edistance -/ lemma closeds.edist_eq {s t : closeds α} : edist s t = Hausdorff_edist s.val t.val := rfl /-- In a complete space, the type of closed subsets is complete for the Hausdorff edistance. -/ instance closeds.complete_space [complete_space α] : complete_space (closeds α) := begin /- We will show that, if a sequence of sets `s n` satisfies `edist (s n) (s (n+1)) < 2^{-n}`, then it converges. This is enough to guarantee completeness, by a standard completeness criterion. We use the shorthand `B n = 2^{-n}` in ennreal. -/ let B : ℕ → ennreal := ennreal.half_pow, /- Consider a sequence of closed sets `s n` with `edist (s n) (s (n+1)) < B n`. We will show that it converges. The limit set is t0 = ⋂n, closure (⋃m≥n, s m). We will have to show that a point in `s n` is close to a point in `t0`, and a point in `t0` is close to a point in `s n`. The completeness then follows from a standard criterion. -/ refine complete_of_convergent_controlled_sequences _ ennreal.half_pow_pos (λs hs, _), let t0 := ⋂n, closure (⋃m≥n, (s m).val), have : is_closed t0 := is_closed_Inter (λ_, is_closed_closure), let t : closeds α := ⟨t0, this⟩, use t, have I1 : ∀n:ℕ, ∀x ∈ (s n).val, ∃y ∈ t0, edist x y ≤ 2 * B n, { /- This is the main difficulty of the proof. Starting from `x ∈ s n`, we want to find a point in `t0` which is close to `x`. Define inductively a sequence of points `z m` with `z n = x` and `z m ∈ s m` and `edist (z m) (z (m+1)) ≤ B m`. This is possible since the Hausdorff distance between `s m` and `s (m+1)` is at most `B m`. This sequence is a Cauchy sequence, therefore converging as the space is complete, to a limit which satisfies the required properties. -/ assume n x hx, haveI : nonempty α := ⟨x⟩, let z : ℕ → α := λk, nat.rec_on k x (λl z, if l < n then x else epsilon (λy, y ∈ (s (l+1)).val ∧ edist z y < B l)), have z_le_n : ∀l≤n, z l = x, { assume l hl, cases l with m, { show z 0 = x, from rfl }, { have : z (nat.succ m) = ite (m < n) x (epsilon (λ (y : α), y ∈ (s (m + 1)).val ∧ edist (z m) y < B m)) := rfl, rw this, simp [nat.lt_of_succ_le hl] }}, have : z n = x := z_le_n n (le_refl n), -- check by induction that the sequence `z m` satisfies the required properties have I : ∀m≥n, z m ∈ (s m).val → (z (m+1) ∈ (s (m+1)).val ∧ edist (z m) (z (m+1)) < B m), { assume m hm hz, have E : ∃y, y ∈ (s (m+1)).val ∧ edist (z m) y < B m, { have : Hausdorff_edist (s m).val (s (m+1)).val < B m := hs m m (m+1) (le_refl _) (by simp), rcases exists_edist_lt_of_Hausdorff_edist_lt hz this with ⟨y, hy, Dy⟩, exact ⟨y, ⟨hy, Dy⟩⟩ }, have : z (m+1) = ite (m < n) x (epsilon (λ (y : α), y ∈ (s (m + 1)).val ∧ edist (z m) y < B m)) := rfl, rw this, simp only [not_lt_of_le hm, if_false], exact epsilon_spec E }, have z_in_s : ∀m≥n, z m ∈ (s m).val := nat.le_induction (by rwa ‹z n = x›) (λm hm zm, (I m hm zm).1), -- for all `m`, the distance between `z m` and `z (m+1)` is controlled by `B m`: -- for `m ≥ n`, this follows from the construction, while for `m < n` all points are `x`. have Im_succm : ∀m, edist (z m) (z (m+1)) ≤ B m, { assume m, by_cases hm : n≤m, { exact le_of_lt (I m hm (z_in_s m hm)).2 }, { rw not_le at hm, have Im : z m = x := z_le_n m (le_of_lt hm), have Im' : z (m+1) = x := z_le_n (m+1) (nat.succ_le_of_lt hm), simp [Im, Im', ennreal.half_pow_pos] }}, /- From the distance control between `z m` and `z (m+1)`, we deduce a distance control between `z k` and `z l` by summing the geometric series. -/ have Iz : ∀k l N, N ≤ k → N ≤ l → edist (z k) (z l) ≤ 2 * B N := λk l N hk hl, ennreal.edist_le_two_mul_half_pow hk hl Im_succm, -- it follows from the previous bound that `z` is a Cauchy sequence have : cauchy_seq z := ennreal.cauchy_seq_of_edist_le_half_pow Im_succm, -- therefore, it converges rcases cauchy_seq_tendsto_of_complete this with ⟨y, y_lim⟩, -- the limit point `y` will be the desired point, in `t0` and close to our initial point `x`. -- First, we check it belongs to `t0`. have : y ∈ t0 := mem_Inter.2 (λk, mem_closure_of_tendsto (by simp) y_lim begin simp only [exists_prop, set.mem_Union, filter.mem_at_top_sets, set.mem_preimage, set.preimage_Union], exact ⟨max n k, λm hm, ⟨m, ⟨le_trans (le_max_right _ _) hm, z_in_s m (le_trans (le_max_left _ _) hm)⟩⟩⟩, end), -- Then, we check that `y` is close to `x = z n`. This follows from the fact that `y` -- is the limit of `z k`, and the distance between `z n` and `z k` has already been estimated. have : edist x y ≤ 2 * B n, { refine le_of_tendsto (by simp) (tendsto_edist tendsto_const_nhds y_lim) _, simp [‹z n = x›.symm], exact ⟨n, λm hm, Iz n m n (le_refl n) hm⟩ }, -- Conclusion of this argument: the point `y` satisfies the required properties. exact ⟨y, ‹y ∈ t0›, ‹edist x y ≤ 2 * B n›⟩ }, have I2 : ∀n:ℕ, ∀x ∈ t0, ∃y ∈ (s n).val, edist x y ≤ 2 * B n, { /- For the (much easier) reverse inequality, we start from a point `x ∈ t0` and we want to find a point `y ∈ s n` which is close to `x`. `x` belongs to `t0`, the intersection of the closures. In particular, it is well approximated by a point `z` in `⋃m≥n, s m`, say in `s m`. Since `s m` and `s n` are close, this point is itself well approximated by a point `y` in `s n`, as required. -/ assume n x xt0, have : x ∈ closure (⋃m≥n, (s m).val), by apply mem_Inter.1 xt0 n, rcases mem_closure_iff'.1 this (B n) (ennreal.half_pow_pos n) with ⟨z, hz, Dxz⟩, -- z : α, Dxz : edist x z < B n, simp only [exists_prop, set.mem_Union] at hz, rcases hz with ⟨m, ⟨m_ge_n, hm⟩⟩, -- m : ℕ, m_ge_n : m ≥ n, hm : z ∈ (s m).val have : Hausdorff_edist (s m).val (s n).val < B n := hs n m n m_ge_n (le_refl n), rcases exists_edist_lt_of_Hausdorff_edist_lt hm this with ⟨y, hy, Dzy⟩, -- y : α, hy : y ∈ (s n).val, Dzy : edist z y < B n exact ⟨y, hy, calc edist x y ≤ edist x z + edist z y : edist_triangle _ _ _ ... ≤ B n + B n : add_le_add' (le_of_lt Dxz) (le_of_lt Dzy) ... = 2 * B n : (two_mul _).symm ⟩ }, -- Deduce from the above inequalities that the distance between `s n` and `t0` is at most `2 B n`. have main : ∀n:ℕ, edist (s n) t ≤ 2 * B n := λn, Hausdorff_edist_le_of_mem_edist (I1 n) (I2 n), -- from this, the convergence of `s n` to `t0` follows. refine (tendsto_at_top _).2 (λε εpos, _), have : tendsto (λn, 2 * ennreal.half_pow n) at_top (nhds (2 * 0)) := ennreal.tendsto_mul_right ennreal.half_pow_tendsto_zero (by simp), rw mul_zero at this, have Z := (tendsto_orderable.1 this).2 ε εpos, simp only [filter.mem_at_top_sets, set.mem_set_of_eq] at Z, rcases Z with ⟨N, hN⟩, -- ∀ (b : ℕ), b ≥ N → ε > 2 * B b exact ⟨N, λn hn, lt_of_le_of_lt (main n) (hN n hn)⟩ end /-- In a compact space, the type of closed subsets is compact. -/ instance closeds.compact_space [compact_space α] : compact_space (closeds α) := ⟨begin /- by completeness, it suffices to show that it is totally bounded, i.e., for all ε>0, there is a finite set which is ε-dense. start from a set `s` which is ε-dense in α. Then the subsets of `s` are finitely many, and ε-dense for the Hausdorff distance. -/ refine compact_of_totally_bounded_is_closed (emetric.totally_bounded_iff.2 (λε εpos, _)) is_closed_univ, rcases dense εpos with ⟨δ, δpos, δlt⟩, rcases emetric.totally_bounded_iff.1 (compact_iff_totally_bounded_complete.1 (@compact_univ α _ _)).1 δ δpos with ⟨s, fs, hs⟩, -- s : set α, fs : finite s, hs : univ ⊆ ⋃ (y : α) (H : y ∈ s), eball y δ -- we first show that any set is well approximated by a subset of `s`. have main : ∀ u : set α, ∃v ⊆ s, Hausdorff_edist u v ≤ δ, { assume u, let v := {x : α | x ∈ s ∧ ∃y∈u, edist x y < δ}, existsi [v, ((λx hx, hx.1) : v ⊆ s)], refine Hausdorff_edist_le_of_mem_edist _ _, { assume x hx, have : x ∈ ⋃y ∈ s, ball y δ := hs (by simp), rcases mem_bUnion_iff.1 this with ⟨y, ⟨ys, dy⟩⟩, have : edist y x < δ := by simp at dy; rwa [edist_comm] at dy, exact ⟨y, ⟨ys, ⟨x, hx, this⟩⟩, le_of_lt dy⟩ }, { rintros x ⟨hx1, ⟨y, yu, hy⟩⟩, exact ⟨y, yu, le_of_lt hy⟩ }}, -- introduce the set F of all subsets of `s` (seen as members of `closeds α`). let F := {f : closeds α | f.val ⊆ s}, use F, split, -- `F` is finite { apply @finite_of_finite_image _ _ F (λf, f.val), { apply set.inj_on_of_injective, simp [subtype.val_injective] }, { refine finite_subset (finite_subsets_of_finite fs) (λb, _), simp only [and_imp, set.mem_image, set.mem_set_of_eq, exists_imp_distrib], assume x hx hx', rwa hx' at hx }}, -- `F` is ε-dense { assume u _, rcases main u.val with ⟨t0, t0s, Dut0⟩, have : finite t0 := finite_subset fs t0s, have : is_closed t0 := closed_of_compact _ (compact_of_finite this), let t : closeds α := ⟨t0, this⟩, have : t ∈ F := t0s, have : edist u t < ε := lt_of_le_of_lt Dut0 δlt, apply mem_bUnion_iff.2, exact ⟨t, ‹t ∈ F›, this⟩ } end⟩ /-- In an emetric space, the type of non-empty compact subsets is an emetric space, where the edistance is the Hausdorff edistance -/ instance nonempty_compacts.emetric_space : emetric_space (nonempty_compacts α) := { edist := λs t, Hausdorff_edist s.val t.val, edist_self := λs, Hausdorff_edist_self, edist_comm := λs t, Hausdorff_edist_comm, edist_triangle := λs t u, Hausdorff_edist_triangle, eq_of_edist_eq_zero := λs t h, subtype.eq $ begin have : closure (s.val) = closure (t.val) := Hausdorff_edist_zero_iff_closure_eq_closure.1 h, rwa [closure_eq_iff_is_closed.2 (closed_of_compact _ s.property.2), closure_eq_iff_is_closed.2 (closed_of_compact _ t.property.2)] at this, end } /-- `nonempty_compacts.to_closeds` is a uniform embedding (as it is an isometry) -/ lemma nonempty_compacts.to_closeds.uniform_embedding : uniform_embedding (@nonempty_compacts.to_closeds α _ _) := isometry.uniform_embedding $ λx y, rfl /-- The range of `nonempty_compacts.to_closeds` is closed in a complete space -/ lemma nonempty_compacts.is_closed_in_closeds [complete_space α] : is_closed (nonempty_compacts.to_closeds '' (univ : set (nonempty_compacts α))) := begin have : nonempty_compacts.to_closeds '' univ = {s : closeds α | s.val ≠ ∅ ∧ compact s.val}, { ext, simp only [set.image_univ, set.mem_range, ne.def, set.mem_set_of_eq], split, { rintros ⟨y, hy⟩, have : x.val = y.val := by rcases hy; simp, rw this, exact y.property }, { rintros ⟨hx1, hx2⟩, existsi (⟨x.val, ⟨hx1, hx2⟩⟩ : nonempty_compacts α), apply subtype.eq, refl }}, rw this, refine is_closed_of_closure_subset (λs hs, _), split, { -- take a set set t which is nonempty and at distance at most 1 of s rcases mem_closure_iff'.1 hs 1 ennreal.zero_lt_one with ⟨t, ht, Dst⟩, rw edist_comm at Dst, -- this set t contains a point x rcases ne_empty_iff_exists_mem.1 ht.1 with ⟨x, hx⟩, -- by the Hausdorff distance control, this point x is at distance at most 1 -- of a point y in s rcases exists_edist_lt_of_Hausdorff_edist_lt hx Dst with ⟨y, hy, _⟩, -- this shows that s is not empty exact ne_empty_of_mem hy }, { refine compact_iff_totally_bounded_complete.2 ⟨_, is_complete_of_is_closed s.property⟩, refine totally_bounded_iff.2 (λε εpos, _), -- we have to show that s is covered by finitely many eballs of radius ε -- pick a nonempty compact set t at distance at most ε/2 of s rcases mem_closure_iff'.1 hs (ε/2) (ennreal.half_pos εpos) with ⟨t, ht, Dst⟩, -- cover this space with finitely many balls of radius ε/2 rcases totally_bounded_iff.1 (compact_iff_totally_bounded_complete.1 ht.2).1 (ε/2) (ennreal.half_pos εpos) with ⟨u, fu, ut⟩, refine ⟨u, ⟨fu, λx hx, _⟩⟩, -- u : set α, fu : finite u, ut : t.val ⊆ ⋃ (y : α) (H : y ∈ u), eball y (ε / 2) -- then s is covered by the union of the balls centered at u of radius ε rcases exists_edist_lt_of_Hausdorff_edist_lt hx Dst with ⟨z, hz, Dxz⟩, rcases mem_bUnion_iff.1 (ut hz) with ⟨y, hy, Dzy⟩, have : edist x y < ε := calc edist x y ≤ edist x z + edist z y : edist_triangle _ _ _ ... < ε/2 + ε/2 : ennreal.add_lt_add Dxz Dzy ... = ε : ennreal.add_halves _, exact mem_bUnion hy this }, end /-- In a complete space, the type of nonempty compact subsets is complete. This follows from the same statement for closed subsets -/ instance nonempty_compacts.complete_space [complete_space α] : complete_space (nonempty_compacts α) := begin apply complete_space_of_is_complete_univ, apply (is_complete_image_iff nonempty_compacts.to_closeds.uniform_embedding).1, apply is_complete_of_is_closed, exact nonempty_compacts.is_closed_in_closeds end /-- In a compact space, the type of nonempty compact subsets is compact. This follows from the same statement for closed subsets -/ instance nonempty_compacts.compact_space [compact_space α] : compact_space (nonempty_compacts α) := ⟨begin rw compact_iff_compact_image_of_embedding nonempty_compacts.to_closeds.uniform_embedding.embedding, exact compact_of_closed nonempty_compacts.is_closed_in_closeds end⟩ /-- In a second countable space, the type of nonempty compact subsets is second countable -/ instance nonempty_compacts.second_countable_topology [second_countable_topology α] : second_countable_topology (nonempty_compacts α) := begin haveI : separable_space (nonempty_compacts α) := begin /- To obtain a countable dense subset of `nonempty_compacts α`, start from a countable dense subset `s` of α, and then consider all its finite nonempty subsets. This set is countable and made of nonempty compact sets. It turns out to be dense: by total boundedness, any compact set `t` can be covered by finitely many small balls, and approximations in `s` of the centers of these balls give the required finite approximation of `t`. -/ have : separable_space α := by apply_instance, rcases this.exists_countable_closure_eq_univ with ⟨s, cs, s_dense⟩, let v0 := {t : set α | finite t ∧ t ⊆ s}, let v : set (nonempty_compacts α) := {t : nonempty_compacts α | t.val ∈ v0}, refine ⟨⟨v, ⟨_, _⟩⟩⟩, { have : countable (subtype.val '' v), { refine countable_subset (λx hx, _) (countable_set_of_finite_subset cs), rcases (mem_image _ _ _).1 hx with ⟨y, ⟨hy, yx⟩⟩, rw ← yx, exact hy }, apply countable_of_injective_of_countable_image _ this, apply inj_on_of_inj_on_of_subset (injective_iff_inj_on_univ.1 subtype.val_injective) (subset_univ _) }, { refine subset.antisymm (subset_univ _) (λt ht, mem_closure_iff'.2 (λε εpos, _)), -- t is a compact nonempty set, that we have to approximate uniformly by a a set in `v`. rcases dense εpos with ⟨δ, δpos, δlt⟩, -- construct a map F associating to a point in α an approximating point in s, up to δ/2. have Exy : ∀x, ∃y, y ∈ s ∧ edist x y < δ/2, { assume x, have : x ∈ closure s := by rw s_dense; exact mem_univ _, rcases mem_closure_iff'.1 this (δ/2) (ennreal.half_pos δpos) with ⟨y, ys, hy⟩, exact ⟨y, ⟨ys, hy⟩⟩ }, let F := λx, some (Exy x), have Fspec : ∀x, F x ∈ s ∧ edist x (F x) < δ/2 := λx, some_spec (Exy x), -- cover `t` with finitely many balls. Their centers form a set `a` have : totally_bounded t.val := (compact_iff_totally_bounded_complete.1 t.property.2).1, rcases totally_bounded_iff.1 this (δ/2) (ennreal.half_pos δpos) with ⟨a, af, ta⟩, -- a : set α, af : finite a, ta : t.val ⊆ ⋃ (y : α) (H : y ∈ a), eball y (δ / 2) -- replace each center by a nearby approximation in `s`, giving a new set `b` let b := F '' a, have : finite b := finite_image _ af, have tb : ∀x ∈ t.val, ∃y ∈ b, edist x y < δ, { assume x hx, rcases mem_bUnion_iff.1 (ta hx) with ⟨z, za, Dxz⟩, existsi [F z, mem_image_of_mem _ za], calc edist x (F z) ≤ edist x z + edist z (F z) : edist_triangle _ _ _ ... < δ/2 + δ/2 : ennreal.add_lt_add Dxz (Fspec z).2 ... = δ : ennreal.add_halves _ }, -- keep only the points in `b` that are close to point in `t`, yielding a new set `c` let c := {y ∈ b | ∃x∈t.val, edist x y < δ}, have : finite c := finite_subset ‹finite b› (λx hx, hx.1), -- points in `t` are well approximated by points in `c` have tc : ∀x ∈ t.val, ∃y ∈ c, edist x y ≤ δ, { assume x hx, rcases tb x hx with ⟨y, yv, Dxy⟩, have : y ∈ c := by simp [c, -mem_image]; exact ⟨yv, ⟨x, hx, Dxy⟩⟩, exact ⟨y, this, le_of_lt Dxy⟩ }, -- points in `c` are well approximated by points in `t` have ct : ∀y ∈ c, ∃x ∈ t.val, edist y x ≤ δ, { rintros y ⟨hy1, ⟨x, xt, Dyx⟩⟩, have : edist y x ≤ δ := calc edist y x = edist x y : edist_comm _ _ ... ≤ δ : le_of_lt Dyx, exact ⟨x, xt, this⟩ }, -- it follows that their Hausdorff distance is small have : Hausdorff_edist t.val c ≤ δ := Hausdorff_edist_le_of_mem_edist tc ct, have Dtc : Hausdorff_edist t.val c < ε := lt_of_le_of_lt this δlt, -- the set `c` is not empty, as it is well approximated by a nonempty set have : c ≠ ∅, { by_contradiction h, simp only [not_not, ne.def] at h, rw [h, Hausdorff_edist_empty t.property.1] at Dtc, exact not_top_lt Dtc }, -- let `d` be the version of `c` in the type `nonempty_compacts α` let d : nonempty_compacts α := ⟨c, ⟨‹c ≠ ∅›, compact_of_finite ‹finite c›⟩⟩, have : c ⊆ s, { assume x hx, rcases (mem_image _ _ _).1 hx.1 with ⟨y, ⟨ya, yx⟩⟩, rw ← yx, exact (Fspec y).1 }, have : d ∈ v := ⟨‹finite c›, this⟩, -- we have proved that `d` is a good approximation of `t` as requested exact ⟨d, ‹d ∈ v›, Dtc⟩ }, end, apply second_countable_of_separable, end end --section end emetric --namespace namespace metric section variables {α : Type u} [metric_space α] /-- `nonempty_compacts α` inherits a metric space structure, as the Hausdorff edistance between two such sets is finite. -/ instance nonempty_compacts.metric_space : metric_space (nonempty_compacts α) := emetric_space.to_metric_space $ λx y, Hausdorff_edist_ne_top_of_ne_empty_of_bounded x.2.1 y.2.1 (bounded_of_compact x.2.2) (bounded_of_compact y.2.2) /-- The distance on `nonempty_compacts α` is the Hausdorff distance, by construction -/ lemma nonempty_compacts.dist_eq {x y : nonempty_compacts α} : dist x y = Hausdorff_dist x.val y.val := rfl lemma uniform_continuous_inf_dist_Hausdorff_dist : uniform_continuous (λp : α × (nonempty_compacts α), inf_dist p.1 (p.2).val) := begin refine uniform_continuous_of_le_add 2 _, rintros ⟨x, s⟩ ⟨y, t⟩, calc inf_dist x (s.val) ≤ inf_dist x (t.val) + Hausdorff_dist (t.val) (s.val) : inf_dist_le_inf_dist_add_Hausdorff_dist (edist_ne_top t s) ... ≤ (inf_dist y (t.val) + dist x y) + Hausdorff_dist (t.val) (s.val) : add_le_add_right inf_dist_le_inf_dist_add_dist _ ... = inf_dist y (t.val) + (dist x y + Hausdorff_dist (s.val) (t.val)) : by simp [add_comm, Hausdorff_dist_comm] ... ≤ inf_dist y (t.val) + (dist (x, s) (y, t) + dist (x, s) (y, t)) : add_le_add_left (add_le_add (by simp [dist, le_refl]) (by simp [dist, nonempty_compacts.dist_eq, le_refl])) _ ... = inf_dist y (t.val) + 2 * dist (x, s) (y, t) : by rw [← mul_two, mul_comm] end end --section end metric --namespace
96f1114ae5fc63d333495ba6208e4c80e7f94cfe
4f643cce24b2d005aeeb5004c2316a8d6cc7f3b1
/src/o_minimal/structure.lean
a787bb8e16e611b076332ca238c543fe57c2e994
[]
no_license
rwbarton/lean-omin
da209ed061d64db65a8f7f71f198064986f30eb9
fd733c6d95ef6f4743aae97de5e15df79877c00e
refs/heads/master
1,674,408,673,325
1,607,343,535,000
1,607,343,535,000
285,150,399
9
0
null
null
null
null
UTF-8
Lean
false
false
6,998
lean
import tactic.omega import data.fin import data.fintype.basic import data.set.finite import data.set.lattice import for_mathlib.equiv import for_mathlib.finvec import for_mathlib.nat open set open_locale finvec namespace o_minimal variables (R : Type*) /-- [vdD:1.2.1] A *structure* on a type R consists of a class 𝑆ₙ of *definable* subsets of Rⁿ for each n ≥ 0 such that: (S1) 𝑆ₙ is a boolean subalgebra of subsets of Rⁿ; (S2) If A belongs to 𝑆ₙ then R × A and A × R belong to 𝑆ₙ₊₁; (S3) For n ≥ 1, {(x₁, ..., xₙ) | x₁ = xₙ} belongs to 𝑆ₙ; (S4) If A belongs to 𝑆ₙ₊₁ then π(A) belongs to Sₙ, where π : Rⁿ⁺¹ → Rⁿ denotes the projection onto the first n coordinates. -/ structure struc := -- TODO: "generalize" to Type instead of Prop here? -- TODO: Try this idea: (definable : (Σ {n : ℕ}, set (R^n)) → Prop)? (definable : Π {n : ℕ} (A : set (finvec n R)), Prop) (definable_empty (n : ℕ) : definable (∅ : set (finvec n R))) (definable_union {n : ℕ} {A B : set (finvec n R)} : definable A → definable B → definable (A ∪ B)) (definable_compl {n : ℕ} {A : set (finvec n R)} : definable A → definable Aᶜ) (definable_r_prod {n : ℕ} {A : set (finvec n R)} : definable A → definable (finvec.univ_prod 1 A)) (definable_prod_r {n : ℕ} {A : set (finvec n R)} : definable A → definable (finvec.prod_univ A 1)) (definable_eq_outer {n : ℕ} : definable ({x | x 0 = x.last} : set (finvec (n + 1) R))) (definable_proj1 {n : ℕ} {A : set (finvec (n + 1) R)} : definable A → definable (finvec.left '' A)) variables {R} (S : struc R) lemma struc.convert_definable {n n' : ℕ} {A : set (finvec n R)} {A' : set (finvec n' R)} (hA' : S.definable A') (h : n = n') (e : ∀ x, x ∈ A ↔ finvec.cast h x ∈ A') : S.definable A := begin cases h, convert hA', ext x, convert e x, rw finvec.cast_id end lemma struc.definable_univ (n : ℕ) : S.definable (univ : set (finvec n R)) := begin rw ←compl_empty, exact S.definable_compl (S.definable_empty n) end lemma struc.definable_inter {n : ℕ} {A B : set (finvec n R)} (hA : S.definable A) (hB : S.definable B) : S.definable (A ∩ B) := begin rw inter_eq_compl_compl_union_compl, exact S.definable_compl (S.definable_union (S.definable_compl hA) (S.definable_compl hB)) end lemma struc.definable_diff {n : ℕ} {A B : set (finvec n R)} (hA : S.definable A) (hB : S.definable B) : S.definable (A \ B) := begin rw diff_eq, exact S.definable_inter hA (S.definable_compl hB) end lemma struc.definable_Inter {ι : Type*} [fintype ι] {n : ℕ} {A : ι → set (finvec n R)} (hA : ∀ i, S.definable (A i)) : S.definable (⋂ i, A i) := suffices ∀ {s : set ι}, set.finite s → S.definable (⋂ i ∈ s, A i), by { convert this finite_univ, simp }, λ s hs, finite.induction_on hs (by { convert S.definable_univ _, simp }) (λ i s _ _ IH, by { convert S.definable_inter (hA i) IH, simp }) lemma struc.definable_rn_prod {m n : ℕ} {A : set (finvec n R)} (hA : S.definable A) : S.definable (finvec.univ_prod m A) := begin induction m using nat.rec_plus_one with m IH, { exact (finvec.univ_prod_zero_like _).mpr hA }, { exact (finvec.univ_prod_plus_one_like _).mpr (S.definable_r_prod IH) } end lemma struc.definable_prod_rn {n m : ℕ} {A : set (finvec n R)} (hA : S.definable A) : S.definable (finvec.prod_univ A m) := begin induction m with m IH, { rw finvec.prod_univ_zero_eq, exact hA }, { rw finvec.prod_univ_plus_one_eq, exact S.definable_prod_r IH } end --- [vdD:1.2.2(i)] lemma struc.definable_external_prod {n m : ℕ} {A : set (finvec n R)} (hA : S.definable A) {B : set (finvec m R)} (hB : S.definable B) : S.definable (A ⊠ B) := S.definable_inter (S.definable_prod_rn hA) (S.definable_rn_prod hB) private lemma obvious_nat_lemma {n : ℕ} {i j : fin n} (h : i ≤ j) : n = ↑i + (↑j - ↑i + 1 + (n - 1 - ↑j)) := begin cases i with i, cases j with j, change i ≤ j at h, dsimp, omega end --- [vdD:1.2.2(ii)] lemma struc.definable_eq {n : ℕ} (i j : fin n) : S.definable {x | x i = x j} := begin wlog h : i ≤ j using i j, swap, { convert this, ext x, apply eq_comm }, have : S.definable (finvec.univ_prod i (finvec.prod_univ {x : finvec ((j - i) + 1) R | x 0 = x (fin.last _)} (n - 1 - j))), { apply S.definable_rn_prod, apply S.definable_prod_rn, apply S.definable_eq_outer }, apply S.convert_definable this (obvious_nat_lemma h), intro x, simp only [finvec.mem_prod_iff, true_and, and_true, mem_univ, mem_set_of_eq, function.comp_app], congr'; ext, { simp, refl }, { simpa using (nat.add_sub_cancel' h).symm } end lemma struc.definable_diag_rn {n : ℕ} : S.definable {x : finvec (n + n) R | x.left = x.right} := begin have : S.definable {x : finvec (n + n) R | ∀ (i : fin n), x.left i = x.right i}, { convert_to S.definable (⋂ (i : fin n), {x : finvec (n + n) R | x.left i = x.right i}), { ext, simp }, exact S.definable_Inter (λ i, S.definable_eq _ _) }, convert this, ext x, apply function.funext_iff end lemma struc.definable_proj (S : struc R) {n m : ℕ} {A : set (finvec (n + m) R)} (hA : S.definable A) : S.definable (finvec.left '' A) := begin induction m with m IH, -- Defeqs are in our favor, so just use `convert`. { convert hA, convert set.image_id _, ext x ⟨i,_⟩, refl }, { convert IH (S.definable_proj1 hA) using 1, rw ←set.image_comp, refl } end lemma struc.definable_reindex_aux {n m : ℕ} (σ : fin n → fin m) {B : set (finvec n R)} (hB : S.definable B) : S.definable {x : finvec (m + n) R | x.left ∘ σ = x.right ∧ x.right ∈ B} := begin let Z : set (finvec (m + n) R) := (⋂ (i : fin n), {z | z ((σ i).cast_add _) = z (i.nat_add _)}) ∩ finvec.univ_prod m B, have Zdef : ∀ (x : finvec m R) (y : finvec n R), x ++ y ∈ Z ↔ x ∘ σ = y ∧ y ∈ B, { intros x y, simp only [set.mem_inter_iff, set.mem_Inter, set.mem_univ, finvec.univ_prod_eq, finvec.append_mem_prod_iff, ←and_assoc, and_true], congr', rw [eq_iff_iff, function.funext_iff], apply forall_congr, intro j, change (x ++ y).left (σ j) = (x ++ y).right j ↔ _, simp }, have : S.definable Z := S.definable_inter (S.definable_Inter $ λ i, S.definable_eq _ _) (S.definable_rn_prod hB), convert this, ext z, dsimp, specialize Zdef (finvec.left z) (finvec.right z), rw finvec.left_append_right at Zdef, simp at Zdef, simp [Zdef], exact iff.rfl, end --- [vdD:1.2.2(iii)] lemma struc.definable_reindex {n m : ℕ} (σ : fin n → fin m) {B : set (finvec n R)} (hB : S.definable B) : S.definable {x | x ∘ σ ∈ B} := begin convert (S.definable_proj (S.definable_reindex_aux σ hB)), ext x, rw ←finvec.append_equiv.symm.exists_congr_left, rw prod.exists, simp only [finvec.append_equiv_symm_app, finvec.left_append], finish [] end end o_minimal
b3b003d89e02efeb13feb7b5270e54540316c64a
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/tactic/assert_exists.lean
876df3c4da70a4917023455e3603374e50bd90b1
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
5,370
lean
/- Copyright (c) 2022 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Scott Morrison -/ import tactic.core import tactic.lint.basic /-! # User commands for assert the (non-)existence of declaration or instances. These commands are used to enforce the independence of different parts of mathlib. ## Implementation notes This file provides two linters that verify that things we assert do not _yet_ exist do _eventually_ exist. This works by creating declarations of the form: * ``assert_not_exists._checked.<uniq> : name := `foo`` for `assert_not_exists foo` * `assert_no_instance._checked.<uniq> := t` for `assert_instance t` These declarations are then picked up by the linter and analyzed accordingly. The `_` in the `_checked` prefix should hide them from doc-gen. -/ section setup_tactic_parser open tactic /-- `assert_exists n` is a user command that asserts that a declaration named `n` exists in the current import scope. Be careful to use names (e.g. `rat`) rather than notations (e.g. `ℚ`). -/ @[user_command] meta def assert_exists (_ : parse $ tk "assert_exists") : lean.parser unit := do decl ← ident, d ← get_decl decl, return () /-- `assert_not_exists n` is a user command that asserts that a declaration named `n` *does not exist* in the current import scope. Be careful to use names (e.g. `rat`) rather than notations (e.g. `ℚ`). It may be used (sparingly!) in mathlib to enforce plans that certain files are independent of each other. If you encounter an error on an `assert_not_exists` command while developing mathlib, it is probably because you have introduced new import dependencies to a file. In this case, you should refactor your work (for example by creating new files rather than adding imports to existing files). You should *not* delete the `assert_not_exists` statement without careful discussion ahead of time. -/ @[user_command] meta def assert_not_exists (_ : parse $ tk "assert_not_exists") : lean.parser unit := do decl ← ident, ff ← succeeds (get_decl decl) | fail format!"Declaration {decl} is not allowed to exist in this file.", n ← tactic.mk_fresh_name, let marker := (`assert_not_exists._checked).append n, add_decl (declaration.defn marker [] `(name) `(decl) default tt), pure () /-- A linter for checking that the declarations marked `assert_not_exists` eventually exist. -/ meta def assert_not_exists.linter : linter := { test := λ d, (do let n := d.to_name, tt ← pure ((`assert_not_exists._checked).is_prefix_of n) | pure none, declaration.defn _ _ `(name) val _ _ ← pure d, n ← tactic.eval_expr name val, tt ← succeeds (get_decl n) | pure (some (format!"`{n}` does not ever exist").to_string), pure none), auto_decls := tt, no_errors_found := "All `assert_not_exists` declarations eventually exist.", errors_found := "The following declarations used in `assert_not_exists` never exist; perhaps there is a typo.", is_fast := tt } /-- `assert_instance e` is a user command that asserts that an instance `e` is available in the current import scope. Example usage: ``` assert_instance semiring ℕ ``` -/ @[user_command] meta def assert_instance (_ : parse $ tk "assert_instance") : lean.parser unit := do q ← texpr, e ← i_to_expr q, mk_instance e, return () /-- `assert_no_instance e` is a user command that asserts that an instance `e` *is not available* in the current import scope. It may be used (sparingly!) in mathlib to enforce plans that certain files are independent of each other. If you encounter an error on an `assert_no_instance` command while developing mathlib, it is probably because you have introduced new import dependencies to a file. In this case, you should refactor your work (for example by creating new files rather than adding imports to existing files). You should *not* delete the `assert_no_instance` statement without careful discussion ahead of time. Example usage: ``` assert_no_instance linear_ordered_field ℚ ``` -/ @[user_command] meta def assert_no_instance (_ : parse $ tk "assert_no_instance") : lean.parser unit := do q ← texpr, e ← i_to_expr q, i ← try_core (mk_instance e), match i with | none := do n ← tactic.mk_fresh_name, let marker := (`assert_no_instance._checked).append n, et ← infer_type e, tt ← succeeds (get_decl marker) | add_decl (declaration.defn marker [] et e default tt), pure () | some i := (fail!"Instance `{i} : {e}` is not allowed to be found in this file." : tactic unit) end /-- A linter for checking that the declarations marked `assert_no_instance` eventually exist. -/ meta def assert_no_instance.linter : linter := { test := λ d, (do let n := d.to_name, tt ← pure ((`assert_no_instance._checked).is_prefix_of n) | pure none, declaration.defn _ _ _ val _ _ ← pure d, tt ← succeeds (tactic.mk_instance val) | (some ∘ format.to_string) <$> pformat!"No instance of `{val}`", pure none), auto_decls := tt, no_errors_found := "All `assert_no_instance` instances eventually exist.", errors_found := "The following typeclass instances used in `assert_no_instance` never exist; perhaps they " ++ "are missing?", is_fast := ff } end
19334bb0c9185dafbc5f93cebff6ec5d324b70b0
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/complex/polynomial.lean
4e2e6dbb049e1a5b115d8eeb1aeb56d7b6197ac1
[ "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
5,590
lean
/- Copyright (c) 2019 Chris Hughes All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import analysis.special_functions.pow import field_theory.is_alg_closed.basic import topology.algebra.polynomial /-! # The fundamental theorem of algebra This file proves that every nonconstant complex polynomial has a root. As a consequence, the complex numbers are algebraically closed. -/ open complex polynomial metric filter is_absolute_value set open_locale classical namespace complex /- The following proof uses the method given at <https://ncatlab.org/nlab/show/fundamental+theorem+of+algebra#classical_fta_via_advanced_calculus> -/ /-- **Fundamental theorem of algebra**: every non constant complex polynomial has a root -/ lemma exists_root {f : polynomial ℂ} (hf : 0 < degree f) : ∃ z : ℂ, is_root f z := let ⟨z₀, hz₀⟩ := f.exists_forall_norm_le in exists.intro z₀ $ classical.by_contradiction $ λ hf0, have hfX : f - C (f.eval z₀) ≠ 0, from mt sub_eq_zero.1 (λ h, not_le_of_gt hf (h.symm ▸ degree_C_le)), let n := root_multiplicity z₀ (f - C (f.eval z₀)) in let g := (f - C (f.eval z₀)) /ₘ ((X - C z₀) ^ n) in have hg0 : g.eval z₀ ≠ 0, from eval_div_by_monic_pow_root_multiplicity_ne_zero _ hfX, have hg : g * (X - C z₀) ^ n = f - C (f.eval z₀), from div_by_monic_mul_pow_root_multiplicity_eq _ _, have hn0 : 0 < n, from nat.pos_of_ne_zero $ λ hn0, by simpa [g, hn0] using hg0, let ⟨δ', hδ'₁, hδ'₂⟩ := continuous_iff.1 (polynomial.continuous g) z₀ ((g.eval z₀).abs) (complex.abs_pos.2 hg0) in let δ := min (min (δ' / 2) 1) (((f.eval z₀).abs / (g.eval z₀).abs) / 2) in have hf0' : 0 < (f.eval z₀).abs, from complex.abs_pos.2 hf0, have hg0' : 0 < abs (eval z₀ g), from complex.abs_pos.2 hg0, have hfg0 : 0 < (f.eval z₀).abs / abs (eval z₀ g), from div_pos hf0' hg0', have hδ0 : 0 < δ, from lt_min (lt_min (half_pos hδ'₁) (by norm_num)) (half_pos hfg0), have hδ : ∀ z : ℂ, abs (z - z₀) = δ → abs (g.eval z - g.eval z₀) < (g.eval z₀).abs, from λ z hz, hδ'₂ z (by rw [complex.dist_eq, hz]; exact ((min_le_left _ _).trans (min_le_left _ _)).trans_lt (half_lt_self hδ'₁)), have hδ1 : δ ≤ 1, from le_trans (min_le_left _ _) (min_le_right _ _), let F : polynomial ℂ := C (f.eval z₀) + C (g.eval z₀) * (X - C z₀) ^ n in let z' := (-f.eval z₀ * (g.eval z₀).abs * δ ^ n / ((f.eval z₀).abs * g.eval z₀)) ^ (n⁻¹ : ℂ) + z₀ in have hF₁ : F.eval z' = f.eval z₀ - f.eval z₀ * (g.eval z₀).abs * δ ^ n / (f.eval z₀).abs, by simp only [F, cpow_nat_inv_pow _ hn0, div_eq_mul_inv, eval_pow, mul_assoc, mul_comm (g.eval z₀), mul_left_comm (g.eval z₀), mul_left_comm (g.eval z₀)⁻¹, mul_inv, inv_mul_cancel hg0, eval_C, eval_add, eval_neg, sub_eq_add_neg, eval_mul, eval_X, add_neg_cancel_right, neg_mul, mul_one, div_eq_mul_inv]; simp only [mul_comm, mul_left_comm, mul_assoc], have hδs : (g.eval z₀).abs * δ ^ n / (f.eval z₀).abs < 1, from (div_lt_one hf0').2 $ (lt_div_iff' hg0').1 $ calc δ ^ n ≤ δ ^ 1 : pow_le_pow_of_le_one (le_of_lt hδ0) hδ1 hn0 ... = δ : pow_one _ ... ≤ ((f.eval z₀).abs / (g.eval z₀).abs) / 2 : min_le_right _ _ ... < _ : half_lt_self (div_pos hf0' hg0'), have hF₂ : (F.eval z').abs = (f.eval z₀).abs - (g.eval z₀).abs * δ ^ n, from calc (F.eval z').abs = (f.eval z₀ - f.eval z₀ * (g.eval z₀).abs * δ ^ n / (f.eval z₀).abs).abs : congr_arg abs hF₁ ... = abs (f.eval z₀) * complex.abs (1 - (g.eval z₀).abs * δ ^ n / (f.eval z₀).abs : ℝ) : by rw [← complex.abs_mul]; exact congr_arg complex.abs (by simp [mul_add, add_mul, mul_assoc, div_eq_mul_inv, sub_eq_add_neg]) ... = _ : by rw [complex.abs_of_nonneg (sub_nonneg.2 (le_of_lt hδs)), mul_sub, mul_div_cancel' _ (ne.symm (ne_of_lt hf0')), mul_one], have hef0 : abs (eval z₀ g) * (eval z₀ f).abs ≠ 0, from mul_ne_zero (mt complex.abs_eq_zero.1 hg0) (mt complex.abs_eq_zero.1 hf0), have hz'z₀ : abs (z' - z₀) = δ, by simp [z', mul_assoc, mul_left_comm _ (_ ^ n), mul_comm _ (_ ^ n), mul_comm (eval z₀ f).abs, _root_.mul_div_cancel _ hef0, of_real_mul, neg_mul, neg_div, is_absolute_value.abv_pow complex.abs, complex.abs_of_nonneg (le_of_lt hδ0), real.pow_nat_rpow_nat_inv (le_of_lt hδ0) hn0], have hF₃ : (f.eval z' - F.eval z').abs < (g.eval z₀).abs * δ ^ n, from calc (f.eval z' - F.eval z').abs = (g.eval z' - g.eval z₀).abs * (z' - z₀).abs ^ n : by rw [← eq_sub_iff_add_eq.1 hg, ← is_absolute_value.abv_pow complex.abs, ← complex.abs_mul, sub_mul]; simp [F, eval_pow, eval_add, eval_mul, eval_sub, eval_C, eval_X, eval_neg, add_sub_cancel, sub_eq_add_neg, add_assoc] ... = (g.eval z' - g.eval z₀).abs * δ ^ n : by rw hz'z₀ ... < _ : (mul_lt_mul_right (pow_pos hδ0 _)).2 (hδ _ hz'z₀), lt_irrefl (f.eval z₀).abs $ calc (f.eval z₀).abs ≤ (f.eval z').abs : hz₀ _ ... = (F.eval z' + (f.eval z' - F.eval z')).abs : by simp ... ≤ (F.eval z').abs + (f.eval z' - F.eval z').abs : complex.abs_add _ _ ... < (f.eval z₀).abs - (g.eval z₀).abs * δ ^ n + (g.eval z₀).abs * δ ^ n : add_lt_add_of_le_of_lt (by rw hF₂) hF₃ ... = (f.eval z₀).abs : sub_add_cancel _ _ instance is_alg_closed : is_alg_closed ℂ := is_alg_closed.of_exists_root _ $ λ p _ hp, complex.exists_root $ degree_pos_of_irreducible hp end complex
7484fbfe7472b6a3bbb6cccd9e54bc7d6261d635
66a6486e19b71391cc438afee5f081a4257564ec
/homotopy/fwedge.hlean
c249aa2a8541b70928e8c5c1b8fa196acbeb74fa
[ "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
15,243
hlean
/- Copyright (c) 2016 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Favonia The Wedge Sum of a family of Pointed Types -/ import homotopy.wedge ..move_to_lib ..choice ..pointed_pi open eq is_equiv pushout pointed unit trunc_index sigma bool equiv choice unit is_trunc sigma.ops lift function pi prod definition fwedge' {I : Type} (F : I → Type*) : Type := pushout (λi, ⟨i, Point (F i)⟩) (λi, ⋆) definition pt' [constructor] {I : Type} {F : I → Type*} : fwedge' F := inr ⋆ definition fwedge [constructor] {I : Type} (F : I → Type*) : Type* := pointed.MK (fwedge' F) pt' notation `⋁` := fwedge namespace fwedge variables {I : Type} {F : I → Type*} definition il {i : I} (x : F i) : ⋁F := inl ⟨i, x⟩ definition inl (i : I) (x : F i) : ⋁F := il x definition pinl [constructor] (i : I) : F i →* ⋁F := pmap.mk (inl i) (glue i) definition glue (i : I) : inl i pt = pt :> ⋁ F := glue i protected definition rec {P : ⋁F → Type} (Pinl : Π(i : I) (x : F i), P (il x)) (Pinr : P pt) (Pglue : Πi, pathover P (Pinl i pt) (glue i) (Pinr)) (y : fwedge' F) : P y := begin induction y, induction x, apply Pinl, induction x, apply Pinr, apply Pglue end protected definition elim {P : Type} (Pinl : Π(i : I) (x : F i), P) (Pinr : P) (Pglue : Πi, Pinl i pt = Pinr) (y : fwedge' F) : P := begin induction y with x u, induction x with i x, exact Pinl i x, induction u, apply Pinr, apply Pglue end protected definition elim_glue {P : Type} {Pinl : Π(i : I) (x : F i), P} {Pinr : P} (Pglue : Πi, Pinl i pt = Pinr) (i : I) : ap (fwedge.elim Pinl Pinr Pglue) (fwedge.glue i) = Pglue i := !pushout.elim_glue protected definition rec_glue {P : ⋁F → Type} {Pinl : Π(i : I) (x : F i), P (il x)} {Pinr : P pt} (Pglue : Πi, pathover P (Pinl i pt) (glue i) (Pinr)) (i : I) : apd (fwedge.rec Pinl Pinr Pglue) (fwedge.glue i) = Pglue i := !pushout.rec_glue end fwedge attribute fwedge.rec fwedge.elim [recursor 7] [unfold 7] attribute fwedge.il fwedge.inl [constructor] namespace fwedge definition fwedge_of_wedge [unfold 3] {A B : Type*} (x : A ∨ B) : ⋁(bool.rec A B) := begin induction x with a b, { exact inl ff a }, { exact inl tt b }, { exact glue ff ⬝ (glue tt)⁻¹ } end definition wedge_of_fwedge [unfold 3] {A B : Type*} (x : ⋁(bool.rec A B)) : A ∨ B := begin induction x with b x b, { induction b, exact pushout.inl x, exact pushout.inr x }, { exact pushout.inr pt }, { induction b, exact pushout.glue ⋆, reflexivity } end definition wedge_pequiv_fwedge [constructor] (A B : Type*) : A ∨ B ≃* ⋁(bool.rec A B) := begin fapply pequiv_of_equiv, { fapply equiv.MK, { exact fwedge_of_wedge }, { exact wedge_of_fwedge }, { exact abstract begin intro x, induction x with b x b, { induction b: reflexivity }, { exact glue tt }, { apply eq_pathover_id_right, refine ap_compose fwedge_of_wedge _ _ ⬝ ap02 _ !elim_glue ⬝ph _, induction b, exact !elim_glue ⬝ph whisker_bl _ hrfl, apply square_of_eq idp } end end }, { exact abstract begin intro x, induction x with a b, { reflexivity }, { reflexivity }, { apply eq_pathover_id_right, refine ap_compose wedge_of_fwedge _ _ ⬝ ap02 _ !elim_glue ⬝ !ap_con ⬝ !elim_glue ◾ (!ap_inv ⬝ !elim_glue⁻²) ⬝ph _, exact hrfl } end end}}, { exact glue ff } end definition is_contr_fwedge_of_neg {I : Type} (P : I → Type*) (H : ¬ I) : is_contr (⋁P) := begin apply is_contr.mk pt, intro x, induction x, contradiction, reflexivity, contradiction end definition is_contr_fwedge_empty [instance] : is_contr (⋁empty.elim) := is_contr_fwedge_of_neg _ id definition fwedge_pmap [constructor] {I : Type} {F : I → Type*} {X : Type*} (f : Πi, F i →* X) : ⋁F →* X := begin fapply pmap.mk, { intro x, induction x, exact f i x, exact pt, exact respect_pt (f i) }, { reflexivity } end definition wedge_pmap [constructor] {A B : Type*} {X : Type*} (f : A →* X) (g : B →* X) : (A ∨ B) →* X := begin fapply pmap.mk, { intro x, induction x, exact (f a), exact (g a), exact (respect_pt (f) ⬝ (respect_pt g)⁻¹) }, { exact respect_pt f } end definition fwedge_pmap_beta [constructor] {I : Type} {F : I → Type*} {X : Type*} (f : Πi, F i →* X) (i : I) : fwedge_pmap f ∘* pinl i ~* f i := begin fapply phomotopy.mk, { reflexivity }, { exact !idp_con ⬝ !fwedge.elim_glue⁻¹ } end definition fwedge_pmap_eta [constructor] {I : Type} {F : I → Type*} {X : Type*} (g : ⋁F →* X) : fwedge_pmap (λi, g ∘* pinl i) ~* g := begin fapply phomotopy.mk, { intro x, induction x, reflexivity, exact (respect_pt g)⁻¹, apply eq_pathover, refine !elim_glue ⬝ph _, apply whisker_lb, exact hrfl }, { exact con.left_inv (respect_pt g) } end definition fwedge_pmap_pinl [constructor] {I : Type} {F : I → Type*} : fwedge_pmap (λi, pinl i) ~* pid (⋁ F) := begin fapply phomotopy.mk, { intro x, induction x, reflexivity, reflexivity, apply eq_pathover, apply hdeg_square, refine !elim_glue ⬝ !ap_id⁻¹ }, { reflexivity } end definition fwedge_pmap_equiv [constructor] {I : Type} (F : I → Type*) (X : Type*) : ⋁F →* X ≃ Πi, F i →* X := begin fapply equiv.MK, { intro g i, exact g ∘* pinl i }, { exact fwedge_pmap }, { intro f, apply eq_of_homotopy, intro i, apply eq_of_phomotopy, apply fwedge_pmap_beta f i }, { intro g, apply eq_of_phomotopy, exact fwedge_pmap_eta g } end definition wedge_pmap_equiv [constructor] (A B X : Type*) : ((A ∨ B) →* X) ≃ ((A →* X) × (B →* X)) := calc (A ∨ B) →* X ≃ ⋁(bool.rec A B) →* X : by exact pequiv_ppcompose_right (wedge_pequiv_fwedge A B)⁻¹ᵉ* ... ≃ Πi, (bool.rec A B) i →* X : by exact fwedge_pmap_equiv (bool.rec A B) X ... ≃ (A →* X) × (B →* X) : by exact pi_bool_left (λ i, bool.rec A B i →* X) definition fwedge_pmap_nat₂ {I : Type}(F : I → Type*){X Y : Type*} (f : X →* Y) (h : Πi, F i →* X) (w : fwedge F) : (f ∘* (fwedge_pmap h)) w = fwedge_pmap (λi, f ∘* (h i)) w := begin induction w, reflexivity, refine !respect_pt, apply eq_pathover, refine ap_compose f (fwedge_pmap h) _ ⬝ph _, refine ap (ap f) !elim_glue ⬝ph _, refine _ ⬝hp !elim_glue⁻¹, esimp, apply whisker_br, apply !hrefl end -- making the maps in hsquare 1: -- top and bottom: definition prod_pi_bool_comp_funct {A B : Type*}(X : Type*) : (A →* X) × (B →* X) → Π u, (bool.rec A B u →* X) := begin refine equiv.symm _, fapply pi_bool_left end -- left: definition prod_funct_comp {A B X Y : Type*} (f : X →* Y) : (A →* X) × (B →* X) → (A →* Y) × (B →* Y) := prod_functor (pcompose f) (pcompose f) -- right: definition left_comp_pi_bool_funct {A B X Y : Type*} (f : X →* Y) : (Π u, (bool.rec A B u →* X)) → (Π u, (bool.rec A B u →* Y)) := begin intro, intro, exact f ∘* (a u) end definition left_comp_pi_bool {A B X Y : Type*} (f : X →* Y) : Π u, ((bool.rec A B u →* X) → (bool.rec A B u →* Y)) := begin intro, intro, exact f∘* a end -- hsquare 1: definition prod_to_pi_bool_nat_square {A B X Y : Type*} (f : X →* Y) : hsquare (prod_pi_bool_comp_funct X) (prod_pi_bool_comp_funct Y) (prod_funct_comp f) (@left_comp_pi_bool_funct A B X Y f) := begin intro x, fapply eq_of_homotopy, intro u, induction u, esimp, esimp end -- hsquare 2: definition fwedge_pmap_nat_square {A B X Y : Type*} (f : X →* Y) : hsquare (fwedge_pmap_equiv (bool.rec A B) X)⁻¹ᵉ (fwedge_pmap_equiv (bool.rec A B) Y)⁻¹ᵉ (left_comp_pi_bool_funct f) (pcompose f) := begin intro h, esimp, fapply eq_of_phomotopy, fapply phomotopy.mk, exact fwedge_pmap_nat₂ (λ u, bool.rec A B u) f h, reflexivity end -- hsquare 3: definition fwedge_to_wedge_nat_square {A B X Y : Type*} (f : X →* Y) : hsquare (pequiv_ppcompose_right (wedge_pequiv_fwedge A B)) (pequiv_ppcompose_right (wedge_pequiv_fwedge A B)) (pcompose f) (pcompose f) := begin exact sorry end definition wedge_pmap_nat₂ (A B X Y : Type*) (f : X →* Y) (h : A →* X) (k : B →* X) : Π (w : A ∨ B), (f ∘* (wedge_pmap h k)) w = wedge_pmap (f ∘* h )(f ∘* k) w := have H : _, from (@prod_to_pi_bool_nat_square A B X Y f) ⬝htyh (fwedge_pmap_nat_square f) ⬝htyh (fwedge_to_wedge_nat_square f), sorry -- SA to here 7/5 definition fwedge_pmap_phomotopy {I : Type} {F : I → Type*} {X : Type*} {f g : Π i, F i →* X} (h : Π i, f i ~* g i) : fwedge_pmap f ~* fwedge_pmap g := begin fconstructor, { fapply fwedge.rec, { exact h }, { reflexivity }, { intro i, apply eq_pathover, refine _ ⬝ph _ ⬝hp _, { exact (respect_pt (g i)) }, { exact (respect_pt (f i)) }, { exact !elim_glue }, { apply square_of_eq, exact ((phomotopy.sigma_char (f i) (g i)) (h i)).2 }, { refine !elim_glue⁻¹ } } }, { reflexivity } end open trunc definition trunc_fwedge_pmap_equiv.{u} {n : ℕ₋₂} {I : Type.{u}} (H : has_choice n I) (F : I → pType.{u}) (X : pType.{u}) : trunc n (⋁F →* X) ≃ Πi, trunc n (F i →* X) := trunc_equiv_trunc n (fwedge_pmap_equiv F X) ⬝e choice_equiv (λi, F i →* X) definition fwedge_functor [constructor] {I : Type} {F F' : I → Type*} (f : Π i, F i →* F' i) : ⋁ F →* ⋁ F' := fwedge_pmap (λ i, pinl i ∘* f i) definition fwedge_functor_pid {I : Type} {F : I → Type*} : @fwedge_functor I F F (λ i, !pid) ~* !pid := calc fwedge_pmap (λ i, pinl i ∘* !pid) ~* fwedge_pmap pinl : by exact fwedge_pmap_phomotopy (λ i, pcompose_pid (pinl i)) ... ~* fwedge_pmap (λ i, !pid ∘* pinl i) : by exact fwedge_pmap_phomotopy (λ i, phomotopy.symm (pid_pcompose (pinl i))) ... ~* !pid : by exact fwedge_pmap_eta !pid definition fwedge_functor_pcompose {I : Type} {F F' F'' : I → Type*} (g : Π i, F' i →* F'' i) (f : Π i, F i →* F' i) : fwedge_functor (λ i, g i ∘* f i) ~* fwedge_functor g ∘* fwedge_functor f := calc fwedge_functor (λ i, g i ∘* f i) ~* fwedge_pmap (λ i, (pinl i ∘* g i) ∘* f i) : by exact fwedge_pmap_phomotopy (λ i, phomotopy.symm (passoc (pinl i) (g i) (f i))) ... ~* fwedge_pmap (λ i, (fwedge_functor g ∘* pinl i) ∘* f i) : by exact fwedge_pmap_phomotopy (λ i, pwhisker_right (f i) (phomotopy.symm (fwedge_pmap_beta (λ i, pinl i ∘* g i) i))) ... ~* fwedge_pmap (λ i, fwedge_functor g ∘* (pinl i ∘* f i)) : by exact fwedge_pmap_phomotopy (λ i, passoc (fwedge_functor g) (pinl i) (f i)) ... ~* fwedge_pmap (λ i, fwedge_functor g ∘* (fwedge_functor f ∘* pinl i)) : by exact fwedge_pmap_phomotopy (λ i, pwhisker_left (fwedge_functor g) (phomotopy.symm (fwedge_pmap_beta (λ i, pinl i ∘* f i) i))) ... ~* fwedge_pmap (λ i, (fwedge_functor g ∘* fwedge_functor f) ∘* pinl i) : by exact fwedge_pmap_phomotopy (λ i, (phomotopy.symm (passoc (fwedge_functor g) (fwedge_functor f) (pinl i)))) ... ~* fwedge_functor g ∘* fwedge_functor f : by exact fwedge_pmap_eta (fwedge_functor g ∘* fwedge_functor f) definition fwedge_functor_phomotopy {I : Type} {F F' : I → Type*} {f g : Π i, F i →* F' i} (h : Π i, f i ~* g i) : fwedge_functor f ~* fwedge_functor g := fwedge_pmap_phomotopy (λ i, pwhisker_left (pinl i) (h i)) definition fwedge_pequiv [constructor] {I : Type} {F F' : I → Type*} (f : Π i, F i ≃* F' i) : ⋁ F ≃* ⋁ F' := let pto := fwedge_functor (λ i, f i) in let pfrom := fwedge_functor (λ i, (f i)⁻¹ᵉ*) in begin fapply pequiv_of_pmap, exact pto, fapply adjointify, exact pfrom, { intro y, refine (fwedge_functor_pcompose (λ i, f i) (λ i, (f i)⁻¹ᵉ*) y)⁻¹ ⬝ _, refine fwedge_functor_phomotopy (λ i, pright_inv (f i)) y ⬝ _, exact fwedge_functor_pid y }, { intro y, refine (fwedge_functor_pcompose (λ i, (f i)⁻¹ᵉ*) (λ i, f i) y)⁻¹ ⬝ _, refine fwedge_functor_phomotopy (λ i, pleft_inv (f i)) y ⬝ _, exact fwedge_functor_pid y } end definition plift_fwedge.{u v} {I : Type} (F : I → pType.{u}) : plift.{u v} (⋁ F) ≃* ⋁ (plift.{u v} ∘ F) := calc plift.{u v} (⋁ F) ≃* ⋁ F : by exact !pequiv_plift ⁻¹ᵉ* ... ≃* ⋁ (λ i, plift.{u v} (F i)) : by exact fwedge_pequiv (λ i, !pequiv_plift) definition fwedge_down_left.{u v} {I : Type} (F : I → pType) : ⋁ (F ∘ down.{u v}) ≃* ⋁ F := proof let pto := @fwedge_pmap (lift.{u v} I) (F ∘ down) (⋁ F) (λ i, pinl (down i)) in let pfrom := @fwedge_pmap I F (⋁ (F ∘ down.{u v})) (λ i, pinl (up.{u v} i)) in begin fapply pequiv_of_pmap, { exact pto }, fapply adjointify, { exact pfrom }, { intro x, exact calc pto (pfrom x) = fwedge_pmap (λ i, (pto ∘* pfrom) ∘* pinl i) x : by exact (fwedge_pmap_eta (pto ∘* pfrom) x)⁻¹ ... = fwedge_pmap (λ i, pto ∘* (pfrom ∘* pinl i)) x : by exact fwedge_pmap_phomotopy (λ i, passoc pto pfrom (pinl i)) x ... = fwedge_pmap (λ i, pto ∘* pinl (up.{u v} i)) x : by exact fwedge_pmap_phomotopy (λ i, pwhisker_left pto (fwedge_pmap_beta (λ i, pinl (up.{u v} i)) i)) x ... = fwedge_pmap pinl x : by exact fwedge_pmap_phomotopy (λ i, fwedge_pmap_beta (λ i, (pinl (down.{u v} i))) (up.{u v} i)) x ... = x : by exact fwedge_pmap_pinl x }, { intro x, exact calc pfrom (pto x) = fwedge_pmap (λ i, (pfrom ∘* pto) ∘* pinl i) x : by exact (fwedge_pmap_eta (pfrom ∘* pto) x)⁻¹ ... = fwedge_pmap (λ i, pfrom ∘* (pto ∘* pinl i)) x : by exact fwedge_pmap_phomotopy (λ i, passoc pfrom pto (pinl i)) x ... = fwedge_pmap (λ i, pfrom ∘* pinl (down.{u v} i)) x : by exact fwedge_pmap_phomotopy (λ i, pwhisker_left pfrom (fwedge_pmap_beta (λ i, pinl (down.{u v} i)) i)) x ... = fwedge_pmap pinl x : by exact fwedge_pmap_phomotopy (λ i, begin induction i with i, exact fwedge_pmap_beta (λ i, (pinl (up.{u v} i))) i end ) x ... = x : by exact fwedge_pmap_pinl x } end qed end fwedge
f3dcdf1ec5312263bd52bdd47baae7c745b911fb
df7bb3acd9623e489e95e85d0bc55590ab0bc393
/lean/love07_metaprogramming_exercise_solution.lean
b415e418010f99b219e2dd17eef0c1e6bc0e4291
[]
no_license
MaschavanderMarel/logical_verification_2020
a41c210b9237c56cb35f6cd399e3ac2fe42e775d
7d562ef174cc6578ca6013f74db336480470b708
refs/heads/master
1,692,144,223,196
1,634,661,675,000
1,634,661,675,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,504
lean
import .love07_metaprogramming_demo /- # LoVe Exercise 7: Metaprogramming -/ set_option pp.beta true set_option pp.generalized_field_notation false 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. -/ meta def expr.repr : expr → string | (expr.var n) := "(var " ++ repr n ++ ")" | (expr.sort l) := "sort" | (expr.const n ls) := "(const " ++ n.to_string ++ ")" | (expr.mvar n m t) := "(mvar " ++ name.to_string n ++ " " ++ name.to_string m ++ " " ++ expr.repr t ++ ")" | (expr.local_const n m bi t) := "(local_const " ++ name.to_string n ++ " " ++ name.to_string m ++ " " ++ expr.repr t ++ ")" | (expr.app e f) := "(app " ++ expr.repr e ++ " " ++ expr.repr f ++ ")" | (expr.lam n bi e t) := "(lam " ++ name.to_string n ++ " " ++ expr.repr e ++ " " ++ expr.repr t ++ ")" | (expr.pi n bi e t) := "(pi " ++ name.to_string n ++ " " ++ expr.repr e ++ " " ++ expr.repr t ++ ")" | (expr.elet n g e f) := "(elet " ++ name.to_string n ++ " " ++ expr.repr g ++ " " ++ expr.repr e ++ " " ++ expr.repr f ++ ")" | (expr.macro d args) := "macro" /- 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 -/ lemma abc_ac₂ (a b c : Prop) (h : a ∧ b ∧ c) : a ∧ c := sorry /- 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 := 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 ()`. -/ meta def destruct_ands : tactic unit := tactic.repeat (do hs ← tactic.local_context, h ← list.mfirst (λh, do `(_ ∧ _) ← tactic.infer_type h, pure h) hs, tactic.cases h, pure ()) -- Alternative solutions: meta def destruct_ands₂ : tactic unit := tactic.try (do hs ← tactic.local_context, h ← list.mfirst (λh, do `(_ ∧ _) ← tactic.infer_type h, pure h) hs, tactic.cases h, destruct_ands₂) meta def destruct_ands₃ : tactic unit := (do hs ← tactic.local_context, h ← list.mfirst (λh, do `(_ ∧ _) ← tactic.infer_type h, pure h) hs, tactic.cases h, destruct_ands₃) <|> 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 /- 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.all_goals (tactic.try tactic.assumption), pure () lemma abcd_bd₃ (a b c d : Prop) (h : a ∧ (b ∧ c) ∧ d) : b ∧ d := 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. -/ lemma ab (a b : Prop) (h : a ∨ b) : a ∨ b := by destro_and lemma abcdef_1 (a b c d e f : Prop) (h : a ∧ b ∧ c ∧ d ∧ e ∧ f) : f ∧ e ∧ f ∧ a ∧ d ∧ b ∧ c ∧ a := by destro_and lemma abcdef_2 (a b c d e f : Prop) (h : a ∧ ((b ∧ ((c ∧ d) ∧ e)) ∧ f)) : f ∧ e ∧ f ∧ a ∧ d ∧ b ∧ c ∧ a := by destro_and lemma abcdef_3 (a b c d e f : Prop) (h : a ∧ (b ∧ (c ∧ (d ∧ e ∧ f)))) : f ∧ (e ∧ (f ∧ (a ∧ d ∧ b ∧ c ∧ a))) := by destro_and /- ## 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 that 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. -/ meta def term_contains (e : expr) (nam : name) : bool := expr.fold e ff (λe' d c, c || expr.is_constant_of e' nam) /- 3.2 (**optional**). Write a metafunction that checks whether an expression contains **all** constants in a list. You can use `list.band` (Boolean and). -/ meta def term_contains_all (nams : list name) (e : expr) : bool := list.band (list.map (term_contains e) nams) /- 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. -/ meta def list_constants (nams : list name) (e : environment) : list name := environment.fold e [] (λdecl nams', if term_contains_all nams decl.type then decl.to_name :: nams' else nams') /- 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] end LoVe
f6c461f786fd2d54df69611c6f7abb9fec294df0
43390109ab88557e6090f3245c47479c123ee500
/src/Topology/Material/pasting_lemma.lean
b7124eb13c208a6c8f83fd1e4ee68666bc659bd3
[ "Apache-2.0" ]
permissive
Ja1941/xena-UROP-2018
41f0956519f94d56b8bf6834a8d39473f4923200
b111fb87f343cf79eca3b886f99ee15c1dd9884b
refs/heads/master
1,662,355,955,139
1,590,577,325,000
1,590,577,325,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,310
lean
/- Copyright (c) 2018 Luca Gerolla. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Mario Carneiro, Luca Gerolla Prove part of pasting lemma (ex 10.7 Sutherland) for continuity proofs -/ import data.set.basic import analysis.topology.continuity open set definition restriction {X Y : Type*} (f : X → Y) (A : set X) : A → Y := λ a, f a.val lemma preimage_sub (X Y : Type*) (f : X → Y) (C : set Y) (A : set X) : (restriction f A) ⁻¹' C = { a : A | a.val ∈ f⁻¹' C} := by finish lemma and_congr_right_iff {a b c : Prop} : (a ∧ b ↔ a ∧ c) ↔ (a → (b ↔ c)) := ⟨λ h ha, by simp [ha] at h; exact h, and_congr_right⟩ theorem handy (X : Type*) (U A B : set X) : U ∩ A = U ∩ B ↔ {u : U | u.val ∈ A} = {u : U | u.val ∈ B} := sorry --by simp [set.set_eq_def, and_congr_right_iff] lemma restriction_closed {X Y : Type*} (f : X → Y) [topological_space X] [topological_space Y] (A : set X) (C : set Y) (HAcont : continuous (restriction f A)) (HAclosed : is_closed A) (HCclosed : is_closed C) : is_closed (f ⁻¹' C ∩ A) := begin have H : is_closed ((restriction f A) ⁻¹' C), exact continuous_iff_is_closed.1 HAcont C HCclosed, have H2 := is_closed_induced_iff.1 H, cases H2 with D HD, suffices : f ⁻¹' C ∩ A = D ∩ A, rw this, exact is_closed_inter HD.1 HAclosed, have H₂ : { a : A | a.val ∈ f⁻¹' C} = { a : A | a.val ∈ D}, rw ←preimage_sub X Y f C A, rw HD.2, refl, rw set.inter_comm, rw set.inter_comm D A, rwa handy, end theorem continuous_closed_union {X Y : Type*} [topological_space X] [topological_space Y] {A B : set X} (f : X → Y) (Hunion : A ∪ B = set.univ) (HAclosed : is_closed A) (HBclosed : is_closed B) : continuous (restriction f A) → continuous (restriction f B) → continuous f := begin intros HAcont HBcont, apply continuous_iff_is_closed.2, intros C HC, have H : f⁻¹' C = ((f⁻¹' C) ∩ A) ∪ ((f⁻¹' C) ∩ B), rw ←set.inter_distrib_left, rw Hunion, exact (set.inter_univ _).symm, rw H, apply is_closed_union, exact restriction_closed f A C HAcont HAclosed HC, exact restriction_closed f B C HBcont HBclosed HC, end ---- Mario Carneiro (21/07/2018) help --- Attempt to define function (f : α → β ) in terms of its restriction -- check two restrictions match def match_of_fun {X Y} {A B : set X} (fa : A → Y) (fb : B → Y) : Prop := ∀ x h₁ h₂, fa ⟨x, h₁⟩ = fb ⟨x, h₂⟩ local attribute [instance] classical.prop_decidable -- define function of pasted restrictions noncomputable def paste {X Y} {A B : set X} (Hunion : A ∪ B = set.univ) (fa : A → Y) (fb : B → Y) (t : X) : Y := if h₁ : t ∈ A then fa ⟨t, h₁⟩ else have t ∈ A ∪ B, from set.eq_univ_iff_forall.1 Hunion t, have h₂ : t ∈ B, from this.resolve_left h₁, fb ⟨t, h₂⟩ -- check paste agrees with fa theorem paste_left {X Y} {A B : set X} (Hunion : A ∪ B = set.univ) (fa : A → Y) (fb : B → Y) (t : X) (h : t ∈ A) : paste Hunion fa fb t = fa ⟨t, h⟩ := dif_pos _ -- check paste agrees with fb theorem paste_right {X Y} {A B : set X} (Hunion : A ∪ B = set.univ) (fa : A → Y) (fb : B → Y) (H : match_of_fun fa fb) (t : X) (h : t ∈ B) : paste Hunion fa fb t = fb ⟨t, h⟩ := by by_cases h' : t ∈ A; simp [paste, h']; apply H lemma rest_of_paste {X : Type* } {Y : Type*} {A B : set X} {Hunion : A ∪ B = set.univ} (fa : A → Y) (fb : B → Y) { f : X → Y } (H : match_of_fun fa fb) ( Hf : f = paste Hunion fa fb ) : fa = restriction f A ∧ fb = restriction f B := begin split, funext, unfold restriction, rw Hf, apply eq.symm _, simp [paste_left Hunion fa fb x.val x.2], funext, unfold restriction, rw Hf, apply eq.symm _, simp [paste_right Hunion fa fb H x.val x.2], end -- prove continuity when pasted continuous restrictions on closed sets theorem cont_of_paste₂ {X : Type* } {Y : Type*} [topological_space X] [topological_space Y] { A B : set X } { Hunion : A ∪ B = set.univ} {fa : A → Y } { fb : B → Y } {HAclosed : is_closed A} {HBclosed : is_closed B} { HM: match_of_fun fa fb } { f : X → Y } ( Hf : f = paste Hunion fa fb ) : continuous fa → continuous fb → continuous f := begin intros CA CB, have ResA : fa = (restriction f A) , exact (rest_of_paste fa fb HM Hf ).1, have ResB : fb = (restriction f B), exact (rest_of_paste fa fb HM Hf ).2, rw ResA at CA, rw ResB at CB, exact continuous_closed_union f Hunion HAclosed HBclosed CA CB end theorem cont_of_paste {X : Type* } {Y : Type*} [topological_space X] [topological_space Y] { A B : set X } { Hunion : A ∪ B = set.univ} {fa : A → Y } { fb : B → Y } (HAclosed : is_closed A) (HBclosed : is_closed B) ( HM : match_of_fun fa fb ) ( CA : continuous fa ) ( CB : continuous fb) : continuous (paste Hunion fa fb) := begin let f := paste Hunion fa fb, have Hf : f = paste Hunion fa fb, trivial, have ResA : fa = (restriction f A) , exact (rest_of_paste fa fb HM Hf ).1, have ResB : fb = (restriction f B), exact (rest_of_paste fa fb HM Hf ).2, rw ResA at CA, rwa ResB at CB, exact continuous_closed_union f Hunion HAclosed HBclosed CA CB end
73796d5885ef66b72ff6782ccc0546fcdbee0c06
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/measure_theory/measure/stieltjes.lean
9cb566b2ffc1870cb5e1ce6dc8d6deb42beff32e
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
16,782
lean
/- Copyright (c) 2021 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Yury Kudryashov, Sébastien Gouëzel -/ import measure_theory.constructions.borel_space /-! # Stieltjes measures on the real line Consider a function `f : ℝ → ℝ` which is monotone and right-continuous. Then one can define a corrresponding measure, giving mass `f b - f a` to the interval `(a, b]`. ## Main definitions * `stieltjes_function` is a structure containing a function from `ℝ → ℝ`, together with the assertions that it is monotone and right-continuous. To `f : stieltjes_function`, one associates a Borel measure `f.measure`. * `f.left_lim x` is the limit of `f` to the left of `x`. * `f.measure_Ioc` asserts that `f.measure (Ioc a b) = of_real (f b - f a)` * `f.measure_Ioo` asserts that `f.measure (Ioo a b) = of_real (f.left_lim b - f a)`. * `f.measure_Icc` and `f.measure_Ico` are analogous. -/ noncomputable theory open classical set filter open ennreal (of_real) open_locale big_operators ennreal nnreal topological_space /-! ### Basic properties of Stieltjes functions -/ /-- Bundled monotone right-continuous real functions, used to construct Stieltjes measures. -/ structure stieltjes_function := (to_fun : ℝ → ℝ) (mono' : monotone to_fun) (right_continuous' : ∀ x, continuous_within_at to_fun (Ici x) x) namespace stieltjes_function instance : has_coe_to_fun stieltjes_function (λ _, ℝ → ℝ) := ⟨to_fun⟩ initialize_simps_projections stieltjes_function (to_fun → apply) variable (f : stieltjes_function) lemma mono : monotone f := f.mono' lemma right_continuous (x : ℝ) : continuous_within_at f (Ici x) x := f.right_continuous' x /-- The limit of a Stieltjes function to the left of `x` (it exists by monotonicity). The fact that it is indeed a left limit is asserted in `tendsto_left_lim` -/ @[irreducible] def left_lim (x : ℝ) := Sup (f '' (Iio x)) lemma tendsto_left_lim (x : ℝ) : tendsto f (𝓝[Iio x] x) (𝓝 (f.left_lim x)) := by { rw left_lim, exact f.mono.tendsto_nhds_within_Iio x } lemma left_lim_le {x y : ℝ} (h : x ≤ y) : f.left_lim x ≤ f y := begin apply le_of_tendsto (f.tendsto_left_lim x), filter_upwards [self_mem_nhds_within], assume z hz, exact (f.mono (le_of_lt hz)).trans (f.mono h) end lemma le_left_lim {x y : ℝ} (h : x < y) : f x ≤ f.left_lim y := begin apply ge_of_tendsto (f.tendsto_left_lim y), apply mem_nhds_within_Iio_iff_exists_Ioo_subset.2 ⟨x, h, _⟩, assume z hz, exact f.mono hz.1.le, end lemma left_lim_le_left_lim {x y : ℝ} (h : x ≤ y) : f.left_lim x ≤ f.left_lim y := begin rcases eq_or_lt_of_le h with rfl|hxy, { exact le_rfl }, { exact (f.left_lim_le le_rfl).trans (f.le_left_lim hxy) } end /-- The identity of `ℝ` as a Stieltjes function, used to construct Lebesgue measure. -/ @[simps] protected def id : stieltjes_function := { to_fun := id, mono' := λ x y, id, right_continuous' := λ x, continuous_within_at_id } @[simp] lemma id_left_lim (x : ℝ) : stieltjes_function.id.left_lim x = x := tendsto_nhds_unique (stieltjes_function.id.tendsto_left_lim x) $ (continuous_at_id).tendsto.mono_left nhds_within_le_nhds instance : inhabited stieltjes_function := ⟨stieltjes_function.id⟩ /-! ### The outer measure associated to a Stieltjes function -/ /-- Length of an interval. This is the largest monotone function which correctly measures all intervals. -/ def length (s : set ℝ) : ℝ≥0∞ := ⨅a b (h : s ⊆ Ioc a b), of_real (f b - f a) @[simp] lemma length_empty : f.length ∅ = 0 := nonpos_iff_eq_zero.1 $ infi_le_of_le 0 $ infi_le_of_le 0 $ by simp @[simp] lemma length_Ioc (a b : ℝ) : f.length (Ioc a b) = of_real (f b - f a) := begin refine le_antisymm (infi_le_of_le a $ binfi_le b (subset.refl _)) (le_infi $ λ a', le_infi $ λ b', le_infi $ λ h, ennreal.coe_le_coe.2 _), cases le_or_lt b a with ab ab, { rw real.to_nnreal_of_nonpos (sub_nonpos.2 (f.mono ab)), apply zero_le, }, cases (Ioc_subset_Ioc_iff ab).1 h with h₁ h₂, exact real.to_nnreal_le_to_nnreal (sub_le_sub (f.mono h₁) (f.mono h₂)) end lemma length_mono {s₁ s₂ : set ℝ} (h : s₁ ⊆ s₂) : f.length s₁ ≤ f.length s₂ := infi_le_infi $ λ a, infi_le_infi $ λ b, infi_le_infi2 $ λ h', ⟨subset.trans h h', le_refl _⟩ open measure_theory /-- The Stieltjes outer measure associated to a Stieltjes function. -/ protected def outer : outer_measure ℝ := outer_measure.of_function f.length f.length_empty lemma outer_le_length (s : set ℝ) : f.outer s ≤ f.length s := outer_measure.of_function_le _ /-- If a compact interval `[a, b]` is covered by a union of open interval `(c i, d i)`, then `f b - f a ≤ ∑ f (d i) - f (c i)`. This is an auxiliary technical statement to prove the same statement for half-open intervals, the point of the current statement being that one can use compactness to reduce it to a finite sum, and argue by induction on the size of the covering set. -/ lemma length_subadditive_Icc_Ioo {a b : ℝ} {c d : ℕ → ℝ} (ss : Icc a b ⊆ ⋃ i, Ioo (c i) (d i)) : of_real (f b - f a) ≤ ∑' i, of_real (f (d i) - f (c i)) := begin suffices : ∀ (s:finset ℕ) b (cv : Icc a b ⊆ ⋃ i ∈ (↑s:set ℕ), Ioo (c i) (d i)), (of_real (f b - f a) : ℝ≥0∞) ≤ ∑ i in s, of_real (f (d i) - f (c i)), { rcases is_compact_Icc.elim_finite_subcover_image (λ (i : ℕ) (_ : i ∈ univ), @is_open_Ioo _ _ _ _ (c i) (d i)) (by simpa using ss) with ⟨s, su, hf, hs⟩, have e : (⋃ i ∈ (↑hf.to_finset:set ℕ), Ioo (c i) (d i)) = (⋃ i ∈ s, Ioo (c i) (d i)), by simp only [ext_iff, exists_prop, finset.set_bUnion_coe, mem_Union, forall_const, iff_self, finite.mem_to_finset], rw ennreal.tsum_eq_supr_sum, refine le_trans _ (le_supr _ hf.to_finset), exact this hf.to_finset _ (by simpa only [e]) }, clear ss b, refine λ s, finset.strong_induction_on s (λ s IH b cv, _), cases le_total b a with ab ab, { rw ennreal.of_real_eq_zero.2 (sub_nonpos.2 (f.mono ab)), exact zero_le _, }, have := cv ⟨ab, le_refl _⟩, simp at this, rcases this with ⟨i, is, cb, bd⟩, rw [← finset.insert_erase is] at cv ⊢, rw [finset.coe_insert, bUnion_insert] at cv, rw [finset.sum_insert (finset.not_mem_erase _ _)], refine le_trans _ (add_le_add_left (IH _ (finset.erase_ssubset is) (c i) _) _), { refine le_trans (ennreal.of_real_le_of_real _) ennreal.of_real_add_le, rw sub_add_sub_cancel, exact sub_le_sub_right (f.mono bd.le) _ }, { rintro x ⟨h₁, h₂⟩, refine (cv ⟨h₁, le_trans h₂ (le_of_lt cb)⟩).resolve_left (mt and.left (not_lt_of_le h₂)) } end @[simp] lemma outer_Ioc (a b : ℝ) : f.outer (Ioc a b) = of_real (f b - f a) := begin /- It suffices to show that, if `(a, b]` is covered by sets `s i`, then `f b - f a` is bounded by `∑ f.length (s i) + ε`. The difficulty is that `f.length` is expressed in terms of half-open intervals, while we would like to have a compact interval covered by open intervals to use compactness and finite sums, as provided by `length_subadditive_Icc_Ioo`. The trick is to use the right-continuity of `f`. If `a'` is close enough to `a` on its right, then `[a', b]` is still covered by the sets `s i` and moreover `f b - f a'` is very close to `f b - f a` (up to `ε/2`). Also, by definition one can cover `s i` by a half-closed interval `(p i, q i]` with `f`-length very close to that of `s i` (within a suitably small `ε' i`, say). If one moves `q i` very slightly to the right, then the `f`-length will change very little by right continuity, and we will get an open interval `(p i, q' i)` covering `s i` with `f (q' i) - f (p i)` within `ε' i` of the `f`-length of `s i`. -/ refine le_antisymm (by { rw ← f.length_Ioc, apply outer_le_length }) (le_binfi $ λ s hs, ennreal.le_of_forall_pos_le_add $ λ ε εpos h, _), let δ := ε / 2, have δpos : 0 < (δ : ℝ≥0∞), by simpa using εpos.ne', rcases ennreal.exists_pos_sum_of_encodable δpos.ne' ℕ with ⟨ε', ε'0, hε⟩, obtain ⟨a', ha', aa'⟩ : ∃ a', f a' - f a < δ ∧ a < a', { have A : continuous_within_at (λ r, f r - f a) (Ioi a) a, { refine continuous_within_at.sub _ continuous_within_at_const, exact (f.right_continuous a).mono Ioi_subset_Ici_self }, have B : f a - f a < δ, by rwa [sub_self, nnreal.coe_pos, ← ennreal.coe_pos], exact (((tendsto_order.1 A).2 _ B).and self_mem_nhds_within).exists }, have : ∀ i, ∃ p:ℝ×ℝ, s i ⊆ Ioo p.1 p.2 ∧ (of_real (f p.2 - f p.1) : ℝ≥0∞) < f.length (s i) + ε' i, { intro i, have := (ennreal.lt_add_right ((ennreal.le_tsum i).trans_lt h).ne (ennreal.coe_ne_zero.2 (ε'0 i).ne')), conv at this { to_lhs, rw length }, simp only [infi_lt_iff, exists_prop] at this, rcases this with ⟨p, q', spq, hq'⟩, have : continuous_within_at (λ r, of_real (f r - f p)) (Ioi q') q', { apply ennreal.continuous_of_real.continuous_at.comp_continuous_within_at, refine continuous_within_at.sub _ continuous_within_at_const, exact (f.right_continuous q').mono Ioi_subset_Ici_self }, rcases (((tendsto_order.1 this).2 _ hq').and self_mem_nhds_within).exists with ⟨q, hq, q'q⟩, exact ⟨⟨p, q⟩, spq.trans (Ioc_subset_Ioo_right q'q), hq⟩ }, choose g hg using this, have I_subset : Icc a' b ⊆ ⋃ i, Ioo (g i).1 (g i).2 := calc Icc a' b ⊆ Ioc a b : λ x hx, ⟨aa'.trans_le hx.1, hx.2⟩ ... ⊆ ⋃ i, s i : hs ... ⊆ ⋃ i, Ioo (g i).1 (g i).2 : Union_subset_Union (λ i, (hg i).1), calc of_real (f b - f a) = of_real ((f b - f a') + (f a' - f a)) : by rw sub_add_sub_cancel ... ≤ of_real (f b - f a') + of_real (f a' - f a) : ennreal.of_real_add_le ... ≤ (∑' i, of_real (f (g i).2 - f (g i).1)) + of_real δ : add_le_add (f.length_subadditive_Icc_Ioo I_subset) (ennreal.of_real_le_of_real ha'.le) ... ≤ (∑' i, (f.length (s i) + ε' i)) + δ : add_le_add (ennreal.tsum_le_tsum (λ i, (hg i).2.le)) (by simp only [ennreal.of_real_coe_nnreal, le_rfl]) ... = (∑' i, f.length (s i)) + (∑' i, ε' i) + δ : by rw [ennreal.tsum_add] ... ≤ (∑' i, f.length (s i)) + δ + δ : add_le_add (add_le_add le_rfl hε.le) le_rfl ... = ∑' (i : ℕ), f.length (s i) + ε : by simp [add_assoc, ennreal.add_halves] end lemma measurable_set_Ioi {c : ℝ} : f.outer.caratheodory.measurable_set' (Ioi c) := begin apply outer_measure.of_function_caratheodory (λ t, _), refine le_infi (λ a, le_infi (λ b, le_infi (λ h, _))), refine le_trans (add_le_add (f.length_mono $ inter_subset_inter_left _ h) (f.length_mono $ diff_subset_diff_left h)) _, cases le_total a c with hac hac; cases le_total b c with hbc hbc, { simp only [Ioc_inter_Ioi, f.length_Ioc, hac, sup_eq_max, hbc, le_refl, Ioc_eq_empty, max_eq_right, min_eq_left, Ioc_diff_Ioi, f.length_empty, zero_add, not_lt] }, { simp only [hac, hbc, Ioc_inter_Ioi, Ioc_diff_Ioi, f.length_Ioc, min_eq_right, sup_eq_max, ←ennreal.of_real_add, f.mono hac, f.mono hbc, sub_nonneg, sub_add_sub_cancel, le_refl, max_eq_right] }, { simp only [hbc, le_refl, Ioc_eq_empty, Ioc_inter_Ioi, min_eq_left, Ioc_diff_Ioi, f.length_empty, zero_add, or_true, le_sup_iff, f.length_Ioc, not_lt] }, { simp only [hac, hbc, Ioc_inter_Ioi, Ioc_diff_Ioi, f.length_Ioc, min_eq_right, sup_eq_max, le_refl, Ioc_eq_empty, add_zero, max_eq_left, f.length_empty, not_lt] } end theorem outer_trim : f.outer.trim = f.outer := begin refine le_antisymm (λ s, _) (outer_measure.le_trim _), rw outer_measure.trim_eq_infi, refine le_infi (λ t, le_infi $ λ ht, ennreal.le_of_forall_pos_le_add $ λ ε ε0 h, _), rcases ennreal.exists_pos_sum_of_encodable (ennreal.coe_pos.2 ε0).ne' ℕ with ⟨ε', ε'0, hε⟩, refine le_trans _ (add_le_add_left (le_of_lt hε) _), rw ← ennreal.tsum_add, choose g hg using show ∀ i, ∃ s, t i ⊆ s ∧ measurable_set s ∧ f.outer s ≤ f.length (t i) + of_real (ε' i), { intro i, have := (ennreal.lt_add_right ((ennreal.le_tsum i).trans_lt h).ne (ennreal.coe_pos.2 (ε'0 i)).ne'), conv at this {to_lhs, rw length}, simp only [infi_lt_iff] at this, rcases this with ⟨a, b, h₁, h₂⟩, rw ← f.outer_Ioc at h₂, exact ⟨_, h₁, measurable_set_Ioc, le_of_lt $ by simpa using h₂⟩ }, simp at hg, apply infi_le_of_le (Union g) _, apply infi_le_of_le (subset.trans ht $ Union_subset_Union (λ i, (hg i).1)) _, apply infi_le_of_le (measurable_set.Union (λ i, (hg i).2.1)) _, exact le_trans (f.outer.Union _) (ennreal.tsum_le_tsum $ λ i, (hg i).2.2) end lemma borel_le_measurable : borel ℝ ≤ f.outer.caratheodory := begin rw borel_eq_generate_Ioi, refine measurable_space.generate_from_le _, simp [f.measurable_set_Ioi] { contextual := tt } end /-! ### The measure associated to a Stieltjes function -/ /-- The measure associated to a Stieltjes function, giving mass `f b - f a` to the interval `(a, b]`. -/ @[irreducible] protected def measure : measure ℝ := { to_outer_measure := f.outer, m_Union := λ s hs, f.outer.Union_eq_of_caratheodory $ λ i, f.borel_le_measurable _ (hs i), trimmed := f.outer_trim } @[simp] lemma measure_Ioc (a b : ℝ) : f.measure (Ioc a b) = of_real (f b - f a) := by { rw stieltjes_function.measure, exact f.outer_Ioc a b } @[simp] lemma measure_singleton (a : ℝ) : f.measure {a} = of_real (f a - f.left_lim a) := begin obtain ⟨u, u_mono, u_lt_a, u_lim⟩ : ∃ (u : ℕ → ℝ), strict_mono u ∧ (∀ (n : ℕ), u n < a) ∧ tendsto u at_top (𝓝 a) := exists_seq_strict_mono_tendsto a, have A : {a} = ⋂ n, Ioc (u n) a, { refine subset.antisymm (λ x hx, by simp [mem_singleton_iff.1 hx, u_lt_a]) (λ x hx, _), simp at hx, have : a ≤ x := le_of_tendsto' u_lim (λ n, (hx n).1.le), simp [le_antisymm this (hx 0).2] }, have L1 : tendsto (λ n, f.measure (Ioc (u n) a)) at_top (𝓝 (f.measure {a})), { rw A, refine tendsto_measure_Inter (λ n, measurable_set_Ioc) (λ m n hmn, _) _, { exact Ioc_subset_Ioc (u_mono.monotone hmn) le_rfl }, { exact ⟨0, by simpa only [measure_Ioc] using ennreal.of_real_ne_top⟩ } }, have L2 : tendsto (λ n, f.measure (Ioc (u n) a)) at_top (𝓝 (of_real (f a - f.left_lim a))), { simp only [measure_Ioc], have : tendsto (λ n, f (u n)) at_top (𝓝 (f.left_lim a)), { apply (f.tendsto_left_lim a).comp, exact tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ u_lim (eventually_of_forall (λ n, u_lt_a n)) }, exact ennreal.continuous_of_real.continuous_at.tendsto.comp (tendsto_const_nhds.sub this) }, exact tendsto_nhds_unique L1 L2 end @[simp] lemma measure_Icc (a b : ℝ) : f.measure (Icc a b) = of_real (f b - f.left_lim a) := begin rcases le_or_lt a b with hab|hab, { have A : disjoint {a} (Ioc a b), by simp, simp [← Icc_union_Ioc_eq_Icc le_rfl hab, -singleton_union, ← ennreal.of_real_add, f.left_lim_le, measure_union A (measurable_set_singleton a) measurable_set_Ioc, f.mono hab] }, { simp only [hab, measure_empty, Icc_eq_empty, not_le], symmetry, simp [ennreal.of_real_eq_zero, f.le_left_lim hab] } end @[simp] lemma measure_Ioo {a b : ℝ} : f.measure (Ioo a b) = of_real (f.left_lim b - f a) := begin rcases le_or_lt b a with hab|hab, { simp only [hab, measure_empty, Ioo_eq_empty, not_lt], symmetry, simp [ennreal.of_real_eq_zero, f.left_lim_le hab] }, { have A : disjoint (Ioo a b) {b}, by simp, have D : f b - f a = (f b - f.left_lim b) + (f.left_lim b - f a), by abel, have := f.measure_Ioc a b, simp only [←Ioo_union_Icc_eq_Ioc hab le_rfl, measure_singleton, measure_union A measurable_set_Ioo (measurable_set_singleton b), Icc_self] at this, rw [D, ennreal.of_real_add, add_comm] at this, { simpa only [ennreal.add_right_inj ennreal.of_real_ne_top] }, { simp only [f.left_lim_le, sub_nonneg] }, { simp only [f.le_left_lim hab, sub_nonneg] } }, end @[simp] lemma measure_Ico (a b : ℝ) : f.measure (Ico a b) = of_real (f.left_lim b - f.left_lim a) := begin rcases le_or_lt b a with hab|hab, { simp only [hab, measure_empty, Ico_eq_empty, not_lt], symmetry, simp [ennreal.of_real_eq_zero, f.left_lim_le_left_lim hab] }, { have A : disjoint {a} (Ioo a b) := by simp, simp [← Icc_union_Ioo_eq_Ico le_rfl hab, -singleton_union, hab.ne, f.left_lim_le, measure_union A (measurable_set_singleton a) measurable_set_Ioo, f.le_left_lim hab, ← ennreal.of_real_add] } end end stieltjes_function
cad48983d7606852dd770420680cb125e3caea62
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/algebra/free.lean
245761a39b2e470fc73a1dff206217f31441eb20
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
23,093
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import data.equiv.basic import control.applicative import control.traversable.basic import algebra.group.hom /-! # Free constructions ## Main definitions * `free_magma α`: free magma (structure with binary operation without any axioms) over alphabet `α`, defined inductively, with traversable instance and decidable equality. * `magma.free_semigroup α`: free semigroup over magma `α`. * `free_semigroup α`: free semigroup over alphabet `α`, defined as a synonym for `α × list α` (i.e. nonempty lists), with traversable instance and decidable equality. * `free_semigroup_free_magma α`: isomorphism between `magma.free_semigroup (free_magma α)` and `free_semigroup α`. * `free_magma.lift`: the universal property of the free magma, expressing its adjointness. -/ universes u v l /-- Free magma over a given alphabet. -/ @[derive decidable_eq] inductive free_magma (α : Type u) : Type u | of : α → free_magma | mul : free_magma → free_magma → free_magma /-- Free nonabelian additive magma over a given alphabet. -/ @[derive decidable_eq] inductive free_add_magma (α : Type u) : Type u | of : α → free_add_magma | add : free_add_magma → free_add_magma → free_add_magma attribute [to_additive] free_magma namespace free_magma variables {α : Type u} @[to_additive] instance [inhabited α] : inhabited (free_magma α) := ⟨of (default _)⟩ @[to_additive] instance : has_mul (free_magma α) := ⟨free_magma.mul⟩ attribute [pattern] has_mul.mul @[simp, to_additive] theorem mul_eq (x y : free_magma α) : mul x y = x * y := rfl /-- Recursor for `free_magma` using `x * y` instead of `free_magma.mul x y`. -/ @[elab_as_eliminator, to_additive "Recursor for `free_add_magma` using `x + y` instead of `free_add_magma.add x y`."] def rec_on' {C : free_magma α → Sort l} (x) (ih1 : ∀ x, C (of x)) (ih2 : ∀ x y, C x → C y → C (x * y)) : C x := free_magma.rec_on x ih1 ih2 end free_magma /-- Lifts a function `α → β` to a magma homomorphism `free_magma α → β` given a magma `β`. -/ def free_magma.lift_aux {α : Type u} {β : Type v} [has_mul β] (f : α → β) : free_magma α → β | (free_magma.of x) := f x | (x * y) := x.lift_aux * y.lift_aux /-- Lifts a function `α → β` to an additive magma homomorphism `free_add_magma α → β` given an additive magma `β`. -/ def free_add_magma.lift_aux {α : Type u} {β : Type v} [has_add β] (f : α → β) : free_add_magma α → β | (free_add_magma.of x) := f x | (x + y) := x.lift_aux + y.lift_aux attribute [to_additive free_add_magma.lift_aux] free_magma.lift_aux namespace free_magma variables {α : Type u} {β : Type v} [has_mul β] (f : α → β) @[to_additive] theorem lift_aux_unique (F : mul_hom (free_magma α) β) : ⇑F = lift_aux (F ∘ of) := funext $ λ x, free_magma.rec_on x (λ x, rfl) $ λ x y ih1 ih2, (F.map_mul x y).trans $ congr (congr_arg _ ih1) ih2 /-- The universal property of the free magma expressing its adjointness. -/ @[to_additive "The universal property of the free additive magma expressing its adjointness."] def lift : (α → β) ≃ mul_hom (free_magma α) β := { to_fun := λ f, { to_fun := lift_aux f, map_mul' := λ x y, rfl, }, inv_fun := λ F, F ∘ of, left_inv := λ f, by { ext, simp only [lift_aux, mul_hom.coe_mk, function.comp_app], }, right_inv := λ F, by { ext, rw [mul_hom.coe_mk, lift_aux_unique], } } @[simp, to_additive] lemma lift_of (x) : lift f (of x) = f x := rfl end free_magma /-- The unique magma homomorphism `free_magma α → free_magma β` that sends each `of x` to `of (f x)`. -/ def free_magma.map {α : Type u} {β : Type v} (f : α → β) : free_magma α → free_magma β | (free_magma.of x) := free_magma.of (f x) | (x * y) := x.map * y.map /-- The unique additive magma homomorphism `free_add_magma α → free_add_magma β` that sends each `of x` to `of (f x)`. -/ def free_add_magma.map {α : Type u} {β : Type v} (f : α → β) : free_add_magma α → free_add_magma β | (free_add_magma.of x) := free_add_magma.of (f x) | (x + y) := x.map + y.map attribute [to_additive free_add_magma.map] free_magma.map namespace free_magma variables {α : Type u} section map variables {β : Type v} (f : α → β) @[simp, to_additive] lemma map_of (x) : map f (of x) = of (f x) := rfl @[simp, to_additive] lemma map_mul (x y) : map f (x * y) = map f x * map f y := rfl end map section category @[to_additive] instance : monad free_magma := { pure := λ _, of, bind := λ _ _ x f, lift f x } /-- Recursor on `free_magma` using `pure` instead of `of`. -/ @[elab_as_eliminator, to_additive "Recursor on `free_add_magma` using `pure` instead of `of`."] protected def rec_on'' {C : free_magma α → Sort l} (x) (ih1 : ∀ x, C (pure x)) (ih2 : ∀ x y, C x → C y → C (x * y)) : C x := free_magma.rec_on' x ih1 ih2 variables {β : Type u} @[simp, to_additive] lemma map_pure (f : α → β) (x) : (f <$> pure x : free_magma β) = pure (f x) := rfl @[simp, to_additive] lemma map_mul' (f : α → β) (x y : free_magma α) : (f <$> (x * y)) = (f <$> x * f <$> y) := rfl @[simp, to_additive] lemma pure_bind (f : α → free_magma β) (x) : (pure x >>= f) = f x := rfl @[simp, to_additive] lemma mul_bind (f : α → free_magma β) (x y : free_magma α) : (x * y >>= f) = ((x >>= f) * (y >>= f)) := rfl @[simp, to_additive] lemma pure_seq {α β : Type u} {f : α → β} {x : free_magma α} : pure f <*> x = f <$> x := rfl @[simp, to_additive] lemma mul_seq {α β : Type u} {f g : free_magma (α → β)} {x : free_magma α} : (f * g) <*> x = (f <*> x) * (g <*> x) := rfl @[to_additive] instance : is_lawful_monad free_magma.{u} := { pure_bind := λ _ _ _ _, rfl, bind_assoc := λ α β γ x f g, free_magma.rec_on'' x (λ x, rfl) (λ x y ih1 ih2, by rw [mul_bind, mul_bind, mul_bind, ih1, ih2]), id_map := λ α x, free_magma.rec_on'' x (λ _, rfl) (λ x y ih1 ih2, by rw [map_mul', ih1, ih2]) } end category end free_magma /-- `free_magma` is traversable. -/ protected def free_magma.traverse {m : Type u → Type u} [applicative m] {α β : Type u} (F : α → m β) : free_magma α → m (free_magma β) | (free_magma.of x) := free_magma.of <$> F x | (x * y) := (*) <$> x.traverse <*> y.traverse /-- `free_add_magma` is traversable. -/ protected def free_add_magma.traverse {m : Type u → Type u} [applicative m] {α β : Type u} (F : α → m β) : free_add_magma α → m (free_add_magma β) | (free_add_magma.of x) := free_add_magma.of <$> F x | (x + y) := (+) <$> x.traverse <*> y.traverse attribute [to_additive free_add_magma.traverse] free_magma.traverse namespace free_magma variables {α : Type u} section category variables {β : Type u} @[to_additive] instance : traversable free_magma := ⟨@free_magma.traverse⟩ variables {m : Type u → Type u} [applicative m] (F : α → m β) @[simp, to_additive] lemma traverse_pure (x) : traverse F (pure x : free_magma α) = pure <$> F x := rfl @[simp, to_additive] lemma traverse_pure' : traverse F ∘ pure = λ x, (pure <$> F x : m (free_magma β)) := rfl @[simp, to_additive] lemma traverse_mul (x y : free_magma α) : traverse F (x * y) = (*) <$> traverse F x <*> traverse F y := rfl @[simp, to_additive] lemma traverse_mul' : function.comp (traverse F) ∘ @has_mul.mul (free_magma α) _ = λ x y, (*) <$> traverse F x <*> traverse F y := rfl @[simp, to_additive] lemma traverse_eq (x) : free_magma.traverse F x = traverse F x := rfl @[simp, to_additive] lemma mul_map_seq (x y : free_magma α) : ((*) <$> x <*> y : id (free_magma α)) = (x * y : free_magma α) := rfl @[to_additive] instance : is_lawful_traversable free_magma.{u} := { id_traverse := λ α x, free_magma.rec_on'' x (λ x, rfl) (λ x y ih1 ih2, by rw [traverse_mul, ih1, ih2, mul_map_seq]), comp_traverse := λ F G hf1 hg1 hf2 hg2 α β γ f g x, free_magma.rec_on'' x (λ x, by resetI; simp only [traverse_pure, traverse_pure'] with functor_norm) (λ x y ih1 ih2, by resetI; rw [traverse_mul, ih1, ih2, traverse_mul]; simp only [traverse_mul'] with functor_norm), naturality := λ F G hf1 hg1 hf2 hg2 η α β f x, free_magma.rec_on'' x (λ x, by simp only [traverse_pure] with functor_norm) (λ x y ih1 ih2, by simp only [traverse_mul] with functor_norm; rw [ih1, ih2]), traverse_eq_map_id := λ α β f x, free_magma.rec_on'' x (λ _, rfl) (λ x y ih1 ih2, by rw [traverse_mul, ih1, ih2, map_mul', mul_map_seq]; refl), .. free_magma.is_lawful_monad } end category end free_magma /-- Representation of an element of a free magma. -/ protected def free_magma.repr {α : Type u} [has_repr α] : free_magma α → string | (free_magma.of x) := repr x | (x * y) := "( " ++ x.repr ++ " * " ++ y.repr ++ " )" /-- Representation of an element of a free additive magma. -/ protected def free_add_magma.repr {α : Type u} [has_repr α] : free_add_magma α → string | (free_add_magma.of x) := repr x | (x + y) := "( " ++ x.repr ++ " + " ++ y.repr ++ " )" attribute [to_additive free_add_magma.repr] free_magma.repr @[to_additive] instance {α : Type u} [has_repr α] : has_repr (free_magma α) := ⟨free_magma.repr⟩ /-- Length of an element of a free magma. -/ def free_magma.length {α : Type u} : free_magma α → ℕ | (free_magma.of x) := 1 | (x * y) := x.length + y.length /-- Length of an element of a free additive magma. -/ def free_add_magma.length {α : Type u} : free_add_magma α → ℕ | (free_add_magma.of x) := 1 | (x + y) := x.length + y.length attribute [to_additive free_add_magma.length] free_magma.length /-- Associativity relations for a magma. -/ inductive magma.free_semigroup.r (α : Type u) [has_mul α] : α → α → Prop | intro : ∀ x y z, magma.free_semigroup.r ((x * y) * z) (x * (y * z)) | left : ∀ w x y z, magma.free_semigroup.r (w * ((x * y) * z)) (w * (x * (y * z))) /-- Associativity relations for an additive magma. -/ inductive add_magma.free_add_semigroup.r (α : Type u) [has_add α] : α → α → Prop | intro : ∀ x y z, add_magma.free_add_semigroup.r ((x + y) + z) (x + (y + z)) | left : ∀ w x y z, add_magma.free_add_semigroup.r (w + ((x + y) + z)) (w + (x + (y + z))) attribute [to_additive add_magma.free_add_semigroup.r] magma.free_semigroup.r namespace magma /-- Free semigroup over a magma. -/ @[to_additive add_magma.free_add_semigroup "Free additive semigroup over an additive magma."] def free_semigroup (α : Type u) [has_mul α] : Type u := quot $ free_semigroup.r α namespace free_semigroup variables {α : Type u} [has_mul α] /-- Embedding from magma to its free semigroup. -/ @[to_additive "Embedding from additive magma to its free additive semigroup."] def of : α → free_semigroup α := quot.mk _ @[to_additive] instance [inhabited α] : inhabited (free_semigroup α) := ⟨of (default _)⟩ @[elab_as_eliminator, to_additive] protected lemma induction_on {C : free_semigroup α → Prop} (x : free_semigroup α) (ih : ∀ x, C (of x)) : C x := quot.induction_on x ih @[to_additive] theorem of_mul_assoc (x y z : α) : of ((x * y) * z) = of (x * (y * z)) := quot.sound $ r.intro x y z @[to_additive] theorem of_mul_assoc_left (w x y z : α) : of (w * ((x * y) * z)) = of (w * (x * (y * z))) := quot.sound $ r.left w x y z @[to_additive] theorem of_mul_assoc_right (w x y z : α) : of (((w * x) * y) * z) = of ((w * (x * y)) * z) := by rw [of_mul_assoc, of_mul_assoc, of_mul_assoc, of_mul_assoc_left] @[to_additive] instance : semigroup (free_semigroup α) := { mul := λ x y, begin refine quot.lift_on x (λ p, quot.lift_on y (λ q, (quot.mk _ $ p * q : free_semigroup α)) _) _, { rintros a b (⟨c, d, e⟩ | ⟨c, d, e, f⟩); change of _ = of _, { rw of_mul_assoc_left }, { rw [← of_mul_assoc, of_mul_assoc_left, of_mul_assoc] } }, { refine quot.induction_on y (λ q, _), rintros a b (⟨c, d, e⟩ | ⟨c, d, e, f⟩); change of _ = of _, { rw of_mul_assoc_right }, { rw [of_mul_assoc, of_mul_assoc, of_mul_assoc_left, of_mul_assoc_left, of_mul_assoc_left, ← of_mul_assoc c d, ← of_mul_assoc c d, of_mul_assoc_left] } } end, mul_assoc := λ x y z, quot.induction_on x $ λ p, quot.induction_on y $ λ q, quot.induction_on z $ λ r, of_mul_assoc p q r } @[to_additive] theorem of_mul (x y : α) : of (x * y) = of x * of y := rfl section lift variables {β : Type v} [semigroup β] (f : α → β) /-- Lifts a magma homomorphism `α → β` to a semigroup homomorphism `magma.free_semigroup α → β` given a semigroup `β`. -/ @[to_additive "Lifts an additive magma homomorphism `α → β` to an additive semigroup homomorphism `add_magma.free_add_semigroup α → β` given an additive semigroup `β`."] def lift (hf : ∀ x y, f (x * y) = f x * f y) : free_semigroup α → β := quot.lift f $ by rintros a b (⟨c, d, e⟩ | ⟨c, d, e, f⟩); simp only [hf, mul_assoc] @[simp, to_additive] lemma lift_of {hf} (x : α) : lift f hf (of x) = f x := rfl @[simp, to_additive] lemma lift_mul {hf} (x y) : lift f hf (x * y) = lift f hf x * lift f hf y := quot.induction_on x $ λ p, quot.induction_on y $ λ q, hf p q @[to_additive] theorem lift_unique (f : free_semigroup α → β) (hf : ∀ x y, f (x * y) = f x * f y) : f = lift (f ∘ of) (λ p q, hf (of p) (of q)) := funext $ λ x, quot.induction_on x $ λ p, rfl end lift variables {β : Type v} [has_mul β] (f : α → β) /-- From a magma homomorphism `α → β` to a semigroup homomorphism `magma.free_semigroup α → magma.free_semigroup β`. -/ @[to_additive "From an additive magma homomorphism `α → β` to an additive semigroup homomorphism `add_magma.free_add_semigroup α → add_magma.free_add_semigroup β`."] def map (hf : ∀ x y, f (x * y) = f x * f y) : free_semigroup α → free_semigroup β := lift (of ∘ f) (λ x y, congr_arg of $ hf x y) @[simp, to_additive] lemma map_of {hf} (x) : map f hf (of x) = of (f x) := rfl @[simp, to_additive] lemma map_mul {hf} (x y) : map f hf (x * y) = map f hf x * map f hf y := lift_mul _ _ _ end free_semigroup end magma /-- Free semigroup over a given alphabet. (Note: In this definition, the free semigroup does not contain the empty word.) -/ @[to_additive "Free additive semigroup over a given alphabet."] def free_semigroup (α : Type u) : Type u := α × list α namespace free_semigroup variables {α : Type u} @[to_additive] instance : semigroup (free_semigroup α) := { mul := λ L1 L2, (L1.1, L1.2 ++ L2.1 :: L2.2), mul_assoc := λ L1 L2 L3, prod.ext rfl $ list.append_assoc _ _ _ } /-- The embedding `α → free_semigroup α`. -/ @[to_additive "The embedding `α → free_add_semigroup α`."] def of (x : α) : free_semigroup α := (x, []) @[to_additive] instance [inhabited α] : inhabited (free_semigroup α) := ⟨of (default _)⟩ /-- Recursor for free semigroup using `of` and `*`. -/ @[elab_as_eliminator, to_additive "Recursor for free additive semigroup using `of` and `+`."] protected def rec_on {C : free_semigroup α → Sort l} (x) (ih1 : ∀ x, C (of x)) (ih2 : ∀ x y, C (of x) → C y → C (of x * y)) : C x := prod.rec_on x $ λ f s, list.rec_on s ih1 (λ hd tl ih f, ih2 f (hd, tl) (ih1 f) (ih hd)) f end free_semigroup /-- Auxiliary function for `free_semigroup.lift`. -/ def free_semigroup.lift' {α : Type u} {β : Type v} [semigroup β] (f : α → β) : α → list α → β | x [] := f x | x (hd::tl) := f x * free_semigroup.lift' hd tl /-- Auxiliary function for `free_semigroup.lift`. -/ def free_add_semigroup.lift' {α : Type u} {β : Type v} [add_semigroup β] (f : α → β) : α → list α → β | x [] := f x | x (hd::tl) := f x + free_add_semigroup.lift' hd tl attribute [to_additive free_add_semigroup.lift'] free_semigroup.lift' namespace free_semigroup variables {α : Type u} section lift variables {β : Type v} [semigroup β] (f : α → β) /-- Lifts a function `α → β` to a semigroup homomorphism `free_semigroup α → β` given a semigroup `β`. -/ @[to_additive "Lifts a function `α → β` to an additive semigroup homomorphism `free_add_semigroup α → β` given an additive semigroup `β`."] def lift (x : free_semigroup α) : β := lift' f x.1 x.2 @[simp, to_additive] lemma lift_of (x : α) : lift f (of x) = f x := rfl @[to_additive] lemma lift_of_mul (x y) : lift f (of x * y) = f x * lift f y := rfl @[simp, to_additive] lemma lift_mul (x y) : lift f (x * y) = lift f x * lift f y := free_semigroup.rec_on x (λ p, rfl) (λ p x ih1 ih2, by rw [mul_assoc, lift_of_mul, lift_of_mul, mul_assoc, ih2]) @[to_additive] theorem lift_unique (f : free_semigroup α → β) (hf : ∀ x y, f (x * y) = f x * f y) : f = lift (f ∘ of) := funext $ λ ⟨x, L⟩, list.rec_on L (λ x, rfl) (λ hd tl ih x, (hf (of x) (hd, tl)).trans $ congr_arg _ $ ih _) x end lift section map variables {β : Type v} (f : α → β) /-- The unique semigroup homomorphism that sends `of x` to `of (f x)`. -/ @[to_additive "The unique additive semigroup homomorphism that sends `of x` to `of (f x)`."] def map : free_semigroup α → free_semigroup β := lift $ of ∘ f @[simp, to_additive] lemma map_of (x) : map f (of x) = of (f x) := rfl @[simp, to_additive] lemma map_mul (x y) : map f (x * y) = map f x * map f y := lift_mul _ _ _ end map section category variables {β : Type u} @[to_additive] instance : monad free_semigroup := { pure := λ _, of, bind := λ _ _ x f, lift f x } /-- Recursor that uses `pure` instead of `of`. -/ @[elab_as_eliminator, to_additive "Recursor that uses `pure` instead of `of`."] def rec_on' {C : free_semigroup α → Sort l} (x) (ih1 : ∀ x, C (pure x)) (ih2 : ∀ x y, C (pure x) → C y → C (pure x * y)) : C x := free_semigroup.rec_on x ih1 ih2 @[simp, to_additive] lemma map_pure (f : α → β) (x) : (f <$> pure x : free_semigroup β) = pure (f x) := rfl @[simp, to_additive] lemma map_mul' (f : α → β) (x y : free_semigroup α) : (f <$> (x * y)) = (f <$> x * f <$> y) := map_mul _ _ _ @[simp, to_additive] lemma pure_bind (f : α → free_semigroup β) (x) : (pure x >>= f) = f x := rfl @[simp, to_additive] lemma mul_bind (f : α → free_semigroup β) (x y : free_semigroup α) : (x * y >>= f) = ((x >>= f) * (y >>= f)) := lift_mul _ _ _ @[simp, to_additive] lemma pure_seq {f : α → β} {x : free_semigroup α} : pure f <*> x = f <$> x := rfl @[simp, to_additive] lemma mul_seq {f g : free_semigroup (α → β)} {x : free_semigroup α} : (f * g) <*> x = (f <*> x) * (g <*> x) := mul_bind _ _ _ @[to_additive] instance : is_lawful_monad free_semigroup.{u} := { pure_bind := λ _ _ _ _, rfl, bind_assoc := λ α β γ x f g, rec_on' x (λ x, rfl) (λ x y ih1 ih2, by rw [mul_bind, mul_bind, mul_bind, ih1, ih2]), id_map := λ α x, rec_on' x (λ _, rfl) (λ x y ih1 ih2, by rw [map_mul', ih1, ih2]) } /-- `free_semigroup` is traversable. -/ @[to_additive "`free_add_semigroup` is traversable."] protected def traverse {m : Type u → Type u} [applicative m] {α β : Type u} (F : α → m β) (x : free_semigroup α) : m (free_semigroup β) := rec_on' x (λ x, pure <$> F x) (λ x y ihx ihy, (*) <$> ihx <*> ihy) @[to_additive] instance : traversable free_semigroup := ⟨@free_semigroup.traverse⟩ variables {m : Type u → Type u} [applicative m] (F : α → m β) @[simp, to_additive] lemma traverse_pure (x) :traverse F (pure x : free_semigroup α) = pure <$> F x := rfl @[simp, to_additive] lemma traverse_pure' : traverse F ∘ pure = λ x, (pure <$> F x : m (free_semigroup β)) := rfl section variables [is_lawful_applicative m] @[simp, to_additive] lemma traverse_mul (x y : free_semigroup α) : traverse F (x * y) = (*) <$> traverse F x <*> traverse F y := let ⟨x, L1⟩ := x, ⟨y, L2⟩ := y in list.rec_on L1 (λ x, rfl) (λ hd tl ih x, show (*) <$> pure <$> F x <*> traverse F ((hd, tl) * (y, L2) : free_semigroup α) = (*) <$> ((*) <$> pure <$> F x <*> traverse F (hd, tl)) <*> traverse F (y, L2), by rw ih; simp only [(∘), (mul_assoc _ _ _).symm] with functor_norm) x @[simp, to_additive] lemma traverse_mul' : function.comp (traverse F) ∘ @has_mul.mul (free_semigroup α) _ = λ x y, (*) <$> traverse F x <*> traverse F y := funext $ λ x, funext $ λ y, traverse_mul F x y end @[simp, to_additive] lemma traverse_eq (x) : free_semigroup.traverse F x = traverse F x := rfl @[simp, to_additive] lemma mul_map_seq (x y : free_semigroup α) : ((*) <$> x <*> y : id (free_semigroup α)) = (x * y : free_semigroup α) := rfl @[to_additive] instance : is_lawful_traversable free_semigroup.{u} := { id_traverse := λ α x, free_semigroup.rec_on x (λ x, rfl) (λ x y ih1 ih2, by rw [traverse_mul, ih1, ih2, mul_map_seq]), comp_traverse := λ F G hf1 hg1 hf2 hg2 α β γ f g x, rec_on' x (λ x, by resetI; simp only [traverse_pure, traverse_pure'] with functor_norm) (λ x y ih1 ih2, by resetI; rw [traverse_mul, ih1, ih2, traverse_mul]; simp only [traverse_mul'] with functor_norm), naturality := λ F G hf1 hg1 hf2 hg2 η α β f x, rec_on' x (λ x, by simp only [traverse_pure] with functor_norm) (λ x y ih1 ih2, by resetI; simp only [traverse_mul] with functor_norm; rw [ih1, ih2]), traverse_eq_map_id := λ α β f x, free_semigroup.rec_on x (λ _, rfl) (λ x y ih1 ih2, by rw [traverse_mul, ih1, ih2, map_mul', mul_map_seq]; refl), .. free_semigroup.is_lawful_monad } end category @[to_additive] instance [decidable_eq α] : decidable_eq (free_semigroup α) := prod.decidable_eq end free_semigroup /-- Isomorphism between `magma.free_semigroup (free_magma α)` and `free_semigroup α`. -/ @[to_additive "Isomorphism between `add_magma.free_add_semigroup (free_add_magma α)` and `free_add_semigroup α`."] def free_semigroup_free_magma (α : Type u) : magma.free_semigroup (free_magma α) ≃ free_semigroup α := { to_fun := magma.free_semigroup.lift (free_magma.lift free_semigroup.of) (free_magma.lift _).map_mul, inv_fun := free_semigroup.lift (magma.free_semigroup.of ∘ free_magma.of), left_inv := λ x, magma.free_semigroup.induction_on x $ λ p, by rw magma.free_semigroup.lift_of; exact free_magma.rec_on' p (λ x, by rw [free_magma.lift_of, free_semigroup.lift_of]) (λ x y ihx ihy, by rw [mul_hom.map_mul, free_semigroup.lift_mul, ihx, ihy, magma.free_semigroup.of_mul]), right_inv := λ x, free_semigroup.rec_on x (λ x, by rw [free_semigroup.lift_of, magma.free_semigroup.lift_of, free_magma.lift_of]) (λ x y ihx ihy, by rw [free_semigroup.lift_mul, magma.free_semigroup.lift_mul, ihx, ihy]) } @[simp, to_additive] lemma free_semigroup_free_magma_mul {α : Type u} (x y) : free_semigroup_free_magma α (x * y) = free_semigroup_free_magma α x * free_semigroup_free_magma α y := magma.free_semigroup.lift_mul _ _ _
2d9fa34d79b28e9c9eaa6e873fbad7e5971dae81
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/data/set/intervals/unordered_interval.lean
67f1079cbb8f3685e2f67a8917910d7f83722c83
[ "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
8,889
lean
/- Copyright (c) 2020 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou -/ import order.bounds import data.set.intervals.image_preimage /-! # Intervals without endpoints ordering In any decidable linear order `α`, we define the set of elements lying between two elements `a` and `b` as `Icc (min a b) (max a b)`. `Icc a b` requires the assumption `a ≤ b` to be meaningful, which is sometimes inconvenient. The interval as defined in this file is always the set of things lying between `a` and `b`, regardless of the relative order of `a` and `b`. For real numbers, `Icc (min a b) (max a b)` is the same as `segment ℝ a b`. ## Notation We use the localized notation `[a, b]` for `interval a b`. One can open the locale `interval` to make the notation available. -/ universe u open_locale pointwise namespace set section linear_order variables {α : Type u} [linear_order α] {a a₁ a₂ b b₁ b₂ x : α} /-- `interval a b` is the set of elements lying between `a` and `b`, with `a` and `b` included. -/ def interval (a b : α) := Icc (min a b) (max a b) localized "notation `[`a `, ` b `]` := set.interval a b" in interval @[simp] lemma interval_of_le (h : a ≤ b) : [a, b] = Icc a b := by rw [interval, min_eq_left h, max_eq_right h] @[simp] lemma interval_of_ge (h : b ≤ a) : [a, b] = Icc b a := by { rw [interval, min_eq_right h, max_eq_left h] } lemma interval_swap (a b : α) : [a, b] = [b, a] := or.elim (le_total a b) (by simp {contextual := tt}) (by simp {contextual := tt}) lemma interval_of_lt (h : a < b) : [a, b] = Icc a b := interval_of_le (le_of_lt h) lemma interval_of_gt (h : b < a) : [a, b] = Icc b a := interval_of_ge (le_of_lt h) lemma interval_of_not_le (h : ¬ a ≤ b) : [a, b] = Icc b a := interval_of_gt (lt_of_not_ge h) lemma interval_of_not_ge (h : ¬ b ≤ a) : [a, b] = Icc a b := interval_of_lt (lt_of_not_ge h) @[simp] lemma interval_self : [a, a] = {a} := set.ext $ by simp [le_antisymm_iff, and_comm] @[simp] lemma nonempty_interval : set.nonempty [a, b] := by { simp only [interval, min_le_iff, le_max_iff, nonempty_Icc], left, left, refl } @[simp] lemma left_mem_interval : a ∈ [a, b] := by { rw [interval, mem_Icc], exact ⟨min_le_left _ _, le_max_left _ _⟩ } @[simp] lemma right_mem_interval : b ∈ [a, b] := by { rw interval_swap, exact left_mem_interval } lemma Icc_subset_interval : Icc a b ⊆ [a, b] := by { assume x h, rwa interval_of_le, exact le_trans h.1 h.2 } lemma Icc_subset_interval' : Icc b a ⊆ [a, b] := by { rw interval_swap, apply Icc_subset_interval } lemma mem_interval_of_le (ha : a ≤ x) (hb : x ≤ b) : x ∈ [a, b] := Icc_subset_interval ⟨ha, hb⟩ lemma mem_interval_of_ge (hb : b ≤ x) (ha : x ≤ a) : x ∈ [a, b] := Icc_subset_interval' ⟨hb, ha⟩ lemma not_mem_interval_of_lt {c : α} (ha : c < a) (hb : c < b) : c ∉ interval a b := not_mem_Icc_of_lt $ lt_min_iff.mpr ⟨ha, hb⟩ lemma not_mem_interval_of_gt {c : α} (ha : a < c) (hb : b < c) : c ∉ interval a b := not_mem_Icc_of_gt $ max_lt_iff.mpr ⟨ha, hb⟩ lemma interval_subset_interval (h₁ : a₁ ∈ [a₂, b₂]) (h₂ : b₁ ∈ [a₂, b₂]) : [a₁, b₁] ⊆ [a₂, b₂] := Icc_subset_Icc (le_min h₁.1 h₂.1) (max_le h₁.2 h₂.2) lemma interval_subset_interval_iff_mem : [a₁, b₁] ⊆ [a₂, b₂] ↔ a₁ ∈ [a₂, b₂] ∧ b₁ ∈ [a₂, b₂] := iff.intro (λh, ⟨h left_mem_interval, h right_mem_interval⟩) (λ h, interval_subset_interval h.1 h.2) lemma interval_subset_interval_iff_le : [a₁, b₁] ⊆ [a₂, b₂] ↔ min a₂ b₂ ≤ min a₁ b₁ ∧ max a₁ b₁ ≤ max a₂ b₂ := by { rw [interval, interval, Icc_subset_Icc_iff], exact min_le_max } lemma interval_subset_interval_right (h : x ∈ [a, b]) : [x, b] ⊆ [a, b] := interval_subset_interval h right_mem_interval lemma interval_subset_interval_left (h : x ∈ [a, b]) : [a, x] ⊆ [a, b] := interval_subset_interval left_mem_interval h lemma bdd_below_bdd_above_iff_subset_interval (s : set α) : bdd_below s ∧ bdd_above s ↔ ∃ a b, s ⊆ [a, b] := begin rw [bdd_below_bdd_above_iff_subset_Icc], split, { rintro ⟨a, b, h⟩, exact ⟨a, b, λ x hx, Icc_subset_interval (h hx)⟩ }, { rintro ⟨a, b, h⟩, exact ⟨min a b, max a b, h⟩ } end /-- The open-closed interval with unordered bounds. -/ def interval_oc : α → α → set α := λ a b, Ioc (min a b) (max a b) -- Below is a capital iota localized "notation `Ι` := set.interval_oc" in interval lemma interval_oc_of_le (h : a ≤ b) : Ι a b = Ioc a b := by simp [interval_oc, h] lemma interval_oc_of_lt (h : b < a) : Ι a b = Ioc b a := by simp [interval_oc, le_of_lt h] lemma forall_interval_oc_iff {P : α → Prop} : (∀ x ∈ Ι a b, P x) ↔ (∀ x ∈ Ioc a b, P x) ∧ (∀ x ∈ Ioc b a, P x) := by { dsimp [interval_oc], cases le_total a b with hab hab ; simp [hab] } end linear_order open_locale interval section ordered_add_comm_group variables {α : Type u} [linear_ordered_add_comm_group α] (a b c x y : α) @[simp] lemma preimage_const_add_interval : (λ x, a + x) ⁻¹' [b, c] = [b - a, c - a] := by simp only [interval, preimage_const_add_Icc, min_sub_sub_right, max_sub_sub_right] @[simp] lemma preimage_add_const_interval : (λ x, x + a) ⁻¹' [b, c] = [b - a, c - a] := by simpa only [add_comm] using preimage_const_add_interval a b c @[simp] lemma preimage_neg_interval : - [a, b] = [-a, -b] := by simp only [interval, preimage_neg_Icc, min_neg_neg, max_neg_neg] @[simp] lemma preimage_sub_const_interval : (λ x, x - a) ⁻¹' [b, c] = [b + a, c + a] := by simp [sub_eq_add_neg] @[simp] lemma preimage_const_sub_interval : (λ x, a - x) ⁻¹' [b, c] = [a - b, a - c] := by { rw [interval, interval, preimage_const_sub_Icc], simp only [sub_eq_add_neg, min_add_add_left, max_add_add_left, min_neg_neg, max_neg_neg], } @[simp] lemma image_const_add_interval : (λ x, a + x) '' [b, c] = [a + b, a + c] := by simp [add_comm] @[simp] lemma image_add_const_interval : (λ x, x + a) '' [b, c] = [b + a, c + a] := by simp @[simp] lemma image_const_sub_interval : (λ x, a - x) '' [b, c] = [a - b, a - c] := by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)] @[simp] lemma image_sub_const_interval : (λ x, x - a) '' [b, c] = [b - a, c - a] := by simp [sub_eq_add_neg, add_comm] lemma image_neg_interval : has_neg.neg '' [a, b] = [-a, -b] := by simp variables {a b c x y} /-- If `[x, y]` is a subinterval of `[a, b]`, then the distance between `x` and `y` is less than or equal to that of `a` and `b` -/ lemma abs_sub_le_of_subinterval (h : [x, y] ⊆ [a, b]) : |y - x| ≤ |b - a| := begin rw [← max_sub_min_eq_abs, ← max_sub_min_eq_abs], rw [interval_subset_interval_iff_le] at h, exact sub_le_sub h.2 h.1, end /-- If `x ∈ [a, b]`, then the distance between `a` and `x` is less than or equal to that of `a` and `b` -/ lemma abs_sub_left_of_mem_interval (h : x ∈ [a, b]) : |x - a| ≤ |b - a| := abs_sub_le_of_subinterval (interval_subset_interval_left h) /-- If `x ∈ [a, b]`, then the distance between `x` and `b` is less than or equal to that of `a` and `b` -/ lemma abs_sub_right_of_mem_interval (h : x ∈ [a, b]) : |b - x| ≤ |b - a| := abs_sub_le_of_subinterval (interval_subset_interval_right h) end ordered_add_comm_group section linear_ordered_field variables {k : Type u} [linear_ordered_field k] {a : k} @[simp] lemma preimage_mul_const_interval (ha : a ≠ 0) (b c : k) : (λ x, x * a) ⁻¹' [b, c] = [b / a, c / a] := (lt_or_gt_of_ne ha).elim (λ ha, by simp [interval, ha, ha.le, min_div_div_right_of_nonpos, max_div_div_right_of_nonpos]) (λ (ha : 0 < a), by simp [interval, ha, ha.le, min_div_div_right, max_div_div_right]) @[simp] lemma preimage_const_mul_interval (ha : a ≠ 0) (b c : k) : (λ x, a * x) ⁻¹' [b, c] = [b / a, c / a] := by simp only [← preimage_mul_const_interval ha, mul_comm] @[simp] lemma preimage_div_const_interval (ha : a ≠ 0) (b c : k) : (λ x, x / a) ⁻¹' [b, c] = [b * a, c * a] := by simp only [div_eq_mul_inv, preimage_mul_const_interval (inv_ne_zero ha), inv_inv₀] @[simp] lemma image_mul_const_interval (a b c : k) : (λ x, x * a) '' [b, c] = [b * a, c * a] := if ha : a = 0 then by simp [ha] else calc (λ x, x * a) '' [b, c] = (λ x, x * a⁻¹) ⁻¹' [b, c] : (units.mk0 a ha).mul_right.image_eq_preimage _ ... = (λ x, x / a) ⁻¹' [b, c] : by simp only [div_eq_mul_inv] ... = [b * a, c * a] : preimage_div_const_interval ha _ _ @[simp] lemma image_const_mul_interval (a b c : k) : (λ x, a * x) '' [b, c] = [a * b, a * c] := by simpa only [mul_comm] using image_mul_const_interval a b c @[simp] lemma image_div_const_interval (a b c : k) : (λ x, x / a) '' [b, c] = [b / a, c / a] := by simp only [div_eq_mul_inv, image_mul_const_interval] end linear_ordered_field end set
08d950127bb9527f899f029e0e81e1c8747b2dbb
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/archive/imo/imo1987_q1.lean
ffae4fbd202d716945495d85fa4d5e5ee59a1f2a
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
4,288
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import data.fintype.big_operators import data.fintype.perm import data.fintype.prod import dynamics.fixed_points.basic /-! # Formalization of IMO 1987, Q1 > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Let $p_{n, k}$ be the number of permutations of a set of cardinality `n ≥ 1` that fix exactly `k` elements. Prove that $∑_{k=0}^n k p_{n,k}=n!$. To prove this identity, we show that both sides are equal to the cardinality of the set `{(x : α, σ : perm α) | σ x = x}`, regrouping by `card (fixed_points σ)` for the left hand side and by `x` for the right hand side. The original problem assumes `n ≥ 1`. It turns out that a version with `n * (n - 1)!` in the RHS holds true for `n = 0` as well, so we first prove it, then deduce the original version in the case `n ≥ 1`. -/ variables (α : Type*) [fintype α] [decidable_eq α] open_locale big_operators nat open equiv fintype function finset (range sum_const) set (Iic) namespace imo1987_q1 /-- The set of pairs `(x : α, σ : perm α)` such that `σ x = x` is equivalent to the set of pairs `(x : α, σ : perm {x}ᶜ)`. -/ def fixed_points_equiv : {σx : α × perm α // σx.2 σx.1 = σx.1} ≃ Σ x : α, perm ({x}ᶜ : set α) := calc {σx : α × perm α // σx.2 σx.1 = σx.1} ≃ Σ x : α, {σ : perm α // σ x = x} : set_prod_equiv_sigma _ ... ≃ Σ x : α, {σ : perm α // ∀ y : ({x} : set α), σ y = equiv.refl ↥({x} : set α) y} : sigma_congr_right (λ x, equiv.set.of_eq $ by { simp only [set_coe.forall], dsimp, simp }) ... ≃ Σ x : α, perm ({x}ᶜ : set α) : sigma_congr_right (λ x, by apply equiv.set.compl) theorem card_fixed_points : card {σx : α × perm α // σx.2 σx.1 = σx.1} = card α * (card α - 1)! := by simp [card_congr (fixed_points_equiv α), card_perm, finset.filter_not, finset.card_sdiff, finset.filter_eq', finset.card_univ] /-- Given `α : Type*` and `k : ℕ`, `fiber α k` is the set of permutations of `α` with exactly `k` fixed points. -/ @[derive fintype] def fiber (k : ℕ) : set (perm α) := {σ : perm α | card (fixed_points σ) = k} @[simp] lemma mem_fiber {σ : perm α} {k : ℕ} : σ ∈ fiber α k ↔ card (fixed_points σ) = k := iff.rfl /-- `p α k` is the number of permutations of `α` with exactly `k` fixed points. -/ def p (k : ℕ) := card (fiber α k) /-- The set of triples `(k ≤ card α, σ ∈ fiber α k, x ∈ fixed_points σ)` is equivalent to the set of pairs `(x : α, σ : perm α)` such that `σ x = x`. The equivalence sends `(k, σ, x)` to `(x, σ)` and `(x, σ)` to `(card (fixed_points σ), σ, x)`. It is easy to see that the cardinality of the LHS is given by `∑ k : fin (card α + 1), k * p α k`. -/ def fixed_points_equiv' : (Σ (k : fin (card α + 1)) (σ : fiber α k), fixed_points σ.1) ≃ {σx : α × perm α // σx.2 σx.1 = σx.1} := { to_fun := λ p, ⟨⟨p.2.2, p.2.1⟩, p.2.2.2⟩, inv_fun := λ p, ⟨⟨card (fixed_points p.1.2), (card_subtype_le _).trans_lt (nat.lt_succ_self _)⟩, ⟨p.1.2, rfl⟩, ⟨p.1.1, p.2⟩⟩, left_inv := λ ⟨⟨k, hk⟩, ⟨σ, hσ⟩, ⟨x, hx⟩⟩, by { simp only [mem_fiber, fin.coe_mk] at hσ, subst k, refl }, right_inv := λ ⟨⟨x, σ⟩, h⟩, rfl } /-- Main statement for any `(α : Type*) [fintype α]`. -/ theorem main_fintype : ∑ k in range (card α + 1), k * p α k = card α * (card α - 1)! := have A : ∀ k (σ : fiber α k), card (fixed_points ⇑(↑σ : perm α)) = k := λ k σ, σ.2, by simpa [A, ← fin.sum_univ_eq_sum_range, -card_of_finset, finset.card_univ, card_fixed_points, mul_comm] using card_congr (fixed_points_equiv' α) /-- Main statement for permutations of `fin n`, a version that works for `n = 0`. -/ theorem main₀ (n : ℕ) : ∑ k in range (n + 1), k * p (fin n) k = n * (n - 1)! := by simpa using main_fintype (fin n) /-- Main statement for permutations of `fin n`. -/ theorem main {n : ℕ} (hn : 1 ≤ n) : ∑ k in range (n + 1), k * p (fin n) k = n! := by rw [main₀, nat.mul_factorial_pred (zero_lt_one.trans_le hn)] end imo1987_q1
857690e1ba9670674c8c464851135158654acd2c
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/gcd_monoid/integrally_closed.lean
341d93937c36b3225ba984bfee3ea233ca360706
[ "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
1,689
lean
/- Copyright (c) 2022 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import algebra.gcd_monoid.basic import ring_theory.integrally_closed import ring_theory.polynomial.eisenstein /-! # GCD domains are integrally closed -/ open_locale big_operators polynomial variables {R A : Type*} [comm_ring R] [is_domain R] [gcd_monoid R] [comm_ring A] [algebra R A] lemma is_localization.surj_of_gcd_domain (M : submonoid R) [is_localization M A] (z : A) : ∃ a b : R, is_unit (gcd a b) ∧ z * algebra_map R A b = algebra_map R A a := begin obtain ⟨x, ⟨y, hy⟩, rfl⟩ := is_localization.mk'_surjective M z, obtain ⟨x', y', hx', hy', hu⟩ := extract_gcd x y, use [x', y', hu], rw [mul_comm, is_localization.mul_mk'_eq_mk'_of_mul], convert is_localization.mk'_mul_cancel_left _ _ using 2, { rw [subtype.coe_mk, hy', ← mul_comm y', mul_assoc], conv_lhs { rw hx' } }, { apply_instance }, end @[priority 100] instance gcd_monoid.to_is_integrally_closed : is_integrally_closed R := ⟨λ X ⟨p, hp₁, hp₂⟩, begin obtain ⟨x, y, hg, he⟩ := is_localization.surj_of_gcd_domain (non_zero_divisors R) X, have := polynomial.dvd_pow_nat_degree_of_eval₂_eq_zero (is_fraction_ring.injective R $ fraction_ring R) hp₁ y x _ hp₂ (by rw [mul_comm, he]), have : is_unit y, { rw [is_unit_iff_dvd_one, ← one_pow], exact (dvd_gcd this $ dvd_refl y).trans (gcd_pow_left_dvd_pow_gcd.trans $ pow_dvd_pow_of_dvd (is_unit_iff_dvd_one.1 hg) _) }, use x * (this.unit⁻¹ : _), erw [map_mul, ← units.coe_map_inv, eq_comm, units.eq_mul_inv_iff_mul_eq], exact he, end⟩
7f213839e8c15b1e7026b619fb2ea7bdc09dbb4d
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/const.lean
13211cfe93cca49fa90edd6ad0bc7f307f4673b9
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
3,373
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`. -/ 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} @[simp] lemma obj_obj (X : C) (j : J) : ((const J).obj X).obj j = X := rfl @[simp] lemma obj_map (X : C) {j j' : J} (f : j ⟶ j') : ((const J).obj X).map f = 𝟙 X := rfl @[simp] lemma map_app {X Y : C} (f : X ⟶ Y) (j : J) : ((const J).map f).app j = f := rfl /-- 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`. -/ def op_obj_op (X : C) : (const Jᵒᵖ).obj (op X) ≅ ((const J).obj X).op := { hom := { app := λ j, 𝟙 _ }, inv := { app := λ j, 𝟙 _ } } @[simp] lemma op_obj_op_hom_app (X : C) (j : Jᵒᵖ) : (op_obj_op X).hom.app j = 𝟙 _ := rfl @[simp] lemma op_obj_op_inv_app (X : C) (j : Jᵒᵖ) : (op_obj_op X).inv.app j = 𝟙 _ := rfl /-- 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
62fc11467ffdf8a43a0093d79fed1d793d8a9aa4
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/data/fintype/card.lean
a10a5f9cb571c170d65c43dc6dbfd1dd48a34a74
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
16,925
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.fintype.basic import algebra.big_operators.ring /-! Results about "big operations" over a `fintype`, and consequent results about cardinalities of certain types. ## Implementation note This content had previously been in `data.fintype.basic`, but was moved here to avoid requiring `algebra.big_operators` (and hence many other imports) as a dependency of `fintype`. However many of the results here really belong in `algebra.big_operators.basic` and should be moved at some point. -/ universes u v variables {α : Type*} {β : Type*} {γ : Type*} open_locale big_operators namespace fintype @[to_additive] lemma prod_bool [comm_monoid α] (f : bool → α) : ∏ b, f b = f tt * f ff := by simp lemma card_eq_sum_ones {α} [fintype α] : fintype.card α = ∑ a : α, 1 := finset.card_eq_sum_ones _ section open finset variables {ι : Type*} [decidable_eq ι] [fintype ι] @[to_additive] lemma prod_extend_by_one [comm_monoid α] (s : finset ι) (f : ι → α) : ∏ i, (if i ∈ s then f i else 1) = ∏ i in s, f i := by rw [← prod_filter, filter_mem_eq_inter, univ_inter] end section variables {M : Type*} [fintype α] [comm_monoid M] @[to_additive] lemma prod_eq_one (f : α → M) (h : ∀ a, f a = 1) : (∏ a, f a) = 1 := finset.prod_eq_one $ λ a ha, h a @[to_additive] lemma prod_congr (f g : α → M) (h : ∀ a, f a = g a) : (∏ a, f a) = ∏ a, g a := finset.prod_congr rfl $ λ a ha, h a @[to_additive] lemma prod_eq_single {f : α → M} (a : α) (h : ∀ x ≠ a, f x = 1) : (∏ x, f x) = f a := finset.prod_eq_single a (λ x _ hx, h x hx) $ λ ha, (ha (finset.mem_univ a)).elim @[to_additive] lemma prod_eq_mul {f : α → M} (a b : α) (h₁ : a ≠ b) (h₂ : ∀ x, x ≠ a ∧ x ≠ b → f x = 1) : (∏ x, f x) = (f a) * (f b) := begin apply finset.prod_eq_mul a b h₁ (λ x _ hx, h₂ x hx); exact λ hc, (hc (finset.mem_univ _)).elim end /-- If a product of a `finset` of a subsingleton type has a given value, so do the terms in that product. -/ @[to_additive "If a sum of a `finset` of a subsingleton type has a given value, so do the terms in that sum."] lemma eq_of_subsingleton_of_prod_eq {ι : Type*} [subsingleton ι] {s : finset ι} {f : ι → M} {b : M} (h : ∏ i in s, f i = b) : ∀ i ∈ s, f i = b := finset.eq_of_card_le_one_of_prod_eq (finset.card_le_one_of_subsingleton s) h end end fintype open finset section variables {M : Type*} [fintype α] [comm_monoid M] @[simp, to_additive] lemma fintype.prod_option (f : option α → M) : ∏ i, f i = f none * ∏ i, f (some i) := show ((finset.insert_none _).1.map f).prod = _, by simp only [finset.prod, finset.insert_none, multiset.map_cons, multiset.prod_cons, multiset.map_map] end @[to_additive] theorem fin.prod_univ_def [comm_monoid β] {n : ℕ} (f : fin n → β) : ∏ i, f i = ((list.fin_range n).map f).prod := by simp [fin.univ_def, finset.fin_range] @[to_additive] theorem finset.prod_range [comm_monoid β] {n : ℕ} (f : ℕ → β) : ∏ i in finset.range n, f i = ∏ i : fin n, f i := begin fapply @finset.prod_bij' _ _ _ _ _ _, exact λ k w, ⟨k, (by simpa using w)⟩, swap 3, exact λ a m, a, swap 3, exact λ a m, by simpa using a.2, all_goals { tidy, }, end @[to_additive] theorem fin.prod_of_fn [comm_monoid β] {n : ℕ} (f : fin n → β) : (list.of_fn f).prod = ∏ i, f i := by rw [list.of_fn_eq_map, fin.prod_univ_def] /-- A product of a function `f : fin 0 → β` is `1` because `fin 0` is empty -/ @[to_additive "A sum of a function `f : fin 0 → β` is `0` because `fin 0` is empty"] theorem fin.prod_univ_zero [comm_monoid β] (f : fin 0 → β) : ∏ i, f i = 1 := rfl /-- A product of a function `f : fin (n + 1) → β` over all `fin (n + 1)` is the product of `f x`, for some `x : fin (n + 1)` times the remaining product -/ theorem fin.prod_univ_succ_above [comm_monoid β] {n : ℕ} (f : fin (n + 1) → β) (x : fin (n + 1)) : ∏ i, f i = f x * ∏ i : fin n, f (x.succ_above i) := begin rw [fin.univ_succ_above, finset.prod_insert, finset.prod_image], { intros x _ y _ hxy, exact fin.succ_above_right_inj.mp hxy }, { simp [fin.succ_above_ne] } end /-- A sum of a function `f : fin (n + 1) → β` over all `fin (n + 1)` is the sum of `f x`, for some `x : fin (n + 1)` plus the remaining product -/ theorem fin.sum_univ_succ_above [add_comm_monoid β] {n : ℕ} (f : fin (n + 1) → β) (x : fin (n + 1)) : ∑ i, f i = f x + ∑ i : fin n, f (x.succ_above i) := by apply @fin.prod_univ_succ_above (multiplicative β) attribute [to_additive] fin.prod_univ_succ_above /-- A product of a function `f : fin (n + 1) → β` over all `fin (n + 1)` is the product of `f 0` plus the remaining product -/ theorem fin.prod_univ_succ [comm_monoid β] {n : ℕ} (f : fin (n + 1) → β) : ∏ i, f i = f 0 * ∏ i : fin n, f i.succ := fin.prod_univ_succ_above f 0 /-- A sum of a function `f : fin (n + 1) → β` over all `fin (n + 1)` is the sum of `f 0` plus the remaining product -/ theorem fin.sum_univ_succ [add_comm_monoid β] {n : ℕ} (f : fin (n + 1) → β) : ∑ i, f i = f 0 + ∑ i : fin n, f i.succ := fin.sum_univ_succ_above f 0 attribute [to_additive] fin.prod_univ_succ /-- A product of a function `f : fin (n + 1) → β` over all `fin (n + 1)` is the product of `f (fin.last n)` plus the remaining product -/ theorem fin.prod_univ_cast_succ [comm_monoid β] {n : ℕ} (f : fin (n + 1) → β) : ∏ i, f i = (∏ i : fin n, f i.cast_succ) * f (fin.last n) := by simpa [mul_comm] using fin.prod_univ_succ_above f (fin.last n) /-- A sum of a function `f : fin (n + 1) → β` over all `fin (n + 1)` is the sum of `f (fin.last n)` plus the remaining sum -/ theorem fin.sum_univ_cast_succ [add_comm_monoid β] {n : ℕ} (f : fin (n + 1) → β) : ∑ i, f i = ∑ i : fin n, f i.cast_succ + f (fin.last n) := by apply @fin.prod_univ_cast_succ (multiplicative β) attribute [to_additive] fin.prod_univ_cast_succ open finset @[simp] theorem fintype.card_sigma {α : Type*} (β : α → Type*) [fintype α] [∀ a, fintype (β a)] : fintype.card (sigma β) = ∑ a, fintype.card (β a) := card_sigma _ _ @[simp] lemma finset.card_pi [decidable_eq α] {δ : α → Type*} (s : finset α) (t : Π a, finset (δ a)) : (s.pi t).card = ∏ a in s, card (t a) := multiset.card_pi _ _ @[simp] lemma fintype.card_pi_finset [decidable_eq α] [fintype α] {δ : α → Type*} (t : Π a, finset (δ a)) : (fintype.pi_finset t).card = ∏ a, card (t a) := by simp [fintype.pi_finset, card_map] @[simp] lemma fintype.card_pi {β : α → Type*} [decidable_eq α] [fintype α] [f : Π a, fintype (β a)] : fintype.card (Π a, β a) = ∏ a, fintype.card (β a) := fintype.card_pi_finset _ -- FIXME ouch, this should be in the main file. @[simp] lemma fintype.card_fun [decidable_eq α] [fintype α] [fintype β] : fintype.card (α → β) = fintype.card β ^ fintype.card α := by rw [fintype.card_pi, finset.prod_const]; refl @[simp] lemma card_vector [fintype α] (n : ℕ) : fintype.card (vector α n) = fintype.card α ^ n := by rw fintype.of_equiv_card; simp @[simp, to_additive] lemma finset.prod_attach_univ [fintype α] [comm_monoid β] (f : {a : α // a ∈ @univ α _} → β) : ∏ x in univ.attach, f x = ∏ x, f ⟨x, (mem_univ _)⟩ := fintype.prod_equiv (equiv.subtype_univ_equiv (λ x, mem_univ _)) _ _ (λ x, by simp) /-- Taking a product over `univ.pi t` is the same as taking the product over `fintype.pi_finset t`. `univ.pi t` and `fintype.pi_finset t` are essentially the same `finset`, but differ in the type of their element, `univ.pi t` is a `finset (Π a ∈ univ, t a)` and `fintype.pi_finset t` is a `finset (Π a, t a)`. -/ @[to_additive "Taking a sum over `univ.pi t` is the same as taking the sum over `fintype.pi_finset t`. `univ.pi t` and `fintype.pi_finset t` are essentially the same `finset`, but differ in the type of their element, `univ.pi t` is a `finset (Π a ∈ univ, t a)` and `fintype.pi_finset t` is a `finset (Π a, t a)`."] lemma finset.prod_univ_pi [decidable_eq α] [fintype α] [comm_monoid β] {δ : α → Type*} {t : Π (a : α), finset (δ a)} (f : (Π (a : α), a ∈ (univ : finset α) → δ a) → β) : ∏ x in univ.pi t, f x = ∏ x in fintype.pi_finset t, f (λ a _, x a) := prod_bij (λ x _ a, x a (mem_univ _)) (by simp) (by simp) (by simp [function.funext_iff] {contextual := tt}) (λ x hx, ⟨λ a _, x a, by simp * at *⟩) /-- The product over `univ` of a sum can be written as a sum over the product of sets, `fintype.pi_finset`. `finset.prod_sum` is an alternative statement when the product is not over `univ` -/ lemma finset.prod_univ_sum [decidable_eq α] [fintype α] [comm_semiring β] {δ : α → Type u_1} [Π (a : α), decidable_eq (δ a)] {t : Π (a : α), finset (δ a)} {f : Π (a : α), δ a → β} : ∏ a, ∑ b in t a, f a b = ∑ p in fintype.pi_finset t, ∏ x, f x (p x) := by simp only [finset.prod_attach_univ, prod_sum, finset.sum_univ_pi] /-- Summing `a^s.card * b^(n-s.card)` over all finite subsets `s` of a fintype of cardinality `n` gives `(a + b)^n`. The "good" proof involves expanding along all coordinates using the fact that `x^n` is multilinear, but multilinear maps are only available now over rings, so we give instead a proof reducing to the usual binomial theorem to have a result over semirings. -/ lemma fintype.sum_pow_mul_eq_add_pow (α : Type*) [fintype α] {R : Type*} [comm_semiring R] (a b : R) : ∑ s : finset α, a ^ s.card * b ^ (fintype.card α - s.card) = (a + b) ^ (fintype.card α) := finset.sum_pow_mul_eq_add_pow _ _ _ lemma fin.sum_pow_mul_eq_add_pow {n : ℕ} {R : Type*} [comm_semiring R] (a b : R) : ∑ s : finset (fin n), a ^ s.card * b ^ (n - s.card) = (a + b) ^ n := by simpa using fintype.sum_pow_mul_eq_add_pow (fin n) a b lemma fin.prod_const [comm_monoid α] (n : ℕ) (x : α) : ∏ i : fin n, x = x ^ n := by simp lemma fin.sum_const [add_comm_monoid α] (n : ℕ) (x : α) : ∑ i : fin n, x = n • x := by simp @[to_additive] lemma function.bijective.prod_comp [fintype α] [fintype β] [comm_monoid γ] {f : α → β} (hf : function.bijective f) (g : β → γ) : ∏ i, g (f i) = ∏ i, g i := fintype.prod_bijective f hf _ _ (λ x, rfl) @[to_additive] lemma equiv.prod_comp [fintype α] [fintype β] [comm_monoid γ] (e : α ≃ β) (f : β → γ) : ∏ i, f (e i) = ∏ i, f i := e.bijective.prod_comp f /-- It is equivalent to sum a function over `fin n` or `finset.range n`. -/ @[to_additive] lemma fin.prod_univ_eq_prod_range [comm_monoid α] (f : ℕ → α) (n : ℕ) : ∏ i : fin n, f i = ∏ i in range n, f i := calc (∏ i : fin n, f i) = ∏ i : {x // x ∈ range n}, f i : ((equiv.fin_equiv_subtype n).trans (equiv.subtype_equiv_right (λ _, mem_range.symm))).prod_comp (f ∘ coe) ... = ∏ i in range n, f i : by rw [← attach_eq_univ, prod_attach] @[to_additive] lemma finset.prod_fin_eq_prod_range [comm_monoid β] {n : ℕ} (c : fin n → β) : ∏ i, c i = ∏ i in finset.range n, if h : i < n then c ⟨i, h⟩ else 1 := begin rw [← fin.prod_univ_eq_prod_range, finset.prod_congr rfl], rintros ⟨i, hi⟩ _, simp only [fin.coe_eq_val, hi, dif_pos] end @[to_additive] lemma finset.prod_to_finset_eq_subtype {M : Type*} [comm_monoid M] [fintype α] (p : α → Prop) [decidable_pred p] (f : α → M) : ∏ a in {x | p x}.to_finset, f a = ∏ a : subtype p, f a := by { rw ← finset.prod_subtype, simp } @[to_additive] lemma finset.prod_fiberwise [decidable_eq β] [fintype β] [comm_monoid γ] (s : finset α) (f : α → β) (g : α → γ) : ∏ b : β, ∏ a in s.filter (λ a, f a = b), g a = ∏ a in s, g a := finset.prod_fiberwise_of_maps_to (λ x _, mem_univ _) _ @[to_additive] lemma fintype.prod_fiberwise [fintype α] [decidable_eq β] [fintype β] [comm_monoid γ] (f : α → β) (g : α → γ) : (∏ b : β, ∏ a : {a // f a = b}, g (a : α)) = ∏ a, g a := begin rw [← (equiv.sigma_preimage_equiv f).prod_comp, ← univ_sigma_univ, prod_sigma], refl end lemma fintype.prod_dite [fintype α] {p : α → Prop} [decidable_pred p] [comm_monoid β] (f : Π (a : α) (ha : p a), β) (g : Π (a : α) (ha : ¬p a), β) : (∏ a, dite (p a) (f a) (g a)) = (∏ a : {a // p a}, f a a.2) * (∏ a : {a // ¬p a}, g a a.2) := begin simp only [prod_dite, attach_eq_univ], congr' 1, { convert (equiv.subtype_equiv_right _).prod_comp (λ x : {x // p x}, f x x.2), simp }, { convert (equiv.subtype_equiv_right _).prod_comp (λ x : {x // ¬p x}, g x x.2), simp } end section open finset variables {α₁ : Type*} {α₂ : Type*} {M : Type*} [fintype α₁] [fintype α₂] [comm_monoid M] @[to_additive] lemma fintype.prod_sum_elim (f : α₁ → M) (g : α₂ → M) : (∏ x, sum.elim f g x) = (∏ a₁, f a₁) * (∏ a₂, g a₂) := by { classical, rw [univ_sum_type, prod_sum_elim] } @[to_additive] lemma fintype.prod_sum_type (f : α₁ ⊕ α₂ → M) : (∏ x, f x) = (∏ a₁, f (sum.inl a₁)) * (∏ a₂, f (sum.inr a₂)) := by simp only [← fintype.prod_sum_elim, sum.elim_comp_inl_inr] end namespace list lemma prod_take_of_fn [comm_monoid α] {n : ℕ} (f : fin n → α) (i : ℕ) : ((of_fn f).take i).prod = ∏ j in finset.univ.filter (λ (j : fin n), j.val < i), f j := begin have A : ∀ (j : fin n), ¬ ((j : ℕ) < 0) := λ j, not_lt_bot, induction i with i IH, { simp [A] }, by_cases h : i < n, { have : i < length (of_fn f), by rwa [length_of_fn f], rw prod_take_succ _ _ this, have A : ((finset.univ : finset (fin n)).filter (λ j, j.val < i + 1)) = ((finset.univ : finset (fin n)).filter (λ j, j.val < i)) ∪ {(⟨i, h⟩ : fin n)}, by { ext j, simp [nat.lt_succ_iff_lt_or_eq, fin.ext_iff, - add_comm] }, have B : _root_.disjoint (finset.filter (λ (j : fin n), j.val < i) finset.univ) (singleton (⟨i, h⟩ : fin n)), by simp, rw [A, finset.prod_union B, IH], simp }, { have A : (of_fn f).take i = (of_fn f).take i.succ, { rw ← length_of_fn f at h, have : length (of_fn f) ≤ i := not_lt.mp h, rw [take_all_of_le this, take_all_of_le (le_trans this (nat.le_succ _))] }, have B : ∀ (j : fin n), ((j : ℕ) < i.succ) = ((j : ℕ) < i), { assume j, have : (j : ℕ) < i := lt_of_lt_of_le j.2 (not_lt.mp h), simp [this, lt_trans this (nat.lt_succ_self _)] }, simp [← A, B, IH] } end -- `to_additive` does not work on `prod_take_of_fn` because of `0 : ℕ` in the proof. -- Use `multiplicative` instead. lemma sum_take_of_fn [add_comm_monoid α] {n : ℕ} (f : fin n → α) (i : ℕ) : ((of_fn f).take i).sum = ∑ j in finset.univ.filter (λ (j : fin n), j.val < i), f j := @prod_take_of_fn (multiplicative α) _ n f i attribute [to_additive] prod_take_of_fn @[to_additive] lemma prod_of_fn [comm_monoid α] {n : ℕ} {f : fin n → α} : (of_fn f).prod = ∏ i, f i := begin convert prod_take_of_fn f n, { rw [take_all_of_le (le_of_eq (length_of_fn f))] }, { have : ∀ (j : fin n), (j : ℕ) < n := λ j, j.is_lt, simp [this] } end lemma alternating_sum_eq_finset_sum {G : Type*} [add_comm_group G] : ∀ (L : list G), alternating_sum L = ∑ i : fin L.length, (-1 : ℤ) ^ (i : ℕ) • L.nth_le i i.is_lt | [] := by { rw [alternating_sum, finset.sum_eq_zero], rintro ⟨i, ⟨⟩⟩ } | (g :: []) := begin show g = ∑ i : fin 1, (-1 : ℤ) ^ (i : ℕ) • [g].nth_le i i.2, rw [fin.sum_univ_succ], simp, end | (g :: h :: L) := calc g + -h + L.alternating_sum = g + -h + ∑ i : fin L.length, (-1 : ℤ) ^ (i : ℕ) • L.nth_le i i.2 : congr_arg _ (alternating_sum_eq_finset_sum _) ... = ∑ i : fin (L.length + 2), (-1 : ℤ) ^ (i : ℕ) • list.nth_le (g :: h :: L) i _ : begin rw [fin.sum_univ_succ, fin.sum_univ_succ, add_assoc], unfold_coes, simp [nat.succ_eq_add_one, pow_add], refl, end @[to_additive] lemma alternating_prod_eq_finset_prod {G : Type*} [comm_group G] : ∀ (L : list G), alternating_prod L = ∏ i : fin L.length, (L.nth_le i i.2) ^ ((-1 : ℤ) ^ (i : ℕ)) | [] := by { rw [alternating_prod, finset.prod_eq_one], rintro ⟨i, ⟨⟩⟩ } | (g :: []) := begin show g = ∏ i : fin 1, [g].nth_le i i.2 ^ (-1 : ℤ) ^ (i : ℕ), rw [fin.prod_univ_succ], simp, end | (g :: h :: L) := calc g * h⁻¹ * L.alternating_prod = g * h⁻¹ * ∏ i : fin L.length, L.nth_le i i.2 ^ (-1 : ℤ) ^ (i : ℕ) : congr_arg _ (alternating_prod_eq_finset_prod _) ... = ∏ i : fin (L.length + 2), list.nth_le (g :: h :: L) i _ ^ (-1 : ℤ) ^ (i : ℕ) : begin rw [fin.prod_univ_succ, fin.prod_univ_succ, mul_assoc], unfold_coes, simp [nat.succ_eq_add_one, pow_add], refl, end end list
d32139da852742e26be95169938eccc996cce2e8
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/logic/unnamed_323.lean
6ac7f610729c92c5585e20a9e39180cb5639ac1c
[]
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
126
lean
import data.real.basic -- BEGIN example (f : ℝ → ℝ) (h : monotone f) : ∀ {a b}, a ≤ b → f a ≤ f b := h -- END
249ce02770c49b6494e4819f37cb8bd5c87d833a
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/measure_theory/bochner_integration.lean
dfee65b3c473350c63b19b86fe23135ddffb8b60
[ "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
82,014
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Yury Kudryashov, Sébastien Gouëzel -/ import measure_theory.simple_func_dense import analysis.normed_space.bounded_linear_maps import measure_theory.l1_space import measure_theory.group import topology.sequences /-! # Bochner integral The Bochner integral extends the definition of the Lebesgue integral to functions that map from a measure space into a Banach space (complete normed vector space). It is constructed here by extending the integral on simple functions. ## Main definitions The Bochner integral is defined following these steps: 1. Define the integral on simple functions of the type `simple_func α E` (notation : `α →ₛ E`) where `E` is a real normed space. (See `simple_func.bintegral` and section `bintegral` for details. Also see `simple_func.integral` for the integral on simple functions of the type `simple_func α ℝ≥0∞`.) 2. Use `α →ₛ E` to cut out the simple functions from L1 functions, and define integral on these. The type of simple functions in L1 space is written as `α →₁ₛ[μ] E`. 3. Show that the embedding of `α →₁ₛ[μ] E` into L1 is a dense and uniform one. 4. Show that the integral defined on `α →₁ₛ[μ] E` is a continuous linear map. 5. Define the Bochner integral on L1 functions by extending the integral on integrable simple functions `α →₁ₛ[μ] E` using `continuous_linear_map.extend`. Define the Bochner integral on functions as the Bochner integral of its equivalence class in L1 space. ## Main statements 1. Basic properties of the Bochner integral on functions of type `α → E`, where `α` is a measure space and `E` is a real normed space. * `integral_zero` : `∫ 0 ∂μ = 0` * `integral_add` : `∫ x, f x + g x ∂μ = ∫ x, f ∂μ + ∫ x, g x ∂μ` * `integral_neg` : `∫ x, - f x ∂μ = - ∫ x, f x ∂μ` * `integral_sub` : `∫ x, f x - g x ∂μ = ∫ x, f x ∂μ - ∫ x, g x ∂μ` * `integral_smul` : `∫ x, r • f x ∂μ = r • ∫ x, f x ∂μ` * `integral_congr_ae` : `f =ᵐ[μ] g → ∫ x, f x ∂μ = ∫ x, g x ∂μ` * `norm_integral_le_integral_norm` : `∥∫ x, f x ∂μ∥ ≤ ∫ x, ∥f x∥ ∂μ` 2. Basic properties of the Bochner integral on functions of type `α → ℝ`, where `α` is a measure space. * `integral_nonneg_of_ae` : `0 ≤ᵐ[μ] f → 0 ≤ ∫ x, f x ∂μ` * `integral_nonpos_of_ae` : `f ≤ᵐ[μ] 0 → ∫ x, f x ∂μ ≤ 0` * `integral_mono_ae` : `f ≤ᵐ[μ] g → ∫ x, f x ∂μ ≤ ∫ x, g x ∂μ` * `integral_nonneg` : `0 ≤ f → 0 ≤ ∫ x, f x ∂μ` * `integral_nonpos` : `f ≤ 0 → ∫ x, f x ∂μ ≤ 0` * `integral_mono` : `f ≤ᵐ[μ] g → ∫ x, f x ∂μ ≤ ∫ x, g x ∂μ` 3. Propositions connecting the Bochner integral with the integral on `ℝ≥0∞`-valued functions, which is called `lintegral` and has the notation `∫⁻`. * `integral_eq_lintegral_max_sub_lintegral_min` : `∫ x, f x ∂μ = ∫⁻ x, f⁺ x ∂μ - ∫⁻ x, f⁻ x ∂μ`, where `f⁺` is the positive part of `f` and `f⁻` is the negative part of `f`. * `integral_eq_lintegral_of_nonneg_ae` : `0 ≤ᵐ[μ] f → ∫ x, f x ∂μ = ∫⁻ x, f x ∂μ` 4. `tendsto_integral_of_dominated_convergence` : the Lebesgue dominated convergence theorem 5. (In the file `set_integral`) integration commutes with continuous linear maps. * `continuous_linear_map.integral_comp_comm` * `linear_isometry.integral_comp_comm` ## Notes Some tips on how to prove a proposition if the API for the Bochner integral is not enough so that you need to unfold the definition of the Bochner integral and go back to simple functions. One method is to use the theorem `integrable.induction` in the file `set_integral`, which allows you to prove something for an arbitrary measurable + integrable function. Another method is using the following steps. See `integral_eq_lintegral_max_sub_lintegral_min` for a complicated example, which proves that `∫ f = ∫⁻ f⁺ - ∫⁻ f⁻`, with the first integral sign being the Bochner integral of a real-valued function `f : α → ℝ`, and second and third integral sign being the integral on `ℝ≥0∞`-valued functions (called `lintegral`). The proof of `integral_eq_lintegral_max_sub_lintegral_min` is scattered in sections with the name `pos_part`. Here are the usual steps of proving that a property `p`, say `∫ f = ∫⁻ f⁺ - ∫⁻ f⁻`, holds for all functions : 1. First go to the `L¹` space. For example, if you see `ennreal.to_real (∫⁻ a, ennreal.of_real $ ∥f a∥)`, that is the norm of `f` in `L¹` space. Rewrite using `L1.norm_of_fun_eq_lintegral_norm`. 2. Show that the set `{f ∈ L¹ | ∫ f = ∫⁻ f⁺ - ∫⁻ f⁻}` is closed in `L¹` using `is_closed_eq`. 3. Show that the property holds for all simple functions `s` in `L¹` space. Typically, you need to convert various notions to their `simple_func` counterpart, using lemmas like `L1.integral_coe_eq_integral`. 4. Since simple functions are dense in `L¹`, ``` univ = closure {s simple} = closure {s simple | ∫ s = ∫⁻ s⁺ - ∫⁻ s⁻} : the property holds for all simple functions ⊆ closure {f | ∫ f = ∫⁻ f⁺ - ∫⁻ f⁻} = {f | ∫ f = ∫⁻ f⁺ - ∫⁻ f⁻} : closure of a closed set is itself ``` Use `is_closed_property` or `dense_range.induction_on` for this argument. ## Notations * `α →ₛ E` : simple functions (defined in `measure_theory/integration`) * `α →₁[μ] E` : functions in L1 space, i.e., equivalence classes of integrable functions (defined in `measure_theory/lp_space`) * `α →₁ₛ[μ] E` : simple functions in L1 space, i.e., equivalence classes of integrable simple functions * `∫ a, f a ∂μ` : integral of `f` with respect to a measure `μ` * `∫ a, f a` : integral of `f` with respect to `volume`, the default measure on the ambient type We also define notations for integral on a set, which are described in the file `measure_theory/set_integral`. Note : `ₛ` is typed using `\_s`. Sometimes it shows as a box if font is missing. ## Tags Bochner integral, simple function, function space, Lebesgue dominated convergence theorem -/ noncomputable theory open_locale classical topological_space big_operators nnreal ennreal measure_theory namespace measure_theory variables {α E : Type*} [measurable_space α] [linear_order E] [has_zero E] local infixr ` →ₛ `:25 := simple_func namespace simple_func section pos_part /-- Positive part of a simple function. -/ def pos_part (f : α →ₛ E) : α →ₛ E := f.map (λb, max b 0) /-- Negative part of a simple function. -/ def neg_part [has_neg E] (f : α →ₛ E) : α →ₛ E := pos_part (-f) lemma pos_part_map_norm (f : α →ₛ ℝ) : (pos_part f).map norm = pos_part f := begin ext, rw [map_apply, real.norm_eq_abs, abs_of_nonneg], rw [pos_part, map_apply], exact le_max_right _ _ end lemma neg_part_map_norm (f : α →ₛ ℝ) : (neg_part f).map norm = neg_part f := by { rw neg_part, exact pos_part_map_norm _ } lemma pos_part_sub_neg_part (f : α →ₛ ℝ) : f.pos_part - f.neg_part = f := begin simp only [pos_part, neg_part], ext a, rw coe_sub, exact max_zero_sub_eq_self (f a) end end pos_part end simple_func end measure_theory namespace measure_theory open set filter topological_space ennreal emetric variables {α E F 𝕜 : Type*} [measurable_space α] local infixr ` →ₛ `:25 := simple_func namespace simple_func section integral /-! ### The Bochner integral of simple functions Define the Bochner integral of simple functions of the type `α →ₛ β` where `β` is a normed group, and prove basic property of this integral. -/ open finset variables [normed_group E] [measurable_space E] [normed_group F] variables {μ : measure α} {p : ℝ≥0∞} /-! #### Properties of simple functions A simple function `f : α →ₛ E` into a normed group `E` verifies, for a measure `μ`: - `mem_ℒp f 0 μ` and `mem_ℒp f ∞ μ`, since `f` is a.e.-measurable and bounded, - for `0 < p < ∞`, `mem_ℒp f p μ ↔ integrable f μ ↔ f.fin_meas_supp μ ↔ ∀ y ≠ 0, μ (f ⁻¹' {y}) < ∞`. -/ lemma exists_forall_norm_le (f : α →ₛ F) : ∃ C, ∀ x, ∥f x∥ ≤ C := exists_forall_le (f.map (λ x, ∥x∥)) lemma mem_ℒp_zero (f : α →ₛ E) (μ : measure α) : mem_ℒp f 0 μ := mem_ℒp_zero_iff_ae_measurable.mpr f.ae_measurable lemma mem_ℒp_top (f : α →ₛ E) (μ : measure α) : mem_ℒp f ∞ μ := let ⟨C, hfC⟩ := f.exists_forall_norm_le in mem_ℒp_top_of_bound f.ae_measurable C $ eventually_of_forall hfC protected lemma snorm'_eq {p : ℝ} (f : α →ₛ F) (μ : measure α) : snorm' f p μ = (∑ y in f.range, (nnnorm y : ℝ≥0∞) ^ p * μ (f ⁻¹' {y})) ^ (1/p) := have h_map : (λ a, (nnnorm (f a) : ℝ≥0∞) ^ p) = f.map (λ a : F, (nnnorm a : ℝ≥0∞) ^ p), by simp, by rw [snorm', h_map, lintegral_eq_lintegral, map_lintegral] lemma measure_preimage_lt_top_of_mem_ℒp (hp_pos : 0 < p) (hp_ne_top : p ≠ ∞) (f : α →ₛ E) (hf : mem_ℒp f p μ) (y : E) (hy_ne : y ≠ 0) : μ (f ⁻¹' {y}) < ∞ := begin have hp_pos_real : 0 < p.to_real, from ennreal.to_real_pos_iff.mpr ⟨hp_pos, hp_ne_top⟩, have hf_snorm := mem_ℒp.snorm_lt_top hf, rw [snorm_eq_snorm' hp_pos.ne.symm hp_ne_top, f.snorm'_eq, ← @ennreal.lt_rpow_one_div_iff _ _ (1 / p.to_real) (by simp [hp_pos_real]), @ennreal.top_rpow_of_pos (1 / (1 / p.to_real)) (by simp [hp_pos_real]), ennreal.sum_lt_top_iff] at hf_snorm, by_cases hyf : y ∈ f.range, swap, { suffices h_empty : f ⁻¹' {y} = ∅, by { rw [h_empty, measure_empty], exact ennreal.coe_lt_top, }, ext1 x, rw [set.mem_preimage, set.mem_singleton_iff, mem_empty_eq, iff_false], refine λ hxy, hyf _, rw [mem_range, set.mem_range], exact ⟨x, hxy⟩, }, specialize hf_snorm y hyf, rw ennreal.mul_lt_top_iff at hf_snorm, cases hf_snorm, { exact hf_snorm.2, }, cases hf_snorm, { refine absurd _ hy_ne, simpa [hp_pos_real] using hf_snorm, }, { simp [hf_snorm], }, end lemma mem_ℒp_of_finite_measure_preimage (p : ℝ≥0∞) {f : α →ₛ E} (hf : ∀ y ≠ 0, μ (f ⁻¹' {y}) < ∞) : mem_ℒp f p μ := begin by_cases hp0 : p = 0, { rw [hp0, mem_ℒp_zero_iff_ae_measurable], exact f.ae_measurable, }, by_cases hp_top : p = ∞, { rw hp_top, exact mem_ℒp_top f μ, }, refine ⟨f.ae_measurable, _⟩, rw [snorm_eq_snorm' hp0 hp_top, f.snorm'_eq], refine ennreal.rpow_lt_top_of_nonneg (by simp) (ennreal.sum_lt_top_iff.mpr (λ y hy, _)).ne, by_cases hy0 : y = 0, { simp [hy0, ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) (ne.symm hp0), hp_top⟩], }, { refine ennreal.mul_lt_top _ (hf y hy0), exact ennreal.rpow_lt_top_of_nonneg ennreal.to_real_nonneg ennreal.coe_ne_top, }, end lemma mem_ℒp_iff {f : α →ₛ E} (hp_pos : 0 < p) (hp_ne_top : p ≠ ∞) : mem_ℒp f p μ ↔ ∀ y ≠ 0, μ (f ⁻¹' {y}) < ∞ := ⟨λ h, measure_preimage_lt_top_of_mem_ℒp hp_pos hp_ne_top f h, λ h, mem_ℒp_of_finite_measure_preimage p h⟩ lemma integrable_iff {f : α →ₛ E} : integrable f μ ↔ ∀ y ≠ 0, μ (f ⁻¹' {y}) < ∞ := mem_ℒp_one_iff_integrable.symm.trans $ mem_ℒp_iff ennreal.zero_lt_one ennreal.coe_ne_top lemma mem_ℒp_iff_integrable {f : α →ₛ E} (hp_pos : 0 < p) (hp_ne_top : p ≠ ∞) : mem_ℒp f p μ ↔ integrable f μ := (mem_ℒp_iff hp_pos hp_ne_top).trans integrable_iff.symm lemma mem_ℒp_iff_fin_meas_supp {f : α →ₛ E} (hp_pos : 0 < p) (hp_ne_top : p ≠ ∞) : mem_ℒp f p μ ↔ f.fin_meas_supp μ := (mem_ℒp_iff hp_pos hp_ne_top).trans fin_meas_supp_iff.symm lemma integrable_iff_fin_meas_supp {f : α →ₛ E} : integrable f μ ↔ f.fin_meas_supp μ := integrable_iff.trans fin_meas_supp_iff.symm lemma fin_meas_supp.integrable {f : α →ₛ E} (h : f.fin_meas_supp μ) : integrable f μ := integrable_iff_fin_meas_supp.2 h lemma integrable_pair [measurable_space F] {f : α →ₛ E} {g : α →ₛ F} : integrable f μ → integrable g μ → integrable (pair f g) μ := by simpa only [integrable_iff_fin_meas_supp] using fin_meas_supp.pair lemma mem_ℒp_of_finite_measure (f : α →ₛ E) (p : ℝ≥0∞) (μ : measure α) [finite_measure μ] : mem_ℒp f p μ := let ⟨C, hfC⟩ := f.exists_forall_norm_le in mem_ℒp.of_bound f.ae_measurable C $ eventually_of_forall hfC lemma integrable_of_finite_measure [finite_measure μ] (f : α →ₛ E) : integrable f μ := mem_ℒp_one_iff_integrable.mp (f.mem_ℒp_of_finite_measure 1 μ) lemma measure_preimage_lt_top_of_integrable (f : α →ₛ E) (hf : integrable f μ) {x : E} (hx : x ≠ 0) : μ (f ⁻¹' {x}) < ∞ := integrable_iff.mp hf x hx variables [normed_space ℝ F] /-- Bochner integral of simple functions whose codomain is a real `normed_space`. -/ def integral (μ : measure α) (f : α →ₛ F) : F := ∑ x in f.range, (ennreal.to_real (μ (f ⁻¹' {x}))) • x lemma integral_eq_sum_filter (f : α →ₛ F) (μ) : f.integral μ = ∑ x in f.range.filter (λ x, x ≠ 0), (ennreal.to_real (μ (f ⁻¹' {x}))) • x := eq.symm $ sum_filter_of_ne $ λ x _, mt $ λ h0, h0.symm ▸ smul_zero _ /-- The Bochner integral is equal to a sum over any set that includes `f.range` (except `0`). -/ lemma integral_eq_sum_of_subset {f : α →ₛ F} {μ : measure α} {s : finset F} (hs : f.range.filter (λ x, x ≠ 0) ⊆ s) : f.integral μ = ∑ x in s, (μ (f ⁻¹' {x})).to_real • x := begin rw [simple_func.integral_eq_sum_filter, finset.sum_subset hs], rintro x - hx, rw [finset.mem_filter, not_and_distrib, ne.def, not_not] at hx, rcases hx with hx|rfl; [skip, simp], rw [simple_func.mem_range] at hx, rw [preimage_eq_empty]; simp [disjoint_singleton_left, hx] end /-- Calculate the integral of `g ∘ f : α →ₛ F`, where `f` is an integrable function from `α` to `E` and `g` is a function from `E` to `F`. We require `g 0 = 0` so that `g ∘ f` is integrable. -/ lemma map_integral (f : α →ₛ E) (g : E → F) (hf : integrable f μ) (hg : g 0 = 0) : (f.map g).integral μ = ∑ x in f.range, (ennreal.to_real (μ (f ⁻¹' {x}))) • (g x) := begin -- We start as in the proof of `map_lintegral` simp only [integral, range_map], refine finset.sum_image' _ (assume b hb, _), rcases mem_range.1 hb with ⟨a, rfl⟩, rw [map_preimage_singleton, ← sum_measure_preimage_singleton _ (λ _ _, f.measurable_set_preimage _)], -- Now we use `hf : integrable f μ` to show that `ennreal.to_real` is additive. by_cases ha : g (f a) = 0, { simp only [ha, smul_zero], refine (sum_eq_zero $ λ x hx, _).symm, simp only [mem_filter] at hx, simp [hx.2] }, { rw [to_real_sum, sum_smul], { refine sum_congr rfl (λ x hx, _), simp only [mem_filter] at hx, rw [hx.2] }, { intros x hx, simp only [mem_filter] at hx, refine (integrable_iff_fin_meas_supp.1 hf).meas_preimage_singleton_ne_zero _, exact λ h0, ha (hx.2 ▸ h0.symm ▸ hg) } }, end /-- `simple_func.integral` and `simple_func.lintegral` agree when the integrand has type `α →ₛ ℝ≥0∞`. But since `ℝ≥0∞` is not a `normed_space`, we need some form of coercion. See `integral_eq_lintegral` for a simpler version. -/ lemma integral_eq_lintegral' {f : α →ₛ E} {g : E → ℝ≥0∞} (hf : integrable f μ) (hg0 : g 0 = 0) (hgt : ∀b, g b < ∞): (f.map (ennreal.to_real ∘ g)).integral μ = ennreal.to_real (∫⁻ a, g (f a) ∂μ) := begin have hf' : f.fin_meas_supp μ := integrable_iff_fin_meas_supp.1 hf, simp only [← map_apply g f, lintegral_eq_lintegral], rw [map_integral f _ hf, map_lintegral, ennreal.to_real_sum], { refine finset.sum_congr rfl (λb hb, _), rw [smul_eq_mul, to_real_mul, mul_comm] }, { assume a ha, by_cases a0 : a = 0, { rw [a0, hg0, zero_mul], exact with_top.zero_lt_top }, { apply mul_lt_top (hgt a) (hf'.meas_preimage_singleton_ne_zero a0) } }, { simp [hg0] } end variables [normed_field 𝕜] [normed_space 𝕜 E] [normed_space ℝ E] [smul_comm_class ℝ 𝕜 E] lemma integral_congr {f g : α →ₛ E} (hf : integrable f μ) (h : f =ᵐ[μ] g): f.integral μ = g.integral μ := show ((pair f g).map prod.fst).integral μ = ((pair f g).map prod.snd).integral μ, from begin have inte := integrable_pair hf (hf.congr h), rw [map_integral (pair f g) _ inte prod.fst_zero, map_integral (pair f g) _ inte prod.snd_zero], refine finset.sum_congr rfl (assume p hp, _), rcases mem_range.1 hp with ⟨a, rfl⟩, by_cases eq : f a = g a, { dsimp only [pair_apply], rw eq }, { have : μ ((pair f g) ⁻¹' {(f a, g a)}) = 0, { refine measure_mono_null (assume a' ha', _) h, simp only [set.mem_preimage, mem_singleton_iff, pair_apply, prod.mk.inj_iff] at ha', show f a' ≠ g a', rwa [ha'.1, ha'.2] }, simp only [this, pair_apply, zero_smul, ennreal.zero_to_real] }, end /-- `simple_func.bintegral` and `simple_func.integral` agree when the integrand has type `α →ₛ ℝ≥0∞`. But since `ℝ≥0∞` is not a `normed_space`, we need some form of coercion. -/ lemma integral_eq_lintegral {f : α →ₛ ℝ} (hf : integrable f μ) (h_pos : 0 ≤ᵐ[μ] f) : f.integral μ = ennreal.to_real (∫⁻ a, ennreal.of_real (f a) ∂μ) := begin have : f =ᵐ[μ] f.map (ennreal.to_real ∘ ennreal.of_real) := h_pos.mono (λ a h, (ennreal.to_real_of_real h).symm), rw [← integral_eq_lintegral' hf], { exact integral_congr hf this }, { exact ennreal.of_real_zero }, { assume b, rw ennreal.lt_top_iff_ne_top, exact ennreal.of_real_ne_top } end lemma integral_add {f g : α →ₛ E} (hf : integrable f μ) (hg : integrable g μ) : integral μ (f + g) = integral μ f + integral μ g := calc integral μ (f + g) = ∑ x in (pair f g).range, ennreal.to_real (μ ((pair f g) ⁻¹' {x})) • (x.fst + x.snd) : begin rw [add_eq_map₂, map_integral (pair f g)], { exact integrable_pair hf hg }, { simp only [add_zero, prod.fst_zero, prod.snd_zero] } end ... = ∑ x in (pair f g).range, (ennreal.to_real (μ ((pair f g) ⁻¹' {x})) • x.fst + ennreal.to_real (μ ((pair f g) ⁻¹' {x})) • x.snd) : finset.sum_congr rfl $ assume a ha, smul_add _ _ _ ... = ∑ x in (pair f g).range, ennreal.to_real (μ ((pair f g) ⁻¹' {x})) • x.fst + ∑ x in (pair f g).range, ennreal.to_real (μ ((pair f g) ⁻¹' {x})) • x.snd : by rw finset.sum_add_distrib ... = ((pair f g).map prod.fst).integral μ + ((pair f g).map prod.snd).integral μ : begin rw [map_integral (pair f g), map_integral (pair f g)], { exact integrable_pair hf hg }, { refl }, { exact integrable_pair hf hg }, { refl } end ... = integral μ f + integral μ g : rfl lemma integral_neg {f : α →ₛ E} (hf : integrable f μ) : integral μ (-f) = - integral μ f := calc integral μ (-f) = integral μ (f.map (has_neg.neg)) : rfl ... = - integral μ f : begin rw [map_integral f _ hf neg_zero, integral, ← sum_neg_distrib], refine finset.sum_congr rfl (λx h, smul_neg _ _), end lemma integral_sub [borel_space E] {f g : α →ₛ E} (hf : integrable f μ) (hg : integrable g μ) : integral μ (f - g) = integral μ f - integral μ g := begin rw [sub_eq_add_neg, integral_add hf, integral_neg hg, sub_eq_add_neg], exact hg.neg end lemma integral_smul (c : 𝕜) {f : α →ₛ E} (hf : integrable f μ) : integral μ (c • f) = c • integral μ f := calc integral μ (c • f) = ∑ x in f.range, ennreal.to_real (μ (f ⁻¹' {x})) • c • x : by rw [smul_eq_map c f, map_integral f _ hf (smul_zero _)] ... = ∑ x in f.range, c • (ennreal.to_real (μ (f ⁻¹' {x}))) • x : finset.sum_congr rfl $ λ b hb, by { exact smul_comm _ _ _} ... = c • integral μ f : by simp only [integral, smul_sum, smul_smul, mul_comm] lemma norm_integral_le_integral_norm (f : α →ₛ E) (hf : integrable f μ) : ∥f.integral μ∥ ≤ (f.map norm).integral μ := begin rw [map_integral f norm hf norm_zero, integral], calc ∥∑ x in f.range, ennreal.to_real (μ (f ⁻¹' {x})) • x∥ ≤ ∑ x in f.range, ∥ennreal.to_real (μ (f ⁻¹' {x})) • x∥ : norm_sum_le _ _ ... = ∑ x in f.range, ennreal.to_real (μ (f ⁻¹' {x})) • ∥x∥ : begin refine finset.sum_congr rfl (λb hb, _), rw [norm_smul, smul_eq_mul, real.norm_eq_abs, abs_of_nonneg to_real_nonneg] end end lemma integral_add_measure {ν} (f : α →ₛ E) (hf : integrable f (μ + ν)) : f.integral (μ + ν) = f.integral μ + f.integral ν := begin simp only [integral_eq_sum_filter, ← sum_add_distrib, ← add_smul, measure.add_apply], refine sum_congr rfl (λ x hx, _), rw [to_real_add]; refine ne_of_lt ((integrable_iff_fin_meas_supp.1 _).meas_preimage_singleton_ne_zero (mem_filter.1 hx).2), exacts [hf.left_of_add_measure, hf.right_of_add_measure] end end integral end simple_func namespace L1 open ae_eq_fun variables [normed_group E] [second_countable_topology E] [measurable_space E] [borel_space E] [normed_group F] [second_countable_topology F] [measurable_space F] [borel_space F] {μ : measure α} variables (α E μ) /-- `L1.simple_func` is a subspace of L1 consisting of equivalence classes of an integrable simple function. -/ def simple_func : add_subgroup (Lp E 1 μ) := { carrier := {f : α →₁[μ] E | ∃ (s : α →ₛ E), (ae_eq_fun.mk s s.ae_measurable : α →ₘ[μ] E) = f}, zero_mem' := ⟨0, rfl⟩, add_mem' := λ f g ⟨s, hs⟩ ⟨t, ht⟩, ⟨s + t, by simp only [←hs, ←ht, mk_add_mk, add_subgroup.coe_add, mk_eq_mk, simple_func.coe_add]⟩, neg_mem' := λ f ⟨s, hs⟩, ⟨-s, by simp only [←hs, neg_mk, simple_func.coe_neg, mk_eq_mk, add_subgroup.coe_neg]⟩ } variables {α E μ} notation α ` →₁ₛ[`:25 μ `] ` E := measure_theory.L1.simple_func α E μ namespace simple_func section instances /-! Simple functions in L1 space form a `normed_space`. -/ instance : has_coe (α →₁ₛ[μ] E) (α →₁[μ] E) := coe_subtype instance : has_coe_to_fun (α →₁ₛ[μ] E) := ⟨λ f, α → E, λ f, ⇑(f : α →₁[μ] E)⟩ @[simp, norm_cast] lemma coe_coe (f : α →₁ₛ[μ] E) : ⇑(f : α →₁[μ] E) = f := rfl protected lemma eq {f g : α →₁ₛ[μ] E} : (f : α →₁[μ] E) = (g : α →₁[μ] E) → f = g := subtype.eq protected lemma eq' {f g : α →₁ₛ[μ] E} : (f : α →ₘ[μ] E) = (g : α →ₘ[μ] E) → f = g := subtype.eq ∘ subtype.eq @[norm_cast] protected lemma eq_iff {f g : α →₁ₛ[μ] E} : (f : α →₁[μ] E) = g ↔ f = g := subtype.ext_iff.symm @[norm_cast] protected lemma eq_iff' {f g : α →₁ₛ[μ] E} : (f : α →ₘ[μ] E) = g ↔ f = g := iff.intro (simple_func.eq') (congr_arg _) /-- L1 simple functions forms a `normed_group`, with the metric being inherited from L1 space, i.e., `dist f g = ennreal.to_real (∫⁻ a, edist (f a) (g a)`). Not declared as an instance as `α →₁ₛ[μ] β` will only be useful in the construction of the Bochner integral. -/ protected def normed_group : normed_group (α →₁ₛ[μ] E) := by apply_instance local attribute [instance] simple_func.normed_group /-- Functions `α →₁ₛ[μ] E` form an additive commutative group. -/ instance : inhabited (α →₁ₛ[μ] E) := ⟨0⟩ @[simp, norm_cast] lemma coe_zero : ((0 : α →₁ₛ[μ] E) : α →₁[μ] E) = 0 := rfl @[simp, norm_cast] lemma coe_add (f g : α →₁ₛ[μ] E) : ((f + g : α →₁ₛ[μ] E) : α →₁[μ] E) = f + g := rfl @[simp, norm_cast] lemma coe_neg (f : α →₁ₛ[μ] E) : ((-f : α →₁ₛ[μ] E) : α →₁[μ] E) = -f := rfl @[simp, norm_cast] lemma coe_sub (f g : α →₁ₛ[μ] E) : ((f - g : α →₁ₛ[μ] E) : α →₁[μ] E) = f - g := rfl @[simp] lemma edist_eq (f g : α →₁ₛ[μ] E) : edist f g = edist (f : α →₁[μ] E) (g : α →₁[μ] E) := rfl @[simp] lemma dist_eq (f g : α →₁ₛ[μ] E) : dist f g = dist (f : α →₁[μ] E) (g : α →₁[μ] E) := rfl lemma norm_eq (f : α →₁ₛ[μ] E) : ∥f∥ = ∥(f : α →₁[μ] E)∥ := rfl variables [normed_field 𝕜] [normed_space 𝕜 E] [measurable_space 𝕜] [opens_measurable_space 𝕜] /-- Not declared as an instance as `α →₁ₛ[μ] E` will only be useful in the construction of the Bochner integral. -/ protected def has_scalar : has_scalar 𝕜 (α →₁ₛ[μ] E) := ⟨λk f, ⟨k • f, begin rcases f with ⟨f, ⟨s, hs⟩⟩, use k • s, apply eq.trans (smul_mk k s s.ae_measurable).symm _, rw hs, refl, end ⟩⟩ local attribute [instance, priority 10000] simple_func.has_scalar @[simp, norm_cast] lemma coe_smul (c : 𝕜) (f : α →₁ₛ[μ] E) : ((c • f : α →₁ₛ[μ] E) : α →₁[μ] E) = c • (f : α →₁[μ] E) := rfl /-- Not declared as an instance as `α →₁ₛ[μ] E` will only be useful in the construction of the Bochner integral. -/ protected def module : module 𝕜 (α →₁ₛ[μ] E) := { one_smul := λf, simple_func.eq (by { simp only [coe_smul], exact one_smul _ _ }), mul_smul := λx y f, simple_func.eq (by { simp only [coe_smul], exact mul_smul _ _ _ }), smul_add := λx f g, simple_func.eq (by { simp only [coe_smul], exact smul_add _ _ _ }), smul_zero := λx, simple_func.eq (by { simp only [coe_smul], exact smul_zero _ }), add_smul := λx y f, simple_func.eq (by { simp only [coe_smul], exact add_smul _ _ _ }), zero_smul := λf, simple_func.eq (by { simp only [coe_smul], exact zero_smul _ _ }) } local attribute [instance] simple_func.normed_group simple_func.module /-- Not declared as an instance as `α →₁ₛ[μ] E` will only be useful in the construction of the Bochner integral. -/ protected def normed_space : normed_space 𝕜 (α →₁ₛ[μ] E) := ⟨ λc f, by { rw [norm_eq, norm_eq, coe_smul, norm_smul] } ⟩ end instances local attribute [instance] simple_func.normed_group simple_func.normed_space section to_L1 /-- Construct the equivalence class `[f]` of an integrable simple function `f`. -/ @[reducible] def to_L1 (f : α →ₛ E) (hf : integrable f μ) : (α →₁ₛ[μ] E) := ⟨hf.to_L1 f, ⟨f, rfl⟩⟩ lemma to_L1_eq_to_L1 (f : α →ₛ E) (hf : integrable f μ) : (to_L1 f hf : α →₁[μ] E) = hf.to_L1 f := rfl lemma to_L1_eq_mk (f : α →ₛ E) (hf : integrable f μ) : (to_L1 f hf : α →ₘ[μ] E) = ae_eq_fun.mk f f.ae_measurable := rfl lemma to_L1_zero : to_L1 (0 : α →ₛ E) (integrable_zero α E μ) = 0 := rfl lemma to_L1_add (f g : α →ₛ E) (hf : integrable f μ) (hg : integrable g μ) : to_L1 (f + g) (hf.add hg) = to_L1 f hf + to_L1 g hg := rfl lemma to_L1_neg (f : α →ₛ E) (hf : integrable f μ) : to_L1 (-f) hf.neg = -to_L1 f hf := rfl lemma to_L1_sub (f g : α →ₛ E) (hf : integrable f μ) (hg : integrable g μ) : to_L1 (f - g) (hf.sub hg) = to_L1 f hf - to_L1 g hg := by { simp only [sub_eq_add_neg, ← to_L1_neg, ← to_L1_add], refl } variables [normed_field 𝕜] [normed_space 𝕜 E] [measurable_space 𝕜] [opens_measurable_space 𝕜] lemma to_L1_smul (f : α →ₛ E) (hf : integrable f μ) (c : 𝕜) : to_L1 (c • f) (hf.smul c) = c • to_L1 f hf := rfl lemma norm_to_L1 (f : α →ₛ E) (hf : integrable f μ) : ∥to_L1 f hf∥ = ennreal.to_real (∫⁻ a, edist (f a) 0 ∂μ) := by simp [to_L1, integrable.norm_to_L1] end to_L1 section to_simple_func /-- Find a representative of a `L1.simple_func`. -/ def to_simple_func (f : α →₁ₛ[μ] E) : α →ₛ E := classical.some f.2 /-- `(to_simple_func f)` is measurable. -/ @[measurability] protected lemma measurable (f : α →₁ₛ[μ] E) : measurable (to_simple_func f) := (to_simple_func f).measurable @[measurability] protected lemma ae_measurable (f : α →₁ₛ[μ] E) : ae_measurable (to_simple_func f) μ := (simple_func.measurable f).ae_measurable /-- `to_simple_func f` is integrable. -/ protected lemma integrable (f : α →₁ₛ[μ] E) : integrable (to_simple_func f) μ := begin apply (integrable_mk (simple_func.ae_measurable f)).1, convert integrable_coe_fn f.val, exact classical.some_spec f.2 end lemma to_L1_to_simple_func (f : α →₁ₛ[μ] E) : to_L1 (to_simple_func f) (simple_func.integrable f) = f := by { rw ← simple_func.eq_iff', exact classical.some_spec f.2 } lemma to_simple_func_to_L1 (f : α →ₛ E) (hfi : integrable f μ) : to_simple_func (to_L1 f hfi) =ᵐ[μ] f := by { rw ← mk_eq_mk, exact classical.some_spec (to_L1 f hfi).2 } lemma to_simple_func_eq_to_fun (f : α →₁ₛ[μ] E) : to_simple_func f =ᵐ[μ] f := begin simp_rw [← integrable.to_L1_eq_to_L1_iff (to_simple_func f) f (simple_func.integrable f) (integrable_coe_fn ↑f), subtype.ext_iff], convert classical.some_spec f.coe_prop, exact integrable.to_L1_coe_fn _ _, end variables (E μ) lemma zero_to_simple_func : to_simple_func (0 : α →₁ₛ[μ] E) =ᵐ[μ] 0 := begin filter_upwards [to_simple_func_eq_to_fun (0 : α →₁ₛ[μ] E), Lp.coe_fn_zero E 1 μ], assume a h₁ h₂, rwa h₁, end variables {E μ} lemma add_to_simple_func (f g : α →₁ₛ[μ] E) : to_simple_func (f + g) =ᵐ[μ] to_simple_func f + to_simple_func g := begin filter_upwards [to_simple_func_eq_to_fun (f + g), to_simple_func_eq_to_fun f, to_simple_func_eq_to_fun g, Lp.coe_fn_add (f : α →₁[μ] E) g], assume a, simp only [← coe_coe, coe_add, pi.add_apply], iterate 4 { assume h, rw h } end lemma neg_to_simple_func (f : α →₁ₛ[μ] E) : to_simple_func (-f) =ᵐ[μ] - to_simple_func f := begin filter_upwards [to_simple_func_eq_to_fun (-f), to_simple_func_eq_to_fun f, Lp.coe_fn_neg (f : α →₁[μ] E)], assume a, simp only [pi.neg_apply, coe_neg, ← coe_coe], repeat { assume h, rw h } end lemma sub_to_simple_func (f g : α →₁ₛ[μ] E) : to_simple_func (f - g) =ᵐ[μ] to_simple_func f - to_simple_func g := begin filter_upwards [to_simple_func_eq_to_fun (f - g), to_simple_func_eq_to_fun f, to_simple_func_eq_to_fun g, Lp.coe_fn_sub (f : α →₁[μ] E) g], assume a, simp only [coe_sub, pi.sub_apply, ← coe_coe], repeat { assume h, rw h } end variables [normed_field 𝕜] [normed_space 𝕜 E] [measurable_space 𝕜] [opens_measurable_space 𝕜] lemma smul_to_simple_func (k : 𝕜) (f : α →₁ₛ[μ] E) : to_simple_func (k • f) =ᵐ[μ] k • to_simple_func f := begin filter_upwards [to_simple_func_eq_to_fun (k • f), to_simple_func_eq_to_fun f, Lp.coe_fn_smul k (f : α →₁[μ] E)], assume a, simp only [pi.smul_apply, coe_smul, ← coe_coe], repeat { assume h, rw h } end lemma lintegral_edist_to_simple_func_lt_top (f g : α →₁ₛ[μ] E) : ∫⁻ (x : α), edist (to_simple_func f x) (to_simple_func g x) ∂μ < ∞ := begin rw lintegral_rw₂ (to_simple_func_eq_to_fun f) (to_simple_func_eq_to_fun g), exact lintegral_edist_lt_top (integrable_coe_fn _) (integrable_coe_fn _) end lemma dist_to_simple_func (f g : α →₁ₛ[μ] E) : dist f g = ennreal.to_real (∫⁻ x, edist (to_simple_func f x) (to_simple_func g x) ∂μ) := begin rw [dist_eq, L1.dist_def, ennreal.to_real_eq_to_real], { rw lintegral_rw₂, repeat { exact ae_eq_symm (to_simple_func_eq_to_fun _) } }, { exact lintegral_edist_lt_top (integrable_coe_fn _) (integrable_coe_fn _) }, { exact lintegral_edist_to_simple_func_lt_top _ _ } end lemma norm_to_simple_func (f : α →₁ₛ[μ] E) : ∥f∥ = ennreal.to_real (∫⁻ (a : α), nnnorm ((to_simple_func f) a) ∂μ) := calc ∥f∥ = ennreal.to_real (∫⁻x, edist ((to_simple_func f) x) (to_simple_func (0 : α →₁ₛ[μ] E) x) ∂μ) : begin rw [← dist_zero_right, dist_to_simple_func] end ... = ennreal.to_real (∫⁻ (x : α), (coe ∘ nnnorm) ((to_simple_func f) x) ∂μ) : begin rw lintegral_nnnorm_eq_lintegral_edist, have : ∫⁻ x, edist ((to_simple_func f) x) ((to_simple_func (0 : α →₁ₛ[μ] E)) x) ∂μ = ∫⁻ x, edist ((to_simple_func f) x) 0 ∂μ, { refine lintegral_congr_ae ((zero_to_simple_func E μ).mono (λ a h, _)), rw [h, pi.zero_apply] }, rw [ennreal.to_real_eq_to_real], { exact this }, { exact lintegral_edist_to_simple_func_lt_top _ _ }, { rw ← this, exact lintegral_edist_to_simple_func_lt_top _ _ } end lemma norm_eq_integral (f : α →₁ₛ[μ] E) : ∥f∥ = ((to_simple_func f).map norm).integral μ := begin rw [norm_to_simple_func, simple_func.integral_eq_lintegral], { simp only [simple_func.map_apply, of_real_norm_eq_coe_nnnorm] }, { exact (simple_func.integrable f).norm }, { exact eventually_of_forall (λ x, norm_nonneg _) } end end to_simple_func section coe_to_L1 protected lemma uniform_continuous : uniform_continuous (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)) := uniform_continuous_comap protected lemma uniform_embedding : uniform_embedding (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)) := uniform_embedding_comap subtype.val_injective protected lemma uniform_inducing : uniform_inducing (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)) := simple_func.uniform_embedding.to_uniform_inducing protected lemma dense_embedding : dense_embedding (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)) := begin apply simple_func.uniform_embedding.dense_embedding, assume f, rw mem_closure_iff_seq_limit, have hfi' : integrable f μ := integrable_coe_fn f, refine ⟨λ n, ↑(to_L1 (simple_func.approx_on f (Lp.measurable f) univ 0 trivial n) (simple_func.integrable_approx_on_univ (Lp.measurable f) hfi' n)), λ n, mem_range_self _, _⟩, convert simple_func.tendsto_approx_on_univ_L1 (Lp.measurable f) hfi', rw integrable.to_L1_coe_fn end protected lemma dense_inducing : dense_inducing (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)) := simple_func.dense_embedding.to_dense_inducing protected lemma dense_range : dense_range (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)) := simple_func.dense_inducing.dense variables [normed_field 𝕜] [normed_space 𝕜 E] [measurable_space 𝕜] [opens_measurable_space 𝕜] variables (α E 𝕜) /-- The uniform and dense embedding of L1 simple functions into L1 functions. -/ def coe_to_L1 : (α →₁ₛ[μ] E) →L[𝕜] (α →₁[μ] E) := { to_fun := (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)), map_add' := λf g, rfl, map_smul' := λk f, rfl, cont := L1.simple_func.uniform_continuous.continuous, } variables {α E 𝕜} end coe_to_L1 section pos_part /-- Positive part of a simple function in L1 space. -/ def pos_part (f : α →₁ₛ[μ] ℝ) : α →₁ₛ[μ] ℝ := ⟨Lp.pos_part (f : α →₁[μ] ℝ), begin rcases f with ⟨f, s, hsf⟩, use s.pos_part, simp only [subtype.coe_mk, Lp.coe_pos_part, ← hsf, ae_eq_fun.pos_part_mk, simple_func.pos_part, simple_func.coe_map] end ⟩ /-- Negative part of a simple function in L1 space. -/ def neg_part (f : α →₁ₛ[μ] ℝ) : α →₁ₛ[μ] ℝ := pos_part (-f) @[norm_cast] lemma coe_pos_part (f : α →₁ₛ[μ] ℝ) : (pos_part f : α →₁[μ] ℝ) = Lp.pos_part (f : α →₁[μ] ℝ) := rfl @[norm_cast] lemma coe_neg_part (f : α →₁ₛ[μ] ℝ) : (neg_part f : α →₁[μ] ℝ) = Lp.neg_part (f : α →₁[μ] ℝ) := rfl end pos_part section simple_func_integral /-! Define the Bochner integral on `α →₁ₛ[μ] E` and prove basic properties of this integral. -/ variables [normed_field 𝕜] [normed_space 𝕜 E] [normed_space ℝ E] [smul_comm_class ℝ 𝕜 E] /-- The Bochner integral over simple functions in L1 space. -/ def integral (f : α →₁ₛ[μ] E) : E := ((to_simple_func f)).integral μ lemma integral_eq_integral (f : α →₁ₛ[μ] E) : integral f = ((to_simple_func f)).integral μ := rfl lemma integral_eq_lintegral {f : α →₁ₛ[μ] ℝ} (h_pos : 0 ≤ᵐ[μ] (to_simple_func f)) : integral f = ennreal.to_real (∫⁻ a, ennreal.of_real ((to_simple_func f) a) ∂μ) := by rw [integral, simple_func.integral_eq_lintegral (simple_func.integrable f) h_pos] lemma integral_congr {f g : α →₁ₛ[μ] E} (h : to_simple_func f =ᵐ[μ] to_simple_func g) : integral f = integral g := simple_func.integral_congr (simple_func.integrable f) h lemma integral_add (f g : α →₁ₛ[μ] E) : integral (f + g) = integral f + integral g := begin simp only [integral], rw ← simple_func.integral_add (simple_func.integrable f) (simple_func.integrable g), apply measure_theory.simple_func.integral_congr (simple_func.integrable (f + g)), apply add_to_simple_func end lemma integral_smul [measurable_space 𝕜] [opens_measurable_space 𝕜] (c : 𝕜) (f : α →₁ₛ[μ] E) : integral (c • f) = c • integral f := begin simp only [integral], rw ← simple_func.integral_smul _ (simple_func.integrable f), apply measure_theory.simple_func.integral_congr (simple_func.integrable (c • f)), apply smul_to_simple_func, repeat { assumption }, end lemma norm_integral_le_norm (f : α →₁ₛ[μ] E) : ∥integral f∥ ≤ ∥f∥ := begin rw [integral, norm_eq_integral], exact (to_simple_func f).norm_integral_le_integral_norm (simple_func.integrable f) end variables (α E μ 𝕜) [measurable_space 𝕜] [opens_measurable_space 𝕜] /-- The Bochner integral over simple functions in L1 space as a continuous linear map. -/ def integral_clm' : (α →₁ₛ[μ] E) →L[𝕜] E := linear_map.mk_continuous ⟨integral, integral_add, integral_smul⟩ 1 (λf, le_trans (norm_integral_le_norm _) $ by rw one_mul) /-- The Bochner integral over simple functions in L1 space as a continuous linear map over ℝ. -/ def integral_clm : (α →₁ₛ[μ] E) →L[ℝ] E := integral_clm' α E ℝ μ variables {α E μ 𝕜} local notation `Integral` := integral_clm α E μ open continuous_linear_map lemma norm_Integral_le_one : ∥Integral∥ ≤ 1 := linear_map.mk_continuous_norm_le _ (zero_le_one) _ section pos_part lemma pos_part_to_simple_func (f : α →₁ₛ[μ] ℝ) : to_simple_func (pos_part f) =ᵐ[μ] (to_simple_func f).pos_part := begin have eq : ∀ a, (to_simple_func f).pos_part a = max ((to_simple_func f) a) 0 := λa, rfl, have ae_eq : ∀ᵐ a ∂μ, to_simple_func (pos_part f) a = max ((to_simple_func f) a) 0, { filter_upwards [to_simple_func_eq_to_fun (pos_part f), Lp.coe_fn_pos_part (f : α →₁[μ] ℝ), to_simple_func_eq_to_fun f], assume a h₁ h₂ h₃, rw [h₁, ← coe_coe, coe_pos_part, h₂, coe_coe, ← h₃] }, refine ae_eq.mono (assume a h, _), rw [h, eq] end lemma neg_part_to_simple_func (f : α →₁ₛ[μ] ℝ) : to_simple_func (neg_part f) =ᵐ[μ] (to_simple_func f).neg_part := begin rw [simple_func.neg_part, measure_theory.simple_func.neg_part], filter_upwards [pos_part_to_simple_func (-f), neg_to_simple_func f], assume a h₁ h₂, rw h₁, show max _ _ = max _ _, rw h₂, refl end lemma integral_eq_norm_pos_part_sub (f : α →₁ₛ[μ] ℝ) : integral f = ∥pos_part f∥ - ∥neg_part f∥ := begin -- Convert things in `L¹` to their `simple_func` counterpart have ae_eq₁ : (to_simple_func f).pos_part =ᵐ[μ] (to_simple_func (pos_part f)).map norm, { filter_upwards [pos_part_to_simple_func f], assume a h, rw [simple_func.map_apply, h], conv_lhs { rw [← simple_func.pos_part_map_norm, simple_func.map_apply] } }, -- Convert things in `L¹` to their `simple_func` counterpart have ae_eq₂ : (to_simple_func f).neg_part =ᵐ[μ] (to_simple_func (neg_part f)).map norm, { filter_upwards [neg_part_to_simple_func f], assume a h, rw [simple_func.map_apply, h], conv_lhs { rw [← simple_func.neg_part_map_norm, simple_func.map_apply] } }, -- Convert things in `L¹` to their `simple_func` counterpart have ae_eq : ∀ᵐ a ∂μ, (to_simple_func f).pos_part a - (to_simple_func f).neg_part a = (to_simple_func (pos_part f)).map norm a - (to_simple_func (neg_part f)).map norm a, { filter_upwards [ae_eq₁, ae_eq₂], assume a h₁ h₂, rw [h₁, h₂] }, rw [integral, norm_eq_integral, norm_eq_integral, ← simple_func.integral_sub], { show (to_simple_func f).integral μ = ((to_simple_func (pos_part f)).map norm - (to_simple_func (neg_part f)).map norm).integral μ, apply measure_theory.simple_func.integral_congr (simple_func.integrable f), filter_upwards [ae_eq₁, ae_eq₂], assume a h₁ h₂, show _ = _ - _, rw [← h₁, ← h₂], have := (to_simple_func f).pos_part_sub_neg_part, conv_lhs {rw ← this}, refl }, { exact (simple_func.integrable f).max_zero.congr ae_eq₁ }, { exact (simple_func.integrable f).neg.max_zero.congr ae_eq₂ } end end pos_part end simple_func_integral end simple_func open simple_func local notation `Integral` := @integral_clm α E _ _ _ _ _ μ _ variables [normed_space ℝ E] [nondiscrete_normed_field 𝕜] [normed_space 𝕜 E] [smul_comm_class ℝ 𝕜 E] [normed_space ℝ F] [complete_space E] section integration_in_L1 local notation `to_L1` := coe_to_L1 α E ℝ local attribute [instance] simple_func.normed_group simple_func.normed_space open continuous_linear_map variables (𝕜) [measurable_space 𝕜] [opens_measurable_space 𝕜] /-- The Bochner integral in L1 space as a continuous linear map. -/ def integral_clm' : (α →₁[μ] E) →L[𝕜] E := (integral_clm' α E 𝕜 μ).extend (coe_to_L1 α E 𝕜) simple_func.dense_range simple_func.uniform_inducing variables {𝕜} /-- The Bochner integral in L1 space as a continuous linear map over ℝ. -/ def integral_clm : (α →₁[μ] E) →L[ℝ] E := integral_clm' ℝ /-- The Bochner integral in L1 space -/ def integral (f : α →₁[μ] E) : E := integral_clm f lemma integral_eq (f : α →₁[μ] E) : integral f = integral_clm f := rfl @[norm_cast] lemma simple_func.integral_L1_eq_integral (f : α →₁ₛ[μ] E) : integral (f : α →₁[μ] E) = (simple_func.integral f) := uniformly_extend_of_ind simple_func.uniform_inducing simple_func.dense_range (simple_func.integral_clm α E μ).uniform_continuous _ variables (α E) @[simp] lemma integral_zero : integral (0 : α →₁[μ] E) = 0 := map_zero integral_clm variables {α E} lemma integral_add (f g : α →₁[μ] E) : integral (f + g) = integral f + integral g := map_add integral_clm f g lemma integral_neg (f : α →₁[μ] E) : integral (-f) = - integral f := map_neg integral_clm f lemma integral_sub (f g : α →₁[μ] E) : integral (f - g) = integral f - integral g := map_sub integral_clm f g lemma integral_smul (c : 𝕜) (f : α →₁[μ] E) : integral (c • f) = c • integral f := map_smul (integral_clm' 𝕜) c f local notation `Integral` := @integral_clm α E _ _ _ _ _ μ _ _ local notation `sIntegral` := @simple_func.integral_clm α E _ _ _ _ _ μ _ lemma norm_Integral_le_one : ∥Integral∥ ≤ 1 := calc ∥Integral∥ ≤ (1 : ℝ≥0) * ∥sIntegral∥ : op_norm_extend_le _ _ _ $ λs, by {rw [nnreal.coe_one, one_mul], refl} ... = ∥sIntegral∥ : one_mul _ ... ≤ 1 : norm_Integral_le_one lemma norm_integral_le (f : α →₁[μ] E) : ∥integral f∥ ≤ ∥f∥ := calc ∥integral f∥ = ∥Integral f∥ : rfl ... ≤ ∥Integral∥ * ∥f∥ : le_op_norm _ _ ... ≤ 1 * ∥f∥ : mul_le_mul_of_nonneg_right norm_Integral_le_one $ norm_nonneg _ ... = ∥f∥ : one_mul _ @[continuity] lemma continuous_integral : continuous (λ (f : α →₁[μ] E), integral f) := by simp [L1.integral, L1.integral_clm.continuous] section pos_part local attribute [instance] fact_one_le_one_ennreal lemma integral_eq_norm_pos_part_sub (f : α →₁[μ] ℝ) : integral f = ∥Lp.pos_part f∥ - ∥Lp.neg_part f∥ := begin -- Use `is_closed_property` and `is_closed_eq` refine @is_closed_property _ _ _ (coe : (α →₁ₛ[μ] ℝ) → (α →₁[μ] ℝ)) (λ f : α →₁[μ] ℝ, integral f = ∥Lp.pos_part f∥ - ∥Lp.neg_part f∥) L1.simple_func.dense_range (is_closed_eq _ _) _ f, { exact cont _ }, { refine continuous.sub (continuous_norm.comp Lp.continuous_pos_part) (continuous_norm.comp Lp.continuous_neg_part) }, -- Show that the property holds for all simple functions in the `L¹` space. { assume s, norm_cast, rw [← simple_func.norm_eq, ← simple_func.norm_eq], exact simple_func.integral_eq_norm_pos_part_sub _} end end pos_part end integration_in_L1 end L1 variables [normed_group E] [second_countable_topology E] [normed_space ℝ E] [complete_space E] [measurable_space E] [borel_space E] [nondiscrete_normed_field 𝕜] [normed_space 𝕜 E] [smul_comm_class ℝ 𝕜 E] [normed_group F] [second_countable_topology F] [normed_space ℝ F] [complete_space F] [measurable_space F] [borel_space F] /-- The Bochner integral -/ def integral (μ : measure α) (f : α → E) : E := if hf : integrable f μ then L1.integral (hf.to_L1 f) else 0 /-! In the notation for integrals, an expression like `∫ x, g ∥x∥ ∂μ` will not be parsed correctly, and needs parentheses. We do not set the binding power of `r` to `0`, because then `∫ x, f x = 0` will be parsed incorrectly. -/ notation `∫` binders `, ` r:(scoped:60 f, f) ` ∂` μ:70 := integral μ r notation `∫` binders `, ` r:(scoped:60 f, integral volume f) := r notation `∫` binders ` in ` s `, ` r:(scoped:60 f, f) ` ∂` μ:70 := integral (measure.restrict μ s) r notation `∫` binders ` in ` s `, ` r:(scoped:60 f, integral (measure.restrict volume s) f) := r section properties open continuous_linear_map measure_theory.simple_func variables {f g : α → E} {μ : measure α} lemma integral_eq (f : α → E) (hf : integrable f μ) : ∫ a, f a ∂μ = L1.integral (hf.to_L1 f) := dif_pos hf lemma L1.integral_eq_integral (f : α →₁[μ] E) : L1.integral f = ∫ a, f a ∂μ := by rw [integral_eq _ (L1.integrable_coe_fn f), integrable.to_L1_coe_fn] lemma integral_undef (h : ¬ integrable f μ) : ∫ a, f a ∂μ = 0 := dif_neg h lemma integral_non_ae_measurable (h : ¬ ae_measurable f μ) : ∫ a, f a ∂μ = 0 := integral_undef $ not_and_of_not_left _ h variables (α E) lemma integral_zero : ∫ a : α, (0:E) ∂μ = 0 := by { rw [integral_eq _ (integrable_zero α E μ)], exact L1.integral_zero _ _ } @[simp] lemma integral_zero' : integral μ (0 : α → E) = 0 := integral_zero α E variables {α E} lemma integral_add (hf : integrable f μ) (hg : integrable g μ) : ∫ a, f a + g a ∂μ = ∫ a, f a ∂μ + ∫ a, g a ∂μ := begin rw [integral_eq, integral_eq f hf, integral_eq g hg, ← L1.integral_add], { refl }, { exact hf.add hg } end lemma integral_add' (hf : integrable f μ) (hg : integrable g μ) : ∫ a, (f + g) a ∂μ = ∫ a, f a ∂μ + ∫ a, g a ∂μ := integral_add hf hg lemma integral_neg (f : α → E) : ∫ a, -f a ∂μ = - ∫ a, f a ∂μ := begin by_cases hf : integrable f μ, { rw [integral_eq f hf, integral_eq (λa, - f a) hf.neg, ← L1.integral_neg], refl }, { rw [integral_undef hf, integral_undef, neg_zero], rwa [← integrable_neg_iff] at hf } end lemma integral_neg' (f : α → E) : ∫ a, (-f) a ∂μ = - ∫ a, f a ∂μ := integral_neg f lemma integral_sub (hf : integrable f μ) (hg : integrable g μ) : ∫ a, f a - g a ∂μ = ∫ a, f a ∂μ - ∫ a, g a ∂μ := by { simp only [sub_eq_add_neg, ← integral_neg], exact integral_add hf hg.neg } lemma integral_sub' (hf : integrable f μ) (hg : integrable g μ) : ∫ a, (f - g) a ∂μ = ∫ a, f a ∂μ - ∫ a, g a ∂μ := integral_sub hf hg lemma integral_smul [measurable_space 𝕜] [opens_measurable_space 𝕜] (c : 𝕜) (f : α → E) : ∫ a, c • (f a) ∂μ = c • ∫ a, f a ∂μ := begin by_cases hf : integrable f μ, { rw [integral_eq f hf, integral_eq (λa, c • (f a)), integrable.to_L1_smul, L1.integral_smul], }, { by_cases hr : c = 0, { simp only [hr, measure_theory.integral_zero, zero_smul] }, have hf' : ¬ integrable (λ x, c • f x) μ, { change ¬ integrable (c • f) μ, rwa [integrable_smul_iff hr f] }, rw [integral_undef hf, integral_undef hf', smul_zero] } end lemma integral_mul_left (r : ℝ) (f : α → ℝ) : ∫ a, r * (f a) ∂μ = r * ∫ a, f a ∂μ := integral_smul r f lemma integral_mul_right (r : ℝ) (f : α → ℝ) : ∫ a, (f a) * r ∂μ = ∫ a, f a ∂μ * r := by { simp only [mul_comm], exact integral_mul_left r f } lemma integral_div (r : ℝ) (f : α → ℝ) : ∫ a, (f a) / r ∂μ = ∫ a, f a ∂μ / r := integral_mul_right r⁻¹ f lemma integral_congr_ae (h : f =ᵐ[μ] g) : ∫ a, f a ∂μ = ∫ a, g a ∂μ := begin by_cases hfi : integrable f μ, { have hgi : integrable g μ := hfi.congr h, rw [integral_eq f hfi, integral_eq g hgi, (integrable.to_L1_eq_to_L1_iff f g hfi hgi).2 h] }, { have hgi : ¬ integrable g μ, { rw integrable_congr h at hfi, exact hfi }, rw [integral_undef hfi, integral_undef hgi] }, end @[simp] lemma L1.integral_of_fun_eq_integral {f : α → E} (hf : integrable f μ) : ∫ a, (hf.to_L1 f) a ∂μ = ∫ a, f a ∂μ := integral_congr_ae $ by simp [integrable.coe_fn_to_L1] @[continuity] lemma continuous_integral : continuous (λ (f : α →₁[μ] E), ∫ a, f a ∂μ) := by { simp only [← L1.integral_eq_integral], exact L1.continuous_integral } lemma norm_integral_le_lintegral_norm (f : α → E) : ∥∫ a, f a ∂μ∥ ≤ ennreal.to_real (∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ) := begin by_cases hf : integrable f μ, { rw [integral_eq f hf, ← integrable.norm_to_L1_eq_lintegral_norm f hf], exact L1.norm_integral_le _ }, { rw [integral_undef hf, norm_zero], exact to_real_nonneg } end lemma ennnorm_integral_le_lintegral_ennnorm (f : α → E) : (nnnorm (∫ a, f a ∂μ) : ℝ≥0∞) ≤ ∫⁻ a, (nnnorm (f a)) ∂μ := by { simp_rw [← of_real_norm_eq_coe_nnnorm], apply ennreal.of_real_le_of_le_to_real, exact norm_integral_le_lintegral_norm f } lemma integral_eq_zero_of_ae {f : α → E} (hf : f =ᵐ[μ] 0) : ∫ a, f a ∂μ = 0 := by simp [integral_congr_ae hf, integral_zero] /-- If `f` has finite integral, then `∫ x in s, f x ∂μ` is absolutely continuous in `s`: it tends to zero as `μ s` tends to zero. -/ lemma has_finite_integral.tendsto_set_integral_nhds_zero {ι} {f : α → E} (hf : has_finite_integral f μ) {l : filter ι} {s : ι → set α} (hs : tendsto (μ ∘ s) l (𝓝 0)) : tendsto (λ i, ∫ x in s i, f x ∂μ) l (𝓝 0) := begin rw [tendsto_zero_iff_norm_tendsto_zero], simp_rw [← coe_nnnorm, ← nnreal.coe_zero, nnreal.tendsto_coe, ← ennreal.tendsto_coe, ennreal.coe_zero], exact tendsto_of_tendsto_of_tendsto_of_le_of_le tendsto_const_nhds (tendsto_set_lintegral_zero hf hs) (λ i, zero_le _) (λ i, ennnorm_integral_le_lintegral_ennnorm _) end /-- If `f` is integrable, then `∫ x in s, f x ∂μ` is absolutely continuous in `s`: it tends to zero as `μ s` tends to zero. -/ lemma integrable.tendsto_set_integral_nhds_zero {ι} {f : α → E} (hf : integrable f μ) {l : filter ι} {s : ι → set α} (hs : tendsto (μ ∘ s) l (𝓝 0)) : tendsto (λ i, ∫ x in s i, f x ∂μ) l (𝓝 0) := hf.2.tendsto_set_integral_nhds_zero hs /-- If `F i → f` in `L1`, then `∫ x, F i x ∂μ → ∫ x, f x∂μ`. -/ lemma tendsto_integral_of_L1 {ι} (f : α → E) (hfi : integrable f μ) {F : ι → α → E} {l : filter ι} (hFi : ∀ᶠ i in l, integrable (F i) μ) (hF : tendsto (λ i, ∫⁻ x, edist (F i x) (f x) ∂μ) l (𝓝 0)) : tendsto (λ i, ∫ x, F i x ∂μ) l (𝓝 $ ∫ x, f x ∂μ) := begin rw [tendsto_iff_norm_tendsto_zero], replace hF : tendsto (λ i, ennreal.to_real $ ∫⁻ x, edist (F i x) (f x) ∂μ) l (𝓝 0) := (ennreal.tendsto_to_real zero_ne_top).comp hF, refine squeeze_zero_norm' (hFi.mp $ hFi.mono $ λ i hFi hFm, _) hF, simp only [norm_norm, ← integral_sub hFi hfi, edist_dist, dist_eq_norm], apply norm_integral_le_lintegral_norm end /-- Lebesgue dominated convergence theorem provides sufficient conditions under which almost everywhere convergence of a sequence of functions implies the convergence of their integrals. -/ theorem tendsto_integral_of_dominated_convergence {F : ℕ → α → E} {f : α → E} (bound : α → ℝ) (F_measurable : ∀ n, ae_measurable (F n) μ) (f_measurable : ae_measurable f μ) (bound_integrable : integrable bound μ) (h_bound : ∀ n, ∀ᵐ a ∂μ, ∥F n a∥ ≤ bound a) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) : tendsto (λn, ∫ a, F n a ∂μ) at_top (𝓝 $ ∫ a, f a ∂μ) := begin /- To show `(∫ a, F n a) --> (∫ f)`, suffices to show `∥∫ a, F n a - ∫ f∥ --> 0` -/ rw tendsto_iff_norm_tendsto_zero, /- But `0 ≤ ∥∫ a, F n a - ∫ f∥ = ∥∫ a, (F n a - f a) ∥ ≤ ∫ a, ∥F n a - f a∥, and thus we apply the sandwich theorem and prove that `∫ a, ∥F n a - f a∥ --> 0` -/ have lintegral_norm_tendsto_zero : tendsto (λn, ennreal.to_real $ ∫⁻ a, (ennreal.of_real ∥F n a - f a∥) ∂μ) at_top (𝓝 0) := (tendsto_to_real zero_ne_top).comp (tendsto_lintegral_norm_of_dominated_convergence F_measurable f_measurable bound_integrable.has_finite_integral h_bound h_lim), -- Use the sandwich theorem refine squeeze_zero (λ n, norm_nonneg _) _ lintegral_norm_tendsto_zero, -- Show `∥∫ a, F n a - ∫ f∥ ≤ ∫ a, ∥F n a - f a∥` for all `n` { assume n, have h₁ : integrable (F n) μ := bound_integrable.mono' (F_measurable n) (h_bound _), have h₂ : integrable f μ := ⟨f_measurable, has_finite_integral_of_dominated_convergence bound_integrable.has_finite_integral h_bound h_lim⟩, rw ← integral_sub h₁ h₂, exact norm_integral_le_lintegral_norm _ } end /-- Lebesgue dominated convergence theorem for filters with a countable basis -/ lemma tendsto_integral_filter_of_dominated_convergence {ι} {l : filter ι} {F : ι → α → E} {f : α → E} (bound : α → ℝ) (hl_cb : l.is_countably_generated) (hF_meas : ∀ᶠ n in l, ae_measurable (F n) μ) (f_measurable : ae_measurable f μ) (h_bound : ∀ᶠ n in l, ∀ᵐ a ∂μ, ∥F n a∥ ≤ bound a) (bound_integrable : integrable bound μ) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) l (𝓝 (f a))) : tendsto (λn, ∫ a, F n a ∂μ) l (𝓝 $ ∫ a, f a ∂μ) := begin rw hl_cb.tendsto_iff_seq_tendsto, { intros x xl, have hxl, { rw tendsto_at_top' at xl, exact xl }, have h := inter_mem_sets hF_meas h_bound, replace h := hxl _ h, rcases h with ⟨k, h⟩, rw ← tendsto_add_at_top_iff_nat k, refine tendsto_integral_of_dominated_convergence _ _ _ _ _ _, { exact bound }, { intro, refine (h _ _).1, exact nat.le_add_left _ _ }, { assumption }, { assumption }, { intro, refine (h _ _).2, exact nat.le_add_left _ _ }, { filter_upwards [h_lim], assume a h_lim, apply @tendsto.comp _ _ _ (λn, x (n + k)) (λn, F n a), { assumption }, rw tendsto_add_at_top_iff_nat, assumption } }, end variables {X : Type*} [topological_space X] [first_countable_topology X] lemma continuous_at_of_dominated {F : X → α → E} {x₀ : X} {bound : α → ℝ} (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_measurable (F x) μ) (h_bound : ∀ᶠ x in 𝓝 x₀, ∀ᵐ a ∂μ, ∥F x a∥ ≤ bound a) (bound_integrable : integrable bound μ) (h_cont : ∀ᵐ a ∂μ, continuous_at (λ x, F x a) x₀) : continuous_at (λ x, ∫ a, F x a ∂μ) x₀ := tendsto_integral_filter_of_dominated_convergence bound (first_countable_topology.nhds_generated_countable x₀) ‹_› (mem_of_mem_nhds hF_meas : _) ‹_› ‹_› ‹_› lemma continuous_of_dominated {F : X → α → E} {bound : α → ℝ} (hF_meas : ∀ x, ae_measurable (F x) μ) (h_bound : ∀ x, ∀ᵐ a ∂μ, ∥F x a∥ ≤ bound a) (bound_integrable : integrable bound μ) (h_cont : ∀ᵐ a ∂μ, continuous (λ x, F x a)) : continuous (λ x, ∫ a, F x a ∂μ) := continuous_iff_continuous_at.mpr (λ x₀, continuous_at_of_dominated (eventually_of_forall hF_meas) (eventually_of_forall h_bound) ‹_› $ h_cont.mono $ λ _, continuous.continuous_at) /-- The Bochner integral of a real-valued function `f : α → ℝ` is the difference between the integral of the positive part of `f` and the integral of the negative part of `f`. -/ lemma integral_eq_lintegral_pos_part_sub_lintegral_neg_part {f : α → ℝ} (hf : integrable f μ) : ∫ a, f a ∂μ = ennreal.to_real (∫⁻ a, (ennreal.of_real $ f a) ∂μ) - ennreal.to_real (∫⁻ a, (ennreal.of_real $ - f a) ∂μ) := let f₁ := hf.to_L1 f in -- Go to the `L¹` space have eq₁ : ennreal.to_real (∫⁻ a, (ennreal.of_real $ f a) ∂μ) = ∥Lp.pos_part f₁∥ := begin rw L1.norm_def, congr' 1, apply lintegral_congr_ae, filter_upwards [Lp.coe_fn_pos_part f₁, hf.coe_fn_to_L1], assume a h₁ h₂, rw [h₁, h₂, ennreal.of_real], congr' 1, apply nnreal.eq, simp [real.norm_of_nonneg, le_max_right, real.coe_to_nnreal] end, -- Go to the `L¹` space have eq₂ : ennreal.to_real (∫⁻ a, (ennreal.of_real $ - f a) ∂μ) = ∥Lp.neg_part f₁∥ := begin rw L1.norm_def, congr' 1, apply lintegral_congr_ae, filter_upwards [Lp.coe_fn_neg_part f₁, hf.coe_fn_to_L1], assume a h₁ h₂, rw [h₁, h₂, ennreal.of_real], congr' 1, apply nnreal.eq, simp only [real.norm_of_nonneg, min_le_right, neg_nonneg, real.coe_to_nnreal', subtype.coe_mk], rw [← max_neg_neg, coe_nnnorm, neg_zero, real.norm_of_nonneg (le_max_right (-f a) 0)] end, begin rw [eq₁, eq₂, integral, dif_pos], exact L1.integral_eq_norm_pos_part_sub _ end lemma integral_eq_lintegral_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ] f) (hfm : ae_measurable f μ) : ∫ a, f a ∂μ = ennreal.to_real (∫⁻ a, (ennreal.of_real $ f a) ∂μ) := begin by_cases hfi : integrable f μ, { rw integral_eq_lintegral_pos_part_sub_lintegral_neg_part hfi, have h_min : ∫⁻ a, ennreal.of_real (-f a) ∂μ = 0, { rw lintegral_eq_zero_iff', { refine hf.mono _, simp only [pi.zero_apply], assume a h, simp only [h, neg_nonpos, of_real_eq_zero], }, { exact measurable_of_real.comp_ae_measurable hfm.neg } }, rw [h_min, zero_to_real, _root_.sub_zero] }, { rw integral_undef hfi, simp_rw [integrable, hfm, has_finite_integral_iff_norm, lt_top_iff_ne_top, ne.def, true_and, not_not] at hfi, have : ∫⁻ (a : α), ennreal.of_real (f a) ∂μ = ∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ, { refine lintegral_congr_ae (hf.mono $ assume a h, _), rw [real.norm_eq_abs, abs_of_nonneg h] }, rw [this, hfi], refl } end lemma integral_eq_integral_pos_part_sub_integral_neg_part {f : α → ℝ} (hf : integrable f μ) : ∫ a, f a ∂μ = (∫ a, real.to_nnreal (f a) ∂μ) - (∫ a, real.to_nnreal (-f a) ∂μ) := begin rw [← integral_sub hf.real_to_nnreal], { simp }, { exact hf.neg.real_to_nnreal } end lemma integral_nonneg_of_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ] f) : 0 ≤ ∫ a, f a ∂μ := begin by_cases hfm : ae_measurable f μ, { rw integral_eq_lintegral_of_nonneg_ae hf hfm, exact to_real_nonneg }, { rw integral_non_ae_measurable hfm } end lemma lintegral_coe_eq_integral (f : α → ℝ≥0) (hfi : integrable (λ x, (f x : ℝ)) μ) : ∫⁻ a, f a ∂μ = ennreal.of_real ∫ a, f a ∂μ := begin simp_rw [integral_eq_lintegral_of_nonneg_ae (eventually_of_forall (λ x, (f x).coe_nonneg)) hfi.ae_measurable, ← ennreal.coe_nnreal_eq], rw [ennreal.of_real_to_real], rw [← lt_top_iff_ne_top], convert hfi.has_finite_integral, ext1 x, rw [nnreal.nnnorm_eq] end lemma integral_to_real {f : α → ℝ≥0∞} (hfm : ae_measurable f μ) (hf : ∀ᵐ x ∂μ, f x < ∞) : ∫ a, (f a).to_real ∂μ = (∫⁻ a, f a ∂μ).to_real := begin rw [integral_eq_lintegral_of_nonneg_ae _ hfm.ennreal_to_real], { rw lintegral_congr_ae, refine hf.mp (eventually_of_forall _), intros x hx, rw [lt_top_iff_ne_top] at hx, simp [hx] }, { exact (eventually_of_forall $ λ x, ennreal.to_real_nonneg) } end lemma integral_nonneg {f : α → ℝ} (hf : 0 ≤ f) : 0 ≤ ∫ a, f a ∂μ := integral_nonneg_of_ae $ eventually_of_forall hf lemma integral_nonpos_of_ae {f : α → ℝ} (hf : f ≤ᵐ[μ] 0) : ∫ a, f a ∂μ ≤ 0 := begin have hf : 0 ≤ᵐ[μ] (-f) := hf.mono (assume a h, by rwa [pi.neg_apply, pi.zero_apply, neg_nonneg]), have : 0 ≤ ∫ a, -f a ∂μ := integral_nonneg_of_ae hf, rwa [integral_neg, neg_nonneg] at this, end lemma integral_nonpos {f : α → ℝ} (hf : f ≤ 0) : ∫ a, f a ∂μ ≤ 0 := integral_nonpos_of_ae $ eventually_of_forall hf lemma integral_eq_zero_iff_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ] f) (hfi : integrable f μ) : ∫ x, f x ∂μ = 0 ↔ f =ᵐ[μ] 0 := by simp_rw [integral_eq_lintegral_of_nonneg_ae hf hfi.1, ennreal.to_real_eq_zero_iff, lintegral_eq_zero_iff' (ennreal.measurable_of_real.comp_ae_measurable hfi.1), ← ennreal.not_lt_top, ← has_finite_integral_iff_of_real hf, hfi.2, not_true, or_false, ← hf.le_iff_eq, filter.eventually_eq, filter.eventually_le, (∘), pi.zero_apply, ennreal.of_real_eq_zero] lemma integral_eq_zero_iff_of_nonneg {f : α → ℝ} (hf : 0 ≤ f) (hfi : integrable f μ) : ∫ x, f x ∂μ = 0 ↔ f =ᵐ[μ] 0 := integral_eq_zero_iff_of_nonneg_ae (eventually_of_forall hf) hfi lemma integral_pos_iff_support_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ] f) (hfi : integrable f μ) : (0 < ∫ x, f x ∂μ) ↔ 0 < μ (function.support f) := by simp_rw [(integral_nonneg_of_ae hf).lt_iff_ne, pos_iff_ne_zero, ne.def, @eq_comm ℝ 0, integral_eq_zero_iff_of_nonneg_ae hf hfi, filter.eventually_eq, ae_iff, pi.zero_apply, function.support] lemma integral_pos_iff_support_of_nonneg {f : α → ℝ} (hf : 0 ≤ f) (hfi : integrable f μ) : (0 < ∫ x, f x ∂μ) ↔ 0 < μ (function.support f) := integral_pos_iff_support_of_nonneg_ae (eventually_of_forall hf) hfi section normed_group variables {H : Type*} [normed_group H] [second_countable_topology H] [measurable_space H] [borel_space H] lemma L1.norm_eq_integral_norm (f : α →₁[μ] H) : ∥f∥ = ∫ a, ∥f a∥ ∂μ := begin simp only [snorm, snorm', ennreal.one_to_real, ennreal.rpow_one, Lp.norm_def, if_false, ennreal.one_ne_top, one_ne_zero, _root_.div_one], rw integral_eq_lintegral_of_nonneg_ae (eventually_of_forall (by simp [norm_nonneg])) (continuous_norm.measurable.comp_ae_measurable (Lp.ae_measurable f)), simp [of_real_norm_eq_coe_nnnorm] end lemma L1.norm_of_fun_eq_integral_norm {f : α → H} (hf : integrable f μ) : ∥hf.to_L1 f∥ = ∫ a, ∥f a∥ ∂μ := begin rw L1.norm_eq_integral_norm, refine integral_congr_ae _, apply hf.coe_fn_to_L1.mono, intros a ha, simp [ha] end end normed_group lemma integral_mono_ae {f g : α → ℝ} (hf : integrable f μ) (hg : integrable g μ) (h : f ≤ᵐ[μ] g) : ∫ a, f a ∂μ ≤ ∫ a, g a ∂μ := le_of_sub_nonneg $ integral_sub hg hf ▸ integral_nonneg_of_ae $ h.mono (λ a, sub_nonneg_of_le) @[mono] lemma integral_mono {f g : α → ℝ} (hf : integrable f μ) (hg : integrable g μ) (h : f ≤ g) : ∫ a, f a ∂μ ≤ ∫ a, g a ∂μ := integral_mono_ae hf hg $ eventually_of_forall h lemma integral_mono_of_nonneg {f g : α → ℝ} (hf : 0 ≤ᵐ[μ] f) (hgi : integrable g μ) (h : f ≤ᵐ[μ] g) : ∫ a, f a ∂μ ≤ ∫ a, g a ∂μ := begin by_cases hfm : ae_measurable f μ, { refine integral_mono_ae ⟨hfm, _⟩ hgi h, refine (hgi.has_finite_integral.mono $ h.mp $ hf.mono $ λ x hf hfg, _), simpa [real.norm_eq_abs, abs_of_nonneg hf, abs_of_nonneg (le_trans hf hfg)] }, { rw [integral_non_ae_measurable hfm], exact integral_nonneg_of_ae (hf.trans h) } end lemma norm_integral_le_integral_norm (f : α → E) : ∥(∫ a, f a ∂μ)∥ ≤ ∫ a, ∥f a∥ ∂μ := have le_ae : ∀ᵐ a ∂μ, 0 ≤ ∥f a∥ := eventually_of_forall (λa, norm_nonneg _), classical.by_cases ( λh : ae_measurable f μ, calc ∥∫ a, f a ∂μ∥ ≤ ennreal.to_real (∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ) : norm_integral_le_lintegral_norm _ ... = ∫ a, ∥f a∥ ∂μ : (integral_eq_lintegral_of_nonneg_ae le_ae $ ae_measurable.norm h).symm ) ( λh : ¬ae_measurable f μ, begin rw [integral_non_ae_measurable h, norm_zero], exact integral_nonneg_of_ae le_ae end ) lemma norm_integral_le_of_norm_le {f : α → E} {g : α → ℝ} (hg : integrable g μ) (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ g x) : ∥∫ x, f x ∂μ∥ ≤ ∫ x, g x ∂μ := calc ∥∫ x, f x ∂μ∥ ≤ ∫ x, ∥f x∥ ∂μ : norm_integral_le_integral_norm f ... ≤ ∫ x, g x ∂μ : integral_mono_of_nonneg (eventually_of_forall $ λ x, norm_nonneg _) hg h lemma integral_finset_sum {ι} (s : finset ι) {f : ι → α → E} (hf : ∀ i, integrable (f i) μ) : ∫ a, ∑ i in s, f i a ∂μ = ∑ i in s, ∫ a, f i a ∂μ := begin refine finset.induction_on s _ _, { simp only [integral_zero, finset.sum_empty] }, { assume i s his ih, simp only [his, finset.sum_insert, not_false_iff], rw [integral_add (hf _) (integrable_finset_sum s hf), ih] } end lemma simple_func.integral_eq_integral (f : α →ₛ E) (hfi : integrable f μ) : f.integral μ = ∫ x, f x ∂μ := begin rw [integral_eq f hfi, ← L1.simple_func.to_L1_eq_to_L1, L1.simple_func.integral_L1_eq_integral, L1.simple_func.integral_eq_integral], exact simple_func.integral_congr hfi (L1.simple_func.to_simple_func_to_L1 _ _).symm end lemma simple_func.integral_eq_sum (f : α →ₛ E) (hfi : integrable f μ) : ∫ x, f x ∂μ = ∑ x in f.range, (ennreal.to_real (μ (f ⁻¹' {x}))) • x := by rw [← f.integral_eq_integral hfi, simple_func.integral] @[simp] lemma integral_const (c : E) : ∫ x : α, c ∂μ = (μ univ).to_real • c := begin by_cases hμ : μ univ < ∞, { haveI : finite_measure μ := ⟨hμ⟩, calc ∫ x : α, c ∂μ = (simple_func.const α c).integral μ : ((simple_func.const α c).integral_eq_integral (integrable_const _)).symm ... = _ : _, rw [simple_func.integral], by_cases ha : nonempty α, { resetI, simp [preimage_const_of_mem] }, { simp [μ.eq_zero_of_not_nonempty ha] } }, { by_cases hc : c = 0, { simp [hc, integral_zero] }, { have : ¬integrable (λ x : α, c) μ, { simp only [integrable_const_iff, not_or_distrib], exact ⟨hc, hμ⟩ }, simp only [not_lt, top_le_iff] at hμ, simp [integral_undef, *] } } end lemma norm_integral_le_of_norm_le_const [finite_measure μ] {f : α → E} {C : ℝ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ C) : ∥∫ x, f x ∂μ∥ ≤ C * (μ univ).to_real := calc ∥∫ x, f x ∂μ∥ ≤ ∫ x, C ∂μ : norm_integral_le_of_norm_le (integrable_const C) h ... = C * (μ univ).to_real : by rw [integral_const, smul_eq_mul, mul_comm] lemma tendsto_integral_approx_on_univ_of_measurable {f : α → E} (fmeas : measurable f) (hf : integrable f μ) : tendsto (λ n, (simple_func.approx_on f fmeas univ 0 trivial n).integral μ) at_top (𝓝 $ ∫ x, f x ∂μ) := begin have : tendsto (λ n, ∫ x, simple_func.approx_on f fmeas univ 0 trivial n x ∂μ) at_top (𝓝 $ ∫ x, f x ∂μ) := tendsto_integral_of_L1 _ hf (eventually_of_forall $ simple_func.integrable_approx_on_univ fmeas hf) (simple_func.tendsto_approx_on_univ_L1_edist fmeas hf), simpa only [simple_func.integral_eq_integral, simple_func.integrable_approx_on_univ fmeas hf] end variable {ν : measure α} private lemma integral_add_measure_of_measurable {f : α → E} (fmeas : measurable f) (hμ : integrable f μ) (hν : integrable f ν) : ∫ x, f x ∂(μ + ν) = ∫ x, f x ∂μ + ∫ x, f x ∂ν := begin have hfi := hμ.add_measure hν, refine tendsto_nhds_unique (tendsto_integral_approx_on_univ_of_measurable fmeas hfi) _, simpa only [simple_func.integral_add_measure _ (simple_func.integrable_approx_on_univ fmeas hfi _)] using (tendsto_integral_approx_on_univ_of_measurable fmeas hμ).add (tendsto_integral_approx_on_univ_of_measurable fmeas hν) end lemma integral_add_measure {f : α → E} (hμ : integrable f μ) (hν : integrable f ν) : ∫ x, f x ∂(μ + ν) = ∫ x, f x ∂μ + ∫ x, f x ∂ν := begin have h : ae_measurable f (μ + ν) := hμ.ae_measurable.add_measure hν.ae_measurable, let g := h.mk f, have A : f =ᵐ[μ + ν] g := h.ae_eq_mk, have B : f =ᵐ[μ] g := A.filter_mono (ae_mono (measure.le_add_right (le_refl μ))), have C : f =ᵐ[ν] g := A.filter_mono (ae_mono (measure.le_add_left (le_refl ν))), calc ∫ x, f x ∂(μ + ν) = ∫ x, g x ∂(μ + ν) : integral_congr_ae A ... = ∫ x, g x ∂μ + ∫ x, g x ∂ν : integral_add_measure_of_measurable h.measurable_mk ((integrable_congr B).1 hμ) ((integrable_congr C).1 hν) ... = ∫ x, f x ∂μ + ∫ x, f x ∂ν : by { congr' 1, { exact integral_congr_ae B.symm }, { exact integral_congr_ae C.symm } } end @[simp] lemma integral_zero_measure (f : α → E) : ∫ x, f x ∂0 = 0 := norm_le_zero_iff.1 $ le_trans (norm_integral_le_lintegral_norm f) $ by simp private lemma integral_smul_measure_aux {f : α → E} {c : ℝ≥0∞} (h0 : 0 < c) (hc : c < ∞) (fmeas : measurable f) (hfi : integrable f μ) : ∫ x, f x ∂(c • μ) = c.to_real • ∫ x, f x ∂μ := begin refine tendsto_nhds_unique _ (tendsto_const_nhds.smul (tendsto_integral_approx_on_univ_of_measurable fmeas hfi)), convert tendsto_integral_approx_on_univ_of_measurable fmeas (hfi.smul_measure hc), simp only [simple_func.integral, measure.smul_apply, finset.smul_sum, smul_smul, ennreal.to_real_mul] end @[simp] lemma integral_smul_measure (f : α → E) (c : ℝ≥0∞) : ∫ x, f x ∂(c • μ) = c.to_real • ∫ x, f x ∂μ := begin -- First we consider “degenerate” cases: -- `c = 0` rcases (zero_le c).eq_or_lt with rfl|h0, { simp }, -- `f` is not almost everywhere measurable by_cases hfm : ae_measurable f μ, swap, { have : ¬ (ae_measurable f (c • μ)), by simpa [ne_of_gt h0] using hfm, simp [integral_non_ae_measurable, hfm, this] }, -- `c = ∞` rcases (le_top : c ≤ ∞).eq_or_lt with rfl|hc, { rw [ennreal.top_to_real, zero_smul], by_cases hf : f =ᵐ[μ] 0, { have : f =ᵐ[∞ • μ] 0 := ae_smul_measure hf ∞, exact integral_eq_zero_of_ae this }, { apply integral_undef, rw [integrable, has_finite_integral, iff_true_intro (hfm.smul_measure ∞), true_and, lintegral_smul_measure, top_mul, if_neg], { apply lt_irrefl }, { rw [lintegral_eq_zero_iff' hfm.ennnorm], refine λ h, hf (h.mono $ λ x, _), simp } } }, -- `f` is not integrable and `0 < c < ∞` by_cases hfi : integrable f μ, swap, { rw [integral_undef hfi, smul_zero], refine integral_undef (mt (λ h, _) hfi), convert h.smul_measure (ennreal.inv_lt_top.2 h0), rw [smul_smul, ennreal.inv_mul_cancel (ne_of_gt h0) (ne_of_lt hc), one_smul] }, -- Main case: `0 < c < ∞`, `f` is almost everywhere measurable and integrable let g := hfm.mk f, calc ∫ x, f x ∂(c • μ) = ∫ x, g x ∂(c • μ) : integral_congr_ae $ ae_smul_measure hfm.ae_eq_mk c ... = c.to_real • ∫ x, g x ∂μ : integral_smul_measure_aux h0 hc hfm.measurable_mk $ hfi.congr hfm.ae_eq_mk ... = c.to_real • ∫ x, f x ∂μ : by { congr' 1, exact integral_congr_ae (hfm.ae_eq_mk.symm) } end lemma integral_map_of_measurable {β} [measurable_space β] {φ : α → β} (hφ : measurable φ) {f : β → E} (hfm : measurable f) : ∫ y, f y ∂(measure.map φ μ) = ∫ x, f (φ x) ∂μ := begin by_cases hfi : integrable f (measure.map φ μ), swap, { rw [integral_undef hfi, integral_undef], rwa [← integrable_map_measure hfm.ae_measurable hφ] }, refine tendsto_nhds_unique (tendsto_integral_approx_on_univ_of_measurable hfm hfi) _, convert tendsto_integral_approx_on_univ_of_measurable (hfm.comp hφ) ((integrable_map_measure hfm.ae_measurable hφ).1 hfi), ext1 i, simp only [simple_func.approx_on_comp, simple_func.integral, measure.map_apply, hφ, simple_func.measurable_set_preimage, ← preimage_comp, simple_func.coe_comp], refine (finset.sum_subset (simple_func.range_comp_subset_range _ hφ) (λ y _ hy, _)).symm, rw [simple_func.mem_range, ← set.preimage_singleton_eq_empty, simple_func.coe_comp] at hy, simp [hy] end lemma integral_map {β} [measurable_space β] {φ : α → β} (hφ : measurable φ) {f : β → E} (hfm : ae_measurable f (measure.map φ μ)) : ∫ y, f y ∂(measure.map φ μ) = ∫ x, f (φ x) ∂μ := let g := hfm.mk f in calc ∫ y, f y ∂(measure.map φ μ) = ∫ y, g y ∂(measure.map φ μ) : integral_congr_ae hfm.ae_eq_mk ... = ∫ x, g (φ x) ∂μ : integral_map_of_measurable hφ hfm.measurable_mk ... = ∫ x, f (φ x) ∂μ : integral_congr_ae $ ae_eq_comp hφ (hfm.ae_eq_mk).symm lemma integral_map_of_closed_embedding {β} [topological_space α] [borel_space α] [topological_space β] [measurable_space β] [borel_space β] {φ : α → β} (hφ : closed_embedding φ) (f : β → E) : ∫ y, f y ∂(measure.map φ μ) = ∫ x, f (φ x) ∂μ := begin by_cases hfm : ae_measurable f (measure.map φ μ), { exact integral_map hφ.continuous.measurable hfm }, { rw [integral_non_ae_measurable hfm, integral_non_ae_measurable], rwa ae_measurable_comp_right_iff_of_closed_embedding hφ } end lemma integral_dirac' (f : α → E) (a : α) (hfm : measurable f) : ∫ x, f x ∂(measure.dirac a) = f a := calc ∫ x, f x ∂(measure.dirac a) = ∫ x, f a ∂(measure.dirac a) : integral_congr_ae $ ae_eq_dirac' hfm ... = f a : by simp [measure.dirac_apply_of_mem] lemma integral_dirac [measurable_singleton_class α] (f : α → E) (a : α) : ∫ x, f x ∂(measure.dirac a) = f a := calc ∫ x, f x ∂(measure.dirac a) = ∫ x, f a ∂(measure.dirac a) : integral_congr_ae $ ae_eq_dirac f ... = f a : by simp [measure.dirac_apply_of_mem] end properties section group variables {G : Type*} [measurable_space G] [topological_space G] [group G] [has_continuous_mul G] [borel_space G] variables {μ : measure G} open measure /-- Translating a function by left-multiplication does not change its integral with respect to a left-invariant measure. -/ @[to_additive] lemma integral_mul_left_eq_self (hμ : is_mul_left_invariant μ) {f : G → E} (g : G) : ∫ x, f (g * x) ∂μ = ∫ x, f x ∂μ := begin have hgμ : measure.map (has_mul.mul g) μ = μ, { rw ← map_mul_left_eq_self at hμ, exact hμ g }, have h_mul : closed_embedding (λ x, g * x) := (homeomorph.mul_left g).closed_embedding, rw [← integral_map_of_closed_embedding h_mul, hgμ] end /-- Translating a function by right-multiplication does not change its integral with respect to a right-invariant measure. -/ @[to_additive] lemma integral_mul_right_eq_self (hμ : is_mul_right_invariant μ) {f : G → E} (g : G) : ∫ x, f (x * g) ∂μ = ∫ x, f x ∂μ := begin have hgμ : measure.map (λ x, x * g) μ = μ, { rw ← map_mul_right_eq_self at hμ, exact hμ g }, have h_mul : closed_embedding (λ x, x * g) := (homeomorph.mul_right g).closed_embedding, rw [← integral_map_of_closed_embedding h_mul, hgμ] end /-- If some left-translate of a function negates it, then the integral of the function with respect to a left-invariant measure is 0. -/ @[to_additive] lemma integral_zero_of_mul_left_eq_neg (hμ : is_mul_left_invariant μ) {f : G → E} {g : G} (hf' : ∀ x, f (g * x) = - f x) : ∫ x, f x ∂μ = 0 := begin refine eq_zero_of_eq_neg ℝ (eq.symm _), have : ∫ x, f (g * x) ∂μ = ∫ x, - f x ∂μ, { congr, ext x, exact hf' x }, convert integral_mul_left_eq_self hμ g using 1, rw [this, integral_neg] end /-- If some right-translate of a function negates it, then the integral of the function with respect to a right-invariant measure is 0. -/ @[to_additive] lemma integral_zero_of_mul_right_eq_neg (hμ : is_mul_right_invariant μ) {f : G → E} {g : G} (hf' : ∀ x, f (x * g) = - f x) : ∫ x, f x ∂μ = 0 := begin refine eq_zero_of_eq_neg ℝ (eq.symm _), have : ∫ x, f (x * g) ∂μ = ∫ x, - f x ∂μ, { congr, ext x, exact hf' x }, convert integral_mul_right_eq_self hμ g using 1, rw [this, integral_neg] end end group mk_simp_attribute integral_simps "Simp set for integral rules." attribute [integral_simps] integral_neg integral_smul L1.integral_add L1.integral_sub L1.integral_smul L1.integral_neg attribute [irreducible] integral L1.integral section integral_trim variables {H β γ : Type*} [normed_group H] [measurable_space H] {m m0 : measurable_space β} {μ : measure β} /-- Simple function seen as simple function of a larger `measurable_space`. -/ def simple_func.to_larger_space (hm : m ≤ m0) (f : @simple_func β m γ) : simple_func β γ := ⟨@simple_func.to_fun β m γ f, λ x, hm _ (@simple_func.measurable_set_fiber β γ m f x), @simple_func.finite_range β γ m f⟩ lemma simple_func.coe_to_larger_space_eq (hm : m ≤ m0) (f : @simple_func β m γ) : ⇑(f.to_larger_space hm) = f := rfl lemma integral_simple_func_larger_space (hm : m ≤ m0) (f : @simple_func β m F) (hf_int : integrable f μ) : ∫ x, f x ∂μ = ∑ x in (@simple_func.range β F m f), (ennreal.to_real (μ (f ⁻¹' {x}))) • x := begin simp_rw ← f.coe_to_larger_space_eq hm, have hf_int : integrable (f.to_larger_space hm) μ, by rwa simple_func.coe_to_larger_space_eq, rw simple_func.integral_eq_sum _ hf_int, congr, end lemma integral_trim_simple_func (hm : m ≤ m0) (f : @simple_func β m F) (hf_int : integrable f μ) : ∫ x, f x ∂μ = @integral β F m _ _ _ _ _ _ (μ.trim hm) f := begin have hf : @measurable _ _ m _ f, from @simple_func.measurable β F m _ f, have hf_int_m := hf_int.trim hm hf, rw [integral_simple_func_larger_space le_rfl f hf_int_m, integral_simple_func_larger_space hm f hf_int], congr, ext1 x, congr, exact (trim_measurable_set_eq hm (@simple_func.measurable_set_fiber β F m f x)).symm, end lemma integral_trim (hm : m ≤ m0) {f : β → F} (hf : @measurable β F m _ f) : ∫ x, f x ∂μ = @integral β F m _ _ _ _ _ _ (μ.trim hm) f := begin by_cases hf_int : integrable f μ, swap, { have hf_int_m : ¬ @integrable β F m _ _ f (μ.trim hm), from λ hf_int_m, hf_int (integrable_of_integrable_trim hm hf_int_m), rw [integral_undef hf_int, @integral_undef _ _ m _ _ _ _ _ _ _ _ hf_int_m], }, let f_seq := @simple_func.approx_on F β _ _ _ m _ hf set.univ 0 (set.mem_univ 0) _, have hf_seq_meas : ∀ n, @measurable _ _ m _ (f_seq n), from λ n, @simple_func.measurable β F m _ (f_seq n), have hf_seq_int : ∀ n, integrable (f_seq n) μ, from simple_func.integrable_approx_on_univ (hf.mono hm le_rfl) hf_int, have hf_seq_int_m : ∀ n, @integrable β F m _ _ (f_seq n) (μ.trim hm), from λ n, (hf_seq_int n).trim hm (hf_seq_meas n) , have hf_seq_eq : ∀ n, ∫ x, f_seq n x ∂μ = @integral β F m _ _ _ _ _ _ (μ.trim hm) (f_seq n), from λ n, integral_trim_simple_func hm (f_seq n) (hf_seq_int n), have h_lim_1 : at_top.tendsto (λ n, ∫ x, f_seq n x ∂μ) (𝓝 (∫ x, f x ∂μ)), { refine tendsto_integral_of_L1 f hf_int (eventually_of_forall hf_seq_int) _, exact simple_func.tendsto_approx_on_univ_L1_edist (hf.mono hm le_rfl) hf_int, }, have h_lim_2 : at_top.tendsto (λ n, ∫ x, f_seq n x ∂μ) (𝓝 (@integral β F m _ _ _ _ _ _ (μ.trim hm) f)), { simp_rw hf_seq_eq, refine @tendsto_integral_of_L1 β F m _ _ _ _ _ _ (μ.trim hm) _ f (hf_int.trim hm hf) _ _ (eventually_of_forall hf_seq_int_m) _, exact @simple_func.tendsto_approx_on_univ_L1_edist β F m _ _ _ _ f _ hf (hf_int.trim hm hf), }, exact tendsto_nhds_unique h_lim_1 h_lim_2, end lemma integral_trim_ae (hm : m ≤ m0) {f : β → F} (hf : @ae_measurable β F m _ f (μ.trim hm)) : ∫ x, f x ∂μ = @integral β F m _ _ _ _ _ _ (μ.trim hm) f := begin let f' := @ae_measurable.mk _ _ m _ _ f hf, have hf'_eq_trim : f =ᶠ[@measure.ae _ m (μ.trim hm)] f', from @ae_measurable.ae_eq_mk _ _ m _ f _ hf, have hf'_eq : f =ᵐ[μ] f' := ae_eq_of_ae_eq_trim hf'_eq_trim, rw [integral_congr_ae hf'_eq, @integral_congr_ae _ _ m _ _ _ _ _ _ _ _ _ hf'_eq_trim], exact integral_trim hm (@ae_measurable.measurable_mk _ _ m _ f _ hf), end lemma ae_eq_trim_of_measurable [measurable_space γ] [add_group γ] [measurable_singleton_class γ] [has_measurable_sub₂ γ] (hm : m ≤ m0) {f g : β → γ} (hf : @measurable _ _ m _ f) (hg : @measurable _ _ m _ g) (hfg : f =ᵐ[μ] g) : f =ᶠ[@measure.ae β m (μ.trim hm)] g := begin rwa [eventually_eq, ae_iff, trim_measurable_set_eq hm _], exact (@measurable_set.compl β _ m (@measurable_set_eq_fun β m γ _ _ _ _ _ _ hf hg)), end lemma ae_eq_trim_iff [measurable_space γ] [add_group γ] [measurable_singleton_class γ] [has_measurable_sub₂ γ] (hm : m ≤ m0) {f g : β → γ} (hf : @measurable _ _ m _ f) (hg : @measurable _ _ m _ g) : f =ᶠ[@measure.ae β m (μ.trim hm)] g ↔ f =ᵐ[μ] g := ⟨ae_eq_of_ae_eq_trim, ae_eq_trim_of_measurable hm hf hg⟩ end integral_trim end measure_theory
1b2b30b352b04a53feb4edb3ac469e746b7bda00
4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d
/stage0/src/Lean/Elab/PreDefinition/Structural/Main.lean
b94d1149cfd1dd9ec96bf48dd681e2f35273828e
[ "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,205
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.Structural.Basic import Lean.Elab.PreDefinition.Structural.FindRecArg import Lean.Elab.PreDefinition.Structural.Preprocess import Lean.Elab.PreDefinition.Structural.BRecOn import Lean.Elab.PreDefinition.Structural.IndPred import Lean.Elab.PreDefinition.Structural.Eqns import Lean.Elab.PreDefinition.Structural.SmartUnfolding namespace Lean.Elab namespace Structural open Meta private def getFixedPrefix (declName : Name) (xs : Array Expr) (value : Expr) : MetaM Nat := do let numFixedRef ← IO.mkRef xs.size forEachExpr' value fun e => do if e.isAppOf declName then let args := e.getAppArgs numFixedRef.modify fun numFixed => if args.size < numFixed then args.size else numFixed for arg in args, x in xs do /- We should not use structural equality here. For example, given the definition ``` def V.map {α β} f x x_1 := @V.map.match_1.{1} α (fun x x_2 => V β x) x x_1 (fun x x_2 => @V.mk₁ β x (f Bool.true x_2)) (fun e => @V.mk₂ β (V.map (fun b => α b) (fun b => β b) f Bool.false e)) ``` The first three arguments at `V.map (fun b => α b) (fun b => β b) f Bool.false e` are "fixed" modulo definitional equality. We disable to proof irrelevance to be able to use structural recursion on inductive predicates. For example, consider the example ``` inductive PList (α : Type) : Prop | nil | cons : α → PList α → PList α infixr:67 " ::: " => PList.cons set_option trace.Elab.definition.structural true in def pmap {α β} (f : α → β) : PList α → PList β | PList.nil => PList.nil | a:::as => f a ::: pmap f as ``` The "Fixed" prefix would be 4 since all elements of type `PList α` are definitionally equal. -/ if !(← withoutProofIrrelevance <| withReducible <| isDefEq arg x) then -- We continue searching if e's arguments are not a prefix of `xs` return true return false else return true numFixedRef.get private def elimRecursion (preDef : PreDefinition) : M (Nat × PreDefinition) := withoutModifyingEnv do lambdaTelescope preDef.value fun xs value => do addAsAxiom preDef let value ← preprocess value preDef.declName trace[Elab.definition.structural] "{preDef.declName} {xs} :=\n{value}" let numFixed ← getFixedPrefix preDef.declName xs value trace[Elab.definition.structural] "numFixed: {numFixed}" findRecArg numFixed xs fun recArgInfo => do -- when (recArgInfo.indName == `Nat) throwStructuralFailed -- HACK to skip Nat argument let valueNew ← if recArgInfo.indPred then mkIndPredBRecOn preDef.declName recArgInfo value else mkBRecOn preDef.declName recArgInfo value let valueNew ← mkLambdaFVars xs valueNew trace[Elab.definition.structural] "result: {valueNew}" -- Recursive applications may still occur in expressions that were not visited by replaceRecApps (e.g., in types) let valueNew ← ensureNoRecFn preDef.declName valueNew let recArgPos := recArgInfo.fixedParams.size + recArgInfo.pos return (recArgPos, { preDef with value := valueNew }) def structuralRecursion (preDefs : Array PreDefinition) : TermElabM Unit := if preDefs.size != 1 then throwError "structural recursion does not handle mutually recursive functions" else do let ((recArgPos, preDefNonRec), state) ← run <| elimRecursion preDefs[0] state.addMatchers.forM liftM mapError (addNonRec preDefNonRec) (fun msg => m!"structural recursion failed, produced type incorrect term{indentD msg}") addAndCompilePartialRec preDefs addSmartUnfoldingDef preDefs[0] recArgPos registerEqnsInfo preDefs[0] recArgPos builtin_initialize registerTraceClass `Elab.definition.structural end Structural export Structural (structuralRecursion) end Lean.Elab
2fd25efb1038319d7f49613e76f4c0b33a9ddba7
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/analysis/normed_space/multilinear.lean
26564838a5f6dff6196501fa58e2918adc88f305
[ "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
73,355
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.normed_space.operator_norm import topology.algebra.multilinear /-! # Operator norm on the space of continuous multilinear maps When `f` is a continuous multilinear map in finitely many variables, we define its norm `∥f∥` as the smallest number such that `∥f m∥ ≤ ∥f∥ * ∏ i, ∥m i∥` for all `m`. We show that it is indeed a norm, and prove its basic properties. ## Main results Let `f` be a multilinear map in finitely many variables. * `exists_bound_of_continuous` asserts that, if `f` is continuous, then there exists `C > 0` with `∥f m∥ ≤ C * ∏ i, ∥m i∥` for all `m`. * `continuous_of_bound`, conversely, asserts that this bound implies continuity. * `mk_continuous` constructs the associated continuous multilinear map. Let `f` be a continuous multilinear map in finitely many variables. * `∥f∥` is its norm, i.e., the smallest number such that `∥f m∥ ≤ ∥f∥ * ∏ i, ∥m i∥` for all `m`. * `le_op_norm f m` asserts the fundamental inequality `∥f m∥ ≤ ∥f∥ * ∏ i, ∥m i∥`. * `norm_image_sub_le f m₁ m₂` gives a control of the difference `f m₁ - f m₂` in terms of `∥f∥` and `∥m₁ - m₂∥`. We also register isomorphisms corresponding to currying or uncurrying variables, transforming a continuous multilinear function `f` in `n+1` variables into a continuous linear function taking values in continuous multilinear functions in `n` variables, and also into a continuous multilinear function in `n` variables taking values in continuous linear functions. These operations are called `f.curry_left` and `f.curry_right` respectively (with inverses `f.uncurry_left` and `f.uncurry_right`). They induce continuous linear equivalences between spaces of continuous multilinear functions in `n+1` variables and spaces of continuous linear functions into continuous multilinear functions in `n` variables (resp. continuous multilinear functions in `n` variables taking values in continuous linear functions), called respectively `continuous_multilinear_curry_left_equiv` and `continuous_multilinear_curry_right_equiv`. ## Implementation notes We mostly follow the API (and the proofs) of `operator_norm.lean`, with the additional complexity that we should deal with multilinear maps in several variables. The currying/uncurrying constructions are based on those in `multilinear.lean`. From the mathematical point of view, all the results follow from the results on operator norm in one variable, by applying them to one variable after the other through currying. However, this is only well defined when there is an order on the variables (for instance on `fin n`) although the final result is independent of the order. While everything could be done following this approach, it turns out that direct proofs are easier and more efficient. -/ noncomputable theory open_locale classical big_operators nnreal open finset metric local attribute [instance, priority 1001] add_comm_group.to_add_comm_monoid normed_group.to_add_comm_group normed_space.to_module -- hack to speed up simp when dealing with complicated types local attribute [-instance] unique.subsingleton pi.subsingleton /-! ### Type variables We use the following type variables in this file: * `𝕜` : a `nondiscrete_normed_field`; * `ι`, `ι'` : finite index types with decidable equality; * `E`, `E₁` : families of normed vector spaces over `𝕜` indexed by `i : ι`; * `E'` : a family of normed vector spaces over `𝕜` indexed by `i' : ι'`; * `Ei` : a family of normed vector spaces over `𝕜` indexed by `i : fin (nat.succ n)`; * `G`, `G'` : normed vector spaces over `𝕜`. -/ universes u v v' wE wE₁ wE' wEi wG wG' variables {𝕜 : Type u} {ι : Type v} {ι' : Type v'} {n : ℕ} {E : ι → Type wE} {E₁ : ι → Type wE₁} {E' : ι' → Type wE'} {Ei : fin n.succ → Type wEi} {G : Type wG} {G' : Type wG'} [decidable_eq ι] [fintype ι] [decidable_eq ι'] [fintype ι'] [nondiscrete_normed_field 𝕜] [Π i, normed_group (E i)] [Π i, normed_space 𝕜 (E i)] [Π i, normed_group (E₁ i)] [Π i, normed_space 𝕜 (E₁ i)] [Π i, normed_group (E' i)] [Π i, normed_space 𝕜 (E' i)] [Π i, normed_group (Ei i)] [Π i, normed_space 𝕜 (Ei i)] [normed_group G] [normed_space 𝕜 G] [normed_group G'] [normed_space 𝕜 G'] /-! ### Continuity properties of multilinear maps We relate continuity of multilinear maps to the inequality `∥f m∥ ≤ C * ∏ i, ∥m i∥`, in both directions. Along the way, we prove useful bounds on the difference `∥f m₁ - f m₂∥`. -/ namespace multilinear_map variable (f : multilinear_map 𝕜 E G) /-- If a multilinear map in finitely many variables on normed spaces satisfies the inequality `∥f m∥ ≤ C * ∏ i, ∥m i∥` on a shell `ε i / ∥c i∥ < ∥m i∥ < ε i` for some positive numbers `ε i` and elements `c i : 𝕜`, `1 < ∥c i∥`, then it satisfies this inequality for all `m`. -/ lemma bound_of_shell {ε : ι → ℝ} {C : ℝ} (hε : ∀ i, 0 < ε i) {c : ι → 𝕜} (hc : ∀ i, 1 < ∥c i∥) (hf : ∀ m : Π i, E i, (∀ i, ε i / ∥c i∥ ≤ ∥m i∥) → (∀ i, ∥m i∥ < ε i) → ∥f m∥ ≤ C * ∏ i, ∥m i∥) (m : Π i, E i) : ∥f m∥ ≤ C * ∏ i, ∥m i∥ := begin rcases em (∃ i, m i = 0) with ⟨i, hi⟩|hm; [skip, push_neg at hm], { simp [f.map_coord_zero i hi, prod_eq_zero (mem_univ i), hi] }, choose δ hδ0 hδm_lt hle_δm hδinv using λ i, rescale_to_shell (hc i) (hε i) (hm i), have hδ0 : 0 < ∏ i, ∥δ i∥, from prod_pos (λ i _, norm_pos_iff.2 (hδ0 i)), simpa [map_smul_univ, norm_smul, prod_mul_distrib, mul_left_comm C, mul_le_mul_left hδ0] using hf (λ i, δ i • m i) hle_δm hδm_lt, end /-- If a multilinear map in finitely many variables on normed spaces is continuous, then it satisfies the inequality `∥f m∥ ≤ C * ∏ i, ∥m i∥`, for some `C` which can be chosen to be positive. -/ theorem exists_bound_of_continuous (hf : continuous f) : ∃ (C : ℝ), 0 < C ∧ (∀ m, ∥f m∥ ≤ C * ∏ i, ∥m i∥) := begin casesI is_empty_or_nonempty ι, { refine ⟨∥f 0∥ + 1, add_pos_of_nonneg_of_pos (norm_nonneg _) zero_lt_one, λ m, _⟩, obtain rfl : m = 0, from funext (is_empty.elim ‹_›), simp [univ_eq_empty, zero_le_one] }, obtain ⟨ε : ℝ, ε0 : 0 < ε, hε : ∀ m : Π i, E i, ∥m - 0∥ < ε → ∥f m - f 0∥ < 1⟩ := normed_group.tendsto_nhds_nhds.1 (hf.tendsto 0) 1 zero_lt_one, simp only [sub_zero, f.map_zero] at hε, rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩, have : 0 < (∥c∥ / ε) ^ fintype.card ι, from pow_pos (div_pos (zero_lt_one.trans hc) ε0) _, refine ⟨_, this, _⟩, refine f.bound_of_shell (λ _, ε0) (λ _, hc) (λ m hcm hm, _), refine (hε m ((pi_norm_lt_iff ε0).2 hm)).le.trans _, rw [← div_le_iff' this, one_div, ← inv_pow₀, inv_div, fintype.card, ← prod_const], exact prod_le_prod (λ _ _, div_nonneg ε0.le (norm_nonneg _)) (λ i _, hcm i) end /-- If `f` satisfies a boundedness property around `0`, one can deduce a bound on `f m₁ - f m₂` using the multilinearity. Here, we give a precise but hard to use version. See `norm_image_sub_le_of_bound` for a less precise but more usable version. The bound reads `∥f m - f m'∥ ≤ C * ∥m 1 - m' 1∥ * max ∥m 2∥ ∥m' 2∥ * max ∥m 3∥ ∥m' 3∥ * ... * max ∥m n∥ ∥m' n∥ + ...`, where the other terms in the sum are the same products where `1` is replaced by any `i`. -/ lemma norm_image_sub_le_of_bound' {C : ℝ} (hC : 0 ≤ C) (H : ∀ m, ∥f m∥ ≤ C * ∏ i, ∥m i∥) (m₁ m₂ : Πi, E i) : ∥f m₁ - f m₂∥ ≤ C * ∑ i, ∏ j, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥ := begin have A : ∀(s : finset ι), ∥f m₁ - f (s.piecewise m₂ m₁)∥ ≤ C * ∑ i in s, ∏ j, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥, { refine finset.induction (by simp) _, assume i s his Hrec, have I : ∥f (s.piecewise m₂ m₁) - f ((insert i s).piecewise m₂ m₁)∥ ≤ C * ∏ j, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥, { have A : ((insert i s).piecewise m₂ m₁) = function.update (s.piecewise m₂ m₁) i (m₂ i) := s.piecewise_insert _ _ _, have B : s.piecewise m₂ m₁ = function.update (s.piecewise m₂ m₁) i (m₁ i), { ext j, by_cases h : j = i, { rw h, simp [his] }, { simp [h] } }, rw [B, A, ← f.map_sub], apply le_trans (H _) (mul_le_mul_of_nonneg_left _ hC), refine prod_le_prod (λj hj, norm_nonneg _) (λj hj, _), by_cases h : j = i, { rw h, simp }, { by_cases h' : j ∈ s; simp [h', h, le_refl] } }, calc ∥f m₁ - f ((insert i s).piecewise m₂ m₁)∥ ≤ ∥f m₁ - f (s.piecewise m₂ m₁)∥ + ∥f (s.piecewise m₂ m₁) - f ((insert i s).piecewise m₂ m₁)∥ : by { rw [← dist_eq_norm, ← dist_eq_norm, ← dist_eq_norm], exact dist_triangle _ _ _ } ... ≤ (C * ∑ i in s, ∏ j, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥) + C * ∏ j, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥ : add_le_add Hrec I ... = C * ∑ i in insert i s, ∏ j, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥ : by simp [his, add_comm, left_distrib] }, convert A univ, simp end /-- If `f` satisfies a boundedness property around `0`, one can deduce a bound on `f m₁ - f m₂` using the multilinearity. Here, we give a usable but not very precise version. See `norm_image_sub_le_of_bound'` for a more precise but less usable version. The bound is `∥f m - f m'∥ ≤ C * card ι * ∥m - m'∥ * (max ∥m∥ ∥m'∥) ^ (card ι - 1)`. -/ lemma norm_image_sub_le_of_bound {C : ℝ} (hC : 0 ≤ C) (H : ∀ m, ∥f m∥ ≤ C * ∏ i, ∥m i∥) (m₁ m₂ : Πi, E i) : ∥f m₁ - f m₂∥ ≤ C * (fintype.card ι) * (max ∥m₁∥ ∥m₂∥) ^ (fintype.card ι - 1) * ∥m₁ - m₂∥ := begin have A : ∀ (i : ι), ∏ j, (if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥) ≤ ∥m₁ - m₂∥ * (max ∥m₁∥ ∥m₂∥) ^ (fintype.card ι - 1), { assume i, calc ∏ j, (if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥) ≤ ∏ j : ι, function.update (λ j, max ∥m₁∥ ∥m₂∥) i (∥m₁ - m₂∥) j : begin apply prod_le_prod, { assume j hj, by_cases h : j = i; simp [h, norm_nonneg] }, { assume j hj, by_cases h : j = i, { rw h, simp, exact norm_le_pi_norm (m₁ - m₂) i }, { simp [h, max_le_max, norm_le_pi_norm] } } end ... = ∥m₁ - m₂∥ * (max ∥m₁∥ ∥m₂∥) ^ (fintype.card ι - 1) : by { rw prod_update_of_mem (finset.mem_univ _), simp [card_univ_diff] } }, calc ∥f m₁ - f m₂∥ ≤ C * ∑ i, ∏ j, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥ : f.norm_image_sub_le_of_bound' hC H m₁ m₂ ... ≤ C * ∑ i, ∥m₁ - m₂∥ * (max ∥m₁∥ ∥m₂∥) ^ (fintype.card ι - 1) : mul_le_mul_of_nonneg_left (sum_le_sum (λi hi, A i)) hC ... = C * (fintype.card ι) * (max ∥m₁∥ ∥m₂∥) ^ (fintype.card ι - 1) * ∥m₁ - m₂∥ : by { rw [sum_const, card_univ, nsmul_eq_mul], ring } end /-- If a multilinear map satisfies an inequality `∥f m∥ ≤ C * ∏ i, ∥m i∥`, then it is continuous. -/ theorem continuous_of_bound (C : ℝ) (H : ∀ m, ∥f m∥ ≤ C * ∏ i, ∥m i∥) : continuous f := begin let D := max C 1, have D_pos : 0 ≤ D := le_trans zero_le_one (le_max_right _ _), replace H : ∀ m, ∥f m∥ ≤ D * ∏ i, ∥m i∥, { assume m, apply le_trans (H m) (mul_le_mul_of_nonneg_right (le_max_left _ _) _), exact prod_nonneg (λ(i : ι) hi, norm_nonneg (m i)) }, refine continuous_iff_continuous_at.2 (λm, _), refine continuous_at_of_locally_lipschitz zero_lt_one (D * (fintype.card ι) * (∥m∥ + 1) ^ (fintype.card ι - 1)) (λm' h', _), rw [dist_eq_norm, dist_eq_norm], have : 0 ≤ (max ∥m'∥ ∥m∥), by simp, have : (max ∥m'∥ ∥m∥) ≤ ∥m∥ + 1, by simp [zero_le_one, norm_le_of_mem_closed_ball (le_of_lt h'), -add_comm], calc ∥f m' - f m∥ ≤ D * (fintype.card ι) * (max ∥m'∥ ∥m∥) ^ (fintype.card ι - 1) * ∥m' - m∥ : f.norm_image_sub_le_of_bound D_pos H m' m ... ≤ D * (fintype.card ι) * (∥m∥ + 1) ^ (fintype.card ι - 1) * ∥m' - m∥ : by apply_rules [mul_le_mul_of_nonneg_right, mul_le_mul_of_nonneg_left, mul_nonneg, norm_nonneg, nat.cast_nonneg, pow_le_pow_of_le_left] end /-- Constructing a continuous multilinear map from a multilinear map satisfying a boundedness condition. -/ def mk_continuous (C : ℝ) (H : ∀ m, ∥f m∥ ≤ C * ∏ i, ∥m i∥) : continuous_multilinear_map 𝕜 E G := { cont := f.continuous_of_bound C H, ..f } @[simp] lemma coe_mk_continuous (C : ℝ) (H : ∀ m, ∥f m∥ ≤ C * ∏ i, ∥m i∥) : ⇑(f.mk_continuous C H) = f := rfl /-- Given a multilinear map in `n` variables, if one restricts it to `k` variables putting `z` on the other coordinates, then the resulting restricted function satisfies an inequality `∥f.restr v∥ ≤ C * ∥z∥^(n-k) * Π ∥v i∥` if the original function satisfies `∥f v∥ ≤ C * Π ∥v i∥`. -/ lemma restr_norm_le {k n : ℕ} (f : (multilinear_map 𝕜 (λ i : fin n, G) G' : _)) (s : finset (fin n)) (hk : s.card = k) (z : G) {C : ℝ} (H : ∀ m, ∥f m∥ ≤ C * ∏ i, ∥m i∥) (v : fin k → G) : ∥f.restr s hk z v∥ ≤ C * ∥z∥ ^ (n - k) * ∏ i, ∥v i∥ := begin rw [mul_right_comm, mul_assoc], convert H _ using 2, simp only [apply_dite norm, fintype.prod_dite, prod_const (∥z∥), finset.card_univ, fintype.card_of_subtype sᶜ (λ x, mem_compl), card_compl, fintype.card_fin, hk, mk_coe, ← (s.order_iso_of_fin hk).symm.bijective.prod_comp (λ x, ∥v x∥)], refl end end multilinear_map /-! ### Continuous multilinear maps We define the norm `∥f∥` of a continuous multilinear map `f` in finitely many variables as the smallest number such that `∥f m∥ ≤ ∥f∥ * ∏ i, ∥m i∥` for all `m`. We show that this defines a normed space structure on `continuous_multilinear_map 𝕜 E G`. -/ namespace continuous_multilinear_map variables (c : 𝕜) (f g : continuous_multilinear_map 𝕜 E G) (m : Πi, E i) theorem bound : ∃ (C : ℝ), 0 < C ∧ (∀ m, ∥f m∥ ≤ C * ∏ i, ∥m i∥) := f.to_multilinear_map.exists_bound_of_continuous f.2 open real /-- The operator norm of a continuous multilinear map is the inf of all its bounds. -/ def op_norm := Inf {c | 0 ≤ (c : ℝ) ∧ ∀ m, ∥f m∥ ≤ c * ∏ i, ∥m i∥} instance has_op_norm : has_norm (continuous_multilinear_map 𝕜 E G) := ⟨op_norm⟩ lemma norm_def : ∥f∥ = Inf {c | 0 ≤ (c : ℝ) ∧ ∀ m, ∥f m∥ ≤ c * ∏ i, ∥m i∥} := rfl -- So that invocations of `le_cInf` make sense: we show that the set of -- bounds is nonempty and bounded below. lemma bounds_nonempty {f : continuous_multilinear_map 𝕜 E G} : ∃ c, c ∈ {c | 0 ≤ c ∧ ∀ m, ∥f m∥ ≤ c * ∏ i, ∥m i∥} := let ⟨M, hMp, hMb⟩ := f.bound in ⟨M, le_of_lt hMp, hMb⟩ lemma bounds_bdd_below {f : continuous_multilinear_map 𝕜 E G} : bdd_below {c | 0 ≤ c ∧ ∀ m, ∥f m∥ ≤ c * ∏ i, ∥m i∥} := ⟨0, λ _ ⟨hn, _⟩, hn⟩ lemma op_norm_nonneg : 0 ≤ ∥f∥ := le_cInf bounds_nonempty (λ _ ⟨hx, _⟩, hx) /-- The fundamental property of the operator norm of a continuous multilinear map: `∥f m∥` is bounded by `∥f∥` times the product of the `∥m i∥`. -/ theorem le_op_norm : ∥f m∥ ≤ ∥f∥ * ∏ i, ∥m i∥ := begin have A : 0 ≤ ∏ i, ∥m i∥ := prod_nonneg (λj hj, norm_nonneg _), cases A.eq_or_lt with h hlt, { rcases prod_eq_zero_iff.1 h.symm with ⟨i, _, hi⟩, rw norm_eq_zero at hi, have : f m = 0 := f.map_coord_zero i hi, rw [this, norm_zero], exact mul_nonneg (op_norm_nonneg f) A }, { rw [← div_le_iff hlt], apply le_cInf bounds_nonempty, rintro c ⟨_, hc⟩, rw [div_le_iff hlt], apply hc } end theorem le_of_op_norm_le {C : ℝ} (h : ∥f∥ ≤ C) : ∥f m∥ ≤ C * ∏ i, ∥m i∥ := (f.le_op_norm m).trans $ mul_le_mul_of_nonneg_right h (prod_nonneg $ λ i _, norm_nonneg (m i)) lemma ratio_le_op_norm : ∥f m∥ / ∏ i, ∥m i∥ ≤ ∥f∥ := div_le_of_nonneg_of_le_mul (prod_nonneg $ λ i _, norm_nonneg _) (op_norm_nonneg _) (f.le_op_norm m) /-- The image of the unit ball under a continuous multilinear map is bounded. -/ lemma unit_le_op_norm (h : ∥m∥ ≤ 1) : ∥f m∥ ≤ ∥f∥ := calc ∥f m∥ ≤ ∥f∥ * ∏ i, ∥m i∥ : f.le_op_norm m ... ≤ ∥f∥ * ∏ i : ι, 1 : mul_le_mul_of_nonneg_left (prod_le_prod (λi hi, norm_nonneg _) (λi hi, le_trans (norm_le_pi_norm _ _) h)) (op_norm_nonneg f) ... = ∥f∥ : by simp /-- If one controls the norm of every `f x`, then one controls the norm of `f`. -/ lemma op_norm_le_bound {M : ℝ} (hMp: 0 ≤ M) (hM : ∀ m, ∥f m∥ ≤ M * ∏ i, ∥m i∥) : ∥f∥ ≤ M := cInf_le bounds_bdd_below ⟨hMp, hM⟩ /-- The operator norm satisfies the triangle inequality. -/ theorem op_norm_add_le : ∥f + g∥ ≤ ∥f∥ + ∥g∥ := cInf_le bounds_bdd_below ⟨add_nonneg (op_norm_nonneg _) (op_norm_nonneg _), λ x, by { rw add_mul, exact norm_add_le_of_le (le_op_norm _ _) (le_op_norm _ _) }⟩ /-- A continuous linear map is zero iff its norm vanishes. -/ theorem op_norm_zero_iff : ∥f∥ = 0 ↔ f = 0 := begin split, { assume h, ext m, simpa [h] using f.le_op_norm m }, { rintro rfl, apply le_antisymm (op_norm_le_bound 0 le_rfl (λm, _)) (op_norm_nonneg _), simp } end variables {𝕜' : Type*} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜' 𝕜] [normed_space 𝕜' G] [is_scalar_tower 𝕜' 𝕜 G] lemma op_norm_smul_le (c : 𝕜') : ∥c • f∥ ≤ ∥c∥ * ∥f∥ := (c • f).op_norm_le_bound (mul_nonneg (norm_nonneg _) (op_norm_nonneg _)) begin intro m, erw [norm_smul, mul_assoc], exact mul_le_mul_of_nonneg_left (le_op_norm _ _) (norm_nonneg _) end lemma op_norm_neg : ∥-f∥ = ∥f∥ := by { rw norm_def, apply congr_arg, ext, simp } /-- Continuous multilinear maps themselves form a normed space with respect to the operator norm. -/ instance to_normed_group : normed_group (continuous_multilinear_map 𝕜 E G) := normed_group.of_core _ ⟨op_norm_zero_iff, op_norm_add_le, op_norm_neg⟩ instance to_normed_space : normed_space 𝕜' (continuous_multilinear_map 𝕜 E G) := ⟨λ c f, f.op_norm_smul_le c⟩ theorem le_op_norm_mul_prod_of_le {b : ι → ℝ} (hm : ∀ i, ∥m i∥ ≤ b i) : ∥f m∥ ≤ ∥f∥ * ∏ i, b i := (f.le_op_norm m).trans $ mul_le_mul_of_nonneg_left (prod_le_prod (λ _ _, norm_nonneg _) (λ i _, hm i)) (norm_nonneg f) theorem le_op_norm_mul_pow_card_of_le {b : ℝ} (hm : ∀ i, ∥m i∥ ≤ b) : ∥f m∥ ≤ ∥f∥ * b ^ fintype.card ι := by simpa only [prod_const] using f.le_op_norm_mul_prod_of_le m hm theorem le_op_norm_mul_pow_of_le {Ei : fin n → Type*} [Π i, normed_group (Ei i)] [Π i, normed_space 𝕜 (Ei i)] (f : continuous_multilinear_map 𝕜 Ei G) (m : Π i, Ei i) {b : ℝ} (hm : ∥m∥ ≤ b) : ∥f m∥ ≤ ∥f∥ * b ^ n := by simpa only [fintype.card_fin] using f.le_op_norm_mul_pow_card_of_le m (λ i, (norm_le_pi_norm m i).trans hm) /-- The fundamental property of the operator norm of a continuous multilinear map: `∥f m∥` is bounded by `∥f∥` times the product of the `∥m i∥`, `nnnorm` version. -/ theorem le_op_nnnorm : nnnorm (f m) ≤ nnnorm f * ∏ i, nnnorm (m i) := nnreal.coe_le_coe.1 $ by { push_cast, exact f.le_op_norm m } theorem le_of_op_nnnorm_le {C : ℝ≥0} (h : nnnorm f ≤ C) : nnnorm (f m) ≤ C * ∏ i, nnnorm (m i) := (f.le_op_nnnorm m).trans $ mul_le_mul' h le_rfl lemma op_norm_prod (f : continuous_multilinear_map 𝕜 E G) (g : continuous_multilinear_map 𝕜 E G') : ∥f.prod g∥ = max (∥f∥) (∥g∥) := le_antisymm (op_norm_le_bound _ (norm_nonneg (f, g)) (λ m, have H : 0 ≤ ∏ i, ∥m i∥, from prod_nonneg $ λ _ _, norm_nonneg _, by simpa only [prod_apply, prod.norm_def, max_mul_of_nonneg, H] using max_le_max (f.le_op_norm m) (g.le_op_norm m))) $ max_le (f.op_norm_le_bound (norm_nonneg _) $ λ m, (le_max_left _ _).trans ((f.prod g).le_op_norm _)) (g.op_norm_le_bound (norm_nonneg _) $ λ m, (le_max_right _ _).trans ((f.prod g).le_op_norm _)) lemma norm_pi {ι' : Type v'} [fintype ι'] {E' : ι' → Type wE'} [Π i', normed_group (E' i')] [Π i', normed_space 𝕜 (E' i')] (f : Π i', continuous_multilinear_map 𝕜 E (E' i')) : ∥pi f∥ = ∥f∥ := begin apply le_antisymm, { refine (op_norm_le_bound _ (norm_nonneg f) (λ m, _)), dsimp, rw pi_norm_le_iff, exacts [λ i, (f i).le_of_op_norm_le m (norm_le_pi_norm f i), mul_nonneg (norm_nonneg f) (prod_nonneg $ λ _ _, norm_nonneg _)] }, { refine (pi_norm_le_iff (norm_nonneg _)).2 (λ i, _), refine (op_norm_le_bound _ (norm_nonneg _) (λ m, _)), refine le_trans _ ((pi f).le_op_norm m), convert norm_le_pi_norm (λ j, f j m) i } end section variables (𝕜 E E' G G') /-- `continuous_multilinear_map.prod` as a `linear_isometry_equiv`. -/ def prodL : (continuous_multilinear_map 𝕜 E G) × (continuous_multilinear_map 𝕜 E G') ≃ₗᵢ[𝕜] continuous_multilinear_map 𝕜 E (G × G') := { to_fun := λ f, f.1.prod f.2, inv_fun := λ f, ((continuous_linear_map.fst 𝕜 G G').comp_continuous_multilinear_map f, (continuous_linear_map.snd 𝕜 G G').comp_continuous_multilinear_map f), map_add' := λ f g, rfl, map_smul' := λ c f, rfl, left_inv := λ f, by ext; refl, right_inv := λ f, by ext; refl, norm_map' := λ f, op_norm_prod f.1 f.2 } /-- `continuous_multilinear_map.pi` as a `linear_isometry_equiv`. -/ def piₗᵢ {ι' : Type v'} [fintype ι'] {E' : ι' → Type wE'} [Π i', normed_group (E' i')] [Π i', normed_space 𝕜 (E' i')] : @linear_isometry_equiv 𝕜 𝕜 _ _ (ring_hom.id 𝕜) _ _ _ (Π i', continuous_multilinear_map 𝕜 E (E' i')) (continuous_multilinear_map 𝕜 E (Π i, E' i)) _ _ (@pi.module ι' _ 𝕜 _ _ (λ i', infer_instance)) _ := { to_linear_equiv := -- note: `pi_linear_equiv` does not unify correctly here, presumably due to issues with dependent -- typeclass arguments. { map_add' := λ f g, rfl, map_smul' := λ c f, rfl, .. pi_equiv, }, norm_map' := norm_pi } end section restrict_scalars variables [Π i, normed_space 𝕜' (E i)] [∀ i, is_scalar_tower 𝕜' 𝕜 (E i)] @[simp] lemma norm_restrict_scalars : ∥f.restrict_scalars 𝕜'∥ = ∥f∥ := by simp only [norm_def, coe_restrict_scalars] variable (𝕜') /-- `continuous_multilinear_map.restrict_scalars` as a `continuous_multilinear_map`. -/ def restrict_scalars_linear : continuous_multilinear_map 𝕜 E G →L[𝕜'] continuous_multilinear_map 𝕜' E G := linear_map.mk_continuous { to_fun := restrict_scalars 𝕜', map_add' := λ m₁ m₂, rfl, map_smul' := λ c m, rfl } 1 $ λ f, by simp variable {𝕜'} lemma continuous_restrict_scalars : continuous (restrict_scalars 𝕜' : continuous_multilinear_map 𝕜 E G → continuous_multilinear_map 𝕜' E G) := (restrict_scalars_linear 𝕜').continuous end restrict_scalars /-- The difference `f m₁ - f m₂` is controlled in terms of `∥f∥` and `∥m₁ - m₂∥`, precise version. For a less precise but more usable version, see `norm_image_sub_le`. The bound reads `∥f m - f m'∥ ≤ ∥f∥ * ∥m 1 - m' 1∥ * max ∥m 2∥ ∥m' 2∥ * max ∥m 3∥ ∥m' 3∥ * ... * max ∥m n∥ ∥m' n∥ + ...`, where the other terms in the sum are the same products where `1` is replaced by any `i`.-/ lemma norm_image_sub_le' (m₁ m₂ : Πi, E i) : ∥f m₁ - f m₂∥ ≤ ∥f∥ * ∑ i, ∏ j, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥ := f.to_multilinear_map.norm_image_sub_le_of_bound' (norm_nonneg _) f.le_op_norm _ _ /-- The difference `f m₁ - f m₂` is controlled in terms of `∥f∥` and `∥m₁ - m₂∥`, less precise version. For a more precise but less usable version, see `norm_image_sub_le'`. The bound is `∥f m - f m'∥ ≤ ∥f∥ * card ι * ∥m - m'∥ * (max ∥m∥ ∥m'∥) ^ (card ι - 1)`.-/ lemma norm_image_sub_le (m₁ m₂ : Πi, E i) : ∥f m₁ - f m₂∥ ≤ ∥f∥ * (fintype.card ι) * (max ∥m₁∥ ∥m₂∥) ^ (fintype.card ι - 1) * ∥m₁ - m₂∥ := f.to_multilinear_map.norm_image_sub_le_of_bound (norm_nonneg _) f.le_op_norm _ _ /-- Applying a multilinear map to a vector is continuous in both coordinates. -/ lemma continuous_eval : continuous (λ p : continuous_multilinear_map 𝕜 E G × Π i, E i, p.1 p.2) := begin apply continuous_iff_continuous_at.2 (λp, _), apply continuous_at_of_locally_lipschitz zero_lt_one ((∥p∥ + 1) * (fintype.card ι) * (∥p∥ + 1) ^ (fintype.card ι - 1) + ∏ i, ∥p.2 i∥) (λq hq, _), have : 0 ≤ (max ∥q.2∥ ∥p.2∥), by simp, have : 0 ≤ ∥p∥ + 1, by simp [le_trans zero_le_one], have A : ∥q∥ ≤ ∥p∥ + 1 := norm_le_of_mem_closed_ball (le_of_lt hq), have : (max ∥q.2∥ ∥p.2∥) ≤ ∥p∥ + 1 := le_trans (max_le_max (norm_snd_le q) (norm_snd_le p)) (by simp [A, -add_comm, zero_le_one]), have : ∀ (i : ι), i ∈ univ → 0 ≤ ∥p.2 i∥ := λ i hi, norm_nonneg _, calc dist (q.1 q.2) (p.1 p.2) ≤ dist (q.1 q.2) (q.1 p.2) + dist (q.1 p.2) (p.1 p.2) : dist_triangle _ _ _ ... = ∥q.1 q.2 - q.1 p.2∥ + ∥q.1 p.2 - p.1 p.2∥ : by rw [dist_eq_norm, dist_eq_norm] ... ≤ ∥q.1∥ * (fintype.card ι) * (max ∥q.2∥ ∥p.2∥) ^ (fintype.card ι - 1) * ∥q.2 - p.2∥ + ∥q.1 - p.1∥ * ∏ i, ∥p.2 i∥ : add_le_add (norm_image_sub_le _ _ _) ((q.1 - p.1).le_op_norm p.2) ... ≤ (∥p∥ + 1) * (fintype.card ι) * (∥p∥ + 1) ^ (fintype.card ι - 1) * ∥q - p∥ + ∥q - p∥ * ∏ i, ∥p.2 i∥ : by apply_rules [add_le_add, mul_le_mul, le_refl, le_trans (norm_fst_le q) A, nat.cast_nonneg, mul_nonneg, pow_le_pow_of_le_left, pow_nonneg, norm_snd_le (q - p), norm_nonneg, norm_fst_le (q - p), prod_nonneg] ... = ((∥p∥ + 1) * (fintype.card ι) * (∥p∥ + 1) ^ (fintype.card ι - 1) + (∏ i, ∥p.2 i∥)) * dist q p : by { rw dist_eq_norm, ring } end lemma continuous_eval_left (m : Π i, E i) : continuous (λ p : continuous_multilinear_map 𝕜 E G, p m) := continuous_eval.comp (continuous_id.prod_mk continuous_const) lemma has_sum_eval {α : Type*} {p : α → continuous_multilinear_map 𝕜 E G} {q : continuous_multilinear_map 𝕜 E G} (h : has_sum p q) (m : Π i, E i) : has_sum (λ a, p a m) (q m) := begin dsimp [has_sum] at h ⊢, convert ((continuous_eval_left m).tendsto _).comp h, ext s, simp end lemma tsum_eval {α : Type*} {p : α → continuous_multilinear_map 𝕜 E G} (hp : summable p) (m : Π i, E i) : (∑' a, p a) m = ∑' a, p a m := (has_sum_eval hp.has_sum m).tsum_eq.symm open_locale topological_space open filter /-- If the target space is complete, the space of continuous multilinear maps with its norm is also complete. The proof is essentially the same as for the space of continuous linear maps (modulo the addition of `finset.prod` where needed. The duplication could be avoided by deducing the linear case from the multilinear case via a currying isomorphism. However, this would mess up imports, and it is more satisfactory to have the simplest case as a standalone proof. -/ instance [complete_space G] : complete_space (continuous_multilinear_map 𝕜 E G) := begin have nonneg : ∀ (v : Π i, E i), 0 ≤ ∏ i, ∥v i∥ := λ v, finset.prod_nonneg (λ i hi, norm_nonneg _), -- We show that every Cauchy sequence converges. refine metric.complete_of_cauchy_seq_tendsto (λ f hf, _), -- We now expand out the definition of a Cauchy sequence, rcases cauchy_seq_iff_le_tendsto_0.1 hf with ⟨b, b0, b_bound, b_lim⟩, -- and establish that the evaluation at any point `v : Π i, E i` is Cauchy. have cau : ∀ v, cauchy_seq (λ n, f n v), { assume v, apply cauchy_seq_iff_le_tendsto_0.2 ⟨λ n, b n * ∏ i, ∥v i∥, λ n, _, _, _⟩, { exact mul_nonneg (b0 n) (nonneg v) }, { assume n m N hn hm, rw dist_eq_norm, apply le_trans ((f n - f m).le_op_norm v) _, exact mul_le_mul_of_nonneg_right (b_bound n m N hn hm) (nonneg v) }, { simpa using b_lim.mul tendsto_const_nhds } }, -- We assemble the limits points of those Cauchy sequences -- (which exist as `G` is complete) -- into a function which we call `F`. choose F hF using λv, cauchy_seq_tendsto_of_complete (cau v), -- Next, we show that this `F` is multilinear, let Fmult : multilinear_map 𝕜 E G := { to_fun := F, map_add' := λ v i x y, begin have A := hF (function.update v i (x + y)), have B := (hF (function.update v i x)).add (hF (function.update v i y)), simp at A B, exact tendsto_nhds_unique A B end, map_smul' := λ v i c x, begin have A := hF (function.update v i (c • x)), have B := filter.tendsto.smul (@tendsto_const_nhds _ ℕ _ c _) (hF (function.update v i x)), simp at A B, exact tendsto_nhds_unique A B end }, -- and that `F` has norm at most `(b 0 + ∥f 0∥)`. have Fnorm : ∀ v, ∥F v∥ ≤ (b 0 + ∥f 0∥) * ∏ i, ∥v i∥, { assume v, have A : ∀ n, ∥f n v∥ ≤ (b 0 + ∥f 0∥) * ∏ i, ∥v i∥, { assume n, apply le_trans ((f n).le_op_norm _) _, apply mul_le_mul_of_nonneg_right _ (nonneg v), calc ∥f n∥ = ∥(f n - f 0) + f 0∥ : by { congr' 1, abel } ... ≤ ∥f n - f 0∥ + ∥f 0∥ : norm_add_le _ _ ... ≤ b 0 + ∥f 0∥ : begin apply add_le_add_right, simpa [dist_eq_norm] using b_bound n 0 0 (zero_le _) (zero_le _) end }, exact le_of_tendsto (hF v).norm (eventually_of_forall A) }, -- Thus `F` is continuous, and we propose that as the limit point of our original Cauchy sequence. let Fcont := Fmult.mk_continuous _ Fnorm, use Fcont, -- Our last task is to establish convergence to `F` in norm. have : ∀ n, ∥f n - Fcont∥ ≤ b n, { assume n, apply op_norm_le_bound _ (b0 n) (λ v, _), have A : ∀ᶠ m in at_top, ∥(f n - f m) v∥ ≤ b n * ∏ i, ∥v i∥, { refine eventually_at_top.2 ⟨n, λ m hm, _⟩, apply le_trans ((f n - f m).le_op_norm _) _, exact mul_le_mul_of_nonneg_right (b_bound n m n (le_refl _) hm) (nonneg v) }, have B : tendsto (λ m, ∥(f n - f m) v∥) at_top (𝓝 (∥(f n - Fcont) v∥)) := tendsto.norm (tendsto_const_nhds.sub (hF v)), exact le_of_tendsto B A }, erw tendsto_iff_norm_tendsto_zero, exact squeeze_zero (λ n, norm_nonneg _) this b_lim, end end continuous_multilinear_map /-- If a continuous multilinear map is constructed from a multilinear map via the constructor `mk_continuous`, then its norm is bounded by the bound given to the constructor if it is nonnegative. -/ lemma multilinear_map.mk_continuous_norm_le (f : multilinear_map 𝕜 E G) {C : ℝ} (hC : 0 ≤ C) (H : ∀ m, ∥f m∥ ≤ C * ∏ i, ∥m i∥) : ∥f.mk_continuous C H∥ ≤ C := continuous_multilinear_map.op_norm_le_bound _ hC (λm, H m) /-- If a continuous multilinear map is constructed from a multilinear map via the constructor `mk_continuous`, then its norm is bounded by the bound given to the constructor if it is nonnegative. -/ lemma multilinear_map.mk_continuous_norm_le' (f : multilinear_map 𝕜 E G) {C : ℝ} (H : ∀ m, ∥f m∥ ≤ C * ∏ i, ∥m i∥) : ∥f.mk_continuous C H∥ ≤ max C 0 := continuous_multilinear_map.op_norm_le_bound _ (le_max_right _ _) $ λ m, (H m).trans $ mul_le_mul_of_nonneg_right (le_max_left _ _) (prod_nonneg $ λ _ _, norm_nonneg _) namespace continuous_multilinear_map /-- Given a continuous multilinear map `f` on `n` variables (parameterized by `fin n`) and a subset `s` of `k` of these variables, one gets a new continuous multilinear map on `fin k` by varying these variables, and fixing the other ones equal to a given value `z`. It is denoted by `f.restr s hk z`, where `hk` is a proof that the cardinality of `s` is `k`. The implicit identification between `fin k` and `s` that we use is the canonical (increasing) bijection. -/ def restr {k n : ℕ} (f : (G [×n]→L[𝕜] G' : _)) (s : finset (fin n)) (hk : s.card = k) (z : G) : G [×k]→L[𝕜] G' := (f.to_multilinear_map.restr s hk z).mk_continuous (∥f∥ * ∥z∥^(n-k)) $ λ v, multilinear_map.restr_norm_le _ _ _ _ f.le_op_norm _ lemma norm_restr {k n : ℕ} (f : G [×n]→L[𝕜] G') (s : finset (fin n)) (hk : s.card = k) (z : G) : ∥f.restr s hk z∥ ≤ ∥f∥ * ∥z∥ ^ (n - k) := begin apply multilinear_map.mk_continuous_norm_le, exact mul_nonneg (norm_nonneg _) (pow_nonneg (norm_nonneg _) _) end section variables (𝕜 ι) (A : Type*) [normed_comm_ring A] [normed_algebra 𝕜 A] /-- The continuous multilinear map on `A^ι`, where `A` is a normed commutative algebra over `𝕜`, associating to `m` the product of all the `m i`. See also `continuous_multilinear_map.mk_pi_algebra_fin`. -/ protected def mk_pi_algebra : continuous_multilinear_map 𝕜 (λ i : ι, A) A := multilinear_map.mk_continuous (multilinear_map.mk_pi_algebra 𝕜 ι A) (if nonempty ι then 1 else ∥(1 : A)∥) $ begin intro m, casesI is_empty_or_nonempty ι with hι hι, { simp [eq_empty_of_is_empty univ, not_nonempty_iff.2 hι] }, { simp [norm_prod_le' univ univ_nonempty, hι] } end variables {A 𝕜 ι} @[simp] lemma mk_pi_algebra_apply (m : ι → A) : continuous_multilinear_map.mk_pi_algebra 𝕜 ι A m = ∏ i, m i := rfl lemma norm_mk_pi_algebra_le [nonempty ι] : ∥continuous_multilinear_map.mk_pi_algebra 𝕜 ι A∥ ≤ 1 := calc ∥continuous_multilinear_map.mk_pi_algebra 𝕜 ι A∥ ≤ if nonempty ι then 1 else ∥(1 : A)∥ : multilinear_map.mk_continuous_norm_le _ (by split_ifs; simp [zero_le_one]) _ ... = _ : if_pos ‹_› lemma norm_mk_pi_algebra_of_empty [is_empty ι] : ∥continuous_multilinear_map.mk_pi_algebra 𝕜 ι A∥ = ∥(1 : A)∥ := begin apply le_antisymm, calc ∥continuous_multilinear_map.mk_pi_algebra 𝕜 ι A∥ ≤ if nonempty ι then 1 else ∥(1 : A)∥ : multilinear_map.mk_continuous_norm_le _ (by split_ifs; simp [zero_le_one]) _ ... = ∥(1 : A)∥ : if_neg (not_nonempty_iff.mpr ‹_›), convert ratio_le_op_norm _ (λ _, (1 : A)), simp [eq_empty_of_is_empty (univ : finset ι)], end @[simp] lemma norm_mk_pi_algebra [norm_one_class A] : ∥continuous_multilinear_map.mk_pi_algebra 𝕜 ι A∥ = 1 := begin casesI is_empty_or_nonempty ι, { simp [norm_mk_pi_algebra_of_empty] }, { refine le_antisymm norm_mk_pi_algebra_le _, convert ratio_le_op_norm _ (λ _, 1); [skip, apply_instance], simp }, end end section variables (𝕜 n) (A : Type*) [normed_ring A] [normed_algebra 𝕜 A] /-- The continuous multilinear map on `A^n`, where `A` is a normed algebra over `𝕜`, associating to `m` the product of all the `m i`. See also: `multilinear_map.mk_pi_algebra`. -/ protected def mk_pi_algebra_fin : continuous_multilinear_map 𝕜 (λ i : fin n, A) A := multilinear_map.mk_continuous (multilinear_map.mk_pi_algebra_fin 𝕜 n A) (nat.cases_on n ∥(1 : A)∥ (λ _, 1)) $ begin intro m, cases n, { simp }, { have : @list.of_fn A n.succ m ≠ [] := by simp, simpa [← fin.prod_of_fn] using list.norm_prod_le' this } end variables {A 𝕜 n} @[simp] lemma mk_pi_algebra_fin_apply (m : fin n → A) : continuous_multilinear_map.mk_pi_algebra_fin 𝕜 n A m = (list.of_fn m).prod := rfl lemma norm_mk_pi_algebra_fin_succ_le : ∥continuous_multilinear_map.mk_pi_algebra_fin 𝕜 n.succ A∥ ≤ 1 := multilinear_map.mk_continuous_norm_le _ zero_le_one _ lemma norm_mk_pi_algebra_fin_le_of_pos (hn : 0 < n) : ∥continuous_multilinear_map.mk_pi_algebra_fin 𝕜 n A∥ ≤ 1 := by cases n; [exact hn.false.elim, exact norm_mk_pi_algebra_fin_succ_le] lemma norm_mk_pi_algebra_fin_zero : ∥continuous_multilinear_map.mk_pi_algebra_fin 𝕜 0 A∥ = ∥(1 : A)∥ := begin refine le_antisymm (multilinear_map.mk_continuous_norm_le _ (norm_nonneg _) _) _, convert ratio_le_op_norm _ (λ _, 1); [simp, apply_instance] end @[simp] lemma norm_mk_pi_algebra_fin [norm_one_class A] : ∥continuous_multilinear_map.mk_pi_algebra_fin 𝕜 n A∥ = 1 := begin cases n, { simp [norm_mk_pi_algebra_fin_zero] }, { refine le_antisymm norm_mk_pi_algebra_fin_succ_le _, convert ratio_le_op_norm _ (λ _, 1); [skip, apply_instance], simp } end end variables (𝕜 ι) /-- The canonical continuous multilinear map on `𝕜^ι`, associating to `m` the product of all the `m i` (multiplied by a fixed reference element `z` in the target module) -/ protected def mk_pi_field (z : G) : continuous_multilinear_map 𝕜 (λ(i : ι), 𝕜) G := multilinear_map.mk_continuous (multilinear_map.mk_pi_ring 𝕜 ι z) (∥z∥) (λ m, by simp only [multilinear_map.mk_pi_ring_apply, norm_smul, normed_field.norm_prod, mul_comm]) variables {𝕜 ι} @[simp] lemma mk_pi_field_apply (z : G) (m : ι → 𝕜) : (continuous_multilinear_map.mk_pi_field 𝕜 ι z : (ι → 𝕜) → G) m = (∏ i, m i) • z := rfl lemma mk_pi_field_apply_one_eq_self (f : continuous_multilinear_map 𝕜 (λ(i : ι), 𝕜) G) : continuous_multilinear_map.mk_pi_field 𝕜 ι (f (λi, 1)) = f := to_multilinear_map_inj f.to_multilinear_map.mk_pi_ring_apply_one_eq_self variables (𝕜 ι G) /-- Continuous multilinear maps on `𝕜^n` with values in `G` are in bijection with `G`, as such a continuous multilinear map is completely determined by its value on the constant vector made of ones. We register this bijection as a linear equivalence in `continuous_multilinear_map.pi_field_equiv_aux`. The continuous linear equivalence is `continuous_multilinear_map.pi_field_equiv`. -/ protected def pi_field_equiv_aux : G ≃ₗ[𝕜] (continuous_multilinear_map 𝕜 (λ(i : ι), 𝕜) G) := { to_fun := λ z, continuous_multilinear_map.mk_pi_field 𝕜 ι z, inv_fun := λ f, f (λi, 1), map_add' := λ z z', by { ext m, simp [smul_add] }, map_smul' := λ c z, by { ext m, simp [smul_smul, mul_comm] }, left_inv := λ z, by simp, right_inv := λ f, f.mk_pi_field_apply_one_eq_self } /-- Continuous multilinear maps on `𝕜^n` with values in `G` are in bijection with `G`, as such a continuous multilinear map is completely determined by its value on the constant vector made of ones. We register this bijection as a continuous linear equivalence in `continuous_multilinear_map.pi_field_equiv`. -/ protected def pi_field_equiv : G ≃L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : ι), 𝕜) G) := { continuous_to_fun := begin refine (continuous_multilinear_map.pi_field_equiv_aux 𝕜 ι G).to_linear_map.continuous_of_bound (1 : ℝ) (λz, _), rw one_mul, change ∥continuous_multilinear_map.mk_pi_field 𝕜 ι z∥ ≤ ∥z∥, exact multilinear_map.mk_continuous_norm_le _ (norm_nonneg _) _ end, continuous_inv_fun := begin refine (continuous_multilinear_map.pi_field_equiv_aux 𝕜 ι G).symm.to_linear_map.continuous_of_bound (1 : ℝ) (λf, _), rw one_mul, change ∥f (λi, 1)∥ ≤ ∥f∥, apply @continuous_multilinear_map.unit_le_op_norm 𝕜 ι (λ (i : ι), 𝕜) G _ _ _ _ _ _ _ f, simp only [pi_norm_le_iff zero_le_one, norm_one], exact λ _, le_rfl end, .. continuous_multilinear_map.pi_field_equiv_aux 𝕜 ι G } end continuous_multilinear_map namespace continuous_linear_map lemma norm_comp_continuous_multilinear_map_le (g : G →L[𝕜] G') (f : continuous_multilinear_map 𝕜 E G) : ∥g.comp_continuous_multilinear_map f∥ ≤ ∥g∥ * ∥f∥ := continuous_multilinear_map.op_norm_le_bound _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) $ λ m, calc ∥g (f m)∥ ≤ ∥g∥ * (∥f∥ * ∏ i, ∥m i∥) : g.le_op_norm_of_le $ f.le_op_norm _ ... = _ : (mul_assoc _ _ _).symm /-- `continuous_linear_map.comp_continuous_multilinear_map` as a bundled continuous bilinear map. -/ def comp_continuous_multilinear_mapL : (G →L[𝕜] G') →L[𝕜] continuous_multilinear_map 𝕜 E G →L[𝕜] continuous_multilinear_map 𝕜 E G' := linear_map.mk_continuous₂ (linear_map.mk₂ 𝕜 comp_continuous_multilinear_map (λ f₁ f₂ g, rfl) (λ c f g, rfl) (λ f g₁ g₂, by { ext1, apply f.map_add }) (λ c f g, by { ext1, simp })) 1 $ λ f g, by { rw one_mul, exact f.norm_comp_continuous_multilinear_map_le g } /-- Flip arguments in `f : G →L[𝕜] continuous_multilinear_map 𝕜 E G'` to get `continuous_multilinear_map 𝕜 E (G →L[𝕜] G')` -/ def flip_multilinear (f : G →L[𝕜] continuous_multilinear_map 𝕜 E G') : continuous_multilinear_map 𝕜 E (G →L[𝕜] G') := multilinear_map.mk_continuous { to_fun := λ m, linear_map.mk_continuous { to_fun := λ x, f x m, map_add' := λ x y, by simp only [map_add, continuous_multilinear_map.add_apply], map_smul' := λ c x, by simp only [continuous_multilinear_map.smul_apply, map_smul, ring_hom.id_apply] } (∥f∥ * ∏ i, ∥m i∥) $ λ x, by { rw mul_right_comm, exact (f x).le_of_op_norm_le _ (f.le_op_norm x) }, map_add' := λ m i x y, by { ext1, simp only [add_apply, continuous_multilinear_map.map_add, linear_map.coe_mk, linear_map.mk_continuous_apply]}, map_smul' := λ m i c x, by { ext1, simp only [coe_smul', continuous_multilinear_map.map_smul, linear_map.coe_mk, linear_map.mk_continuous_apply, pi.smul_apply]} } ∥f∥ $ λ m, linear_map.mk_continuous_norm_le _ (mul_nonneg (norm_nonneg f) (prod_nonneg $ λ i hi, norm_nonneg (m i))) _ end continuous_linear_map open continuous_multilinear_map namespace multilinear_map /-- Given a map `f : G →ₗ[𝕜] multilinear_map 𝕜 E G'` and an estimate `H : ∀ x m, ∥f x m∥ ≤ C * ∥x∥ * ∏ i, ∥m i∥`, construct a continuous linear map from `G` to `continuous_multilinear_map 𝕜 E G'`. In order to lift, e.g., a map `f : (multilinear_map 𝕜 E G) →ₗ[𝕜] multilinear_map 𝕜 E' G'` to a map `(continuous_multilinear_map 𝕜 E G) →L[𝕜] continuous_multilinear_map 𝕜 E' G'`, one can apply this construction to `f.comp continuous_multilinear_map.to_multilinear_map_linear` which is a linear map from `continuous_multilinear_map 𝕜 E G` to `multilinear_map 𝕜 E' G'`. -/ def mk_continuous_linear (f : G →ₗ[𝕜] multilinear_map 𝕜 E G') (C : ℝ) (H : ∀ x m, ∥f x m∥ ≤ C * ∥x∥ * ∏ i, ∥m i∥) : G →L[𝕜] continuous_multilinear_map 𝕜 E G' := linear_map.mk_continuous { to_fun := λ x, (f x).mk_continuous (C * ∥x∥) $ H x, map_add' := λ x y, by { ext1, simp }, map_smul' := λ c x, by { ext1, simp } } (max C 0) $ λ x, ((f x).mk_continuous_norm_le' _).trans_eq $ by rw [max_mul_of_nonneg _ _ (norm_nonneg x), zero_mul] lemma mk_continuous_linear_norm_le' (f : G →ₗ[𝕜] multilinear_map 𝕜 E G') (C : ℝ) (H : ∀ x m, ∥f x m∥ ≤ C * ∥x∥ * ∏ i, ∥m i∥) : ∥mk_continuous_linear f C H∥ ≤ max C 0 := begin dunfold mk_continuous_linear, exact linear_map.mk_continuous_norm_le _ (le_max_right _ _) _ end lemma mk_continuous_linear_norm_le (f : G →ₗ[𝕜] multilinear_map 𝕜 E G') {C : ℝ} (hC : 0 ≤ C) (H : ∀ x m, ∥f x m∥ ≤ C * ∥x∥ * ∏ i, ∥m i∥) : ∥mk_continuous_linear f C H∥ ≤ C := (mk_continuous_linear_norm_le' f C H).trans_eq (max_eq_left hC) /-- Given a map `f : multilinear_map 𝕜 E (multilinear_map 𝕜 E' G)` and an estimate `H : ∀ m m', ∥f m m'∥ ≤ C * ∏ i, ∥m i∥ * ∏ i, ∥m' i∥`, upgrade all `multilinear_map`s in the type to `continuous_multilinear_map`s. -/ def mk_continuous_multilinear (f : multilinear_map 𝕜 E (multilinear_map 𝕜 E' G)) (C : ℝ) (H : ∀ m₁ m₂, ∥f m₁ m₂∥ ≤ C * (∏ i, ∥m₁ i∥) * ∏ i, ∥m₂ i∥) : continuous_multilinear_map 𝕜 E (continuous_multilinear_map 𝕜 E' G) := mk_continuous { to_fun := λ m, mk_continuous (f m) (C * ∏ i, ∥m i∥) $ H m, map_add' := λ m i x y, by { ext1, simp }, map_smul' := λ m i c x, by { ext1, simp } } (max C 0) $ λ m, ((f m).mk_continuous_norm_le' _).trans_eq $ by { rw [max_mul_of_nonneg, zero_mul], exact prod_nonneg (λ _ _, norm_nonneg _) } @[simp] lemma mk_continuous_multilinear_apply (f : multilinear_map 𝕜 E (multilinear_map 𝕜 E' G)) {C : ℝ} (H : ∀ m₁ m₂, ∥f m₁ m₂∥ ≤ C * (∏ i, ∥m₁ i∥) * ∏ i, ∥m₂ i∥) (m : Π i, E i) : ⇑(mk_continuous_multilinear f C H m) = f m := rfl lemma mk_continuous_multilinear_norm_le' (f : multilinear_map 𝕜 E (multilinear_map 𝕜 E' G)) (C : ℝ) (H : ∀ m₁ m₂, ∥f m₁ m₂∥ ≤ C * (∏ i, ∥m₁ i∥) * ∏ i, ∥m₂ i∥) : ∥mk_continuous_multilinear f C H∥ ≤ max C 0 := begin dunfold mk_continuous_multilinear, exact mk_continuous_norm_le _ (le_max_right _ _) _ end lemma mk_continuous_multilinear_norm_le (f : multilinear_map 𝕜 E (multilinear_map 𝕜 E' G)) {C : ℝ} (hC : 0 ≤ C) (H : ∀ m₁ m₂, ∥f m₁ m₂∥ ≤ C * (∏ i, ∥m₁ i∥) * ∏ i, ∥m₂ i∥) : ∥mk_continuous_multilinear f C H∥ ≤ C := (mk_continuous_multilinear_norm_le' f C H).trans_eq (max_eq_left hC) end multilinear_map namespace continuous_multilinear_map lemma norm_comp_continuous_linear_le (g : continuous_multilinear_map 𝕜 E₁ G) (f : Π i, E i →L[𝕜] E₁ i) : ∥g.comp_continuous_linear_map f∥ ≤ ∥g∥ * ∏ i, ∥f i∥ := op_norm_le_bound _ (mul_nonneg (norm_nonneg _) $ prod_nonneg $ λ i hi, norm_nonneg _) $ λ m, calc ∥g (λ i, f i (m i))∥ ≤ ∥g∥ * ∏ i, ∥f i (m i)∥ : g.le_op_norm _ ... ≤ ∥g∥ * ∏ i, (∥f i∥ * ∥m i∥) : mul_le_mul_of_nonneg_left (prod_le_prod (λ _ _, norm_nonneg _) (λ i hi, (f i).le_op_norm (m i))) (norm_nonneg g) ... = (∥g∥ * ∏ i, ∥f i∥) * ∏ i, ∥m i∥ : by rw [prod_mul_distrib, mul_assoc] /-- `continuous_multilinear_map.comp_continuous_linear_map` as a bundled continuous linear map. This implementation fixes `f : Π i, E i →L[𝕜] E₁ i`. TODO: Actually, the map is multilinear in `f` but an attempt to formalize this failed because of issues with class instances. -/ def comp_continuous_linear_mapL (f : Π i, E i →L[𝕜] E₁ i) : continuous_multilinear_map 𝕜 E₁ G →L[𝕜] continuous_multilinear_map 𝕜 E G := linear_map.mk_continuous { to_fun := λ g, g.comp_continuous_linear_map f, map_add' := λ g₁ g₂, rfl, map_smul' := λ c g, rfl } (∏ i, ∥f i∥) $ λ g, (norm_comp_continuous_linear_le _ _).trans_eq (mul_comm _ _) @[simp] lemma comp_continuous_linear_mapL_apply (g : continuous_multilinear_map 𝕜 E₁ G) (f : Π i, E i →L[𝕜] E₁ i) : comp_continuous_linear_mapL f g = g.comp_continuous_linear_map f := rfl lemma norm_comp_continuous_linear_mapL_le (f : Π i, E i →L[𝕜] E₁ i) : ∥@comp_continuous_linear_mapL 𝕜 ι E E₁ G _ _ _ _ _ _ _ _ _ f∥ ≤ (∏ i, ∥f i∥) := linear_map.mk_continuous_norm_le _ (prod_nonneg $ λ i _, norm_nonneg _) _ end continuous_multilinear_map section currying /-! ### Currying We associate to a continuous multilinear map in `n+1` variables (i.e., based on `fin n.succ`) two curried functions, named `f.curry_left` (which is a continuous linear map on `E 0` taking values in continuous multilinear maps in `n` variables) and `f.curry_right` (which is a continuous multilinear map in `n` variables taking values in continuous linear maps on `E (last n)`). The inverse operations are called `uncurry_left` and `uncurry_right`. We also register continuous linear equiv versions of these correspondences, in `continuous_multilinear_curry_left_equiv` and `continuous_multilinear_curry_right_equiv`. -/ open fin function lemma continuous_linear_map.norm_map_tail_le (f : Ei 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), Ei i.succ) G)) (m : Πi, Ei i) : ∥f (m 0) (tail m)∥ ≤ ∥f∥ * ∏ i, ∥m i∥ := calc ∥f (m 0) (tail m)∥ ≤ ∥f (m 0)∥ * ∏ i, ∥(tail m) i∥ : (f (m 0)).le_op_norm _ ... ≤ (∥f∥ * ∥m 0∥) * ∏ i, ∥(tail m) i∥ : mul_le_mul_of_nonneg_right (f.le_op_norm _) (prod_nonneg (λi hi, norm_nonneg _)) ... = ∥f∥ * (∥m 0∥ * ∏ i, ∥(tail m) i∥) : by ring ... = ∥f∥ * ∏ i, ∥m i∥ : by { rw prod_univ_succ, refl } lemma continuous_multilinear_map.norm_map_init_le (f : continuous_multilinear_map 𝕜 (λ(i : fin n), Ei i.cast_succ) (Ei (last n) →L[𝕜] G)) (m : Πi, Ei i) : ∥f (init m) (m (last n))∥ ≤ ∥f∥ * ∏ i, ∥m i∥ := calc ∥f (init m) (m (last n))∥ ≤ ∥f (init m)∥ * ∥m (last n)∥ : (f (init m)).le_op_norm _ ... ≤ (∥f∥ * (∏ i, ∥(init m) i∥)) * ∥m (last n)∥ : mul_le_mul_of_nonneg_right (f.le_op_norm _) (norm_nonneg _) ... = ∥f∥ * ((∏ i, ∥(init m) i∥) * ∥m (last n)∥) : mul_assoc _ _ _ ... = ∥f∥ * ∏ i, ∥m i∥ : by { rw prod_univ_cast_succ, refl } lemma continuous_multilinear_map.norm_map_cons_le (f : continuous_multilinear_map 𝕜 Ei G) (x : Ei 0) (m : Π(i : fin n), Ei i.succ) : ∥f (cons x m)∥ ≤ ∥f∥ * ∥x∥ * ∏ i, ∥m i∥ := calc ∥f (cons x m)∥ ≤ ∥f∥ * ∏ i, ∥cons x m i∥ : f.le_op_norm _ ... = (∥f∥ * ∥x∥) * ∏ i, ∥m i∥ : by { rw prod_univ_succ, simp [mul_assoc] } lemma continuous_multilinear_map.norm_map_snoc_le (f : continuous_multilinear_map 𝕜 Ei G) (m : Π(i : fin n), Ei i.cast_succ) (x : Ei (last n)) : ∥f (snoc m x)∥ ≤ ∥f∥ * (∏ i, ∥m i∥) * ∥x∥ := calc ∥f (snoc m x)∥ ≤ ∥f∥ * ∏ i, ∥snoc m x i∥ : f.le_op_norm _ ... = ∥f∥ * (∏ i, ∥m i∥) * ∥x∥ : by { rw prod_univ_cast_succ, simp [mul_assoc] } /-! #### Left currying -/ /-- Given a continuous linear map `f` from `E 0` to continuous multilinear maps on `n` variables, construct the corresponding continuous multilinear map on `n+1` variables obtained by concatenating the variables, given by `m ↦ f (m 0) (tail m)`-/ def continuous_linear_map.uncurry_left (f : Ei 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), Ei i.succ) G)) : continuous_multilinear_map 𝕜 Ei G := (@linear_map.uncurry_left 𝕜 n Ei G _ _ _ _ _ (continuous_multilinear_map.to_multilinear_map_linear.comp f.to_linear_map)).mk_continuous (∥f∥) (λm, continuous_linear_map.norm_map_tail_le f m) @[simp] lemma continuous_linear_map.uncurry_left_apply (f : Ei 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), Ei i.succ) G)) (m : Πi, Ei i) : f.uncurry_left m = f (m 0) (tail m) := rfl /-- Given a continuous multilinear map `f` in `n+1` variables, split the first variable to obtain a continuous linear map into continuous multilinear maps in `n` variables, given by `x ↦ (m ↦ f (cons x m))`. -/ def continuous_multilinear_map.curry_left (f : continuous_multilinear_map 𝕜 Ei G) : Ei 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), Ei i.succ) G) := linear_map.mk_continuous { -- define a linear map into `n` continuous multilinear maps from an `n+1` continuous multilinear -- map to_fun := λx, (f.to_multilinear_map.curry_left x).mk_continuous (∥f∥ * ∥x∥) (f.norm_map_cons_le x), map_add' := λx y, by { ext m, exact f.cons_add m x y }, map_smul' := λc x, by { ext m, exact f.cons_smul m c x } } -- then register its continuity thanks to its boundedness properties. (∥f∥) (λx, multilinear_map.mk_continuous_norm_le _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) _) @[simp] lemma continuous_multilinear_map.curry_left_apply (f : continuous_multilinear_map 𝕜 Ei G) (x : Ei 0) (m : Π(i : fin n), Ei i.succ) : f.curry_left x m = f (cons x m) := rfl @[simp] lemma continuous_linear_map.curry_uncurry_left (f : Ei 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), Ei i.succ) G)) : f.uncurry_left.curry_left = f := begin ext m x, simp only [tail_cons, continuous_linear_map.uncurry_left_apply, continuous_multilinear_map.curry_left_apply], rw cons_zero end @[simp] lemma continuous_multilinear_map.uncurry_curry_left (f : continuous_multilinear_map 𝕜 Ei G) : f.curry_left.uncurry_left = f := continuous_multilinear_map.to_multilinear_map_inj $ f.to_multilinear_map.uncurry_curry_left variables (𝕜 Ei G) /-- The space of continuous multilinear maps on `Π(i : fin (n+1)), E i` is canonically isomorphic to the space of continuous linear maps from `E 0` to the space of continuous multilinear maps on `Π(i : fin n), E i.succ `, by separating the first variable. We register this isomorphism in `continuous_multilinear_curry_left_equiv 𝕜 E E₂`. The algebraic version (without topology) is given in `multilinear_curry_left_equiv 𝕜 E E₂`. The direct and inverse maps are given by `f.uncurry_left` and `f.curry_left`. Use these unless you need the full framework of linear isometric equivs. -/ def continuous_multilinear_curry_left_equiv : (Ei 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), Ei i.succ) G)) ≃ₗᵢ[𝕜] (continuous_multilinear_map 𝕜 Ei G) := linear_isometry_equiv.of_bounds { to_fun := continuous_linear_map.uncurry_left, map_add' := λf₁ f₂, by { ext m, refl }, map_smul' := λc f, by { ext m, refl }, inv_fun := continuous_multilinear_map.curry_left, left_inv := continuous_linear_map.curry_uncurry_left, right_inv := continuous_multilinear_map.uncurry_curry_left } (λ f, multilinear_map.mk_continuous_norm_le _ (norm_nonneg f) _) (λ f, linear_map.mk_continuous_norm_le _ (norm_nonneg f) _) variables {𝕜 Ei G} @[simp] lemma continuous_multilinear_curry_left_equiv_apply (f : Ei 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ i : fin n, Ei i.succ) G)) (v : Π i, Ei i) : continuous_multilinear_curry_left_equiv 𝕜 Ei G f v = f (v 0) (tail v) := rfl @[simp] lemma continuous_multilinear_curry_left_equiv_symm_apply (f : continuous_multilinear_map 𝕜 Ei G) (x : Ei 0) (v : Π i : fin n, Ei i.succ) : (continuous_multilinear_curry_left_equiv 𝕜 Ei G).symm f x v = f (cons x v) := rfl @[simp] lemma continuous_multilinear_map.curry_left_norm (f : continuous_multilinear_map 𝕜 Ei G) : ∥f.curry_left∥ = ∥f∥ := (continuous_multilinear_curry_left_equiv 𝕜 Ei G).symm.norm_map f @[simp] lemma continuous_linear_map.uncurry_left_norm (f : Ei 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), Ei i.succ) G)) : ∥f.uncurry_left∥ = ∥f∥ := (continuous_multilinear_curry_left_equiv 𝕜 Ei G).norm_map f /-! #### Right currying -/ /-- Given a continuous linear map `f` from continuous multilinear maps on `n` variables to continuous linear maps on `E 0`, construct the corresponding continuous multilinear map on `n+1` variables obtained by concatenating the variables, given by `m ↦ f (init m) (m (last n))`. -/ def continuous_multilinear_map.uncurry_right (f : continuous_multilinear_map 𝕜 (λ i : fin n, Ei i.cast_succ) (Ei (last n) →L[𝕜] G)) : continuous_multilinear_map 𝕜 Ei G := let f' : multilinear_map 𝕜 (λ(i : fin n), Ei i.cast_succ) (Ei (last n) →ₗ[𝕜] G) := { to_fun := λ m, (f m).to_linear_map, map_add' := λ m i x y, by simp, map_smul' := λ m i c x, by simp } in (@multilinear_map.uncurry_right 𝕜 n Ei G _ _ _ _ _ f').mk_continuous (∥f∥) (λm, f.norm_map_init_le m) @[simp] lemma continuous_multilinear_map.uncurry_right_apply (f : continuous_multilinear_map 𝕜 (λ(i : fin n), Ei i.cast_succ) (Ei (last n) →L[𝕜] G)) (m : Πi, Ei i) : f.uncurry_right m = f (init m) (m (last n)) := rfl /-- Given a continuous multilinear map `f` in `n+1` variables, split the last variable to obtain a continuous multilinear map in `n` variables into continuous linear maps, given by `m ↦ (x ↦ f (snoc m x))`. -/ def continuous_multilinear_map.curry_right (f : continuous_multilinear_map 𝕜 Ei G) : continuous_multilinear_map 𝕜 (λ i : fin n, Ei i.cast_succ) (Ei (last n) →L[𝕜] G) := let f' : multilinear_map 𝕜 (λ(i : fin n), Ei i.cast_succ) (Ei (last n) →L[𝕜] G) := { to_fun := λm, (f.to_multilinear_map.curry_right m).mk_continuous (∥f∥ * ∏ i, ∥m i∥) $ λx, f.norm_map_snoc_le m x, map_add' := λ m i x y, by { simp, refl }, map_smul' := λ m i c x, by { simp, refl } } in f'.mk_continuous (∥f∥) (λm, linear_map.mk_continuous_norm_le _ (mul_nonneg (norm_nonneg _) (prod_nonneg (λj hj, norm_nonneg _))) _) @[simp] lemma continuous_multilinear_map.curry_right_apply (f : continuous_multilinear_map 𝕜 Ei G) (m : Π i : fin n, Ei i.cast_succ) (x : Ei (last n)) : f.curry_right m x = f (snoc m x) := rfl @[simp] lemma continuous_multilinear_map.curry_uncurry_right (f : continuous_multilinear_map 𝕜 (λ i : fin n, Ei i.cast_succ) (Ei (last n) →L[𝕜] G)) : f.uncurry_right.curry_right = f := begin ext m x, simp only [snoc_last, continuous_multilinear_map.curry_right_apply, continuous_multilinear_map.uncurry_right_apply], rw init_snoc end @[simp] lemma continuous_multilinear_map.uncurry_curry_right (f : continuous_multilinear_map 𝕜 Ei G) : f.curry_right.uncurry_right = f := by { ext m, simp } variables (𝕜 Ei G) /-- The space of continuous multilinear maps on `Π(i : fin (n+1)), Ei i` is canonically isomorphic to the space of continuous multilinear maps on `Π(i : fin n), Ei i.cast_succ` with values in the space of continuous linear maps on `Ei (last n)`, by separating the last variable. We register this isomorphism as a continuous linear equiv in `continuous_multilinear_curry_right_equiv 𝕜 Ei G`. The algebraic version (without topology) is given in `multilinear_curry_right_equiv 𝕜 Ei G`. The direct and inverse maps are given by `f.uncurry_right` and `f.curry_right`. Use these unless you need the full framework of linear isometric equivs. -/ def continuous_multilinear_curry_right_equiv : (continuous_multilinear_map 𝕜 (λ(i : fin n), Ei i.cast_succ) (Ei (last n) →L[𝕜] G)) ≃ₗᵢ[𝕜] (continuous_multilinear_map 𝕜 Ei G) := linear_isometry_equiv.of_bounds { to_fun := continuous_multilinear_map.uncurry_right, map_add' := λf₁ f₂, by { ext m, refl }, map_smul' := λc f, by { ext m, refl }, inv_fun := continuous_multilinear_map.curry_right, left_inv := continuous_multilinear_map.curry_uncurry_right, right_inv := continuous_multilinear_map.uncurry_curry_right } (λ f, multilinear_map.mk_continuous_norm_le _ (norm_nonneg f) _) (λ f, multilinear_map.mk_continuous_norm_le _ (norm_nonneg f) _) variables (n G') /-- The space of continuous multilinear maps on `Π(i : fin (n+1)), G` is canonically isomorphic to the space of continuous multilinear maps on `Π(i : fin n), G` with values in the space of continuous linear maps on `G`, by separating the last variable. We register this isomorphism as a continuous linear equiv in `continuous_multilinear_curry_right_equiv' 𝕜 n G G'`. For a version allowing dependent types, see `continuous_multilinear_curry_right_equiv`. When there are no dependent types, use the primed version as it helps Lean a lot for unification. The direct and inverse maps are given by `f.uncurry_right` and `f.curry_right`. Use these unless you need the full framework of linear isometric equivs. -/ def continuous_multilinear_curry_right_equiv' : (G [×n]→L[𝕜] (G →L[𝕜] G')) ≃ₗᵢ[𝕜] (G [×n.succ]→L[𝕜] G') := continuous_multilinear_curry_right_equiv 𝕜 (λ (i : fin n.succ), G) G' variables {n 𝕜 G Ei G'} @[simp] lemma continuous_multilinear_curry_right_equiv_apply (f : (continuous_multilinear_map 𝕜 (λ(i : fin n), Ei i.cast_succ) (Ei (last n) →L[𝕜] G))) (v : Π i, Ei i) : (continuous_multilinear_curry_right_equiv 𝕜 Ei G) f v = f (init v) (v (last n)) := rfl @[simp] lemma continuous_multilinear_curry_right_equiv_symm_apply (f : continuous_multilinear_map 𝕜 Ei G) (v : Π (i : fin n), Ei i.cast_succ) (x : Ei (last n)) : (continuous_multilinear_curry_right_equiv 𝕜 Ei G).symm f v x = f (snoc v x) := rfl @[simp] lemma continuous_multilinear_curry_right_equiv_apply' (f : G [×n]→L[𝕜] (G →L[𝕜] G')) (v : Π (i : fin n.succ), G) : continuous_multilinear_curry_right_equiv' 𝕜 n G G' f v = f (init v) (v (last n)) := rfl @[simp] lemma continuous_multilinear_curry_right_equiv_symm_apply' (f : G [×n.succ]→L[𝕜] G') (v : Π (i : fin n), G) (x : G) : (continuous_multilinear_curry_right_equiv' 𝕜 n G G').symm f v x = f (snoc v x) := rfl @[simp] lemma continuous_multilinear_map.curry_right_norm (f : continuous_multilinear_map 𝕜 Ei G) : ∥f.curry_right∥ = ∥f∥ := (continuous_multilinear_curry_right_equiv 𝕜 Ei G).symm.norm_map f @[simp] lemma continuous_multilinear_map.uncurry_right_norm (f : continuous_multilinear_map 𝕜 (λ i : fin n, Ei i.cast_succ) (Ei (last n) →L[𝕜] G)) : ∥f.uncurry_right∥ = ∥f∥ := (continuous_multilinear_curry_right_equiv 𝕜 Ei G).norm_map f /-! #### Currying with `0` variables The space of multilinear maps with `0` variables is trivial: such a multilinear map is just an arbitrary constant (note that multilinear maps in `0` variables need not map `0` to `0`!). Therefore, the space of continuous multilinear maps on `(fin 0) → G` with values in `E₂` is isomorphic (and even isometric) to `E₂`. As this is the zeroth step in the construction of iterated derivatives, we register this isomorphism. -/ section local attribute [instance] unique.subsingleton variables {𝕜 G G'} /-- Associating to a continuous multilinear map in `0` variables the unique value it takes. -/ def continuous_multilinear_map.uncurry0 (f : continuous_multilinear_map 𝕜 (λ (i : fin 0), G) G') : G' := f 0 variables (𝕜 G) /-- Associating to an element `x` of a vector space `E₂` the continuous multilinear map in `0` variables taking the (unique) value `x` -/ def continuous_multilinear_map.curry0 (x : G') : G [×0]→L[𝕜] G' := { to_fun := λm, x, map_add' := λ m i, fin.elim0 i, map_smul' := λ m i, fin.elim0 i, cont := continuous_const } variable {G} @[simp] lemma continuous_multilinear_map.curry0_apply (x : G') (m : (fin 0) → G) : continuous_multilinear_map.curry0 𝕜 G x m = x := rfl variable {𝕜} @[simp] lemma continuous_multilinear_map.uncurry0_apply (f : G [×0]→L[𝕜] G') : f.uncurry0 = f 0 := rfl @[simp] lemma continuous_multilinear_map.apply_zero_curry0 (f : G [×0]→L[𝕜] G') {x : fin 0 → G} : continuous_multilinear_map.curry0 𝕜 G (f x) = f := by { ext m, simp [(subsingleton.elim _ _ : x = m)] } lemma continuous_multilinear_map.uncurry0_curry0 (f : G [×0]→L[𝕜] G') : continuous_multilinear_map.curry0 𝕜 G (f.uncurry0) = f := by simp variables (𝕜 G) @[simp] lemma continuous_multilinear_map.curry0_uncurry0 (x : G') : (continuous_multilinear_map.curry0 𝕜 G x).uncurry0 = x := rfl @[simp] lemma continuous_multilinear_map.curry0_norm (x : G') : ∥continuous_multilinear_map.curry0 𝕜 G x∥ = ∥x∥ := begin apply le_antisymm, { exact continuous_multilinear_map.op_norm_le_bound _ (norm_nonneg _) (λm, by simp) }, { simpa using (continuous_multilinear_map.curry0 𝕜 G x).le_op_norm 0 } end variables {𝕜 G} @[simp] lemma continuous_multilinear_map.fin0_apply_norm (f : G [×0]→L[𝕜] G') {x : fin 0 → G} : ∥f x∥ = ∥f∥ := begin have : x = 0 := subsingleton.elim _ _, subst this, refine le_antisymm (by simpa using f.le_op_norm 0) _, have : ∥continuous_multilinear_map.curry0 𝕜 G (f.uncurry0)∥ ≤ ∥f.uncurry0∥ := continuous_multilinear_map.op_norm_le_bound _ (norm_nonneg _) (λm, by simp [-continuous_multilinear_map.apply_zero_curry0]), simpa end lemma continuous_multilinear_map.uncurry0_norm (f : G [×0]→L[𝕜] G') : ∥f.uncurry0∥ = ∥f∥ := by simp variables (𝕜 G G') /-- The continuous linear isomorphism between elements of a normed space, and continuous multilinear maps in `0` variables with values in this normed space. The direct and inverse maps are `uncurry0` and `curry0`. Use these unless you need the full framework of linear isometric equivs. -/ def continuous_multilinear_curry_fin0 : (G [×0]→L[𝕜] G') ≃ₗᵢ[𝕜] G' := { to_fun := λf, continuous_multilinear_map.uncurry0 f, inv_fun := λf, continuous_multilinear_map.curry0 𝕜 G f, map_add' := λf g, rfl, map_smul' := λc f, rfl, left_inv := continuous_multilinear_map.uncurry0_curry0, right_inv := continuous_multilinear_map.curry0_uncurry0 𝕜 G, norm_map' := continuous_multilinear_map.uncurry0_norm } variables {𝕜 G G'} @[simp] lemma continuous_multilinear_curry_fin0_apply (f : G [×0]→L[𝕜] G') : continuous_multilinear_curry_fin0 𝕜 G G' f = f 0 := rfl @[simp] lemma continuous_multilinear_curry_fin0_symm_apply (x : G') (v : (fin 0) → G) : (continuous_multilinear_curry_fin0 𝕜 G G').symm x v = x := rfl end /-! #### With 1 variable -/ variables (𝕜 G G') /-- Continuous multilinear maps from `G^1` to `G'` are isomorphic with continuous linear maps from `G` to `G'`. -/ def continuous_multilinear_curry_fin1 : (G [×1]→L[𝕜] G') ≃ₗᵢ[𝕜] (G →L[𝕜] G') := (continuous_multilinear_curry_right_equiv 𝕜 (λ (i : fin 1), G) G').symm.trans (continuous_multilinear_curry_fin0 𝕜 G (G →L[𝕜] G')) variables {𝕜 G G'} @[simp] lemma continuous_multilinear_curry_fin1_apply (f : G [×1]→L[𝕜] G') (x : G) : continuous_multilinear_curry_fin1 𝕜 G G' f x = f (fin.snoc 0 x) := rfl @[simp] lemma continuous_multilinear_curry_fin1_symm_apply (f : G →L[𝕜] G') (v : (fin 1) → G) : (continuous_multilinear_curry_fin1 𝕜 G G').symm f v = f (v 0) := rfl namespace continuous_multilinear_map variables (𝕜 G G') /-- An equivalence of the index set defines a linear isometric equivalence between the spaces of multilinear maps. -/ def dom_dom_congr (σ : ι ≃ ι') : continuous_multilinear_map 𝕜 (λ _ : ι, G) G' ≃ₗᵢ[𝕜] continuous_multilinear_map 𝕜 (λ _ : ι', G) G' := linear_isometry_equiv.of_bounds { to_fun := λ f, (multilinear_map.dom_dom_congr σ f.to_multilinear_map).mk_continuous ∥f∥ $ λ m, (f.le_op_norm (λ i, m (σ i))).trans_eq $ by rw [← σ.prod_comp], inv_fun := λ f, (multilinear_map.dom_dom_congr σ.symm f.to_multilinear_map).mk_continuous ∥f∥ $ λ m, (f.le_op_norm (λ i, m (σ.symm i))).trans_eq $ by rw [← σ.symm.prod_comp], left_inv := λ f, ext $ λ m, congr_arg f $ by simp only [σ.symm_apply_apply], right_inv := λ f, ext $ λ m, congr_arg f $ by simp only [σ.apply_symm_apply], map_add' := λ f g, rfl, map_smul' := λ c f, rfl } (λ f, multilinear_map.mk_continuous_norm_le _ (norm_nonneg f) _) (λ f, multilinear_map.mk_continuous_norm_le _ (norm_nonneg f) _) variables {𝕜 G G'} section variable [decidable_eq (ι ⊕ ι')] /-- A continuous multilinear map with variables indexed by `ι ⊕ ι'` defines a continuous multilinear map with variables indexed by `ι` taking values in the space of continuous multilinear maps with variables indexed by `ι'`. -/ def curry_sum (f : continuous_multilinear_map 𝕜 (λ x : ι ⊕ ι', G) G') : continuous_multilinear_map 𝕜 (λ x : ι, G) (continuous_multilinear_map 𝕜 (λ x : ι', G) G') := multilinear_map.mk_continuous_multilinear (multilinear_map.curry_sum f.to_multilinear_map) (∥f∥) $ λ m m', by simpa [fintype.prod_sum_type, mul_assoc] using f.le_op_norm (sum.elim m m') @[simp] lemma curry_sum_apply (f : continuous_multilinear_map 𝕜 (λ x : ι ⊕ ι', G) G') (m : ι → G) (m' : ι' → G) : f.curry_sum m m' = f (sum.elim m m') := rfl /-- A continuous multilinear map with variables indexed by `ι` taking values in the space of continuous multilinear maps with variables indexed by `ι'` defines a continuous multilinear map with variables indexed by `ι ⊕ ι'`. -/ def uncurry_sum (f : continuous_multilinear_map 𝕜 (λ x : ι, G) (continuous_multilinear_map 𝕜 (λ x : ι', G) G')) : continuous_multilinear_map 𝕜 (λ x : ι ⊕ ι', G) G' := multilinear_map.mk_continuous (to_multilinear_map_linear.comp_multilinear_map f.to_multilinear_map).uncurry_sum (∥f∥) $ λ m, by simpa [fintype.prod_sum_type, mul_assoc] using (f (m ∘ sum.inl)).le_of_op_norm_le (m ∘ sum.inr) (f.le_op_norm _) @[simp] lemma uncurry_sum_apply (f : continuous_multilinear_map 𝕜 (λ x : ι, G) (continuous_multilinear_map 𝕜 (λ x : ι', G) G')) (m : ι ⊕ ι' → G) : f.uncurry_sum m = f (m ∘ sum.inl) (m ∘ sum.inr) := rfl variables (𝕜 ι ι' G G') /-- Linear isometric equivalence between the space of continuous multilinear maps with variables indexed by `ι ⊕ ι'` and the space of continuous multilinear maps with variables indexed by `ι` taking values in the space of continuous multilinear maps with variables indexed by `ι'`. The forward and inverse functions are `continuous_multilinear_map.curry_sum` and `continuous_multilinear_map.uncurry_sum`. Use this definition only if you need some properties of `linear_isometry_equiv`. -/ def curry_sum_equiv : continuous_multilinear_map 𝕜 (λ x : ι ⊕ ι', G) G' ≃ₗᵢ[𝕜] continuous_multilinear_map 𝕜 (λ x : ι, G) (continuous_multilinear_map 𝕜 (λ x : ι', G) G') := linear_isometry_equiv.of_bounds { to_fun := curry_sum, inv_fun := uncurry_sum, map_add' := λ f g, by { ext, refl }, map_smul' := λ c f, by { ext, refl }, left_inv := λ f, by { ext m, exact congr_arg f (sum.elim_comp_inl_inr m) }, right_inv := λ f, by { ext m₁ m₂, change f _ _ = f _ _, rw [sum.elim_comp_inl, sum.elim_comp_inr] } } (λ f, multilinear_map.mk_continuous_multilinear_norm_le _ (norm_nonneg f) _) (λ f, multilinear_map.mk_continuous_norm_le _ (norm_nonneg f) _) end section variables (𝕜 G G') {k l : ℕ} {s : finset (fin n)} /-- If `s : finset (fin n)` is a finite set of cardinality `k` and its complement has cardinality `l`, then the space of continuous multilinear maps `G [×n]→L[𝕜] G'` of `n` variables is isomorphic to the space of continuous multilinear maps `G [×k]→L[𝕜] G [×l]→L[𝕜] G'` of `k` variables taking values in the space of continuous multilinear maps of `l` variables. -/ def curry_fin_finset {k l n : ℕ} {s : finset (fin n)} (hk : s.card = k) (hl : sᶜ.card = l) : (G [×n]→L[𝕜] G') ≃ₗᵢ[𝕜] (G [×k]→L[𝕜] G [×l]→L[𝕜] G') := (dom_dom_congr 𝕜 G G' (fin_sum_equiv_of_finset hk hl).symm).trans (curry_sum_equiv 𝕜 (fin k) (fin l) G G') variables {𝕜 G G'} @[simp] lemma curry_fin_finset_apply (hk : s.card = k) (hl : sᶜ.card = l) (f : G [×n]→L[𝕜] G') (mk : fin k → G) (ml : fin l → G) : curry_fin_finset 𝕜 G G' hk hl f mk ml = f (λ i, sum.elim mk ml ((fin_sum_equiv_of_finset hk hl).symm i)) := rfl @[simp] lemma curry_fin_finset_symm_apply (hk : s.card = k) (hl : sᶜ.card = l) (f : G [×k]→L[𝕜] G [×l]→L[𝕜] G') (m : fin n → G) : (curry_fin_finset 𝕜 G G' hk hl).symm f m = f (λ i, m $ fin_sum_equiv_of_finset hk hl (sum.inl i)) (λ i, m $ fin_sum_equiv_of_finset hk hl (sum.inr i)) := rfl @[simp] lemma curry_fin_finset_symm_apply_piecewise_const (hk : s.card = k) (hl : sᶜ.card = l) (f : G [×k]→L[𝕜] G [×l]→L[𝕜] G') (x y : G) : (curry_fin_finset 𝕜 G G' hk hl).symm f (s.piecewise (λ _, x) (λ _, y)) = f (λ _, x) (λ _, y) := multilinear_map.curry_fin_finset_symm_apply_piecewise_const hk hl _ x y @[simp] lemma curry_fin_finset_symm_apply_const (hk : s.card = k) (hl : sᶜ.card = l) (f : G [×k]→L[𝕜] G [×l]→L[𝕜] G') (x : G) : (curry_fin_finset 𝕜 G G' hk hl).symm f (λ _, x) = f (λ _, x) (λ _, x) := rfl @[simp] lemma curry_fin_finset_apply_const (hk : s.card = k) (hl : sᶜ.card = l) (f : G [×n]→L[𝕜] G') (x y : G) : curry_fin_finset 𝕜 G G' hk hl f (λ _, x) (λ _, y) = f (s.piecewise (λ _, x) (λ _, y)) := begin refine (curry_fin_finset_symm_apply_piecewise_const hk hl _ _ _).symm.trans _, -- `rw` fails rw linear_isometry_equiv.symm_apply_apply end end end continuous_multilinear_map end currying
83f1f696053bded8ae065bacbf2195b5faa7be2d
853df553b1d6ca524e3f0a79aedd32dde5d27ec3
/src/tactic/interactive_expr.lean
5f97ea18bc8839dbea7f987b4772b334e06013ae
[ "Apache-2.0" ]
permissive
DanielFabian/mathlib
efc3a50b5dde303c59eeb6353ef4c35a345d7112
f520d07eba0c852e96fe26da71d85bf6d40fcc2a
refs/heads/master
1,668,739,922,971
1,595,201,756,000
1,595,201,756,000
279,469,476
0
0
null
1,594,696,604,000
1,594,696,604,000
null
UTF-8
Lean
false
false
12,805
lean
/- Copyright (c) 2020 E.W.Ayers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: E.W.Ayers -/ /-! # Widgets used for tactic state and term-mode goal display The vscode extension supports the display of interactive widgets. Default implementation of these widgets are included in the core library. We override them here using `vm_override` so that we can change them quickly without waiting for the next Lean release. The function `widget_override.interactive_expression.mk` renders a single expression as a widget component. Each goal in a tactic state is rendered using the `widget_override.tactic_view_goal` function, a complete tactic state is rendered using `widget_override.tactic_view_component`. Lean itself calls the `widget_override.term_goal_widget` function to render term-mode goals and `widget_override.tactic_state_widget` to render the tactic state in a tactic proof. -/ namespace widget_override open widget open tagged_format open widget.html widget.attr namespace interactive_expression /-- eformat but without any of the formatting stuff like highlighting, groups etc. -/ meta inductive sf : Type | tag_expr : expr.address → expr → sf → sf | compose : sf → sf → sf | of_string : string → sf /-- Prints a debugging representation of an `sf` object. -/ meta def sf.repr : sf → format | (sf.tag_expr addr e a) := format.group $ format.nest 2 $ "(tag_expr " ++ to_fmt addr ++ format.line ++ "`(" ++ to_fmt e ++ ")" ++ format.line ++ a.repr ++ ")" | (sf.compose a b) := a.repr ++ format.line ++ b.repr | (sf.of_string s) := repr s meta instance : has_to_format sf := ⟨sf.repr⟩ meta instance : has_to_string sf := ⟨λ s, s.repr.to_string⟩ meta instance : has_repr sf := ⟨λ s, s.repr.to_string⟩ /-- Constructs an `sf` from an `eformat` by forgetting grouping, nesting, etc. -/ meta def sf.of_eformat : eformat → sf | (tag ⟨ea,e⟩ m) := sf.tag_expr ea e $ sf.of_eformat m | (group m) := sf.of_eformat m | (nest i m) := sf.of_eformat m | (highlight i m) := sf.of_eformat m | (of_format f) := sf.of_string $ format.to_string f | (compose x y) := sf.compose (sf.of_eformat x) (sf.of_eformat y) /-- Flattens an `sf`, i.e. merges adjacent `of_string` constructors. -/ meta def sf.flatten : sf → sf | (sf.tag_expr e ea m) := (sf.tag_expr e ea $ sf.flatten m) | (sf.compose x y) := match (sf.flatten x), (sf.flatten y) with | (sf.of_string sx), (sf.of_string sy) := sf.of_string (sx ++ sy) | (sf.of_string sx), (sf.compose (sf.of_string sy) z) := sf.compose (sf.of_string (sx ++ sy)) z | (sf.compose x (sf.of_string sy)), (sf.of_string sz) := sf.compose x (sf.of_string (sy ++ sz)) | (sf.compose x (sf.of_string sy1)), (sf.compose (sf.of_string sy2) z) := sf.compose x (sf.compose (sf.of_string (sy1 ++ sy2)) z) | x, y := sf.compose x y end | (sf.of_string s) := sf.of_string s /-- The actions accepted by an expression widget. -/ meta inductive action (γ : Type) | on_mouse_enter : subexpr → action | on_mouse_leave_all : action | on_click : subexpr → action | on_tooltip_action : γ → action | on_close_tooltip : action /-- Renders a subexpression as a list of html elements. -/ meta def view {γ} (tooltip_component : tc subexpr (action γ)) (click_address : option expr.address) (select_address : option expr.address) : subexpr → sf → tactic (list (html (action γ))) | ⟨ce, current_address⟩ (sf.tag_expr ea e m) := do let new_address := current_address ++ ea, let select_attrs : list (attr (action γ)) := if some new_address = select_address then [className "highlight"] else [], click_attrs : list (attr (action γ)) ← if some new_address = click_address then do content ← tc.to_html tooltip_component (e, new_address), pure [tooltip $ h "div" [] [ h "button" [cn "fr pointer ba br3", on_click (λ _, action.on_close_tooltip)] ["x"], content ]] else pure [], let as := [className "expr-boundary", key (ea)] ++ select_attrs ++ click_attrs, inner ← view (e,new_address) m, pure [h "span" as inner] | ca (sf.compose x y) := pure (++) <*> view ca x <*> view ca y | ca (sf.of_string s) := pure [h "span" [ on_mouse_enter (λ _, action.on_mouse_enter ca), on_click (λ _, action.on_click ca), key s ] [html.of_string s]] /-- Make an interactive expression. -/ meta def mk {γ} (tooltip : tc subexpr γ) : tc expr γ := let tooltip_comp := component.with_should_update (λ (x y : tactic_state × expr × expr.address), x.2.2 ≠ y.2.2) $ component.map_action (action.on_tooltip_action) tooltip in tc.mk_simple (action γ) (option subexpr × option subexpr) (λ e, pure $ (none, none)) (λ e ⟨ca, sa⟩ act, pure $ match act with | (action.on_mouse_enter ⟨e, ea⟩) := ((ca, some (e, ea)), none) | (action.on_mouse_leave_all) := ((ca, none), none) | (action.on_click ⟨e, ea⟩) := if some (e,ea) = ca then ((none, sa), none) else ((some (e, ea), sa), none) | (action.on_tooltip_action g) := ((none, sa), some g) | (action.on_close_tooltip) := ((none, sa), none) end ) (λ e ⟨ca, sa⟩, do ts ← tactic.read, let m : sf := sf.flatten $ sf.of_eformat $ tactic_state.pp_tagged ts e, let m : sf := sf.tag_expr [] e m, -- [hack] in pp.cpp I forgot to add an expr-boundary for the root expression. v ← view tooltip_comp (prod.snd <$> ca) (prod.snd <$> sa) ⟨e, []⟩ m, pure $ [ h "span" [ className "expr", key e.hash, on_mouse_leave (λ _, action.on_mouse_leave_all) ] $ v ] ) /-- Render the implicit arguments for an expression in fancy, little pills. -/ meta def implicit_arg_list (tooltip : tc subexpr empty) (e : expr) : tactic $ html empty := do fn ← (mk tooltip) $ expr.get_app_fn e, args ← list.mmap (mk tooltip) $ expr.get_app_args e, pure $ h "div" [] ( (h "span" [className "bg-blue br3 ma1 ph2 white"] [fn]) :: list.map (λ a, h "span" [className "bg-gray br3 ma1 ph2 white"] [a]) args ) /-- Component for the type tooltip. -/ meta def type_tooltip : tc subexpr empty := tc.stateless (λ ⟨e,ea⟩, do y ← tactic.infer_type e, y_comp ← mk type_tooltip y, implicit_args ← implicit_arg_list type_tooltip e, pure [ h "div" [] [ h "div" [] [y_comp], h "hr" [] [], implicit_args ] ] ) end interactive_expression /-- Supported tactic state filters. -/ @[derive decidable_eq] meta inductive filter_type | none | no_instances | only_props /-- Filters a local constant using the given filter. -/ meta def filter_local : filter_type → expr → tactic bool | (filter_type.none) e := pure tt | (filter_type.no_instances) e := do t ← tactic.infer_type e, bnot <$> tactic.is_class t | (filter_type.only_props) e := do t ← tactic.infer_type e, tactic.is_prop t /-- Component for the filter dropdown. -/ meta def filter_component : component filter_type filter_type := component.stateless (λ lf, [ h "label" [] ["filter: "], select [ ⟨filter_type.none, "0", ["no filter"]⟩, ⟨filter_type.no_instances, "1", ["no instances"]⟩, ⟨filter_type.only_props, "2", ["only props"]⟩ ] lf ] ) /-- Converts a name into an html element. -/ meta def html.of_name {α : Type} : name → html α | n := html.of_string $ name.to_string n open tactic /-- Component that shows a type. -/ meta def show_type_component : tc expr empty := tc.stateless (λ x, do y ← infer_type x, y_comp ← interactive_expression.mk interactive_expression.type_tooltip $ y, pure y_comp ) /-- A group of local constants in the context that should be rendered as one line. -/ @[derive decidable_eq] meta structure local_collection := (key : string) (locals : list expr) (type : expr) (value : option expr) /-- Converts a single local constant into a (singleton) `local_collection` -/ meta def to_local_collection (l : expr) : tactic local_collection := tactic.unsafe.type_context.run $ do lctx ← tactic.unsafe.type_context.get_local_context, some ldecl ← pure $ lctx.get_local_decl l.local_uniq_name, pure { key := l.local_uniq_name.repr, locals := [l], type := ldecl.type, value := ldecl.value } /-- Groups consecutive local collections by type -/ meta def group_local_collection : list local_collection → list local_collection | (a :: b :: rest) := if a.type = b.type ∧ a.value = b.value then group_local_collection $ { locals := a.locals ++ b.locals, ..a } :: rest else a :: group_local_collection (b :: rest) | ls := ls /-- Component that displays the main (first) goal. -/ meta def tactic_view_goal {γ} (local_c : tc local_collection γ) (target_c : tc expr γ) : tc filter_type γ := tc.stateless $ λ ft, do g@(expr.mvar u_n pp_n y) ← main_goal, t ← get_tag g, let case_tag : list (html γ) := match interactive.case_tag.parse t with | some t := [h "li" [key "_case"] $ [h "span" [cn "goal-case b"] ["case"]] ++ (t.case_names.bind $ λ n, [" ", n])] | none := [] end, lcs ← local_context, lcs ← list.mfilter (filter_local ft) lcs, lcs ← lcs.mmap $ to_local_collection, let lcs := group_local_collection lcs, lchs ← lcs.mmap (λ lc, do lh ← local_c lc, let ns : list (html γ) := lc.locals.map $ λ n, h "span" [cn "goal-hyp b pr2", key n.local_uniq_name] [html.of_name n.local_pp_name], pure $ h "li" [key lc.key] (ns ++ [": ", h "span" [cn "goal-hyp-type", key "type"] [lh]])), t_comp ← target_c g, pure $ h "ul" [key g.hash, className "list pl0 font-code"] $ case_tag ++ lchs ++ [ h "li" [key u_n] [ h "span" [cn "goal-vdash b"] ["⊢ "], t_comp ]] /-- Actions accepted by the `tactic_view_component`. -/ meta inductive tactic_view_action (γ : Type) | out (a:γ): tactic_view_action | filter (f: filter_type): tactic_view_action /-- Component that displays all goals, together with the `$n goals` message. -/ meta def tactic_view_component {γ} (local_c : tc local_collection γ) (target_c : tc expr γ) : tc unit γ := tc.mk_simple (tactic_view_action γ) (filter_type) (λ _, pure $ filter_type.none) (λ ⟨⟩ ft a, match a with | (tactic_view_action.out a) := pure (ft, some a) | (tactic_view_action.filter ft) := pure (ft, none) end) (λ ⟨⟩ ft, do gs ← get_goals, hs ← gs.mmap (λ g, do set_goals [g], flip tc.to_html ft $ tactic_view_goal local_c target_c), set_goals gs, let goal_message : html γ := if gs.length = 0 then h "div" [cn "f5"] ["goals accomplished 🎉"] else if gs.length = 1 then "1 goal" else html.of_string $ to_string gs.length ++ " goals", let goal_message : html γ := h "strong" [cn "goal-goals"] [goal_message], let goals : html γ := h "ul" [className "list pl0"] $ list.map_with_index (λ i x, h "li" [className $ "lh-copy mt2", key i] [x]) $ (goal_message :: hs), pure [ h "div" [className "fr"] [html.of_component ft $ component.map_action tactic_view_action.filter filter_component], html.map_action tactic_view_action.out goals ]) /-- Component that displays the term-mode goal. -/ meta def tactic_view_term_goal {γ} (local_c : tc local_collection γ) (target_c : tc expr γ) : tc unit γ := tc.stateless $ λ _, do goal ← flip tc.to_html (filter_type.none) $ tactic_view_goal local_c target_c, pure [h "ul" [className "list pl0"] [ h "li" [className "lh-copy"] [h "strong" [cn "goal-goals"] ["expected type:"]], h "li" [className "lh-copy"] [goal]]] /-- Component showing a local collection. -/ meta def show_local_collection_component : tc local_collection empty := tc.stateless (λ lc, do (l::_) ← pure lc.locals, c ← show_type_component l, match lc.value with | some v := do v ← interactive_expression.mk interactive_expression.type_tooltip v, pure [c, " := ", v] | none := pure [c] end) /-- Renders the current tactic state. -/ meta def tactic_render : tc unit empty := component.ignore_action $ tactic_view_component show_local_collection_component show_type_component /-- Component showing the current tactic state. -/ meta def tactic_state_widget : component tactic_state empty := tc.to_component tactic_render /-- Widget used to display term-proof goals. -/ meta def term_goal_widget : component tactic_state empty := (tactic_view_term_goal show_local_collection_component show_type_component).to_component end widget_override attribute [vm_override widget_override.term_goal_widget] widget.term_goal_widget attribute [vm_override widget_override.tactic_state_widget] widget.tactic_state_widget
972e01ad8bc28cb8b432fd4722c80c77ac629fdb
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/diamond8.lean
790fbfe3edd6695fecaf73c2c0176e05f4b25d0b
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
720
lean
class One (M : Type u) where one : M instance {M} [One M] : OfNat M (nat_lit 1) := ⟨One.one⟩ class Zero (A : Type u) where zero : A instance {A} [Zero A] : OfNat A (nat_lit 0) := ⟨Zero.zero⟩ class Monoid (M : Type u) extends Mul M, One M where mul_one (m : M) : m * 1 = m class AddCommMonoid (A : Type u) extends Add A, Zero A class MonoidWithZero (M₀ : Type u) extends Monoid M₀, Zero M₀ class Semiring (R : Type u) extends AddCommMonoid R, MonoidWithZero R, One R #print Semiring -- only toMonoid field, no duplicate toOne def oneViaMonoid {M} [Monoid M] : M := 1 example {R} [Semiring R] : (1 : R) = oneViaMonoid := rfl example : Semiring Nat where mul_one := by simp zero := 0 one := 1
9cf8d83aef6589371aa3c7c4db3ccc9bc6c0f181
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/order/filter/basic.lean
cc91d9f50492ef08a4ee558bca51c677676d3be7
[ "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
117,677
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jeremy Avigad -/ import control.traversable.instances import data.set.finite import order.copy import tactic.monotonicity /-! # Theory of filters on sets ## Main definitions * `filter` : filters on a set; * `at_top`, `at_bot`, `cofinite`, `principal` : specific filters; * `map`, `comap`, `prod` : operations on filters; * `tendsto` : limit with respect to filters; * `eventually` : `f.eventually p` means `{x | p x} ∈ f`; * `frequently` : `f.frequently p` means `{x | ¬p x} ∉ f`; * `filter_upwards [h₁, ..., hₙ]` : takes a list of proofs `hᵢ : sᵢ ∈ f`, and replaces a goal `s ∈ f` with `∀ x, x ∈ s₁ → ... → x ∈ sₙ → x ∈ s`; * `ne_bot f` : an utility class stating that `f` is a non-trivial filter. Filters on a type `X` are sets of sets of `X` satisfying three conditions. They are mostly used to abstract two related kinds of ideas: * *limits*, including finite or infinite limits of sequences, finite or infinite limits of functions at a point or at infinity, etc... * *things happening eventually*, including things happening for large enough `n : ℕ`, or near enough a point `x`, or for close enough pairs of points, or things happening almost everywhere in the sense of measure theory. Dually, filters can also express the idea of *things happening often*: for arbitrarily large `n`, or at a point in any neighborhood of given a point etc... In this file, we define the type `filter X` of filters on `X`, and endow it with a complete lattice structure. This structure is lifted from the lattice structure on `set (set X)` using the Galois insertion which maps a filter to its elements in one direction, and an arbitrary set of sets to the smallest filter containing it in the other direction. We also prove `filter` is a monadic functor, with a push-forward operation `filter.map` and a pull-back operation `filter.comap` that form a Galois connections for the order on filters. Finally we describe a product operation `filter X → filter Y → filter (X × Y)`. The examples of filters appearing in the description of the two motivating ideas are: * `(at_top : filter ℕ)` : made of sets of `ℕ` containing `{n | n ≥ N}` for some `N` * `𝓝 x` : made of neighborhoods of `x` in a topological space (defined in topology.basic) * `𝓤 X` : made of entourages of a uniform space (those space are generalizations of metric spaces defined in topology.uniform_space.basic) * `μ.ae` : made of sets whose complement has zero measure with respect to `μ` (defined in `measure_theory.measure_space`) The general notion of limit of a map with respect to filters on the source and target types is `filter.tendsto`. It is defined in terms of the order and the push-forward operation. The predicate "happening eventually" is `filter.eventually`, and "happening often" is `filter.frequently`, whose definitions are immediate after `filter` is defined (but they come rather late in this file in order to immediately relate them to the lattice structure). For instance, anticipating on topology.basic, the statement: "if a sequence `u` converges to some `x` and `u n` belongs to a set `M` for `n` large enough then `x` is in the closure of `M`" is formalized as: `tendsto u at_top (𝓝 x) → (∀ᶠ n in at_top, u n ∈ M) → x ∈ closure M`, which is a special case of `mem_closure_of_tendsto` from topology.basic. ## Notations * `∀ᶠ x in f, p x` : `f.eventually p`; * `∃ᶠ x in f, p x` : `f.frequently p`; * `f =ᶠ[l] g` : `∀ᶠ x in l, f x = g x`; * `f ≤ᶠ[l] g` : `∀ᶠ x in l, f x ≤ g x`; * `f ×ᶠ g` : `filter.prod f g`, localized in `filter`; * `𝓟 s` : `principal s`, localized in `filter`. ## References * [N. Bourbaki, *General Topology*][bourbaki1966] Important note: Bourbaki requires that a filter on `X` cannot contain all sets of `X`, which we do *not* require. This gives `filter X` better formal properties, in particular a bottom element `⊥` for its lattice structure, at the cost of including the assumption `[ne_bot f]` in a number of lemmas and definitions. -/ open set function universes u v w x y open_locale classical /-- A filter `F` on a type `α` is a collection of sets of `α` which contains the whole `α`, is upwards-closed, and is stable under intersection. We do not forbid this collection to be all sets of `α`. -/ structure filter (α : Type*) := (sets : set (set α)) (univ_sets : set.univ ∈ sets) (sets_of_superset {x y} : x ∈ sets → x ⊆ y → y ∈ sets) (inter_sets {x y} : x ∈ sets → y ∈ sets → x ∩ y ∈ sets) /-- If `F` is a filter on `α`, and `U` a subset of `α` then we can write `U ∈ F` as on paper. -/ instance {α : Type*}: has_mem (set α) (filter α) := ⟨λ U F, U ∈ F.sets⟩ namespace filter variables {α : Type u} {f g : filter α} {s t : set α} @[simp] protected lemma mem_mk {t : set (set α)} {h₁ h₂ h₃} : s ∈ mk t h₁ h₂ h₃ ↔ s ∈ t := iff.rfl @[simp] protected lemma mem_sets : s ∈ f.sets ↔ s ∈ f := iff.rfl instance inhabited_mem : inhabited {s : set α // s ∈ f} := ⟨⟨univ, f.univ_sets⟩⟩ lemma filter_eq : ∀ {f g : filter α}, f.sets = g.sets → f = g | ⟨a, _, _, _⟩ ⟨._, _, _, _⟩ rfl := rfl lemma filter_eq_iff : f = g ↔ f.sets = g.sets := ⟨congr_arg _, filter_eq⟩ protected lemma ext_iff : f = g ↔ ∀ s, s ∈ f ↔ s ∈ g := by simp only [filter_eq_iff, ext_iff, filter.mem_sets] @[ext] protected lemma ext : (∀ s, s ∈ f ↔ s ∈ g) → f = g := filter.ext_iff.2 @[simp] lemma univ_mem : univ ∈ f := f.univ_sets lemma mem_of_superset {x y : set α} (hx : x ∈ f) (hxy : x ⊆ y) : y ∈ f := f.sets_of_superset hx hxy lemma inter_mem {s t : set α} (hs : s ∈ f) (ht : t ∈ f) : s ∩ t ∈ f := f.inter_sets hs ht @[simp] lemma inter_mem_iff {s t : set α} : s ∩ t ∈ f ↔ s ∈ f ∧ t ∈ f := ⟨λ h, ⟨mem_of_superset h (inter_subset_left s t), mem_of_superset h (inter_subset_right s t)⟩, and_imp.2 inter_mem⟩ lemma diff_mem {s t : set α} (hs : s ∈ f) (ht : tᶜ ∈ f) : s \ t ∈ f := inter_mem hs ht lemma univ_mem' (h : ∀ a, a ∈ s) : s ∈ f := mem_of_superset univ_mem (λ x _, h x) lemma mp_mem (hs : s ∈ f) (h : {x | x ∈ s → x ∈ t} ∈ f) : t ∈ f := mem_of_superset (inter_mem hs h) $ λ x ⟨h₁, h₂⟩, h₂ h₁ lemma congr_sets (h : {x | x ∈ s ↔ x ∈ t} ∈ f) : s ∈ f ↔ t ∈ f := ⟨λ hs, mp_mem hs (mem_of_superset h (λ x, iff.mp)), λ hs, mp_mem hs (mem_of_superset h (λ x, iff.mpr))⟩ @[simp] lemma bInter_mem {β : Type v} {s : β → set α} {is : set β} (hf : finite is) : (⋂ i ∈ is, s i) ∈ f ↔ ∀ i ∈ is, s i ∈ f := finite.induction_on hf (by simp) (λ i s hi _ hs, by simp [hs]) @[simp] lemma bInter_finset_mem {β : Type v} {s : β → set α} (is : finset β) : (⋂ i ∈ is, s i) ∈ f ↔ ∀ i ∈ is, s i ∈ f := bInter_mem is.finite_to_set alias bInter_finset_mem ← finset.Inter_mem_sets attribute [protected] finset.Inter_mem_sets @[simp] lemma sInter_mem {s : set (set α)} (hfin : finite s) : ⋂₀ s ∈ f ↔ ∀ U ∈ s, U ∈ f := by rw [sInter_eq_bInter, bInter_mem hfin] @[simp] lemma Inter_mem {β : Type v} {s : β → set α} [fintype β] : (⋂ i, s i) ∈ f ↔ ∀ i, s i ∈ f := by simpa using bInter_mem finite_univ lemma exists_mem_subset_iff : (∃ t ∈ f, t ⊆ s) ↔ s ∈ f := ⟨λ ⟨t, ht, ts⟩, mem_of_superset ht ts, λ hs, ⟨s, hs, subset.rfl⟩⟩ lemma monotone_mem {f : filter α} : monotone (λ s, s ∈ f) := λ s t hst h, mem_of_superset h hst end filter namespace tactic.interactive open tactic setup_tactic_parser /-- `filter_upwards [h₁, ⋯, hₙ]` replaces a goal of the form `s ∈ f` and terms `h₁ : t₁ ∈ f, ⋯, hₙ : tₙ ∈ f` with `∀ x, x ∈ t₁ → ⋯ → x ∈ tₙ → x ∈ s`. The list is an optional parameter, `[]` being its default value. `filter_upwards [h₁, ⋯, hₙ] with a₁ a₂ ⋯ aₖ` is a short form for `{ filter_upwards [h₁, ⋯, hₙ], intros a₁ a₂ ⋯ aₖ }`. `filter_upwards [h₁, ⋯, hₙ] using e` is a short form for `{ filter_upwards [h1, ⋯, hn], exact e }`. Combining both shortcuts is done by writing `filter_upwards [h₁, ⋯, hₙ] with a₁ a₂ ⋯ aₖ using e`. Note that in this case, the `aᵢ` terms can be used in `e`. -/ meta def filter_upwards (s : parse types.pexpr_list?) (wth : parse with_ident_list?) (tgt : parse (tk "using" *> texpr)?) : tactic unit := do (s.get_or_else []).reverse.mmap (λ e, eapplyc `filter.mp_mem >> eapply e), eapplyc `filter.univ_mem', `[dsimp only [set.mem_set_of_eq]], let wth := wth.get_or_else [], if ¬wth.empty then intros wth else skip, match tgt with | some e := exact e | none := skip end add_tactic_doc { name := "filter_upwards", category := doc_category.tactic, decl_names := [`tactic.interactive.filter_upwards], tags := ["goal management", "lemma application"] } end tactic.interactive namespace filter variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} section principal /-- The principal filter of `s` is the collection of all supersets of `s`. -/ def principal (s : set α) : filter α := { sets := {t | s ⊆ t}, univ_sets := subset_univ s, sets_of_superset := λ x y hx, subset.trans hx, inter_sets := λ x y, subset_inter } localized "notation `𝓟` := filter.principal" in filter instance : inhabited (filter α) := ⟨𝓟 ∅⟩ @[simp] lemma mem_principal {s t : set α} : s ∈ 𝓟 t ↔ t ⊆ s := iff.rfl lemma mem_principal_self (s : set α) : s ∈ 𝓟 s := subset.rfl end principal open_locale filter section join /-- The join of a filter of filters is defined by the relation `s ∈ join f ↔ {t | s ∈ t} ∈ f`. -/ def join (f : filter (filter α)) : filter α := { sets := {s | {t : filter α | s ∈ t} ∈ f}, univ_sets := by simp only [mem_set_of_eq, univ_sets, ← filter.mem_sets, set_of_true], sets_of_superset := λ x y hx xy, mem_of_superset hx $ λ f h, mem_of_superset h xy, inter_sets := λ x y hx hy, mem_of_superset (inter_mem hx hy) $ λ f ⟨h₁, h₂⟩, inter_mem h₁ h₂ } @[simp] lemma mem_join {s : set α} {f : filter (filter α)} : s ∈ join f ↔ {t | s ∈ t} ∈ f := iff.rfl end join section lattice instance : partial_order (filter α) := { le := λ f g, ∀ ⦃U : set α⦄, U ∈ g → U ∈ f, le_antisymm := λ a b h₁ h₂, filter_eq $ subset.antisymm h₂ h₁, le_refl := λ a, subset.rfl, le_trans := λ a b c h₁ h₂, subset.trans h₂ h₁ } theorem le_def {f g : filter α} : f ≤ g ↔ ∀ x ∈ g, x ∈ f := iff.rfl /-- `generate_sets g s`: `s` is in the filter closure of `g`. -/ inductive generate_sets (g : set (set α)) : set α → Prop | basic {s : set α} : s ∈ g → generate_sets s | univ : generate_sets univ | superset {s t : set α} : generate_sets s → s ⊆ t → generate_sets t | inter {s t : set α} : generate_sets s → generate_sets t → generate_sets (s ∩ t) /-- `generate g` is the smallest filter containing the sets `g`. -/ def generate (g : set (set α)) : filter α := { sets := generate_sets g, univ_sets := generate_sets.univ, sets_of_superset := λ x y, generate_sets.superset, inter_sets := λ s t, generate_sets.inter } lemma sets_iff_generate {s : set (set α)} {f : filter α} : f ≤ filter.generate s ↔ s ⊆ f.sets := iff.intro (λ h u hu, h $ generate_sets.basic $ hu) (λ h u hu, hu.rec_on h univ_mem (λ x y _ hxy hx, mem_of_superset hx hxy) (λ x y _ _ hx hy, inter_mem hx hy)) lemma mem_generate_iff {s : set $ set α} {U : set α} : U ∈ generate s ↔ ∃ t ⊆ s, finite t ∧ ⋂₀ t ⊆ U := begin split ; intro h, { induction h with V V_in V W V_in hVW hV V W V_in W_in hV hW, { use {V}, simp [V_in] }, { use ∅, simp [subset.refl, univ] }, { rcases hV with ⟨t, hts, htfin, hinter⟩, exact ⟨t, hts, htfin, hinter.trans hVW⟩ }, { rcases hV with ⟨t, hts, htfin, htinter⟩, rcases hW with ⟨z, hzs, hzfin, hzinter⟩, refine ⟨t ∪ z, union_subset hts hzs, htfin.union hzfin, _⟩, rw sInter_union, exact inter_subset_inter htinter hzinter } }, { rcases h with ⟨t, ts, tfin, h⟩, apply generate_sets.superset _ h, revert ts, apply finite.induction_on tfin, { intro h, rw sInter_empty, exact generate_sets.univ }, { intros V r hV rfin hinter h, cases insert_subset.mp h with V_in r_sub, rw [insert_eq V r, sInter_union], apply generate_sets.inter _ (hinter r_sub), rw sInter_singleton, exact generate_sets.basic V_in } }, end /-- `mk_of_closure s hs` constructs a filter on `α` whose elements set is exactly `s : set (set α)`, provided one gives the assumption `hs : (generate s).sets = s`. -/ protected def mk_of_closure (s : set (set α)) (hs : (generate s).sets = s) : filter α := { sets := s, univ_sets := hs ▸ (univ_mem : univ ∈ generate s), sets_of_superset := λ x y, hs ▸ (mem_of_superset : x ∈ generate s → x ⊆ y → y ∈ generate s), inter_sets := λ x y, hs ▸ (inter_mem : x ∈ generate s → y ∈ generate s → x ∩ y ∈ generate s) } lemma mk_of_closure_sets {s : set (set α)} {hs : (generate s).sets = s} : filter.mk_of_closure s hs = generate s := filter.ext $ λ u, show u ∈ (filter.mk_of_closure s hs).sets ↔ u ∈ (generate s).sets, from hs.symm ▸ iff.rfl /-- Galois insertion from sets of sets into filters. -/ def gi_generate (α : Type*) : @galois_insertion (set (set α)) (order_dual (filter α)) _ _ filter.generate filter.sets := { gc := λ s f, sets_iff_generate, le_l_u := λ f u h, generate_sets.basic h, choice := λ s hs, filter.mk_of_closure s (le_antisymm hs $ sets_iff_generate.1 $ le_rfl), choice_eq := λ s hs, mk_of_closure_sets } /-- The infimum of filters is the filter generated by intersections of elements of the two filters. -/ instance : has_inf (filter α) := ⟨λf g : filter α, { sets := {s | ∃ (a ∈ f) (b ∈ g), s = a ∩ b }, univ_sets := ⟨_, univ_mem, _, univ_mem, by simp⟩, sets_of_superset := begin rintro x y ⟨a, ha, b, hb, rfl⟩ xy, refine ⟨a ∪ y, mem_of_superset ha (subset_union_left a y), b ∪ y, mem_of_superset hb (subset_union_left b y), _⟩, rw [← inter_union_distrib_right, union_eq_self_of_subset_left xy] end, inter_sets := begin rintro x y ⟨a, ha, b, hb, rfl⟩ ⟨c, hc, d, hd, rfl⟩, refine ⟨a ∩ c, inter_mem ha hc, b ∩ d, inter_mem hb hd, _⟩, ac_refl end }⟩ lemma mem_inf_iff {f g : filter α} {s : set α} : s ∈ f ⊓ g ↔ ∃ t₁ ∈ f, ∃ t₂ ∈ g, s = t₁ ∩ t₂ := iff.rfl lemma mem_inf_of_left {f g : filter α} {s : set α} (h : s ∈ f) : s ∈ f ⊓ g := ⟨s, h, univ, univ_mem, (inter_univ s).symm⟩ lemma mem_inf_of_right {f g : filter α} {s : set α} (h : s ∈ g) : s ∈ f ⊓ g := ⟨univ, univ_mem, s, h, (univ_inter s).symm⟩ lemma inter_mem_inf {α : Type u} {f g : filter α} {s t : set α} (hs : s ∈ f) (ht : t ∈ g) : s ∩ t ∈ f ⊓ g := ⟨s, hs, t, ht, rfl⟩ lemma mem_inf_of_inter {f g : filter α} {s t u : set α} (hs : s ∈ f) (ht : t ∈ g) (h : s ∩ t ⊆ u) : u ∈ f ⊓ g := mem_of_superset (inter_mem_inf hs ht) h lemma mem_inf_iff_superset {f g : filter α} {s : set α} : s ∈ f ⊓ g ↔ ∃ t₁ ∈ f, ∃ t₂ ∈ g, t₁ ∩ t₂ ⊆ s := ⟨λ ⟨t₁, h₁, t₂, h₂, eq⟩, ⟨t₁, h₁, t₂, h₂, eq ▸ subset.rfl⟩, λ ⟨t₁, h₁, t₂, h₂, sub⟩, mem_inf_of_inter h₁ h₂ sub⟩ instance : has_top (filter α) := ⟨{ sets := {s | ∀ x, x ∈ s}, univ_sets := λ x, mem_univ x, sets_of_superset := λ x y hx hxy a, hxy (hx a), inter_sets := λ x y hx hy a, mem_inter (hx _) (hy _) }⟩ lemma mem_top_iff_forall {s : set α} : s ∈ (⊤ : filter α) ↔ (∀ x, x ∈ s) := iff.rfl @[simp] lemma mem_top {s : set α} : s ∈ (⊤ : filter α) ↔ s = univ := by rw [mem_top_iff_forall, eq_univ_iff_forall] section complete_lattice /- We lift the complete lattice along the Galois connection `generate` / `sets`. Unfortunately, we want to have different definitional equalities for the lattice operations. So we define them upfront and change the lattice operations for the complete lattice instance. -/ private def original_complete_lattice : complete_lattice (filter α) := @order_dual.complete_lattice _ (gi_generate α).lift_complete_lattice local attribute [instance] original_complete_lattice instance : complete_lattice (filter α) := original_complete_lattice.copy /- le -/ filter.partial_order.le rfl /- top -/ (filter.has_top).1 (top_unique $ λ s hs, by simp [mem_top.1 hs]) /- bot -/ _ rfl /- sup -/ _ rfl /- inf -/ (filter.has_inf).1 begin ext f g : 2, exact le_antisymm (le_inf (λ s, mem_inf_of_left) (λ s, mem_inf_of_right)) (begin rintro s ⟨a, ha, b, hb, rfl⟩, exact inter_sets _ (@inf_le_left (filter α) _ _ _ _ ha) (@inf_le_right (filter α) _ _ _ _ hb) end) end /- Sup -/ (join ∘ 𝓟) (by { ext s x, exact mem_Inter₂.symm.trans (set.ext_iff.1 (sInter_image _ _) x).symm}) /- Inf -/ _ rfl end complete_lattice /-- A filter is `ne_bot` if it is not equal to `⊥`, or equivalently the empty set does not belong to the filter. Bourbaki include this assumption in the definition of a filter but we prefer to have a `complete_lattice` structure on filter, so we use a typeclass argument in lemmas instead. -/ class ne_bot (f : filter α) : Prop := (ne' : f ≠ ⊥) lemma ne_bot_iff {f : filter α} : ne_bot f ↔ f ≠ ⊥ := ⟨λ h, h.1, λ h, ⟨h⟩⟩ lemma ne_bot.ne {f : filter α} (hf : ne_bot f) : f ≠ ⊥ := ne_bot.ne' @[simp] lemma not_ne_bot {α : Type*} {f : filter α} : ¬ f.ne_bot ↔ f = ⊥ := not_iff_comm.1 ne_bot_iff.symm lemma ne_bot.mono {f g : filter α} (hf : ne_bot f) (hg : f ≤ g) : ne_bot g := ⟨ne_bot_of_le_ne_bot hf.1 hg⟩ lemma ne_bot_of_le {f g : filter α} [hf : ne_bot f] (hg : f ≤ g) : ne_bot g := hf.mono hg @[simp] lemma sup_ne_bot {f g : filter α} : ne_bot (f ⊔ g) ↔ ne_bot f ∨ ne_bot g := by simp [ne_bot_iff, not_and_distrib] lemma bot_sets_eq : (⊥ : filter α).sets = univ := rfl lemma sup_sets_eq {f g : filter α} : (f ⊔ g).sets = f.sets ∩ g.sets := (gi_generate α).gc.u_inf lemma Sup_sets_eq {s : set (filter α)} : (Sup s).sets = (⋂ f ∈ s, (f : filter α).sets) := (gi_generate α).gc.u_Inf lemma supr_sets_eq {f : ι → filter α} : (supr f).sets = (⋂ i, (f i).sets) := (gi_generate α).gc.u_infi lemma generate_empty : filter.generate ∅ = (⊤ : filter α) := (gi_generate α).gc.l_bot lemma generate_univ : filter.generate univ = (⊥ : filter α) := mk_of_closure_sets.symm lemma generate_union {s t : set (set α)} : filter.generate (s ∪ t) = filter.generate s ⊓ filter.generate t := (gi_generate α).gc.l_sup lemma generate_Union {s : ι → set (set α)} : filter.generate (⋃ i, s i) = (⨅ i, filter.generate (s i)) := (gi_generate α).gc.l_supr @[simp] lemma mem_bot {s : set α} : s ∈ (⊥ : filter α) := trivial @[simp] lemma mem_sup {f g : filter α} {s : set α} : s ∈ f ⊔ g ↔ s ∈ f ∧ s ∈ g := iff.rfl lemma union_mem_sup {f g : filter α} {s t : set α} (hs : s ∈ f) (ht : t ∈ g) : s ∪ t ∈ f ⊔ g := ⟨mem_of_superset hs (subset_union_left s t), mem_of_superset ht (subset_union_right s t)⟩ @[simp] lemma mem_Sup {x : set α} {s : set (filter α)} : x ∈ Sup s ↔ (∀ f ∈ s, x ∈ (f : filter α)) := iff.rfl @[simp] lemma mem_supr {x : set α} {f : ι → filter α} : x ∈ supr f ↔ (∀ i, x ∈ f i) := by simp only [← filter.mem_sets, supr_sets_eq, iff_self, mem_Inter] @[simp] lemma supr_ne_bot {f : ι → filter α} : (⨆ i, f i).ne_bot ↔ ∃ i, (f i).ne_bot := by simp [ne_bot_iff] lemma infi_eq_generate (s : ι → filter α) : infi s = generate (⋃ i, (s i).sets) := show generate _ = generate _, from congr_arg _ $ congr_arg Sup $ (range_comp _ _).symm lemma mem_infi_of_mem {f : ι → filter α} (i : ι) : ∀ {s}, s ∈ f i → s ∈ ⨅ i, f i := show (⨅ i, f i) ≤ f i, from infi_le _ _ lemma mem_infi_of_Inter {ι} {s : ι → filter α} {U : set α} {I : set ι} (I_fin : finite I) {V : I → set α} (hV : ∀ i, V i ∈ s i) (hU : (⋂ i, V i) ⊆ U) : U ∈ ⨅ i, s i := begin haveI := I_fin.fintype, refine mem_of_superset (Inter_mem.2 $ λ i, _) hU, exact mem_infi_of_mem i (hV _) end lemma mem_infi {ι} {s : ι → filter α} {U : set α} : (U ∈ ⨅ i, s i) ↔ ∃ I : set ι, finite I ∧ ∃ V : I → set α, (∀ i, V i ∈ s i) ∧ U = ⋂ i, V i := begin split, { rw [infi_eq_generate, mem_generate_iff], rintro ⟨t, tsub, tfin, tinter⟩, rcases eq_finite_Union_of_finite_subset_Union tfin tsub with ⟨I, Ifin, σ, σfin, σsub, rfl⟩, rw sInter_Union at tinter, set V := λ i, U ∪ ⋂₀ σ i with hV, have V_in : ∀ i, V i ∈ s i, { rintro i, have : (⋂₀ σ i) ∈ s i, { rw sInter_mem (σfin _), apply σsub }, exact mem_of_superset this (subset_union_right _ _) }, refine ⟨I, Ifin, V, V_in, _⟩, rwa [hV, ← union_Inter, union_eq_self_of_subset_right] }, { rintro ⟨I, Ifin, V, V_in, rfl⟩, exact mem_infi_of_Inter Ifin V_in subset.rfl } end lemma mem_infi' {ι} {s : ι → filter α} {U : set α} : (U ∈ ⨅ i, s i) ↔ ∃ I : set ι, finite I ∧ ∃ V : ι → set α, (∀ i, V i ∈ s i) ∧ (∀ i ∉ I, V i = univ) ∧ (U = ⋂ i ∈ I, V i) ∧ U = ⋂ i, V i := begin simp only [mem_infi, set_coe.forall', bInter_eq_Inter], refine ⟨_, λ ⟨I, If, V, hVs, _, hVU, _⟩, ⟨I, If, λ i, V i, λ i, hVs i, hVU⟩⟩, rintro ⟨I, If, V, hV, rfl⟩, refine ⟨I, If, λ i, if hi : i ∈ I then V ⟨i, hi⟩ else univ, λ i, _, λ i hi, _, _⟩, { split_ifs, exacts [hV _, univ_mem] }, { exact dif_neg hi }, { simp only [Inter_dite, bInter_eq_Inter, dif_pos (subtype.coe_prop _), subtype.coe_eta, Inter_univ, inter_univ, eq_self_iff_true, true_and] } end lemma exists_Inter_of_mem_infi {ι : Type*} {α : Type*} {f : ι → filter α} {s} (hs : s ∈ ⨅ i, f i) : ∃ t : ι → set α, (∀ i, t i ∈ f i) ∧ s = ⋂ i, t i := let ⟨I, If, V, hVs, hV', hVU, hVU'⟩ := mem_infi'.1 hs in ⟨V, hVs, hVU'⟩ lemma mem_infi_of_fintype {ι : Type*} [fintype ι] {α : Type*} {f : ι → filter α} (s) : s ∈ (⨅ i, f i) ↔ ∃ t : ι → set α, (∀ i, t i ∈ f i) ∧ s = ⋂ i, t i := begin refine ⟨exists_Inter_of_mem_infi, _⟩, rintro ⟨t, ht, rfl⟩, exact Inter_mem.2 (λ i, mem_infi_of_mem i (ht i)) end @[simp] lemma le_principal_iff {s : set α} {f : filter α} : f ≤ 𝓟 s ↔ s ∈ f := show (∀ {t}, s ⊆ t → t ∈ f) ↔ s ∈ f, from ⟨λ h, h (subset.refl s), λ hs t ht, mem_of_superset hs ht⟩ lemma principal_mono {s t : set α} : 𝓟 s ≤ 𝓟 t ↔ s ⊆ t := by simp only [le_principal_iff, iff_self, mem_principal] @[mono] lemma monotone_principal : monotone (𝓟 : set α → filter α) := λ _ _, principal_mono.2 @[simp] lemma principal_eq_iff_eq {s t : set α} : 𝓟 s = 𝓟 t ↔ s = t := by simp only [le_antisymm_iff, le_principal_iff, mem_principal]; refl @[simp] lemma join_principal_eq_Sup {s : set (filter α)} : join (𝓟 s) = Sup s := rfl @[simp] lemma principal_univ : 𝓟 (univ : set α) = ⊤ := top_unique $ by simp only [le_principal_iff, mem_top, eq_self_iff_true] @[simp] lemma principal_empty : 𝓟 (∅ : set α) = ⊥ := bot_unique $ λ s _, empty_subset _ lemma generate_eq_binfi (S : set (set α)) : generate S = ⨅ s ∈ S, 𝓟 s := eq_of_forall_le_iff $ λ f, by simp [sets_iff_generate, le_principal_iff, subset_def] /-! ### Lattice equations -/ lemma empty_mem_iff_bot {f : filter α} : ∅ ∈ f ↔ f = ⊥ := ⟨λ h, bot_unique $ λ s _, mem_of_superset h (empty_subset s), λ h, h.symm ▸ mem_bot⟩ lemma nonempty_of_mem {f : filter α} [hf : ne_bot f] {s : set α} (hs : s ∈ f) : s.nonempty := s.eq_empty_or_nonempty.elim (λ h, absurd hs (h.symm ▸ mt empty_mem_iff_bot.mp hf.1)) id lemma ne_bot.nonempty_of_mem {f : filter α} (hf : ne_bot f) {s : set α} (hs : s ∈ f) : s.nonempty := @nonempty_of_mem α f hf s hs @[simp] lemma empty_not_mem (f : filter α) [ne_bot f] : ¬(∅ ∈ f) := λ h, (nonempty_of_mem h).ne_empty rfl lemma nonempty_of_ne_bot (f : filter α) [ne_bot f] : nonempty α := nonempty_of_exists $ nonempty_of_mem (univ_mem : univ ∈ f) lemma compl_not_mem {f : filter α} {s : set α} [ne_bot f] (h : s ∈ f) : sᶜ ∉ f := λ hsc, (nonempty_of_mem (inter_mem h hsc)).ne_empty $ inter_compl_self s lemma filter_eq_bot_of_is_empty [is_empty α] (f : filter α) : f = ⊥ := empty_mem_iff_bot.mp $ univ_mem' is_empty_elim protected lemma disjoint_iff {f g : filter α} : disjoint f g ↔ ∃ (s ∈ f) (t ∈ g), disjoint s t := by simp only [disjoint_iff, ← empty_mem_iff_bot, mem_inf_iff, inf_eq_inter, bot_eq_empty, @eq_comm _ ∅] lemma disjoint_of_disjoint_of_mem {f g : filter α} {s t : set α} (h : disjoint s t) (hs : s ∈ f) (ht : t ∈ g) : disjoint f g := filter.disjoint_iff.mpr ⟨s, hs, t, ht, h⟩ lemma inf_eq_bot_iff {f g : filter α} : f ⊓ g = ⊥ ↔ ∃ (U ∈ f) (V ∈ g), U ∩ V = ∅ := by simpa only [disjoint_iff] using filter.disjoint_iff /-- There is exactly one filter on an empty type. --/ -- TODO[gh-6025]: make this globally an instance once safe to do so local attribute [instance] protected def unique [is_empty α] : unique (filter α) := { default := ⊥, uniq := filter_eq_bot_of_is_empty } lemma forall_mem_nonempty_iff_ne_bot {f : filter α} : (∀ (s : set α), s ∈ f → s.nonempty) ↔ ne_bot f := ⟨λ h, ⟨λ hf, empty_not_nonempty (h ∅ $ hf.symm ▸ mem_bot)⟩, @nonempty_of_mem _ _⟩ lemma nontrivial_iff_nonempty : nontrivial (filter α) ↔ nonempty α := ⟨λ ⟨⟨f, g, hfg⟩⟩, by_contra $ λ h, hfg $ by haveI : is_empty α := not_nonempty_iff.1 h; exact subsingleton.elim _ _, λ ⟨x⟩, ⟨⟨⊤, ⊥, ne_bot.ne $ forall_mem_nonempty_iff_ne_bot.1 $ λ s hs, by rwa [mem_top.1 hs, ← nonempty_iff_univ_nonempty]⟩⟩⟩ lemma eq_Inf_of_mem_iff_exists_mem {S : set (filter α)} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ f ∈ S, s ∈ f) : l = Inf S := le_antisymm (le_Inf $ λ f hf s hs, h.2 ⟨f, hf, hs⟩) (λ s hs, let ⟨f, hf, hs⟩ := h.1 hs in (Inf_le hf : Inf S ≤ f) hs) lemma eq_infi_of_mem_iff_exists_mem {f : ι → filter α} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ i, s ∈ f i) : l = infi f := eq_Inf_of_mem_iff_exists_mem $ λ s, h.trans exists_range_iff.symm lemma eq_binfi_of_mem_iff_exists_mem {f : ι → filter α} {p : ι → Prop} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ i (_ : p i), s ∈ f i) : l = ⨅ i (_ : p i), f i := begin rw [infi_subtype'], apply eq_infi_of_mem_iff_exists_mem, intro s, exact h.trans ⟨λ ⟨i, pi, si⟩, ⟨⟨i, pi⟩, si⟩, λ ⟨⟨i, pi⟩, si⟩, ⟨i, pi, si⟩⟩ end lemma infi_sets_eq {f : ι → filter α} (h : directed (≥) f) [ne : nonempty ι] : (infi f).sets = (⋃ i, (f i).sets) := let ⟨i⟩ := ne, u := { filter . sets := (⋃ i, (f i).sets), univ_sets := by simp only [mem_Union]; exact ⟨i, univ_mem⟩, sets_of_superset := by simp only [mem_Union, exists_imp_distrib]; intros x y i hx hxy; exact ⟨i, mem_of_superset hx hxy⟩, inter_sets := begin simp only [mem_Union, exists_imp_distrib], intros x y a hx b hy, rcases h a b with ⟨c, ha, hb⟩, exact ⟨c, inter_mem (ha hx) (hb hy)⟩ end } in have u = infi f, from eq_infi_of_mem_iff_exists_mem (λ s, by simp only [filter.mem_mk, mem_Union, filter.mem_sets]), congr_arg filter.sets this.symm lemma mem_infi_of_directed {f : ι → filter α} (h : directed (≥) f) [nonempty ι] (s) : s ∈ infi f ↔ ∃ i, s ∈ f i := by simp only [← filter.mem_sets, infi_sets_eq h, mem_Union] lemma mem_binfi_of_directed {f : β → filter α} {s : set β} (h : directed_on (f ⁻¹'o (≥)) s) (ne : s.nonempty) {t : set α} : t ∈ (⨅ i ∈ s, f i) ↔ ∃ i ∈ s, t ∈ f i := by haveI : nonempty {x // x ∈ s} := ne.to_subtype; erw [infi_subtype', mem_infi_of_directed h.directed_coe, subtype.exists]; refl lemma binfi_sets_eq {f : β → filter α} {s : set β} (h : directed_on (f ⁻¹'o (≥)) s) (ne : s.nonempty) : (⨅ i ∈ s, f i).sets = ⋃ i ∈ s, (f i).sets := ext $ λ t, by simp [mem_binfi_of_directed h ne] lemma infi_sets_eq_finite {ι : Type*} (f : ι → filter α) : (⨅ i, f i).sets = (⋃ t : finset ι, (⨅ i ∈ t, f i).sets) := begin rw [infi_eq_infi_finset, infi_sets_eq], exact (directed_of_sup $ λ s₁ s₂ hs, infi_le_infi $ λ i, infi_le_infi_const $ λ h, hs h), end lemma infi_sets_eq_finite' (f : ι → filter α) : (⨅ i, f i).sets = (⋃ t : finset (plift ι), (⨅ i ∈ t, f (plift.down i)).sets) := by { rw [← infi_sets_eq_finite, ← equiv.plift.surjective.infi_comp], refl } lemma mem_infi_finite {ι : Type*} {f : ι → filter α} (s) : s ∈ infi f ↔ ∃ t : finset ι, s ∈ ⨅ i ∈ t, f i := (set.ext_iff.1 (infi_sets_eq_finite f) s).trans mem_Union lemma mem_infi_finite' {f : ι → filter α} (s) : s ∈ infi f ↔ ∃ t : finset (plift ι), s ∈ ⨅ i ∈ t, f (plift.down i) := (set.ext_iff.1 (infi_sets_eq_finite' f) s).trans mem_Union @[simp] lemma sup_join {f₁ f₂ : filter (filter α)} : (join f₁ ⊔ join f₂) = join (f₁ ⊔ f₂) := filter.ext $ λ x, by simp only [mem_sup, mem_join] @[simp] lemma supr_join {ι : Sort w} {f : ι → filter (filter α)} : (⨆ x, join (f x)) = join (⨆ x, f x) := filter.ext $ λ x, by simp only [mem_supr, mem_join] instance : distrib_lattice (filter α) := { le_sup_inf := begin intros x y z s, simp only [and_assoc, mem_inf_iff, mem_sup, exists_prop, exists_imp_distrib, and_imp], rintro hs t₁ ht₁ t₂ ht₂ rfl, exact ⟨t₁, x.sets_of_superset hs (inter_subset_left t₁ t₂), ht₁, t₂, x.sets_of_superset hs (inter_subset_right t₁ t₂), ht₂, rfl⟩ end, ..filter.complete_lattice } /- the complementary version with ⨆ i, f ⊓ g i does not hold! -/ lemma infi_sup_left {f : filter α} {g : ι → filter α} : (⨅ x, f ⊔ g x) = f ⊔ infi g := begin refine le_antisymm _ (le_infi $ λ i, sup_le_sup_left (infi_le _ _) _), rintro t ⟨h₁, h₂⟩, rw [infi_sets_eq_finite'] at h₂, simp only [mem_Union, (finset.inf_eq_infi _ _).symm] at h₂, rcases h₂ with ⟨s, hs⟩, suffices : (⨅ i, f ⊔ g i) ≤ f ⊔ s.inf (λ i, g i.down), { exact this ⟨h₁, hs⟩ }, refine finset.induction_on s _ _, { exact le_sup_of_le_right le_top }, { rintro ⟨i⟩ s his ih, rw [finset.inf_insert, sup_inf_left], exact le_inf (infi_le _ _) ih } end lemma infi_sup_right {f : filter α} {g : ι → filter α} : (⨅ x, g x ⊔ f) = infi g ⊔ f := by simp [sup_comm, ← infi_sup_left] lemma binfi_sup_right (p : ι → Prop) (f : ι → filter α) (g : filter α) : (⨅ i (h : p i), (f i ⊔ g)) = (⨅ i (h : p i), f i) ⊔ g := by rw [infi_subtype', infi_sup_right, infi_subtype'] lemma binfi_sup_left (p : ι → Prop) (f : ι → filter α) (g : filter α) : (⨅ i (h : p i), (g ⊔ f i)) = g ⊔ (⨅ i (h : p i), f i) := by rw [infi_subtype', infi_sup_left, infi_subtype'] lemma mem_infi_finset {s : finset α} {f : α → filter β} {t : set β} : t ∈ (⨅ a ∈ s, f a) ↔ (∃ p : α → set β, (∀ a ∈ s, p a ∈ f a) ∧ t = ⋂ a ∈ s, p a) := begin simp only [← finset.set_bInter_coe, bInter_eq_Inter, infi_subtype'], refine ⟨λ h, _, _⟩, { rcases (mem_infi_of_fintype _).1 h with ⟨p, hp, rfl⟩, refine ⟨λ a, if h : a ∈ s then p ⟨a, h⟩ else univ, λ a ha, by simpa [ha] using hp ⟨a, ha⟩, _⟩, refine Inter_congr_of_surjective id surjective_id _, rintro ⟨a, ha⟩, simp [ha] }, { rintro ⟨p, hpf, rfl⟩, exact Inter_mem.2 (λ a, mem_infi_of_mem a (hpf a a.2)) } end /-- If `f : ι → filter α` is directed, `ι` is not empty, and `∀ i, f i ≠ ⊥`, then `infi f ≠ ⊥`. See also `infi_ne_bot_of_directed` for a version assuming `nonempty α` instead of `nonempty ι`. -/ lemma infi_ne_bot_of_directed' {f : ι → filter α} [nonempty ι] (hd : directed (≥) f) (hb : ∀ i, ne_bot (f i)) : ne_bot (infi f) := ⟨begin intro h, have he : ∅ ∈ (infi f), from h.symm ▸ (mem_bot : ∅ ∈ (⊥ : filter α)), obtain ⟨i, hi⟩ : ∃ i, ∅ ∈ f i, from (mem_infi_of_directed hd ∅).1 he, exact (hb i).ne (empty_mem_iff_bot.1 hi) end⟩ /-- If `f : ι → filter α` is directed, `α` is not empty, and `∀ i, f i ≠ ⊥`, then `infi f ≠ ⊥`. See also `infi_ne_bot_of_directed'` for a version assuming `nonempty ι` instead of `nonempty α`. -/ lemma infi_ne_bot_of_directed {f : ι → filter α} [hn : nonempty α] (hd : directed (≥) f) (hb : ∀ i, ne_bot (f i)) : ne_bot (infi f) := if hι : nonempty ι then @infi_ne_bot_of_directed' _ _ _ hι hd hb else ⟨λ h : infi f = ⊥, have univ ⊆ (∅ : set α), begin rw [←principal_mono, principal_univ, principal_empty, ←h], exact (le_infi $ λ i, false.elim $ hι ⟨i⟩) end, let ⟨x⟩ := hn in this (mem_univ x)⟩ lemma infi_ne_bot_iff_of_directed' {f : ι → filter α} [nonempty ι] (hd : directed (≥) f) : ne_bot (infi f) ↔ ∀ i, ne_bot (f i) := ⟨λ H i, H.mono (infi_le _ i), infi_ne_bot_of_directed' hd⟩ lemma infi_ne_bot_iff_of_directed {f : ι → filter α} [nonempty α] (hd : directed (≥) f) : ne_bot (infi f) ↔ (∀ i, ne_bot (f i)) := ⟨λ H i, H.mono (infi_le _ i), infi_ne_bot_of_directed hd⟩ @[elab_as_eliminator] lemma infi_sets_induct {f : ι → filter α} {s : set α} (hs : s ∈ infi f) {p : set α → Prop} (uni : p univ) (ins : ∀ {i s₁ s₂}, s₁ ∈ f i → p s₂ → p (s₁ ∩ s₂)) : p s := begin rw [mem_infi_finite'] at hs, simp only [← finset.inf_eq_infi] at hs, rcases hs with ⟨is, his⟩, revert s, refine finset.induction_on is _ _, { intros s hs, rwa [mem_top.1 hs] }, { rintro ⟨i⟩ js his ih s hs, rw [finset.inf_insert, mem_inf_iff] at hs, rcases hs with ⟨s₁, hs₁, s₂, hs₂, rfl⟩, exact ins hs₁ (ih hs₂) } end /-! #### `principal` equations -/ @[simp] lemma inf_principal {s t : set α} : 𝓟 s ⊓ 𝓟 t = 𝓟 (s ∩ t) := le_antisymm (by simp only [le_principal_iff, mem_inf_iff]; exact ⟨s, subset.rfl, t, subset.rfl, rfl⟩) (by simp [le_inf_iff, inter_subset_left, inter_subset_right]) @[simp] lemma sup_principal {s t : set α} : 𝓟 s ⊔ 𝓟 t = 𝓟 (s ∪ t) := filter.ext $ λ u, by simp only [union_subset_iff, mem_sup, mem_principal] @[simp] lemma supr_principal {ι : Sort w} {s : ι → set α} : (⨆ x, 𝓟 (s x)) = 𝓟 (⋃ i, s i) := filter.ext $ λ x, by simp only [mem_supr, mem_principal, Union_subset_iff] @[simp] lemma principal_eq_bot_iff {s : set α} : 𝓟 s = ⊥ ↔ s = ∅ := empty_mem_iff_bot.symm.trans $ mem_principal.trans subset_empty_iff @[simp] lemma principal_ne_bot_iff {s : set α} : ne_bot (𝓟 s) ↔ s.nonempty := ne_bot_iff.trans $ (not_congr principal_eq_bot_iff).trans ne_empty_iff_nonempty lemma is_compl_principal (s : set α) : is_compl (𝓟 s) (𝓟 sᶜ) := ⟨by simp only [inf_principal, inter_compl_self, principal_empty, le_refl], by simp only [sup_principal, union_compl_self, principal_univ, le_refl]⟩ theorem mem_inf_principal' {f : filter α} {s t : set α} : s ∈ f ⊓ 𝓟 t ↔ tᶜ ∪ s ∈ f := by simp only [← le_principal_iff, (is_compl_principal s).le_left_iff, disjoint_assoc, inf_principal, ← (is_compl_principal (t ∩ sᶜ)).le_right_iff, compl_inter, compl_compl] theorem mem_inf_principal {f : filter α} {s t : set α} : s ∈ f ⊓ 𝓟 t ↔ {x | x ∈ t → x ∈ s} ∈ f := by { simp only [mem_inf_principal', imp_iff_not_or], refl } lemma supr_inf_principal (f : ι → filter α) (s : set α) : (⨆ i, f i ⊓ 𝓟 s) = (⨆ i, f i) ⊓ 𝓟 s := by { ext, simp only [mem_supr, mem_inf_principal] } lemma inf_principal_eq_bot {f : filter α} {s : set α} : f ⊓ 𝓟 s = ⊥ ↔ sᶜ ∈ f := by { rw [← empty_mem_iff_bot, mem_inf_principal], refl } lemma mem_of_eq_bot {f : filter α} {s : set α} (h : f ⊓ 𝓟 sᶜ = ⊥) : s ∈ f := by rwa [inf_principal_eq_bot, compl_compl] at h lemma diff_mem_inf_principal_compl {f : filter α} {s : set α} (hs : s ∈ f) (t : set α) : s \ t ∈ f ⊓ 𝓟 tᶜ := inter_mem_inf hs $ mem_principal_self tᶜ lemma principal_le_iff {s : set α} {f : filter α} : 𝓟 s ≤ f ↔ ∀ V ∈ f, s ⊆ V := begin change (∀ V, V ∈ f → V ∈ _) ↔ _, simp_rw mem_principal, end @[simp] lemma infi_principal_finset {ι : Type w} (s : finset ι) (f : ι → set α) : (⨅ i ∈ s, 𝓟 (f i)) = 𝓟 (⋂ i ∈ s, f i) := begin induction s using finset.induction_on with i s hi hs, { simp }, { rw [finset.infi_insert, finset.set_bInter_insert, hs, inf_principal] }, end @[simp] lemma infi_principal_fintype {ι : Type w} [fintype ι] (f : ι → set α) : (⨅ i, 𝓟 (f i)) = 𝓟 (⋂ i, f i) := by simpa using infi_principal_finset finset.univ f lemma infi_principal_finite {ι : Type w} {s : set ι} (hs : finite s) (f : ι → set α) : (⨅ i ∈ s, 𝓟 (f i)) = 𝓟 (⋂ i ∈ s, f i) := begin lift s to finset ι using hs, exact_mod_cast infi_principal_finset s f end end lattice @[mono] lemma join_mono {f₁ f₂ : filter (filter α)} (h : f₁ ≤ f₂) : join f₁ ≤ join f₂ := λ s hs, h hs /-! ### Eventually -/ /-- `f.eventually p` or `∀ᶠ x in f, p x` mean that `{x | p x} ∈ f`. E.g., `∀ᶠ x in at_top, p x` means that `p` holds true for sufficiently large `x`. -/ protected def eventually (p : α → Prop) (f : filter α) : Prop := {x | p x} ∈ f notation `∀ᶠ` binders ` in ` f `, ` r:(scoped p, filter.eventually p f) := r lemma eventually_iff {f : filter α} {P : α → Prop} : (∀ᶠ x in f, P x) ↔ {x | P x} ∈ f := iff.rfl @[simp] lemma eventually_mem_set {s : set α} {l : filter α} : (∀ᶠ x in l, x ∈ s) ↔ s ∈ l := iff.rfl protected lemma ext' {f₁ f₂ : filter α} (h : ∀ p : α → Prop, (∀ᶠ x in f₁, p x) ↔ (∀ᶠ x in f₂, p x)) : f₁ = f₂ := filter.ext h lemma eventually.filter_mono {f₁ f₂ : filter α} (h : f₁ ≤ f₂) {p : α → Prop} (hp : ∀ᶠ x in f₂, p x) : ∀ᶠ x in f₁, p x := h hp lemma eventually_of_mem {f : filter α} {P : α → Prop} {U : set α} (hU : U ∈ f) (h : ∀ x ∈ U, P x) : ∀ᶠ x in f, P x := mem_of_superset hU h protected lemma eventually.and {p q : α → Prop} {f : filter α} : f.eventually p → f.eventually q → ∀ᶠ x in f, p x ∧ q x := inter_mem @[simp] lemma eventually_true (f : filter α) : ∀ᶠ x in f, true := univ_mem lemma eventually_of_forall {p : α → Prop} {f : filter α} (hp : ∀ x, p x) : ∀ᶠ x in f, p x := univ_mem' hp @[simp] lemma eventually_false_iff_eq_bot {f : filter α} : (∀ᶠ x in f, false) ↔ f = ⊥ := empty_mem_iff_bot @[simp] lemma eventually_const {f : filter α} [t : ne_bot f] {p : Prop} : (∀ᶠ x in f, p) ↔ p := classical.by_cases (λ h : p, by simp [h]) (λ h, by simpa [h] using t.ne) lemma eventually_iff_exists_mem {p : α → Prop} {f : filter α} : (∀ᶠ x in f, p x) ↔ ∃ v ∈ f, ∀ y ∈ v, p y := exists_mem_subset_iff.symm lemma eventually.exists_mem {p : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) : ∃ v ∈ f, ∀ y ∈ v, p y := eventually_iff_exists_mem.1 hp lemma eventually.mp {p q : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) (hq : ∀ᶠ x in f, p x → q x) : ∀ᶠ x in f, q x := mp_mem hp hq lemma eventually.mono {p q : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) (hq : ∀ x, p x → q x) : ∀ᶠ x in f, q x := hp.mp (eventually_of_forall hq) @[simp] lemma eventually_and {p q : α → Prop} {f : filter α} : (∀ᶠ x in f, p x ∧ q x) ↔ (∀ᶠ x in f, p x) ∧ (∀ᶠ x in f, q x) := inter_mem_iff lemma eventually.congr {f : filter α} {p q : α → Prop} (h' : ∀ᶠ x in f, p x) (h : ∀ᶠ x in f, p x ↔ q x) : ∀ᶠ x in f, q x := h'.mp (h.mono $ λ x hx, hx.mp) lemma eventually_congr {f : filter α} {p q : α → Prop} (h : ∀ᶠ x in f, p x ↔ q x) : (∀ᶠ x in f, p x) ↔ (∀ᶠ x in f, q x) := ⟨λ hp, hp.congr h, λ hq, hq.congr $ by simpa only [iff.comm] using h⟩ @[simp] lemma eventually_all {ι} [fintype ι] {l} {p : ι → α → Prop} : (∀ᶠ x in l, ∀ i, p i x) ↔ ∀ i, ∀ᶠ x in l, p i x := by simpa only [filter.eventually, set_of_forall] using Inter_mem @[simp] lemma eventually_all_finite {ι} {I : set ι} (hI : I.finite) {l} {p : ι → α → Prop} : (∀ᶠ x in l, ∀ i ∈ I, p i x) ↔ (∀ i ∈ I, ∀ᶠ x in l, p i x) := by simpa only [filter.eventually, set_of_forall] using bInter_mem hI alias eventually_all_finite ← set.finite.eventually_all attribute [protected] set.finite.eventually_all @[simp] lemma eventually_all_finset {ι} (I : finset ι) {l} {p : ι → α → Prop} : (∀ᶠ x in l, ∀ i ∈ I, p i x) ↔ ∀ i ∈ I, ∀ᶠ x in l, p i x := I.finite_to_set.eventually_all alias eventually_all_finset ← finset.eventually_all attribute [protected] finset.eventually_all @[simp] lemma eventually_or_distrib_left {f : filter α} {p : Prop} {q : α → Prop} : (∀ᶠ x in f, p ∨ q x) ↔ (p ∨ ∀ᶠ x in f, q x) := classical.by_cases (λ h : p, by simp [h]) (λ h, by simp [h]) @[simp] lemma eventually_or_distrib_right {f : filter α} {p : α → Prop} {q : Prop} : (∀ᶠ x in f, p x ∨ q) ↔ ((∀ᶠ x in f, p x) ∨ q) := by simp only [or_comm _ q, eventually_or_distrib_left] @[simp] lemma eventually_imp_distrib_left {f : filter α} {p : Prop} {q : α → Prop} : (∀ᶠ x in f, p → q x) ↔ (p → ∀ᶠ x in f, q x) := by simp only [imp_iff_not_or, eventually_or_distrib_left] @[simp] lemma eventually_bot {p : α → Prop} : ∀ᶠ x in ⊥, p x := ⟨⟩ @[simp] lemma eventually_top {p : α → Prop} : (∀ᶠ x in ⊤, p x) ↔ (∀ x, p x) := iff.rfl @[simp] lemma eventually_sup {p : α → Prop} {f g : filter α} : (∀ᶠ x in f ⊔ g, p x) ↔ (∀ᶠ x in f, p x) ∧ (∀ᶠ x in g, p x) := iff.rfl @[simp] lemma eventually_Sup {p : α → Prop} {fs : set (filter α)} : (∀ᶠ x in Sup fs, p x) ↔ (∀ f ∈ fs, ∀ᶠ x in f, p x) := iff.rfl @[simp] lemma eventually_supr {p : α → Prop} {fs : β → filter α} : (∀ᶠ x in (⨆ b, fs b), p x) ↔ (∀ b, ∀ᶠ x in fs b, p x) := mem_supr @[simp] lemma eventually_principal {a : set α} {p : α → Prop} : (∀ᶠ x in 𝓟 a, p x) ↔ (∀ x ∈ a, p x) := iff.rfl lemma eventually_inf {f g : filter α} {p : α → Prop} : (∀ᶠ x in f ⊓ g, p x) ↔ ∃ (s ∈ f) (t ∈ g), ∀ x ∈ s ∩ t, p x := mem_inf_iff_superset theorem eventually_inf_principal {f : filter α} {p : α → Prop} {s : set α} : (∀ᶠ x in f ⊓ 𝓟 s, p x) ↔ ∀ᶠ x in f, x ∈ s → p x := mem_inf_principal /-! ### Frequently -/ /-- `f.frequently p` or `∃ᶠ x in f, p x` mean that `{x | ¬p x} ∉ f`. E.g., `∃ᶠ x in at_top, p x` means that there exist arbitrarily large `x` for which `p` holds true. -/ protected def frequently (p : α → Prop) (f : filter α) : Prop := ¬∀ᶠ x in f, ¬p x notation `∃ᶠ` binders ` in ` f `, ` r:(scoped p, filter.frequently p f) := r lemma eventually.frequently {f : filter α} [ne_bot f] {p : α → Prop} (h : ∀ᶠ x in f, p x) : ∃ᶠ x in f, p x := compl_not_mem h lemma frequently_of_forall {f : filter α} [ne_bot f] {p : α → Prop} (h : ∀ x, p x) : ∃ᶠ x in f, p x := eventually.frequently (eventually_of_forall h) lemma frequently.mp {p q : α → Prop} {f : filter α} (h : ∃ᶠ x in f, p x) (hpq : ∀ᶠ x in f, p x → q x) : ∃ᶠ x in f, q x := mt (λ hq, hq.mp $ hpq.mono $ λ x, mt) h lemma frequently.filter_mono {p : α → Prop} {f g : filter α} (h : ∃ᶠ x in f, p x) (hle : f ≤ g) : ∃ᶠ x in g, p x := mt (λ h', h'.filter_mono hle) h lemma frequently.mono {p q : α → Prop} {f : filter α} (h : ∃ᶠ x in f, p x) (hpq : ∀ x, p x → q x) : ∃ᶠ x in f, q x := h.mp (eventually_of_forall hpq) lemma frequently.and_eventually {p q : α → Prop} {f : filter α} (hp : ∃ᶠ x in f, p x) (hq : ∀ᶠ x in f, q x) : ∃ᶠ x in f, p x ∧ q x := begin refine mt (λ h, hq.mp $ h.mono _) hp, exact λ x hpq hq hp, hpq ⟨hp, hq⟩ end lemma eventually.and_frequently {p q : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) (hq : ∃ᶠ x in f, q x) : ∃ᶠ x in f, p x ∧ q x := by simpa only [and.comm] using hq.and_eventually hp lemma frequently.exists {p : α → Prop} {f : filter α} (hp : ∃ᶠ x in f, p x) : ∃ x, p x := begin by_contradiction H, replace H : ∀ᶠ x in f, ¬ p x, from eventually_of_forall (not_exists.1 H), exact hp H end lemma eventually.exists {p : α → Prop} {f : filter α} [ne_bot f] (hp : ∀ᶠ x in f, p x) : ∃ x, p x := hp.frequently.exists lemma frequently_iff_forall_eventually_exists_and {p : α → Prop} {f : filter α} : (∃ᶠ x in f, p x) ↔ ∀ {q : α → Prop}, (∀ᶠ x in f, q x) → ∃ x, p x ∧ q x := ⟨λ hp q hq, (hp.and_eventually hq).exists, λ H hp, by simpa only [and_not_self, exists_false] using H hp⟩ lemma frequently_iff {f : filter α} {P : α → Prop} : (∃ᶠ x in f, P x) ↔ ∀ {U}, U ∈ f → ∃ x ∈ U, P x := begin simp only [frequently_iff_forall_eventually_exists_and, exists_prop, and_comm (P _)], refl end @[simp] lemma not_eventually {p : α → Prop} {f : filter α} : (¬ ∀ᶠ x in f, p x) ↔ (∃ᶠ x in f, ¬ p x) := by simp [filter.frequently] @[simp] lemma not_frequently {p : α → Prop} {f : filter α} : (¬ ∃ᶠ x in f, p x) ↔ (∀ᶠ x in f, ¬ p x) := by simp only [filter.frequently, not_not] @[simp] lemma frequently_true_iff_ne_bot (f : filter α) : (∃ᶠ x in f, true) ↔ ne_bot f := by simp [filter.frequently, -not_eventually, eventually_false_iff_eq_bot, ne_bot_iff] @[simp] lemma frequently_false (f : filter α) : ¬ ∃ᶠ x in f, false := by simp @[simp] lemma frequently_const {f : filter α} [ne_bot f] {p : Prop} : (∃ᶠ x in f, p) ↔ p := classical.by_cases (λ h : p, by simpa [h]) (λ h, by simp [h]) @[simp] lemma frequently_or_distrib {f : filter α} {p q : α → Prop} : (∃ᶠ x in f, p x ∨ q x) ↔ (∃ᶠ x in f, p x) ∨ (∃ᶠ x in f, q x) := by simp only [filter.frequently, ← not_and_distrib, not_or_distrib, eventually_and] lemma frequently_or_distrib_left {f : filter α} [ne_bot f] {p : Prop} {q : α → Prop} : (∃ᶠ x in f, p ∨ q x) ↔ (p ∨ ∃ᶠ x in f, q x) := by simp lemma frequently_or_distrib_right {f : filter α} [ne_bot f] {p : α → Prop} {q : Prop} : (∃ᶠ x in f, p x ∨ q) ↔ (∃ᶠ x in f, p x) ∨ q := by simp @[simp] lemma frequently_imp_distrib {f : filter α} {p q : α → Prop} : (∃ᶠ x in f, p x → q x) ↔ ((∀ᶠ x in f, p x) → ∃ᶠ x in f, q x) := by simp [imp_iff_not_or, not_eventually, frequently_or_distrib] lemma frequently_imp_distrib_left {f : filter α} [ne_bot f] {p : Prop} {q : α → Prop} : (∃ᶠ x in f, p → q x) ↔ (p → ∃ᶠ x in f, q x) := by simp lemma frequently_imp_distrib_right {f : filter α} [ne_bot f] {p : α → Prop} {q : Prop} : (∃ᶠ x in f, p x → q) ↔ ((∀ᶠ x in f, p x) → q) := by simp @[simp] lemma eventually_imp_distrib_right {f : filter α} {p : α → Prop} {q : Prop} : (∀ᶠ x in f, p x → q) ↔ ((∃ᶠ x in f, p x) → q) := by simp only [imp_iff_not_or, eventually_or_distrib_right, not_frequently] @[simp] lemma frequently_and_distrib_left {f : filter α} {p : Prop} {q : α → Prop} : (∃ᶠ x in f, p ∧ q x) ↔ (p ∧ ∃ᶠ x in f, q x) := by simp only [filter.frequently, not_and, eventually_imp_distrib_left, not_imp] @[simp] lemma frequently_and_distrib_right {f : filter α} {p : α → Prop} {q : Prop} : (∃ᶠ x in f, p x ∧ q) ↔ ((∃ᶠ x in f, p x) ∧ q) := by simp only [and_comm _ q, frequently_and_distrib_left] @[simp] lemma frequently_bot {p : α → Prop} : ¬ ∃ᶠ x in ⊥, p x := by simp @[simp] lemma frequently_top {p : α → Prop} : (∃ᶠ x in ⊤, p x) ↔ (∃ x, p x) := by simp [filter.frequently] @[simp] lemma frequently_principal {a : set α} {p : α → Prop} : (∃ᶠ x in 𝓟 a, p x) ↔ (∃ x ∈ a, p x) := by simp [filter.frequently, not_forall] lemma frequently_sup {p : α → Prop} {f g : filter α} : (∃ᶠ x in f ⊔ g, p x) ↔ (∃ᶠ x in f, p x) ∨ (∃ᶠ x in g, p x) := by simp only [filter.frequently, eventually_sup, not_and_distrib] @[simp] lemma frequently_Sup {p : α → Prop} {fs : set (filter α)} : (∃ᶠ x in Sup fs, p x) ↔ (∃ f ∈ fs, ∃ᶠ x in f, p x) := by simp [filter.frequently, -not_eventually, not_forall] @[simp] lemma frequently_supr {p : α → Prop} {fs : β → filter α} : (∃ᶠ x in (⨆ b, fs b), p x) ↔ (∃ b, ∃ᶠ x in fs b, p x) := by simp [filter.frequently, -not_eventually, not_forall] /-! ### Relation “eventually equal” -/ /-- Two functions `f` and `g` are *eventually equal* along a filter `l` if the set of `x` such that `f x = g x` belongs to `l`. -/ def eventually_eq (l : filter α) (f g : α → β) : Prop := ∀ᶠ x in l, f x = g x notation f ` =ᶠ[`:50 l:50 `] `:0 g:50 := eventually_eq l f g lemma eventually_eq.eventually {l : filter α} {f g : α → β} (h : f =ᶠ[l] g) : ∀ᶠ x in l, f x = g x := h lemma eventually_eq.rw {l : filter α} {f g : α → β} (h : f =ᶠ[l] g) (p : α → β → Prop) (hf : ∀ᶠ x in l, p x (f x)) : ∀ᶠ x in l, p x (g x) := hf.congr $ h.mono $ λ x hx, hx ▸ iff.rfl lemma eventually_eq_set {s t : set α} {l : filter α} : s =ᶠ[l] t ↔ ∀ᶠ x in l, x ∈ s ↔ x ∈ t := eventually_congr $ eventually_of_forall $ λ x, ⟨eq.to_iff, iff.to_eq⟩ alias eventually_eq_set ↔ filter.eventually_eq.mem_iff filter.eventually.set_eq @[simp] lemma eventually_eq_univ {s : set α} {l : filter α} : s =ᶠ[l] univ ↔ s ∈ l := by simp [eventually_eq_set] lemma eventually_eq.exists_mem {l : filter α} {f g : α → β} (h : f =ᶠ[l] g) : ∃ s ∈ l, eq_on f g s := h.exists_mem lemma eventually_eq_of_mem {l : filter α} {f g : α → β} {s : set α} (hs : s ∈ l) (h : eq_on f g s) : f =ᶠ[l] g := eventually_of_mem hs h lemma eventually_eq_iff_exists_mem {l : filter α} {f g : α → β} : (f =ᶠ[l] g) ↔ ∃ s ∈ l, eq_on f g s := eventually_iff_exists_mem lemma eventually_eq.filter_mono {l l' : filter α} {f g : α → β} (h₁ : f =ᶠ[l] g) (h₂ : l' ≤ l) : f =ᶠ[l'] g := h₂ h₁ @[refl] lemma eventually_eq.refl (l : filter α) (f : α → β) : f =ᶠ[l] f := eventually_of_forall $ λ x, rfl lemma eventually_eq.rfl {l : filter α} {f : α → β} : f =ᶠ[l] f := eventually_eq.refl l f @[symm] lemma eventually_eq.symm {f g : α → β} {l : filter α} (H : f =ᶠ[l] g) : g =ᶠ[l] f := H.mono $ λ _, eq.symm @[trans] lemma eventually_eq.trans {f g h : α → β} {l : filter α} (H₁ : f =ᶠ[l] g) (H₂ : g =ᶠ[l] h) : f =ᶠ[l] h := H₂.rw (λ x y, f x = y) H₁ lemma eventually_eq.prod_mk {l} {f f' : α → β} (hf : f =ᶠ[l] f') {g g' : α → γ} (hg : g =ᶠ[l] g') : (λ x, (f x, g x)) =ᶠ[l] (λ x, (f' x, g' x)) := hf.mp $ hg.mono $ by { intros, simp only * } lemma eventually_eq.fun_comp {f g : α → β} {l : filter α} (H : f =ᶠ[l] g) (h : β → γ) : (h ∘ f) =ᶠ[l] (h ∘ g) := H.mono $ λ x hx, congr_arg h hx lemma eventually_eq.comp₂ {δ} {f f' : α → β} {g g' : α → γ} {l} (Hf : f =ᶠ[l] f') (h : β → γ → δ) (Hg : g =ᶠ[l] g') : (λ x, h (f x) (g x)) =ᶠ[l] (λ x, h (f' x) (g' x)) := (Hf.prod_mk Hg).fun_comp (uncurry h) @[to_additive] lemma eventually_eq.mul [has_mul β] {f f' g g' : α → β} {l : filter α} (h : f =ᶠ[l] g) (h' : f' =ᶠ[l] g') : ((λ x, f x * f' x) =ᶠ[l] (λ x, g x * g' x)) := h.comp₂ (*) h' @[to_additive] lemma eventually_eq.inv [has_inv β] {f g : α → β} {l : filter α} (h : f =ᶠ[l] g) : ((λ x, (f x)⁻¹) =ᶠ[l] (λ x, (g x)⁻¹)) := h.fun_comp has_inv.inv lemma eventually_eq.div [group_with_zero β] {f f' g g' : α → β} {l : filter α} (h : f =ᶠ[l] g) (h' : f' =ᶠ[l] g') : ((λ x, f x / f' x) =ᶠ[l] (λ x, g x / g' x)) := by simpa only [div_eq_mul_inv] using h.mul h'.inv lemma eventually_eq.div' [group β] {f f' g g' : α → β} {l : filter α} (h : f =ᶠ[l] g) (h' : f' =ᶠ[l] g') : ((λ x, f x / f' x) =ᶠ[l] (λ x, g x / g' x)) := by simpa only [div_eq_mul_inv] using h.mul h'.inv lemma eventually_eq.sub [add_group β] {f f' g g' : α → β} {l : filter α} (h : f =ᶠ[l] g) (h' : f' =ᶠ[l] g') : ((λ x, f x - f' x) =ᶠ[l] (λ x, g x - g' x)) := by simpa only [sub_eq_add_neg] using h.add h'.neg lemma eventually_eq.inter {s t s' t' : set α} {l : filter α} (h : s =ᶠ[l] t) (h' : s' =ᶠ[l] t') : (s ∩ s' : set α) =ᶠ[l] (t ∩ t' : set α) := h.comp₂ (∧) h' lemma eventually_eq.union {s t s' t' : set α} {l : filter α} (h : s =ᶠ[l] t) (h' : s' =ᶠ[l] t') : (s ∪ s' : set α) =ᶠ[l] (t ∪ t' : set α) := h.comp₂ (∨) h' lemma eventually_eq.compl {s t : set α} {l : filter α} (h : s =ᶠ[l] t) : (sᶜ : set α) =ᶠ[l] (tᶜ : set α) := h.fun_comp not lemma eventually_eq.diff {s t s' t' : set α} {l : filter α} (h : s =ᶠ[l] t) (h' : s' =ᶠ[l] t') : (s \ s' : set α) =ᶠ[l] (t \ t' : set α) := h.inter h'.compl lemma eventually_eq_empty {s : set α} {l : filter α} : s =ᶠ[l] (∅ : set α) ↔ ∀ᶠ x in l, x ∉ s := eventually_eq_set.trans $ by simp lemma inter_eventually_eq_left {s t : set α} {l : filter α} : (s ∩ t : set α) =ᶠ[l] s ↔ ∀ᶠ x in l, x ∈ s → x ∈ t := by simp only [eventually_eq_set, mem_inter_eq, and_iff_left_iff_imp] lemma inter_eventually_eq_right {s t : set α} {l : filter α} : (s ∩ t : set α) =ᶠ[l] t ↔ ∀ᶠ x in l, x ∈ t → x ∈ s := by rw [inter_comm, inter_eventually_eq_left] @[simp] lemma eventually_eq_principal {s : set α} {f g : α → β} : f =ᶠ[𝓟 s] g ↔ eq_on f g s := iff.rfl lemma eventually_eq_inf_principal_iff {F : filter α} {s : set α} {f g : α → β} : (f =ᶠ[F ⊓ 𝓟 s] g) ↔ ∀ᶠ x in F, x ∈ s → f x = g x := eventually_inf_principal lemma eventually_eq.sub_eq [add_group β] {f g : α → β} {l : filter α} (h : f =ᶠ[l] g) : f - g =ᶠ[l] 0 := by simpa using (eventually_eq.sub (eventually_eq.refl l f) h).symm lemma eventually_eq_iff_sub [add_group β] {f g : α → β} {l : filter α} : f =ᶠ[l] g ↔ f - g =ᶠ[l] 0 := ⟨λ h, h.sub_eq, λ h, by simpa using h.add (eventually_eq.refl l g)⟩ section has_le variables [has_le β] {l : filter α} /-- A function `f` is eventually less than or equal to a function `g` at a filter `l`. -/ def eventually_le (l : filter α) (f g : α → β) : Prop := ∀ᶠ x in l, f x ≤ g x notation f ` ≤ᶠ[`:50 l:50 `] `:0 g:50 := eventually_le l f g lemma eventually_le.congr {f f' g g' : α → β} (H : f ≤ᶠ[l] g) (hf : f =ᶠ[l] f') (hg : g =ᶠ[l] g') : f' ≤ᶠ[l] g' := H.mp $ hg.mp $ hf.mono $ λ x hf hg H, by rwa [hf, hg] at H lemma eventually_le_congr {f f' g g' : α → β} (hf : f =ᶠ[l] f') (hg : g =ᶠ[l] g') : f ≤ᶠ[l] g ↔ f' ≤ᶠ[l] g' := ⟨λ H, H.congr hf hg, λ H, H.congr hf.symm hg.symm⟩ end has_le section preorder variables [preorder β] {l : filter α} {f g h : α → β} lemma eventually_eq.le (h : f =ᶠ[l] g) : f ≤ᶠ[l] g := h.mono $ λ x, le_of_eq @[refl] lemma eventually_le.refl (l : filter α) (f : α → β) : f ≤ᶠ[l] f := eventually_eq.rfl.le lemma eventually_le.rfl : f ≤ᶠ[l] f := eventually_le.refl l f @[trans] lemma eventually_le.trans (H₁ : f ≤ᶠ[l] g) (H₂ : g ≤ᶠ[l] h) : f ≤ᶠ[l] h := H₂.mp $ H₁.mono $ λ x, le_trans @[trans] lemma eventually_eq.trans_le (H₁ : f =ᶠ[l] g) (H₂ : g ≤ᶠ[l] h) : f ≤ᶠ[l] h := H₁.le.trans H₂ @[trans] lemma eventually_le.trans_eq (H₁ : f ≤ᶠ[l] g) (H₂ : g =ᶠ[l] h) : f ≤ᶠ[l] h := H₁.trans H₂.le end preorder lemma eventually_le.antisymm [partial_order β] {l : filter α} {f g : α → β} (h₁ : f ≤ᶠ[l] g) (h₂ : g ≤ᶠ[l] f) : f =ᶠ[l] g := h₂.mp $ h₁.mono $ λ x, le_antisymm lemma eventually_le_antisymm_iff [partial_order β] {l : filter α} {f g : α → β} : f =ᶠ[l] g ↔ f ≤ᶠ[l] g ∧ g ≤ᶠ[l] f := by simp only [eventually_eq, eventually_le, le_antisymm_iff, eventually_and] lemma eventually_le.le_iff_eq [partial_order β] {l : filter α} {f g : α → β} (h : f ≤ᶠ[l] g) : g ≤ᶠ[l] f ↔ g =ᶠ[l] f := ⟨λ h', h'.antisymm h, eventually_eq.le⟩ lemma eventually.ne_of_lt [preorder β] {l : filter α} {f g : α → β} (h : ∀ᶠ x in l, f x < g x) : ∀ᶠ x in l, f x ≠ g x := h.mono (λ x hx, hx.ne) lemma eventually.ne_top_of_lt [partial_order β] [order_top β] {l : filter α} {f g : α → β} (h : ∀ᶠ x in l, f x < g x) : ∀ᶠ x in l, f x ≠ ⊤ := h.mono (λ x hx, hx.ne_top) lemma eventually.lt_top_of_ne [partial_order β] [order_top β] {l : filter α} {f : α → β} (h : ∀ᶠ x in l, f x ≠ ⊤) : ∀ᶠ x in l, f x < ⊤ := h.mono (λ x hx, hx.lt_top) lemma eventually.lt_top_iff_ne_top [partial_order β] [order_top β] {l : filter α} {f : α → β} : (∀ᶠ x in l, f x < ⊤) ↔ ∀ᶠ x in l, f x ≠ ⊤ := ⟨eventually.ne_of_lt, eventually.lt_top_of_ne⟩ @[mono] lemma eventually_le.inter {s t s' t' : set α} {l : filter α} (h : s ≤ᶠ[l] t) (h' : s' ≤ᶠ[l] t') : (s ∩ s' : set α) ≤ᶠ[l] (t ∩ t' : set α) := h'.mp $ h.mono $ λ x, and.imp @[mono] lemma eventually_le.union {s t s' t' : set α} {l : filter α} (h : s ≤ᶠ[l] t) (h' : s' ≤ᶠ[l] t') : (s ∪ s' : set α) ≤ᶠ[l] (t ∪ t' : set α) := h'.mp $ h.mono $ λ x, or.imp @[mono] lemma eventually_le.compl {s t : set α} {l : filter α} (h : s ≤ᶠ[l] t) : (tᶜ : set α) ≤ᶠ[l] (sᶜ : set α) := h.mono $ λ x, mt @[mono] lemma eventually_le.diff {s t s' t' : set α} {l : filter α} (h : s ≤ᶠ[l] t) (h' : t' ≤ᶠ[l] s') : (s \ s' : set α) ≤ᶠ[l] (t \ t' : set α) := h.inter h'.compl lemma join_le {f : filter (filter α)} {l : filter α} (h : ∀ᶠ m in f, m ≤ l) : join f ≤ l := λ s hs, h.mono $ λ m hm, hm hs /-! ### Push-forwards, pull-backs, and the monad structure -/ section map /-- The forward map of a filter -/ def map (m : α → β) (f : filter α) : filter β := { sets := preimage m ⁻¹' f.sets, univ_sets := univ_mem, sets_of_superset := λ s t hs st, mem_of_superset hs $ preimage_mono st, inter_sets := λ s t hs ht, inter_mem hs ht } @[simp] lemma map_principal {s : set α} {f : α → β} : map f (𝓟 s) = 𝓟 (set.image f s) := filter.ext $ λ a, image_subset_iff.symm variables {f : filter α} {m : α → β} {m' : β → γ} {s : set α} {t : set β} @[simp] lemma eventually_map {P : β → Prop} : (∀ᶠ b in map m f, P b) ↔ ∀ᶠ a in f, P (m a) := iff.rfl @[simp] lemma frequently_map {P : β → Prop} : (∃ᶠ b in map m f, P b) ↔ ∃ᶠ a in f, P (m a) := iff.rfl @[simp] lemma mem_map : t ∈ map m f ↔ m ⁻¹' t ∈ f := iff.rfl lemma mem_map' : t ∈ map m f ↔ {x | m x ∈ t} ∈ f := iff.rfl lemma image_mem_map (hs : s ∈ f) : m '' s ∈ map m f := f.sets_of_superset hs $ subset_preimage_image m s lemma image_mem_map_iff (hf : injective m) : m '' s ∈ map m f ↔ s ∈ f := ⟨λ h, by rwa [← preimage_image_eq s hf], image_mem_map⟩ lemma range_mem_map : range m ∈ map m f := by { rw ←image_univ, exact image_mem_map univ_mem } lemma mem_map_iff_exists_image : t ∈ map m f ↔ (∃ s ∈ f, m '' s ⊆ t) := ⟨λ ht, ⟨m ⁻¹' t, ht, image_preimage_subset _ _⟩, λ ⟨s, hs, ht⟩, mem_of_superset (image_mem_map hs) ht⟩ @[simp] lemma map_id : filter.map id f = f := filter_eq $ rfl @[simp] lemma map_id' : filter.map (λ x, x) f = f := map_id @[simp] lemma map_compose : filter.map m' ∘ filter.map m = filter.map (m' ∘ m) := funext $ λ _, filter_eq $ rfl @[simp] lemma map_map : filter.map m' (filter.map m f) = filter.map (m' ∘ m) f := congr_fun (@@filter.map_compose m m') f /-- If functions `m₁` and `m₂` are eventually equal at a filter `f`, then they map this filter to the same filter. -/ lemma map_congr {m₁ m₂ : α → β} {f : filter α} (h : m₁ =ᶠ[f] m₂) : map m₁ f = map m₂ f := filter.ext' $ λ p, by { simp only [eventually_map], exact eventually_congr (h.mono $ λ x hx, hx ▸ iff.rfl) } end map section comap /-- The inverse map of a filter -/ def comap (m : α → β) (f : filter β) : filter α := { sets := { s | ∃ t ∈ f, m ⁻¹' t ⊆ s }, univ_sets := ⟨univ, univ_mem, by simp only [subset_univ, preimage_univ]⟩, sets_of_superset := λ a b ⟨a', ha', ma'a⟩ ab, ⟨a', ha', ma'a.trans ab⟩, inter_sets := λ a b ⟨a', ha₁, ha₂⟩ ⟨b', hb₁, hb₂⟩, ⟨a' ∩ b', inter_mem ha₁ hb₁, inter_subset_inter ha₂ hb₂⟩ } lemma eventually_comap' {f : filter β} {φ : α → β} {p : β → Prop} (hf : ∀ᶠ b in f, p b) : ∀ᶠ a in comap φ f, p (φ a) := ⟨_, hf, (λ a h, h)⟩ @[simp] lemma eventually_comap {f : filter β} {φ : α → β} {P : α → Prop} : (∀ᶠ a in comap φ f, P a) ↔ ∀ᶠ b in f, ∀ a, φ a = b → P a := begin split ; intro h, { rcases h with ⟨t, t_in, ht⟩, apply mem_of_superset t_in, rintro y y_in _ rfl, apply ht y_in }, { exact ⟨_, h, λ _ x_in, x_in _ rfl⟩ } end @[simp] lemma frequently_comap {f : filter β} {φ : α → β} {P : α → Prop} : (∃ᶠ a in comap φ f, P a) ↔ ∃ᶠ b in f, ∃ a, φ a = b ∧ P a := by simp only [filter.frequently, eventually_comap, not_exists, not_and] end comap /-- The monadic bind operation on filter is defined the usual way in terms of `map` and `join`. Unfortunately, this `bind` does not result in the expected applicative. See `filter.seq` for the applicative instance. -/ def bind (f : filter α) (m : α → filter β) : filter β := join (map m f) /-- The applicative sequentiation operation. This is not induced by the bind operation. -/ def seq (f : filter (α → β)) (g : filter α) : filter β := ⟨{ s | ∃ u ∈ f, ∃ t ∈ g, (∀ m ∈ u, ∀ x ∈ t, (m : α → β) x ∈ s) }, ⟨univ, univ_mem, univ, univ_mem, by simp only [forall_prop_of_true, mem_univ, forall_true_iff]⟩, λ s₀ s₁ ⟨t₀, t₁, h₀, h₁, h⟩ hst, ⟨t₀, t₁, h₀, h₁, λ x hx y hy, hst $ h _ hx _ hy⟩, λ s₀ s₁ ⟨t₀, ht₀, t₁, ht₁, ht⟩ ⟨u₀, hu₀, u₁, hu₁, hu⟩, ⟨t₀ ∩ u₀, inter_mem ht₀ hu₀, t₁ ∩ u₁, inter_mem ht₁ hu₁, λ x ⟨hx₀, hx₁⟩ x ⟨hy₀, hy₁⟩, ⟨ht _ hx₀ _ hy₀, hu _ hx₁ _ hy₁⟩⟩⟩ /-- `pure x` is the set of sets that contain `x`. It is equal to `𝓟 {x}` but with this definition we have `s ∈ pure a` defeq `a ∈ s`. -/ instance : has_pure filter := ⟨λ (α : Type u) x, { sets := {s | x ∈ s}, inter_sets := λ s t, and.intro, sets_of_superset := λ s t hs hst, hst hs, univ_sets := trivial }⟩ instance : has_bind filter := ⟨@filter.bind⟩ instance : has_seq filter := ⟨@filter.seq⟩ instance : functor filter := { map := @filter.map } lemma pure_sets (a : α) : (pure a : filter α).sets = {s | a ∈ s} := rfl @[simp] lemma mem_pure {a : α} {s : set α} : s ∈ (pure a : filter α) ↔ a ∈ s := iff.rfl @[simp] lemma eventually_pure {a : α} {p : α → Prop} : (∀ᶠ x in pure a, p x) ↔ p a := iff.rfl @[simp] lemma principal_singleton (a : α) : 𝓟 {a} = pure a := filter.ext $ λ s, by simp only [mem_pure, mem_principal, singleton_subset_iff] @[simp] lemma map_pure (f : α → β) (a : α) : map f (pure a) = pure (f a) := rfl @[simp] lemma join_pure (f : filter α) : join (pure f) = f := filter.ext $ λ s, iff.rfl @[simp] lemma pure_bind (a : α) (m : α → filter β) : bind (pure a) m = m a := by simp only [has_bind.bind, bind, map_pure, join_pure] section -- this section needs to be before applicative, otherwise the wrong instance will be chosen /-- The monad structure on filters. -/ protected def monad : monad filter := { map := @filter.map } local attribute [instance] filter.monad protected lemma is_lawful_monad : is_lawful_monad filter := { id_map := λ α f, filter_eq rfl, pure_bind := λ α β, pure_bind, bind_assoc := λ α β γ f m₁ m₂, filter_eq rfl, bind_pure_comp_eq_map := λ α β f x, filter.ext $ λ s, by simp only [has_bind.bind, bind, functor.map, mem_map', mem_join, mem_set_of_eq, comp, mem_pure] } end instance : applicative filter := { map := @filter.map, seq := @filter.seq } instance : alternative filter := { failure := λ α, ⊥, orelse := λ α x y, x ⊔ y } @[simp] lemma map_def {α β} (m : α → β) (f : filter α) : m <$> f = map m f := rfl @[simp] lemma bind_def {α β} (f : filter α) (m : α → filter β) : f >>= m = bind f m := rfl /-! #### `map` and `comap` equations -/ section map variables {f f₁ f₂ : filter α} {g g₁ g₂ : filter β} {m : α → β} {m' : β → γ} {s : set α} {t : set β} @[simp] theorem mem_comap : s ∈ comap m g ↔ ∃ t ∈ g, m ⁻¹' t ⊆ s := iff.rfl theorem preimage_mem_comap (ht : t ∈ g) : m ⁻¹' t ∈ comap m g := ⟨t, ht, subset.rfl⟩ lemma comap_id : comap id f = f := le_antisymm (λ s, preimage_mem_comap) (λ s ⟨t, ht, hst⟩, mem_of_superset ht hst) lemma comap_const_of_not_mem {x : α} {f : filter α} {V : set α} (hV : V ∈ f) (hx : x ∉ V) : comap (λ y : α, x) f = ⊥ := begin ext W, suffices : ∃ t ∈ f, (λ (y : α), x) ⁻¹' t ⊆ W, by simpa, use [V, hV], simp [preimage_const_of_not_mem hx], end lemma comap_const_of_mem {x : α} {f : filter α} (h : ∀ V ∈ f, x ∈ V) : comap (λ y : α, x) f = ⊤ := begin ext W, suffices : (∃ (t : set α), t ∈ f ∧ (λ (y : α), x) ⁻¹' t ⊆ W) ↔ W = univ, by simpa, split, { rintro ⟨V, V_in, hW⟩, simpa [preimage_const_of_mem (h V V_in), univ_subset_iff] using hW }, { rintro rfl, use univ, simp [univ_mem] }, end lemma comap_comap {m : γ → β} {n : β → α} : comap m (comap n f) = comap (n ∘ m) f := le_antisymm (λ c ⟨b, hb, (h : preimage (n ∘ m) b ⊆ c)⟩, ⟨preimage n b, preimage_mem_comap hb, h⟩) (λ c ⟨b, ⟨a, ha, (h₁ : preimage n a ⊆ b)⟩, (h₂ : preimage m b ⊆ c)⟩, ⟨a, ha, show preimage m (preimage n a) ⊆ c, from (preimage_mono h₁).trans h₂⟩) section comm variables {δ : Type*} /-! The variables in the following lemmas are used as in this diagram: ``` φ α → β θ ↓ ↓ ψ γ → δ ρ ``` -/ variables {φ : α → β} {θ : α → γ} {ψ : β → δ} {ρ : γ → δ} (H : ψ ∘ φ = ρ ∘ θ) include H lemma map_comm (F : filter α) : map ψ (map φ F) = map ρ (map θ F) := by rw [filter.map_map, H, ← filter.map_map] lemma comap_comm (G : filter δ) : comap φ (comap ψ G) = comap θ (comap ρ G) := by rw [filter.comap_comap, H, ← filter.comap_comap] end comm @[simp] theorem comap_principal {t : set β} : comap m (𝓟 t) = 𝓟 (m ⁻¹' t) := filter.ext $ λ s, ⟨λ ⟨u, (hu : t ⊆ u), (b : preimage m u ⊆ s)⟩, (preimage_mono hu).trans b, λ h, ⟨t, subset.refl t, h⟩⟩ @[simp] theorem comap_pure {b : β} : comap m (pure b) = 𝓟 (m ⁻¹' {b}) := by rw [← principal_singleton, comap_principal] lemma map_le_iff_le_comap : map m f ≤ g ↔ f ≤ comap m g := ⟨λ h s ⟨t, ht, hts⟩, mem_of_superset (h ht) hts, λ h s ht, h ⟨_, ht, subset.rfl⟩⟩ lemma gc_map_comap (m : α → β) : galois_connection (map m) (comap m) := λ f g, map_le_iff_le_comap @[mono] lemma map_mono : monotone (map m) := (gc_map_comap m).monotone_l @[mono] lemma comap_mono : monotone (comap m) := (gc_map_comap m).monotone_u @[simp] lemma map_bot : map m ⊥ = ⊥ := (gc_map_comap m).l_bot @[simp] lemma map_sup : map m (f₁ ⊔ f₂) = map m f₁ ⊔ map m f₂ := (gc_map_comap m).l_sup @[simp] lemma map_supr {f : ι → filter α} : map m (⨆ i, f i) = (⨆ i, map m (f i)) := (gc_map_comap m).l_supr @[simp] lemma comap_top : comap m ⊤ = ⊤ := (gc_map_comap m).u_top @[simp] lemma comap_inf : comap m (g₁ ⊓ g₂) = comap m g₁ ⊓ comap m g₂ := (gc_map_comap m).u_inf @[simp] lemma comap_infi {f : ι → filter β} : comap m (⨅ i, f i) = (⨅ i, comap m (f i)) := (gc_map_comap m).u_infi lemma le_comap_top (f : α → β) (l : filter α) : l ≤ comap f ⊤ := by { rw [comap_top], exact le_top } lemma map_comap_le : map m (comap m g) ≤ g := (gc_map_comap m).l_u_le _ lemma le_comap_map : f ≤ comap m (map m f) := (gc_map_comap m).le_u_l _ @[simp] lemma comap_bot : comap m ⊥ = ⊥ := bot_unique $ λ s _, ⟨∅, by simp only [mem_bot], by simp only [empty_subset, preimage_empty]⟩ lemma disjoint_comap (h : disjoint g₁ g₂) : disjoint (comap m g₁) (comap m g₂) := by simp only [disjoint_iff, ← comap_inf, h.eq_bot, comap_bot] lemma comap_supr {ι} {f : ι → filter β} {m : α → β} : comap m (supr f) = (⨆ i, comap m (f i)) := le_antisymm (λ s hs, have ∀ i, ∃ t, t ∈ f i ∧ m ⁻¹' t ⊆ s, by simpa only [mem_comap, exists_prop, mem_supr] using mem_supr.1 hs, let ⟨t, ht⟩ := classical.axiom_of_choice this in ⟨⋃ i, t i, mem_supr.2 $ λ i, (f i).sets_of_superset (ht i).1 (subset_Union _ _), begin rw [preimage_Union, Union_subset_iff], exact λ i, (ht i).2 end⟩) (supr_le $ λ i, comap_mono $ le_supr _ _) lemma comap_Sup {s : set (filter β)} {m : α → β} : comap m (Sup s) = (⨆ f ∈ s, comap m f) := by simp only [Sup_eq_supr, comap_supr, eq_self_iff_true] lemma comap_sup : comap m (g₁ ⊔ g₂) = comap m g₁ ⊔ comap m g₂ := by rw [sup_eq_supr, comap_supr, supr_bool_eq, bool.cond_tt, bool.cond_ff] lemma map_comap (f : filter β) (m : α → β) : (f.comap m).map m = f ⊓ 𝓟 (range m) := begin refine le_antisymm (le_inf map_comap_le $ le_principal_iff.2 range_mem_map) _, rintro t' ⟨t, ht, sub⟩, refine mem_inf_principal.2 (mem_of_superset ht _), rintro _ hxt ⟨x, rfl⟩, exact sub hxt end lemma map_comap_of_mem {f : filter β} {m : α → β} (hf : range m ∈ f) : (f.comap m).map m = f := by rw [map_comap, inf_eq_left.2 (le_principal_iff.2 hf)] instance [can_lift α β] : can_lift (filter α) (filter β) := { coe := map can_lift.coe, cond := λ f, ∀ᶠ x : α in f, can_lift.cond β x, prf := λ f hf, ⟨comap can_lift.coe f, map_comap_of_mem $ hf.mono can_lift.prf⟩ } lemma comap_le_comap_iff {f g : filter β} {m : α → β} (hf : range m ∈ f) : comap m f ≤ comap m g ↔ f ≤ g := ⟨λ h, map_comap_of_mem hf ▸ (map_mono h).trans map_comap_le, λ h, comap_mono h⟩ theorem map_comap_of_surjective {f : α → β} (hf : surjective f) (l : filter β) : map f (comap f l) = l := map_comap_of_mem $ by simp only [hf.range_eq, univ_mem] lemma _root_.function.surjective.filter_map_top {f : α → β} (hf : surjective f) : map f ⊤ = ⊤ := (congr_arg _ comap_top).symm.trans $ map_comap_of_surjective hf ⊤ lemma subtype_coe_map_comap (s : set α) (f : filter α) : map (coe : s → α) (comap (coe : s → α) f) = f ⊓ 𝓟 s := by rw [map_comap, subtype.range_coe] lemma subtype_coe_map_comap_prod (s : set α) (f : filter (α × α)) : map (coe : s × s → α × α) (comap (coe : s × s → α × α) f) = f ⊓ 𝓟 (s ×ˢ s) := have (coe : s × s → α × α) = (λ x, (x.1, x.2)), by ext ⟨x, y⟩; refl, by simp [this, map_comap, ← prod_range_range_eq] lemma image_mem_of_mem_comap {f : filter α} {c : β → α} (h : range c ∈ f) {W : set β} (W_in : W ∈ comap c f) : c '' W ∈ f := begin rw ← map_comap_of_mem h, exact image_mem_map W_in end lemma image_coe_mem_of_mem_comap {f : filter α} {U : set α} (h : U ∈ f) {W : set U} (W_in : W ∈ comap (coe : U → α) f) : coe '' W ∈ f := image_mem_of_mem_comap (by simp [h]) W_in lemma comap_map {f : filter α} {m : α → β} (h : injective m) : comap m (map m f) = f := le_antisymm (λ s hs, mem_of_superset (preimage_mem_comap $ image_mem_map hs) $ by simp only [preimage_image_eq s h]) le_comap_map lemma mem_comap_iff {f : filter β} {m : α → β} (inj : injective m) (large : set.range m ∈ f) {S : set α} : S ∈ comap m f ↔ m '' S ∈ f := by rw [← image_mem_map_iff inj, map_comap_of_mem large] lemma le_of_map_le_map_inj' {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀ x ∈ s, ∀ y ∈ s, m x = m y → x = y) (h : map m f ≤ map m g) : f ≤ g := λ t ht, by filter_upwards [hsf, h $ image_mem_map (inter_mem hsg ht)] using λ _ has ⟨_, ⟨hbs, hb⟩, h⟩, hm _ hbs _ has h ▸ hb lemma le_of_map_le_map_inj_iff {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀ x ∈ s, ∀ y ∈ s, m x = m y → x = y) : map m f ≤ map m g ↔ f ≤ g := iff.intro (le_of_map_le_map_inj' hsf hsg hm) (λ h, map_mono h) lemma eq_of_map_eq_map_inj' {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀ x ∈ s, ∀ y ∈ s, m x = m y → x = y) (h : map m f = map m g) : f = g := le_antisymm (le_of_map_le_map_inj' hsf hsg hm $ le_of_eq h) (le_of_map_le_map_inj' hsg hsf hm $ le_of_eq h.symm) lemma map_inj {f g : filter α} {m : α → β} (hm : injective m) (h : map m f = map m g) : f = g := have comap m (map m f) = comap m (map m g), by rw h, by rwa [comap_map hm, comap_map hm] at this lemma comap_ne_bot_iff {f : filter β} {m : α → β} : ne_bot (comap m f) ↔ ∀ t ∈ f, ∃ a, m a ∈ t := begin rw ← forall_mem_nonempty_iff_ne_bot, exact ⟨λ h t t_in, h (m ⁻¹' t) ⟨t, t_in, subset.rfl⟩, λ h s ⟨u, u_in, hu⟩, let ⟨x, hx⟩ := h u u_in in ⟨x, hu hx⟩⟩, end lemma comap_ne_bot {f : filter β} {m : α → β} (hm : ∀ t ∈ f, ∃ a, m a ∈ t) : ne_bot (comap m f) := comap_ne_bot_iff.mpr hm lemma comap_ne_bot_iff_frequently {f : filter β} {m : α → β} : ne_bot (comap m f) ↔ ∃ᶠ y in f, y ∈ range m := by simp [comap_ne_bot_iff, frequently_iff, ← exists_and_distrib_left, and.comm] lemma comap_ne_bot_iff_compl_range {f : filter β} {m : α → β} : ne_bot (comap m f) ↔ (range m)ᶜ ∉ f := comap_ne_bot_iff_frequently lemma ne_bot.comap_of_range_mem {f : filter β} {m : α → β} (hf : ne_bot f) (hm : range m ∈ f) : ne_bot (comap m f) := comap_ne_bot_iff_frequently.2 $ eventually.frequently hm @[simp] lemma comap_fst_ne_bot_iff {f : filter α} : (f.comap (prod.fst : α × β → α)).ne_bot ↔ f.ne_bot ∧ nonempty β := begin casesI is_empty_or_nonempty β, { rw [filter_eq_bot_of_is_empty (f.comap _), ← not_iff_not]; [simp *, apply_instance] }, { simp [comap_ne_bot_iff_frequently, h] } end @[instance] lemma comap_fst_ne_bot [nonempty β] {f : filter α} [ne_bot f] : (f.comap (prod.fst : α × β → α)).ne_bot := comap_fst_ne_bot_iff.2 ⟨‹_›, ‹_›⟩ @[simp] lemma comap_snd_ne_bot_iff {f : filter β} : (f.comap (prod.snd : α × β → β)).ne_bot ↔ nonempty α ∧ f.ne_bot := begin casesI is_empty_or_nonempty α with hα hα, { rw [filter_eq_bot_of_is_empty (f.comap _), ← not_iff_not]; [simpa using hα.elim, apply_instance] }, { simp [comap_ne_bot_iff_frequently, hα] } end @[instance] lemma comap_snd_ne_bot [nonempty α] {f : filter β} [ne_bot f] : (f.comap (prod.snd : α × β → β)).ne_bot := comap_snd_ne_bot_iff.2 ⟨‹_›, ‹_›⟩ lemma comap_eval_ne_bot_iff' {ι : Type*} {α : ι → Type*} {i : ι} {f : filter (α i)} : (comap (eval i) f).ne_bot ↔ (∀ j, nonempty (α j)) ∧ ne_bot f := begin casesI is_empty_or_nonempty (Π j, α j) with H H, { rw [filter_eq_bot_of_is_empty (f.comap _), ← not_iff_not]; [skip, assumption], simpa [← classical.nonempty_pi] using H.elim }, { haveI : ∀ j, nonempty (α j), from classical.nonempty_pi.1 H, simp [comap_ne_bot_iff_frequently, *] } end @[simp] lemma comap_eval_ne_bot_iff {ι : Type*} {α : ι → Type*} [∀ j, nonempty (α j)] {i : ι} {f : filter (α i)} : (comap (eval i) f).ne_bot ↔ ne_bot f := by simp [comap_eval_ne_bot_iff', *] @[instance] lemma comap_eval_ne_bot {ι : Type*} {α : ι → Type*} [∀ j, nonempty (α j)] (i : ι) (f : filter (α i)) [ne_bot f] : (comap (eval i) f).ne_bot := comap_eval_ne_bot_iff.2 ‹_› lemma comap_inf_principal_ne_bot_of_image_mem {f : filter β} {m : α → β} (hf : ne_bot f) {s : set α} (hs : m '' s ∈ f) : ne_bot (comap m f ⊓ 𝓟 s) := begin refine ⟨compl_compl s ▸ mt mem_of_eq_bot _⟩, rintro ⟨t, ht, hts⟩, rcases hf.nonempty_of_mem (inter_mem hs ht) with ⟨_, ⟨x, hxs, rfl⟩, hxt⟩, exact absurd hxs (hts hxt) end lemma comap_coe_ne_bot_of_le_principal {s : set γ} {l : filter γ} [h : ne_bot l] (h' : l ≤ 𝓟 s) : ne_bot (comap (coe : s → γ) l) := h.comap_of_range_mem $ (@subtype.range_coe γ s).symm ▸ h' (mem_principal_self s) lemma ne_bot.comap_of_surj {f : filter β} {m : α → β} (hf : ne_bot f) (hm : surjective m) : ne_bot (comap m f) := hf.comap_of_range_mem $ univ_mem' hm lemma ne_bot.comap_of_image_mem {f : filter β} {m : α → β} (hf : ne_bot f) {s : set α} (hs : m '' s ∈ f) : ne_bot (comap m f) := hf.comap_of_range_mem $ mem_of_superset hs (image_subset_range _ _) @[simp] lemma map_eq_bot_iff : map m f = ⊥ ↔ f = ⊥ := ⟨by { rw [←empty_mem_iff_bot, ←empty_mem_iff_bot], exact id }, λ h, by simp only [h, map_bot]⟩ lemma map_ne_bot_iff (f : α → β) {F : filter α} : ne_bot (map f F) ↔ ne_bot F := by simp only [ne_bot_iff, ne, map_eq_bot_iff] lemma ne_bot.map (hf : ne_bot f) (m : α → β) : ne_bot (map m f) := (map_ne_bot_iff m).2 hf instance map_ne_bot [hf : ne_bot f] : ne_bot (f.map m) := hf.map m lemma sInter_comap_sets (f : α → β) (F : filter β) : ⋂₀ (comap f F).sets = ⋂ U ∈ F, f ⁻¹' U := begin ext x, suffices : (∀ (A : set α) (B : set β), B ∈ F → f ⁻¹' B ⊆ A → x ∈ A) ↔ ∀ (B : set β), B ∈ F → f x ∈ B, by simp only [mem_sInter, mem_Inter, filter.mem_sets, mem_comap, this, and_imp, exists_prop, mem_preimage, exists_imp_distrib], split, { intros h U U_in, simpa only [subset.refl, forall_prop_of_true, mem_preimage] using h (f ⁻¹' U) U U_in }, { intros h V U U_in f_U_V, exact f_U_V (h U U_in) }, end end map -- this is a generic rule for monotone functions: lemma map_infi_le {f : ι → filter α} {m : α → β} : map m (infi f) ≤ (⨅ i, map m (f i)) := le_infi $ λ i, map_mono $ infi_le _ _ lemma map_infi_eq {f : ι → filter α} {m : α → β} (hf : directed (≥) f) [nonempty ι] : map m (infi f) = (⨅ i, map m (f i)) := map_infi_le.antisymm (λ s (hs : preimage m s ∈ infi f), let ⟨i, hi⟩ := (mem_infi_of_directed hf _).1 hs in have (⨅ i, map m (f i)) ≤ 𝓟 s, from infi_le_of_le i $ by { simp only [le_principal_iff, mem_map], assumption }, filter.le_principal_iff.1 this) lemma map_binfi_eq {ι : Type w} {f : ι → filter α} {m : α → β} {p : ι → Prop} (h : directed_on (f ⁻¹'o (≥)) {x | p x}) (ne : ∃ i, p i) : map m (⨅ i (h : p i), f i) = (⨅ i (h : p i), map m (f i)) := begin haveI := nonempty_subtype.2 ne, simp only [infi_subtype'], exact map_infi_eq h.directed_coe end lemma map_inf_le {f g : filter α} {m : α → β} : map m (f ⊓ g) ≤ map m f ⊓ map m g := (@map_mono _ _ m).map_inf_le f g lemma map_inf {f g : filter α} {m : α → β} (h : injective m) : map m (f ⊓ g) = map m f ⊓ map m g := begin refine map_inf_le.antisymm _, rintro t ⟨s₁, hs₁, s₂, hs₂, ht : m ⁻¹' t = s₁ ∩ s₂⟩, refine mem_inf_of_inter (image_mem_map hs₁) (image_mem_map hs₂) _, rw [image_inter h, image_subset_iff, ht] end lemma map_inf' {f g : filter α} {m : α → β} {t : set α} (htf : t ∈ f) (htg : t ∈ g) (h : inj_on m t) : map m (f ⊓ g) = map m f ⊓ map m g := begin lift f to filter t using htf, lift g to filter t using htg, replace h : injective (m ∘ coe) := h.injective, simp only [map_map, ← map_inf subtype.coe_injective, map_inf h], end lemma disjoint_map {m : α → β} (hm : injective m) {f₁ f₂ : filter α} : disjoint (map m f₁) (map m f₂) ↔ disjoint f₁ f₂ := by simp only [disjoint_iff, ← map_inf hm, map_eq_bot_iff] lemma map_eq_comap_of_inverse {f : filter α} {m : α → β} {n : β → α} (h₁ : m ∘ n = id) (h₂ : n ∘ m = id) : map m f = comap n f := le_antisymm (λ b ⟨a, ha, (h : preimage n a ⊆ b)⟩, f.sets_of_superset ha $ calc a = preimage (n ∘ m) a : by simp only [h₂, preimage_id, eq_self_iff_true] ... ⊆ preimage m b : preimage_mono h) (λ b (hb : preimage m b ∈ f), ⟨preimage m b, hb, show preimage (m ∘ n) b ⊆ b, by simp only [h₁]; apply subset.refl⟩) lemma map_swap_eq_comap_swap {f : filter (α × β)} : prod.swap <$> f = comap prod.swap f := map_eq_comap_of_inverse prod.swap_swap_eq prod.swap_swap_eq lemma le_map {f : filter α} {m : α → β} {g : filter β} (h : ∀ s ∈ f, m '' s ∈ g) : g ≤ f.map m := λ s hs, mem_of_superset (h _ hs) $ image_preimage_subset _ _ protected lemma push_pull (f : α → β) (F : filter α) (G : filter β) : map f (F ⊓ comap f G) = map f F ⊓ G := begin apply le_antisymm, { calc map f (F ⊓ comap f G) ≤ map f F ⊓ (map f $ comap f G) : map_inf_le ... ≤ map f F ⊓ G : inf_le_inf_left (map f F) map_comap_le }, { rintro U ⟨V, V_in, W, ⟨Z, Z_in, hZ⟩, h⟩, apply mem_inf_of_inter (image_mem_map V_in) Z_in, calc f '' V ∩ Z = f '' (V ∩ f ⁻¹' Z) : by rw image_inter_preimage ... ⊆ f '' (V ∩ W) : image_subset _ (inter_subset_inter_right _ ‹_›) ... = f '' (f ⁻¹' U) : by rw h ... ⊆ U : image_preimage_subset f U } end protected lemma push_pull' (f : α → β) (F : filter α) (G : filter β) : map f (comap f G ⊓ F) = G ⊓ map f F := by simp only [filter.push_pull, inf_comm] section applicative lemma singleton_mem_pure {a : α} : {a} ∈ (pure a : filter α) := mem_singleton a lemma pure_injective : injective (pure : α → filter α) := λ a b hab, (filter.ext_iff.1 hab {x | a = x}).1 rfl instance pure_ne_bot {α : Type u} {a : α} : ne_bot (pure a) := ⟨mt empty_mem_iff_bot.2 $ not_mem_empty a⟩ @[simp] lemma le_pure_iff {f : filter α} {a : α} : f ≤ pure a ↔ {a} ∈ f := ⟨λ h, h singleton_mem_pure, λ h s hs, mem_of_superset h $ singleton_subset_iff.2 hs⟩ lemma mem_seq_def {f : filter (α → β)} {g : filter α} {s : set β} : s ∈ f.seq g ↔ (∃ u ∈ f, ∃ t ∈ g, ∀ x ∈ u, ∀ y ∈ t, (x : α → β) y ∈ s) := iff.rfl lemma mem_seq_iff {f : filter (α → β)} {g : filter α} {s : set β} : s ∈ f.seq g ↔ (∃ u ∈ f, ∃ t ∈ g, set.seq u t ⊆ s) := by simp only [mem_seq_def, seq_subset, exists_prop, iff_self] lemma mem_map_seq_iff {f : filter α} {g : filter β} {m : α → β → γ} {s : set γ} : s ∈ (f.map m).seq g ↔ (∃ t u, t ∈ g ∧ u ∈ f ∧ ∀ x ∈ u, ∀ y ∈ t, m x y ∈ s) := iff.intro (λ ⟨t, ht, s, hs, hts⟩, ⟨s, m ⁻¹' t, hs, ht, λ a, hts _⟩) (λ ⟨t, s, ht, hs, hts⟩, ⟨m '' s, image_mem_map hs, t, ht, λ f ⟨a, has, eq⟩, eq ▸ hts _ has⟩) lemma seq_mem_seq {f : filter (α → β)} {g : filter α} {s : set (α → β)} {t : set α} (hs : s ∈ f) (ht : t ∈ g) : s.seq t ∈ f.seq g := ⟨s, hs, t, ht, λ f hf a ha, ⟨f, hf, a, ha, rfl⟩⟩ lemma le_seq {f : filter (α → β)} {g : filter α} {h : filter β} (hh : ∀ t ∈ f, ∀ u ∈ g, set.seq t u ∈ h) : h ≤ seq f g := λ s ⟨t, ht, u, hu, hs⟩, mem_of_superset (hh _ ht _ hu) $ λ b ⟨m, hm, a, ha, eq⟩, eq ▸ hs _ hm _ ha @[mono] lemma seq_mono {f₁ f₂ : filter (α → β)} {g₁ g₂ : filter α} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁.seq g₁ ≤ f₂.seq g₂ := le_seq $ λ s hs t ht, seq_mem_seq (hf hs) (hg ht) @[simp] lemma pure_seq_eq_map (g : α → β) (f : filter α) : seq (pure g) f = f.map g := begin refine le_antisymm (le_map $ λ s hs, _) (le_seq $ λ s hs t ht, _), { rw ← singleton_seq, apply seq_mem_seq _ hs, exact singleton_mem_pure }, { refine sets_of_superset (map g f) (image_mem_map ht) _, rintro b ⟨a, ha, rfl⟩, exact ⟨g, hs, a, ha, rfl⟩ } end @[simp] lemma seq_pure (f : filter (α → β)) (a : α) : seq f (pure a) = map (λ g : α → β, g a) f := begin refine le_antisymm (le_map $ λ s hs, _) (le_seq $ λ s hs t ht, _), { rw ← seq_singleton, exact seq_mem_seq hs singleton_mem_pure }, { refine sets_of_superset (map (λg:α→β, g a) f) (image_mem_map hs) _, rintro b ⟨g, hg, rfl⟩, exact ⟨g, hg, a, ht, rfl⟩ } end @[simp] lemma seq_assoc (x : filter α) (g : filter (α → β)) (h : filter (β → γ)) : seq h (seq g x) = seq (seq (map (∘) h) g) x := begin refine le_antisymm (le_seq $ λ s hs t ht, _) (le_seq $ λ s hs t ht, _), { rcases mem_seq_iff.1 hs with ⟨u, hu, v, hv, hs⟩, rcases mem_map_iff_exists_image.1 hu with ⟨w, hw, hu⟩, refine mem_of_superset _ (set.seq_mono ((set.seq_mono hu subset.rfl).trans hs) subset.rfl), rw ← set.seq_seq, exact seq_mem_seq hw (seq_mem_seq hv ht) }, { rcases mem_seq_iff.1 ht with ⟨u, hu, v, hv, ht⟩, refine mem_of_superset _ (set.seq_mono subset.rfl ht), rw set.seq_seq, exact seq_mem_seq (seq_mem_seq (image_mem_map hs) hu) hv } end lemma prod_map_seq_comm (f : filter α) (g : filter β) : (map prod.mk f).seq g = seq (map (λ b a, (a, b)) g) f := begin refine le_antisymm (le_seq $ λ s hs t ht, _) (le_seq $ λ s hs t ht, _), { rcases mem_map_iff_exists_image.1 hs with ⟨u, hu, hs⟩, refine mem_of_superset _ (set.seq_mono hs subset.rfl), rw ← set.prod_image_seq_comm, exact seq_mem_seq (image_mem_map ht) hu }, { rcases mem_map_iff_exists_image.1 hs with ⟨u, hu, hs⟩, refine mem_of_superset _ (set.seq_mono hs subset.rfl), rw set.prod_image_seq_comm, exact seq_mem_seq (image_mem_map ht) hu } end instance : is_lawful_functor (filter : Type u → Type u) := { id_map := λ α f, map_id, comp_map := λ α β γ f g a, map_map.symm } instance : is_lawful_applicative (filter : Type u → Type u) := { pure_seq_eq_map := λ α β, pure_seq_eq_map, map_pure := λ α β, map_pure, seq_pure := λ α β, seq_pure, seq_assoc := λ α β γ, seq_assoc } instance : is_comm_applicative (filter : Type u → Type u) := ⟨λ α β f g, prod_map_seq_comm f g⟩ lemma {l} seq_eq_filter_seq {α β : Type l} (f : filter (α → β)) (g : filter α) : f <*> g = seq f g := rfl end applicative /-! #### `bind` equations -/ section bind @[simp] lemma eventually_bind {f : filter α} {m : α → filter β} {p : β → Prop} : (∀ᶠ y in bind f m, p y) ↔ ∀ᶠ x in f, ∀ᶠ y in m x, p y := iff.rfl @[simp] lemma eventually_eq_bind {f : filter α} {m : α → filter β} {g₁ g₂ : β → γ} : (g₁ =ᶠ[bind f m] g₂) ↔ ∀ᶠ x in f, g₁ =ᶠ[m x] g₂ := iff.rfl @[simp] lemma eventually_le_bind [has_le γ] {f : filter α} {m : α → filter β} {g₁ g₂ : β → γ} : (g₁ ≤ᶠ[bind f m] g₂) ↔ ∀ᶠ x in f, g₁ ≤ᶠ[m x] g₂ := iff.rfl lemma mem_bind' {s : set β} {f : filter α} {m : α → filter β} : s ∈ bind f m ↔ {a | s ∈ m a} ∈ f := iff.rfl @[simp] lemma mem_bind {s : set β} {f : filter α} {m : α → filter β} : s ∈ bind f m ↔ ∃ t ∈ f, ∀ x ∈ t, s ∈ m x := calc s ∈ bind f m ↔ {a | s ∈ m a} ∈ f : iff.rfl ... ↔ (∃ t ∈ f, t ⊆ {a | s ∈ m a}) : exists_mem_subset_iff.symm ... ↔ (∃ t ∈ f, ∀ x ∈ t, s ∈ m x) : iff.rfl lemma bind_le {f : filter α} {g : α → filter β} {l : filter β} (h : ∀ᶠ x in f, g x ≤ l) : f.bind g ≤ l := join_le $ eventually_map.2 h @[mono] lemma bind_mono {f₁ f₂ : filter α} {g₁ g₂ : α → filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ᶠ[f₁] g₂) : bind f₁ g₁ ≤ bind f₂ g₂ := begin refine le_trans (λ s hs, _) (join_mono $ map_mono hf), simp only [mem_join, mem_bind', mem_map] at hs ⊢, filter_upwards [hg, hs] with _ hx hs using hx hs, end lemma bind_inf_principal {f : filter α} {g : α → filter β} {s : set β} : f.bind (λ x, g x ⊓ 𝓟 s) = (f.bind g) ⊓ 𝓟 s := filter.ext $ λ s, by simp only [mem_bind, mem_inf_principal] lemma sup_bind {f g : filter α} {h : α → filter β} : bind (f ⊔ g) h = bind f h ⊔ bind g h := by simp only [bind, sup_join, map_sup, eq_self_iff_true] lemma principal_bind {s : set α} {f : α → filter β} : (bind (𝓟 s) f) = (⨆ x ∈ s, f x) := show join (map f (𝓟 s)) = (⨆ x ∈ s, f x), by simp only [Sup_image, join_principal_eq_Sup, map_principal, eq_self_iff_true] end bind section list_traverse /- This is a separate section in order to open `list`, but mostly because of universe equality requirements in `traverse` -/ open list lemma sequence_mono : ∀ (as bs : list (filter α)), forall₂ (≤) as bs → sequence as ≤ sequence bs | [] [] forall₂.nil := le_rfl | (a :: as) (b :: bs) (forall₂.cons h hs) := seq_mono (map_mono h) (sequence_mono as bs hs) variables {α' β' γ' : Type u} {f : β' → filter α'} {s : γ' → set α'} lemma mem_traverse : ∀ (fs : list β') (us : list γ'), forall₂ (λ b c, s c ∈ f b) fs us → traverse s us ∈ traverse f fs | [] [] forall₂.nil := mem_pure.2 $ mem_singleton _ | (f :: fs) (u :: us) (forall₂.cons h hs) := seq_mem_seq (image_mem_map h) (mem_traverse fs us hs) lemma mem_traverse_iff (fs : list β') (t : set (list α')) : t ∈ traverse f fs ↔ (∃ us : list (set α'), forall₂ (λ b (s : set α'), s ∈ f b) fs us ∧ sequence us ⊆ t) := begin split, { induction fs generalizing t, case nil { simp only [sequence, mem_pure, imp_self, forall₂_nil_left_iff, exists_eq_left, set.pure_def, singleton_subset_iff, traverse_nil] }, case cons : b fs ih t { intro ht, rcases mem_seq_iff.1 ht with ⟨u, hu, v, hv, ht⟩, rcases mem_map_iff_exists_image.1 hu with ⟨w, hw, hwu⟩, rcases ih v hv with ⟨us, hus, hu⟩, exact ⟨w :: us, forall₂.cons hw hus, (set.seq_mono hwu hu).trans ht⟩ } }, { rintro ⟨us, hus, hs⟩, exact mem_of_superset (mem_traverse _ _ hus) hs } end end list_traverse /-! ### Limits -/ /-- `tendsto` is the generic "limit of a function" predicate. `tendsto f l₁ l₂` asserts that for every `l₂` neighborhood `a`, the `f`-preimage of `a` is an `l₁` neighborhood. -/ def tendsto (f : α → β) (l₁ : filter α) (l₂ : filter β) := l₁.map f ≤ l₂ lemma tendsto_def {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ ∀ s ∈ l₂, f ⁻¹' s ∈ l₁ := iff.rfl lemma tendsto_iff_eventually {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ ∀ ⦃p : β → Prop⦄, (∀ᶠ y in l₂, p y) → ∀ᶠ x in l₁, p (f x) := iff.rfl lemma tendsto.eventually {f : α → β} {l₁ : filter α} {l₂ : filter β} {p : β → Prop} (hf : tendsto f l₁ l₂) (h : ∀ᶠ y in l₂, p y) : ∀ᶠ x in l₁, p (f x) := hf h lemma tendsto.frequently {f : α → β} {l₁ : filter α} {l₂ : filter β} {p : β → Prop} (hf : tendsto f l₁ l₂) (h : ∃ᶠ x in l₁, p (f x)) : ∃ᶠ y in l₂, p y := mt hf.eventually h lemma tendsto.frequently_map {l₁ : filter α} {l₂ : filter β} {p : α → Prop} {q : β → Prop} (f : α → β) (c : filter.tendsto f l₁ l₂) (w : ∀ x, p x → q (f x)) (h : ∃ᶠ x in l₁, p x) : ∃ᶠ y in l₂, q y := c.frequently (h.mono w) @[simp] lemma tendsto_bot {f : α → β} {l : filter β} : tendsto f ⊥ l := by simp [tendsto] @[simp] lemma tendsto_top {f : α → β} {l : filter α} : tendsto f l ⊤ := le_top lemma le_map_of_right_inverse {mab : α → β} {mba : β → α} {f : filter α} {g : filter β} (h₁ : mab ∘ mba =ᶠ[g] id) (h₂ : tendsto mba g f) : g ≤ map mab f := by { rw [← @map_id _ g, ← map_congr h₁, ← map_map], exact map_mono h₂ } lemma tendsto_of_is_empty [is_empty α] {f : α → β} {la : filter α} {lb : filter β} : tendsto f la lb := by simp only [filter_eq_bot_of_is_empty la, tendsto_bot] lemma eventually_eq_of_left_inv_of_right_inv {f : α → β} {g₁ g₂ : β → α} {fa : filter α} {fb : filter β} (hleft : ∀ᶠ x in fa, g₁ (f x) = x) (hright : ∀ᶠ y in fb, f (g₂ y) = y) (htendsto : tendsto g₂ fb fa) : g₁ =ᶠ[fb] g₂ := (htendsto.eventually hleft).mp $ hright.mono $ λ y hr hl, (congr_arg g₁ hr.symm).trans hl lemma tendsto_iff_comap {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ l₁ ≤ l₂.comap f := map_le_iff_le_comap alias tendsto_iff_comap ↔ filter.tendsto.le_comap _ protected lemma tendsto.disjoint {f : α → β} {la₁ la₂ : filter α} {lb₁ lb₂ : filter β} (h₁ : tendsto f la₁ lb₁) (hd : disjoint lb₁ lb₂) (h₂ : tendsto f la₂ lb₂) : disjoint la₁ la₂ := (disjoint_comap hd).mono h₁.le_comap h₂.le_comap lemma tendsto_congr' {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (hl : f₁ =ᶠ[l₁] f₂) : tendsto f₁ l₁ l₂ ↔ tendsto f₂ l₁ l₂ := by rw [tendsto, tendsto, map_congr hl] lemma tendsto.congr' {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (hl : f₁ =ᶠ[l₁] f₂) (h : tendsto f₁ l₁ l₂) : tendsto f₂ l₁ l₂ := (tendsto_congr' hl).1 h theorem tendsto_congr {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (h : ∀ x, f₁ x = f₂ x) : tendsto f₁ l₁ l₂ ↔ tendsto f₂ l₁ l₂ := tendsto_congr' (univ_mem' h) theorem tendsto.congr {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (h : ∀ x, f₁ x = f₂ x) : tendsto f₁ l₁ l₂ → tendsto f₂ l₁ l₂ := (tendsto_congr h).1 lemma tendsto_id' {x y : filter α} : x ≤ y → tendsto id x y := by simp only [tendsto, map_id, forall_true_iff] {contextual := tt} lemma tendsto_id {x : filter α} : tendsto id x x := tendsto_id' $ le_refl x lemma tendsto.comp {f : α → β} {g : β → γ} {x : filter α} {y : filter β} {z : filter γ} (hg : tendsto g y z) (hf : tendsto f x y) : tendsto (g ∘ f) x z := calc map (g ∘ f) x = map g (map f x) : by rw [map_map] ... ≤ map g y : map_mono hf ... ≤ z : hg lemma tendsto.mono_left {f : α → β} {x y : filter α} {z : filter β} (hx : tendsto f x z) (h : y ≤ x) : tendsto f y z := (map_mono h).trans hx lemma tendsto.mono_right {f : α → β} {x : filter α} {y z : filter β} (hy : tendsto f x y) (hz : y ≤ z) : tendsto f x z := le_trans hy hz lemma tendsto.ne_bot {f : α → β} {x : filter α} {y : filter β} (h : tendsto f x y) [hx : ne_bot x] : ne_bot y := (hx.map _).mono h lemma tendsto_map {f : α → β} {x : filter α} : tendsto f x (map f x) := le_refl (map f x) lemma tendsto_map' {f : β → γ} {g : α → β} {x : filter α} {y : filter γ} (h : tendsto (f ∘ g) x y) : tendsto f (map g x) y := by rwa [tendsto, map_map] @[simp] lemma tendsto_map'_iff {f : β → γ} {g : α → β} {x : filter α} {y : filter γ} : tendsto f (map g x) y ↔ tendsto (f ∘ g) x y := by { rw [tendsto, map_map], refl } lemma tendsto_comap {f : α → β} {x : filter β} : tendsto f (comap f x) x := map_comap_le @[simp] lemma tendsto_comap_iff {f : α → β} {g : β → γ} {a : filter α} {c : filter γ} : tendsto f a (c.comap g) ↔ tendsto (g ∘ f) a c := ⟨λ h, tendsto_comap.comp h, λ h, map_le_iff_le_comap.mp $ by rwa [map_map]⟩ lemma tendsto_comap'_iff {m : α → β} {f : filter α} {g : filter β} {i : γ → α} (h : range i ∈ f) : tendsto (m ∘ i) (comap i f) g ↔ tendsto m f g := by { rw [tendsto, ← map_compose], simp only [(∘), map_comap_of_mem h, tendsto] } lemma tendsto.of_tendsto_comp {f : α → β} {g : β → γ} {a : filter α} {b : filter β} {c : filter γ} (hfg : tendsto (g ∘ f) a c) (hg : comap g c ≤ b) : tendsto f a b := begin rw tendsto_iff_comap at hfg ⊢, calc a ≤ comap (g ∘ f) c : hfg ... ≤ comap f b : by simpa [comap_comap] using comap_mono hg end lemma comap_eq_of_inverse {f : filter α} {g : filter β} {φ : α → β} (ψ : β → α) (eq : ψ ∘ φ = id) (hφ : tendsto φ f g) (hψ : tendsto ψ g f) : comap φ g = f := begin refine ((comap_mono $ map_le_iff_le_comap.1 hψ).trans _).antisymm (map_le_iff_le_comap.1 hφ), rw [comap_comap, eq, comap_id], exact le_rfl end lemma map_eq_of_inverse {f : filter α} {g : filter β} {φ : α → β} (ψ : β → α) (eq : φ ∘ ψ = id) (hφ : tendsto φ f g) (hψ : tendsto ψ g f) : map φ f = g := begin refine le_antisymm hφ (le_trans _ (map_mono hψ)), rw [map_map, eq, map_id], exact le_rfl end lemma tendsto_inf {f : α → β} {x : filter α} {y₁ y₂ : filter β} : tendsto f x (y₁ ⊓ y₂) ↔ tendsto f x y₁ ∧ tendsto f x y₂ := by simp only [tendsto, le_inf_iff, iff_self] lemma tendsto_inf_left {f : α → β} {x₁ x₂ : filter α} {y : filter β} (h : tendsto f x₁ y) : tendsto f (x₁ ⊓ x₂) y := le_trans (map_mono inf_le_left) h lemma tendsto_inf_right {f : α → β} {x₁ x₂ : filter α} {y : filter β} (h : tendsto f x₂ y) : tendsto f (x₁ ⊓ x₂) y := le_trans (map_mono inf_le_right) h lemma tendsto.inf {f : α → β} {x₁ x₂ : filter α} {y₁ y₂ : filter β} (h₁ : tendsto f x₁ y₁) (h₂ : tendsto f x₂ y₂) : tendsto f (x₁ ⊓ x₂) (y₁ ⊓ y₂) := tendsto_inf.2 ⟨tendsto_inf_left h₁, tendsto_inf_right h₂⟩ @[simp] lemma tendsto_infi {f : α → β} {x : filter α} {y : ι → filter β} : tendsto f x (⨅ i, y i) ↔ ∀ i, tendsto f x (y i) := by simp only [tendsto, iff_self, le_infi_iff] lemma tendsto_infi' {f : α → β} {x : ι → filter α} {y : filter β} (i : ι) (hi : tendsto f (x i) y) : tendsto f (⨅ i, x i) y := hi.mono_left $ infi_le _ _ @[simp] lemma tendsto_sup {f : α → β} {x₁ x₂ : filter α} {y : filter β} : tendsto f (x₁ ⊔ x₂) y ↔ tendsto f x₁ y ∧ tendsto f x₂ y := by simp only [tendsto, map_sup, sup_le_iff] lemma tendsto.sup {f : α → β} {x₁ x₂ : filter α} {y : filter β} : tendsto f x₁ y → tendsto f x₂ y → tendsto f (x₁ ⊔ x₂) y := λ h₁ h₂, tendsto_sup.mpr ⟨ h₁, h₂ ⟩ @[simp] lemma tendsto_supr {f : α → β} {x : ι → filter α} {y : filter β} : tendsto f (⨆ i, x i) y ↔ ∀ i, tendsto f (x i) y := by simp only [tendsto, map_supr, supr_le_iff] @[simp] lemma tendsto_principal {f : α → β} {l : filter α} {s : set β} : tendsto f l (𝓟 s) ↔ ∀ᶠ a in l, f a ∈ s := by simp only [tendsto, le_principal_iff, mem_map', filter.eventually] @[simp] lemma tendsto_principal_principal {f : α → β} {s : set α} {t : set β} : tendsto f (𝓟 s) (𝓟 t) ↔ ∀ a ∈ s, f a ∈ t := by simp only [tendsto_principal, eventually_principal] @[simp] lemma tendsto_pure {f : α → β} {a : filter α} {b : β} : tendsto f a (pure b) ↔ ∀ᶠ x in a, f x = b := by simp only [tendsto, le_pure_iff, mem_map', mem_singleton_iff, filter.eventually] lemma tendsto_pure_pure (f : α → β) (a : α) : tendsto f (pure a) (pure (f a)) := tendsto_pure.2 rfl lemma tendsto_const_pure {a : filter α} {b : β} : tendsto (λ x, b) a (pure b) := tendsto_pure.2 $ univ_mem' $ λ _, rfl lemma pure_le_iff {a : α} {l : filter α} : pure a ≤ l ↔ ∀ s ∈ l, a ∈ s := iff.rfl lemma tendsto_pure_left {f : α → β} {a : α} {l : filter β} : tendsto f (pure a) l ↔ ∀ s ∈ l, f a ∈ s := iff.rfl @[simp] lemma map_inf_principal_preimage {f : α → β} {s : set β} {l : filter α} : map f (l ⊓ 𝓟 (f ⁻¹' s)) = map f l ⊓ 𝓟 s := filter.ext $ λ t, by simp only [mem_map', mem_inf_principal, mem_set_of_eq, mem_preimage] /-- If two filters are disjoint, then a function cannot tend to both of them along a non-trivial filter. -/ lemma tendsto.not_tendsto {f : α → β} {a : filter α} {b₁ b₂ : filter β} (hf : tendsto f a b₁) [ne_bot a] (hb : disjoint b₁ b₂) : ¬ tendsto f a b₂ := λ hf', (tendsto_inf.2 ⟨hf, hf'⟩).ne_bot.ne hb.eq_bot lemma tendsto.if {l₁ : filter α} {l₂ : filter β} {f g : α → β} {p : α → Prop} [∀ x, decidable (p x)] (h₀ : tendsto f (l₁ ⊓ 𝓟 {x | p x}) l₂) (h₁ : tendsto g (l₁ ⊓ 𝓟 { x | ¬ p x }) l₂) : tendsto (λ x, if p x then f x else g x) l₁ l₂ := begin simp only [tendsto_def, mem_inf_principal] at *, intros s hs, filter_upwards [h₀ s hs, h₁ s hs], simp only [mem_preimage], intros x hp₀ hp₁, split_ifs, exacts [hp₀ h, hp₁ h], end lemma tendsto.piecewise {l₁ : filter α} {l₂ : filter β} {f g : α → β} {s : set α} [∀ x, decidable (x ∈ s)] (h₀ : tendsto f (l₁ ⊓ 𝓟 s) l₂) (h₁ : tendsto g (l₁ ⊓ 𝓟 sᶜ) l₂) : tendsto (piecewise s f g) l₁ l₂ := h₀.if h₁ /-! ### Products of filters -/ section prod variables {s : set α} {t : set β} {f : filter α} {g : filter β} /- The product filter cannot be defined using the monad structure on filters. For example: F := do {x ← seq, y ← top, return (x, y)} hence: s ∈ F ↔ ∃ n, [n..∞] × univ ⊆ s G := do {y ← top, x ← seq, return (x, y)} hence: s ∈ G ↔ ∀ i:ℕ, ∃ n, [n..∞] × {i} ⊆ s Now ⋃ i, [i..∞] × {i} is in G but not in F. As product filter we want to have F as result. -/ /-- Product of filters. This is the filter generated by cartesian products of elements of the component filters. -/ protected def prod (f : filter α) (g : filter β) : filter (α × β) := f.comap prod.fst ⊓ g.comap prod.snd localized "infix ` ×ᶠ `:60 := filter.prod" in filter lemma prod_mem_prod {s : set α} {t : set β} {f : filter α} {g : filter β} (hs : s ∈ f) (ht : t ∈ g) : s ×ˢ t ∈ f ×ᶠ g := inter_mem_inf (preimage_mem_comap hs) (preimage_mem_comap ht) lemma mem_prod_iff {s : set (α×β)} {f : filter α} {g : filter β} : s ∈ f ×ᶠ g ↔ (∃ t₁ ∈ f, ∃ t₂ ∈ g, t₁ ×ˢ t₂ ⊆ s) := begin simp only [filter.prod], split, { rintro ⟨t₁, ⟨s₁, hs₁, hts₁⟩, t₂, ⟨s₂, hs₂, hts₂⟩, rfl⟩, exact ⟨s₁, hs₁, s₂, hs₂, λ p ⟨h, h'⟩, ⟨hts₁ h, hts₂ h'⟩⟩ }, { rintro ⟨t₁, ht₁, t₂, ht₂, h⟩, exact mem_inf_of_inter (preimage_mem_comap ht₁) (preimage_mem_comap ht₂) h } end @[simp] lemma prod_mem_prod_iff {s : set α} {t : set β} {f : filter α} {g : filter β} [f.ne_bot] [g.ne_bot] : s ×ˢ t ∈ f ×ᶠ g ↔ s ∈ f ∧ t ∈ g := ⟨λ h, let ⟨s', hs', t', ht', H⟩ := mem_prod_iff.1 h in (prod_subset_prod_iff.1 H).elim (λ ⟨hs's, ht't⟩, ⟨mem_of_superset hs' hs's, mem_of_superset ht' ht't⟩) (λ h, h.elim (λ hs'e, absurd hs'e (nonempty_of_mem hs').ne_empty) (λ ht'e, absurd ht'e (nonempty_of_mem ht').ne_empty)), λ h, prod_mem_prod h.1 h.2⟩ lemma mem_prod_principal {f : filter α} {s : set (α × β)} {t : set β}: s ∈ f ×ᶠ 𝓟 t ↔ {a | ∀ b ∈ t, (a, b) ∈ s} ∈ f := begin rw [← @exists_mem_subset_iff _ f, mem_prod_iff], refine exists₂_congr (λ u u_in, ⟨_, λ h, ⟨t, mem_principal_self t, _⟩⟩), { rintros ⟨v, v_in, hv⟩ a a_in b b_in, exact hv (mk_mem_prod a_in $ v_in b_in) }, { rintro ⟨x, y⟩ ⟨hx, hy⟩, exact h hx y hy } end lemma mem_prod_top {f : filter α} {s : set (α × β)} : s ∈ f ×ᶠ (⊤ : filter β) ↔ {a | ∀ b, (a, b) ∈ s} ∈ f := begin rw [← principal_univ, mem_prod_principal], simp only [mem_univ, forall_true_left] end lemma comap_prod (f : α → β × γ) (b : filter β) (c : filter γ) : comap f (b ×ᶠ c) = (comap (prod.fst ∘ f) b) ⊓ (comap (prod.snd ∘ f) c) := by erw [comap_inf, filter.comap_comap, filter.comap_comap] lemma prod_top {f : filter α} : f ×ᶠ (⊤ : filter β) = f.comap prod.fst := by rw [filter.prod, comap_top, inf_top_eq] lemma sup_prod (f₁ f₂ : filter α) (g : filter β) : (f₁ ⊔ f₂) ×ᶠ g = (f₁ ×ᶠ g) ⊔ (f₂ ×ᶠ g) := by rw [filter.prod, comap_sup, inf_sup_right, ← filter.prod, ← filter.prod] lemma prod_sup (f : filter α) (g₁ g₂ : filter β) : f ×ᶠ (g₁ ⊔ g₂) = (f ×ᶠ g₁) ⊔ (f ×ᶠ g₂) := by rw [filter.prod, comap_sup, inf_sup_left, ← filter.prod, ← filter.prod] lemma eventually_prod_iff {p : α × β → Prop} {f : filter α} {g : filter β} : (∀ᶠ x in f ×ᶠ g, p x) ↔ ∃ (pa : α → Prop) (ha : ∀ᶠ x in f, pa x) (pb : β → Prop) (hb : ∀ᶠ y in g, pb y), ∀ {x}, pa x → ∀ {y}, pb y → p (x, y) := by simpa only [set.prod_subset_iff] using @mem_prod_iff α β p f g lemma tendsto_fst {f : filter α} {g : filter β} : tendsto prod.fst (f ×ᶠ g) f := tendsto_inf_left tendsto_comap lemma tendsto_snd {f : filter α} {g : filter β} : tendsto prod.snd (f ×ᶠ g) g := tendsto_inf_right tendsto_comap lemma tendsto.prod_mk {f : filter α} {g : filter β} {h : filter γ} {m₁ : α → β} {m₂ : α → γ} (h₁ : tendsto m₁ f g) (h₂ : tendsto m₂ f h) : tendsto (λ x, (m₁ x, m₂ x)) f (g ×ᶠ h) := tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩ lemma eventually.prod_inl {la : filter α} {p : α → Prop} (h : ∀ᶠ x in la, p x) (lb : filter β) : ∀ᶠ x in la ×ᶠ lb, p (x : α × β).1 := tendsto_fst.eventually h lemma eventually.prod_inr {lb : filter β} {p : β → Prop} (h : ∀ᶠ x in lb, p x) (la : filter α) : ∀ᶠ x in la ×ᶠ lb, p (x : α × β).2 := tendsto_snd.eventually h lemma eventually.prod_mk {la : filter α} {pa : α → Prop} (ha : ∀ᶠ x in la, pa x) {lb : filter β} {pb : β → Prop} (hb : ∀ᶠ y in lb, pb y) : ∀ᶠ p in la ×ᶠ lb, pa (p : α × β).1 ∧ pb p.2 := (ha.prod_inl lb).and (hb.prod_inr la) lemma eventually.curry {la : filter α} {lb : filter β} {p : α × β → Prop} (h : ∀ᶠ x in la ×ᶠ lb, p x) : ∀ᶠ x in la, ∀ᶠ y in lb, p (x, y) := begin rcases eventually_prod_iff.1 h with ⟨pa, ha, pb, hb, h⟩, exact ha.mono (λ a ha, hb.mono $ λ b hb, h ha hb) end lemma prod_infi_left [nonempty ι] {f : ι → filter α} {g : filter β}: (⨅ i, f i) ×ᶠ g = (⨅ i, (f i) ×ᶠ g) := by { rw [filter.prod, comap_infi, infi_inf], simp only [filter.prod, eq_self_iff_true] } lemma prod_infi_right [nonempty ι] {f : filter α} {g : ι → filter β} : f ×ᶠ (⨅ i, g i) = (⨅ i, f ×ᶠ (g i)) := by { rw [filter.prod, comap_infi, inf_infi], simp only [filter.prod, eq_self_iff_true] } @[mono] lemma prod_mono {f₁ f₂ : filter α} {g₁ g₂ : filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁ ×ᶠ g₁ ≤ f₂ ×ᶠ g₂ := inf_le_inf (comap_mono hf) (comap_mono hg) lemma prod_comap_comap_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : β₁ → α₁} {m₂ : β₂ → α₂} : (comap m₁ f₁) ×ᶠ (comap m₂ f₂) = comap (λ p : β₁×β₂, (m₁ p.1, m₂ p.2)) (f₁ ×ᶠ f₂) := by simp only [filter.prod, comap_comap, eq_self_iff_true, comap_inf] lemma prod_comm' : f ×ᶠ g = comap (prod.swap) (g ×ᶠ f) := by simp only [filter.prod, comap_comap, (∘), inf_comm, prod.fst_swap, eq_self_iff_true, prod.snd_swap, comap_inf] lemma prod_comm : f ×ᶠ g = map (λ p : β×α, (p.2, p.1)) (g ×ᶠ f) := by { rw [prod_comm', ← map_swap_eq_comap_swap], refl } lemma prod_map_map_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : α₁ → β₁} {m₂ : α₂ → β₂} : (map m₁ f₁) ×ᶠ (map m₂ f₂) = map (λ p : α₁×α₂, (m₁ p.1, m₂ p.2)) (f₁ ×ᶠ f₂) := le_antisymm (λ s hs, let ⟨s₁, hs₁, s₂, hs₂, h⟩ := mem_prod_iff.mp hs in filter.sets_of_superset _ (prod_mem_prod (image_mem_map hs₁) (image_mem_map hs₂)) $ calc m₁ '' s₁ ×ˢ m₂ '' s₂ = (λ p : α₁×α₂, (m₁ p.1, m₂ p.2)) '' (s₁ ×ˢ s₂) : set.prod_image_image_eq ... ⊆ _ : by rwa [image_subset_iff]) ((tendsto.comp le_rfl tendsto_fst).prod_mk (tendsto.comp le_rfl tendsto_snd)) lemma prod_map_map_eq' {α₁ : Type*} {α₂ : Type*} {β₁ : Type*} {β₂ : Type*} (f : α₁ → α₂) (g : β₁ → β₂) (F : filter α₁) (G : filter β₁) : (map f F) ×ᶠ (map g G) = map (prod.map f g) (F ×ᶠ G) := prod_map_map_eq lemma tendsto.prod_map {δ : Type*} {f : α → γ} {g : β → δ} {a : filter α} {b : filter β} {c : filter γ} {d : filter δ} (hf : tendsto f a c) (hg : tendsto g b d) : tendsto (prod.map f g) (a ×ᶠ b) (c ×ᶠ d) := begin erw [tendsto, ← prod_map_map_eq], exact filter.prod_mono hf hg, end lemma map_prod (m : α × β → γ) (f : filter α) (g : filter β) : map m (f ×ᶠ g) = (f.map (λ a b, m (a, b))).seq g := begin simp [filter.ext_iff, mem_prod_iff, mem_map_seq_iff], intro s, split, exact λ ⟨t, ht, s, hs, h⟩, ⟨s, hs, t, ht, λ x hx y hy, @h ⟨x, y⟩ ⟨hx, hy⟩⟩, exact λ ⟨s, hs, t, ht, h⟩, ⟨t, ht, s, hs, λ ⟨x, y⟩ ⟨hx, hy⟩, h x hx y hy⟩ end lemma prod_eq {f : filter α} {g : filter β} : f ×ᶠ g = (f.map prod.mk).seq g := have h : _ := map_prod id f g, by rwa [map_id] at h lemma prod_inf_prod {f₁ f₂ : filter α} {g₁ g₂ : filter β} : (f₁ ×ᶠ g₁) ⊓ (f₂ ×ᶠ g₂) = (f₁ ⊓ f₂) ×ᶠ (g₁ ⊓ g₂) := by simp only [filter.prod, comap_inf, inf_comm, inf_assoc, inf_left_comm] @[simp] lemma prod_bot {f : filter α} : f ×ᶠ (⊥ : filter β) = ⊥ := by simp [filter.prod] @[simp] lemma bot_prod {g : filter β} : (⊥ : filter α) ×ᶠ g = ⊥ := by simp [filter.prod] @[simp] lemma prod_principal_principal {s : set α} {t : set β} : (𝓟 s) ×ᶠ (𝓟 t) = 𝓟 (s ×ˢ t) := by simp only [filter.prod, comap_principal, principal_eq_iff_eq, comap_principal, inf_principal]; refl @[simp] lemma pure_prod {a : α} {f : filter β} : pure a ×ᶠ f = map (prod.mk a) f := by rw [prod_eq, map_pure, pure_seq_eq_map] @[simp] lemma prod_pure {f : filter α} {b : β} : f ×ᶠ pure b = map (λ a, (a, b)) f := by rw [prod_eq, seq_pure, map_map] lemma prod_pure_pure {a : α} {b : β} : (pure a) ×ᶠ (pure b) = pure (a, b) := by simp lemma prod_eq_bot {f : filter α} {g : filter β} : f ×ᶠ g = ⊥ ↔ (f = ⊥ ∨ g = ⊥) := begin split, { intro h, rcases mem_prod_iff.1 (empty_mem_iff_bot.2 h) with ⟨s, hs, t, ht, hst⟩, rw [subset_empty_iff, set.prod_eq_empty_iff] at hst, cases hst with s_eq t_eq, { left, exact empty_mem_iff_bot.1 (s_eq ▸ hs) }, { right, exact empty_mem_iff_bot.1 (t_eq ▸ ht) } }, { rintro (rfl | rfl), exact bot_prod, exact prod_bot } end lemma prod_ne_bot {f : filter α} {g : filter β} : ne_bot (f ×ᶠ g) ↔ (ne_bot f ∧ ne_bot g) := by simp only [ne_bot_iff, ne, prod_eq_bot, not_or_distrib] lemma ne_bot.prod {f : filter α} {g : filter β} (hf : ne_bot f) (hg : ne_bot g) : ne_bot (f ×ᶠ g) := prod_ne_bot.2 ⟨hf, hg⟩ instance prod_ne_bot' {f : filter α} {g : filter β} [hf : ne_bot f] [hg : ne_bot g] : ne_bot (f ×ᶠ g) := hf.prod hg lemma tendsto_prod_iff {f : α × β → γ} {x : filter α} {y : filter β} {z : filter γ} : filter.tendsto f (x ×ᶠ y) z ↔ ∀ W ∈ z, ∃ U ∈ x, ∃ V ∈ y, ∀ x y, x ∈ U → y ∈ V → f (x, y) ∈ W := by simp only [tendsto_def, mem_prod_iff, prod_sub_preimage_iff, exists_prop, iff_self] end prod /-! ### Coproducts of filters -/ section coprod variables {f : filter α} {g : filter β} /-- Coproduct of filters. -/ protected def coprod (f : filter α) (g : filter β) : filter (α × β) := f.comap prod.fst ⊔ g.comap prod.snd lemma mem_coprod_iff {s : set (α×β)} {f : filter α} {g : filter β} : s ∈ f.coprod g ↔ ((∃ t₁ ∈ f, prod.fst ⁻¹' t₁ ⊆ s) ∧ (∃ t₂ ∈ g, prod.snd ⁻¹' t₂ ⊆ s)) := by simp [filter.coprod] @[mono] lemma coprod_mono {f₁ f₂ : filter α} {g₁ g₂ : filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁.coprod g₁ ≤ f₂.coprod g₂ := sup_le_sup (comap_mono hf) (comap_mono hg) lemma coprod_ne_bot_iff : (f.coprod g).ne_bot ↔ f.ne_bot ∧ nonempty β ∨ nonempty α ∧ g.ne_bot := by simp [filter.coprod] @[instance] lemma coprod_ne_bot_left [ne_bot f] [nonempty β] : (f.coprod g).ne_bot := coprod_ne_bot_iff.2 (or.inl ⟨‹_›, ‹_›⟩) @[instance] lemma coprod_ne_bot_right [ne_bot g] [nonempty α] : (f.coprod g).ne_bot := coprod_ne_bot_iff.2 (or.inr ⟨‹_›, ‹_›⟩) lemma principal_coprod_principal (s : set α) (t : set β) : (𝓟 s).coprod (𝓟 t) = 𝓟 (sᶜ ×ˢ tᶜ)ᶜ := begin rw [filter.coprod, comap_principal, comap_principal, sup_principal], congr, ext x, simp ; tauto, end -- this inequality can be strict; see `map_const_principal_coprod_map_id_principal` and -- `map_prod_map_const_id_principal_coprod_principal` below. lemma map_prod_map_coprod_le {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : α₁ → β₁} {m₂ : α₂ → β₂} : map (prod.map m₁ m₂) (f₁.coprod f₂) ≤ (map m₁ f₁).coprod (map m₂ f₂) := begin intros s, simp only [mem_map, mem_coprod_iff], rintro ⟨⟨u₁, hu₁, h₁⟩, u₂, hu₂, h₂⟩, refine ⟨⟨m₁ ⁻¹' u₁, hu₁, λ _ hx, h₁ _⟩, ⟨m₂ ⁻¹' u₂, hu₂, λ _ hx, h₂ _⟩⟩; convert hx end /-- Characterization of the coproduct of the `filter.map`s of two principal filters `𝓟 {a}` and `𝓟 {i}`, the first under the constant function `λ a, b` and the second under the identity function. Together with the next lemma, `map_prod_map_const_id_principal_coprod_principal`, this provides an example showing that the inequality in the lemma `map_prod_map_coprod_le` can be strict. -/ lemma map_const_principal_coprod_map_id_principal {α β ι : Type*} (a : α) (b : β) (i : ι) : (map (λ _ : α, b) (𝓟 {a})).coprod (map id (𝓟 {i})) = 𝓟 (({b} : set β) ×ˢ (univ : set ι) ∪ (univ : set β) ×ˢ ({i} : set ι)) := begin rw [map_principal, map_principal, principal_coprod_principal], congr, ext ⟨b', i'⟩, simp, tauto, end /-- Characterization of the `filter.map` of the coproduct of two principal filters `𝓟 {a}` and `𝓟 {i}`, under the `prod.map` of two functions, respectively the constant function `λ a, b` and the identity function. Together with the previous lemma, `map_const_principal_coprod_map_id_principal`, this provides an example showing that the inequality in the lemma `map_prod_map_coprod_le` can be strict. -/ lemma map_prod_map_const_id_principal_coprod_principal {α β ι : Type*} (a : α) (b : β) (i : ι) : map (prod.map (λ _ : α, b) id) ((𝓟 {a}).coprod (𝓟 {i})) = 𝓟 (({b} : set β) ×ˢ (univ : set ι)) := begin rw [principal_coprod_principal, map_principal], congr, ext ⟨b', i'⟩, split, { rintro ⟨⟨a'', i''⟩, h₁, h₂, h₃⟩, simp }, { rintro ⟨h₁, h₂⟩, use (a, i'), simpa using h₁.symm } end lemma tendsto.prod_map_coprod {δ : Type*} {f : α → γ} {g : β → δ} {a : filter α} {b : filter β} {c : filter γ} {d : filter δ} (hf : tendsto f a c) (hg : tendsto g b d) : tendsto (prod.map f g) (a.coprod b) (c.coprod d) := map_prod_map_coprod_le.trans (coprod_mono hf hg) end coprod end filter open_locale filter lemma set.eq_on.eventually_eq {α β} {s : set α} {f g : α → β} (h : eq_on f g s) : f =ᶠ[𝓟 s] g := h lemma set.eq_on.eventually_eq_of_mem {α β} {s : set α} {l : filter α} {f g : α → β} (h : eq_on f g s) (hl : s ∈ l) : f =ᶠ[l] g := h.eventually_eq.filter_mono $ filter.le_principal_iff.2 hl lemma set.subset.eventually_le {α} {l : filter α} {s t : set α} (h : s ⊆ t) : s ≤ᶠ[l] t := filter.eventually_of_forall h lemma set.maps_to.tendsto {α β} {s : set α} {t : set β} {f : α → β} (h : maps_to f s t) : filter.tendsto f (𝓟 s) (𝓟 t) := filter.tendsto_principal_principal.2 h
c0ffa2c44b3f84b292f19ab2767ebea6476110d8
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/topology/uniform_space/separation.lean
b1b65c00ed2a8b9040a953f0b5adb2d36bb3ef28
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
13,603
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, Patrick Massot Hausdorff properties of uniform spaces. Separation quotient. -/ import topology.uniform_space.basic open filter topological_space lattice set classical local attribute [instance, priority 0] prop_decidable noncomputable theory set_option eqn_compiler.zeta true universes u v w variables {α : Type u} {β : Type v} {γ : Type w} variables [uniform_space α] [uniform_space β] [uniform_space γ] local notation `𝓤` := uniformity /- separated uniformity -/ /-- The separation relation is the intersection of all entourages. Two points which are related by the separation relation are "indistinguishable" according to the uniform structure. -/ protected def separation_rel (α : Type u) [u : uniform_space α] := ⋂₀ (𝓤 α).sets lemma separated_equiv : equivalence (λx y, (x, y) ∈ separation_rel α) := ⟨assume x, assume s, refl_mem_uniformity, assume x y, assume h (s : set (α×α)) hs, have preimage prod.swap s ∈ 𝓤 α, from symm_le_uniformity hs, h _ this, assume x y z (hxy : (x, y) ∈ separation_rel α) (hyz : (y, z) ∈ separation_rel α) s (hs : s ∈ 𝓤 α), let ⟨t, ht, (h_ts : comp_rel t t ⊆ s)⟩ := comp_mem_uniformity_sets hs in h_ts $ show (x, z) ∈ comp_rel t t, from ⟨y, hxy t ht, hyz t ht⟩⟩ @[class] def separated (α : Type u) [uniform_space α] := separation_rel α = id_rel theorem separated_def {α : Type u} [uniform_space α] : separated α ↔ ∀ x y, (∀ r ∈ 𝓤 α, (x, y) ∈ r) → x = y := by simp [separated, id_rel_subset.2 separated_equiv.1, subset.antisymm_iff]; simp [subset_def, separation_rel] theorem separated_def' {α : Type u} [uniform_space α] : separated α ↔ ∀ x y, x ≠ y → ∃ r ∈ 𝓤 α, (x, y) ∉ r := separated_def.trans $ forall_congr $ λ x, forall_congr $ λ y, by rw ← not_imp_not; simp [classical.not_forall] instance separated_t2 [s : separated α] : t2_space α := ⟨assume x y, assume h : x ≠ y, let ⟨d, hd, (hxy : (x, y) ∉ d)⟩ := separated_def'.1 s x y h in let ⟨d', hd', (hd'd' : comp_rel d' d' ⊆ d)⟩ := comp_mem_uniformity_sets hd in have {y | (x, y) ∈ d'} ∈ nhds x, from mem_nhds_left x hd', let ⟨u, hu₁, hu₂, hu₃⟩ := mem_nhds_sets_iff.mp this in have {x | (x, y) ∈ d'} ∈ nhds y, from mem_nhds_right y hd', let ⟨v, hv₁, hv₂, hv₃⟩ := mem_nhds_sets_iff.mp this in have u ∩ v = ∅, from eq_empty_of_subset_empty $ assume z ⟨(h₁ : z ∈ u), (h₂ : z ∈ v)⟩, have (x, y) ∈ comp_rel d' d', from ⟨z, hu₁ h₁, hv₁ h₂⟩, hxy $ hd'd' this, ⟨u, v, hu₂, hv₂, hu₃, hv₃, this⟩⟩ instance separated_regular [separated α] : regular_space α := { regular := λs a hs ha, have -s ∈ nhds a, from mem_nhds_sets hs ha, have {p : α × α | p.1 = a → p.2 ∈ -s} ∈ 𝓤 α, from mem_nhds_uniformity_iff.mp this, let ⟨d, hd, h⟩ := comp_mem_uniformity_sets this in let e := {y:α| (a, y) ∈ d} in have hae : a ∈ closure e, from subset_closure $ refl_mem_uniformity hd, have set.prod (closure e) (closure e) ⊆ comp_rel d (comp_rel (set.prod e e) d), begin rw [←closure_prod_eq, closure_eq_inter_uniformity], change (⨅d' ∈ 𝓤 α, _) ≤ comp_rel d (comp_rel _ d), exact (infi_le_of_le d $ infi_le_of_le hd $ le_refl _) end, have e_subset : closure e ⊆ -s, from assume a' ha', let ⟨x, (hx : (a, x) ∈ d), y, ⟨hx₁, hx₂⟩, (hy : (y, _) ∈ d)⟩ := @this ⟨a, a'⟩ ⟨hae, ha'⟩ in have (a, a') ∈ comp_rel d d, from ⟨y, hx₂, hy⟩, h this rfl, have closure e ∈ nhds a, from (nhds a).sets_of_superset (mem_nhds_left a hd) subset_closure, have nhds a ⊓ principal (-closure e) = ⊥, from (@inf_eq_bot_iff_le_compl _ _ _ (principal (- closure e)) (principal (closure e)) (by simp [principal_univ, union_comm]) (by simp)).mpr (by simp [this]), ⟨- closure e, is_closed_closure, assume x h₁ h₂, @e_subset x h₂ h₁, this⟩, ..separated_t2 } /- separation space -/ namespace uniform_space def separation_setoid (α : Type u) [uniform_space α] : setoid α := ⟨λx y, (x, y) ∈ separation_rel α, separated_equiv⟩ local attribute [instance] separation_setoid instance {α : Type u} [u : uniform_space α] : uniform_space (quotient (separation_setoid α)) := { to_topological_space := u.to_topological_space.coinduced (λx, ⟦x⟧), uniformity := map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) u.uniformity, refl := le_trans (by simp [quotient.exists_rep]) (filter.map_mono refl_le_uniformity), symm := tendsto_map' $ by simp [prod.swap, (∘)]; exact tendsto_map.comp tendsto_swap_uniformity, comp := calc (map (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) u.uniformity).lift' (λs, comp_rel s s) = u.uniformity.lift' ((λs, comp_rel s s) ∘ image (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧))) : map_lift'_eq2 $ monotone_comp_rel monotone_id monotone_id ... ≤ u.uniformity.lift' (image (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) ∘ (λs:set (α×α), comp_rel s (comp_rel s s))) : lift'_mono' $ assume s hs ⟨a, b⟩ ⟨c, ⟨⟨a₁, a₂⟩, ha, a_eq⟩, ⟨⟨b₁, b₂⟩, hb, b_eq⟩⟩, begin simp at a_eq, simp at b_eq, have h : ⟦a₂⟧ = ⟦b₁⟧, { rw [a_eq.right, b_eq.left] }, have h : (a₂, b₁) ∈ separation_rel α := quotient.exact h, simp [function.comp, set.image, comp_rel, and.comm, and.left_comm, and.assoc], exact ⟨a₁, a_eq.left, b₂, b_eq.right, a₂, ha, b₁, h s hs, hb⟩ end ... = map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) (u.uniformity.lift' (λs:set (α×α), comp_rel s (comp_rel s s))) : by rw [map_lift'_eq]; exact monotone_comp_rel monotone_id (monotone_comp_rel monotone_id monotone_id) ... ≤ map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) u.uniformity : map_mono comp_le_uniformity3, is_open_uniformity := assume s, have ∀a, ⟦a⟧ ∈ s → ({p:α×α | p.1 = a → ⟦p.2⟧ ∈ s} ∈ 𝓤 α ↔ {p:α×α | p.1 ≈ a → ⟦p.2⟧ ∈ s} ∈ 𝓤 α), from assume a ha, ⟨assume h, let ⟨t, ht, hts⟩ := comp_mem_uniformity_sets h in have hts : ∀{a₁ a₂}, (a, a₁) ∈ t → (a₁, a₂) ∈ t → ⟦a₂⟧ ∈ s, from assume a₁ a₂ ha₁ ha₂, @hts (a, a₂) ⟨a₁, ha₁, ha₂⟩ rfl, have ht' : ∀{a₁ a₂}, a₁ ≈ a₂ → (a₁, a₂) ∈ t, from assume a₁ a₂ h, sInter_subset_of_mem ht h, u.uniformity.sets_of_superset ht $ assume ⟨a₁, a₂⟩ h₁ h₂, hts (ht' $ setoid.symm h₂) h₁, assume h, u.uniformity.sets_of_superset h $ by simp {contextual := tt}⟩, begin simp [topological_space.coinduced, u.is_open_uniformity, uniformity, forall_quotient_iff], exact ⟨λh a ha, (this a ha).mp $ h a ha, λh a ha, (this a ha).mpr $ h a ha⟩ end } lemma uniformity_quotient : 𝓤 (quotient (separation_setoid α)) = (𝓤 α).map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) := rfl lemma uniform_continuous_quotient_mk : uniform_continuous (quotient.mk : α → quotient (separation_setoid α)) := le_refl _ lemma uniform_continuous_quotient {f : quotient (separation_setoid α) → β} (hf : uniform_continuous (λx, f ⟦x⟧)) : uniform_continuous f := hf lemma uniform_continuous_quotient_lift {f : α → β} {h : ∀a b, (a, b) ∈ separation_rel α → f a = f b} (hf : uniform_continuous f) : uniform_continuous (λa, quotient.lift f h a) := uniform_continuous_quotient hf lemma uniform_continuous_quotient_lift₂ [uniform_space γ] {f : α → β → γ} {h : ∀a c b d, (a, b) ∈ separation_rel α → (c, d) ∈ separation_rel β → f a c = f b d} (hf : uniform_continuous (λp:α×β, f p.1 p.2)) : uniform_continuous (λp:_×_, quotient.lift₂ f h p.1 p.2) := begin rw [uniform_continuous, uniformity_prod_eq_prod, uniformity_quotient, uniformity_quotient, filter.prod_map_map_eq, filter.tendsto_map'_iff, filter.tendsto_map'_iff], rwa [uniform_continuous, uniformity_prod_eq_prod, filter.tendsto_map'_iff] at hf end lemma comap_quotient_le_uniformity : (𝓤 $ quotient $ separation_setoid α).comap (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) ≤ (𝓤 α) := assume t' ht', let ⟨t, ht, tt_t'⟩ := comp_mem_uniformity_sets ht' in let ⟨s, hs, ss_t⟩ := comp_mem_uniformity_sets ht in ⟨(λp:α×α, (⟦p.1⟧, ⟦p.2⟧)) '' s, (𝓤 α).sets_of_superset hs $ assume x hx, ⟨x, hx, rfl⟩, assume ⟨a₁, a₂⟩ ⟨⟨b₁, b₂⟩, hb, ab_eq⟩, have ⟦b₁⟧ = ⟦a₁⟧ ∧ ⟦b₂⟧ = ⟦a₂⟧, from prod.mk.inj ab_eq, have b₁ ≈ a₁ ∧ b₂ ≈ a₂, from and.imp quotient.exact quotient.exact this, have ab₁ : (a₁, b₁) ∈ t, from (setoid.symm this.left) t ht, have ba₂ : (b₂, a₂) ∈ s, from this.right s hs, tt_t' ⟨b₁, show ((a₁, a₂).1, b₁) ∈ t, from ab₁, ss_t ⟨b₂, show ((b₁, a₂).1, b₂) ∈ s, from hb, ba₂⟩⟩⟩ lemma comap_quotient_eq_uniformity : (𝓤 $ quotient $ separation_setoid α).comap (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) = 𝓤 α := le_antisymm comap_quotient_le_uniformity le_comap_map instance separated_separation : separated (quotient (separation_setoid α)) := set.ext $ assume ⟨a, b⟩, quotient.induction_on₂ a b $ assume a b, ⟨assume h, have a ≈ b, from assume s hs, have s ∈ (𝓤 $ quotient $ separation_setoid α).comap (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)), from comap_quotient_le_uniformity hs, let ⟨t, ht, hts⟩ := this in hts begin dsimp [preimage], exact h t ht end, show ⟦a⟧ = ⟦b⟧, from quotient.sound this, assume heq : ⟦a⟧ = ⟦b⟧, assume h hs, heq ▸ refl_mem_uniformity hs⟩ lemma separated_of_uniform_continuous {f : α → β} {x y : α} (H : uniform_continuous f) (h : x ≈ y) : f x ≈ f y := assume _ h', h _ (H h') lemma eq_of_separated_of_uniform_continuous [separated β] {f : α → β} {x y : α} (H : uniform_continuous f) (h : x ≈ y) : f x = f y := separated_def.1 (by apply_instance) _ _ $ separated_of_uniform_continuous H h def separation_quotient (α : Type*) [uniform_space α] := quotient (separation_setoid α) namespace separation_quotient instance : uniform_space (separation_quotient α) := by dunfold separation_quotient ; apply_instance instance : separated (separation_quotient α) := by dunfold separation_quotient ; apply_instance def lift [separated β] (f : α → β) : (separation_quotient α → β) := if h : uniform_continuous f then quotient.lift f (λ x y, eq_of_separated_of_uniform_continuous h) else λ x, f (classical.inhabited_of_nonempty $ (nonempty_quotient_iff $ separation_setoid α).1 ⟨x⟩).default lemma lift_mk [separated β] {f : α → β} (h : uniform_continuous f) (a : α) : lift f ⟦a⟧ = f a := by rw [lift, dif_pos h]; refl lemma uniform_continuous_lift [separated β] (f : α → β) : uniform_continuous (lift f) := begin by_cases hf : uniform_continuous f, { rw [lift, dif_pos hf], exact uniform_continuous_quotient_lift hf }, { rw [lift, dif_neg hf], exact uniform_continuous_of_const (assume a b, rfl) } end def map (f : α → β) : separation_quotient α → separation_quotient β := lift (quotient.mk ∘ f) lemma map_mk {f : α → β} (h : uniform_continuous f) (a : α) : map f ⟦a⟧ = ⟦f a⟧ := by rw [map, lift_mk (uniform_continuous_quotient_mk.comp h)] lemma uniform_continuous_map (f : α → β) : uniform_continuous (map f) := uniform_continuous_lift (quotient.mk ∘ f) lemma map_unique {f : α → β} (hf : uniform_continuous f) {g : separation_quotient α → separation_quotient β} (comm : quotient.mk ∘ f = g ∘ quotient.mk) : map f = g := by ext ⟨a⟩; calc map f ⟦a⟧ = ⟦f a⟧ : map_mk hf a ... = g ⟦a⟧ : congr_fun comm a lemma map_id : map (@id α) = id := map_unique uniform_continuous_id rfl lemma map_comp {f : α → β} {g : β → γ} (hf : uniform_continuous f) (hg : uniform_continuous g) : map g ∘ map f = map (g ∘ f) := (map_unique (hg.comp hf) $ by simp only [(∘), map_mk, hf, hg]).symm end separation_quotient lemma separation_prod {a₁ a₂ : α} {b₁ b₂ : β} : (a₁, b₁) ≈ (a₂, b₂) ↔ a₁ ≈ a₂ ∧ b₁ ≈ b₂ := begin split, { assume h, exact ⟨separated_of_uniform_continuous uniform_continuous_fst h, separated_of_uniform_continuous uniform_continuous_snd h⟩ }, { rintros ⟨eqv_α, eqv_β⟩ r r_in, rw uniformity_prod at r_in, rcases r_in with ⟨t_α, ⟨r_α, r_α_in, h_α⟩, t_β, ⟨r_β, r_β_in, h_β⟩, H⟩, let p_α := λ(p : (α × β) × (α × β)), (p.1.1, p.2.1), let p_β := λ(p : (α × β) × (α × β)), (p.1.2, p.2.2), have key_α : p_α ((a₁, b₁), (a₂, b₂)) ∈ r_α, { simp [p_α, eqv_α r_α r_α_in] }, have key_β : p_β ((a₁, b₁), (a₂, b₂)) ∈ r_β, { simp [p_β, eqv_β r_β r_β_in] }, exact H ⟨h_α key_α, h_β key_β⟩ }, end instance separated.prod [separated α] [separated β] : separated (α × β) := separated_def.2 $ assume x y H, prod.ext (eq_of_separated_of_uniform_continuous uniform_continuous_fst H) (eq_of_separated_of_uniform_continuous uniform_continuous_snd H) end uniform_space
8e8c321ca4524be91e4cb8c0c5ae5de5ab82ce34
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/number_theory/class_number/admissible_absolute_value.lean
76cb757fac39612484d61d60ddb66e94fbc062d7
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,763
lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import algebra.euclidean_absolute_value import analysis.special_functions.pow import combinatorics.pigeonhole /-! # Admissible absolute values This file defines a structure `absolute_value.is_admissible` which we use to show the class number of the ring of integers of a global field is finite. ## Main definitions * `absolute_value.is_admissible abv` states the absolute value `abv : R → ℤ` respects the Euclidean domain structure on `R`, and that a large enough set of elements of `R^n` contains a pair of elements whose remainders are pointwise close together. ## Main results * `absolute_value.abs_is_admissible` shows the "standard" absolute value on `ℤ`, mapping negative `x` to `-x`, is admissible. * `polynomial.card_pow_degree_is_admissible` shows `card_pow_degree`, mapping `p : polynomial 𝔽_q` to `q ^ degree p`, is admissible -/ local infix ` ≺ `:50 := euclidean_domain.r namespace absolute_value variables {R : Type*} [euclidean_domain R] variables (abv : absolute_value R ℤ) /-- An absolute value `R → ℤ` is admissible if it respects the Euclidean domain structure and a large enough set of elements in `R^n` will contain a pair of elements whose remainders are pointwise close together. -/ structure is_admissible extends is_euclidean abv := (card : ℝ → ℕ) (exists_partition' : ∀ (n : ℕ) {ε : ℝ} (hε : 0 < ε) {b : R} (hb : b ≠ 0) (A : fin n → R), ∃ (t : fin n → fin (card ε)), ∀ i₀ i₁, t i₀ = t i₁ → (abv (A i₁ % b - A i₀ % b) : ℝ) < abv b • ε) attribute [protected] is_admissible.card namespace is_admissible variables {abv} /-- For all `ε > 0` and finite families `A`, we can partition the remainders of `A` mod `b` into `abv.card ε` sets, such that all elements in each part of remainders are close together. -/ lemma exists_partition {ι : Type*} [fintype ι] {ε : ℝ} (hε : 0 < ε) {b : R} (hb : b ≠ 0) (A : ι → R) (h : abv.is_admissible) : ∃ (t : ι → fin (h.card ε)), ∀ i₀ i₁, t i₀ = t i₁ → (abv (A i₁ % b - A i₀ % b) : ℝ) < abv b • ε := begin let e := fintype.equiv_fin ι, obtain ⟨t, ht⟩ := h.exists_partition' (fintype.card ι) hε hb (A ∘ e.symm), refine ⟨t ∘ e, λ i₀ i₁ h, _⟩, convert ht (e i₀) (e i₁) h; simp only [e.symm_apply_apply] end /-- Any large enough family of vectors in `R^n` has a pair of elements whose remainders are close together, pointwise. -/ lemma exists_approx_aux (n : ℕ) (h : abv.is_admissible) : ∀ {ε : ℝ} (hε : 0 < ε) {b : R} (hb : b ≠ 0) (A : fin (h.card ε ^ n).succ → (fin n → R)), ∃ (i₀ i₁), (i₀ ≠ i₁) ∧ ∀ k, (abv (A i₁ k % b - A i₀ k % b) : ℝ) < abv b • ε := begin haveI := classical.dec_eq R, induction n with n ih, { intros ε hε b hb A, refine ⟨0, 1, _, _⟩, { simp }, rintros ⟨i, ⟨⟩⟩ }, intros ε hε b hb A, set M := h.card ε with hM, -- By the "nicer" pigeonhole principle, we can find a collection `s` -- of more than `M^n` remainders where the first components lie close together: obtain ⟨s, s_inj, hs⟩ : ∃ s : fin (M ^ n).succ → fin (M ^ n.succ).succ, function.injective s ∧ ∀ i₀ i₁, (abv (A (s i₁) 0 % b - A (s i₀) 0 % b) : ℝ) < abv b • ε, { -- We can partition the `A`s into `M` subsets where -- the first components lie close together: obtain ⟨t, ht⟩ : ∃ (t : fin (M ^ n.succ).succ → fin M), ∀ i₀ i₁, t i₀ = t i₁ → (abv (A i₁ 0 % b - A i₀ 0 % b) : ℝ) < abv b • ε := h.exists_partition hε hb (λ x, A x 0), -- Since the `M` subsets contain more than `M * M^n` elements total, -- there must be a subset that contains more than `M^n` elements. obtain ⟨s, hs⟩ := @fintype.exists_lt_card_fiber_of_mul_lt_card _ _ _ _ _ t (M ^ n) (by simpa only [fintype.card_fin, pow_succ] using nat.lt_succ_self (M ^ n.succ) ), refine ⟨λ i, (finset.univ.filter (λ x, t x = s)).to_list.nth_le i _, _, λ i₀ i₁, ht _ _ _⟩, { refine i.2.trans_le _, rwa finset.length_to_list }, { intros i j h, ext, exact list.nodup_iff_nth_le_inj.mp (finset.nodup_to_list _) _ _ _ _ h }, have : ∀ i h, (finset.univ.filter (λ x, t x = s)).to_list.nth_le i h ∈ finset.univ.filter (λ x, t x = s), { intros i h, exact (finset.mem_to_list _).mp (list.nth_le_mem _ _ _) }, obtain ⟨_, h₀⟩ := finset.mem_filter.mp (this i₀ _), obtain ⟨_, h₁⟩ := finset.mem_filter.mp (this i₁ _), exact h₀.trans h₁.symm }, -- Since `s` is large enough, there are two elements of `A ∘ s` -- where the second components lie close together. obtain ⟨k₀, k₁, hk, h⟩ := ih hε hb (λ x, fin.tail (A (s x))), refine ⟨s k₀, s k₁, λ h, hk (s_inj h), λ i, fin.cases _ (λ i, _) i⟩, { exact hs k₀ k₁ }, { exact h i }, end /-- Any large enough family of vectors in `R^ι` has a pair of elements whose remainders are close together, pointwise. -/ lemma exists_approx {ι : Type*} [fintype ι] {ε : ℝ} (hε : 0 < ε) {b : R} (hb : b ≠ 0) (h : abv.is_admissible) (A : fin (h.card ε ^ fintype.card ι).succ → ι → R) : ∃ (i₀ i₁), (i₀ ≠ i₁) ∧ ∀ k, (abv (A i₁ k % b - A i₀ k % b) : ℝ) < abv b • ε := begin let e := fintype.equiv_fin ι, obtain ⟨i₀, i₁, ne, h⟩ := h.exists_approx_aux (fintype.card ι) hε hb (λ x y, A x (e.symm y)), refine ⟨i₀, i₁, ne, λ k, _⟩, convert h (e k); simp only [e.symm_apply_apply] end end is_admissible end absolute_value
9174afd78d06c0f25c5062edf678448f4bc39483
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/elabissues/issues8.lean
fea4289061c2989bb9b47d5c67610d2423422ede
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
759
lean
def forceNat (a : Nat) := true def forceInt (a : Int) := false def f1 := /- The following example works, but it adds a coercion at `forceInt i`. The elaborated term is ``` fun (n i : Nat) => if n == i then forceNat n else forceInt (coe i) -/ fun n i => if n == i then forceNat n else forceInt i -- works def f2 := fun n i => if coe n == i then forceInt i else forceNat n -- works #check f1 -- Nat → Nat → Bool #check f2 -- Nat → Int → Bool def f3 := /- Fails. - `n == i` generates type constraint enforcing `n` and `i` to have the same type. - `forceInt i` forces `i` (and consequently `n`) to have type `Int`. - `forceNat n` fails because there is no coercion from `Nat` to `Int`. -/ fun n i => if n == i then forceInt i else forceNat n
1eaaaaf88582e0bf049d66d002e6833903059f37
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/category/Module/subobject.lean
226ba8b43b8761532f3d3d8fe50b154b75973df8
[ "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,523
lean
/- Copyright (c) 2021 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import algebra.category.Module.epi_mono import algebra.category.Module.kernels import category_theory.subobject.well_powered import category_theory.subobject.limits import category_theory.limits.concrete_category /-! # Subobjects in the category of `R`-modules We construct an explicit order isomorphism between the categorical subobjects of an `R`-module `M` and its submodules. This immediately implies that the category of `R`-modules is well-powered. -/ open category_theory open category_theory.subobject open category_theory.limits open_locale Module universes v u namespace Module variables {R : Type u} [ring R] (M : Module.{v} R) /-- The categorical subobjects of a module `M` are in one-to-one correspondence with its submodules.-/ noncomputable def subobject_Module : subobject M ≃o submodule R M := order_iso.symm ({ inv_fun := λ S, S.arrow.range, to_fun := λ N, subobject.mk ↾N.subtype, right_inv := λ S, eq.symm begin fapply eq_mk_of_comm, { apply linear_equiv.to_Module_iso'_left, apply linear_equiv.of_bijective (linear_map.cod_restrict S.arrow.range S.arrow _), { simpa only [← linear_map.ker_eq_bot, linear_map.ker_cod_restrict] using ker_eq_bot_of_mono _ }, { rw [← linear_map.range_eq_top, linear_map.range_cod_restrict, submodule.comap_subtype_self] }, { exact linear_map.mem_range_self _ } }, { apply linear_map.ext, intros x, refl } end, left_inv := λ N, begin convert congr_arg linear_map.range (underlying_iso_arrow ↾N.subtype) using 1, { have : (underlying_iso ↾N.subtype).inv = (underlying_iso ↾N.subtype).symm.to_linear_equiv, { apply linear_map.ext, intros x, refl }, rw [this, comp_def, linear_equiv.range_comp] }, { exact (submodule.range_subtype _).symm } end, map_rel_iff' := λ S T, begin refine ⟨λ h, _, λ h, mk_le_mk_of_comm ↟(submodule.of_le h) (by { ext, refl })⟩, convert linear_map.range_comp_le_range (of_mk_le_mk _ _ h) ↾T.subtype, { simpa only [←comp_def, of_mk_le_mk_comp] using (submodule.range_subtype _).symm }, { exact (submodule.range_subtype _).symm } end }) instance well_powered_Module : well_powered (Module.{v} R) := ⟨λ M, ⟨⟨_, ⟨(subobject_Module M).to_equiv⟩⟩⟩⟩ local attribute [instance] has_kernels_Module /-- Bundle an element `m : M` such that `f m = 0` as a term of `kernel_subobject f`. -/ noncomputable def to_kernel_subobject {M N : Module R} {f : M ⟶ N} : linear_map.ker f →ₗ[R] kernel_subobject f := (kernel_subobject_iso f ≪≫ Module.kernel_iso_ker f).inv @[simp] lemma to_kernel_subobject_arrow {M N : Module R} {f : M ⟶ N} (x : linear_map.ker f) : (kernel_subobject f).arrow (to_kernel_subobject x) = x.1 := by simp [to_kernel_subobject] /-- An extensionality lemma showing that two elements of a cokernel by an image are equal if they differ by an element of the image. The application is for homology: two elements in homology are equal if they differ by a boundary. -/ @[ext] lemma cokernel_π_image_subobject_ext {L M N : Module.{v} R} (f : L ⟶ M) [has_image f] (g : (image_subobject f : Module.{v} R) ⟶ N) [has_cokernel g] {x y : N} (l : L) (w : x = y + g (factor_thru_image_subobject f l)) : cokernel.π g x = cokernel.π g y := by { subst w, simp, } end Module
336e32898961b490dd5f6cca4c50aec445fba42f
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/algebra/module/ordered.lean
4e07abc390210304a90b9892c3b29a02dc6033bb
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
3,594
lean
/- Copyright (c) 2020 Frédéric Dupuis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Frédéric Dupuis -/ import algebra.module.basic import algebra.ordered_group /-! # Ordered semimodules In this file we define * `ordered_semimodule R M` : an ordered additive commutative monoid `M` is an `ordered_semimodule` over an `ordered_semiring` `R` if the scalar product respects the order relation on the monoid and on the ring. There is a correspondence between this structure and convex cones, which is proven in `analysis/convex/cone.lean`. ## Implementation notes * We choose to define `ordered_semimodule` so that it extends `semimodule` only, as is done for semimodules itself. * To get ordered modules and ordered vector spaces, it suffices to the replace the `order_add_comm_monoid` and the `ordered_semiring` as desired. ## References * https://en.wikipedia.org/wiki/Ordered_vector_space ## Tags ordered semimodule, ordered module, ordered vector space -/ /-- An ordered semimodule is an ordered additive commutative monoid with a partial order in which the scalar multiplication is compatible with the order. -/ @[protect_proj, ancestor semimodule] class ordered_semimodule (R β : Type*) [ordered_semiring R] [ordered_add_comm_monoid β] extends semimodule R β := (smul_lt_smul_of_pos : ∀ {a b : β}, ∀ {c : R}, a < b → 0 < c → c • a < c • b) (lt_of_smul_lt_smul_of_nonneg : ∀ {a b : β}, ∀ {c : R}, c • a < c • b → 0 ≤ c → a < b) section ordered_semimodule variables {R β : Type*} [ordered_semiring R] [ordered_add_comm_monoid β] [ordered_semimodule R β] {a b : β} {c : R} lemma smul_lt_smul_of_pos : a < b → 0 < c → c • a < c • b := ordered_semimodule.smul_lt_smul_of_pos lemma smul_le_smul_of_nonneg (h₁ : a ≤ b) (h₂ : 0 ≤ c) : c • a ≤ c • b := begin by_cases H₁ : c = 0, { simp [H₁, zero_smul] }, { by_cases H₂ : a = b, { rw H₂ }, { exact le_of_lt (smul_lt_smul_of_pos (lt_of_le_of_ne h₁ H₂) (lt_of_le_of_ne h₂ (ne.symm H₁))), } } end end ordered_semimodule section instances variables {R : Type*} [linear_ordered_ring R] instance linear_ordered_ring.to_ordered_semimodule : ordered_semimodule R R := { smul_lt_smul_of_pos := ordered_semiring.mul_lt_mul_of_pos_left, lt_of_smul_lt_smul_of_nonneg := λ _ _ _, lt_of_mul_lt_mul_left } end instances section order_dual variables {R β : Type*} instance [semiring R] [ordered_add_comm_monoid β] [semimodule R β] : has_scalar R (order_dual β) := { smul := @has_scalar.smul R β _ } instance [semiring R] [ordered_add_comm_monoid β] [semimodule R β] : mul_action R (order_dual β) := { one_smul := @mul_action.one_smul R β _ _, mul_smul := @mul_action.mul_smul R β _ _ } instance [semiring R] [ordered_add_comm_monoid β] [semimodule R β] : distrib_mul_action R (order_dual β) := { smul_add := @distrib_mul_action.smul_add R β _ _ _, smul_zero := @distrib_mul_action.smul_zero R β _ _ _ } instance [semiring R] [ordered_add_comm_monoid β] [semimodule R β] : semimodule R (order_dual β) := { add_smul := @semimodule.add_smul R β _ _ _, zero_smul := @semimodule.zero_smul R β _ _ _ } instance [ordered_semiring R] [ordered_add_comm_monoid β] [ordered_semimodule R β] : ordered_semimodule R (order_dual β) := { smul_lt_smul_of_pos := λ a b, @ordered_semimodule.smul_lt_smul_of_pos R β _ _ _ b a, lt_of_smul_lt_smul_of_nonneg := λ a b, @ordered_semimodule.lt_of_smul_lt_smul_of_nonneg R β _ _ _ b a } end order_dual
6033a52c13ca3915890bd967fa637e5585570f7d
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Elab/Term.lean
2bf15f500113fbafe05650c16c291056ba4d06e2
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
69,872
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.ResolveName import Lean.Util.Sorry import Lean.Util.ReplaceExpr import Lean.Structure import Lean.Meta.AppBuilder import Lean.Meta.CollectMVars import Lean.Meta.Coe import Lean.Hygiene import Lean.Util.RecDepth import Lean.Elab.Log import Lean.Elab.Config import Lean.Elab.Level import Lean.Elab.Attributes import Lean.Elab.AutoBound import Lean.Elab.InfoTree import Lean.Elab.Open import Lean.Elab.SetOption namespace Lean.Elab.Term structure Context where fileName : String fileMap : FileMap declName? : Option Name := none macroStack : MacroStack := [] currMacroScope : MacroScope := firstFrontendMacroScope /- When `mayPostpone == true`, an elaboration function may interrupt its execution by throwing `Exception.postpone`. The function `elabTerm` catches this exception and creates fresh synthetic metavariable `?m`, stores `?m` in the list of pending synthetic metavariables, and returns `?m`. -/ mayPostpone : Bool := true /- When `errToSorry` is set to true, the method `elabTerm` catches exceptions and converts them into synthetic `sorry`s. The implementation of choice nodes and overloaded symbols rely on the fact that when `errToSorry` is set to false for an elaboration function `F`, then `errToSorry` remains `false` for all elaboration functions invoked by `F`. That is, it is safe to transition `errToSorry` from `true` to `false`, but we must not set `errToSorry` to `true` when it is currently set to `false`. -/ errToSorry : Bool := true /- When `autoBoundImplicit` is set to true, instead of producing an "unknown identifier" error for unbound variables, we generate an internal exception. This exception is caught at `elabBinders` and `elabTypeWithUnboldImplicit`. Both methods add implicit declarations for the unbound variable and try again. -/ autoBoundImplicit : Bool := false autoBoundImplicits : Std.PArray Expr := {} /-- Map from user name to internal unique name -/ sectionVars : NameMap Name := {} /-- Map from internal name to fvar -/ sectionFVars : NameMap Expr := {} /-- Enable/disable implicit lambdas feature. -/ implicitLambda : Bool := true /-- noncomputable sections automatically add the `noncomputable` modifier to any declaration we cannot generate code for -/ isNoncomputableSection : Bool := false /-- Saved context for postponed terms and tactics to be executed. -/ structure SavedContext where declName? : Option Name options : Options openDecls : List OpenDecl macroStack : MacroStack errToSorry : Bool /-- We use synthetic metavariables as placeholders for pending elaboration steps. -/ inductive SyntheticMVarKind where -- typeclass instance search | typeClass /- Similar to typeClass, but error messages are different. if `f?` is `some f`, we produce an application type mismatch error message. Otherwise, if `header?` is `some header`, we generate the error `(header ++ "has type" ++ eType ++ "but it is expected to have type" ++ expectedType)` Otherwise, we generate the error `("type mismatch" ++ e ++ "has type" ++ eType ++ "but it is expected to have type" ++ expectedType)` -/ | coe (header? : Option String) (eNew : Expr) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) -- tactic block execution | tactic (tacticCode : Syntax) (ctx : SavedContext) -- `elabTerm` call that threw `Exception.postpone` (input is stored at `SyntheticMVarDecl.ref`) | postponed (ctx : SavedContext) instance : ToString SyntheticMVarKind where toString | SyntheticMVarKind.typeClass => "typeclass" | SyntheticMVarKind.coe .. => "coe" | SyntheticMVarKind.tactic .. => "tactic" | SyntheticMVarKind.postponed .. => "postponed" structure SyntheticMVarDecl where mvarId : MVarId stx : Syntax kind : SyntheticMVarKind inductive MVarErrorKind where | implicitArg (ctx : Expr) | hole | custom (msgData : MessageData) deriving Inhabited instance : ToString MVarErrorKind where toString | MVarErrorKind.implicitArg ctx => "implicitArg" | MVarErrorKind.hole => "hole" | MVarErrorKind.custom msg => "custom" structure MVarErrorInfo where mvarId : MVarId ref : Syntax kind : MVarErrorKind argName? : Option Name := none deriving Inhabited structure LetRecToLift where ref : Syntax fvarId : FVarId attrs : Array Attribute shortDeclName : Name declName : Name lctx : LocalContext localInstances : LocalInstances type : Expr val : Expr mvarId : MVarId structure State where levelNames : List Name := [] syntheticMVars : List SyntheticMVarDecl := [] mvarErrorInfos : MVarIdMap MVarErrorInfo := {} messages : MessageLog := {} letRecsToLift : List LetRecToLift := [] infoState : InfoState := {} deriving Inhabited abbrev TermElabM := ReaderT Context $ StateRefT State MetaM abbrev TermElab := Syntax → Option Expr → TermElabM Expr -- Make the compiler generate specialized `pure`/`bind` so we do not have to optimize through the -- whole monad stack at every use site. May eventually be covered by `deriving`. instance : Monad TermElabM := let i := inferInstanceAs (Monad TermElabM); { pure := i.pure, bind := i.bind } open Meta instance : Inhabited (TermElabM α) where default := throw arbitrary structure SavedState where meta : Meta.SavedState «elab» : State deriving Inhabited protected def saveState : TermElabM SavedState := do pure { meta := (← Meta.saveState), «elab» := (← get) } def SavedState.restore (s : SavedState) (restoreInfo : Bool := false) : TermElabM Unit := do let traceState ← getTraceState -- We never backtrack trace message let infoState := (← get).infoState -- We also do not backtrack the info nodes when `restoreInfo == false` s.meta.restore set s.elab setTraceState traceState unless restoreInfo do modify fun s => { s with infoState := infoState } instance : MonadBacktrack SavedState TermElabM where saveState := Term.saveState restoreState b := b.restore abbrev TermElabResult (α : Type) := EStateM.Result Exception SavedState α instance [Inhabited α] : Inhabited (TermElabResult α) where default := EStateM.Result.ok arbitrary arbitrary def setMessageLog (messages : MessageLog) : TermElabM Unit := modify fun s => { s with messages := messages } def resetMessageLog : TermElabM Unit := setMessageLog {} def getMessageLog : TermElabM MessageLog := return (← get).messages /-- Execute `x`, save resulting expression and new state. We remove any `Info` created by `x`. The info nodes are committed when we execute `applyResult`. We use `observing` to implement overloaded notation and decls. We want to save `Info` nodes for the chosen alternative. -/ def observing (x : TermElabM α) : TermElabM (TermElabResult α) := do let s ← saveState try let e ← x let sNew ← saveState s.restore (restoreInfo := true) pure (EStateM.Result.ok e sNew) catch | ex@(Exception.error _ _) => let sNew ← saveState s.restore (restoreInfo := true) pure (EStateM.Result.error ex sNew) | ex@(Exception.internal id _) => if id == postponeExceptionId then s.restore (restoreInfo := true) throw ex /-- Apply the result/exception and state captured with `observing`. We use this method to implement overloaded notation and symbols. -/ def applyResult (result : TermElabResult α) : TermElabM α := match result with | EStateM.Result.ok a r => do r.restore (restoreInfo := true); pure a | EStateM.Result.error ex r => do r.restore (restoreInfo := true); throw ex /-- Execute `x`, but keep state modifications only if `x` did not postpone. This method is useful to implement elaboration functions that cannot decide whether they need to postpone or not without updating the state. -/ def commitIfDidNotPostpone (x : TermElabM α) : TermElabM α := do -- We just reuse the implementation of `observing` and `applyResult`. let r ← observing x applyResult r def getLevelNames : TermElabM (List Name) := return (← get).levelNames def getFVarLocalDecl! (fvar : Expr) : TermElabM LocalDecl := do match (← getLCtx).find? fvar.fvarId! with | some d => pure d | none => unreachable! instance : AddErrorMessageContext TermElabM where add ref msg := do let ctx ← read let ref := getBetterRef ref ctx.macroStack let msg ← addMessageContext msg let msg ← addMacroStack msg ctx.macroStack pure (ref, msg) instance : MonadLog TermElabM where getRef := getRef getFileMap := return (← read).fileMap getFileName := return (← read).fileName logMessage msg := do let ctx ← readThe Core.Context let msg := { msg with data := MessageData.withNamingContext { currNamespace := ctx.currNamespace, openDecls := ctx.openDecls } msg.data }; modify fun s => { s with messages := s.messages.add msg } protected def getCurrMacroScope : TermElabM MacroScope := do pure (← read).currMacroScope protected def getMainModule : TermElabM Name := do pure (← getEnv).mainModule protected def withFreshMacroScope (x : TermElabM α) : TermElabM α := do let fresh ← modifyGetThe Core.State (fun st => (st.nextMacroScope, { st with nextMacroScope := st.nextMacroScope + 1 })) withReader (fun ctx => { ctx with currMacroScope := fresh }) x instance : MonadQuotation TermElabM where getCurrMacroScope := Term.getCurrMacroScope getMainModule := Term.getMainModule withFreshMacroScope := Term.withFreshMacroScope instance : MonadInfoTree TermElabM where getInfoState := return (← get).infoState modifyInfoState f := modify fun s => { s with infoState := f s.infoState } /-- Execute `x` but discard changes performed at `Term.State` and `Meta.State`. Recall that the environment is at `Core.State`. Thus, any updates to it will be preserved. This method is useful for performing computations where all metavariable must be resolved or discarded. The info trees are not discarded, however, and wrapped in `InfoTree.Context` to store their metavariable context. -/ def withoutModifyingElabMetaStateWithInfo (x : TermElabM α) : TermElabM α := do let s ← get let sMeta ← getThe Meta.State try withSaveInfoContext x finally modify ({ s with infoState := ·.infoState }) set sMeta /-- Execute `x` bud discard changes performed to the state. However, the info trees and messages are not discarded. -/ private def withoutModifyingStateWithInfoAndMessagesImpl (x : TermElabM α) : TermElabM α := do let saved ← saveState try x finally let s ← get let saved := { saved with elab.infoState := s.infoState, elab.messages := s.messages } restoreState saved unsafe def mkTermElabAttributeUnsafe : IO (KeyedDeclsAttribute TermElab) := mkElabAttribute TermElab `Lean.Elab.Term.termElabAttribute `builtinTermElab `termElab `Lean.Parser.Term `Lean.Elab.Term.TermElab "term" @[implementedBy mkTermElabAttributeUnsafe] constant mkTermElabAttribute : IO (KeyedDeclsAttribute TermElab) builtin_initialize termElabAttribute : KeyedDeclsAttribute TermElab ← mkTermElabAttribute /-- Auxiliary datatatype for presenting a Lean lvalue modifier. We represent a unelaborated lvalue as a `Syntax` (or `Expr`) and `List LVal`. Example: `a.foo[i].1` is represented as the `Syntax` `a` and the list `[LVal.fieldName "foo", LVal.getOp i, LVal.fieldIdx 1]`. Recall that the notation `a[i]` is not just for accessing arrays in Lean. -/ inductive LVal where | fieldIdx (ref : Syntax) (i : Nat) /- Field `suffix?` is for producing better error messages because `x.y` may be a field access or a hierachical/composite name. `ref` is the syntax object representing the field. `targetStx` is the target object being accessed. -/ | fieldName (ref : Syntax) (name : String) (suffix? : Option Name) (targetStx : Syntax) | getOp (ref : Syntax) (idx : Syntax) def LVal.getRef : LVal → Syntax | LVal.fieldIdx ref _ => ref | LVal.fieldName ref .. => ref | LVal.getOp ref _ => ref def LVal.isFieldName : LVal → Bool | LVal.fieldName .. => true | _ => false instance : ToString LVal where toString | LVal.fieldIdx _ i => toString i | LVal.fieldName _ n .. => n | LVal.getOp _ idx => "[" ++ toString idx ++ "]" def getDeclName? : TermElabM (Option Name) := return (← read).declName? def getLetRecsToLift : TermElabM (List LetRecToLift) := return (← get).letRecsToLift def isExprMVarAssigned (mvarId : MVarId) : TermElabM Bool := return (← getMCtx).isExprAssigned mvarId def getMVarDecl (mvarId : MVarId) : TermElabM MetavarDecl := return (← getMCtx).getDecl mvarId def assignLevelMVar (mvarId : MVarId) (val : Level) : TermElabM Unit := modifyThe Meta.State fun s => { s with mctx := s.mctx.assignLevel mvarId val } def withDeclName (name : Name) (x : TermElabM α) : TermElabM α := withReader (fun ctx => { ctx with declName? := name }) x def setLevelNames (levelNames : List Name) : TermElabM Unit := modify fun s => { s with levelNames := levelNames } def withLevelNames (levelNames : List Name) (x : TermElabM α) : TermElabM α := do let levelNamesSaved ← getLevelNames setLevelNames levelNames try x finally setLevelNames levelNamesSaved def withoutErrToSorry (x : TermElabM α) : TermElabM α := withReader (fun ctx => { ctx with errToSorry := false }) x /-- For testing `TermElabM` methods. The #eval command will sign the error. -/ def throwErrorIfErrors : TermElabM Unit := do if (← get).messages.hasErrors then throwError "Error(s)" def traceAtCmdPos (cls : Name) (msg : Unit → MessageData) : TermElabM Unit := withRef Syntax.missing $ trace cls msg def ppGoal (mvarId : MVarId) : TermElabM Format := Meta.ppGoal mvarId open Level (LevelElabM) def liftLevelM (x : LevelElabM α) : TermElabM α := do let ctx ← read let mctx ← getMCtx let ngen ← getNGen let lvlCtx : Level.Context := { options := (← getOptions), ref := (← getRef), autoBoundImplicit := ctx.autoBoundImplicit } match (x lvlCtx).run { ngen := ngen, mctx := mctx, levelNames := (← getLevelNames) } with | EStateM.Result.ok a newS => setMCtx newS.mctx; setNGen newS.ngen; setLevelNames newS.levelNames; pure a | EStateM.Result.error ex _ => throw ex def elabLevel (stx : Syntax) : TermElabM Level := liftLevelM $ Level.elabLevel stx /- Elaborate `x` with `stx` on the macro stack -/ def withMacroExpansion (beforeStx afterStx : Syntax) (x : TermElabM α) : TermElabM α := withMacroExpansionInfo beforeStx afterStx do withReader (fun ctx => { ctx with macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack }) x /- Add the given metavariable to the list of pending synthetic metavariables. The method `synthesizeSyntheticMVars` is used to process the metavariables on this list. -/ def registerSyntheticMVar (stx : Syntax) (mvarId : MVarId) (kind : SyntheticMVarKind) : TermElabM Unit := do modify fun s => { s with syntheticMVars := { mvarId := mvarId, stx := stx, kind := kind } :: s.syntheticMVars } def registerSyntheticMVarWithCurrRef (mvarId : MVarId) (kind : SyntheticMVarKind) : TermElabM Unit := do registerSyntheticMVar (← getRef) mvarId kind def registerMVarErrorInfo (mvarErrorInfo : MVarErrorInfo) : TermElabM Unit := modify fun s => { s with mvarErrorInfos := s.mvarErrorInfos.insert mvarErrorInfo.mvarId mvarErrorInfo } def registerMVarErrorHoleInfo (mvarId : MVarId) (ref : Syntax) : TermElabM Unit := registerMVarErrorInfo { mvarId := mvarId, ref := ref, kind := MVarErrorKind.hole } def registerMVarErrorImplicitArgInfo (mvarId : MVarId) (ref : Syntax) (app : Expr) : TermElabM Unit := do registerMVarErrorInfo { mvarId := mvarId, ref := ref, kind := MVarErrorKind.implicitArg app } def registerMVarErrorCustomInfo (mvarId : MVarId) (ref : Syntax) (msgData : MessageData) : TermElabM Unit := do registerMVarErrorInfo { mvarId := mvarId, ref := ref, kind := MVarErrorKind.custom msgData } def getMVarErrorInfo? (mvarId : MVarId) : TermElabM (Option MVarErrorInfo) := do return (← get).mvarErrorInfos.find? mvarId def registerCustomErrorIfMVar (e : Expr) (ref : Syntax) (msgData : MessageData) : TermElabM Unit := match e.getAppFn with | Expr.mvar mvarId _ => registerMVarErrorCustomInfo mvarId ref msgData | _ => pure () /- Auxiliary method for reporting errors of the form "... contains metavariables ...". This kind of error is thrown, for example, at `Match.lean` where elaboration cannot continue if there are metavariables in patterns. We only want to log it if we haven't logged any error so far. -/ def throwMVarError (m : MessageData) : TermElabM α := do if (← get).messages.hasErrors then throwAbortTerm else throwError m def MVarErrorInfo.logError (mvarErrorInfo : MVarErrorInfo) (extraMsg? : Option MessageData) : TermElabM Unit := do match mvarErrorInfo.kind with | MVarErrorKind.implicitArg app => do let app ← instantiateMVars app let msg := addArgName "don't know how to synthesize implicit argument" let msg := msg ++ m!"{indentExpr app.setAppPPExplicitForExposingMVars}" ++ Format.line ++ "context:" ++ Format.line ++ MessageData.ofGoal mvarErrorInfo.mvarId logErrorAt mvarErrorInfo.ref (appendExtra msg) | MVarErrorKind.hole => do let msg := addArgName "don't know how to synthesize placeholder" " for argument" let msg := msg ++ Format.line ++ "context:" ++ Format.line ++ MessageData.ofGoal mvarErrorInfo.mvarId logErrorAt mvarErrorInfo.ref (MessageData.tagged `Elab.synthPlaceholder <| appendExtra msg) | MVarErrorKind.custom msg => logErrorAt mvarErrorInfo.ref (appendExtra msg) where /-- Append `mvarErrorInfo` argument name (if available) to the message. Remark: if the argument name contains macro scopes we do not append it. -/ addArgName (msg : MessageData) (extra : String := "") : MessageData := match mvarErrorInfo.argName? with | none => msg | some argName => if argName.hasMacroScopes then msg else msg ++ extra ++ m!" '{argName}'" appendExtra (msg : MessageData) : MessageData := match extraMsg? with | none => msg | some extraMsg => msg ++ extraMsg /-- Try to log errors for the unassigned metavariables `pendingMVarIds`. Return `true` if there were "unfilled holes", and we should "abort" declaration. TODO: try to fill "all" holes using synthetic "sorry's" Remark: We only log the "unfilled holes" as new errors if no error has been logged so far. -/ def logUnassignedUsingErrorInfos (pendingMVarIds : Array MVarId) (extraMsg? : Option MessageData := none) : TermElabM Bool := do let s ← get let hasOtherErrors := s.messages.hasErrors let mut hasNewErrors := false let mut alreadyVisited : MVarIdSet := {} let mut errors : Array MVarErrorInfo := #[] for (_, mvarErrorInfo) in s.mvarErrorInfos do let mvarId := mvarErrorInfo.mvarId unless alreadyVisited.contains mvarId do alreadyVisited := alreadyVisited.insert mvarId /- The metavariable `mvarErrorInfo.mvarId` may have been assigned or delayed assigned to another metavariable that is unassigned. -/ let mvarDeps ← getMVars (mkMVar mvarId) if mvarDeps.any pendingMVarIds.contains then do unless hasOtherErrors do errors := errors.push mvarErrorInfo hasNewErrors := true -- To sort the errors by position use -- let sortedErrors := errors.qsort fun e₁ e₂ => e₁.ref.getPos?.getD 0 < e₂.ref.getPos?.getD 0 for error in errors do withMVarContext error.mvarId do error.logError extraMsg? return hasNewErrors /-- Ensure metavariables registered using `registerMVarErrorInfos` (and used in the given declaration) have been assigned. -/ def ensureNoUnassignedMVars (decl : Declaration) : TermElabM Unit := do let pendingMVarIds ← getMVarsAtDecl decl if (← logUnassignedUsingErrorInfos pendingMVarIds) then throwAbortCommand /- Execute `x` without allowing it to postpone elaboration tasks. That is, `tryPostpone` is a noop. -/ def withoutPostponing (x : TermElabM α) : TermElabM α := withReader (fun ctx => { ctx with mayPostpone := false }) x /-- Creates syntax for `(` <ident> `:` <type> `)` -/ def mkExplicitBinder (ident : Syntax) (type : Syntax) : Syntax := mkNode ``Lean.Parser.Term.explicitBinder #[mkAtom "(", mkNullNode #[ident], mkNullNode #[mkAtom ":", type], mkNullNode, mkAtom ")"] /-- Convert unassigned universe level metavariables into parameters. The new parameter names are of the form `u_i` where `i >= nextParamIdx`. The method returns the updated expression and new `nextParamIdx`. Remark: we make sure the generated parameter names do not clash with the universe at `ctx.levelNames`. -/ def levelMVarToParam (e : Expr) (nextParamIdx : Nat := 1) : TermElabM (Expr × Nat) := do let mctx ← getMCtx let levelNames ← getLevelNames let r := mctx.levelMVarToParam (fun n => levelNames.elem n) e `u nextParamIdx setMCtx r.mctx pure (r.expr, r.nextParamIdx) /-- Variant of `levelMVarToParam` where `nextParamIdx` is stored in a state monad. -/ def levelMVarToParam' (e : Expr) : StateRefT Nat TermElabM Expr := do let nextParamIdx ← get let (e, nextParamIdx) ← levelMVarToParam e nextParamIdx set nextParamIdx pure e /-- Auxiliary method for creating fresh binder names. Do not confuse with the method for creating fresh free/meta variable ids. -/ def mkFreshBinderName [Monad m] [MonadQuotation m] : m Name := withFreshMacroScope $ MonadQuotation.addMacroScope `x /-- Auxiliary method for creating a `Syntax.ident` containing a fresh name. This method is intended for creating fresh binder names. It is just a thin layer on top of `mkFreshUserName`. -/ def mkFreshIdent [Monad m] [MonadQuotation m] (ref : Syntax) : m Syntax := return mkIdentFrom ref (← mkFreshBinderName) private def applyAttributesCore (declName : Name) (attrs : Array Attribute) (applicationTime? : Option AttributeApplicationTime) : TermElabM Unit := for attr in attrs do let env ← getEnv match getAttributeImpl env attr.name with | Except.error errMsg => throwError errMsg | Except.ok attrImpl => match applicationTime? with | none => attrImpl.add declName attr.stx attr.kind | some applicationTime => if applicationTime == attrImpl.applicationTime then attrImpl.add declName attr.stx attr.kind /-- Apply given attributes **at** a given application time -/ def applyAttributesAt (declName : Name) (attrs : Array Attribute) (applicationTime : AttributeApplicationTime) : TermElabM Unit := applyAttributesCore declName attrs applicationTime def applyAttributes (declName : Name) (attrs : Array Attribute) : TermElabM Unit := applyAttributesCore declName attrs none def mkTypeMismatchError (header? : Option String) (e : Expr) (eType : Expr) (expectedType : Expr) : TermElabM MessageData := do let header : MessageData := match header? with | some header => m!"{header} " | none => m!"type mismatch{indentExpr e}\n" return m!"{header}{← mkHasTypeButIsExpectedMsg eType expectedType}" def throwTypeMismatchError (header? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr := none) (extraMsg? : Option MessageData := none) : TermElabM α := do /- We ignore `extraMsg?` for now. In all our tests, it contained no useful information. It was always of the form: ``` failed to synthesize instance CoeT <eType> <e> <expectedType> ``` We should revisit this decision in the future and decide whether it may contain useful information or not. -/ let extraMsg := Format.nil /- let extraMsg : MessageData := match extraMsg? with | none => Format.nil | some extraMsg => Format.line ++ extraMsg; -/ match f? with | none => throwError "{← mkTypeMismatchError header? e eType expectedType}{extraMsg}" | some f => Meta.throwAppTypeMismatch f e extraMsg def withoutMacroStackAtErr (x : TermElabM α) : TermElabM α := withTheReader Core.Context (fun (ctx : Core.Context) => { ctx with options := pp.macroStack.set ctx.options false }) x namespace ContainsPendingMVar abbrev M := MonadCacheT Expr Unit (OptionT TermElabM) /-- See `containsPostponedTerm` -/ partial def visit (e : Expr) : M Unit := do checkCache e fun _ => do match e with | 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.app f a _ => visit f; visit a | Expr.mdata _ b _ => visit b | Expr.proj _ _ b _ => visit b | Expr.fvar fvarId .. => match (← getLocalDecl fvarId) with | LocalDecl.cdecl .. => return () | LocalDecl.ldecl (value := v) .. => visit v | Expr.mvar mvarId .. => let e' ← instantiateMVars e if e' != e then visit e' else match (← getDelayedAssignment? mvarId) with | some d => visit d.val | none => failure | _ => return () end ContainsPendingMVar /-- Return `true` if `e` contains a pending metavariable. Remark: it also visits let-declarations. -/ def containsPendingMVar (e : Expr) : TermElabM Bool := do match (← ContainsPendingMVar.visit e |>.run.run) with | some _ => return false | none => return true /- Try to synthesize metavariable using type class resolution. This method assumes the local context and local instances of `instMVar` coincide with the current local context and local instances. Return `true` if the instance was synthesized successfully, and `false` if the instance contains unassigned metavariables that are blocking the type class resolution procedure. Throw an exception if resolution or assignment irrevocably fails. -/ def synthesizeInstMVarCore (instMVar : MVarId) (maxResultSize? : Option Nat := none) : TermElabM Bool := do let instMVarDecl ← getMVarDecl instMVar let type := instMVarDecl.type let type ← instantiateMVars type let result ← trySynthInstance type maxResultSize? match result with | LOption.some val => if (← isExprMVarAssigned instMVar) then let oldVal ← instantiateMVars (mkMVar instMVar) unless (← isDefEq oldVal val) do if (← containsPendingMVar oldVal <||> containsPendingMVar val) then /- If `val` or `oldVal` contains metavariables directly or indirectly (e.g., in a let-declaration), we return `false` to indicate we should try again later. This is very course grain since the metavariable may not be responsible for the failure. We should refine the test in the future if needed. This check has been added to address dependencies between postponed metavariables. The following example demonstrates the issue fixed by this test. ``` structure Point where x : Nat y : Nat def Point.compute (p : Point) : Point := let p := { p with x := 1 } let p := { p with y := 0 } if (p.x - p.y) > p.x then p else p ``` The `isDefEq` test above fails for `Decidable (p.x - p.y ≤ p.x)` when the structure instance assigned to `p` has not been elaborated yet. -/ return false -- we will try again later let oldValType ← inferType oldVal let valType ← inferType val unless (← isDefEq oldValType valType) do throwError "synthesized type class instance type is not definitionally equal to expected type, synthesized{indentExpr val}\nhas type{indentExpr valType}\nexpected{indentExpr oldValType}" throwError "synthesized type class instance is not definitionally equal to expression inferred by typing rules, synthesized{indentExpr val}\ninferred{indentExpr oldVal}" else unless (← isDefEq (mkMVar instMVar) val) do throwError "failed to assign synthesized type class instance{indentExpr val}" pure true | LOption.undef => pure false -- we will try later | LOption.none => throwError "failed to synthesize instance{indentExpr type}" register_builtin_option autoLift : Bool := { defValue := true descr := "insert monadic lifts (i.e., `liftM` and `liftCoeM`) when needed" } register_builtin_option maxCoeSize : Nat := { defValue := 16 descr := "maximum number of instances used to construct an automatic coercion" } def synthesizeCoeInstMVarCore (instMVar : MVarId) : TermElabM Bool := do synthesizeInstMVarCore instMVar (some (maxCoeSize.get (← getOptions))) /- The coercion from `α` to `Thunk α` cannot be implemented using an instance because it would eagerly evaluate `e` -/ def tryCoeThunk? (expectedType : Expr) (eType : Expr) (e : Expr) : TermElabM (Option Expr) := do match expectedType with | Expr.app (Expr.const ``Thunk u _) arg _ => if (← isDefEq eType arg) then pure (some (mkApp2 (mkConst ``Thunk.mk u) arg (mkSimpleThunk e))) else pure none | _ => pure none def mkCoe (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr := none) (errorMsgHeader? : Option String := none) : TermElabM Expr := do let u ← getLevel eType let v ← getLevel expectedType let coeTInstType := mkAppN (mkConst ``CoeT [u, v]) #[eType, e, expectedType] let mvar ← mkFreshExprMVar coeTInstType MetavarKind.synthetic let eNew := mkAppN (mkConst ``coe [u, v]) #[eType, expectedType, e, mvar] let mvarId := mvar.mvarId! try withoutMacroStackAtErr do if (← synthesizeCoeInstMVarCore mvarId) then expandCoe eNew else -- We create an auxiliary metavariable to represent the result, because we need to execute `expandCoe` -- after we syntheze `mvar` let mvarAux ← mkFreshExprMVar expectedType MetavarKind.syntheticOpaque registerSyntheticMVarWithCurrRef mvarAux.mvarId! (SyntheticMVarKind.coe errorMsgHeader? eNew expectedType eType e f?) return mvarAux catch | Exception.error _ msg => throwTypeMismatchError errorMsgHeader? expectedType eType e f? msg | _ => throwTypeMismatchError errorMsgHeader? expectedType eType e f? /-- Try to apply coercion to make sure `e` has type `expectedType`. Relevant definitions: ``` class CoeT (α : Sort u) (a : α) (β : Sort v) abbrev coe {α : Sort u} {β : Sort v} (a : α) [CoeT α a β] : β ``` -/ private def tryCoe (errorMsgHeader? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) : TermElabM Expr := do if (← isDefEq expectedType eType) then return e else match (← tryCoeThunk? expectedType eType e) with | some r => return r | none => mkCoe expectedType eType e f? errorMsgHeader? def isTypeApp? (type : Expr) : TermElabM (Option (Expr × Expr)) := do let type ← withReducible $ whnf type match type with | Expr.app m α _ => pure (some ((← instantiateMVars m), (← instantiateMVars α))) | _ => pure none def synthesizeInst (type : Expr) : TermElabM Expr := do let type ← instantiateMVars type match (← trySynthInstance type) with | LOption.some val => pure val | LOption.undef => throwError "failed to synthesize instance{indentExpr type}" | LOption.none => throwError "failed to synthesize instance{indentExpr type}" def isMonadApp (type : Expr) : TermElabM Bool := do let some (m, _) ← isTypeApp? type | pure false return (← isMonad? m) |>.isSome /-- Try to coerce `a : α` into `m β` by first coercing `a : α` into ‵β`, and then using `pure`. The method is only applied if `α` is not monadic (e.g., `Nat → IO Unit`), and the head symbol of the resulting type is not a metavariable (e.g., `?m Unit` or `Bool → ?m Nat`). The main limitation of the approach above is polymorphic code. As usual, coercions and polymorphism do not interact well. In the example above, the lift is successfully applied to `true`, `false` and `!y` since none of them is polymorphic ``` def f (x : Bool) : IO Bool := do let y ← if x == 0 then IO.println "hello"; true else false; !y ``` On the other hand, the following fails since `+` is polymorphic ``` def f (x : Bool) : IO Nat := do IO.prinln x x + x -- Error: failed to synthesize `Add (IO Nat)` ``` -/ private def tryPureCoe? (errorMsgHeader? : Option String) (m β α a : Expr) : TermElabM (Option Expr) := commitWhenSome? do let doIt : TermElabM (Option Expr) := do try let aNew ← tryCoe errorMsgHeader? β α a none let aNew ← mkPure m aNew pure (some aNew) catch _ => pure none forallTelescope α fun _ α => do if (← isMonadApp α) then pure none else if !α.getAppFn.isMVar then doIt else pure none /- Try coercions and monad lifts to make sure `e` has type `expectedType`. If `expectedType` is of the form `n β`, we try monad lifts and other extensions. Otherwise, we just use the basic `tryCoe`. Extensions for monads. Given an expected type of the form `n β`, if `eType` is of the form `α`, but not `m α` 1 - Try to coerce ‵α` into ‵β`, and use `pure` to lift it to `n α`. It only works if `n` implements `Pure` If `eType` is of the form `m α`. We use the following approaches. 1- Try to unify `n` and `m`. If it succeeds, then we use ``` coeM {m : Type u → Type v} {α β : Type u} [∀ a, CoeT α a β] [Monad m] (x : m α) : m β ``` `n` must be a `Monad` to use this one. 2- If there is monad lift from `m` to `n` and we can unify `α` and `β`, we use ``` liftM : ∀ {m : Type u_1 → Type u_2} {n : Type u_1 → Type u_3} [self : MonadLiftT m n] {α : Type u_1}, m α → n α ``` Note that `n` may not be a `Monad` in this case. This happens quite a bit in code such as ``` def g (x : Nat) : IO Nat := do IO.println x pure x def f {m} [MonadLiftT IO m] : m Nat := g 10 ``` 3- If there is a monad lif from `m` to `n` and a coercion from `α` to `β`, we use ``` liftCoeM {m : Type u → Type v} {n : Type u → Type w} {α β : Type u} [MonadLiftT m n] [∀ a, CoeT α a β] [Monad n] (x : m α) : n β ``` Note that approach 3 does not subsume 1 because it is only applicable if there is a coercion from `α` to `β` for all values in `α`. This is not the case for example for `pure $ x > 0` when the expected type is `IO Bool`. The given type is `IO Prop`, and we only have a coercion from decidable propositions. Approach 1 works because it constructs the coercion `CoeT (m Prop) (pure $ x > 0) (m Bool)` using the instance `pureCoeDepProp`. Note that, approach 2 is more powerful than `tryCoe`. Recall that type class resolution never assigns metavariables created by other modules. Now, consider the following scenario ```lean def g (x : Nat) : IO Nat := ... deg h (x : Nat) : StateT Nat IO Nat := do v ← g x; IO.Println v; ... ``` Let's assume there is no other occurrence of `v` in `h`. Thus, we have that the expected of `g x` is `StateT Nat IO ?α`, and the given type is `IO Nat`. So, even if we add a coercion. ``` instance {α m n} [MonadLiftT m n] {α} : Coe (m α) (n α) := ... ``` It is not applicable because TC would have to assign `?α := Nat`. On the other hand, TC can easily solve `[MonadLiftT IO (StateT Nat IO)]` since this goal does not contain any metavariables. And then, we convert `g x` into `liftM $ g x`. -/ private def tryLiftAndCoe (errorMsgHeader? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) : TermElabM Expr := do let expectedType ← instantiateMVars expectedType let eType ← instantiateMVars eType let throwMismatch {α} : TermElabM α := throwTypeMismatchError errorMsgHeader? expectedType eType e f? let tryCoeSimple : TermElabM Expr := tryCoe errorMsgHeader? expectedType eType e f? let some (n, β) ← isTypeApp? expectedType | tryCoeSimple let tryPureCoeAndSimple : TermElabM Expr := do if autoLift.get (← getOptions) then match (← tryPureCoe? errorMsgHeader? n β eType e) with | some eNew => pure eNew | none => tryCoeSimple else tryCoeSimple let some (m, α) ← isTypeApp? eType | tryPureCoeAndSimple if (← isDefEq m n) then let some monadInst ← isMonad? n | tryCoeSimple try expandCoe (← mkAppOptM ``coeM #[m, α, β, none, monadInst, e]) catch _ => throwMismatch else if autoLift.get (← getOptions) then try -- Construct lift from `m` to `n` let monadLiftType ← mkAppM ``MonadLiftT #[m, n] let monadLiftVal ← synthesizeInst monadLiftType let u_1 ← getDecLevel α let u_2 ← getDecLevel eType let u_3 ← getDecLevel expectedType let eNew := mkAppN (Lean.mkConst ``liftM [u_1, u_2, u_3]) #[m, n, monadLiftVal, α, e] let eNewType ← inferType eNew if (← isDefEq expectedType eNewType) then return eNew -- approach 2 worked else let some monadInst ← isMonad? n | tryCoeSimple let u ← getLevel α let v ← getLevel β let coeTInstType := Lean.mkForall `a BinderInfo.default α $ mkAppN (mkConst ``CoeT [u, v]) #[α, mkBVar 0, β] let coeTInstVal ← synthesizeInst coeTInstType let eNew ← expandCoe (← mkAppN (Lean.mkConst ``liftCoeM [u_1, u_2, u_3]) #[m, n, α, β, monadLiftVal, coeTInstVal, monadInst, e]) let eNewType ← inferType eNew unless (← isDefEq expectedType eNewType) do throwMismatch return eNew -- approach 3 worked catch _ => /- If `m` is not a monad, then we try to use `tryPureCoe?` and then `tryCoe?`. Otherwise, we just try `tryCoe?`. -/ match (← isMonad? m) with | none => tryPureCoeAndSimple | some _ => tryCoeSimple else tryCoeSimple /-- If `expectedType?` is `some t`, then ensure `t` and `eType` are definitionally equal. If they are not, then try coercions. Argument `f?` is used only for generating error messages. -/ def ensureHasTypeAux (expectedType? : Option Expr) (eType : Expr) (e : Expr) (f? : Option Expr := none) (errorMsgHeader? : Option String := none) : TermElabM Expr := do match expectedType? with | none => pure e | some expectedType => if (← isDefEq eType expectedType) then pure e else tryLiftAndCoe errorMsgHeader? expectedType eType e f? /-- If `expectedType?` is `some t`, then ensure `t` and type of `e` are definitionally equal. If they are not, then try coercions. -/ def ensureHasType (expectedType? : Option Expr) (e : Expr) (errorMsgHeader? : Option String := none) : TermElabM Expr := match expectedType? with | none => pure e | _ => do let eType ← inferType e ensureHasTypeAux expectedType? eType e none errorMsgHeader? private def mkSyntheticSorryFor (expectedType? : Option Expr) : TermElabM Expr := do let expectedType ← match expectedType? with | none => mkFreshTypeMVar | some expectedType => pure expectedType mkSyntheticSorry expectedType private def exceptionToSorry (ex : Exception) (expectedType? : Option Expr) : TermElabM Expr := do let syntheticSorry ← mkSyntheticSorryFor expectedType? logException ex pure syntheticSorry /-- If `mayPostpone == true`, throw `Expection.postpone`. -/ def tryPostpone : TermElabM Unit := do if (← read).mayPostpone then throwPostpone /-- If `mayPostpone == true` and `e`'s head is a metavariable, throw `Exception.postpone`. -/ def tryPostponeIfMVar (e : Expr) : TermElabM Unit := do if e.getAppFn.isMVar then let e ← instantiateMVars e if e.getAppFn.isMVar then tryPostpone def tryPostponeIfNoneOrMVar (e? : Option Expr) : TermElabM Unit := match e? with | some e => tryPostponeIfMVar e | none => tryPostpone def tryPostponeIfHasMVars (expectedType? : Option Expr) (msg : String) : TermElabM Expr := do tryPostponeIfNoneOrMVar expectedType? let some expectedType ← pure expectedType? | throwError "{msg}, expected type must be known" let expectedType ← instantiateMVars expectedType if expectedType.hasExprMVar then tryPostpone throwError "{msg}, expected type contains metavariables{indentExpr expectedType}" pure expectedType def saveContext : TermElabM SavedContext := return { macroStack := (← read).macroStack declName? := (← read).declName? options := (← getOptions) openDecls := (← getOpenDecls) errToSorry := (← read).errToSorry } def withSavedContext (savedCtx : SavedContext) (x : TermElabM α) : TermElabM α := do withReader (fun ctx => { ctx with declName? := savedCtx.declName?, macroStack := savedCtx.macroStack, errToSorry := savedCtx.errToSorry }) <| withTheReader Core.Context (fun ctx => { ctx with options := savedCtx.options, openDecls := savedCtx.openDecls }) x private def postponeElabTerm (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do trace[Elab.postpone] "{stx} : {expectedType?}" let mvar ← mkFreshExprMVar expectedType? MetavarKind.syntheticOpaque let ctx ← read registerSyntheticMVar stx mvar.mvarId! (SyntheticMVarKind.postponed (← saveContext)) pure mvar def getSyntheticMVarDecl? (mvarId : MVarId) : TermElabM (Option SyntheticMVarDecl) := return (← get).syntheticMVars.find? fun d => d.mvarId == mvarId /-- Create an auxiliary annotation to make sure we create a `Info` even if `e` is a metavariable. See `mkTermInfo`. We use this functions because some elaboration functions elaborate subterms that may not be immediately part of the resulting term. Example: ``` let_mvar% ?m := b; wait_if_type_mvar% ?m; body ``` If the type of `b` is not known, then `wait_if_type_mvar% ?m; body` is postponed and just return a fresh metavariable `?n`. The elaborator for ``` let_mvar% ?m := b; wait_if_type_mvar% ?m; body ``` returns `mkSaveInfoAnnotation ?n` to make sure the info nodes created when elaborating `b` are "saved". This is a bit hackish, but elaborators like `let_mvar%` are rare. -/ def mkSaveInfoAnnotation (e : Expr) : Expr := if e.isMVar then mkAnnotation `save_info e else e def isSaveInfoAnnotation? (e : Expr) : Option Expr := annotation? `save_info e partial def removeSaveInfoAnnotation (e : Expr) : Expr := match isSaveInfoAnnotation? e with | some e => removeSaveInfoAnnotation e | _ => e def mkTermInfo (elaborator : Name) (stx : Syntax) (e : Expr) (expectedType? : Option Expr := none) (lctx? : Option LocalContext := none) (isBinder := false) : TermElabM (Sum Info MVarId) := do let isHole? : TermElabM (Option MVarId) := do match e with | Expr.mvar mvarId _ => match (← getSyntheticMVarDecl? mvarId) with | some { kind := SyntheticMVarKind.tactic .., .. } => return mvarId | some { kind := SyntheticMVarKind.postponed .., .. } => return mvarId | _ => return none | _ => pure none match (← isHole?) with | some mvarId => return Sum.inr mvarId | none => let e := removeSaveInfoAnnotation e return Sum.inl <| Info.ofTermInfo { elaborator, lctx := lctx?.getD (← getLCtx), expr := e, stx, expectedType?, isBinder } def addTermInfo (stx : Syntax) (e : Expr) (expectedType? : Option Expr := none) (lctx? : Option LocalContext := none) (elaborator := Name.anonymous) (isBinder := false) : TermElabM Unit := do withInfoContext' (pure ()) (fun _ => mkTermInfo elaborator stx e expectedType? lctx? isBinder) |> discard /- Helper function for `elabTerm` is tries the registered elaboration functions for `stxNode` kind until it finds one that supports the syntax or an error is found. -/ private def elabUsingElabFnsAux (s : SavedState) (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone : Bool) : List (KeyedDeclsAttribute.AttributeEntry TermElab) → TermElabM Expr | [] => do throwError "unexpected syntax{indentD stx}" | (elabFn::elabFns) => try -- record elaborator in info tree, but only when not backtracking to other elaborators (outer `try`) withInfoContext' (mkInfo := mkTermInfo elabFn.declName (expectedType? := expectedType?) stx) (try elabFn.value stx expectedType? catch ex => match ex with | Exception.error ref msg => if (← read).errToSorry then exceptionToSorry ex expectedType? else throw ex | Exception.internal id _ => if (← read).errToSorry && id == abortTermExceptionId then exceptionToSorry ex expectedType? else if id == unsupportedSyntaxExceptionId then throw ex -- to outer try else if catchExPostpone && id == postponeExceptionId then /- If `elab` threw `Exception.postpone`, we reset any state modifications. For example, we want to make sure pending synthetic metavariables created by `elab` before it threw `Exception.postpone` are discarded. Note that we are also discarding the messages created by `elab`. For example, consider the expression. `((f.x a1).x a2).x a3` Now, suppose the elaboration of `f.x a1` produces an `Exception.postpone`. Then, a new metavariable `?m` is created. Then, `?m.x a2` also throws `Exception.postpone` because the type of `?m` is not yet known. Then another, metavariable `?n` is created, and finally `?n.x a3` also throws `Exception.postpone`. If we did not restore the state, we would keep "dead" metavariables `?m` and `?n` on the pending synthetic metavariable list. This is wasteful because when we resume the elaboration of `((f.x a1).x a2).x a3`, we start it from scratch and new metavariables are created for the nested functions. -/ s.restore postponeElabTerm stx expectedType? else throw ex) catch ex => match ex with | Exception.internal id _ => if id == unsupportedSyntaxExceptionId then s.restore -- also removes the info tree created above elabUsingElabFnsAux s stx expectedType? catchExPostpone elabFns else throw ex | _ => throw ex private def elabUsingElabFns (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone : Bool) : TermElabM Expr := do let s ← saveState let k := stx.getKind match termElabAttribute.getEntries (← getEnv) k with | [] => throwError "elaboration function for '{k}' has not been implemented{indentD stx}" | elabFns => elabUsingElabFnsAux s stx expectedType? catchExPostpone elabFns instance : MonadMacroAdapter TermElabM where getCurrMacroScope := getCurrMacroScope getNextMacroScope := return (← getThe Core.State).nextMacroScope setNextMacroScope next := modifyThe Core.State fun s => { s with nextMacroScope := next } private def isExplicit (stx : Syntax) : Bool := match stx with | `(@$f) => true | _ => false private def isExplicitApp (stx : Syntax) : Bool := stx.getKind == ``Lean.Parser.Term.app && isExplicit stx[0] /-- Return true if `stx` if a lambda abstraction containing a `{}` or `[]` binder annotation. Example: `fun {α} (a : α) => a` -/ private def isLambdaWithImplicit (stx : Syntax) : Bool := match stx with | `(fun $binders* => $body) => binders.any fun b => b.isOfKind ``Lean.Parser.Term.implicitBinder || b.isOfKind `Lean.Parser.Term.instBinder | _ => false private partial def dropTermParens : Syntax → Syntax := fun stx => match stx with | `(($stx)) => dropTermParens stx | _ => stx private def isHole (stx : Syntax) : Bool := match stx with | `(_) => true | `(? _) => true | `(? $x:ident) => true | _ => false private def isTacticBlock (stx : Syntax) : Bool := match stx with | `(by $x:tacticSeq) => true | _ => false private def isNoImplicitLambda (stx : Syntax) : Bool := match stx with | `(no_implicit_lambda% $x:term) => true | _ => false private def isTypeAscription (stx : Syntax) : Bool := match stx with | `(($e : $type)) => true | _ => false def mkNoImplicitLambdaAnnotation (type : Expr) : Expr := mkAnnotation `noImplicitLambda type def hasNoImplicitLambdaAnnotation (type : Expr) : Bool := annotation? `noImplicitLambda type |>.isSome /-- Block usage of implicit lambdas if `stx` is `@f` or `@f arg1 ...` or `fun` with an implicit binder annotation. -/ def blockImplicitLambda (stx : Syntax) : Bool := let stx := dropTermParens stx -- TODO: make it extensible isExplicit stx || isExplicitApp stx || isLambdaWithImplicit stx || isHole stx || isTacticBlock stx || isNoImplicitLambda stx || isTypeAscription stx /-- Return normalized expected type if it is of the form `{a : α} → β` or `[a : α] → β` and `blockImplicitLambda stx` is not true, else return `none`. Remark: implicit lambdas are not triggered by the strict implicit binder annotation `{{a : α}} → β` -/ private def useImplicitLambda? (stx : Syntax) (expectedType? : Option Expr) : TermElabM (Option Expr) := if blockImplicitLambda stx then return none else match expectedType? with | some expectedType => do if hasNoImplicitLambdaAnnotation expectedType then return none else let expectedType ← whnfForall expectedType match expectedType with | Expr.forallE _ _ _ c => if c.binderInfo.isImplicit || c.binderInfo.isInstImplicit then return some expectedType else return none | _ => return none | _ => return none private def decorateErrorMessageWithLambdaImplicitVars (ex : Exception) (impFVars : Array Expr) : TermElabM Exception := do match ex with | Exception.error ref msg => if impFVars.isEmpty then return Exception.error ref msg else let mut msg := m!"{msg}\nthe following variables have been introduced by the implicit lamda feature" for impFVar in impFVars do let auxMsg := m!"{impFVar} : {← inferType impFVar}" let auxMsg ← addMessageContext auxMsg msg := m!"{msg}{indentD auxMsg}" msg := m!"{msg}\nyou can disable implict lambdas using `@` or writing a lambda expression with `\{}` or `[]` binder annotations." return Exception.error ref msg | _ => return ex private def elabImplicitLambdaAux (stx : Syntax) (catchExPostpone : Bool) (expectedType : Expr) (impFVars : Array Expr) : TermElabM Expr := do let body ← elabUsingElabFns stx expectedType catchExPostpone try let body ← ensureHasType expectedType body let r ← mkLambdaFVars impFVars body trace[Elab.implicitForall] r pure r catch ex => throw (← decorateErrorMessageWithLambdaImplicitVars ex impFVars) private partial def elabImplicitLambda (stx : Syntax) (catchExPostpone : Bool) (type : Expr) : TermElabM Expr := loop type #[] where loop | type@(Expr.forallE n d b c), fvars => if c.binderInfo.isExplicit then elabImplicitLambdaAux stx catchExPostpone type fvars else withFreshMacroScope do let n ← MonadQuotation.addMacroScope n withLocalDecl n c.binderInfo d fun fvar => do let type ← whnfForall (b.instantiate1 fvar) loop type (fvars.push fvar) | type, fvars => elabImplicitLambdaAux stx catchExPostpone type fvars /- Main loop for `elabTerm` -/ private partial def elabTermAux (expectedType? : Option Expr) (catchExPostpone : Bool) (implicitLambda : Bool) : Syntax → TermElabM Expr | Syntax.missing => mkSyntheticSorryFor expectedType? | stx => withFreshMacroScope <| withIncRecDepth do trace[Elab.step] "expected type: {expectedType?}, term\n{stx}" checkMaxHeartbeats "elaborator" withNestedTraces do let env ← getEnv match (← liftMacroM (expandMacroImpl? env stx)) with | some (decl, Except.ok stxNew) => withInfoContext' (mkInfo := mkTermInfo decl (expectedType? := expectedType?) stx) <| withMacroExpansion stx stxNew <| withRef stxNew <| elabTermAux expectedType? catchExPostpone implicitLambda stxNew | _ => let implicit? ← if implicitLambda && (← read).implicitLambda then useImplicitLambda? stx expectedType? else pure none match implicit? with | some expectedType => elabImplicitLambda stx catchExPostpone expectedType | none => elabUsingElabFns stx expectedType? catchExPostpone /-- Store in the `InfoTree` that `e` is a "dot"-completion target. -/ def addDotCompletionInfo (stx : Syntax) (e : Expr) (expectedType? : Option Expr) (field? : Option Syntax := none) : TermElabM Unit := do addCompletionInfo <| CompletionInfo.dot { expr := e, stx, lctx := (← getLCtx), elaborator := Name.anonymous, expectedType? } (field? := field?) (expectedType? := expectedType?) /-- Main function for elaborating terms. It extracts the elaboration methods from the environment using the node kind. Recall that the environment has a mapping from `SyntaxNodeKind` to `TermElab` methods. It creates a fresh macro scope for executing the elaboration method. All unlogged trace messages produced by the elaboration method are logged using the position information at `stx`. If the elaboration method throws an `Exception.error` and `errToSorry == true`, the error is logged and a synthetic sorry expression is returned. If the elaboration throws `Exception.postpone` and `catchExPostpone == true`, a new synthetic metavariable of kind `SyntheticMVarKind.postponed` is created, registered, and returned. The option `catchExPostpone == false` is used to implement `resumeElabTerm` to prevent the creation of another synthetic metavariable when resuming the elaboration. If `implicitLambda == true`, then disable implicit lambdas feature for the given syntax, but not for its subterms. We use this flag to implement, for example, the `@` modifier. If `Context.implicitLambda == false`, then this parameter has no effect. -/ def elabTerm (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) (implicitLambda := true) : TermElabM Expr := withRef stx <| elabTermAux expectedType? catchExPostpone implicitLambda stx def elabTermEnsuringType (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) (implicitLambda := true) (errorMsgHeader? : Option String := none) : TermElabM Expr := do let e ← elabTerm stx expectedType? catchExPostpone implicitLambda withRef stx <| ensureHasType expectedType? e errorMsgHeader? /-- Execute `x` and then restore `syntheticMVars`, `levelNames`, `mvarErrorInfos`, and `letRecsToLift`. We use this combinator when we don't want the pending problems created by `x` to persist after its execution. -/ def withoutPending (x : TermElabM α) : TermElabM α := do let saved ← get try x finally modify fun s => { s with syntheticMVars := saved.syntheticMVars, levelNames := saved.levelNames, letRecsToLift := saved.letRecsToLift, mvarErrorInfos := saved.mvarErrorInfos } /-- Execute `x` and return `some` if no new errors were recorded or exceptions was thrown. Otherwise, return `none` -/ def commitIfNoErrors? (x : TermElabM α) : TermElabM (Option α) := do let saved ← saveState modify fun s => { s with messages := {} } try let a ← x if (← get).messages.hasErrors then restoreState saved return none else modify fun s => { s with messages := saved.elab.messages ++ s.messages } return a catch _ => restoreState saved return none /-- Adapt a syntax transformation to a regular, term-producing elaborator. -/ def adaptExpander (exp : Syntax → TermElabM Syntax) : TermElab := fun stx expectedType? => do let stx' ← exp stx withMacroExpansion stx stx' $ elabTerm stx' expectedType? def mkInstMVar (type : Expr) : TermElabM Expr := do let mvar ← mkFreshExprMVar type MetavarKind.synthetic let mvarId := mvar.mvarId! unless (← synthesizeInstMVarCore mvarId) do registerSyntheticMVarWithCurrRef mvarId SyntheticMVarKind.typeClass pure mvar /- Relevant definitions: ``` class CoeSort (α : Sort u) (β : outParam (Sort v)) abbrev coeSort {α : Sort u} {β : Sort v} (a : α) [CoeSort α β] : β ``` -/ private def tryCoeSort (α : Expr) (a : Expr) : TermElabM Expr := do let β ← mkFreshTypeMVar let u ← getLevel α let v ← getLevel β let coeSortInstType := mkAppN (Lean.mkConst ``CoeSort [u, v]) #[α, β] let mvar ← mkFreshExprMVar coeSortInstType MetavarKind.synthetic let mvarId := mvar.mvarId! try withoutMacroStackAtErr do if (← synthesizeCoeInstMVarCore mvarId) then let result ← expandCoe <| mkAppN (Lean.mkConst ``coeSort [u, v]) #[α, β, a, mvar] unless (← isType result) do throwError "failed to coerse{indentExpr a}\nto a type, after applying `coeSort`, result is still not a type{indentExpr result}\nthis is often due to incorrect `CoeSort` instances, the synthesized value for{indentExpr coeSortInstType}\nwas{indentExpr mvar}" return result else throwError "type expected" catch | Exception.error _ msg => throwError "type expected\n{msg}" | _ => throwError "type expected" /-- Make sure `e` is a type by inferring its type and making sure it is a `Expr.sort` or is unifiable with `Expr.sort`, or can be coerced into one. -/ def ensureType (e : Expr) : TermElabM Expr := do if (← isType e) then pure e else let eType ← inferType e let u ← mkFreshLevelMVar if (← isDefEq eType (mkSort u)) then pure e else tryCoeSort eType e /-- Elaborate `stx` and ensure result is a type. -/ def elabType (stx : Syntax) : TermElabM Expr := do let u ← mkFreshLevelMVar let type ← elabTerm stx (mkSort u) withRef stx $ ensureType type /-- Enable auto-bound implicits, and execute `k` while catching auto bound implicit exceptions. When an exception is caught, a new local declaration is created, registered, and `k` is tried to be executed again. -/ partial def withAutoBoundImplicit (k : TermElabM α) : TermElabM α := do let flag := autoBoundImplicitLocal.get (← getOptions) if flag then withReader (fun ctx => { ctx with autoBoundImplicit := flag, autoBoundImplicits := {} }) do let rec loop (s : SavedState) : TermElabM α := do try k catch | ex => match isAutoBoundImplicitLocalException? ex with | some n => -- Restore state, declare `n`, and try again s.restore withLocalDecl n BinderInfo.implicit (← mkFreshTypeMVar) fun x => withReader (fun ctx => { ctx with autoBoundImplicits := ctx.autoBoundImplicits.push x } ) do loop (← saveState) | none => throw ex loop (← saveState) else k def withoutAutoBoundImplicit (k : TermElabM α) : TermElabM α := do withReader (fun ctx => { ctx with autoBoundImplicit := false, autoBoundImplicits := {} }) k /-- Return `autoBoundImplicits ++ xs. This methoid throws an error if a variable in `autoBoundImplicits` depends on some `x` in `xs` -/ def addAutoBoundImplicits (xs : Array Expr) : TermElabM (Array Expr) := do let autoBoundImplicits := (← read).autoBoundImplicits for auto in autoBoundImplicits do let localDecl ← getLocalDecl auto.fvarId! for x in xs do if (← getMCtx).localDeclDependsOn localDecl x.fvarId! then throwError "invalid auto implicit argument '{auto}', it depends on explicitly provided argument '{x}'" return autoBoundImplicits.toArray ++ xs def mkAuxName (suffix : Name) : TermElabM Name := do match (← read).declName? with | none => throwError "auxiliary declaration cannot be created when declaration name is not available" | some declName => Lean.mkAuxName (declName ++ suffix) 1 builtin_initialize registerTraceClass `Elab.letrec /- Return true if mvarId is an auxiliary metavariable created for compiling `let rec` or it is delayed assigned to one. -/ def isLetRecAuxMVar (mvarId : MVarId) : TermElabM Bool := do trace[Elab.letrec] "mvarId: {mkMVar mvarId} letrecMVars: {(← get).letRecsToLift.map (mkMVar $ ·.mvarId)}" let mvarId := (← getMCtx).getDelayedRoot mvarId trace[Elab.letrec] "mvarId root: {mkMVar mvarId}" return (← get).letRecsToLift.any (·.mvarId == mvarId) def resolveLocalName (n : Name) : TermElabM (Option (Expr × List String)) := do let lctx ← getLCtx let view := extractMacroScopes n let rec loop (n : Name) (projs : List String) := match lctx.findFromUserName? { view with name := n }.review with | some decl => if decl.isAuxDecl && !projs.isEmpty then /- We do not consider dot notation for local decls corresponding to recursive functions being defined. The following example would not be elaborated correctly without this case. ``` def foo.aux := 1 def foo : Nat → Nat | n => foo.aux -- should not be interpreted as `(foo).bar` ``` -/ none else some (decl.toExpr, projs) | none => match n with | Name.str pre s _ => loop pre (s::projs) | _ => none return loop view.name [] /- Return true iff `stx` is a `Syntax.ident`, and it is a local variable. -/ def isLocalIdent? (stx : Syntax) : TermElabM (Option Expr) := match stx with | Syntax.ident _ _ val _ => do let r? ← resolveLocalName val match r? with | some (fvar, []) => pure (some fvar) | _ => pure none | _ => pure none /-- Create an `Expr.const` using the given name and explicit levels. Remark: fresh universe metavariables are created if the constant has more universe parameters than `explicitLevels`. -/ def mkConst (constName : Name) (explicitLevels : List Level := []) : TermElabM Expr := do let cinfo ← getConstInfo constName if explicitLevels.length > cinfo.levelParams.length then throwError "too many explicit universe levels for '{constName}'" else let numMissingLevels := cinfo.levelParams.length - explicitLevels.length let us ← mkFreshLevelMVars numMissingLevels return Lean.mkConst constName (explicitLevels ++ us) private def mkConsts (candidates : List (Name × List String)) (explicitLevels : List Level) : TermElabM (List (Expr × List String)) := do candidates.foldlM (init := []) fun result (constName, projs) => do -- TODO: better suppor for `mkConst` failure. We may want to cache the failures, and report them if all candidates fail. let const ← mkConst constName explicitLevels return (const, projs) :: result def resolveName (stx : Syntax) (n : Name) (preresolved : List (Name × List String)) (explicitLevels : List Level) (expectedType? : Option Expr := none) : TermElabM (List (Expr × List String)) := do try if let some (e, projs) ← resolveLocalName n then unless explicitLevels.isEmpty do throwError "invalid use of explicit universe parameters, '{e}' is a local" return [(e, projs)] -- check for section variable capture by a quotation let ctx ← read if let some (e, projs) := preresolved.findSome? fun (n, projs) => ctx.sectionFVars.find? n |>.map (·, projs) then return [(e, projs)] -- section variables should shadow global decls if preresolved.isEmpty then process (← resolveGlobalName n) else process preresolved catch ex => if preresolved.isEmpty && explicitLevels.isEmpty then addCompletionInfo <| CompletionInfo.id stx stx.getId (danglingDot := false) (← getLCtx) expectedType? throw ex where process (candidates : List (Name × List String)) : TermElabM (List (Expr × List String)) := do if candidates.isEmpty then if (← read).autoBoundImplicit && isValidAutoBoundImplicitName n then throwAutoBoundImplicitLocal n else throwError "unknown identifier '{Lean.mkConst n}'" if preresolved.isEmpty && explicitLevels.isEmpty then addCompletionInfo <| CompletionInfo.id stx stx.getId (danglingDot := false) (← getLCtx) expectedType? mkConsts candidates explicitLevels /-- Similar to `resolveName`, but creates identifiers for the main part and each projection with position information derived from `ident`. Example: Assume resolveName `v.head.bla.boo` produces `(v.head, ["bla", "boo"])`, then this method produces `(v.head, id, [f₁, f₂])` where `id` is an identifier for `v.head`, and `f₁` and `f₂` are identifiers for fields `"bla"` and `"boo"`. -/ def resolveName' (ident : Syntax) (explicitLevels : List Level) (expectedType? : Option Expr := none) : TermElabM (List (Expr × Syntax × List Syntax)) := do match ident with | Syntax.ident info rawStr n preresolved => let r ← resolveName ident n preresolved explicitLevels expectedType? r.mapM fun (c, fields) => do let ids := ident.identComponents (nFields? := fields.length) return (c, ids.head!, ids.tail!) | _ => throwError "identifier expected" def resolveId? (stx : Syntax) (kind := "term") (withInfo := false) : TermElabM (Option Expr) := match stx with | Syntax.ident _ _ val preresolved => do let rs ← try resolveName stx val preresolved [] catch _ => pure [] let rs := rs.filter fun ⟨f, projs⟩ => projs.isEmpty let fs := rs.map fun (f, _) => f match fs with | [] => pure none | [f] => if withInfo then addTermInfo stx f pure (some f) | _ => throwError "ambiguous {kind}, use fully qualified name, possible interpretations {fs}" | _ => throwError "identifier expected" private def mkSomeContext : Context := { fileName := "<TermElabM>" fileMap := arbitrary } def TermElabM.run (x : TermElabM α) (ctx : Context := mkSomeContext) (s : State := {}) : MetaM (α × State) := withConfig setElabConfig (x ctx |>.run s) @[inline] def TermElabM.run' (x : TermElabM α) (ctx : Context := mkSomeContext) (s : State := {}) : MetaM α := (·.1) <$> x.run ctx s def TermElabM.toIO (x : TermElabM α) (ctxCore : Core.Context) (sCore : Core.State) (ctxMeta : Meta.Context) (sMeta : Meta.State) (ctx : Context) (s : State) : IO (α × Core.State × Meta.State × State) := do let ((a, s), sCore, sMeta) ← (x.run ctx s).toIO ctxCore sCore ctxMeta sMeta pure (a, sCore, sMeta, s) instance [MetaEval α] : MetaEval (TermElabM α) where eval env opts x _ := let x : TermElabM α := do try x finally let s ← get s.messages.forM fun msg => do IO.println (← msg.toString) MetaEval.eval env opts (hideUnit := true) $ x.run' mkSomeContext unsafe def evalExpr (α) (typeName : Name) (value : Expr) : TermElabM α := withoutModifyingEnv do let name ← mkFreshUserName `_tmp let type ← inferType value let type ← whnfD type unless type.isConstOf typeName do throwError "unexpected type at evalExpr{indentExpr type}" let decl := Declaration.defnDecl { name := name, levelParams := [], type := type, value := value, hints := ReducibilityHints.opaque, safety := DefinitionSafety.unsafe } ensureNoUnassignedMVars decl addAndCompile decl evalConst α name private def throwStuckAtUniverseCnstr : TermElabM Unit := do -- This code assumes `entries` is not empty. Note that `processPostponed` uses `exceptionOnFailure` to guarantee this property let entries ← getPostponed let mut found : Std.HashSet (Level × Level) := {} let mut uniqueEntries := #[] for entry in entries do let mut lhs := entry.lhs let mut rhs := entry.rhs if Level.normLt rhs lhs then (lhs, rhs) := (rhs, lhs) unless found.contains (lhs, rhs) do found := found.insert (lhs, rhs) uniqueEntries := uniqueEntries.push entry for i in [1:uniqueEntries.size] do logErrorAt uniqueEntries[i].ref (← mkLevelStuckErrorMessage uniqueEntries[i]) throwErrorAt uniqueEntries[0].ref (← mkLevelStuckErrorMessage uniqueEntries[0]) def withoutPostponingUniverseConstraints (x : TermElabM α) : TermElabM α := do let postponed ← getResetPostponed try let a ← x unless (← processPostponed (mayPostpone := false) (exceptionOnFailure := true)) do throwStuckAtUniverseCnstr setPostponed postponed return a catch ex => setPostponed postponed throw ex end Term open Term in def withoutModifyingStateWithInfoAndMessages [MonadControlT TermElabM m] [Monad m] (x : m α) : m α := do controlAt TermElabM fun runInBase => withoutModifyingStateWithInfoAndMessagesImpl <| runInBase x builtin_initialize registerTraceClass `Elab.postpone registerTraceClass `Elab.coe registerTraceClass `Elab.debug export Term (TermElabM) end Lean.Elab
aed3f441ef6a72549401bae55ed50eda64d5172e
a9e33f9c83301c461f3c3ebc6799d9de1f6d4d20
/assignments/hw3_function_terms_lambda.lean
ca371add113c6e48ab05a751f13dad0a91db5d38
[]
no_license
yl4df/Discrete-Mathematics
f1c9a6cf8cfb4686fb617637f69a481e1522f0c2
c93ce9f6a6e36d194e350d9fa0a0360191e97fa0
refs/heads/master
1,598,714,938,443
1,572,275,647,000
1,572,275,647,000
218,074,726
0
0
null
null
null
null
UTF-8
Lean
false
false
7,031
lean
-- You can ignore this line for now, but don't remove it. namespace hw3 /- In this assignment, you will put into practice your new knowledge of terms and definitions in predicate logic by using it to implement a library of Boolean functions. You will also gain practice using different forms of syntax for defining functions. -/ /- To begin, we present one "unary" Boolean function (taking one Boolean argument and returning a Boolean result) and one "binary" function (taking two arguments), using each of three styles of syntax. -/ /- First, here are three implementations of exactly the same unary function, namely negation, in three styles. -/ -- explicitly lambda expression def neg_bool : bool → bool := λ (b : bool), match b with | ff := tt | tt := ff end -- by cases; note absence of := after function type def neg_bool' : bool → bool | ff := tt | tt := ff -- C-style; note return type is now between : and := def neg_bool'' (b : bool) : bool := match b with | ff := tt | tt := ff end /- Second, here are three implementations of exactly the same binary function (Boolean "and"), in the same three styles. -/ -- Note commas in match expression and in each case def and_bool : bool → bool → bool := λ (b1 b2 : bool), --shorthand for two lambdas match b1, b2 with -- matching on two arguments | ff, ff := ff | ff, tt := ff | tt, ff := ff | tt, tt := tt end -- Note absence of := and of commas in each of the cases def and_bool' : bool → bool → bool | ff ff := ff | ff tt := ff | tt ff := ff | tt tt := tt -- should seem straightforward now def and_bool'' (b1 b2 : bool) : bool := match b1, b2 with | ff, ff := ff | ff, tt := ff | tt, ff := ff | tt, tt := tt end /- Your homework is to implement the remaining unary Boolean functions, and several key binary Boolean functions, each one in each of these styles: lambda, by-cases, and C-style. -/ /- 1. Implement the always false unary Boolean function in each of the three styles, lambda, by-cases, and C-style. Call the functions false_bool, false_bool', and false_bool'', in that order. -/ -- Here's the first one, just to get you going. def false_bool : bool → bool := λ (b : bool), ff -- Now false_bool' def false_bool' : bool → bool | tt := ff | ff := ff -- And now false_bool'' def false_bool'' (b:bool) : bool := match b with | ff := ff | tt := ff end /- 2. Do the same for the always true unary Boolean function, using true_bool as the function name (with zero, one, and two ' marks to avoid name conflicts. You will use ' in this way for each of the remaining parts of this assignment). -/ def true_bool : bool → bool := λ (b : bool), tt def true_bool' : bool → bool | tt := tt | ff := tt def true_bool'' (b:bool) : bool := match b with | ff := tt | tt := tt end /- 3. Do the same for the unary Boolean identity function, using ident_bool (and ' variants) as the function name. -/ def ident_bool : bool → bool := λ (b : bool), match b with | ff := ff | tt := tt end def ident_bool' : bool → bool | tt := tt | ff := ff def ident_bool'' (b:bool) : bool := match b with | ff := ff | tt := tt end /- Congrats, you now have a small library of all unary Boolean functions. Now turn to the binary functions. Each will take two Boolean arguments, we can call them b1 and b2, and will return a Boolean result. -/ /- 4. The Boolean "or" function is true if and only if at least one of b1 and b2 is true. Equivalently it is false if and only if both b1 and b2 are false. Implement this function in each of the three styles, using or_bool as the function name. You may use the example of "and_bool" above as a model. While you could just cut and paste, we strongly recommend that you type your answers in full. Learning new syntax is an exercise is "muscle memory", so don't take shortcuts here. Learn the syntax now and it will save you frustration later. -/ def or_bool : bool → bool → bool := λ (b1 b2 : bool), match b1, b2 with |ff, ff := ff |ff, tt := tt |tt, ff := tt |tt, tt := tt end def or_bool' : bool → bool → bool |ff ff := ff |ff tt := tt |tt ff := tt |tt tt := tt def or_bool'' (b1 b2 : bool) : bool := match b1, b2 with |ff, ff := ff |ff, tt := tt |tt, ff := tt |tt, tt := tt end /- 5. The Boolean "exclusive or" function is true if and only if exactly one of its arguments is true. Implement this function in each style using xor_bool as the function name. -/ def xor_bool : bool → bool → bool := λ (b1 b2 : bool), match b1, b2 with |ff, ff := ff |ff, tt := tt |tt, ff := tt |tt, tt := ff end def xor_bool' : bool → bool → bool |ff ff := ff |ff tt := tt |tt ff := tt |tt tt := ff def xor_bool'' (b1 b2 : bool) : bool := match b1, b2 with |ff, ff := ff |ff, tt := tt |tt, ff := tt |tt, tt := ff end /- 6. The Boolean "implies" function is true if and only if either its first argument is false, or its first argument is true and its second argument is also true. Equivalently it is false if and only if its first argument is true and its second is false. Implement it in each style, calling it implies_bool. -/ def implies_bool : bool → bool → bool := λ (b1 b2 : bool), match b1, b2 with |ff, ff := tt |ff, tt := tt |tt, ff := ff |tt, tt := tt end def implies_bool' : bool → bool → bool |ff ff := tt |ff tt := tt |tt ff := ff |tt tt := tt def implies_bool'' (b1 b2 : bool) : bool := match b1, b2 with |ff, ff := tt |ff, tt := tt |tt, ff := ff |tt, tt := tt end /- 7. The Boolean "equivalent-to" function is true if its two arguments are the same, either both true or both false; otherwise it is false. Implement it in the three styles, using equiv_bool as a function name. -/ def equiv_bool : bool → bool → bool := λ (b1 b2 : bool), match b1, b2 with |ff, ff := tt |ff, tt := ff |tt, ff := ff |tt, tt := tt end def equiv_bool' : bool → bool → bool |ff ff := tt |ff tt := ff |tt ff := ff |tt tt := tt def equiv_bool'' (b1 b2 : bool) : bool := match b1, b2 with |ff, ff := tt |ff, tt := ff |tt, ff := ff |tt, tt := tt end -- leave the following in place as the last line in this file end hw3
9a5c21877a74a099ab64ed21534bf023a1441652
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/tactic/omega/coeffs.lean
81fbe2f2848fcbe04129576a52e3722f816e25fd
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
10,458
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Seul Baek -/ /- Non-constant terms of linear constraints are represented by storing their coefficients in integer lists. -/ import data.list.func import tactic.ring import tactic.omega.misc namespace omega namespace coeffs open list.func variable {v : nat → int} /-- `val_between v as l o` is the value (under valuation `v`) of the term obtained taking the term represented by `(0, as)` and dropping all subterms that include variables outside the range `[l,l+o)` -/ @[simp] def val_between (v : nat → int) (as : list int) (l : nat) : nat → int | 0 := 0 | (o+1) := (val_between o) + (get (l+o) as * v (l+o)) @[simp] lemma val_between_nil {l : nat} : ∀ m, val_between v [] l m = 0 | 0 := by simp only [val_between] | (m+1) := by simp only [val_between_nil m, omega.coeffs.val_between, get_nil, zero_add, zero_mul, int.default_eq_zero] /-- Evaluation of the nonconstant component of a normalized linear arithmetic term. -/ def val (v : nat → int) (as : list int) : int := val_between v as 0 as.length @[simp] lemma val_nil : val v [] = 0 := rfl lemma val_between_eq_of_le {as : list int} {l : nat} : ∀ m, as.length ≤ l + m → val_between v as l m = val_between v as l (as.length - l) | 0 h1 := by { rw add_zero at h1, rw tsub_eq_zero_iff_le.mpr h1 } | (m+1) h1 := begin rw le_iff_eq_or_lt at h1, cases h1, { rw [h1, add_comm l, add_tsub_cancel_right] }, have h2 : list.length as ≤ l + m, { rw ← nat.lt_succ_iff, apply h1 }, simpa [ get_eq_default_of_le _ h2, zero_mul, add_zero, val_between ] using val_between_eq_of_le _ h2 end lemma val_eq_of_le {as : list int} {k : nat} : as.length ≤ k → val v as = val_between v as 0 k := begin intro h1, unfold val, rw [val_between_eq_of_le k _], refl, rw zero_add, exact h1 end lemma val_between_eq_val_between {v w : nat → int} {as bs : list int} {l : nat} : ∀ {m}, (∀ x, l ≤ x → x < l + m → v x = w x) → (∀ x, l ≤ x → x < l + m → get x as = get x bs) → val_between v as l m = val_between w bs l m | 0 h1 h2 := rfl | (m+1) h1 h2 := begin unfold val_between, have h3 : l + m < l + (m + 1), { rw ← add_assoc, apply lt_add_one }, apply fun_mono_2, apply val_between_eq_val_between; intros x h4 h5, { apply h1 _ h4 (lt_trans h5 h3) }, { apply h2 _ h4 (lt_trans h5 h3) }, rw [h1 _ _ h3, h2 _ _ h3]; apply nat.le_add_right end open_locale list.func lemma val_between_set {a : int} {l n : nat} : ∀ {m}, l ≤ n → n < l + m → val_between v ([] {n ↦ a}) l m = a * v n | 0 h1 h2 := begin exfalso, apply lt_irrefl l (lt_of_le_of_lt h1 h2) end | (m+1) h1 h2 := begin rw [← add_assoc, nat.lt_succ_iff, le_iff_eq_or_lt] at h2, cases h2; unfold val_between, { have h3 : val_between v ([] {l + m ↦ a}) l m = 0, { apply @eq.trans _ _ (val_between v [] l m), { apply val_between_eq_val_between, { intros, refl }, { intros x h4 h5, rw [get_nil, get_set_eq_of_ne, get_nil], apply ne_of_lt h5 } }, apply val_between_nil }, rw h2, simp only [h3, zero_add, list.func.get_set] }, { have h3 : l + m ≠ n, { apply ne_of_gt h2 }, rw [@val_between_set m h1 h2, get_set_eq_of_ne _ _ h3], simp only [h3, get_nil, add_zero, zero_mul, int.default_eq_zero] } end @[simp] lemma val_set {m : nat} {a : int} : val v ([] {m ↦ a}) = a * v m := begin apply val_between_set (zero_le _), rw [length_set, zero_add], exact lt_max_of_lt_right (lt_add_one _), end lemma val_between_neg {as : list int} {l : nat} : ∀ {o}, val_between v (neg as) l o = -(val_between v as l o) | 0 := rfl | (o+1) := begin unfold val_between, rw [neg_add, neg_mul_eq_neg_mul], apply fun_mono_2, apply val_between_neg, apply fun_mono_2 _ rfl, apply get_neg end @[simp] lemma val_neg {as : list int} : val v (neg as) = -(val v as) := by simpa only [val, length_neg] using val_between_neg lemma val_between_add {is js : list int} {l : nat} : ∀ m, val_between v (add is js) l m = (val_between v is l m) + (val_between v js l m) | 0 := rfl | (m+1) := by { simp only [val_between, val_between_add m, list.func.get, get_add], ring } @[simp] lemma val_add {is js : list int} : val v (add is js) = (val v is) + (val v js) := begin unfold val, rw val_between_add, apply fun_mono_2; apply val_between_eq_of_le; rw [zero_add, length_add], apply le_max_left, apply le_max_right end lemma val_between_sub {is js : list int} {l : nat} : ∀ m, val_between v (sub is js) l m = (val_between v is l m) - (val_between v js l m) | 0 := rfl | (m+1) := by { simp only [val_between, val_between_sub m, list.func.get, get_sub], ring } @[simp] lemma val_sub {is js : list int} : val v (sub is js) = (val v is) - (val v js) := begin unfold val, rw val_between_sub, apply fun_mono_2; apply val_between_eq_of_le; rw [zero_add, length_sub], apply le_max_left, apply le_max_right end /-- `val_except k v as` is the value (under valuation `v`) of the term obtained taking the term represented by `(0, as)` and dropping the subterm that includes the `k`th variable. -/ def val_except (k : nat) (v : nat → int) (as) := val_between v as 0 k + val_between v as (k+1) (as.length - (k+1)) lemma val_except_eq_val_except {k : nat} {is js : list int} {v w : nat → int} : (∀ x ≠ k, v x = w x) → (∀ x ≠ k, get x is = get x js) → val_except k v is = val_except k w js := begin intros h1 h2, unfold val_except, apply fun_mono_2, { apply val_between_eq_val_between; intros x h3 h4; [ {apply h1}, {apply h2} ]; apply ne_of_lt; rw zero_add at h4; apply h4 }, { repeat { rw ← val_between_eq_of_le ((max is.length js.length) - (k+1)) }, { apply val_between_eq_val_between; intros x h3 h4; [ {apply h1}, {apply h2} ]; apply ne.symm; apply ne_of_lt; rw nat.lt_iff_add_one_le; exact h3 }, { refine le_trans (le_max_right _ _) le_add_tsub }, { refine le_trans (le_max_left _ _) le_add_tsub } } end open_locale omega lemma val_except_update_set {n : nat} {as : list int} {i j : int} : val_except n (v⟨n ↦ i⟩) (as {n ↦ j}) = val_except n v as := by apply val_except_eq_val_except update_eq_of_ne (get_set_eq_of_ne _) lemma val_between_add_val_between {as : list int} {l m : nat} : ∀ {n}, val_between v as l m + val_between v as (l+m) n = val_between v as l (m+n) | 0 := by simp only [val_between, add_zero] | (n+1) := begin rw ← add_assoc, unfold val_between, rw add_assoc, rw ← @val_between_add_val_between n, ring, end lemma val_except_add_eq (n : nat) {as : list int} : (val_except n v as) + ((get n as) * (v n)) = val v as := begin unfold val_except, unfold val, cases le_total (n + 1) as.length with h1 h1, { have h4 := @val_between_add_val_between v as 0 (n+1) (as.length - (n+1)), have h5 : n + 1 + (as.length - (n + 1)) = as.length, { rw [add_comm, tsub_add_cancel_of_le h1] }, rw h5 at h4, apply eq.trans _ h4, simp only [val_between, zero_add], ring }, have h2 : list.length as - (n + 1) = 0, { exact tsub_eq_zero_iff_le.mpr h1 }, have h3 : val_between v as 0 (list.length as) = val_between v as 0 (n + 1), { simpa only [val] using @val_eq_of_le v as (n+1) h1 }, simp only [add_zero, val_between, zero_add, h2, h3] end @[simp] lemma val_between_map_mul {i : int} {as: list int} {l : nat} : ∀ {m}, val_between v (list.map ((*) i) as) l m = i * val_between v as l m | 0 := by simp only [val_between, mul_zero, list.map] | (m+1) := begin unfold val_between, rw [@val_between_map_mul m, mul_add], apply fun_mono_2 rfl, by_cases h1 : l + m < as.length, { rw [get_map h1, mul_assoc] }, rw not_lt at h1, rw [get_eq_default_of_le, get_eq_default_of_le]; try {simp}; apply h1 end lemma forall_val_dvd_of_forall_mem_dvd {i : int} {as : list int} : (∀ x ∈ as, i ∣ x) → (∀ n, i ∣ get n as) | h1 n := by { apply forall_val_of_forall_mem _ h1, apply dvd_zero } lemma dvd_val_between {i} {as: list int} {l : nat} : ∀ {m}, (∀ x ∈ as, i ∣ x) → (i ∣ val_between v as l m) | 0 h1 := dvd_zero _ | (m+1) h1 := begin unfold val_between, apply dvd_add, apply dvd_val_between h1, apply dvd_mul_of_dvd_left, by_cases h2 : get (l+m) as = 0, { rw h2, apply dvd_zero }, apply h1, apply mem_get_of_ne_zero h2 end lemma dvd_val {as : list int} {i : int} : (∀ x ∈ as, i ∣ x) → (i ∣ val v as) := by apply dvd_val_between @[simp] lemma val_between_map_div {as: list int} {i : int} {l : nat} (h1 : ∀ x ∈ as, i ∣ x) : ∀ {m}, val_between v (list.map (λ x, x / i) as) l m = (val_between v as l m) / i | 0 := by simp only [int.zero_div, val_between, list.map] | (m+1) := begin unfold val_between, rw [@val_between_map_div m, int.add_div_of_dvd_right], apply fun_mono_2 rfl, { apply calc get (l + m) (list.map (λ (x : ℤ), x / i) as) * v (l + m) = ((get (l + m) as) / i) * v (l + m) : begin apply fun_mono_2 _ rfl, rw get_map', apply int.zero_div end ... = get (l + m) as * v (l + m) / i : begin repeat {rw mul_comm _ (v (l+m))}, rw int.mul_div_assoc, apply forall_val_dvd_of_forall_mem_dvd h1 end }, apply dvd_mul_of_dvd_left, apply forall_val_dvd_of_forall_mem_dvd h1, end @[simp] lemma val_map_div {as : list int} {i : int} : (∀ x ∈ as, i ∣ x) → val v (list.map (λ x, x / i) as) = (val v as) / i := by {intro h1, simpa only [val, list.length_map] using val_between_map_div h1} lemma val_between_eq_zero {is: list int} {l : nat} : ∀ {m}, (∀ x : int, x ∈ is → x = 0) → val_between v is l m = 0 | 0 h1 := rfl | (m+1) h1 := begin have h2 := @forall_val_of_forall_mem _ _ is (λ x, x = 0) rfl h1, simpa only [val_between, h2 (l+m), zero_mul, add_zero] using @val_between_eq_zero m h1, end lemma val_eq_zero {is : list int} : (∀ x : int, x ∈ is → x = 0) → val v is = 0 := by apply val_between_eq_zero end coeffs end omega
0b6c2c54652f066041410b99ac4556f8cf3e0159
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/axioms_of.lean
9adad7a53311a7383eb0907cd1bc3cebbc6c0b17
[ "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
243
lean
import data.finset data.rat print axioms nat.add print "-----" print axioms int.add print "-----" print axioms rat.add print "-----" print axioms finset.union print "-----" print axioms finset.mem print "-----" print axioms finset.union_comm
9f9130799d88e61ff1f2d575c74de1c34003f6e3
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/compiler/str.lean
69db1e35d5a0546d6d8d86f324a711c721071d68
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
937
lean
def showChars : Nat → String → String.Pos → IO Unit | 0, _, _ => pure () | n+1, s, idx => do unless s.atEnd idx do IO.println (">> " ++ toString (s.get idx)) *> showChars n s (s.next idx) def main : IO UInt32 := let s₁ := "hello α_world_β"; let b : String.Pos := 0; let e := s₁.bsize; IO.println (s₁.extract b e) *> IO.println (s₁.extract (b+2) e) *> IO.println (s₁.extract (b+2) (e-1)) *> IO.println (s₁.extract (b+2) (e-2)) *> IO.println (s₁.extract (b+7) e) *> IO.println (s₁.extract (b+8) e) *> IO.println (toString e) *> IO.println (repr " aaa ".trim) *> showChars s₁.length s₁ 0 *> IO.println ("abc".isPrefixOf "abcd") *> IO.println ("abcd".isPrefixOf "abcd") *> IO.println ("".isPrefixOf "abcd") *> IO.println ("".isPrefixOf "") *> IO.println ("ab".isPrefixOf "cb") *> IO.println ("ab".isPrefixOf "a") *> IO.println ("αb".isPrefixOf "αbc") *> pure 0
c2561b5b652c2d0c65a20e0d193055938c958e15
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/order/closure.lean
b3b6e056750be5fd7442b8420583ecf36a92a96c
[ "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
17,374
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, Yaël Dillies -/ import data.set_like.basic import order.preorder_hom import order.galois_connection import tactic.monotonicity /-! # Closure operators between preorders We define (bundled) closure operators on a preorder as monotone (increasing), extensive (inflationary) and idempotent functions. We define closed elements for the operator as elements which are fixed by it. Lower adjoints to a function between preorders `u : β → α` allow to generalise closure operators to situations where the closure operator we are dealing with naturally decomposes as `u ∘ l` where `l` is a worthy function to have on its own. Typical examples include `l : set G → subgroup G := subgroup.closure`, `u : subgroup G → set G := coe`, where `G` is a group. This shows there is a close connection between closure operators, lower adjoints and Galois connections/insertions: every Galois connection induces a lower adjoint which itself induces a closure operator by composition (see `galois_connection.lower_adjoint` and `lower_adjoint.closure_operator`), and every closure operator on a partial order induces a Galois insertion from the set of closed elements to the underlying type (see `closure_operator.gi`). ## Main definitions * `closure_operator`: A closure operator is a monotone function `f : α → α` such that `∀ x, x ≤ f x` and `∀ x, f (f x) = f x`. * `lower_adjoint`: A lower adjoint to `u : β → α` is a function `l : α → β` such that `l` and `u` form a Galois connection. ## Implementation details Although `lower_adjoint` is technically a generalisation of `closure_operator` (by defining `to_fun := id`), it is desirable to have both as otherwise `id`s would be carried all over the place when using concrete closure operators such as `convex_hull`. `lower_adjoint` really is a semibundled `structure` version of `galois_connection`. ## References * https://en.wikipedia.org/wiki/Closure_operator#Closure_operators_on_partially_ordered_sets -/ universe u /-! ### Closure operator -/ variable (α : Type*) /-- A closure operator on the preorder `α` is a monotone function which is extensive (every `x` is less than its closure) and idempotent. -/ structure closure_operator [preorder α] extends α →ₘ α := (le_closure' : ∀ x, x ≤ to_fun x) (idempotent' : ∀ x, to_fun (to_fun x) = to_fun x) namespace closure_operator instance [preorder α] : has_coe_to_fun (closure_operator α) (λ _, α → α) := ⟨λ c, c.to_fun⟩ /-- See Note [custom simps projection] -/ def simps.apply [preorder α] (f : closure_operator α) : α → α := f initialize_simps_projections closure_operator (to_preorder_hom_to_fun → apply, -to_preorder_hom) section partial_order variable [partial_order α] /-- The identity function as a closure operator. -/ @[simps] def id : closure_operator α := { to_preorder_hom := preorder_hom.id, le_closure' := λ _, le_rfl, idempotent' := λ _, rfl } instance : inhabited (closure_operator α) := ⟨id α⟩ variables {α} (c : closure_operator α) @[ext] lemma ext : ∀ (c₁ c₂ : closure_operator α), (c₁ : α → α) = (c₂ : α → α) → c₁ = c₂ | ⟨⟨c₁, _⟩, _, _⟩ ⟨⟨c₂, _⟩, _, _⟩ h := by { congr, exact h } /-- Constructor for a closure operator using the weaker idempotency axiom: `f (f x) ≤ f x`. -/ @[simps] def mk' (f : α → α) (hf₁ : monotone f) (hf₂ : ∀ x, x ≤ f x) (hf₃ : ∀ x, f (f x) ≤ f x) : closure_operator α := { to_fun := f, monotone' := hf₁, le_closure' := hf₂, idempotent' := λ x, (hf₃ x).antisymm (hf₁ (hf₂ x)) } /-- Convenience constructor for a closure operator using the weaker minimality axiom: `x ≤ f y → f x ≤ f y`, which is sometimes easier to prove in practice. -/ @[simps] def mk₂ (f : α → α) (hf : ∀ x, x ≤ f x) (hmin : ∀ ⦃x y⦄, x ≤ f y → f x ≤ f y) : closure_operator α := { to_fun := f, monotone' := λ x y hxy, hmin (hxy.trans (hf y)), le_closure' := hf, idempotent' := λ x, (hmin le_rfl).antisymm (hf _) } /-- Expanded out version of `mk₂`. `p` implies being closed. This constructor should be used when you already know a sufficient condition for being closed and using `mem_mk₃_closed` will avoid you the (slight) hassle of having to prove it both inside and outside the constructor. -/ @[simps] def mk₃ (f : α → α) (p : α → Prop) (hf : ∀ x, x ≤ f x) (hfp : ∀ x, p (f x)) (hmin : ∀ ⦃x y⦄, x ≤ y → p y → f x ≤ y) : closure_operator α := mk₂ f hf (λ x y hxy, hmin hxy (hfp y)) /-- This lemma shows that the image of `x` of a closure operator built from the `mk₃` constructor respects `p`, the property that was fed into it. -/ lemma closure_mem_mk₃ {f : α → α} {p : α → Prop} {hf : ∀ x, x ≤ f x} {hfp : ∀ x, p (f x)} {hmin : ∀ ⦃x y⦄, x ≤ y → p y → f x ≤ y} (x : α) : p (mk₃ f p hf hfp hmin x) := hfp x /-- Analogue of `closure_le_closed_iff_le` but with the `p` that was fed into the `mk₃` constructor. -/ lemma closure_le_mk₃_iff {f : α → α} {p : α → Prop} {hf : ∀ x, x ≤ f x} {hfp : ∀ x, p (f x)} {hmin : ∀ ⦃x y⦄, x ≤ y → p y → f x ≤ y} {x y : α} (hxy : x ≤ y) (hy : p y) : mk₃ f p hf hfp hmin x ≤ y := hmin hxy hy @[mono] lemma monotone : monotone c := c.monotone' /-- Every element is less than its closure. This property is sometimes referred to as extensivity or inflationarity. -/ lemma le_closure (x : α) : x ≤ c x := c.le_closure' x @[simp] lemma idempotent (x : α) : c (c x) = c x := c.idempotent' x lemma le_closure_iff (x y : α) : x ≤ c y ↔ c x ≤ c y := ⟨λ h, c.idempotent y ▸ c.monotone h, λ h, (c.le_closure x).trans h⟩ /-- An element `x` is closed for the closure operator `c` if it is a fixed point for it. -/ def closed : set α := λ x, c x = x lemma mem_closed_iff (x : α) : x ∈ c.closed ↔ c x = x := iff.rfl lemma mem_closed_iff_closure_le (x : α) : x ∈ c.closed ↔ c x ≤ x := ⟨le_of_eq, λ h, h.antisymm (c.le_closure x)⟩ lemma closure_eq_self_of_mem_closed {x : α} (h : x ∈ c.closed) : c x = x := h @[simp] lemma closure_is_closed (x : α) : c x ∈ c.closed := c.idempotent x /-- The set of closed elements for `c` is exactly its range. -/ lemma closed_eq_range_close : c.closed = set.range c := set.ext $ λ x, ⟨λ h, ⟨x, h⟩, by { rintro ⟨y, rfl⟩, apply c.idempotent }⟩ /-- Send an `x` to an element of the set of closed elements (by taking the closure). -/ def to_closed (x : α) : c.closed := ⟨c x, c.closure_is_closed x⟩ @[simp] lemma closure_le_closed_iff_le (x : α) {y : α} (hy : c.closed y) : c x ≤ y ↔ x ≤ y := by rw [←c.closure_eq_self_of_mem_closed hy, ←le_closure_iff] /-- A closure operator is equal to the closure operator obtained by feeding `c.closed` into the `mk₃` constructor. -/ lemma eq_mk₃_closed (c : closure_operator α) : c = mk₃ c c.closed c.le_closure c.closure_is_closed (λ x y hxy hy, (c.closure_le_closed_iff_le x hy).2 hxy) := by { ext, refl } /-- The property `p` fed into the `mk₃` constructor implies being closed. -/ lemma mem_mk₃_closed {f : α → α} {p : α → Prop} {hf : ∀ x, x ≤ f x} {hfp : ∀ x, p (f x)} {hmin : ∀ ⦃x y⦄, x ≤ y → p y → f x ≤ y} {x : α} (hx : p x) : x ∈ (mk₃ f p hf hfp hmin).closed := (hmin (le_refl _) hx).antisymm (hf _) end partial_order variable {α} section order_top variables [partial_order α] [order_top α] (c : closure_operator α) @[simp] lemma closure_top : c ⊤ = ⊤ := le_top.antisymm (c.le_closure _) lemma top_mem_closed : ⊤ ∈ c.closed := c.closure_top end order_top lemma closure_inf_le [semilattice_inf α] (c : closure_operator α) (x y : α) : c (x ⊓ y) ≤ c x ⊓ c y := c.monotone.map_inf_le _ _ section semilattice_sup variables [semilattice_sup α] (c : closure_operator α) lemma closure_sup_closure_le (x y : α) : c x ⊔ c y ≤ c (x ⊔ y) := c.monotone.le_map_sup _ _ lemma closure_sup_closure_left (x y : α) : c (c x ⊔ y) = c (x ⊔ y) := ((c.le_closure_iff _ _).1 (sup_le (c.monotone le_sup_left) (le_sup_right.trans (c.le_closure _)))).antisymm (c.monotone (sup_le_sup_right (c.le_closure _) _)) lemma closure_sup_closure_right (x y : α) : c (x ⊔ c y) = c (x ⊔ y) := by rw [sup_comm, closure_sup_closure_left, sup_comm] lemma closure_sup_closure (x y : α) : c (c x ⊔ c y) = c (x ⊔ y) := by rw [closure_sup_closure_left, closure_sup_closure_right] end semilattice_sup section complete_lattice variables [complete_lattice α] (c : closure_operator α) lemma closure_supr_closure {ι : Type u} (x : ι → α) : c (⨆ i, c (x i)) = c (⨆ i, x i) := le_antisymm ((c.le_closure_iff _ _).1 (supr_le (λ i, c.monotone (le_supr x i)))) (c.monotone (supr_le_supr (λ i, c.le_closure _))) lemma closure_bsupr_closure (p : α → Prop) : c (⨆ x (H : p x), c x) = c (⨆ x (H : p x), x) := le_antisymm ((c.le_closure_iff _ _).1 (bsupr_le (λ x hx, c.monotone (le_bsupr_of_le x hx (le_refl x))))) (c.monotone (bsupr_le_bsupr (λ x hx, c.le_closure x))) end complete_lattice end closure_operator /-! ### Lower adjoint -/ variables {α} {β : Type*} /-- A lower adjoint of `u` on the preorder `α` is a function `l` such that `l` and `u` form a Galois connection. It allows us to define closure operators whose output does not match the input. In practice, `u` is often `coe : β → α`. -/ structure lower_adjoint [preorder α] [preorder β] (u : β → α) := (to_fun : α → β) (gc' : galois_connection to_fun u) namespace lower_adjoint variable (α) /-- The identity function as a lower adjoint to itself. -/ @[simps] protected def id [preorder α] : lower_adjoint (id : α → α) := { to_fun := λ x, x, gc' := galois_connection.id } variable {α} instance [preorder α] : inhabited (lower_adjoint (id : α → α)) := ⟨lower_adjoint.id α⟩ section preorder variables [preorder α] [preorder β] {u : β → α} (l : lower_adjoint u) instance : has_coe_to_fun (lower_adjoint u) (λ _, α → β) := { coe := to_fun } /-- See Note [custom simps projection] -/ def simps.apply : α → β := l lemma gc : galois_connection l u := l.gc' @[ext] lemma ext : ∀ (l₁ l₂ : lower_adjoint u), (l₁ : α → β) = (l₂ : α → β) → l₁ = l₂ | ⟨l₁, _⟩ ⟨l₂, _⟩ h := by { congr, exact h } @[mono] lemma monotone : monotone (u ∘ l) := l.gc.monotone_u.comp l.gc.monotone_l /-- Every element is less than its closure. This property is sometimes referred to as extensivity or inflationarity. -/ lemma le_closure (x : α) : x ≤ u (l x) := l.gc.le_u_l _ end preorder section partial_order variables [partial_order α] [preorder β] {u : β → α} (l : lower_adjoint u) /-- Every lower adjoint induces a closure operator given by the composition. This is the partial order version of the statement that every adjunction induces a monad. -/ @[simps] def closure_operator : closure_operator α := { to_fun := λ x, u (l x), monotone' := l.monotone, le_closure' := l.le_closure, idempotent' := λ x, l.gc.u_l_u_eq_u (l x) } lemma idempotent (x : α) : u (l (u (l x))) = u (l x) := l.closure_operator.idempotent _ lemma le_closure_iff (x y : α) : x ≤ u (l y) ↔ u (l x) ≤ u (l y) := l.closure_operator.le_closure_iff _ _ end partial_order section preorder variables [preorder α] [preorder β] {u : β → α} (l : lower_adjoint u) /-- An element `x` is closed for `l : lower_adjoint u` if it is a fixed point: `u (l x) = x` -/ def closed : set α := λ x, u (l x) = x lemma mem_closed_iff (x : α) : x ∈ l.closed ↔ u (l x) = x := iff.rfl lemma closure_eq_self_of_mem_closed {x : α} (h : x ∈ l.closed) : u (l x) = x := h end preorder section partial_order variables [partial_order α] [partial_order β] {u : β → α} (l : lower_adjoint u) lemma mem_closed_iff_closure_le (x : α) : x ∈ l.closed ↔ u (l x) ≤ x := l.closure_operator.mem_closed_iff_closure_le _ @[simp] lemma closure_is_closed (x : α) : u (l x) ∈ l.closed := l.idempotent x /-- The set of closed elements for `l` is the range of `u ∘ l`. -/ lemma closed_eq_range_close : l.closed = set.range (u ∘ l) := l.closure_operator.closed_eq_range_close /-- Send an `x` to an element of the set of closed elements (by taking the closure). -/ def to_closed (x : α) : l.closed := ⟨u (l x), l.closure_is_closed x⟩ @[simp] lemma closure_le_closed_iff_le (x : α) {y : α} (hy : l.closed y) : u (l x) ≤ y ↔ x ≤ y := l.closure_operator.closure_le_closed_iff_le x hy end partial_order lemma closure_top [partial_order α] [order_top α] [preorder β] {u : β → α} (l : lower_adjoint u) : u (l ⊤) = ⊤ := l.closure_operator.closure_top lemma closure_inf_le [semilattice_inf α] [preorder β] {u : β → α} (l : lower_adjoint u) (x y : α) : u (l (x ⊓ y)) ≤ u (l x) ⊓ u (l y) := l.closure_operator.closure_inf_le x y section semilattice_sup variables [semilattice_sup α] [preorder β] {u : β → α} (l : lower_adjoint u) lemma closure_sup_closure_le (x y : α) : u (l x) ⊔ u (l y) ≤ u (l (x ⊔ y)) := l.closure_operator.closure_sup_closure_le x y lemma closure_sup_closure_left (x y : α) : u (l (u (l x) ⊔ y)) = u (l (x ⊔ y)) := l.closure_operator.closure_sup_closure_left x y lemma closure_sup_closure_right (x y : α) : u (l (x ⊔ u (l y))) = u (l (x ⊔ y)) := l.closure_operator.closure_sup_closure_right x y lemma closure_sup_closure (x y : α) : u (l (u (l x) ⊔ u (l y))) = u (l (x ⊔ y)) := l.closure_operator.closure_sup_closure x y end semilattice_sup section complete_lattice variables [complete_lattice α] [preorder β] {u : β → α} (l : lower_adjoint u) lemma closure_supr_closure {ι : Type u} (x : ι → α) : u (l (⨆ i, u (l (x i)))) = u (l (⨆ i, x i)) := l.closure_operator.closure_supr_closure x lemma closure_bsupr_closure (p : α → Prop) : u (l (⨆ x (H : p x), u (l x))) = u (l (⨆ x (H : p x), x)) := l.closure_operator.closure_bsupr_closure p end complete_lattice /- Lemmas for `lower_adjoint (coe : α → set β)`, where `set_like α β` -/ section coe_to_set variables [set_like α β] (l : lower_adjoint (coe : α → set β)) lemma subset_closure (s : set β) : s ⊆ l s := l.le_closure s lemma not_mem_of_not_mem_closure {s : set β} {P : β} (hP : P ∉ l s) : P ∉ s := λ h, hP (subset_closure _ s h) lemma le_iff_subset (s : set β) (S : α) : l s ≤ S ↔ s ⊆ S := l.gc s S lemma mem_iff (s : set β) (x : β) : x ∈ l s ↔ ∀ S : α, s ⊆ S → x ∈ S := by { simp_rw [←set_like.mem_coe, ←set.singleton_subset_iff, ←l.le_iff_subset], exact ⟨λ h S, h.trans, λ h, h _ le_rfl⟩ } lemma eq_of_le {s : set β} {S : α} (h₁ : s ⊆ S) (h₂ : S ≤ l s) : l s = S := ((l.le_iff_subset _ _).2 h₁).antisymm h₂ lemma closure_union_closure_subset (x y : α) : (l x : set β) ∪ (l y) ⊆ l (x ∪ y) := l.closure_sup_closure_le x y @[simp] lemma closure_union_closure_left (x y : α) : (l ((l x) ∪ y) : set β) = l (x ∪ y) := l.closure_sup_closure_left x y @[simp] lemma closure_union_closure_right (x y : α) : l (x ∪ (l y)) = l (x ∪ y) := set_like.coe_injective (l.closure_sup_closure_right x y) @[simp] lemma closure_union_closure (x y : α) : l ((l x) ∪ (l y)) = l (x ∪ y) := set_like.coe_injective (l.closure_operator.closure_sup_closure x y) @[simp] lemma closure_Union_closure {ι : Type u} (x : ι → α) : l (⋃ i, l (x i)) = l (⋃ i, x i) := set_like.coe_injective (l.closure_supr_closure (coe ∘ x)) @[simp] lemma closure_bUnion_closure (p : set β → Prop) : l (⋃ x (H : p x), l x) = l (⋃ x (H : p x), x) := set_like.coe_injective (l.closure_bsupr_closure p) end coe_to_set end lower_adjoint /-! ### Translations between `galois_connection`, `lower_adjoint`, `closure_operator` -/ variable {α} /-- Every Galois connection induces a lower adjoint. -/ @[simps] def galois_connection.lower_adjoint [preorder α] [preorder β] {l : α → β} {u : β → α} (gc : galois_connection l u) : lower_adjoint u := { to_fun := l, gc' := gc } /-- Every Galois connection induces a closure operator given by the composition. This is the partial order version of the statement that every adjunction induces a monad. -/ @[simps] def galois_connection.closure_operator [partial_order α] [preorder β] {l : α → β} {u : β → α} (gc : galois_connection l u) : closure_operator α := gc.lower_adjoint.closure_operator /-- The set of closed elements has a Galois insertion to the underlying type. -/ def closure_operator.gi [partial_order α] (c : closure_operator α) : galois_insertion c.to_closed coe := { choice := λ x hx, ⟨x, hx.antisymm (c.le_closure x)⟩, gc := λ x y, (c.closure_le_closed_iff_le _ y.2), le_l_u := λ x, c.le_closure _, choice_eq := λ x hx, le_antisymm (c.le_closure x) hx } /-- The Galois insertion associated to a closure operator can be used to reconstruct the closure operator. Note that the inverse in the opposite direction does not hold in general. -/ @[simp] lemma closure_operator_gi_self [partial_order α] (c : closure_operator α) : c.gi.gc.closure_operator = c := by { ext x, refl }
4f009e894ba8139f11ac38f5129096619e072199
07c76fbd96ea1786cc6392fa834be62643cea420
/library/algebra/ordered_ring.lean
38531ffbcce2448f6281fb88b9b9cfeb12b56424
[ "Apache-2.0" ]
permissive
fpvandoorn/lean2
5a430a153b570bf70dc8526d06f18fc000a60ad9
0889cf65b7b3cebfb8831b8731d89c2453dd1e9f
refs/heads/master
1,592,036,508,364
1,545,093,958,000
1,545,093,958,000
75,436,854
0
0
null
1,480,718,780,000
1,480,718,780,000
null
UTF-8
Lean
false
false
28,487
lean
/- 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 variable {A : Type} 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_lt_mul' {a b c d : A} (H1 : a < c) (H2 : b < d) (H3 : b ≥ 0) (H4 : c > 0) : a * b < c * d := calc a * b ≤ c * b : mul_le_mul_of_nonneg_right (le_of_lt H1) H3 ... < c * d : mul_lt_mul_of_pos_left H2 H4 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 theorem mul_self_lt_mul_self {a b : A} (H1 : 0 ≤ a) (H2 : a < b) : a * a < b * b := mul_lt_mul' H2 H2 H1 (lt_of_le_of_lt H1 H2) 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 zero_le_one : 0 ≤ (1:A) := le_of_lt zero_lt_one 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_ordered_cancel_comm_monoid 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, have 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, have 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, have 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, have 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] [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, have 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, have 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, have 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, have 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] [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_or_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, or.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, or.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, or.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] [s: linear_ordered_comm_ring A] : integral_domain A := ⦃ integral_domain, s, eq_zero_or_eq_zero_of_mul_eq_zero := @linear_ordered_comm_ring.eq_zero_or_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 := or.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 pos_and_pos_or_neg_and_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, or.inl (and.intro 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, or.inr (and.intro 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, note Hposa := lt_of_le_of_lt Hb Hab, note 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 definition decidable_linear_ordered_comm_ring.to_decidable_linear_ordered_semiring [trans_instance] [s : decidable_linear_ordered_comm_ring A] : decidable_linear_ordered_semiring A := ⦃decidable_linear_ordered_semiring, s, @linear_ordered_ring.to_linear_ordered_semiring 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 := or.elim (le.total 0 a) (assume H1 : 0 ≤ a, or.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, or.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 lemma eq_zero_of_mul_self_add_mul_self_eq_zero {x y : A} (H : x * x + y * y = 0) : x = 0 := have x * x ≤ (0 : A), from calc x * x ≤ x * x + y * y : le_add_of_nonneg_right (mul_self_nonneg y) ... = 0 : H, eq_zero_of_mul_self_eq_zero (le.antisymm this (mul_self_nonneg x)) 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
f270c154688e366ecae108412cc95414965f72da
9028d228ac200bbefe3a711342514dd4e4458bff
/src/group_theory/sylow.lean
4a635adcb095b6a35bb78b26a4b91c908b80baeb
[ "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
12,388
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import group_theory.group_action import group_theory.quotient_group import group_theory.order_of_element import data.zmod.basic import data.fintype.card import data.list.rotate open equiv fintype finset mul_action function open equiv.perm subgroup list quotient_group open_locale big_operators universes u v w variables {G : Type u} {α : Type v} {β : Type w} [group G] local attribute [instance, priority 10] subtype.fintype set_fintype classical.prop_decidable namespace mul_action variables [mul_action G α] lemma mem_fixed_points_iff_card_orbit_eq_one {a : α} [fintype (orbit G a)] : a ∈ fixed_points G α ↔ card (orbit G a) = 1 := begin rw [fintype.card_eq_one_iff, mem_fixed_points], split, { exact λ h, ⟨⟨a, mem_orbit_self _⟩, λ ⟨b, ⟨x, hx⟩⟩, subtype.eq $ by simp [h x, hx.symm]⟩ }, { assume h x, rcases h with ⟨⟨z, hz⟩, hz₁⟩, exact calc x • a = z : subtype.mk.inj (hz₁ ⟨x • a, mem_orbit _ _⟩) ... = a : (subtype.mk.inj (hz₁ ⟨a, mem_orbit_self _⟩)).symm } end lemma card_modeq_card_fixed_points [fintype α] [fintype G] [fintype (fixed_points G α)] (p : ℕ) {n : ℕ} [hp : fact p.prime] (h : card G = p ^ n) : card α ≡ card (fixed_points G α) [MOD p] := calc card α = card (Σ y : quotient (orbit_rel G α), {x // quotient.mk' x = y}) : card_congr (sigma_preimage_equiv (@quotient.mk' _ (orbit_rel G α))).symm ... = ∑ a : quotient (orbit_rel G α), card {x // quotient.mk' x = a} : card_sigma _ ... ≡ ∑ a : fixed_points G α, 1 [MOD p] : begin rw [← zmod.eq_iff_modeq_nat p, sum_nat_cast, sum_nat_cast], refine eq.symm (sum_bij_ne_zero (λ a _ _, quotient.mk' a.1) (λ _ _ _, mem_univ _) (λ a₁ a₂ _ _ _ _ h, subtype.eq ((mem_fixed_points' α).1 a₂.2 a₁.1 (quotient.exact' h))) (λ b, _) (λ a ha _, by rw [← mem_fixed_points_iff_card_orbit_eq_one.1 a.2]; simp only [quotient.eq']; congr)), { refine quotient.induction_on' b (λ b _ hb, _), have : card (orbit G b) ∣ p ^ n, { rw [← h, fintype.card_congr (orbit_equiv_quotient_stabilizer G b)]; exact card_quotient_dvd_card _ }, rcases (nat.dvd_prime_pow hp).1 this with ⟨k, _, hk⟩, have hb' :¬ p ^ 1 ∣ p ^ k, { rw [pow_one, ← hk, ← nat.modeq.modeq_zero_iff, ← zmod.eq_iff_modeq_nat, nat.cast_zero, ← ne.def], exact eq.mpr (by simp only [quotient.eq']; congr) hb }, have : k = 0 := nat.le_zero_iff.1 (nat.le_of_lt_succ (lt_of_not_ge (mt (pow_dvd_pow p) hb'))), refine ⟨⟨b, mem_fixed_points_iff_card_orbit_eq_one.2 $ by rw [hk, this, pow_zero]⟩, mem_univ _, _, rfl⟩, rw [nat.cast_one], exact one_ne_zero } end ... = _ : by simp; refl end mul_action lemma quotient_group.card_preimage_mk [fintype G] (s : subgroup G) (t : set (quotient s)) : fintype.card (quotient_group.mk ⁻¹' t) = fintype.card s * fintype.card t := by rw [← fintype.card_prod, fintype.card_congr (preimage_mk_equiv_subgroup_times_set _ _)] namespace sylow /-- Given a vector `v` of length `n`, make a vector of length `n+1` whose product is `1`, by consing the the inverse of the product of `v`. -/ def mk_vector_prod_eq_one (n : ℕ) (v : vector G n) : vector G (n+1) := v.to_list.prod⁻¹ ::ᵥ v lemma mk_vector_prod_eq_one_injective (n : ℕ) : injective (@mk_vector_prod_eq_one G _ n) := λ ⟨v, _⟩ ⟨w, _⟩ h, subtype.eq (show v = w, by injection h with h; injection h) /-- The type of vectors with terms from `G`, length `n`, and product equal to `1:G`. -/ def vectors_prod_eq_one (G : Type*) [group G] (n : ℕ) : set (vector G n) := {v | v.to_list.prod = 1} lemma mem_vectors_prod_eq_one {n : ℕ} (v : vector G n) : v ∈ vectors_prod_eq_one G n ↔ v.to_list.prod = 1 := iff.rfl lemma mem_vectors_prod_eq_one_iff {n : ℕ} (v : vector G (n + 1)) : v ∈ vectors_prod_eq_one G (n + 1) ↔ v ∈ set.range (@mk_vector_prod_eq_one G _ n) := ⟨λ (h : v.to_list.prod = 1), ⟨v.tail, begin unfold mk_vector_prod_eq_one, conv {to_rhs, rw ← vector.cons_head_tail v}, suffices : (v.tail.to_list.prod)⁻¹ = v.head, { rw this }, rw [← mul_left_inj v.tail.to_list.prod, inv_mul_self, ← list.prod_cons, ← vector.to_list_cons, vector.cons_head_tail, h] end⟩, λ ⟨w, hw⟩, by rw [mem_vectors_prod_eq_one, ← hw, mk_vector_prod_eq_one, vector.to_list_cons, list.prod_cons, inv_mul_self]⟩ /-- The rotation action of `zmod n` (viewed as multiplicative group) on `vectors_prod_eq_one G n`, where `G` is a multiplicative group. -/ def rotate_vectors_prod_eq_one (G : Type*) [group G] (n : ℕ) (m : multiplicative (zmod n)) (v : vectors_prod_eq_one G n) : vectors_prod_eq_one G n := ⟨⟨v.1.to_list.rotate m.val, by simp⟩, prod_rotate_eq_one_of_prod_eq_one v.2 _⟩ instance rotate_vectors_prod_eq_one.mul_action (n : ℕ) [fact (0 < n)] : mul_action (multiplicative (zmod n)) (vectors_prod_eq_one G n) := { smul := (rotate_vectors_prod_eq_one G n), one_smul := begin intro v, apply subtype.eq, apply vector.eq _ _, show rotate _ (0 : zmod n).val = _, rw zmod.val_zero, exact rotate_zero v.1.to_list end, mul_smul := λ a b ⟨⟨v, hv₁⟩, hv₂⟩, subtype.eq $ vector.eq _ _ $ show v.rotate ((a + b : zmod n).val) = list.rotate (list.rotate v (b.val)) (a.val), by rw [zmod.val_add, rotate_rotate, ← rotate_mod _ (b.val + a.val), add_comm, hv₁] } lemma one_mem_vectors_prod_eq_one (n : ℕ) : vector.repeat (1 : G) n ∈ vectors_prod_eq_one G n := by simp [vector.repeat, vectors_prod_eq_one] lemma one_mem_fixed_points_rotate (n : ℕ) [fact (0 < n)] : (⟨vector.repeat (1 : G) n, one_mem_vectors_prod_eq_one n⟩ : vectors_prod_eq_one G n) ∈ fixed_points (multiplicative (zmod n)) (vectors_prod_eq_one G n) := λ m, subtype.eq $ vector.eq _ _ $ rotate_eq_self_iff_eq_repeat.2 ⟨(1 : G), show list.repeat (1 : G) n = list.repeat 1 (list.repeat (1 : G) n).length, by simp⟩ _ /-- Cauchy's theorem -/ lemma exists_prime_order_of_dvd_card [fintype G] (p : ℕ) [hp : fact p.prime] (hdvd : p ∣ card G) : ∃ x : G, order_of x = p := let n : ℕ+ := ⟨p - 1, nat.sub_pos_of_lt hp.one_lt⟩ in have hn : p = n + 1 := nat.succ_sub hp.pos, have hcard : card (vectors_prod_eq_one G (n + 1)) = card G ^ (n : ℕ), by rw [set.ext mem_vectors_prod_eq_one_iff, set.card_range_of_injective (mk_vector_prod_eq_one_injective _), card_vector], have hzmod : fintype.card (multiplicative (zmod p)) = p ^ 1, by { rw pow_one p, exact zmod.card p }, have hmodeq : _ = _ := @mul_action.card_modeq_card_fixed_points (multiplicative (zmod p)) (vectors_prod_eq_one G p) _ _ _ _ _ _ 1 hp hzmod, have hdvdcard : p ∣ fintype.card (vectors_prod_eq_one G (n + 1)) := calc p ∣ card G ^ 1 : by rwa pow_one ... ∣ card G ^ (n : ℕ) : pow_dvd_pow _ n.2 ... = card (vectors_prod_eq_one G (n + 1)) : hcard.symm, have hdvdcard₂ : p ∣ card (fixed_points (multiplicative (zmod p)) (vectors_prod_eq_one G p)), by { rw nat.dvd_iff_mod_eq_zero at hdvdcard ⊢, rwa [← hn, hmodeq] at hdvdcard }, have hcard_pos : 0 < card (fixed_points (multiplicative (zmod p)) (vectors_prod_eq_one G p)) := fintype.card_pos_iff.2 ⟨⟨⟨vector.repeat 1 p, one_mem_vectors_prod_eq_one _⟩, one_mem_fixed_points_rotate _⟩⟩, have hlt : 1 < card (fixed_points (multiplicative (zmod p)) (vectors_prod_eq_one G p)) := calc (1 : ℕ) < p : hp.one_lt ... ≤ _ : nat.le_of_dvd hcard_pos hdvdcard₂, let ⟨⟨⟨⟨x, hx₁⟩, hx₂⟩, hx₃⟩, hx₄⟩ := fintype.exists_ne_of_one_lt_card hlt ⟨_, one_mem_fixed_points_rotate p⟩ in have hx : x ≠ list.repeat (1 : G) p, from λ h, by simpa [h, vector.repeat] using hx₄, have ∃ a, x = list.repeat a x.length := by exactI rotate_eq_self_iff_eq_repeat.1 (λ n, have list.rotate x (n : zmod p).val = x := subtype.mk.inj (subtype.mk.inj (hx₃ (n : zmod p))), by rwa [zmod.val_cast_nat, ← hx₁, rotate_mod] at this), let ⟨a, ha⟩ := this in ⟨a, have hx1 : x.prod = 1 := hx₂, have ha1: a ≠ 1, from λ h, hx (ha.symm ▸ h ▸ hx₁ ▸ rfl), have a ^ p = 1, by rwa [ha, list.prod_repeat, hx₁] at hx1, (hp.2 _ (order_of_dvd_of_pow_eq_one this)).resolve_left (λ h, ha1 (order_of_eq_one_iff.1 h))⟩ open subgroup submonoid is_group_hom mul_action lemma mem_fixed_points_mul_left_cosets_iff_mem_normalizer {H : subgroup G} [fintype ((H : set G) : Type u)] {x : G} : (x : quotient H) ∈ fixed_points H (quotient H) ↔ x ∈ normalizer H := ⟨λ hx, have ha : ∀ {y : quotient H}, y ∈ orbit H (x : quotient H) → y = x, from λ _, ((mem_fixed_points' _).1 hx _), (inv_mem_iff _).1 (@mem_normalizer_fintype _ _ _ _inst_2 _ (λ n (hn : n ∈ H), have (n⁻¹ * x)⁻¹ * x ∈ H := quotient_group.eq.1 (ha (mem_orbit _ ⟨n⁻¹, H.inv_mem hn⟩)), show _ ∈ H, by {rw [mul_inv_rev, inv_inv] at this, convert this, rw inv_inv} )), λ (hx : ∀ (n : G), n ∈ H ↔ x * n * x⁻¹ ∈ H), (mem_fixed_points' _).2 $ λ y, quotient.induction_on' y $ λ y hy, quotient_group.eq.2 (let ⟨⟨b, hb₁⟩, hb₂⟩ := hy in have hb₂ : (b * x)⁻¹ * y ∈ H := quotient_group.eq.1 hb₂, (inv_mem_iff H).1 $ (hx _).2 $ (mul_mem_cancel_left H (H.inv_mem hb₁)).1 $ by rw hx at hb₂; simpa [mul_inv_rev, mul_assoc] using hb₂)⟩ def fixed_points_mul_left_cosets_equiv_quotient (H : subgroup G) [fintype (H : set G)] : fixed_points H (quotient H) ≃ quotient (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H) := @subtype_quotient_equiv_quotient_subtype G (normalizer H : set G) (id _) (id _) (fixed_points _ _) (λ a, (@mem_fixed_points_mul_left_cosets_iff_mem_normalizer _ _ _ _inst_2 _).symm) (by intros; refl) lemma exists_subgroup_card_pow_prime [fintype G] (p : ℕ) : ∀ {n : ℕ} [hp : fact p.prime] (hdvd : p ^ n ∣ card G), ∃ H : subgroup G, fintype.card H = p ^ n | 0 := λ _ _, ⟨(⊥ : subgroup G), by convert card_trivial⟩ | (n+1) := λ hp hdvd, let ⟨H, hH2⟩ := @exists_subgroup_card_pow_prime _ hp (dvd.trans (pow_dvd_pow _ (nat.le_succ _)) hdvd) in let ⟨s, hs⟩ := exists_eq_mul_left_of_dvd hdvd in have hcard : card (quotient H) = s * p := (nat.mul_left_inj (show card H > 0, from fintype.card_pos_iff.2 ⟨⟨1, H.one_mem⟩⟩)).1 (by rwa [← card_eq_card_quotient_mul_card_subgroup, hH2, hs, pow_succ', mul_assoc, mul_comm p]), have hm : s * p % p = card (quotient (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H)) % p := card_congr (fixed_points_mul_left_cosets_equiv_quotient H) ▸ hcard ▸ @card_modeq_card_fixed_points _ _ _ _ _ _ _ p _ hp hH2, have hm' : p ∣ card (quotient (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H)) := nat.dvd_of_mod_eq_zero (by rwa [nat.mod_eq_zero_of_dvd (dvd_mul_left _ _), eq_comm] at hm), let ⟨x, hx⟩ := @exists_prime_order_of_dvd_card _ (quotient_group.group _) _ _ hp hm' in have hxcard : ∀ {f : fintype (subgroup.gpowers x)}, card (subgroup.gpowers x) = p, from λ f, by rw [← hx, order_eq_card_gpowers]; congr, have fintype (subgroup.comap (quotient_group.mk' (comap H.normalizer.subtype H)) (gpowers x)), by apply_instance, have hequiv : H ≃ (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H) := ⟨λ a, ⟨⟨a.1, le_normalizer a.2⟩, a.2⟩, λ a, ⟨a.1.1, a.2⟩, λ ⟨_, _⟩, rfl, λ ⟨⟨_, _⟩, _⟩, rfl⟩, -- begin proof of ∃ H : subgroup G, fintype.card H = p ^ n ⟨subgroup.map ((normalizer H).subtype) (subgroup.comap (quotient_group.mk' _) (gpowers x)), begin show card ↥(map H.normalizer.subtype (comap (mk' (comap H.normalizer.subtype H)) (subgroup.gpowers x))) = p ^ (n + 1), suffices : card ↥(subtype.val '' ((subgroup.comap (mk' (comap H.normalizer.subtype H)) (gpowers x)) : set (↥(H.normalizer)))) = p^(n+1), { convert this }, rw [set.card_image_of_injective (subgroup.comap (mk' _) (gpowers x) : set (H.normalizer)) subtype.val_injective, pow_succ', ← hH2, fintype.card_congr hequiv, ← hx, order_eq_card_gpowers, ← fintype.card_prod], exact @fintype.card_congr _ _ (id _) (id _) (preimage_mk_equiv_subgroup_times_set _ _) end⟩ end sylow
3c1256f57de79e23bd82ae25c5aecbf703c15f44
3446e92e64a5de7ed1f2109cfb024f83cd904c34
/src/game/world3/level1.lean
2fee7393da27201a75a8a8f7fd56dba7599882f3
[]
no_license
kckennylau/natural_number_game
019f4a5f419c9681e65234ecd124c564f9a0a246
ad8c0adaa725975be8a9f978c8494a39311029be
refs/heads/master
1,598,784,137,722
1,571,905,156,000
1,571,905,156,000
218,354,686
0
0
null
1,572,373,319,000
1,572,373,318,000
null
UTF-8
Lean
false
false
1,421
lean
import game.world2.level6 -- hide import mynat.mul /- # World 3 A new import! This import gives you the definition of multiplication on your natural numbers. It is defined by recursion, just like addition. Here are the two new axioms: * `mul_zero : ∀ a : mynat, a * 0 = 0` * `mul_succ : ∀ a b : mynat, a * succ(b) = a * b + b` In words, we define multiplication by "induction on the second variable", with `a * 0` defined to be `0` and, if we know `a * b`, then `a` times the number after `b` is defined to be `a * b + b`. You can keep all the theorems you proved about addition, but for multiplication, those two results above are you've got right now. Like addition, we need to go for the proofs that multiplication is commutative and associative, but as well as that we will need to prove facts about the relationship between multiplication and addition, for example `a * (b + c) = a * b + a * c`, so now there is a lot more to do. Good luck! We are given `mul_zero`, and the first thing to prove is `zero_mul`. Like `zero_add`, we of course prove it by induction. ## World 3 Level 1 : `zero_mul` -/ namespace mynat -- hide /- Lemma For all natural numbers $m$, we have $$ 0 * m = 0. $$ -/ lemma zero_mul (m : mynat) : 0 * m = 0 := begin [less_leaky] induction m with d hd, { rw mul_zero, refl }, { rw mul_succ, rw hd, rw add_zero, refl } end end mynat -- hide
2ea492873b48895be3d92f98c962abd2fc8ddf5a
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/set_theory/game/state.lean
e584092187067dd72caad5d09470f62e3f4a2cdc
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,404
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 set_theory.game.short /-! # Games described via "the state of the board". We provide a simple mechanism for constructing combinatorial (pre-)games, by describing "the state of the board", and providing an upper bound on the number of turns remaining. ## Implementation notes We're very careful to produce a computable definition, so small games can be evaluated using `dec_trivial`. To achieve this, I've had to rely solely on induction on natural numbers: relying on general well-foundedness seems to be poisonous to computation? See `set_theory/game/domineering` for an example using this construction. -/ universe u namespace pgame /-- `pgame_state S` describes how to interpret `s : S` as a state of a combinatorial game. Use `pgame.of s` or `game.of s` to construct the game. `pgame_state.L : S → finset S` and `pgame_state.R : S → finset S` describe the states reachable by a move by Left or Right. `pgame_state.turn_bound : S → ℕ` gives an upper bound on the number of possible turns remaining from this state. -/ class state (S : Type u) := (turn_bound : S → ℕ) (L : S → finset S) (R : S → finset S) (left_bound : ∀ {s t : S} (m : t ∈ L s), turn_bound t < turn_bound s) (right_bound : ∀ {s t : S} (m : t ∈ R s), turn_bound t < turn_bound s) open state variables {S : Type u} [state S] lemma turn_bound_ne_zero_of_left_move {s t : S} (m : t ∈ L s) : turn_bound s ≠ 0 := begin intro h, have t := state.left_bound m, rw h at t, exact nat.not_succ_le_zero _ t, end lemma turn_bound_ne_zero_of_right_move {s t : S} (m : t ∈ R s) : turn_bound s ≠ 0 := begin intro h, have t := state.right_bound m, rw h at t, exact nat.not_succ_le_zero _ t, end lemma turn_bound_of_left {s t : S} (m : t ∈ L s) (n : ℕ) (h : turn_bound s ≤ n + 1) : turn_bound t ≤ n := nat.le_of_lt_succ (nat.lt_of_lt_of_le (left_bound m) h) lemma turn_bound_of_right {s t : S} (m : t ∈ R s) (n : ℕ) (h : turn_bound s ≤ n + 1) : turn_bound t ≤ n := nat.le_of_lt_succ (nat.lt_of_lt_of_le (right_bound m) h) /-- Construct a `pgame` from a state and a (not necessarily optimal) bound on the number of turns remaining. -/ def of_aux : Π (n : ℕ) (s : S) (h : turn_bound s ≤ n), pgame | 0 s h := pgame.mk {t // t ∈ L s} {t // t ∈ R s} (λ t, begin exfalso, exact turn_bound_ne_zero_of_left_move t.2 (nonpos_iff_eq_zero.mp h) end) (λ t, begin exfalso, exact turn_bound_ne_zero_of_right_move t.2 (nonpos_iff_eq_zero.mp h) end) | (n+1) s h := pgame.mk {t // t ∈ L s} {t // t ∈ R s} (λ t, of_aux n t (turn_bound_of_left t.2 n h)) (λ t, of_aux n t (turn_bound_of_right t.2 n h)) /-- Two different (valid) turn bounds give equivalent games. -/ def of_aux_relabelling : Π (s : S) (n m : ℕ) (hn : turn_bound s ≤ n) (hm : turn_bound s ≤ m), relabelling (of_aux n s hn) (of_aux m s hm) | s 0 0 hn hm := begin dsimp [pgame.of_aux], fsplit, refl, refl, { intro i, dsimp at i, exfalso, exact turn_bound_ne_zero_of_left_move i.2 (nonpos_iff_eq_zero.mp hn) }, { intro j, dsimp at j, exfalso, exact turn_bound_ne_zero_of_right_move j.2 (nonpos_iff_eq_zero.mp hm) } end | s 0 (m+1) hn hm := begin dsimp [pgame.of_aux], fsplit, refl, refl, { intro i, dsimp at i, exfalso, exact turn_bound_ne_zero_of_left_move i.2 (nonpos_iff_eq_zero.mp hn) }, { intro j, dsimp at j, exfalso, exact turn_bound_ne_zero_of_right_move j.2 (nonpos_iff_eq_zero.mp hn) } end | s (n+1) 0 hn hm := begin dsimp [pgame.of_aux], fsplit, refl, refl, { intro i, dsimp at i, exfalso, exact turn_bound_ne_zero_of_left_move i.2 (nonpos_iff_eq_zero.mp hm) }, { intro j, dsimp at j, exfalso, exact turn_bound_ne_zero_of_right_move j.2 (nonpos_iff_eq_zero.mp hm) } end | s (n+1) (m+1) hn hm := begin dsimp [pgame.of_aux], fsplit, refl, refl, { intro i, apply of_aux_relabelling, }, { intro j, apply of_aux_relabelling, } end /-- Construct a combinatorial `pgame` from a state. -/ def of (s : S) : pgame := of_aux (turn_bound s) s (refl _) /-- The equivalence between `left_moves` for a `pgame` constructed using `of_aux _ s _`, and `L s`. -/ def left_moves_of_aux (n : ℕ) {s : S} (h : turn_bound s ≤ n) : left_moves (of_aux n s h) ≃ {t // t ∈ L s} := by induction n; refl /-- The equivalence between `left_moves` for a `pgame` constructed using `of s`, and `L s`. -/ def left_moves_of (s : S) : left_moves (of s) ≃ {t // t ∈ L s} := left_moves_of_aux _ _ /-- The equivalence between `right_moves` for a `pgame` constructed using `of_aux _ s _`, and `R s`. -/ def right_moves_of_aux (n : ℕ) {s : S} (h : turn_bound s ≤ n) : right_moves (of_aux n s h) ≃ {t // t ∈ R s} := by induction n; refl /-- The equivalence between `right_moves` for a `pgame` constructed using `of s`, and `R s`. -/ def right_moves_of (s : S) : right_moves (of s) ≃ {t // t ∈ R s} := right_moves_of_aux _ _ /-- The relabelling showing `move_left` applied to a game constructed using `of_aux` has itself been constructed using `of_aux`. -/ def relabelling_move_left_aux (n : ℕ) {s : S} (h : turn_bound s ≤ n) (t : left_moves (of_aux n s h)) : relabelling (move_left (of_aux n s h) t) (of_aux (n-1) (((left_moves_of_aux n h) t) : S) ((turn_bound_of_left ((left_moves_of_aux n h) t).2 (n-1) (nat.le_trans h le_sub_add)))) := begin induction n, { have t' := (left_moves_of_aux 0 h) t, exfalso, exact turn_bound_ne_zero_of_left_move t'.2 (nonpos_iff_eq_zero.mp h), }, { refl }, end /-- The relabelling showing `move_left` applied to a game constructed using `of` has itself been constructed using `of`. -/ def relabelling_move_left (s : S) (t : left_moves (of s)) : relabelling (move_left (of s) t) (of (((left_moves_of s).to_fun t) : S)) := begin transitivity, apply relabelling_move_left_aux, apply of_aux_relabelling, end /-- The relabelling showing `move_right` applied to a game constructed using `of_aux` has itself been constructed using `of_aux`. -/ def relabelling_move_right_aux (n : ℕ) {s : S} (h : turn_bound s ≤ n) (t : right_moves (of_aux n s h)) : relabelling (move_right (of_aux n s h) t) (of_aux (n-1) (((right_moves_of_aux n h) t) : S) ((turn_bound_of_right ((right_moves_of_aux n h) t).2 (n-1) (nat.le_trans h le_sub_add)))) := begin induction n, { have t' := (right_moves_of_aux 0 h) t, exfalso, exact turn_bound_ne_zero_of_right_move t'.2 (nonpos_iff_eq_zero.mp h), }, { refl }, end /-- The relabelling showing `move_right` applied to a game constructed using `of` has itself been constructed using `of`. -/ def relabelling_move_right (s : S) (t : right_moves (of s)) : relabelling (move_right (of s) t) (of (((right_moves_of s).to_fun t) : S)) := begin transitivity, apply relabelling_move_right_aux, apply of_aux_relabelling, end instance fintype_left_moves_of_aux (n : ℕ) (s : S) (h : turn_bound s ≤ n) : fintype (left_moves (of_aux n s h)) := begin apply fintype.of_equiv _ (left_moves_of_aux _ _).symm, apply_instance, end instance fintype_right_moves_of_aux (n : ℕ) (s : S) (h : turn_bound s ≤ n) : fintype (right_moves (of_aux n s h)) := begin apply fintype.of_equiv _ (right_moves_of_aux _ _).symm, apply_instance, end instance short_of_aux : Π (n : ℕ) {s : S} (h : turn_bound s ≤ n), short (of_aux n s h) | 0 s h := short.mk' (λ i, begin have i := (left_moves_of_aux _ _).to_fun i, exfalso, exact turn_bound_ne_zero_of_left_move i.2 (nonpos_iff_eq_zero.mp h), end) (λ j, begin have j := (right_moves_of_aux _ _).to_fun j, exfalso, exact turn_bound_ne_zero_of_right_move j.2 (nonpos_iff_eq_zero.mp h), end) | (n+1) s h := short.mk' (λ i, short_of_relabelling (relabelling_move_left_aux (n+1) h i).symm (short_of_aux n _)) (λ j, short_of_relabelling (relabelling_move_right_aux (n+1) h j).symm (short_of_aux n _)) instance short_of (s : S) : short (of s) := begin dsimp [pgame.of], apply_instance end end pgame namespace game /-- Construct a combinatorial `game` from a state. -/ def of {S : Type u} [pgame.state S] (s : S) : game := ⟦pgame.of s⟧ end game
d0e0d96dc70604b4f3887c080e741be81d96fc49
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/group_theory/perm/basic.lean
e3ee863f0aba069e5e6203041dced4e760ab48bb
[ "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
15,631
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro -/ import algebra.group.pi import algebra.group_power.lemmas import algebra.group.prod import logic.function.iterate /-! # The group of permutations (self-equivalences) of a type `α` This file defines the `group` structure on `equiv.perm α`. -/ universes u v namespace equiv variables {α : Type u} {β : Type v} namespace perm instance perm_group : group (perm α) := { mul := λ f g, equiv.trans g f, one := equiv.refl α, inv := equiv.symm, mul_assoc := λ f g h, (trans_assoc _ _ _).symm, one_mul := trans_refl, mul_one := refl_trans, mul_left_inv := self_trans_symm } /-- The permutation of a type is equivalent to the units group of the endomorphisms monoid of this type. -/ @[simps] def equiv_units_End : perm α ≃* units (function.End α) := { to_fun := λ e, ⟨e, e.symm, e.self_comp_symm, e.symm_comp_self⟩, inv_fun := λ u, ⟨(u : function.End α), (↑u⁻¹ : function.End α), congr_fun u.inv_val, congr_fun u.val_inv⟩, left_inv := λ e, ext $ λ x, rfl, right_inv := λ u, units.ext rfl, map_mul' := λ e₁ e₂, rfl } /-- Lift a monoid homomorphism `f : G →* function.End α` to a monoid homomorphism `f : G →* equiv.perm α`. -/ @[simps] def _root_.monoid_hom.to_hom_perm {G : Type*} [group G] (f : G →* function.End α) : G →* perm α := equiv_units_End.symm.to_monoid_hom.comp f.to_hom_units theorem mul_apply (f g : perm α) (x) : (f * g) x = f (g x) := equiv.trans_apply _ _ _ theorem one_apply (x) : (1 : perm α) x = x := rfl @[simp] lemma inv_apply_self (f : perm α) (x) : f⁻¹ (f x) = x := f.symm_apply_apply x @[simp] lemma apply_inv_self (f : perm α) (x) : f (f⁻¹ x) = x := f.apply_symm_apply x lemma one_def : (1 : perm α) = equiv.refl α := rfl lemma mul_def (f g : perm α) : f * g = g.trans f := rfl lemma inv_def (f : perm α) : f⁻¹ = f.symm := rfl @[simp] lemma coe_mul (f g : perm α) : ⇑(f * g) = f ∘ g := rfl @[simp] lemma coe_one : ⇑(1 : perm α) = id := rfl lemma eq_inv_iff_eq {f : perm α} {x y : α} : x = f⁻¹ y ↔ f x = y := f.eq_symm_apply lemma inv_eq_iff_eq {f : perm α} {x y : α} : f⁻¹ x = y ↔ x = f y := f.symm_apply_eq lemma zpow_apply_comm {α : Type*} (σ : perm α) (m n : ℤ) {x : α} : (σ ^ m) ((σ ^ n) x) = (σ ^ n) ((σ ^ m) x) := by rw [←equiv.perm.mul_apply, ←equiv.perm.mul_apply, zpow_mul_comm] @[simp] lemma iterate_eq_pow (f : perm α) : ∀ n, f^[n] = ⇑(f ^ n) | 0 := rfl | (n + 1) := by { rw [function.iterate_succ, pow_add, iterate_eq_pow], refl } /-! Lemmas about mixing `perm` with `equiv`. Because we have multiple ways to express `equiv.refl`, `equiv.symm`, and `equiv.trans`, we want simp lemmas for every combination. The assumption made here is that if you're using the group structure, you want to preserve it after simp. -/ @[simp] lemma trans_one {α : Sort*} {β : Type*} (e : α ≃ β) : e.trans (1 : perm β) = e := equiv.trans_refl e @[simp] lemma mul_refl (e : perm α) : e * equiv.refl α = e := equiv.trans_refl e @[simp] lemma one_symm : (1 : perm α).symm = 1 := equiv.refl_symm @[simp] lemma refl_inv : (equiv.refl α : perm α)⁻¹ = 1 := equiv.refl_symm @[simp] lemma one_trans {α : Type*} {β : Sort*} (e : α ≃ β) : (1 : perm α).trans e = e := equiv.refl_trans e @[simp] lemma refl_mul (e : perm α) : equiv.refl α * e = e := equiv.refl_trans e @[simp] lemma inv_trans_self (e : perm α) : e⁻¹.trans e = 1 := equiv.symm_trans_self e @[simp] lemma mul_symm (e : perm α) : e * e.symm = 1 := equiv.symm_trans_self e @[simp] lemma self_trans_inv (e : perm α) : e.trans e⁻¹ = 1 := equiv.self_trans_symm e @[simp] lemma symm_mul (e : perm α) : e.symm * e = 1 := equiv.self_trans_symm e /-! Lemmas about `equiv.perm.sum_congr` re-expressed via the group structure. -/ @[simp] lemma sum_congr_mul {α β : Type*} (e : perm α) (f : perm β) (g : perm α) (h : perm β) : sum_congr e f * sum_congr g h = sum_congr (e * g) (f * h) := sum_congr_trans g h e f @[simp] lemma sum_congr_inv {α β : Type*} (e : perm α) (f : perm β) : (sum_congr e f)⁻¹ = sum_congr e⁻¹ f⁻¹ := sum_congr_symm e f @[simp] lemma sum_congr_one {α β : Type*} : sum_congr (1 : perm α) (1 : perm β) = 1 := sum_congr_refl /-- `equiv.perm.sum_congr` as a `monoid_hom`, with its two arguments bundled into a single `prod`. This is particularly useful for its `monoid_hom.range` projection, which is the subgroup of permutations which do not exchange elements between `α` and `β`. -/ @[simps] def sum_congr_hom (α β : Type*) : perm α × perm β →* perm (α ⊕ β) := { to_fun := λ a, sum_congr a.1 a.2, map_one' := sum_congr_one, map_mul' := λ a b, (sum_congr_mul _ _ _ _).symm} lemma sum_congr_hom_injective {α β : Type*} : function.injective (sum_congr_hom α β) := begin rintros ⟨⟩ ⟨⟩ h, rw prod.mk.inj_iff, split; ext i, { simpa using equiv.congr_fun h (sum.inl i), }, { simpa using equiv.congr_fun h (sum.inr i), }, end @[simp] lemma sum_congr_swap_one {α β : Type*} [decidable_eq α] [decidable_eq β] (i j : α) : sum_congr (equiv.swap i j) (1 : perm β) = equiv.swap (sum.inl i) (sum.inl j) := sum_congr_swap_refl i j @[simp] lemma sum_congr_one_swap {α β : Type*} [decidable_eq α] [decidable_eq β] (i j : β) : sum_congr (1 : perm α) (equiv.swap i j) = equiv.swap (sum.inr i) (sum.inr j) := sum_congr_refl_swap i j /-! Lemmas about `equiv.perm.sigma_congr_right` re-expressed via the group structure. -/ @[simp] lemma sigma_congr_right_mul {α : Type*} {β : α → Type*} (F : Π a, perm (β a)) (G : Π a, perm (β a)) : sigma_congr_right F * sigma_congr_right G = sigma_congr_right (F * G) := sigma_congr_right_trans G F @[simp] lemma sigma_congr_right_inv {α : Type*} {β : α → Type*} (F : Π a, perm (β a)) : (sigma_congr_right F)⁻¹ = sigma_congr_right (λ a, (F a)⁻¹) := sigma_congr_right_symm F @[simp] lemma sigma_congr_right_one {α : Type*} {β : α → Type*} : (sigma_congr_right (1 : Π a, equiv.perm $ β a)) = 1 := sigma_congr_right_refl /-- `equiv.perm.sigma_congr_right` as a `monoid_hom`. This is particularly useful for its `monoid_hom.range` projection, which is the subgroup of permutations which do not exchange elements between fibers. -/ @[simps] def sigma_congr_right_hom {α : Type*} (β : α → Type*) : (Π a, perm (β a)) →* perm (Σ a, β a) := { to_fun := sigma_congr_right, map_one' := sigma_congr_right_one, map_mul' := λ a b, (sigma_congr_right_mul _ _).symm } lemma sigma_congr_right_hom_injective {α : Type*} {β : α → Type*} : function.injective (sigma_congr_right_hom β) := begin intros x y h, ext a b, simpa using equiv.congr_fun h ⟨a, b⟩, end /-- `equiv.perm.subtype_congr` as a `monoid_hom`. -/ @[simps] def subtype_congr_hom (p : α → Prop) [decidable_pred p] : (perm {a // p a}) × (perm {a // ¬ p a}) →* perm α := { to_fun := λ pair, perm.subtype_congr pair.fst pair.snd, map_one' := perm.subtype_congr.refl, map_mul' := λ _ _, (perm.subtype_congr.trans _ _ _ _).symm } lemma subtype_congr_hom_injective (p : α → Prop) [decidable_pred p] : function.injective (subtype_congr_hom p) := begin rintros ⟨⟩ ⟨⟩ h, rw prod.mk.inj_iff, split; ext i; simpa using equiv.congr_fun h i end /-- If `e` is also a permutation, we can write `perm_congr` completely in terms of the group structure. -/ @[simp] lemma perm_congr_eq_mul (e p : perm α) : e.perm_congr p = e * p * e⁻¹ := rfl section extend_domain /-! Lemmas about `equiv.perm.extend_domain` re-expressed via the group structure. -/ variables (e : perm α) {p : β → Prop} [decidable_pred p] (f : α ≃ subtype p) @[simp] lemma extend_domain_one : extend_domain 1 f = 1 := extend_domain_refl f @[simp] lemma extend_domain_inv : (e.extend_domain f)⁻¹ = e⁻¹.extend_domain f := rfl @[simp] lemma extend_domain_mul (e e' : perm α) : (e.extend_domain f) * (e'.extend_domain f) = (e * e').extend_domain f := extend_domain_trans _ _ _ /-- `extend_domain` as a group homomorphism -/ @[simps] def extend_domain_hom : perm α →* perm β := { to_fun := λ e, extend_domain e f, map_one' := extend_domain_one f, map_mul' := λ e e', (extend_domain_mul f e e').symm } lemma extend_domain_hom_injective : function.injective (extend_domain_hom f) := (injective_iff_map_eq_one (extend_domain_hom f)).mpr (λ e he, ext (λ x, f.injective (subtype.ext ((extend_domain_apply_image e f x).symm.trans (ext_iff.mp he (f x)))))) @[simp] lemma extend_domain_eq_one_iff {e : perm α} {f : α ≃ subtype p} : e.extend_domain f = 1 ↔ e = 1 := (injective_iff_map_eq_one' (extend_domain_hom f)).mp (extend_domain_hom_injective f) e end extend_domain /-- If the permutation `f` fixes the subtype `{x // p x}`, then this returns the permutation on `{x // p x}` induced by `f`. -/ def subtype_perm (f : perm α) {p : α → Prop} (h : ∀ x, p x ↔ p (f x)) : perm {x // p x} := ⟨λ x, ⟨f x, (h _).1 x.2⟩, λ x, ⟨f⁻¹ x, (h (f⁻¹ x)).2 $ by simpa using x.2⟩, λ _, by simp only [perm.inv_apply_self, subtype.coe_eta, subtype.coe_mk], λ _, by simp only [perm.apply_inv_self, subtype.coe_eta, subtype.coe_mk]⟩ @[simp] lemma subtype_perm_apply (f : perm α) {p : α → Prop} (h : ∀ x, p x ↔ p (f x)) (x : {x // p x}) : subtype_perm f h x = ⟨f x, (h _).1 x.2⟩ := rfl @[simp] lemma subtype_perm_one (p : α → Prop) (h : ∀ x, p x ↔ p ((1 : perm α) x)) : @subtype_perm α 1 p h = 1 := equiv.ext $ λ ⟨_, _⟩, rfl /-- The inclusion map of permutations on a subtype of `α` into permutations of `α`, fixing the other points. -/ def of_subtype {p : α → Prop} [decidable_pred p] : perm (subtype p) →* perm α := { to_fun := λ f, extend_domain f (equiv.refl (subtype p)), map_one' := equiv.perm.extend_domain_one _, map_mul' := λ f g, (equiv.perm.extend_domain_mul _ f g).symm, } lemma of_subtype_subtype_perm {f : perm α} {p : α → Prop} [decidable_pred p] (h₁ : ∀ x, p x ↔ p (f x)) (h₂ : ∀ x, f x ≠ x → p x) : of_subtype (subtype_perm f h₁) = f := equiv.ext $ λ x, begin by_cases hx : p x, { exact (subtype_perm f h₁).extend_domain_apply_subtype _ hx, }, { rw [of_subtype, monoid_hom.coe_mk, equiv.perm.extend_domain_apply_not_subtype], { exact not_not.mp (λ h, hx (h₂ x (ne.symm h))), }, { exact hx, }, } end lemma of_subtype_apply_of_mem {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) {x : α} (hx : p x) : of_subtype f x = f ⟨x, hx⟩ := extend_domain_apply_subtype f _ hx @[simp] lemma of_subtype_apply_coe {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) (x : subtype p) : of_subtype f x = f x := subtype.cases_on x $ λ _, of_subtype_apply_of_mem f lemma of_subtype_apply_of_not_mem {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) {x : α} (hx : ¬ p x) : of_subtype f x = x := extend_domain_apply_not_subtype f (equiv.refl (subtype p)) hx lemma mem_iff_of_subtype_apply_mem {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) (x : α) : p x ↔ p ((of_subtype f : α → α) x) := if h : p x then by simpa only [h, true_iff, monoid_hom.coe_mk, of_subtype_apply_of_mem f h] using (f ⟨x, h⟩).2 else by simp [h, of_subtype_apply_of_not_mem f h] @[simp] lemma subtype_perm_of_subtype {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) : subtype_perm (of_subtype f) (mem_iff_of_subtype_apply_mem f) = f := equiv.ext $ λ ⟨x, hx⟩, subtype.coe_injective (of_subtype_apply_of_mem f hx) @[simp] lemma default_perm {n : Type*} : (default : perm n) = 1 := rfl /-- Permutations on a subtype are equivalent to permutations on the original type that fix pointwise the rest. -/ @[simps] protected def subtype_equiv_subtype_perm (p : α → Prop) [decidable_pred p] : perm (subtype p) ≃ {f : perm α // ∀ a, ¬p a → f a = a} := { to_fun := λ f, ⟨f.of_subtype, λ a, f.of_subtype_apply_of_not_mem⟩, inv_fun := λ f, (f : perm α).subtype_perm (λ a, ⟨decidable.not_imp_not.1 $ λ hfa, (f.val.injective (f.prop _ hfa) ▸ hfa), decidable.not_imp_not.1 $ λ ha hfa, ha $ f.prop a ha ▸ hfa⟩), left_inv := equiv.perm.subtype_perm_of_subtype, right_inv := λ f, subtype.ext (equiv.perm.of_subtype_subtype_perm _ $ λ a, not.decidable_imp_symm $ f.prop a) } lemma subtype_equiv_subtype_perm_apply_of_mem {α : Type*} {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) {a : α} (h : p a) : perm.subtype_equiv_subtype_perm p f a = f ⟨a, h⟩ := f.of_subtype_apply_of_mem h lemma subtype_equiv_subtype_perm_apply_of_not_mem {α : Type*} {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) {a : α} (h : ¬ p a) : perm.subtype_equiv_subtype_perm p f a = a := f.of_subtype_apply_of_not_mem h end perm section swap variables [decidable_eq α] @[simp] lemma swap_inv (x y : α) : (swap x y)⁻¹ = swap x y := rfl @[simp] lemma swap_mul_self (i j : α) : swap i j * swap i j = 1 := swap_swap i j lemma swap_mul_eq_mul_swap (f : perm α) (x y : α) : swap x y * f = f * swap (f⁻¹ x) (f⁻¹ y) := equiv.ext $ λ z, begin simp only [perm.mul_apply, swap_apply_def], split_ifs; simp only [perm.apply_inv_self, *, perm.eq_inv_iff_eq, eq_self_iff_true, not_true] at * end lemma mul_swap_eq_swap_mul (f : perm α) (x y : α) : f * swap x y = swap (f x) (f y) * f := by rw [swap_mul_eq_mul_swap, perm.inv_apply_self, perm.inv_apply_self] lemma swap_apply_apply (f : perm α) (x y : α) : swap (f x) (f y) = f * swap x y * f⁻¹ := by rw [mul_swap_eq_swap_mul, mul_inv_cancel_right] /-- Left-multiplying a permutation with `swap i j` twice gives the original permutation. This specialization of `swap_mul_self` is useful when using cosets of permutations. -/ @[simp] lemma swap_mul_self_mul (i j : α) (σ : perm α) : equiv.swap i j * (equiv.swap i j * σ) = σ := by rw [←mul_assoc, swap_mul_self, one_mul] /-- Right-multiplying a permutation with `swap i j` twice gives the original permutation. This specialization of `swap_mul_self` is useful when using cosets of permutations. -/ @[simp] lemma mul_swap_mul_self (i j : α) (σ : perm α) : (σ * equiv.swap i j) * equiv.swap i j = σ := by rw [mul_assoc, swap_mul_self, mul_one] /-- A stronger version of `mul_right_injective` -/ @[simp] lemma swap_mul_involutive (i j : α) : function.involutive ((*) (equiv.swap i j)) := swap_mul_self_mul i j /-- A stronger version of `mul_left_injective` -/ @[simp] lemma mul_swap_involutive (i j : α) : function.involutive (* (equiv.swap i j)) := mul_swap_mul_self i j @[simp] lemma swap_eq_one_iff {i j : α} : swap i j = (1 : perm α) ↔ i = j := swap_eq_refl_iff lemma swap_mul_eq_iff {i j : α} {σ : perm α} : swap i j * σ = σ ↔ i = j := ⟨(assume h, have swap_id : swap i j = 1 := mul_right_cancel (trans h (one_mul σ).symm), by {rw [←swap_apply_right i j, swap_id], refl}), (assume h, by erw [h, swap_self, one_mul])⟩ lemma mul_swap_eq_iff {i j : α} {σ : perm α} : σ * swap i j = σ ↔ i = j := ⟨(assume h, have swap_id : swap i j = 1 := mul_left_cancel (trans h (one_mul σ).symm), by {rw [←swap_apply_right i j, swap_id], refl}), (assume h, by erw [h, swap_self, mul_one])⟩ lemma swap_mul_swap_mul_swap {x y z : α} (hwz: x ≠ y) (hxz : x ≠ z) : swap y z * swap x y * swap y z = swap z x := equiv.ext $ λ n, by { simp only [swap_apply_def, perm.mul_apply], split_ifs; cc } end swap end equiv
db148556a91eaad7fbe94eb98d22cafbfd06c136
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/evalInit.lean
685297991bdf70626831fdb77c1c1ae62c159d99
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
78
lean
#eval show IO _ from do return RandomGen.next (← IO.stdGenRef.get) |>.fst
cd72000e3b705835012b9f53969f90477f3f987a
968e2f50b755d3048175f176376eff7139e9df70
/examples/prop_logic_theory/unnamed_2121.lean
1c04c93823c7fd69d157ca8d626d987ab4d1d284
[]
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
608
lean
variables {p q : Prop} -- BEGIN example : (¬p ∨ q) → (p → q) := begin intros h₁ h₂, -- Assume `h₁ : ¬p ∨ q`. Assume `h₂ : p`. It suffices to prove `q`. -- By or elim. on `h₁`, it suffices to 1. assume `h₃ : ¬p` and derive `q` and 2. assume `h₄ : q` and derive `q` cases h₁ with h₃ h₄, { exfalso, -- By false elimination, it suffices to prove `false`. show false, from h₃ h₂, }, -- We show false by false introduction on `h₃` and `h₂`. { show q, from h₄, }, -- We show `q` by reiteration on `h₄`. end -- END
804dd0f588c4ddbd55fffa2592599cca1bb74052
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/library/theories/analysis/normed_space.lean
bd114ae5e1224b1c2bde485b923ea0799cacd38b
[ "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
8,325
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad Normed spaces. -/ import algebra.module .metric_space open real nat classical noncomputable theory structure has_norm [class] (M : Type) : Type := (norm : M → ℝ) namespace analysis definition norm {M : Type} [has_normM : has_norm M] (v : M) : ℝ := has_norm.norm v notation `∥`v`∥` := norm v end analysis -- where is the right place to put this? structure real_vector_space [class] (V : Type) extends vector_space ℝ V structure normed_vector_space [class] (V : Type) extends real_vector_space V, has_norm V := (norm_zero : norm zero = 0) (eq_zero_of_norm_eq_zero : ∀ u : V, norm u = 0 → u = zero) (norm_triangle : ∀ u v, norm (add u v) ≤ norm u + norm v) (norm_smul : ∀ (a : ℝ) (v : V), norm (smul a v) = abs a * norm v) namespace analysis variable {V : Type} variable [normed_vector_space V] proposition norm_zero : ∥ (0 : V) ∥ = 0 := !normed_vector_space.norm_zero proposition eq_zero_of_norm_eq_zero {u : V} (H : ∥ u ∥ = 0) : u = 0 := !normed_vector_space.eq_zero_of_norm_eq_zero H proposition norm_triangle (u v : V) : ∥ u + v ∥ ≤ ∥ u ∥ + ∥ v ∥ := !normed_vector_space.norm_triangle proposition norm_smul (a : ℝ) (v : V) : ∥ a • v ∥ = abs a * ∥ v ∥ := !normed_vector_space.norm_smul proposition norm_neg (v : V) : ∥ -v ∥ = ∥ v ∥ := have abs (1 : ℝ) = 1, from abs_of_nonneg zero_le_one, by+ rewrite [-@neg_one_smul ℝ V, norm_smul, abs_neg, this, one_mul] end analysis section open analysis variable {V : Type} variable [normed_vector_space V] private definition nvs_dist [reducible] (u v : V) := ∥ u - v ∥ private lemma nvs_dist_self (u : V) : nvs_dist u u = 0 := by rewrite [↑nvs_dist, sub_self, norm_zero] private lemma eq_of_nvs_dist_eq_zero (u v : V) (H : nvs_dist u v = 0) : u = v := have u - v = 0, from eq_zero_of_norm_eq_zero H, eq_of_sub_eq_zero this private lemma nvs_dist_triangle (u v w : V) : nvs_dist u w ≤ nvs_dist u v + nvs_dist v w := calc nvs_dist u w = ∥ (u - v) + (v - w) ∥ : by rewrite [↑nvs_dist, *sub_eq_add_neg, add.assoc, neg_add_cancel_left] ... ≤ ∥ u - v ∥ + ∥ v - w ∥ : norm_triangle private lemma nvs_dist_comm (u v : V) : nvs_dist u v = nvs_dist v u := by rewrite [↑nvs_dist, -norm_neg, neg_sub] definition normed_vector_space_to_metric_space [reducible] [trans_instance] (V : Type) [nvsV : normed_vector_space V] : metric_space V := ⦃ metric_space, dist := nvs_dist, dist_self := nvs_dist_self, eq_of_dist_eq_zero := eq_of_nvs_dist_eq_zero, dist_comm := nvs_dist_comm, dist_triangle := nvs_dist_triangle ⦄ open nat proposition converges_to_seq_norm_elim {X : ℕ → V} {x : V} (H : X ⟶ x in ℕ) : ∀ {ε : ℝ}, ε > 0 → ∃ N₁ : ℕ, ∀ {n : ℕ}, n ≥ N₁ → ∥ X n - x ∥ < ε := H proposition dist_eq_norm_sub (u v : V) : dist u v = ∥ u - v ∥ := rfl proposition norm_eq_dist_zero (u : V) : ∥ u ∥ = dist u 0 := by rewrite [dist_eq_norm_sub, sub_zero] proposition norm_nonneg (u : V) : ∥ u ∥ ≥ 0 := by rewrite norm_eq_dist_zero; apply !dist_nonneg end structure banach_space [class] (V : Type) extends nvsV : normed_vector_space V := (complete : ∀ X, @analysis.cauchy V (@normed_vector_space_to_metric_space V nvsV) X → @analysis.converges_seq V (@normed_vector_space_to_metric_space V nvsV) X) definition banach_space_to_metric_space [reducible] [trans_instance] (V : Type) [bsV : banach_space V] : complete_metric_space V := ⦃ complete_metric_space, normed_vector_space_to_metric_space V, complete := banach_space.complete ⦄ namespace analysis variable {V : Type} variable [normed_vector_space V] variables {X Y : ℕ → V} variables {x y : V} proposition add_converges_to_seq (HX : X ⟶ x in ℕ) (HY : Y ⟶ y in ℕ) : (λ n, X n + Y n) ⟶ x + y in ℕ := take ε : ℝ, suppose ε > 0, have e2pos : ε / 2 > 0, from div_pos_of_pos_of_pos `ε > 0` two_pos, obtain (N₁ : ℕ) (HN₁ : ∀ {n}, n ≥ N₁ → ∥ X n - x ∥ < ε / 2), from converges_to_seq_norm_elim HX e2pos, obtain (N₂ : ℕ) (HN₂ : ∀ {n}, n ≥ N₂ → ∥ Y n - y ∥ < ε / 2), from converges_to_seq_norm_elim HY e2pos, let N := max N₁ N₂ in exists.intro N (take n, suppose n ≥ N, have ngtN₁ : n ≥ N₁, from nat.le_trans !le_max_left `n ≥ N`, have ngtN₂ : n ≥ N₂, from nat.le_trans !le_max_right `n ≥ N`, show ∥ (X n + Y n) - (x + y) ∥ < ε, from calc ∥ (X n + Y n) - (x + y) ∥ = ∥ (X n - x) + (Y n - y) ∥ : by rewrite [sub_add_eq_sub_sub, *sub_eq_add_neg, *add.assoc, add.left_comm (-x)] ... ≤ ∥ X n - x ∥ + ∥ Y n - y ∥ : norm_triangle ... < ε / 2 + ε / 2 : add_lt_add (HN₁ ngtN₁) (HN₂ ngtN₂) ... = ε : add_halves) private lemma smul_converges_to_seq_aux {c : ℝ} (cnz : c ≠ 0) (HX : X ⟶ x in ℕ) : (λ n, c • X n) ⟶ c • x in ℕ := take ε : ℝ, suppose ε > 0, have abscpos : abs c > 0, from abs_pos_of_ne_zero cnz, have epos : ε / abs c > 0, from div_pos_of_pos_of_pos `ε > 0` abscpos, obtain N (HN : ∀ {n}, n ≥ N → norm (X n - x) < ε / abs c), from converges_to_seq_norm_elim HX epos, exists.intro N (take n, suppose n ≥ N, have H : norm (X n - x) < ε / abs c, from HN this, show norm (c • X n - c • x) < ε, from calc norm (c • X n - c • x) = abs c * norm (X n - x) : by rewrite [-smul_sub_left_distrib, norm_smul] ... < abs c * (ε / abs c) : mul_lt_mul_of_pos_left H abscpos ... = ε : mul_div_cancel' (ne_of_gt abscpos)) proposition smul_converges_to_seq (c : ℝ) (HX : X ⟶ x in ℕ) : (λ n, c • X n) ⟶ c • x in ℕ := by_cases (assume cz : c = 0, have (λ n, c • X n) = (λ n, 0), from funext (take x, by rewrite [cz, zero_smul]), begin+ rewrite [this, cz, zero_smul], apply converges_to_seq_constant end) (suppose c ≠ 0, smul_converges_to_seq_aux this HX) proposition neg_converges_to_seq (HX : X ⟶ x in ℕ) : (λ n, - X n) ⟶ - x in ℕ := take ε, suppose ε > 0, obtain N (HN : ∀ {n}, n ≥ N → norm (X n - x) < ε), from converges_to_seq_norm_elim HX this, exists.intro N (take n, suppose n ≥ N, show norm (- X n - (- x)) < ε, by rewrite [-neg_neg_sub_neg, *neg_neg, norm_neg]; exact HN `n ≥ N`) proposition neg_converges_to_seq_iff : ((λ n, - X n) ⟶ - x in ℕ) ↔ (X ⟶ x in ℕ) := have aux : X = λ n, (- (- X n)), from funext (take n, by rewrite neg_neg), iff.intro (assume H : (λ n, -X n)⟶ -x in ℕ, show X ⟶ x in ℕ, by+ rewrite [aux, -neg_neg x]; exact neg_converges_to_seq H) neg_converges_to_seq proposition norm_converges_to_seq_zero (HX : X ⟶ 0 in ℕ) : (λ n, norm (X n)) ⟶ 0 in ℕ := take ε, suppose ε > 0, obtain N (HN : ∀ n, n ≥ N → norm (X n - 0) < ε), from HX `ε > 0`, exists.intro N (take n, assume Hn : n ≥ N, have norm (X n) < ε, begin rewrite -(sub_zero (X n)), apply HN n Hn end, show abs (norm (X n) - 0) < ε, using this, by rewrite [sub_zero, abs_of_nonneg !norm_nonneg]; apply this) proposition converges_to_seq_zero_of_norm_converges_to_seq_zero (HX : (λ n, norm (X n)) ⟶ 0 in ℕ) : X ⟶ 0 in ℕ := take ε, suppose ε > 0, obtain N (HN : ∀ n, n ≥ N → abs (norm (X n) - 0) < ε), from HX `ε > 0`, exists.intro (N : ℕ) (take n : ℕ, assume Hn : n ≥ N, have HN' : abs (norm (X n) - 0) < ε, from HN n Hn, have norm (X n) < ε, by+ rewrite [sub_zero at HN', abs_of_nonneg !norm_nonneg at HN']; apply HN', show norm (X n - 0) < ε, using this, by rewrite sub_zero; apply this) proposition norm_converges_to_seq_zero_iff (X : ℕ → V) : ((λ n, norm (X n)) ⟶ 0 in ℕ) ↔ (X ⟶ 0 in ℕ) := iff.intro converges_to_seq_zero_of_norm_converges_to_seq_zero norm_converges_to_seq_zero end analysis
679dab3b999e82242a264cdf9549f43bbd464023
e61bd74d1f38315f3bf7c924da3ee8d67d73fdab
/src/syntax.lean
cc672c57289350a4a148dc64333f1ef005693249
[]
no_license
maxd13/logic-soundness
4e0ef2ca8be1ed24ae0f1b4b9e50e63c6f231fb7
8821cc01ffcd3a73ed1e0eaaf2c97694fb4f422a
refs/heads/master
1,670,286,287,157
1,598,023,967,000
1,598,023,967,000
263,057,652
4
0
null
null
null
null
UTF-8
Lean
false
false
19,159
lean
import data.set.lattice tactic.find tactic.tidy tactic.ring universe u -- We implement first order predicate logic. namespace logic open list tactic set -- The type of signatures, which defines a first-order language, -- possibly with extra modalities, and with room for defining your -- own preferred variable type. @[derive inhabited] structure signature : Type (u+1) := (functional_symbol : Type u := pempty) (relational_symbol : Type u := pempty) (modality : Type u := pempty) (vars : Type u := ulift ℕ) (dec_vars : decidable_eq vars . apply_instance) (arity : functional_symbol → ℕ := λ_, 0) (rarity : relational_symbol → ℕ := λ_, 0) (marity : modality → ℕ := λ_, 0) -- A pseudo-predicate saying that the we can decide the equality -- between any symbols of the signature. -- Many definitions of proof theory need us to decide whether -- 2 symbols are equal, but many also do not, which justifies us -- keeping this as a separate structure. class signature.symbolic (σ : signature) := (dec_fun : decidable_eq σ.functional_symbol) (dec_rel : decidable_eq σ.relational_symbol) (dec_mod : decidable_eq σ.modality) -- decidable_eq instances that we get to infer from a -- (symbolic) signature. instance dec_vars (σ : signature) : decidable_eq σ.vars := σ.dec_vars instance dec_fun (σ : signature) [h : σ.symbolic] : decidable_eq σ.functional_symbol := h.dec_fun instance dec_rel (σ : signature) [h : σ.symbolic] : decidable_eq σ.relational_symbol := h.dec_rel instance dec_mod (σ : signature) [h : σ.symbolic] : decidable_eq σ.modality := h.dec_mod -- The signature whose formulas are propositional formulas built up -- from taking the instances of type α as propositional variables. def propositional_signature (α : Type u := ulift ℕ) : signature := { relational_symbol := α, vars := pempty, dec_vars := by apply_instance, } -- here we start with the syntactical definitions variable {σ : signature} -- arity types -- the type of functional symbols of arity n def signature.nary (σ : signature) (n : ℕ) := subtype {f : σ.functional_symbol | σ.arity f = n} -- the type of relational symbols of arity n def signature.nrary (σ : signature) (n : ℕ) := subtype {r : σ.relational_symbol | σ.rarity r = n} -- the predicate defining, and the type of, constants def is_constant (f : σ.functional_symbol) := σ.arity f = 0 def signature.const (σ : signature) := σ.nary 0 -- terms in the language inductive signature.term (σ : signature) | var : σ.vars → signature.term | app {n : ℕ} (f : σ.nary n) (v : fin n → signature.term) : signature.term -- constant terms. A function that lifts a constant to a term. def signature.cterm (σ : signature) : σ.const → σ.term | c := term.app c fin_zero_elim -- Rewrite a variable for a term in a term. -- This is also called a substitution of a variable for a term. def signature.term.rw : σ.term → σ.vars → σ.term → σ.term | (term.var a) x t := if x = a then t else term.var a | (term.app f v) x t := let v₂ := λ m, signature.term.rw (v m) x t in term.app f v₂ -- Get the set of variables of a term. def signature.term.vars : σ.term → set σ.vars | (term.var a) := {a} | (term.app f v) := let v₂ := λ m, signature.term.vars (v m) in ⋃ m, v₂ m -- denotative and non-denotative terms. @[reducible] def signature.term.denotes (t : σ.term) : Prop := t.vars = (∅ : set σ.vars) @[reducible] def signature.term.conotes (t : σ.term) := ¬ t.denotes -- a closed term is a Herbrand term. def signature.hterm (σ : signature) := subtype {t : σ.term | t.denotes} -- an open term is an expression. def signature.expression (σ : signature) := subtype {t : σ.term | t.conotes} -- some lemmas about term rewriting: theorem rw_eq_of_not_in_vars : ∀ (t₁ t₂ : σ.term) (x : σ.vars), x ∉ t₁.vars → t₁.rw x t₂ = t₁ := begin intros t₁ t₂ x, induction t₁; dunfold signature.term.vars signature.term.rw; simp; intro h, simp[h], ext y, specialize h y, exact t₁_ih y h, end theorem trivial_rw : ∀ (t: σ.term) (x), t.rw x (term.var x) = t := begin intros t x, induction t; dunfold signature.term.rw, by_cases x = t; simp [h], simp at *, ext y, exact t_ih y, end theorem den_rw : ∀ (t₁ t₂ : σ.term) (x : σ.vars), t₁.denotes → t₁.rw x t₂ = t₁ := begin intros t₁ t₂ x den₁, induction t₁, -- case var replace den₁ : (term.var t₁).vars = ∅ := den₁, replace den₁ : {t₁} = ∅ := den₁, replace den₁ := eq_empty_iff_forall_not_mem.mp den₁, specialize den₁ t₁, simp at den₁, contradiction, -- case app replace den₁ : (term.app t₁_f t₁_v).vars = ∅ := den₁, let v₂ := λ m, (t₁_v m).vars, replace den₁ : (⋃ m, v₂ m) = ∅ := den₁, have c₀ : ∀ m, (v₂ m) = ∅, intro m, ext, constructor, intro h, simp, have c : x_1 ∈ (⋃ m, v₂ m), simp, existsi m, exact h, rwa den₁ at c, intro insanity, simp at insanity, contradiction, have c₁ : ∀ m, (t₁_v m).denotes := c₀, have c₂ : ∀ m, (t₁_v m).rw x t₂ = (t₁_v m), intro m, exact t₁_ih m (c₁ m), dunfold signature.term.rw, simp[c₂], end -- Some auxiliary functions about terms (mostly unused): -- subterms of a term. def signature.term.subterms : σ.term → set σ.term | (term.app f v) := let v₂ := λ m, signature.term.subterms (v m) in (⋃ m, v₂ m) ∪ {(term.app f v)} | t := {t} -- set of all variables appearing in a list of terms. def list.vars : list σ.term → set σ.vars | [] := ∅ | (hd :: tl) := hd.vars ∪ tl.vars -- subterms of a list of terms. def list.subterms : list σ.term → set σ.term | [] := ∅ | (hd :: tl) := hd.subterms ∪ tl.subterms -- the same for sets. def subterms : set σ.term → set σ.term | S := ⋃ x ∈ S, signature.term.subterms x -- rewrite a variable in a list of terms. def list.rw : list σ.term → σ.vars → σ.term → list σ.term | [] _ _:= ∅ | (hd :: tl) x t := (hd.rw x t) :: tl.rw x t -- the type of formulas in the language inductive signature.formula (σ : signature) | relational {n : ℕ} (r : σ.nrary n) (v : fin n → σ.term) : signature.formula | for_all : σ.vars → signature.formula → signature.formula | if_then : signature.formula → signature.formula → signature.formula | equation (t₁ t₂ : σ.term) : signature.formula | false : signature.formula -- a convenient notation to set up for if_then reserve infixr ` ⇒ `:55 class has_exp (α : Type u) := (exp : α → α → α) infixr ⇒ := has_exp.exp instance signature.formula.has_exp : has_exp σ.formula := ⟨signature.formula.if_then⟩ -- definition of connectives def signature.formula.not (φ : σ.formula) := φ ⇒ signature.formula.false def signature.formula.or (φ ψ : σ.formula) := φ.not ⇒ ψ def signature.formula.and (φ ψ : σ.formula) := (φ.not.or ψ.not).not def signature.formula.iff (φ ψ : σ.formula) := (φ ⇒ ψ).and (ψ ⇒ φ) def signature.formula.exists (φ : σ.formula) (x : σ.vars) := (signature.formula.for_all x φ.not).not -- Rewrite (substitute) a variable for a term in a formula. def signature.formula.rw : σ.formula → σ.vars → σ.term → σ.formula | ( signature.formula.relational r v) x t := let v₂ := λ m, (v m).rw x t in signature.formula.relational r v₂ | ( signature.formula.for_all y φ) x t := let ψ := if y = x then φ else φ.rw x t in signature.formula.for_all y ψ | ( signature.formula.if_then φ ψ) x t := (φ.rw x t) ⇒ (ψ.rw x t) | ( signature.formula.equation t₁ t₂) x t := signature.formula.equation (t₁.rw x t) (t₂.rw x t) | φ _ _ := φ -- free variables def signature.formula.free : σ.formula → set σ.vars | ( signature.formula.relational r v) := ⋃ m, (v m).vars | ( signature.formula.for_all x φ) := φ.free - {x} | ( signature.formula.if_then φ ψ) := φ.free ∪ ψ.free | ( signature.formula.equation t₁ t₂) := t₁.vars ∪ t₂.vars | signature.formula.false := ∅ -- definition of whether a variable is -- substitutable for a term in a formula. -- Needed for proving some lemmas. def signature.formula.substitutable : σ.formula → σ.vars → σ.term → Prop | ( signature.formula.for_all y φ) x t := x ∉ ( signature.formula.for_all y φ).free ∨ (y ∉ t.vars ∧ φ.substitutable x t) | ( signature.formula.if_then φ ψ) y t := φ.substitutable y t ∧ ψ.substitutable y t | _ _ _ := true -- open and closed σ.formulas. def signature.formula.closed : σ.formula → Prop | φ := φ.free = ∅ def signature.formula.open : σ.formula → Prop | φ := ¬ φ.closed -- atomic and molecular formulas def signature.formula.atomic : σ.formula → bool | (formula.relational r v) := tt | (formula.equation t₁ t₂) := tt | formula.false := tt | _ := ff def signature.formula.molecular : σ.formula → bool | (formula.for_all x φ) := ff | (formula.if_then φ ψ) := φ.molecular && ψ.molecular | _ := tt -- utility for propositional logic def signature.proposition (σ : signature) := subtype {φ : σ.formula | φ.molecular} -- variables present in a formula def signature.formula.vars : σ.formula → set σ.vars | ( signature.formula.for_all x φ) := φ.free ∪ {x} | ( signature.formula.if_then φ ψ) := φ.vars ∪ ψ.vars | φ := φ.free -- terms present in a formula def signature.formula.terms : σ.formula → set σ.term | ( signature.formula.relational r v) := list.subterms (of_fn v) | ( signature.formula.for_all x φ) := φ.terms ∪ {term.var x} | ( signature.formula.if_then φ ψ) := φ.terms ∪ ψ.terms | _ := ∅ -- tells wether a term is present in a set of formulas. -- The name comes from the universal introduction rule, -- where we prove that a formula is valid for an "abstract" -- representative and conclude it is universally valid. def term.abstract_in : σ.term → set σ.formula → Prop | t S := t ∉ (⋃ φ ∈ S, signature.formula.terms φ) -- the same for variables. def abstract_in : σ.vars → set σ.formula → Prop | x S := x ∉ (⋃ φ ∈ S, signature.formula.free φ) -- construct the generalization of a σ.formula from a list of variables. -- This is just a fold but, I like being explicit about my folds when possible. -- Anyway, this ended up not being used so far. def signature.formula.generalize : σ.formula → list σ.vars → σ.formula | φ [] := φ | φ (x::xs) := signature.formula.for_all x $ φ.generalize xs -- lemmas about rewriting in formulas: theorem formula_rw : ∀ {φ : σ.formula} {x : σ.vars}, x ∉ φ.free → ∀(t : σ.term),φ.rw x t = φ := begin intros φ x h t, revert h, induction φ; dunfold signature.formula.free signature.formula.rw; simp; intro h, ext y, specialize h y, revert h, induction φ_v y; dunfold signature.term.rw signature.term.vars; intro h; simp at *, simp[h], ext z, specialize h z, specialize ih z, exact ih h, classical, by_cases eq₁ : x ∈ φ_a_1.free, simp [h eq₁], by_cases eq₂ : φ_a = x; simp [eq₂], exact φ_ih eq₁, all_goals{ push_neg at h, obtain ⟨h₁, h₂⟩ := h, }, replace h₁ := φ_ih_a h₁, replace h₂ := φ_ih_a_1 h₂, rw [h₁, h₂], refl, constructor; apply rw_eq_of_not_in_vars; assumption, end lemma trivial_formula_rw : ∀ {φ: σ.formula} {x}, φ.rw x (term.var x) = φ := begin intros φ x, induction φ; dunfold signature.formula.rw; try{simp}, ext, induction (φ_v x_1); dunfold signature.term.rw, by_cases x = a; simp [h], simp, ext, exact ih x_2, rw φ_ih, simp, simp [φ_ih_a, φ_ih_a_1], refl, constructor; apply trivial_rw; assumption, end -- deductive consequence of formulas: Γ ⊢ φ. -- Type of proofs from Γ to φ. -- The universe var here has been automatically generated, inductive proof : set σ.formula → σ.formula → Type u_1 | reflexivity (Γ : set σ.formula) (φ : σ.formula)(h : φ ∈ Γ) : proof Γ φ | transitivity (Γ Δ : set σ.formula) (φ : σ.formula) (h₁ : ∀ ψ ∈ Δ, proof Γ ψ) (h₂ : proof Δ φ) : proof Γ φ | modus_ponens (φ ψ : σ.formula) (Γ : set σ.formula) (h₁ : proof Γ (φ ⇒ ψ)) (h₂ : proof Γ φ) : proof Γ ψ | intro (φ ψ : σ.formula) (Γ : set σ.formula) (h : proof (Γ ∪ {φ}) ψ) : proof Γ (φ ⇒ ψ) | for_all_intro (Γ : set σ.formula) (φ : σ.formula) (x : σ.vars) (xf : x ∈ φ.free) (abs : abstract_in x Γ) (h : proof Γ φ) : proof Γ ( signature.formula.for_all x φ) | for_all_elim (Γ : set σ.formula) (φ : σ.formula) (x : σ.vars) --(xf : x ∈ φ.free) (t : σ.term) (sub : φ.substitutable x t) (h : proof Γ ( signature.formula.for_all x φ)) : proof Γ (φ.rw x t) | exfalso (Γ : set σ.formula) (φ : σ.formula) (h : proof Γ signature.formula.false) : proof Γ φ | by_contradiction (Γ : set σ.formula) (φ : σ.formula) (h : proof Γ φ.not.not) : proof Γ φ | identity_intro (Γ : set σ.formula) (t : σ.term) : proof Γ ( signature.formula.equation t t) | identity_elim (Γ : set σ.formula) (φ : σ.formula) (x : σ.vars) (xf : x ∈ φ.free) (t₁ t₂: σ.term) (sub₁ : φ.substitutable x t₁) (sub₂ : φ.substitutable x t₂) (h : proof Γ (φ.rw x t₁)) (eq : proof Γ ( signature.formula.equation t₁ t₂)) : proof Γ (φ.rw x t₂) local infixr `⊢`:55 := proof -- Some simple (meta-)theorems: variables (Γ Δ : set σ.formula) (φ : σ.formula) theorem self_entailment : Γ ⊢ (φ ⇒ φ) := begin apply proof.intro, apply proof.reflexivity (Γ∪{φ}) φ, simp end theorem monotonicity : Δ ⊆ Γ → Δ ⊢ φ → Γ ⊢ φ := begin intros H h, have c₁ : ∀ ψ ∈ Δ, proof Γ ψ, intros ψ hψ, apply proof.reflexivity Γ ψ, exact H hψ, apply proof.transitivity; assumption, end -- The following commented code chunks are unfinished attempts -- to prove that proofs are finite (they can be safely ignored): -- This one depends on syntatical equality between σ.formulas -- being decidable, which in turn depends on the equality of -- functional and relational symbols being decidable -- (i.e. σ must be "symbolic"). We will probably move this -- to another module to deal with "symbolic" signatures later. -- extracts the premisses (∈ Γ) use to prove φ from Γ. -- def proof.premisses : Γ ⊢ φ → list (subtype Γ) := -- begin -- intros h, -- induction h, -- -- case reflexivity -- exact [⟨h_φ, h_h⟩], -- -- case transitivity -- rename h_ih_h₁ ih₁, -- induction h_ih_h₂, -- exact [], -- obtain ⟨ψ, H⟩ := h_ih_h₂_hd, -- specialize ih₁ ψ H, -- exact ih₁ ++ h_ih_h₂_ih, -- -- case modus ponens -- exact h_ih_h₁ ++ h_ih_h₂, -- -- case intro -- set t : set σ.formula := h_Γ ∪ {h_φ}, -- have ct : h_φ ∈ t, simp, -- let c : subtype t := ⟨h_φ, ct⟩, -- all_goals{admit}, -- end -- This here are earlier attempts to squash proof trees either as lists -- or finsets. -- open finset -- local notation `{` x `}ₙ` := finset.singleton x -- #find ∀ _ ∈ _, ∃ _, _ -- def list.to_set : list σ.formula → set σ.formula -- | [] := ∅ -- | (φ::xs) := {φ} ∪ xs.to_set -- def proof : list σ.formula → Prop -- | [] := false -- | (ψ::[]) := ψ ∈ Γ ∨ ∅ ⊢ ψ -- | (ψ::xs) := (ψ ∈ Γ ∨ list.to_set xs ⊢ ψ) ∧ -- proof xs -- def proof_of (φ) : list σ.formula → Prop -- | [] := false -- | (ψ::xs) := ψ = φ ∧ proof Γ (ψ::xs) -- theorem finite_proofs : Γ ⊢ φ → ∃ xs : list σ.formula, proof_of Γ φ xs := -- begin -- intro h, -- induction h, -- -- case reflexivity -- let xs := [h_φ], -- use xs, -- simp [xs, proof_of,proof], -- left, -- assumption, -- -- case transitivity -- rename h_ih_h₁ ih, -- obtain ⟨p, hp⟩ := h_ih_h₂, -- -- let xs : list σ.formula, -- -- cases p; -- -- simp[proof_of] at hp, -- -- contradiction, -- -- obtain ⟨hp₁, hp₂⟩ := hp, -- -- revert hp₂, -- admit, -- -- case modus ponens -- end -- theorem finite_proofs : Γ ⊢ φ → ∃ Δ : finset σ.formula, ↑Δ ⊆ Γ ∧ ↑Δ ⊢ φ := -- begin -- intro h, -- induction h, -- -- case reflexivity -- existsi finset.singleton h_φ, -- simp [proof.reflexivity], -- assumption, -- -- case transitivity -- obtain ⟨Δ, HΔ, hΔ⟩ := h_ih_h₂, -- -- have c : ∀ ψ ∈ Δ, ∃ (Δ₂ : finset σ.formula), ↑Δ₂ ⊆ h_Γ ∧ proof ↑Δ₂ ψ, -- -- intros ψ Hψ, -- -- exact h_ih_h₁ ψ (HΔ Hψ), -- -- have c := λ ψ ∈ Δ, classical.subtype_of_exists (h_ih_h₁ ψ (HΔ _)), -- -- have c₂ : ⋃ ψ ∈ Δ, classical.some (h_ih_h₁ ψ (HΔ _)), -- -- have d : ∀ {α} -- -- induction Δ using finset.induction, -- -- admit, -- -- use ∅, -- -- simp, -- -- exact hΔ, -- -- classical, -- -- by_cases ne : Δ.nonempty, -- -- obtain ⟨ψ, Hψ⟩ := ne, -- -- have ih := h_ih_h₁ ψ H, -- -- existsi ⋃ ψ ∈ Δ, (c ψ H).val, -- end -- Consistency doesn't need to be defined just for theories. def consistent (Γ : set σ.formula) := ¬ nonempty (Γ ⊢ signature.formula.false) -- At any rate we can define it for theories as well. -- Here is the definition of a theory: def signature.theory (σ : signature) := subtype {Γ : set σ.formula | ∀ φ, Γ ⊢ φ → φ ∈ Γ} def theory.consistent (Γ : σ.theory) := consistent Γ.val end logic