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
ffc9fd4a9789c68abf91f228c9e181a14662c7ad
4727251e0cd73359b15b664c3170e5d754078599
/src/ring_theory/localization/submodule.lean
ffe41ebd8441f28414b7e2544832223379578453
[ "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,515
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro, Johan Commelin, Amelia Livingston, Anne Baanen -/ import ring_theory.localization.fraction_ring import ring_theory.localization.ideal import ring_theory.principal_ideal_domain /-! # Submodules in localizations of commutative rings ## Implementation notes See `src/ring_theory/localization/basic.lean` for a design overview. ## Tags localization, ring localization, commutative ring localization, characteristic predicate, commutative ring, field of fractions -/ variables {R : Type*} [comm_ring R] (M : submonoid R) (S : Type*) [comm_ring S] variables [algebra R S] {P : Type*} [comm_ring P] namespace is_localization /-- Map from ideals of `R` to submodules of `S` induced by `f`. -/ -- This was previously a `has_coe` instance, but if `S = R` then this will loop. -- It could be a `has_coe_t` instance, but we keep it explicit here to avoid slowing down -- the rest of the library. def coe_submodule (I : ideal R) : submodule R S := submodule.map (algebra.linear_map R S) I lemma mem_coe_submodule (I : ideal R) {x : S} : x ∈ coe_submodule S I ↔ ∃ y : R, y ∈ I ∧ algebra_map R S y = x := iff.rfl lemma coe_submodule_mono {I J : ideal R} (h : I ≤ J) : coe_submodule S I ≤ coe_submodule S J := submodule.map_mono h @[simp] lemma coe_submodule_bot : coe_submodule S (⊥ : ideal R) = ⊥ := by rw [coe_submodule, submodule.map_bot] @[simp] lemma coe_submodule_top : coe_submodule S (⊤ : ideal R) = 1 := by rw [coe_submodule, submodule.map_top, submodule.one_eq_range] @[simp] lemma coe_submodule_sup (I J : ideal R) : coe_submodule S (I ⊔ J) = coe_submodule S I ⊔ coe_submodule S J := submodule.map_sup _ _ _ @[simp] lemma coe_submodule_mul (I J : ideal R) : coe_submodule S (I * J) = coe_submodule S I * coe_submodule S J := submodule.map_mul _ _ (algebra.of_id R S) lemma coe_submodule_fg (hS : function.injective (algebra_map R S)) (I : ideal R) : submodule.fg (coe_submodule S I) ↔ submodule.fg I := ⟨submodule.fg_of_fg_map _ (linear_map.ker_eq_bot.mpr hS), submodule.fg.map _⟩ @[simp] lemma coe_submodule_span (s : set R) : coe_submodule S (ideal.span s) = submodule.span R ((algebra_map R S) '' s) := by { rw [is_localization.coe_submodule, ideal.span, submodule.map_span], refl } @[simp] lemma coe_submodule_span_singleton (x : R) : coe_submodule S (ideal.span {x}) = submodule.span R {(algebra_map R S) x} := by rw [coe_submodule_span, set.image_singleton] variables {g : R →+* P} variables {T : submonoid P} (hy : M ≤ T.comap g) {Q : Type*} [comm_ring Q] variables [algebra P Q] [is_localization T Q] variables [is_localization M S] section include M lemma is_noetherian_ring (h : is_noetherian_ring R) : is_noetherian_ring S := begin rw [is_noetherian_ring_iff, is_noetherian_iff_well_founded] at h ⊢, exact order_embedding.well_founded ((is_localization.order_embedding M S).dual) h end end variables {S Q M} @[mono] lemma coe_submodule_le_coe_submodule (h : M ≤ non_zero_divisors R) {I J : ideal R} : coe_submodule S I ≤ coe_submodule S J ↔ I ≤ J := submodule.map_le_map_iff_of_injective (is_localization.injective _ h) _ _ @[mono] lemma coe_submodule_strict_mono (h : M ≤ non_zero_divisors R) : strict_mono (coe_submodule S : ideal R → submodule R S) := strict_mono_of_le_iff_le (λ _ _, (coe_submodule_le_coe_submodule h).symm) variables (S) {Q M} lemma coe_submodule_injective (h : M ≤ non_zero_divisors R) : function.injective (coe_submodule S : ideal R → submodule R S) := injective_of_le_imp_le _ (λ _ _, (coe_submodule_le_coe_submodule h).mp) lemma coe_submodule_is_principal {I : ideal R} (h : M ≤ non_zero_divisors R) : (coe_submodule S I).is_principal ↔ I.is_principal := begin split; unfreezingI { rintros ⟨⟨x, hx⟩⟩ }, { have x_mem : x ∈ coe_submodule S I := hx.symm ▸ submodule.mem_span_singleton_self x, obtain ⟨x, x_mem, rfl⟩ := (mem_coe_submodule _ _).mp x_mem, refine ⟨⟨x, coe_submodule_injective S h _⟩⟩, rw [ideal.submodule_span_eq, hx, coe_submodule_span_singleton] }, { refine ⟨⟨algebra_map R S x, _⟩⟩, rw [hx, ideal.submodule_span_eq, coe_submodule_span_singleton] } end variables {S} (M) lemma mem_span_iff {N : Type*} [add_comm_group N] [module R N] [module S N] [is_scalar_tower R S N] {x : N} {a : set N} : x ∈ submodule.span S a ↔ ∃ (y ∈ submodule.span R a) (z : M), x = mk' S 1 z • y := begin split, intro h, { refine submodule.span_induction h _ _ _ _, { rintros x hx, exact ⟨x, submodule.subset_span hx, 1, by rw [mk'_one, _root_.map_one, one_smul]⟩ }, { exact ⟨0, submodule.zero_mem _, 1, by rw [mk'_one, _root_.map_one, one_smul]⟩ }, { rintros _ _ ⟨y, hy, z, rfl⟩ ⟨y', hy', z', rfl⟩, refine ⟨(z' : R) • y + (z : R) • y', (submodule.add_mem _ (submodule.smul_mem _ _ hy) (submodule.smul_mem _ _ hy')), z * z', _⟩, rw [smul_add, ← is_scalar_tower.algebra_map_smul S (z : R), ← is_scalar_tower.algebra_map_smul S (z' : R), smul_smul, smul_smul], congr' 1, { rw [← mul_one (1 : R), mk'_mul, mul_assoc, mk'_spec, _root_.map_one, mul_one, mul_one] }, { rw [← mul_one (1 : R), mk'_mul, mul_right_comm, mk'_spec, _root_.map_one, mul_one, one_mul] }, all_goals { apply_instance } }, { rintros a _ ⟨y, hy, z, rfl⟩, obtain ⟨y', z', rfl⟩ := mk'_surjective M a, refine ⟨y' • y, submodule.smul_mem _ _ hy, z' * z, _⟩, rw [← is_scalar_tower.algebra_map_smul S y', smul_smul, ← mk'_mul, smul_smul, mul_comm (mk' S _ _), mul_mk'_eq_mk'_of_mul], all_goals { apply_instance } } }, { rintro ⟨y, hy, z, rfl⟩, exact submodule.smul_mem _ _ (submodule.span_subset_span R S _ hy) } end lemma mem_span_map {x : S} {a : set R} : x ∈ ideal.span (algebra_map R S '' a) ↔ ∃ (y ∈ ideal.span a) (z : M), x = mk' S y z := begin refine (mem_span_iff M).trans _, split, { rw ← coe_submodule_span, rintros ⟨_, ⟨y, hy, rfl⟩, z, hz⟩, refine ⟨y, hy, z, _⟩, rw [hz, algebra.linear_map_apply, smul_eq_mul, mul_comm, mul_mk'_eq_mk'_of_mul, mul_one] }, { rintros ⟨y, hy, z, hz⟩, refine ⟨algebra_map R S y, submodule.map_mem_span_algebra_map_image _ _ hy, z, _⟩, rw [hz, smul_eq_mul, mul_comm, mul_mk'_eq_mk'_of_mul, mul_one] }, end end is_localization namespace is_fraction_ring open is_localization variables {R} {A K : Type*} [comm_ring A] section comm_ring variables [comm_ring K] [algebra R K] [is_fraction_ring R K] [algebra A K] [is_fraction_ring A K] @[simp, mono] lemma coe_submodule_le_coe_submodule {I J : ideal R} : coe_submodule K I ≤ coe_submodule K J ↔ I ≤ J := is_localization.coe_submodule_le_coe_submodule le_rfl @[mono] lemma coe_submodule_strict_mono : strict_mono (coe_submodule K : ideal R → submodule R K) := strict_mono_of_le_iff_le (λ _ _, coe_submodule_le_coe_submodule.symm) variables (R K) lemma coe_submodule_injective : function.injective (coe_submodule K : ideal R → submodule R K) := injective_of_le_imp_le _ (λ _ _, (coe_submodule_le_coe_submodule).mp) @[simp] lemma coe_submodule_is_principal {I : ideal R} : (coe_submodule K I).is_principal ↔ I.is_principal := is_localization.coe_submodule_is_principal _ le_rfl end comm_ring end is_fraction_ring
80163cb9c840f81788829ec6927772d35bfa50e4
df7bb3acd9623e489e95e85d0bc55590ab0bc393
/lean/love06_monads_demo.lean
664ea96fbc7210a919e49539f4c7bcff8de33e4d
[]
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
11,478
lean
import .lovelib /- # LoVe Demo 6: Monads We take a look at an important functional programming abstraction: monads. Monads generalize computation with side effects. Haskell has shown that monads can be used very successful to write imperative programs. For us, they are interesting in their own right and for two more reasons: * They provide a nice example of axiomatic reasoning. * They are useful for programming Lean itself (metaprogramming, lecture 7). -/ set_option pp.beta true set_option pp.generalized_field_notation false namespace LoVe /- ## Introductory Example Consider the following programming task: Implement a function `sum_2_5_7 ns` that sums up the second, fifth, and seventh items of a list `ns` of natural numbers. Use `option ℕ` for the result so that if the list has fewer than seven elements, you can return `option.none`. A straightforward solution follows: -/ def sum_2_5_7 (ns : list ℕ) : option ℕ := match list.nth ns 1 with | option.none := option.none | option.some n2 := match list.nth ns 4 with | option.none := option.none | option.some n5 := match list.nth ns 6 with | option.none := option.none | option.some n7 := option.some (n2 + n5 + n7) end end end /- The code is ugly, because of all the pattern matching on options. We can put all the ugliness in one function, which we call `connect`: -/ def connect {α : Type} {β : Type} : option α → (α → option β) → option β | option.none f := option.none | (option.some a) f := f a def sum_2_5_7₂ (ns : list ℕ) : option ℕ := connect (list.nth ns 1) (λn2, connect (list.nth ns 4) (λn5, connect (list.nth ns 6) (λn7, option.some (n2 + n5 + n7)))) /- Instead of defining `connect` ourselves, we can use Lean's predefined general `bind` operation. We can also use `pure` instead of `option.some`: -/ #check bind def sum_2_5_7₃ (ns : list ℕ) : option ℕ := bind (list.nth ns 1) (λn2, bind (list.nth ns 4) (λn5, bind (list.nth ns 6) (λn7, pure (n2 + n5 + n7)))) /- Syntactic sugar: `ma >>= f` := `bind ma f` -/ #check (>>=) def sum_2_5_7₄ (ns : list ℕ) : option ℕ := list.nth ns 1 >>= λn2, list.nth ns 4 >>= λn5, list.nth ns 6 >>= λn7, pure (n2 + n5 + n7) /- Syntactic sugar: `do a ← ma, t` := `ma >>= (λa, t)` `do ma, t` := `ma >>= (λ_, t)` -/ def sum_2_5_7₅ (ns : list ℕ) : option ℕ := do n2 ← list.nth ns 1, do n5 ← list.nth ns 4, do n7 ← list.nth ns 6, pure (n2 + n5 + n7) /- The `do`s can be combined: -/ def sum_2_5_7₆ (ns : list ℕ) : option ℕ := do n2 ← list.nth ns 1, n5 ← list.nth ns 4, n7 ← list.nth ns 6, pure (n2 + n5 + n7) /- Although the notation has an imperative flavor, the function is a pure functional program. ## Two Operations and Three Laws The `option` type constructor is an example of a monad. In general, a __monad__ is a type constructor `m` that depends on some type parameter `α` (i.e., `m α`) equipped with two distinguished operations: `pure {α : Type} : α → m α` `bind {α β : Type} : m α → (α → m β) → m β` For `option`: `pure` := `option.some` `bind` := `connect` Intuitively, we can think of a monad as a "box": * `pure` puts the data into the box. * `bind` allows us to access the data in the box and modify it (possibly even changing its type, since the result is an `m β` monad, not a `m α` monad). There is no general way to extract the data from the monad, i.e., to obtain an `α` from an `m α`. To summarize, `pure a` provides no side effect and simply provides a box containing the the value `a`, whereas `bind ma f` (also written `ma >>= f`) executes `ma`, then executes `f` with the boxed result `a` of `ma`. The option monad is only one instance among many. Type | Effect ------------ | -------------------------------------------------------------- `id α` | no effect `option α` | simple exceptions `σ → α × σ` | threading through a state of type `σ` `set α` | nondeterministic computation returning `α` values `t → α` | reading elements of type `t` (e.g., a configuration) `ℕ × α` | adjoining running time (e.g., to model algorithmic complexity) `string × α` | adjoining text output (e.g., for logging) `prob α` | probability (e.g., using random number generators) `io α` | interaction with the operating system `tactic α` | interaction with the proof assistant All of the above are type constructors `m` are parameterized by a type `α`. Some effects can be combined (e.g., `option (t → α)`). Some effects are not executable (e.g., `set α`, `prob α`). They are nonetheless useful for modeling programs abstractly in the logic. Specific monads may provide a way to extract the boxed value stored in the monad without `bind`'s requirement of putting it back in a monad. Monads have several benefits, including: * They provide the convenient and highly readable `do` notation. * They support generic operations, such as `mmap {α β : Type} : (α → m β) → list α → m (list β)`, which work uniformly across all monads. The `bind` and `pure` operations are normally required to obey three laws, called the monad laws. Pure data as the first program can be simplified away: do a' ← pure a, f a' = f a Pure data as the second program can be simplified away: do a ← ma, pure a = ma Nested programs `ma`, `f`, `g` can be flattened using this associativity rule: do b ← do { a ← ma, f a }, g b = do a ← ma, b ← f a, g b ## A Type Class of Monads Monads are a mathematical structure, so we use class to add them as a type class. We can think of a type class as a structure that is parameterized by a type—or here, by a type constructor `m : Type → Type`. -/ @[class] structure lawful_monad (m : Type → Type) extends has_bind m, has_pure m := (pure_bind {α β : Type} (a : α) (f : α → m β) : (pure a >>= f) = f a) (bind_pure {α : Type} (ma : m α) : (ma >>= pure) = ma) (bind_assoc {α β γ : Type} (f : α → m β) (g : β → m γ) (ma : m α) : ((ma >>= f) >>= g) = (ma >>= (λa, f a >>= g))) #print monad #print is_lawful_monad /- Step by step: * We are creating a structure parameterized by a unary type constructor `m`. * The structure inherits the fields, and any syntactic sugar, from structures called `has_bind` and `has_pure`, which provide the `bind` and `pure` operations on `m` and some syntactic sugar. * The definition adds three fields to those already provided by `has_bind` and `has_pure`, to store the proofs of the monad laws. To instantiate this definition with a concrete monad, we must supply the type constructor `m` (e.g., `option`), `bind` and `pure` operators, and proofs of the monad laws. (Lean's actual definition of monads is more complicated.) ## No Effects -/ def id.pure {α : Type} : α → id α := id def id.bind {α β : Type} : id α → (α → id β) → id β | a f := f a @[instance] def id.lawful_monad : lawful_monad id := { pure := @id.pure, bind := @id.bind, pure_bind := begin intros α β a f, refl end, bind_pure := begin intros α ma, refl end, bind_assoc := begin intros α β γ f g ma, refl end } /- ## Exceptions -/ def option.pure {α : Type} : α → option α := option.some def option.bind {α β : Type} : option α → (α → option β) → option β | option.none f := option.none | (option.some a) f := f a @[instance] def option.lawful_monad : lawful_monad option := { pure := @option.pure, bind := @option.bind, pure_bind := begin intros α β a f, refl end, bind_pure := begin intros α ma, cases' ma, { refl }, { refl } end, bind_assoc := begin intros α β γ f g ma, cases' ma, { refl }, { refl } end } def option.throw {α : Type} : option α := option.none def option.catch {α : Type} : option α → option α → option α | option.none ma' := ma' | (option.some a) _ := option.some a @[instance] def option.has_orelse : has_orelse option := { orelse := @option.catch } /- ## Mutable State -/ def action (σ α : Type) := σ → α × σ def action.read {σ : Type} : action σ σ | s := (s, s) def action.write {σ : Type} (s : σ) : action σ unit | _ := ((), s) def action.pure {σ α : Type} (a : α) : action σ α | s := (a, s) def action.bind {σ : Type} {α β : Type} (ma : action σ α) (f : α → action σ β) : action σ β | s := match ma s with | (a, s') := f a s' end @[instance] def action.lawful_monad {σ : Type} : lawful_monad (action σ) := { pure := @action.pure σ, bind := @action.bind σ, pure_bind := begin intros α β a f, apply funext, intro s, refl end, bind_pure := begin intros α ma, apply funext, intro s, simp [action.bind], cases' ma s, refl end, bind_assoc := begin intros α β γ f g ma, apply funext, intro s, simp [action.bind], cases' ma s, refl end } def diff_list : list ℕ → action ℕ (list ℕ) | [] := pure [] | (n :: ns) := do prev ← action.read, if n < prev then diff_list ns else do action.write n, ns' ← diff_list ns, pure (n :: ns') #eval diff_list [1, 2, 3, 2] 0 #eval diff_list [1, 2, 3, 2, 4, 5, 2] 0 /- ## Nondeterminism -/ #check set def set.pure {α : Type} : α → set α | a := {a} def set.bind {α β : Type} : set α → (α → set β) → set β | A f := {b | ∃a, a ∈ A ∧ b ∈ f a} @[instance] def set.lawful_monad : lawful_monad set := { pure := @set.pure, bind := @set.bind, pure_bind := begin intros α β a f, simp [set.pure, set.bind] end, bind_pure := begin intros α ma, simp [set.pure, set.bind] end, bind_assoc := begin intros α β γ f g ma, simp [set.pure, set.bind], apply set.ext, simp, tautology end } /- `tautology` performs elimination of the logical symbols `∧`, `∨`, `↔`, and `∃` in hypotheses and introduction of `∧`, `↔`, and `∃` in the conclusion, until all the emerging subgoals can be trivially proved (e.g., by `refl`). ## A Generic Algorithm: Iteration over a List -/ def mmap {m : Type → Type} [lawful_monad m] {α β : Type} (f : α → m β) : list α → m (list β) | [] := pure [] | (a :: as) := do b ← f a, bs ← mmap as, pure (b :: bs) lemma mmap_append {m : Type → Type} [lawful_monad m] {α β : Type} (f : α → m β) : ∀as as' : list α, mmap f (as ++ as') = do bs ← mmap f as, bs' ← mmap f as', pure (bs ++ bs') | [] _ := by simp [mmap, lawful_monad.bind_pure, lawful_monad.pure_bind] | (a :: as) as' := by simp [mmap, mmap_append as as', lawful_monad.pure_bind, lawful_monad.bind_assoc] def nths {α : Type} (xss : list (list α)) (n : ℕ) : option (list α) := mmap (λxs, list.nth xs n) xss #eval nths [[11, 12, 13, 14], [21, 22, 23], [31, 32, 33]] 2 end LoVe
42581f2b3228cd79a1a58cb46dbcd9316ccb4e18
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/concrete_category/basic.lean
1b2a24cd9c1d8dc61ddb498a9646286450999820
[ "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
7,751
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Johannes Hölzl, Reid Barton, Sean Leather, Yury Kudryashov -/ import category_theory.types import category_theory.epi_mono /-! # Concrete categories A concrete category is a category `C` with a fixed faithful functor `forget : C ⥤ Type*`. We define concrete categories using `class concrete_category`. In particular, we impose no restrictions on the carrier type `C`, so `Type` is a concrete category with the identity forgetful functor. Each concrete category `C` comes with a canonical faithful functor `forget C : C ⥤ Type*`. We say that a concrete category `C` admits a *forgetful functor* to a concrete category `D`, if it has a functor `forget₂ C D : C ⥤ D` such that `(forget₂ C D) ⋙ (forget D) = forget C`, see `class has_forget₂`. Due to `faithful.div_comp`, it suffices to verify that `forget₂.obj` and `forget₂.map` agree with the equality above; then `forget₂` will satisfy the functor laws automatically, see `has_forget₂.mk'`. Two classes helping construct concrete categories in the two most common cases are provided in the files `bundled_hom` and `unbundled_hom`, see their documentation for details. ## References See [Ahrens and Lumsdaine, *Displayed Categories*][ahrens2017] for related work. -/ universes w v v' u namespace category_theory /-- A concrete category is a category `C` with a fixed faithful functor `forget : C ⥤ Type`. Note that `concrete_category` potentially depends on three independent universe levels, * the universe level `w` appearing in `forget : C ⥤ Type w` * the universe level `v` of the morphisms (i.e. we have a `category.{v} C`) * the universe level `u` of the objects (i.e `C : Type u`) They are specified that order, to avoid unnecessary universe annotations. -/ class concrete_category (C : Type u) [category.{v} C] := (forget [] : C ⥤ Type w) [forget_faithful : faithful forget] attribute [instance] concrete_category.forget_faithful /-- The forgetful functor from a concrete category to `Type u`. -/ @[reducible] def forget (C : Type v) [category C] [concrete_category.{u} C] : C ⥤ Type u := concrete_category.forget C instance concrete_category.types : concrete_category (Type u) := { forget := 𝟭 _ } /-- Provide a coercion to `Type u` for a concrete category. This is not marked as an instance as it could potentially apply to every type, and so is too expensive in typeclass search. You can use it on particular examples as: ``` instance : has_coe_to_sort X := concrete_category.has_coe_to_sort X ``` -/ def concrete_category.has_coe_to_sort (C : Type v) [category C] [concrete_category C] : has_coe_to_sort C := { S := Type u, coe := (concrete_category.forget C).obj } section local attribute [instance] concrete_category.has_coe_to_sort variables {C : Type v} [category C] [concrete_category C] @[simp] lemma forget_obj_eq_coe {X : C} : (forget C).obj X = X := rfl /-- Usually a bundled hom structure already has a coercion to function that works with different universes. So we don't use this as a global instance. -/ def concrete_category.has_coe_to_fun {X Y : C} : has_coe_to_fun (X ⟶ Y) := { F := λ f, X → Y, coe := λ f, (forget _).map f } local attribute [instance] concrete_category.has_coe_to_fun /-- In any concrete category, we can test equality of morphisms by pointwise evaluations.-/ lemma concrete_category.hom_ext {X Y : C} (f g : X ⟶ Y) (w : ∀ x : X, f x = g x) : f = g := begin apply faithful.map_injective (forget C), ext, exact w x, end @[simp] lemma forget_map_eq_coe {X Y : C} (f : X ⟶ Y) : (forget C).map f = f := rfl /-- Analogue of `congr_fun h x`, when `h : f = g` is an equality between morphisms in a concrete category. -/ lemma congr_hom {X Y : C} {f g : X ⟶ Y} (h : f = g) (x : X) : f x = g x := congr_fun (congr_arg (λ k : X ⟶ Y, (k : X → Y)) h) x lemma coe_id {X : C} : ((𝟙 X) : X → X) = id := (forget _).map_id X lemma coe_comp {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g : X → Z) = g ∘ f := (forget _).map_comp f g @[simp] lemma id_apply {X : C} (x : X) : ((𝟙 X) : X → X) x = x := congr_fun ((forget _).map_id X) x @[simp] lemma comp_apply {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) (x : X) : (f ≫ g) x = g (f x) := congr_fun ((forget _).map_comp _ _) x @[simp] lemma coe_hom_inv_id {X Y : C} (f : X ≅ Y) (x : X) : f.inv (f.hom x) = x := congr_fun ((forget C).map_iso f).hom_inv_id x @[simp] lemma coe_inv_hom_id {X Y : C} (f : X ≅ Y) (y : Y) : f.hom (f.inv y) = y := congr_fun ((forget C).map_iso f).inv_hom_id y lemma concrete_category.congr_hom {X Y : C} {f g : X ⟶ Y} (h : f = g) (x : X) : f x = g x := congr_fun (congr_arg (λ f : X ⟶ Y, (f : X → Y)) h) x lemma concrete_category.congr_arg {X Y : C} (f : X ⟶ Y) {x x' : X} (h : x = x') : f x = f x' := congr_arg (f : X → Y) h /-- In any concrete category, injective morphisms are monomorphisms. -/ lemma concrete_category.mono_of_injective {X Y : C} (f : X ⟶ Y) (i : function.injective f) : mono f := faithful_reflects_mono (forget C) ((mono_iff_injective f).2 i) /-- In any concrete category, surjective morphisms are epimorphisms. -/ lemma concrete_category.epi_of_surjective {X Y : C} (f : X ⟶ Y) (s : function.surjective f) : epi f := faithful_reflects_epi (forget C) ((epi_iff_surjective f).2 s) @[simp] lemma concrete_category.has_coe_to_fun_Type {X Y : Type u} (f : X ⟶ Y) : coe_fn f = f := rfl end /-- `has_forget₂ C D`, where `C` and `D` are both concrete categories, provides a functor `forget₂ C D : C ⥤ D` and a proof that `forget₂ ⋙ (forget D) = forget C`. -/ class has_forget₂ (C : Type v) (D : Type v') [category C] [concrete_category.{u} C] [category D] [concrete_category.{u} D] := (forget₂ : C ⥤ D) (forget_comp : forget₂ ⋙ (forget D) = forget C . obviously) /-- The forgetful functor `C ⥤ D` between concrete categories for which we have an instance `has_forget₂ C `. -/ @[reducible] def forget₂ (C : Type v) (D : Type v') [category C] [concrete_category C] [category D] [concrete_category D] [has_forget₂ C D] : C ⥤ D := has_forget₂.forget₂ instance forget_faithful (C : Type v) (D : Type v') [category C] [concrete_category C] [category D] [concrete_category D] [has_forget₂ C D] : faithful (forget₂ C D) := has_forget₂.forget_comp.faithful_of_comp instance induced_category.concrete_category {C : Type v} {D : Type v'} [category D] [concrete_category D] (f : C → D) : concrete_category (induced_category D f) := { forget := induced_functor f ⋙ forget D } instance induced_category.has_forget₂ {C : Type v} {D : Type v'} [category D] [concrete_category D] (f : C → D) : has_forget₂ (induced_category D f) D := { forget₂ := induced_functor f, forget_comp := rfl } /-- In order to construct a “partially forgetting” functor, we do not need to verify functor laws; it suffices to ensure that compositions agree with `forget₂ C D ⋙ forget D = forget C`. -/ def has_forget₂.mk' {C : Type v} {D : Type v'} [category C] [concrete_category C] [category D] [concrete_category D] (obj : C → D) (h_obj : ∀ X, (forget D).obj (obj X) = (forget C).obj X) (map : Π {X Y}, (X ⟶ Y) → (obj X ⟶ obj Y)) (h_map : ∀ {X Y} {f : X ⟶ Y}, (forget D).map (map f) == (forget C).map f) : has_forget₂ C D := { forget₂ := faithful.div _ _ _ @h_obj _ @h_map, forget_comp := by apply faithful.div_comp } instance has_forget_to_Type (C : Type v) [category C] [concrete_category C] : has_forget₂ C (Type u) := { forget₂ := forget C, forget_comp := functor.comp_id _ } end category_theory
5484ebe97a56d03fb63f45fde50fafc11df37522
b815abf92ce063fe0d1fabf5b42da483552aa3e8
/library/init/algebra/ordered_group.lean
62f4650570c4c824dde8faa33dc31c9d40a9e172
[ "Apache-2.0" ]
permissive
yodalee/lean
a368d842df12c63e9f79414ed7bbee805b9001ef
317989bf9ef6ae1dec7488c2363dbfcdc16e0756
refs/heads/master
1,610,551,176,860
1,481,430,138,000
1,481,646,441,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,599
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura -/ prelude import init.algebra.order init.algebra.group /- Make sure instances defined in this file have lower priority than the ones defined for concrete structures -/ set_option default_priority 100 universe variable u class ordered_mul_cancel_comm_monoid (α : Type u) extends comm_monoid α, left_cancel_semigroup α, right_cancel_semigroup α, order_pair α := (mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b) (le_of_mul_le_mul_left : ∀ a b c : α, a * b ≤ a * c → b ≤ c) (mul_lt_mul_left : ∀ a b : α, a < b → ∀ c : α, c * a < c * b) (lt_of_mul_lt_mul_left : ∀ a b c : α, a * b < a * c → b < c) @[class] def ordered_cancel_comm_monoid : Type u → Type (max 1 u) := ordered_mul_cancel_comm_monoid instance add_comm_monoid_of_ordered_cancel_comm_monoid (α : Type u) [s : ordered_cancel_comm_monoid α] : add_comm_monoid α := @ordered_mul_cancel_comm_monoid.to_comm_monoid α s instance add_left_cancel_semigroup_of_ordered_cancel_comm_monoid (α : Type u) [s : ordered_cancel_comm_monoid α] : add_left_cancel_semigroup α := @ordered_mul_cancel_comm_monoid.to_left_cancel_semigroup α s instance add_right_cancel_semigroup_of_ordered_cancel_comm_monoid (α : Type u) [s : ordered_cancel_comm_monoid α] : add_right_cancel_semigroup α := @ordered_mul_cancel_comm_monoid.to_right_cancel_semigroup α s instance order_pair_of_ordered_cancel_comm_monoid (α : Type u) [s : ordered_cancel_comm_monoid α] : order_pair α := @ordered_mul_cancel_comm_monoid.to_order_pair α s section ordered_cancel_comm_monoid variable {α : Type u} variable [s : ordered_cancel_comm_monoid α] lemma add_le_add_left {a b : α} (h : a ≤ b) (c : α) : c + a ≤ c + b := @ordered_mul_cancel_comm_monoid.mul_le_mul_left α s a b h c lemma le_of_add_le_add_left {a b c : α} (h : a + b ≤ a + c) : b ≤ c := @ordered_mul_cancel_comm_monoid.le_of_mul_le_mul_left α s a b c h lemma add_lt_add_left {a b : α} (h : a < b) (c : α) : c + a < c + b := @ordered_mul_cancel_comm_monoid.mul_lt_mul_left α s a b h c lemma lt_of_add_lt_add_left {a b c : α} (h : a + b < a + c) : b < c := @ordered_mul_cancel_comm_monoid.lt_of_mul_lt_mul_left α s a b c h end ordered_cancel_comm_monoid section ordered_cancel_comm_monoid variable {α : Type u} variable [ordered_cancel_comm_monoid α] lemma add_le_add_right {a b : α} (h : a ≤ b) (c : α) : a + c ≤ b + c := add_comm c a ▸ add_comm c b ▸ add_le_add_left h c theorem add_lt_add_right {a b : α} (h : a < b) (c : α) : a + c < b + c := begin rw [add_comm a c, add_comm b c], exact (add_lt_add_left h c) end lemma add_le_add {a b c d : α} (h₁ : a ≤ b) (h₂ : c ≤ d) : a + c ≤ b + d := le_trans (add_le_add_right h₁ c) (add_le_add_left h₂ b) lemma le_add_of_nonneg_right {a b : α} (h : b ≥ 0) : a ≤ a + b := have a + b ≥ a + 0, from add_le_add_left h a, by rwa add_zero at this lemma le_add_of_nonneg_left {a b : α} (h : b ≥ 0) : a ≤ b + a := have 0 + a ≤ b + a, from add_le_add_right h a, by rwa zero_add at this lemma add_lt_add {a b c d : α} (h₁ : a < b) (h₂ : c < d) : a + c < b + d := lt_trans (add_lt_add_right h₁ c) (add_lt_add_left h₂ b) lemma add_lt_add_of_le_of_lt {a b c d : α} (h₁ : a ≤ b) (h₂ : c < d) : a + c < b + d := lt_of_le_of_lt (add_le_add_right h₁ c) (add_lt_add_left h₂ b) lemma add_lt_add_of_lt_of_le {a b c d : α} (h₁ : a < b) (h₂ : c ≤ d) : a + c < b + d := lt_of_lt_of_le (add_lt_add_right h₁ c) (add_le_add_left h₂ b) lemma lt_add_of_pos_right (a : α) {b : α} (h : b > 0) : a < a + b := have a + 0 < a + b, from add_lt_add_left h a, by rwa [add_zero] at this lemma lt_add_of_pos_left (a : α) {b : α} (h : b > 0) : a < b + a := have 0 + a < b + a, from add_lt_add_right h a, by rwa [zero_add] at this lemma le_of_add_le_add_right {a b c : α} (h : a + b ≤ c + b) : a ≤ c := le_of_add_le_add_left (show b + a ≤ b + c, begin rw [add_comm b a, add_comm b c], assumption end) lemma lt_of_add_lt_add_right {a b c : α} (h : a + b < c + b) : a < c := lt_of_add_lt_add_left (show b + a < b + c, begin rw [add_comm b a, add_comm b c], assumption end) end ordered_cancel_comm_monoid class ordered_mul_comm_group (α : Type u) extends comm_group α, order_pair α := (mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b) (mul_lt_mul_left : ∀ a b : α, a < b → ∀ c : α, c * a < c * b) @[class] def ordered_comm_group : Type u → Type (max 1 u) := ordered_mul_comm_group instance add_comm_group_of_ordered_comm_group (α : Type u) [s : ordered_comm_group α] : add_comm_group α := @ordered_mul_comm_group.to_comm_group α s section ordered_mul_comm_group variable {α : Type u} variable [ordered_mul_comm_group α] lemma ordered_mul_comm_group.le_of_mul_le_mul_left {a b c : α} (h : a * b ≤ a * c) : b ≤ c := have a⁻¹ * (a * b) ≤ a⁻¹ * (a * c), from ordered_mul_comm_group.mul_le_mul_left _ _ h _, begin simp [inv_mul_cancel_left] at this, assumption end lemma ordered_mul_comm_group.lt_of_mul_lt_mul_left {a b c : α} (h : a * b < a * c) : b < c := have a⁻¹ * (a * b) < a⁻¹ * (a * c), from ordered_mul_comm_group.mul_lt_mul_left _ _ h _, begin simp [inv_mul_cancel_left] at this, assumption end end ordered_mul_comm_group instance ordered_mul_comm_group.to_ordered_mul_cancel_comm_monoid (α : Type u) [s : ordered_mul_comm_group α] : ordered_mul_cancel_comm_monoid α := { s with mul_left_cancel := @mul_left_cancel α _, mul_right_cancel := @mul_right_cancel α _, le_of_mul_le_mul_left := @ordered_mul_comm_group.le_of_mul_le_mul_left α _, lt_of_mul_lt_mul_left := @ordered_mul_comm_group.lt_of_mul_lt_mul_left α _ } instance ordered_comm_group.to_ordered_cancel_comm_monoid (α : Type u) [s : ordered_comm_group α] : ordered_cancel_comm_monoid α := @ordered_mul_comm_group.to_ordered_mul_cancel_comm_monoid α s section ordered_comm_group variables {α : Type u} [ordered_comm_group α] theorem neg_le_neg {a b : α} (h : a ≤ b) : -b ≤ -a := have 0 ≤ -a + b, from add_left_neg a ▸ add_le_add_left h (-a), have 0 + -b ≤ -a + b + -b, from add_le_add_right this (-b), by rwa [add_neg_cancel_right, zero_add] at this lemma le_of_neg_le_neg {a b : α} (h : -b ≤ -a) : a ≤ b := suffices -(-a) ≤ -(-b), from begin simp [neg_neg] at this, assumption end, neg_le_neg h lemma nonneg_of_neg_nonpos {a : α} (h : -a ≤ 0) : 0 ≤ a := have -a ≤ -0, by rwa neg_zero, le_of_neg_le_neg this lemma neg_nonpos_of_nonneg {a : α} (h : 0 ≤ a) : -a ≤ 0 := have -a ≤ -0, from neg_le_neg h, by rwa neg_zero at this lemma nonpos_of_neg_nonneg {a : α} (h : 0 ≤ -a) : a ≤ 0 := have -0 ≤ -a, by rwa neg_zero, le_of_neg_le_neg this lemma neg_nonneg_of_nonpos {a : α} (h : a ≤ 0) : 0 ≤ -a := have -0 ≤ -a, from neg_le_neg h, by rwa neg_zero at this lemma neg_lt_neg {a b : α} (h : a < b) : -b < -a := have 0 < -a + b, from add_left_neg a ▸ add_lt_add_left h (-a), have 0 + -b < -a + b + -b, from add_lt_add_right this (-b), by rwa [add_neg_cancel_right, zero_add] at this lemma lt_of_neg_lt_neg {a b : α} (h : -b < -a) : a < b := neg_neg a ▸ neg_neg b ▸ neg_lt_neg h lemma pos_of_neg_neg {a : α} (h : -a < 0) : 0 < a := have -a < -0, by rwa neg_zero, lt_of_neg_lt_neg this lemma neg_neg_of_pos {a : α} (h : 0 < a) : -a < 0 := have -a < -0, from neg_lt_neg h, by rwa neg_zero at this lemma neg_of_neg_pos {a : α} (h : 0 < -a) : a < 0 := have -0 < -a, by rwa neg_zero, lt_of_neg_lt_neg this lemma neg_pos_of_neg {a : α} (h : a < 0) : 0 < -a := have -0 < -a, from neg_lt_neg h, by rwa neg_zero at this lemma le_neg_of_le_neg {a b : α} (h : a ≤ -b) : b ≤ -a := begin note h := neg_le_neg h, rwa neg_neg at h end lemma neg_le_of_neg_le {a b : α} (h : -a ≤ b) : -b ≤ a := begin note h := neg_le_neg h, rwa neg_neg at h end lemma lt_neg_of_lt_neg {a b : α} (h : a < -b) : b < -a := begin note h := neg_lt_neg h, rwa neg_neg at h end lemma neg_lt_of_neg_lt {a b : α} (h : -a < b) : -b < a := begin note h := neg_lt_neg h, rwa neg_neg at h end lemma sub_nonneg_of_le {a b : α} (h : b ≤ a) : 0 ≤ a - b := begin note h := add_le_add_right h (-b), rwa add_right_neg at h end lemma le_of_sub_nonneg {a b : α} (h : 0 ≤ a - b) : b ≤ a := begin note h := add_le_add_right h b, rwa [sub_add_cancel, zero_add] at h end lemma sub_nonpos_of_le {a b : α} (h : a ≤ b) : a - b ≤ 0 := begin note h := add_le_add_right h (-b), rwa add_right_neg at h end lemma le_of_sub_nonpos {a b : α} (h : a - b ≤ 0) : a ≤ b := begin note h := add_le_add_right h b, rwa [sub_add_cancel, zero_add] at h end lemma sub_pos_of_lt {a b : α} (h : b < a) : 0 < a - b := begin note h := add_lt_add_right h (-b), rwa add_right_neg at h end lemma lt_of_sub_pos {a b : α} (h : 0 < a - b) : b < a := begin note h := add_lt_add_right h b, rwa [sub_add_cancel, zero_add] at h end lemma sub_neg_of_lt {a b : α} (h : a < b) : a - b < 0 := begin note h := add_lt_add_right h (-b), rwa add_right_neg at h end lemma lt_of_sub_neg {a b : α} (h : a - b < 0) : a < b := begin note h := add_lt_add_right h b, rwa [sub_add_cancel, zero_add] at h end lemma add_le_of_le_neg_add {a b c : α} (h : b ≤ -a + c) : a + b ≤ c := begin note h := add_le_add_left h a, rwa add_neg_cancel_left at h end lemma le_neg_add_of_add_le {a b c : α} (h : a + b ≤ c) : b ≤ -a + c := begin note h := add_le_add_left h (-a), rwa neg_add_cancel_left at h end lemma add_le_of_le_sub_left {a b c : α} (h : b ≤ c - a) : a + b ≤ c := begin note h := add_le_add_left h a, rwa [-add_sub_assoc, add_comm a c, add_sub_cancel] at h end lemma le_sub_left_of_add_le {a b c : α} (h : a + b ≤ c) : b ≤ c - a := begin note h := add_le_add_right h (-a), rwa [add_comm a b, add_neg_cancel_right] at h end lemma add_le_of_le_sub_right {a b c : α} (h : a ≤ c - b) : a + b ≤ c := begin note h := add_le_add_right h b, rwa sub_add_cancel at h end lemma le_sub_right_of_add_le {a b c : α} (h : a + b ≤ c) : a ≤ c - b := begin note h := add_le_add_right h (-b), rwa add_neg_cancel_right at h end lemma le_add_of_neg_add_le {a b c : α} (h : -b + a ≤ c) : a ≤ b + c := begin note h := add_le_add_left h b, rwa add_neg_cancel_left at h end lemma neg_add_le_of_le_add {a b c : α} (h : a ≤ b + c) : -b + a ≤ c := begin note h := add_le_add_left h (-b), rwa neg_add_cancel_left at h end lemma le_add_of_sub_left_le {a b c : α} (h : a - b ≤ c) : a ≤ b + c := begin note h := add_le_add_right h b, rwa [sub_add_cancel, add_comm] at h end lemma sub_left_le_of_le_add {a b c : α} (h : a ≤ b + c) : a - b ≤ c := begin note h := add_le_add_right h (-b), rwa [add_comm b c, add_neg_cancel_right] at h end lemma le_add_of_sub_right_le {a b c : α} (h : a - c ≤ b) : a ≤ b + c := begin note h := add_le_add_right h c, rwa sub_add_cancel at h end lemma sub_right_le_of_le_add {a b c : α} (h : a ≤ b + c) : a - c ≤ b := begin note h := add_le_add_right h (-c), rwa add_neg_cancel_right at h end lemma le_add_of_neg_add_le_left {a b c : α} (h : -b + a ≤ c) : a ≤ b + c := begin rw add_comm at h, exact le_add_of_sub_left_le h end lemma neg_add_le_left_of_le_add {a b c : α} (h : a ≤ b + c) : -b + a ≤ c := begin rw add_comm, exact sub_left_le_of_le_add h end lemma le_add_of_neg_add_le_right {a b c : α} (h : -c + a ≤ b) : a ≤ b + c := begin rw add_comm at h, exact le_add_of_sub_right_le h end lemma neg_add_le_right_of_le_add {a b c : α} (h : a ≤ b + c) : -c + a ≤ b := begin rw add_comm at h, apply neg_add_le_left_of_le_add h end lemma le_add_of_neg_le_sub_left {a b c : α} (h : -a ≤ b - c) : c ≤ a + b := le_add_of_neg_add_le_left (add_le_of_le_sub_right h) lemma neg_le_sub_left_of_le_add {a b c : α} (h : c ≤ a + b) : -a ≤ b - c := begin note h := le_neg_add_of_add_le (sub_left_le_of_le_add h), rwa add_comm at h end lemma le_add_of_neg_le_sub_right {a b c : α} (h : -b ≤ a - c) : c ≤ a + b := le_add_of_sub_right_le (add_le_of_le_sub_left h) lemma neg_le_sub_right_of_le_add {a b c : α} (h : c ≤ a + b) : -b ≤ a - c := le_sub_left_of_add_le (sub_right_le_of_le_add h) lemma sub_le_of_sub_le {a b c : α} (h : a - b ≤ c) : a - c ≤ b := sub_left_le_of_le_add (le_add_of_sub_right_le h) lemma sub_le_sub_left {a b : α} (h : a ≤ b) (c : α) : c - b ≤ c - a := add_le_add_left (neg_le_neg h) c lemma sub_le_sub_right {a b : α} (h : a ≤ b) (c : α) : a - c ≤ b - c := add_le_add_right h (-c) lemma sub_le_sub {a b c d : α} (hab : a ≤ b) (hcd : c ≤ d) : a - d ≤ b - c := add_le_add hab (neg_le_neg hcd) lemma add_lt_of_lt_neg_add {a b c : α} (h : b < -a + c) : a + b < c := begin note h := add_lt_add_left h a, rwa add_neg_cancel_left at h end lemma lt_neg_add_of_add_lt {a b c : α} (h : a + b < c) : b < -a + c := begin note h := add_lt_add_left h (-a), rwa neg_add_cancel_left at h end lemma add_lt_of_lt_sub_left {a b c : α} (h : b < c - a) : a + b < c := begin note h := add_lt_add_left h a, rwa [-add_sub_assoc, add_comm a c, add_sub_cancel] at h end lemma lt_sub_left_of_add_lt {a b c : α} (h : a + b < c) : b < c - a := begin note h := add_lt_add_right h (-a), rwa [add_comm a b, add_neg_cancel_right] at h end lemma add_lt_of_lt_sub_right {a b c : α} (h : a < c - b) : a + b < c := begin note h := add_lt_add_right h b, rwa sub_add_cancel at h end lemma lt_sub_right_of_add_lt {a b c : α} (h : a + b < c) : a < c - b := begin note h := add_lt_add_right h (-b), rwa add_neg_cancel_right at h end lemma lt_add_of_neg_add_lt {a b c : α} (h : -b + a < c) : a < b + c := begin note h := add_lt_add_left h b, rwa add_neg_cancel_left at h end lemma neg_add_lt_of_lt_add {a b c : α} (h : a < b + c) : -b + a < c := begin note h := add_lt_add_left h (-b), rwa neg_add_cancel_left at h end lemma lt_add_of_sub_left_lt {a b c : α} (h : a - b < c) : a < b + c := begin note h := add_lt_add_right h b, rwa [sub_add_cancel, add_comm] at h end lemma sub_left_lt_of_lt_add {a b c : α} (h : a < b + c) : a - b < c := begin note h := add_lt_add_right h (-b), rwa [add_comm b c, add_neg_cancel_right] at h end lemma lt_add_of_sub_right_lt {a b c : α} (h : a - c < b) : a < b + c := begin note h := add_lt_add_right h c, rwa sub_add_cancel at h end lemma sub_right_lt_of_lt_add {a b c : α} (h : a < b + c) : a - c < b := begin note h := add_lt_add_right h (-c), rwa add_neg_cancel_right at h end lemma lt_add_of_neg_add_lt_left {a b c : α} (h : -b + a < c) : a < b + c := begin rw add_comm at h, exact lt_add_of_sub_left_lt h end lemma neg_add_lt_left_of_lt_add {a b c : α} (h : a < b + c) : -b + a < c := begin rw add_comm, exact sub_left_lt_of_lt_add h end lemma lt_add_of_neg_add_lt_right {a b c : α} (h : -c + a < b) : a < b + c := begin rw add_comm at h, exact lt_add_of_sub_right_lt h end lemma neg_add_lt_right_of_lt_add {a b c : α} (h : a < b + c) : -c + a < b := begin rw add_comm at h, apply neg_add_lt_left_of_lt_add h end lemma lt_add_of_neg_lt_sub_left {a b c : α} (h : -a < b - c) : c < a + b := lt_add_of_neg_add_lt_left (add_lt_of_lt_sub_right h) lemma neg_lt_sub_left_of_lt_add {a b c : α} (h : c < a + b) : -a < b - c := begin note h := lt_neg_add_of_add_lt (sub_left_lt_of_lt_add h), rwa add_comm at h end lemma lt_add_of_neg_lt_sub_right {a b c : α} (h : -b < a - c) : c < a + b := lt_add_of_sub_right_lt (add_lt_of_lt_sub_left h) lemma neg_lt_sub_right_of_lt_add {a b c : α} (h : c < a + b) : -b < a - c := lt_sub_left_of_add_lt (sub_right_lt_of_lt_add h) lemma sub_lt_of_sub_lt {a b c : α} (h : a - b < c) : a - c < b := sub_left_lt_of_lt_add (lt_add_of_sub_right_lt h) lemma sub_lt_sub_left {a b : α} (h : a < b) (c : α) : c - b < c - a := add_lt_add_left (neg_lt_neg h) c lemma sub_lt_sub_right {a b : α} (h : a < b) (c : α) : a - c < b - c := add_lt_add_right h (-c) lemma sub_lt_sub {a b c d : α} (hab : a < b) (hcd : c < d) : a - d < b - c := add_lt_add hab (neg_lt_neg hcd) lemma sub_lt_sub_of_le_of_lt {a b c d : α} (hab : a ≤ b) (hcd : c < d) : a - d < b - c := add_lt_add_of_le_of_lt hab (neg_lt_neg hcd) lemma sub_lt_sub_of_lt_of_le {a b c d : α} (hab : a < b) (hcd : c ≤ d) : a - d < b - c := add_lt_add_of_lt_of_le hab (neg_le_neg hcd) lemma sub_le_self (a : α) {b : α} (h : b ≥ 0) : a - b ≤ a := calc a - b = a + -b : rfl ... ≤ a + 0 : add_le_add_left (neg_nonpos_of_nonneg h) _ ... = a : by rw add_zero lemma sub_lt_self (a : α) {b : α} (h : b > 0) : a - b < a := calc a - b = a + -b : rfl ... < a + 0 : add_lt_add_left (neg_neg_of_pos h) _ ... = a : by rw add_zero lemma add_le_add_three {a b c d e f : α} (h₁ : a ≤ d) (h₂ : b ≤ e) (h₃ : c ≤ f) : a + b + c ≤ d + e + f := begin apply le_trans, apply add_le_add, apply add_le_add, repeat {assumption}, apply le_refl end end ordered_comm_group class decidable_linear_ordered_mul_comm_group (α : Type u) extends comm_group α, decidable_linear_order α := (mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b) (mul_lt_mul_left : ∀ a b : α, a < b → ∀ c : α, c * a < c * b) @[class] def decidable_linear_ordered_comm_group : Type u → Type (max 1 u) := decidable_linear_ordered_mul_comm_group instance add_comm_group_of_decidable_linear_ordered_comm_group (α : Type u) [s : decidable_linear_ordered_comm_group α] : add_comm_group α := @decidable_linear_ordered_mul_comm_group.to_comm_group α s instance decidable_linear_order_of_decidable_linear_ordered_comm_group (α : Type u) [s : decidable_linear_ordered_comm_group α] : decidable_linear_order α := @decidable_linear_ordered_mul_comm_group.to_decidable_linear_order α s instance decidable_linear_ordered_mul_comm_group.to_ordered_mul_comm_group (α : Type u) [s : decidable_linear_ordered_mul_comm_group α] : ordered_mul_comm_group α := {s with le_of_lt := @le_of_lt α _, lt_of_le_of_lt := @lt_of_le_of_lt α _, lt_of_lt_of_le := @lt_of_lt_of_le α _ } instance decidable_linear_ordered_comm_group.to_ordered_comm_group (α : Type u) [s : decidable_linear_ordered_comm_group α] : ordered_comm_group α := @decidable_linear_ordered_mul_comm_group.to_ordered_mul_comm_group α s
ac67e0514fda4214af19e04256878935a844f1ac
7cef822f3b952965621309e88eadf618da0c8ae9
/src/category_theory/functor_category.lean
266f65ddc07e648e739c036ccb9b352f41f57813
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
4,082
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tim Baumann, Stephen Morgan, Scott Morrison, Floris van Doorn -/ import category_theory.natural_transformation namespace category_theory universes v₁ v₂ v₃ u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation open nat_trans category category_theory.functor variables (C : Type u₁) [𝒞 : category.{v₁} C] (D : Type u₂) [𝒟 : category.{v₂} D] include 𝒞 𝒟 /-- `functor.category C D` gives the category structure on functors and natural transformations between categories `C` and `D`. Notice that if `C` and `D` are both small categories at the same universe level, this is another small category at that level. However if `C` and `D` are both large categories at the same universe level, this is a small category at the next higher level. -/ instance functor.category : category.{(max u₁ v₂)} (C ⥤ D) := { hom := λ F G, nat_trans F G, id := λ F, nat_trans.id F, comp := λ _ _ _ α β, vcomp α β } variables {C D} {E : Type u₃} [ℰ : category.{v₃} E] variables {F G H I : C ⥤ D} namespace nat_trans @[simp] lemma vcomp_eq_comp (α : F ⟶ G) (β : G ⟶ H) : vcomp α β = α ≫ β := rfl lemma congr_app {α β : F ⟶ G} (h : α = β) (X : C) : α.app X = β.app X := by rw h @[simp] lemma id_app (F : C ⥤ D) (X : C) : (𝟙 F : F ⟶ F).app X = 𝟙 (F.obj X) := rfl @[simp] lemma comp_app {F G H : C ⥤ D} (α : F ⟶ G) (β : G ⟶ H) (X : C) : (α ≫ β).app X = α.app X ≫ β.app X := rfl include ℰ lemma app_naturality {F G : C ⥤ (D ⥤ E)} (T : F ⟶ G) (X : C) {Y Z : D} (f : Y ⟶ Z) : ((F.obj X).map f) ≫ ((T.app X).app Z) = ((T.app X).app Y) ≫ ((G.obj X).map f) := (T.app X).naturality f lemma naturality_app {F G : C ⥤ (D ⥤ E)} (T : F ⟶ G) (Z : D) {X Y : C} (f : X ⟶ Y) : ((F.map f).app Z) ≫ ((T.app Y).app Z) = ((T.app X).app Z) ≫ ((G.map f).app Z) := congr_fun (congr_arg app (T.naturality f)) Z /-- `hcomp α β` is the horizontal composition of natural transformations. -/ def hcomp {H I : D ⥤ E} (α : F ⟶ G) (β : H ⟶ I) : (F ⋙ H) ⟶ (G ⋙ I) := { app := λ X : C, (β.app (F.obj X)) ≫ (I.map (α.app X)), naturality' := λ X Y f, begin rw [functor.comp_map, functor.comp_map, ←assoc, naturality, assoc, ←map_comp I, naturality, map_comp, assoc] end } infix ` ◫ `:80 := hcomp @[simp] lemma hcomp_app {H I : D ⥤ E} (α : F ⟶ G) (β : H ⟶ I) (X : C) : (α ◫ β).app X = (β.app (F.obj X)) ≫ (I.map (α.app X)) := rfl -- Note that we don't yet prove a `hcomp_assoc` lemma here: even stating it is painful, because we -- need to use associativity of functor composition. (It's true without the explicit associator, -- because functor composition is definitionally associative, but relying on the definitional equality -- causes bad problems with elaboration later.) lemma exchange {I J K : D ⥤ E} (α : F ⟶ G) (β : G ⟶ H) (γ : I ⟶ J) (δ : J ⟶ K) : (α ≫ β) ◫ (γ ≫ δ) = (α ◫ γ) ≫ (β ◫ δ) := by { ext, dsimp, rw [assoc, assoc, map_comp, ←assoc _ (δ.app _), ← naturality, assoc] } end nat_trans open nat_trans namespace functor include ℰ protected def flip (F : C ⥤ (D ⥤ E)) : D ⥤ (C ⥤ E) := { obj := λ k, { obj := λ j, (F.obj j).obj k, map := λ j j' f, (F.map f).app k, map_id' := λ X, begin rw category_theory.functor.map_id, refl end, map_comp' := λ X Y Z f g, by rw [map_comp, ←comp_app] }, map := λ c c' f, { app := λ j, (F.obj j).map f } }. @[simp] lemma flip_obj_obj (F : C ⥤ (D ⥤ E)) (c) (d) : (F.flip.obj d).obj c = (F.obj c).obj d := rfl @[simp] lemma flip_obj_map (F : C ⥤ (D ⥤ E)) {c c' : C} (f : c ⟶ c') (d : D) : (F.flip.obj d).map f = (F.map f).app d := rfl @[simp] lemma flip_map_app (F : C ⥤ (D ⥤ E)) {d d' : D} (f : d ⟶ d') (c : C) : (F.flip.map f).app c = (F.obj c).map f := rfl end functor end category_theory
ba8a873b817f436b9ac1eed9006925d1eaf26766
618003631150032a5676f229d13a079ac875ff77
/src/linear_algebra/finsupp_vector_space.lean
32489baacd304e3bb16858c069cef12036895bd9
[ "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
6,364
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl Linear structures on function with finite support `ι →₀ β`. -/ import data.mv_polynomial import linear_algebra.dimension noncomputable theory local attribute [instance, priority 100] classical.prop_decidable open set linear_map submodule namespace finsupp section module variables {R : Type*} {M : Type*} {ι : Type*} variables [ring R] [add_comm_group M] [module R M] lemma linear_independent_single {φ : ι → Type*} {f : Π ι, φ ι → M} (hf : ∀i, linear_independent R (f i)) : linear_independent R (λ ix : Σ i, φ i, single ix.1 (f ix.1 ix.2)) := begin apply @linear_independent_Union_finite R _ _ _ _ ι φ (λ i x, single i (f i x)), { assume i, have h_disjoint : disjoint (span R (range (f i))) (ker (lsingle i)), { rw ker_lsingle, exact disjoint_bot_right }, apply linear_independent.image (hf i) h_disjoint }, { intros i t ht hit, refine (disjoint_lsingle_lsingle {i} t (disjoint_singleton_left.2 hit)).mono _ _, { rw span_le, simp only [supr_singleton], rw range_coe, apply range_comp_subset_range }, { refine supr_le_supr (λ i, supr_le_supr _), intros hi, rw span_le, rw range_coe, apply range_comp_subset_range } } end end module section vector_space variables {K : Type*} {V : Type*} {ι : Type*} variables [field K] [add_comm_group V] [vector_space K V] open linear_map submodule lemma is_basis_single {φ : ι → Type*} (f : Π ι, φ ι → V) (hf : ∀i, is_basis K (f i)) : is_basis K (λ ix : Σ i, φ i, single ix.1 (f ix.1 ix.2)) := begin split, { apply linear_independent_single, exact λ i, (hf i).1 }, { rw [range_sigma_eq_Union_range, span_Union], simp only [image_univ.symm, λ i, image_comp (single i) (f i), span_single_image], simp only [image_univ, (hf _).2, map_top, supr_lsingle_range] } end end vector_space section dim universes u v variables {K : Type u} {V : Type v} {ι : Type v} variables [field K] [add_comm_group V] [vector_space K V] lemma dim_eq : vector_space.dim K (ι →₀ V) = cardinal.mk ι * vector_space.dim K V := begin rcases exists_is_basis K V with ⟨bs, hbs⟩, rw [← cardinal.lift_inj, cardinal.lift_mul, ← hbs.mk_eq_dim, ← (is_basis_single _ (λa:ι, hbs)).mk_eq_dim, ← cardinal.sum_mk, ← cardinal.lift_mul, cardinal.lift_inj], { simp only [cardinal.mk_image_eq (injective_single.{u u} _), cardinal.sum_const] } end end dim end finsupp section vector_space /- We use `universe variables` instead of `universes` here because universes introduced by the `universes` keyword do not get replaced by metavariables once a lemma has been proven. So if you prove a lemma using universe `u`, you can only apply it to universe `u` in other lemmas of the same section. -/ universe variables u v w variables {K : Type u} {V V₁ V₂ : Type v} {V' : Type w} variables [field K] variables [add_comm_group V] [vector_space K V] variables [add_comm_group V₁] [vector_space K V₁] variables [add_comm_group V₂] [vector_space K V₂] variables [add_comm_group V'] [vector_space K V'] open vector_space lemma equiv_of_dim_eq_lift_dim (h : cardinal.lift.{v w} (dim K V) = cardinal.lift.{w v} (dim K V')) : nonempty (V ≃ₗ[K] V') := begin haveI := classical.dec_eq V, haveI := classical.dec_eq V', rcases exists_is_basis K V with ⟨m, hm⟩, rcases exists_is_basis K V' with ⟨m', hm'⟩, rw [←cardinal.lift_inj.1 hm.mk_eq_dim, ←cardinal.lift_inj.1 hm'.mk_eq_dim] at h, rcases quotient.exact h with ⟨e⟩, let e := (equiv.ulift.symm.trans e).trans equiv.ulift, exact ⟨((module_equiv_finsupp hm).trans (finsupp.dom_lcongr e)).trans (module_equiv_finsupp hm').symm⟩, end def equiv_of_dim_eq_dim (h : dim K V₁ = dim K V₂) : V₁ ≃ₗ[K] V₂ := begin classical, exact classical.choice (equiv_of_dim_eq_lift_dim (cardinal.lift_inj.2 h)) end def fin_dim_vectorspace_equiv (n : ℕ) (hn : (dim K V) = n) : V ≃ₗ[K] (fin n → K) := begin have : cardinal.lift.{v u} (n : cardinal.{v}) = cardinal.lift.{u v} (n : cardinal.{u}), by simp, have hn := cardinal.lift_inj.{v u}.2 hn, rw this at hn, rw ←@dim_fin_fun K _ n at hn, exact classical.choice (equiv_of_dim_eq_lift_dim hn), end lemma eq_bot_iff_dim_eq_zero (p : submodule K V) (h : dim K p = 0) : p = ⊥ := begin have : dim K p = dim K (⊥ : submodule K V) := by rwa [dim_bot], let e := equiv_of_dim_eq_dim this, exact e.eq_bot_of_equiv _ end lemma injective_of_surjective (f : V₁ →ₗ[K] V₂) (hV₁ : dim K V₁ < cardinal.omega) (heq : dim K V₂ = dim K V₁) (hf : f.range = ⊤) : f.ker = ⊥ := have hk : dim K f.ker < cardinal.omega := lt_of_le_of_lt (dim_submodule_le _) hV₁, begin rcases cardinal.lt_omega.1 hV₁ with ⟨d₁, eq₁⟩, rcases cardinal.lt_omega.1 hk with ⟨d₂, eq₂⟩, have : 0 = d₂, { have := dim_eq_surjective f (linear_map.range_eq_top.1 hf), rw [heq, eq₁, eq₂, ← nat.cast_add, cardinal.nat_cast_inj] at this, exact nat.add_left_cancel this }, refine eq_bot_iff_dim_eq_zero _ _, rw [eq₂, ← this, nat.cast_zero] end end vector_space section vector_space universes u open vector_space variables {K V : Type u} [field K] [add_comm_group V] [vector_space K V] set_option pp.universes false lemma cardinal_mk_eq_cardinal_mk_field_pow_dim (h : dim K V < cardinal.omega) : cardinal.mk V = cardinal.mk K ^ dim K V := begin rcases exists_is_basis K V with ⟨s, hs⟩, have : nonempty (fintype s), { rwa [← cardinal.lt_omega_iff_fintype, cardinal.lift_inj.1 hs.mk_eq_dim] }, cases this with hsf, letI := hsf, calc cardinal.mk V = cardinal.mk (s →₀ K) : quotient.sound ⟨(module_equiv_finsupp hs).to_equiv⟩ ... = cardinal.mk (s → K) : quotient.sound ⟨finsupp.equiv_fun_on_fintype⟩ ... = _ : by rw [← cardinal.lift_inj.1 hs.mk_eq_dim, cardinal.power_def] end lemma cardinal_lt_omega_of_dim_lt_omega [fintype K] (h : dim K V < cardinal.omega) : cardinal.mk V < cardinal.omega := begin rw [cardinal_mk_eq_cardinal_mk_field_pow_dim h], exact cardinal.power_lt_omega (cardinal.lt_omega_iff_fintype.2 ⟨infer_instance⟩) h end end vector_space
9a5fd0f715fc2738ac19f94ce0ab188b7d44ec46
7da5ceac20aaab989eeb795a4be9639982e7b35a
/src/analysis/manifolds/basic.lean
3fd811d04d717ab6f9f31b99e5413771eb91a18f
[ "MIT" ]
permissive
formalabstracts/formalabstracts
46c2f1b3a172e62ca6ffeb46fbbdf1705718af49
b0173da1af45421239d44492eeecd54bf65ee0f6
refs/heads/master
1,606,896,370,374
1,572,988,776,000
1,572,988,776,000
96,763,004
165
28
null
1,555,709,319,000
1,499,680,948,000
Lean
UTF-8
Lean
false
false
2,958
lean
import topology.instances.real data.pfun2 order.lattice ...basic open topological_space set noncomputable theory universes u v w variables {α : Type u} {β : Type v} {γ : Type w} {n : ℕ} /- continuity of a partial function -/ namespace pfun def is_continuous [topological_space α] [topological_space β] (f : α →. β) := continuous (f.as_subtype) def is_continuous_id [topological_space α] : is_continuous (@pfun.id α) := omitted end pfun open pfun -- instance [t : topological_space α] : topological_space (vector α n) := -- ⨆(l : fin n), induced (λ x, vector.nth x l) t structure Top := (carrier : Type u) (struct : topological_space carrier) namespace Top instance : has_coe_to_sort Top := ⟨Type*, Top.carrier⟩ attribute [instance] Top.struct def restrict (X : Top) (s : set X) : Top := ⟨subtype s, by apply_instance⟩ end Top structure euclidean_space := (carrier : Type u) (dim : ℕ) (equiv : carrier ≃ vector ℝ dim) namespace euclidean_space instance : has_coe_to_sort euclidean_space := ⟨Type*, euclidean_space.carrier⟩ instance to_topological_space (E : euclidean_space) : topological_space E := induced (@euclidean_space.equiv E) (by apply_instance) def to_Top (E : euclidean_space) : Top := ⟨E, by apply_instance⟩ instance : has_coe euclidean_space Top := ⟨to_Top⟩ def real_euclidean_space (n : ℕ) : euclidean_space := ⟨ℝ, 1, vector.vector_one_equiv.symm⟩ def standard_euclidean_space (n : ℕ) : euclidean_space := ⟨vector ℝ n, n, equiv.refl _⟩ notation `ℝ^` := standard_euclidean_space end euclidean_space variables {k k' : ℕ∞} {E : euclidean_space.{u}} {E' : euclidean_space.{v}} def is_smooth_at (k : ℕ∞) (f : E →. E') (x : E) : Prop := sorry def is_smooth (k : ℕ∞) (f : E →. E') : Prop := sorry --∀x, is_smooth_at k f x /- the empty map is smooth -/ lemma is_smooth_empty (k : ℕ∞) (E E' : euclidean_space) : is_smooth k (pfun.empty E E') := omitted /- every smooth map is continuous -/ lemma is_continuous_of_is_smooth {f : E →. E'} (hf : is_smooth k f) : f.is_continuous := omitted lemma is_smooth_of_le {f : E →. E'} (hf : is_smooth k f) (hk : k' ≤ k) : is_smooth k' f := omitted /- a partial homeomorphism -/ structure phomeo (X Y : Top) extends X ≃. Y := (continuous_to_fun : to_fun.is_continuous) (continuous_inv_fun : inv_fun.is_continuous) infixr ` ≃ₜ. `:25 := phomeo namespace phomeo variables {X : Top} {Y : Top} {Z : Top} def restrict_phomeo (p : set X) : X.restrict p ≃ₜ. X := ⟨pequiv.subtype_pequiv p, omitted, omitted⟩ protected def rfl : X ≃ₜ. X := ⟨pequiv.rfl, is_continuous_id, is_continuous_id⟩ protected def refl (X) : X ≃ₜ. X := phomeo.rfl def symm (f : X ≃ₜ. Y) : Y ≃ₜ. X := ⟨f.to_pequiv.symm, f.continuous_inv_fun, f.continuous_to_fun⟩ def trans (f : X ≃ₜ. Y) (g : Y ≃ₜ. Z) : X ≃ₜ. Z := ⟨f.to_pequiv.trans g.to_pequiv, omitted, omitted⟩ end phomeo
f820b3365f99c1ead572ff4f129b1692ad1453aa
69d4931b605e11ca61881fc4f66db50a0a875e39
/test/norm_num.lean
940bdc659ee7e85b33f6678d67f9e56ae56bb62f
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
12,497
lean
/- Copyright (c) 2017 Simon Hudon All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Mario Carneiro Tests for norm_num -/ import tactic.norm_num import data.complex.basic import data.nat.prime -- constant real : Type -- notation `ℝ` := real -- @[instance] constant real.linear_ordered_ring : linear_ordered_field ℝ -- constant complex : Type -- notation `ℂ` := complex -- @[instance] constant complex.field : field ℂ -- @[instance] constant complex.char_zero : char_zero ℂ example : 374 + (32 - (2 * 8123) : ℤ) - 61 * 50 = 86 + 32 * 32 - 4 * 5000 ∧ 43 ≤ 74 + (33 : ℤ) := by norm_num example : ¬ (7-2)/(2*3) ≥ (1:ℝ) + 2/(3^2) := by norm_num example : (6:real) + 9 = 15 := by norm_num example : (2:real)/4 + 4 = 3*3/2 := by norm_num example : (((3:real)/4)-12)<6 := by norm_num example : (5:real) ≠ 8 := by norm_num example : (10:real) > 7 := by norm_num example : (2:real) * 2 + 3 = 7 := by norm_num example : (6:real) < 10 := by norm_num example : (7:real)/2 > 3 := by norm_num example : (4:real)⁻¹ < 1 := by norm_num example : ((1:real) / 2)⁻¹ = 2 := by norm_num example : 2 ^ 17 - 1 = 131071 := by {norm_num, tactic.try_for 200 (tactic.result >>= tactic.type_check)} example : (1:complex) ≠ 2 := by norm_num example : (1:complex) / 3 ≠ 2 / 7 := by norm_num example {α} [semiring α] [char_zero α] : (1:α) ≠ 2 := by norm_num example {α} [ring α] [char_zero α] : (-1:α) ≠ 2 := by norm_num example {α} [division_ring α] [char_zero α] : (-1:α) ≠ 2 := by norm_num example {α} [division_ring α] [char_zero α] : (1:α) / 3 ≠ 2 / 7 := by norm_num example {α} [division_ring α] [char_zero α] : (1:α) / 3 ≠ 0 := by norm_num example : (5 / 2:ℕ) = 2 := by norm_num example : (5 / -2:ℤ) < -1 := by norm_num example : (0 + 1) / 2 < 0 + 1 := by norm_num example : nat.succ (nat.succ (2 ^ 3)) = 10 := by norm_num example : 10 = (-1 : ℤ) % 11 := by norm_num example : (12321 - 2 : ℤ) = 12319 := by norm_num example (x : ℤ) (h : 1000 + 2000 < x) : 100 * 30 < x := by norm_num at *; try_for 100 {exact h} example : (1103 : ℤ) ≤ (2102 : ℤ) := by norm_num example : (110474 : ℤ) ≤ (210485 : ℤ) := by norm_num example : (11047462383473829263 : ℤ) ≤ (21048574677772382462 : ℤ) := by norm_num example : (210485742382937847263 : ℤ) ≤ (1104857462382937847262 : ℤ) := by norm_num example : (210485987642382937847263 : ℕ) ≤ (11048512347462382937847262 : ℕ) := by norm_num example : (210485987642382937847263 : ℚ) ≤ (11048512347462382937847262 : ℚ) := by norm_num example : (2 * 12868 + 25705) * 11621 ^ 2 ≤ 23235 ^ 2 * 12868 := by norm_num example (x : ℕ) : ℕ := begin let n : ℕ, {apply_normed (2^32 - 71)}, exact n end example (a : ℚ) (h : 3⁻¹ * a = a) : true := begin norm_num at h, guard_hyp h : 1 / 3 * a = a, trivial end example : nat.prime 1277 := by norm_num example : nat.min_fac 221 = 13 := by norm_num example (h : (5 : ℤ) ∣ 2) : false := by norm_num at h example (h : false) : false := by norm_num at h example : true := by norm_num example : true ∧ true := by { split, norm_num, norm_num } example : 10 + 2 = 1 + 11 := by norm_num example : 10 - 1 = 9 := by norm_num example : 12 - 5 = 3 + 4 := by norm_num example : 5 - 20 = 0 := by norm_num example : 0 - 2 = 0 := by norm_num example : 4 - (5 - 10) = 2 + (3 - 1) := by norm_num example : 0 - 0 = 0 := by norm_num example : 100 - 100 = 0 := by norm_num example : 5 * (2 - 3) = 0 := by norm_num example : 10 - 5 * 5 + (7 - 3) * 6 = 27 - 3 := by norm_num def foo : ℕ := 1 @[norm_num] meta def eval_foo : expr → tactic (expr × expr) | `(foo) := pure (`(1:ℕ), `(eq.refl 1)) | _ := tactic.failed example : foo = 1 := by norm_num -- ordered field examples variable {α : Type} variable [linear_ordered_field α] example : (-1 :α) * 1 = -1 := by norm_num example : (-2 :α) * 1 = -2 := by norm_num example : (-2 :α) * -1 = 2 := by norm_num example : (-2 :α) * -2 = 4 := by norm_num example : (1 : α) * 0 = 0 := by norm_num example : ((1 : α) + 1) * 5 = 6 + 4 := by norm_num example : (1 : α) = 0 + 1 := by norm_num example : (1 : α) = 1 + 0 := by norm_num example : (2 : α) = 1 + 1 := by norm_num example : (2 : α) = 0 + 2 := by norm_num example : (3 : α) = 1 + 2 := by norm_num example : (3 : α) = 2 + 1 := by norm_num example : (4 : α) = 3 + 1 := by norm_num example : (4 : α) = 2 + 2 := by norm_num example : (5 : α) = 4 + 1 := by norm_num example : (5 : α) = 3 + 2 := by norm_num example : (5 : α) = 2 + 3 := by norm_num example : (6 : α) = 0 + 6 := by norm_num example : (6 : α) = 3 + 3 := by norm_num example : (6 : α) = 4 + 2 := by norm_num example : (6 : α) = 5 + 1 := by norm_num example : (7 : α) = 4 + 3 := by norm_num example : (7 : α) = 1 + 6 := by norm_num example : (7 : α) = 6 + 1 := by norm_num example : 33 = 5 + (28 : α) := by norm_num example : (12 : α) = 0 + (2 + 3) + 7 := by norm_num example : (105 : α) = 70 + (33 + 2) := by norm_num example : (45000000000 : α) = 23000000000 + 22000000000 := by norm_num example : (0 : α) - 3 = -3 := by norm_num example : (0 : α) - 2 = -2 := by norm_num example : (1 : α) - 3 = -2 := by norm_num example : (1 : α) - 1 = 0 := by norm_num example : (0 : α) - 3 = -3 := by norm_num example : (0 : α) - 3 = -3 := by norm_num example : (12 : α) - 4 - (5 + -2) = 5 := by norm_num example : (12 : α) - 4 - (5 + -2) - 20 = -15 := by norm_num example : (0 : α) * 0 = 0 := by norm_num example : (0 : α) * 1 = 0 := by norm_num example : (0 : α) * 2 = 0 := by norm_num example : (2 : α) * 0 = 0 := by norm_num example : (1 : α) * 0 = 0 := by norm_num example : (1 : α) * 1 = 1 := by norm_num example : (2 : α) * 1 = 2 := by norm_num example : (1 : α) * 2 = 2 := by norm_num example : (2 : α) * 2 = 4 := by norm_num example : (3 : α) * 2 = 6 := by norm_num example : (2 : α) * 3 = 6 := by norm_num example : (4 : α) * 1 = 4 := by norm_num example : (1 : α) * 4 = 4 := by norm_num example : (3 : α) * 3 = 9 := by norm_num example : (3 : α) * 4 = 12 := by norm_num example : (4 : α) * 4 = 16 := by norm_num example : (11 : α) * 2 = 22 := by norm_num example : (15 : α) * 6 = 90 := by norm_num example : (123456 : α) * 123456 = 15241383936 := by norm_num example : (4 : α) / 2 = 2 := by norm_num example : (4 : α) / 1 = 4 := by norm_num example : (4 : α) / 3 = 4 / 3 := by norm_num example : (50 : α) / 5 = 10 := by norm_num example : (1056 : α) / 1 = 1056 := by norm_num example : (6 : α) / 4 = 3/2 := by norm_num example : (0 : α) / 3 = 0 := by norm_num example : (3 : α) / 0 = 0 := by norm_num example : (9 * 9 * 9) * (12 : α) / 27 = 81 * (2 + 2) := by norm_num example : (-2 : α) * 4 / 3 = -8 / 3 := by norm_num example : - (-4 / 3) = 1 / (3 / (4 : α)) := by norm_num -- auto gen tests example : ((25 * (1 / 1)) + (30 - 16)) = (39 : α) := by norm_num example : ((19 * (- 2 - 3)) / 6) = (-95/6 : α) := by norm_num example : - (3 * 28) = (-84 : α) := by norm_num example : - - (16 / ((11 / (- - (6 * 19) + 12)) * 21)) = (96/11 : α) := by norm_num example : (- (- 21 + 24) - - (- - (28 + (- 21 / - (16 / ((1 * 26) * ((0 * - 11) + 13))))) * 21)) = (79209/8 : α) := by norm_num example : (27 * (((16 + - (12 + 4)) + (22 - - 19)) - 23)) = (486 : α) := by norm_num example : - (13 * (- 30 / ((7 / 24) + - 7))) = (-9360/161 : α) := by norm_num example : - (0 + 20) = (-20 : α) := by norm_num example : (- 2 - (27 + (((2 / 14) - (7 + 21)) + (16 - - - 14)))) = (-22/7 : α) := by norm_num example : (25 + ((8 - 2) + 16)) = (47 : α) := by norm_num example : (- - 26 / 27) = (26/27 : α) := by norm_num example : ((((16 * (22 / 14)) - 18) / 11) + 30) = (2360/77 : α) := by norm_num example : (((- 28 * 28) / (29 - 24)) * 24) = (-18816/5 : α) := by norm_num example : ((- (18 - ((- - (10 + - 2) - - (23 / 5)) / 5)) - (21 * 22)) - (((20 / - ((((19 + 18) + 15) + 3) + - 22)) + 14) / 17)) = (-394571/825 : α) := by norm_num example : ((3 + 25) - - 4) = (32 : α) := by norm_num example : ((1 - 0) - 22) = (-21 : α) := by norm_num example : (((- (8 / 7) / 14) + 20) + 22) = (2054/49 : α) := by norm_num example : ((21 / 20) - 29) = (-559/20 : α) := by norm_num example : - - 20 = (20 : α) := by norm_num example : (24 - (- 9 / 4)) = (105/4 : α) := by norm_num example : (((7 / ((23 * 19) + (27 * 10))) - ((28 - - 15) * 24)) + (9 / - (10 * - 3))) = (-1042007/1010 : α) := by norm_num example : (26 - (- 29 + (12 / 25))) = (1363/25 : α) := by norm_num example : ((11 * 27) / (4 - 5)) = (-297 : α) := by norm_num example : (24 - (9 + 15)) = (0 : α) := by norm_num example : (- 9 - - 0) = (-9 : α) := by norm_num example : (- 10 / (30 + 10)) = (-1/4 : α) := by norm_num example : (22 - (6 * (28 * - 8))) = (1366 : α) := by norm_num example : ((- - 2 * (9 * - 3)) + (22 / 30)) = (-799/15 : α) := by norm_num example : - (26 / ((3 + 7) / - (27 * (12 / - 16)))) = (-1053/20 : α) := by norm_num example : ((- 29 / 1) + 28) = (-1 : α) := by norm_num example : ((21 * ((10 - (((17 + 28) - - 0) + 20)) + 26)) + ((17 + - 16) * 7)) = (-602 : α) := by norm_num example : (((- 5 - ((24 + - - 8) + 3)) + 20) + - 23) = (-43 : α) := by norm_num example : ((- ((14 - 15) * (14 + 8)) + ((- (18 - 27) - 0) + 12)) - 11) = (32 : α) := by norm_num example : (((15 / 17) * (26 / 27)) + 28) = (4414/153 : α) := by norm_num example : (14 - ((- 16 - 3) * - (20 * 19))) = (-7206 : α) := by norm_num example : (21 - - - (28 - (12 * 11))) = (125 : α) := by norm_num example : ((0 + (7 + (25 + 8))) * - (11 * 27)) = (-11880 : α) := by norm_num example : (19 * - 5) = (-95 : α) := by norm_num example : (29 * - 8) = (-232 : α) := by norm_num example : ((22 / 9) - 29) = (-239/9 : α) := by norm_num example : (3 + (19 / 12)) = (55/12 : α) := by norm_num example : - (13 + 30) = (-43 : α) := by norm_num example : - - - (((21 * - - ((- 25 - (- (30 - 5) / (- 5 - 5))) / (((6 + ((25 * - 13) + 22)) - 3) / 2))) / (- 3 / 10)) * (- 8 - 0)) = (-308/3 : α) := by norm_num example : - (2 * - (- 24 * 22)) = (-1056 : α) := by norm_num example : - - (((28 / - ((- 13 * - 5) / - (((7 - 30) / 16) + 6))) * 0) - 24) = (-24 : α) := by norm_num example : ((13 + 24) - (27 / (21 * 13))) = (3358/91 : α) := by norm_num example : ((3 / - 21) * 25) = (-25/7 : α) := by norm_num example : (17 - (29 - 18)) = (6 : α) := by norm_num example : ((28 / 20) * 15) = (21 : α) := by norm_num example : ((((26 * (- (23 - 13) - 3)) / 20) / (14 - (10 + 20))) / ((16 / 6) / (16 * - (3 / 28)))) = (-1521/2240 : α) := by norm_num example : (46 / (- ((- 17 * 28) - 77) + 87)) = (23/320 : α) := by norm_num example : (73 * - (67 - (74 * - - 11))) = (54531 : α) := by norm_num example : ((8 * (25 / 9)) + 59) = (731/9 : α) := by norm_num example : - ((59 + 85) * - 70) = (10080 : α) := by norm_num example : (66 + (70 * 58)) = (4126 : α) := by norm_num example : (- - 49 * 0) = (0 : α) := by norm_num example : ((- 78 - 69) * 9) = (-1323 : α) := by norm_num example : - - (7 - - (50 * 79)) = (3957 : α) := by norm_num example : - (85 * (((4 * 93) * 19) * - 31)) = (18624180 : α) := by norm_num example : (21 + (- 5 / ((74 * 85) / 45))) = (26373/1258 : α) := by norm_num example : (42 - ((27 + 64) + 26)) = (-75 : α) := by norm_num example : (- ((38 - - 17) + 86) - (74 + 58)) = (-273 : α) := by norm_num example : ((29 * - (75 + - 68)) + (- 41 / 28)) = (-5725/28 : α) := by norm_num example : (- - (40 - 11) - (68 * 86)) = (-5819 : α) := by norm_num example : (6 + ((65 - 14) + - 89)) = (-32 : α) := by norm_num example : (97 * - (29 * 35)) = (-98455 : α) := by norm_num example : - (66 / 33) = (-2 : α) := by norm_num example : - ((94 * 89) + (79 - (23 - (((- 1 / 55) + 95) * (28 - (54 / - - - 22)))))) = (-1369070/121 : α) := by norm_num example : (- 23 + 61) = (38 : α) := by norm_num example : - (93 / 69) = (-31/23 : α) := by norm_num example : (- - ((68 / (39 + (((45 * - (59 - (37 + 35))) / (53 - 75)) - - (100 + - (50 / (- 30 - 59)))))) - (69 - (23 * 30))) / (57 + 17)) = (137496481/16368578 : α) := by norm_num example : (- 19 * - - (75 * - - 41)) = (-58425 : α) := by norm_num example : ((3 / ((- 28 * 45) * (19 + ((- (- 88 - (- (- 1 + 90) + 8)) + 87) * 48)))) + 1) = (1903019/1903020 : α) := by norm_num example : ((- - (28 + 48) / 75) + ((- 59 - 14) - 0)) = (-5399/75 : α) := by norm_num example : (- ((- (((66 - 86) - 36) / 94) - 3) / - - (77 / (56 - - - 79))) + 87) = (312254/3619 : α) := by norm_num
d4fa8454a03aaee99f371292b55db89a9bb2d429
450ef90ab419a8d1a41b0acbfcd9c40d706ef262
/data/finset/basic.lean
04f09b6aa1affd5987f74bf6c7b757c2ca6696b4
[]
no_license
minchaowu/library_dev
7bb62d254aaeae027dd78095cc4b1f0b0f3271ba
9309df1085d8fb019f5b12d22fafd06bc1be6bf4
refs/heads/master
1,609,344,118,976
1,501,167,567,000
1,501,167,567,000
91,199,828
0
0
null
1,494,705,872,000
1,494,705,872,000
null
UTF-8
Lean
false
false
26,435
lean
import ..list.set ..list.perm open list subtype nat def nodup_list (A : Type) := {l : list A // nodup l} variable {α : Type} def to_nodup_list_of_nodup {l : list α} (n : nodup l) : nodup_list α := ⟨l, n⟩ def to_nodup_list [decidable_eq α] (l : list α) : nodup_list α := @to_nodup_list_of_nodup α (erase_dup l) (nodup_erase_dup l) private definition eqv (l₁ l₂ : nodup_list α) := perm l₁.1 l₂.1 local infix ~ := eqv private definition eqv.refl (l : nodup_list α) : l ~ l := perm.refl _ private definition eqv.symm {l₁ l₂ : nodup_list α} : l₁ ~ l₂ → l₂ ~ l₁ := perm.symm private definition eqv.trans {l₁ l₂ l₃ : nodup_list α} : l₁ ~ l₂ → l₂ ~ l₃ → l₁ ~ l₃ := perm.trans instance finset.nodup_list_setoid (α : Type) : setoid (nodup_list α) := setoid.mk (@eqv α) (mk_equivalence (@eqv α) (@eqv.refl α) (@eqv.symm α) (@eqv.trans α)) definition finset (α : Type) : Type := quotient (finset.nodup_list_setoid α) namespace finset definition to_finset_of_nodup (l : list α) (n : nodup l) : finset α := ⟦to_nodup_list_of_nodup n⟧ definition to_finset [decidable_eq α] (l : list α) : finset α := ⟦to_nodup_list l⟧ -- lemma to_finset_eq_of_nodup [decidable_eq α] {l : list α} (n : nodup l) : -- to_finset_of_nodup l n = to_finset l := -- have P : to_nodup_list_of_nodup n = to_nodup_list l, from -- begin -- rewrite [↑to_nodup_list, ↑to_nodup_list_of_nodup], -- congruence, -- rewrite [erase_dup_eq_of_nodup n] -- end, -- quotient.sound (eq.subst P (setoid.refl _)) instance has_decidable_eq [decidable_eq α] : decidable_eq (finset α) := λ s₁ s₂, quotient.rec_on_subsingleton₂ s₁ s₂ (λ l₁ l₂, match perm.decidable_perm l₁.1 l₂.1 with | decidable.is_true e := decidable.is_true (quot.sound e) | decidable.is_false n := decidable.is_false (λ e : ⟦l₁⟧ = ⟦l₂⟧, absurd (quotient.exact e) n) end) definition mem (a : α) (s : finset α) : Prop := quot.lift_on s (λ l, a ∈ l.1) (λ l₁ l₂ (e : l₁ ~ l₂), propext (iff.intro (λ ainl₁, perm.mem_of_perm e ainl₁) (λ ainl₂, perm.mem_of_perm (perm.symm e) ainl₂))) -- instance : has_mem α (finset α) := ⟨mem⟩ -- this causes failure of type class inference on mem_of_mem_list infix ∈ := mem notation a ∉ b := ¬ mem a b theorem mem_of_mem_list {a : α} {l : nodup_list α} : a ∈ l.1 → a ∈ ⟦l⟧ := λ ainl, ainl theorem mem_list_of_mem {a : α} {l : nodup_list α} : a ∈ ⟦l⟧ → a ∈ l.1 := λ ainl, ainl instance decidable_mem [h : decidable_eq α] : ∀ (a : α) (s : finset α), decidable (a ∈ s) := λ a s, quot.rec_on_subsingleton s (λ l, match list.decidable_mem a l.1 with | decidable.is_true p := decidable.is_true (mem_of_mem_list p) | decidable.is_false n := decidable.is_false (λ p, absurd (mem_list_of_mem p) n) end) theorem mem_to_finset [decidable_eq α] {a : α} {l : list α} : a ∈ l → a ∈ to_finset l := λ ainl, mem_erase_dup ainl theorem mem_to_finset_of_nodup {a : α} {l : list α} (n : nodup l) : a ∈ l → a ∈ to_finset_of_nodup l n := λ ainl, ainl /- extensionality -/ theorem ext {s₁ s₂ : finset α} : (∀ a, a ∈ s₁ ↔ a ∈ s₂) → s₁ = s₂ := quotient.induction_on₂ s₁ s₂ (λ l₁ l₂ e, quot.sound (perm.perm_ext l₁.2 l₂.2 e)) /- empty -/ definition empty : finset α := to_finset_of_nodup [] nodup_nil instance : has_emptyc (finset α) := ⟨empty⟩ attribute [simp] theorem not_mem_empty (a : α) : a ∉ (∅ : finset α) := λ aine, aine attribute [simp] theorem mem_empty_iff (x : α) : x ∈ (∅ : finset α) ↔ false := iff_false_intro (not_mem_empty _) theorem mem_empty_eq (x : α) : x ∈ (∅ : finset α) = false := propext (mem_empty_iff _) theorem eq_empty_of_forall_not_mem {s : finset α} (H : ∀x, x ∉ s) : s = ∅ := ext (λ x, iff_false_intro (H x)) -- /- universe -/ -- definition univ [h : fintype A] : finset A := -- to_finset_of_nodup (@fintype.elems A h) (@fintype.unique A h) -- theorem mem_univ [fintype A] (x : A) : x ∈ univ := -- fintype.complete x -- theorem mem_univ_eq [fintype A] (x : A) : x ∈ univ = true := propext (iff_true_intro !mem_univ) /- card -/ definition card (s : finset α) : nat := quot.lift_on s (λ l, length l.1) (λ l₁ l₂ p, perm.length_eq_length_of_perm p) theorem card_empty : card (@empty α) = 0 := rfl lemma ne_empty_of_card_eq_succ {s : finset α} {n : nat} : card s = succ n → s ≠ ∅ := λ h hn, by rw hn at h; contradiction /- insert -/ section insert variable [h : decidable_eq α] include h definition insert (a : α) (s : finset α) : finset α := quot.lift_on s (λ l, to_finset_of_nodup (insert a l.1) (nodup_insert l.2)) (λ (l₁ l₂ : nodup_list α) (p : l₁ ~ l₂), quot.sound (perm.perm_insert a p)) -- set builder notation notation `'{`:max a:(foldr `, ` (x b, insert x b) ∅) `}`:0 := a theorem mem_insert (a : α) (s : finset α) : a ∈ insert a s := quot.induction_on s (λ l : nodup_list α, mem_to_finset_of_nodup _ (mem_insert_self _ _)) theorem mem_insert_of_mem {a : α} {s : finset α} (b : α) : a ∈ s → a ∈ insert b s := quot.induction_on s (λ (l : nodup_list α) (ainl : a ∈ ⟦l⟧), mem_to_finset_of_nodup _ (mem_insert_of_mem ainl)) theorem eq_or_mem_of_mem_insert {x a : α} {s : finset α} : x ∈ insert a s → x = a ∨ x ∈ s := quot.induction_on s (λ l : nodup_list α, λ H, list.eq_or_mem_of_mem_insert H) theorem mem_of_mem_insert_of_ne {x a : α} {s : finset α} (xin : x ∈ insert a s) : x ≠ a → x ∈ s := or_resolve_right (eq_or_mem_of_mem_insert xin) theorem mem_insert_iff (x a : α) (s : finset α) : x ∈ insert a s ↔ (x = a ∨ x ∈ s) := iff.intro eq_or_mem_of_mem_insert (λ h, or.elim h (λ l, by rw l; apply mem_insert) (λ r, mem_insert_of_mem _ r)) theorem mem_insert_eq (x a : α) (s : finset α) : x ∈ insert a s = (x = a ∨ x ∈ s) := propext (mem_insert_iff _ _ _) theorem mem_singleton_iff (x a : α) : x ∈ '{a} ↔ (x = a) := by rewrite [mem_insert_eq, mem_empty_eq, or_false] theorem mem_singleton (a : α) : a ∈ '{a} := mem_insert a ∅ theorem mem_singleton_of_eq {x a : α} (H : x = a) : x ∈ '{a} := by rewrite H; apply mem_insert theorem eq_of_mem_singleton {x a : α} (H : x ∈ '{a}) : x = a := iff.mp (mem_singleton_iff _ _) H theorem eq_of_singleton_eq {a b : α} (H : '{a} = '{b}) : a = b := have a ∈ '{b}, by rewrite ←H; apply mem_singleton, eq_of_mem_singleton this theorem insert_eq_of_mem {a : α} {s : finset α} (H : a ∈ s) : insert a s = s := ext (λ x, eq.substr (mem_insert_eq x a s) (or_iff_right_of_imp (λH1, eq.substr H1 H))) theorem singleton_ne_empty (a : α) : '{a} ≠ ∅ := begin intro H, apply not_mem_empty a, rewrite ←H, apply mem_insert end theorem pair_eq_singleton (a : α) : '{a, a} = '{a} := by rw [insert_eq_of_mem]; apply mem_singleton -- useful in proofs by induction theorem forall_of_forall_insert {P : α → Prop} {a : α} {s : finset α} (H : ∀ x, x ∈ insert a s → P x) : ∀ x, x ∈ s → P x := λ x xs, H x (mem_insert_of_mem _ xs) theorem insert.comm (x y : α) (s : finset α) : insert x (insert y s) = insert y (insert x s) := ext (λ a, begin repeat {rw mem_insert_eq}, rw [propext or.left_comm] end) theorem card_insert_of_mem {a : α} {s : finset α} : a ∈ s → card (insert a s) = card s := quot.induction_on s (λ (l : nodup_list α) (ainl : a ∈ ⟦l⟧), list.length_insert_of_mem ainl) theorem card_insert_of_not_mem {a : α} {s : finset α} : a ∉ s → card (insert a s) = card s + 1 := quot.induction_on s (λ (l : nodup_list α) (nainl : a ∉ ⟦l⟧), list.length_insert_of_not_mem nainl) theorem card_insert_le (a : α) (s : finset α) : card (insert a s) ≤ card s + 1 := if H : a ∈ s then by rewrite [card_insert_of_mem H]; apply le_succ else by rewrite [card_insert_of_not_mem H] attribute [recursor 6] protected theorem induction {P : finset α → Prop} (H1 : P empty) (H2 : ∀ ⦃a : α⦄, ∀{s : finset α}, a ∉ s → P s → P (insert a s)) : ∀s, P s := λ s, quot.induction_on s (λ u, subtype.rec_on u (λ l, list.rec_on l (λ nodup_l, H1) (λ a l', λ IH nodup_al', have aux₁: a ∉ l', from not_mem_of_nodup_cons nodup_al', have ndl' : nodup l', from nodup_of_nodup_cons nodup_al', have p1 : P (quot.mk _ (subtype.mk l' ndl')), from IH ndl', have ¬ mem a (quot.mk _ (subtype.mk l' ndl')), from aux₁, have P (insert a (quot.mk _ (subtype.mk l' _))), from H2 this p1, have hperm : perm (list.insert a l') (a :: l'), from perm.perm_insert_cons_of_not_mem aux₁, begin apply @eq.subst _ P _ _ _ this, apply quot.sound, exact hperm end))) protected theorem induction_on {P : finset α → Prop} (s : finset α) (H1 : P empty) (H2 : ∀ ⦃a : α⦄, ∀ {s : finset α}, a ∉ s → P s → P (insert a s)) : P s := finset.induction H1 H2 s theorem exists_mem_of_ne_empty {s : finset α} : s ≠ ∅ → ∃ a : α, a ∈ s := @finset.induction_on _ _ (λ x, x ≠ empty → ∃ a : α, mem a x) s (λ h, absurd rfl h) (by intros a s nin ih h; existsi a; apply mem_insert) theorem eq_empty_of_card_eq_zero {s : finset α} (H : card s = 0) : s = ∅ := @finset.induction_on _ _ (λ x, card x = 0 → x = empty) s (λ h, rfl) (by intros a s' H1 Ih H; rw (card_insert_of_not_mem H1) at H; contradiction) H end insert /- erase -/ section erase variable [h : decidable_eq α] include h definition erase (a : α) (s : finset α) : finset α := quot.lift_on s (λ l, to_finset_of_nodup (l.1.erase a) (nodup_erase_of_nodup a l.2)) (λ (l₁ l₂ : nodup_list α) (p : l₁ ~ l₂), quot.sound (perm.erase_perm_erase_of_perm a p)) theorem not_mem_erase (a : α) (s : finset α) : a ∉ erase a s := quot.induction_on s (λ l, list.mem_erase_of_nodup _ l.2) theorem card_erase_of_mem {a : α} {s : finset α} : a ∈ s → card (erase a s) = pred (card s) := quot.induction_on s (λ l ainl, list.length_erase_of_mem ainl) theorem card_erase_of_not_mem {a : α} {s : finset α} : a ∉ s → card (erase a s) = card s := quot.induction_on s (λ l nainl, length_erase_of_not_mem nainl) theorem erase_empty (a : α) : erase a ∅ = ∅ := rfl theorem ne_of_mem_erase {a b : α} {s : finset α} : b ∈ erase a s → b ≠ a := by intros h beqa; subst b; exact absurd h (not_mem_erase _ _) theorem mem_of_mem_erase {a b : α} {s : finset α} : b ∈ erase a s → b ∈ s := quot.induction_on s (λ l bin, mem_of_mem_erase bin) theorem mem_erase_of_ne_of_mem {a b : α} {s : finset α} : a ≠ b → a ∈ s → a ∈ erase b s := quot.induction_on s (λ l n ain, list.mem_erase_of_ne_of_mem n ain) theorem mem_erase_iff (a b : α) (s : finset α) : a ∈ erase b s ↔ a ∈ s ∧ a ≠ b := iff.intro (λ H, and.intro (mem_of_mem_erase H) (ne_of_mem_erase H)) (λ H, mem_erase_of_ne_of_mem (and.right H) (and.left H)) theorem mem_erase_eq (a b : α) (s : finset α) : a ∈ erase b s = (a ∈ s ∧ a ≠ b) := propext (mem_erase_iff _ _ _) open decidable theorem erase_insert {a : α} {s : finset α} : a ∉ s → erase a (insert a s) = s := λ anins, finset.ext (λ b, by_cases (λ beqa : b = a, iff.intro (λ bin, by subst b; exact absurd bin (not_mem_erase _ _)) (λ bin, by subst b; contradiction)) (λ bnea : b ≠ a, iff.intro (λ bin, have b ∈ insert a s, from mem_of_mem_erase bin, mem_of_mem_insert_of_ne this bnea) (λ bin, have b ∈ insert a s, from mem_insert_of_mem _ bin, mem_erase_of_ne_of_mem bnea this))) theorem insert_erase {a : α} {s : finset α} : a ∈ s → insert a (erase a s) = s := λ ains, finset.ext (λ b, by_cases (λ h : b = a, iff.intro (λ bin, by subst b; assumption) (λ bin, by subst b; apply mem_insert)) (λ hn : b ≠ a, iff.intro (λ bin, mem_of_mem_erase (mem_of_mem_insert_of_ne bin hn)) (λ bin, mem_insert_of_mem _ (mem_erase_of_ne_of_mem hn bin)))) end erase /- union -/ section union variable [h : decidable_eq α] include h definition union (s₁ s₂ : finset α) : finset α := quotient.lift_on₂ s₁ s₂ (λ l₁ l₂, to_finset_of_nodup (list.union l₁.1 l₂.1) (nodup_union_of_nodup_of_nodup l₁.2 l₂.2)) (λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound (perm.perm_union p₁ p₂)) infix ∪ := union theorem mem_union_left {a : α} {s₁ : finset α} (s₂ : finset α) : a ∈ s₁ → a ∈ s₁ ∪ s₂ := quotient.induction_on₂ s₁ s₂ (λ l₁ l₂ ainl₁, list.mem_union_left ainl₁ _) theorem mem_union_l {a : α} {s₁ : finset α} {s₂ : finset α} : a ∈ s₁ → a ∈ s₁ ∪ s₂ := mem_union_left s₂ theorem mem_union_right {a : α} {s₂ : finset α} (s₁ : finset α) : a ∈ s₂ → a ∈ s₁ ∪ s₂ := quotient.induction_on₂ s₁ s₂ (λ l₁ l₂ ainl₂, list.mem_union_right _ ainl₂) theorem mem_union_r {a : α} {s₂ : finset α} {s₁ : finset α} : a ∈ s₂ → a ∈ s₁ ∪ s₂ := mem_union_right s₁ theorem mem_or_mem_of_mem_union {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∪ s₂ → a ∈ s₁ ∨ a ∈ s₂ := quotient.induction_on₂ s₁ s₂ (λ l₁ l₂ ainl₁l₂, list.mem_or_mem_of_mem_union ainl₁l₂) theorem mem_union_iff (a : α) (s₁ s₂ : finset α) : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ := iff.intro (λ h, mem_or_mem_of_mem_union h) (λ d, or.elim d (λ i, mem_union_left _ i) (λ i, mem_union_right _ i)) theorem mem_union_eq (a : α) (s₁ s₂ : finset α) : (a ∈ s₁ ∪ s₂) = (a ∈ s₁ ∨ a ∈ s₂) := propext (mem_union_iff _ _ _) theorem union_comm (s₁ s₂ : finset α) : s₁ ∪ s₂ = s₂ ∪ s₁ := ext (λ a, by repeat {rw mem_union_eq}; exact or.comm) theorem union_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) := ext (λ a, by repeat {rw mem_union_eq}; exact or.assoc) theorem union_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := left_comm _ union_comm union_assoc s₁ s₂ s₃ theorem union_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := right_comm _ union_comm union_assoc s₁ s₂ s₃ theorem union_self (s : finset α) : s ∪ s = s := ext (λ a, iff.intro (λ ain, or.elim (mem_or_mem_of_mem_union ain) (λ i, i) (λ i, i)) (λ i, mem_union_left _ i)) theorem union_empty (s : finset α) : s ∪ empty = s := ext (λ a, iff.intro (λ l, or.elim (mem_or_mem_of_mem_union l) (λ i, i) (λ i, absurd i (not_mem_empty _))) (λ r, mem_union_left _ r)) theorem empty_union (s : finset α) : empty ∪ s = s := calc empty ∪ s = s ∪ empty : union_comm _ _ ... = s : union_empty _ theorem insert_eq (a : α) (s : finset α) : insert a s = '{a} ∪ s := ext (λ x, by rw [mem_insert_iff, mem_union_iff, mem_singleton_iff]) theorem insert_union (a : α) (s t : finset α) : insert a (s ∪ t) = insert a s ∪ t := by rewrite [insert_eq, insert_eq a s, union_assoc] end union /- inter -/ section inter variable [h : decidable_eq α] include h definition inter (s₁ s₂ : finset α) : finset α := quotient.lift_on₂ s₁ s₂ (λ l₁ l₂, to_finset_of_nodup (list.inter l₁.1 l₂.1) (nodup_inter_of_nodup _ l₁.2)) (λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound (perm.perm_inter p₁ p₂)) infix ∩ := inter theorem mem_of_mem_inter_left {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∩ s₂ → a ∈ s₁ := quotient.induction_on₂ s₁ s₂ (λ l₁ l₂ ainl₁l₂, list.mem_of_mem_inter_left ainl₁l₂) theorem mem_of_mem_inter_right {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∩ s₂ → a ∈ s₂ := quotient.induction_on₂ s₁ s₂ (λ l₁ l₂ ainl₁l₂, list.mem_of_mem_inter_right ainl₁l₂) theorem mem_inter {a : α} {s₁ s₂ : finset α} : a ∈ s₁ → a ∈ s₂ → a ∈ s₁ ∩ s₂ := quotient.induction_on₂ s₁ s₂ (λ l₁ l₂ ainl₁ ainl₂, list.mem_inter_of_mem_of_mem ainl₁ ainl₂) theorem mem_inter_iff (a : α) (s₁ s₂ : finset α) : a ∈ s₁ ∩ s₂ ↔ a ∈ s₁ ∧ a ∈ s₂ := iff.intro (λ h, and.intro (mem_of_mem_inter_left h) (mem_of_mem_inter_right h)) (λ h, mem_inter (and.elim_left h) (and.elim_right h)) theorem mem_inter_eq (a : α) (s₁ s₂ : finset α) : (a ∈ s₁ ∩ s₂) = (a ∈ s₁ ∧ a ∈ s₂) := propext (mem_inter_iff _ _ _) theorem inter_comm (s₁ s₂ : finset α) : s₁ ∩ s₂ = s₂ ∩ s₁ := ext (λ a, by repeat {rw mem_inter_eq}; exact and.comm) theorem inter_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = s₁ ∩ (s₂ ∩ s₃) := ext (λ a, by repeat {rw mem_inter_eq}; exact and.assoc) theorem inter_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := left_comm _ inter_comm inter_assoc s₁ s₂ s₃ theorem inter_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := right_comm _ inter_comm inter_assoc s₁ s₂ s₃ theorem inter_self (s : finset α) : s ∩ s = s := ext (λ a, iff.intro (λ h, mem_of_mem_inter_right h) (λ h, mem_inter h h)) theorem inter_empty (s : finset α) : s ∩ empty = empty := ext (λ a, iff.intro (λ h, absurd (mem_of_mem_inter_right h) (not_mem_empty _)) (λ h, absurd h (not_mem_empty _))) theorem empty_inter (s : finset α) : empty ∩ s = empty := calc empty ∩ s = s ∩ empty : inter_comm _ _ ... = empty : inter_empty _ theorem singleton_inter_of_mem {a : α} {s : finset α} (H : a ∈ s) : '{a} ∩ s = '{a} := ext (λ x, begin rewrite [mem_inter_eq, mem_singleton_iff], exact iff.intro (λ h, h.left) (λ h, ⟨h, (eq.subst (eq.symm h) H)⟩) end) theorem singleton_inter_of_not_mem {a : α} {s : finset α} (H : a ∉ s) : '{a} ∩ s = (∅ : finset α) := ext (λ x, begin rewrite [mem_inter_eq, mem_singleton_iff, mem_empty_eq], exact iff.intro (λ h, H (eq.subst h.left h.right)) (false.elim) end) end inter /- distributivity laws -/ section inter variable [h : decidable_eq α] include h theorem inter_distrib_left (s t u : finset α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := ext (λ x, by rw [mem_inter_eq];repeat {rw mem_union_eq};repeat {rw mem_inter_eq}; super) theorem inter_distrib_right (s t u : finset α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := ext (λ x, by rw [mem_inter_eq]; repeat {rw mem_union_eq}; repeat {rw mem_inter_eq}; super) theorem union_distrib_left (s t u : finset α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := ext (λ x, by rw [mem_union_eq]; repeat {rw mem_inter_eq}; repeat {rw mem_union_eq}; super) theorem union_distrib_right (s t u : finset α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := ext (λ x, by rw [mem_union_eq]; repeat {rw mem_inter_eq}; repeat {rw mem_union_eq}; super) end inter definition subset_aux {T : Type} (l₁ l₂ : list T) := ∀ ⦃a : T⦄, a ∈ l₁ → a ∈ l₂ /- subset -/ definition subset (s₁ s₂ : finset α) : Prop := quotient.lift_on₂ s₁ s₂ (λ l₁ l₂, subset_aux l₁.1 l₂.1) (λ v₁ v₂ w₁ w₂ p₁ p₂, propext (iff.intro (λ s₁ a i, perm.mem_of_perm p₂ (s₁ (perm.mem_of_perm (perm.symm p₁) i))) (λ s₂ a i, perm.mem_of_perm (perm.symm p₂) (s₂ (perm.mem_of_perm p₁ i))))) infix ⊆ := subset theorem empty_subset (s : finset α) : empty ⊆ s := quot.induction_on s (λ l, list.nil_subset l.1) -- theorem subset_univ [h : fintype α] (s : finset α) : s ⊆ univ := -- quot.induction_on s (λ l a i, fintype.complete a) theorem subset.refl (s : finset α) : s ⊆ s := quot.induction_on s (λ l, list.subset.refl l.1) theorem subset.trans {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₂ ⊆ s₃ → s₁ ⊆ s₃ := quotient.induction_on₃ s₁ s₂ s₃ (λ l₁ l₂ l₃ h₁ h₂, list.subset.trans h₁ h₂) theorem mem_of_subset_of_mem {s₁ s₂ : finset α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := quotient.induction_on₂ s₁ s₂ (λ l₁ l₂ h₁ h₂, h₁ h₂) theorem subset.antisymm {s₁ s₂ : finset α} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ := ext (λ x, iff.intro (λ H, mem_of_subset_of_mem H₁ H) (λ H, mem_of_subset_of_mem H₂ H)) -- alternative name theorem eq_of_subset_of_subset {s₁ s₂ : finset α} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ := subset.antisymm H₁ H₂ theorem subset_of_forall {s₁ s₂ : finset α} : (∀x, x ∈ s₁ → x ∈ s₂) → s₁ ⊆ s₂ := quotient.induction_on₂ s₁ s₂ (λ l₁ l₂ H, H) theorem subset_insert [h : decidable_eq α] (s : finset α) (a : α) : s ⊆ insert a s := subset_of_forall (λ x h, mem_insert_of_mem _ h) theorem eq_empty_of_subset_empty {x : finset α} (H : x ⊆ empty) : x = empty := subset.antisymm H (empty_subset x) theorem subset_empty_iff (x : finset α) : x ⊆ empty ↔ x = empty := iff.intro eq_empty_of_subset_empty (λ xeq, by rewrite xeq; apply subset.refl empty) section variable [decα : decidable_eq α] include decα theorem erase_subset_erase (a : α) {s t : finset α} (H : s ⊆ t) : erase a s ⊆ erase a t := begin apply subset_of_forall, intro x, repeat {rw mem_erase_eq}, intro H', show x ∈ t ∧ x ≠ a, from and.intro (mem_of_subset_of_mem H (and.left H')) (and.right H') end theorem erase_subset (a : α) (s : finset α) : erase a s ⊆ s := begin apply subset_of_forall, intro x, rewrite mem_erase_eq, intro H, apply and.left H end theorem erase_eq_of_not_mem {a : α} {s : finset α} (anins : a ∉ s) : erase a s = s := eq_of_subset_of_subset (erase_subset _ _) (subset_of_forall (λ x, λ xs : x ∈ s, have x ≠ a, from λ H', anins (eq.subst H' xs), mem_erase_of_ne_of_mem this xs)) theorem erase_insert_subset (a : α) (s : finset α) : erase a (insert a s) ⊆ s := decidable.by_cases (λ ains : a ∈ s, by rewrite [insert_eq_of_mem ains]; apply erase_subset) (λ nains : a ∉ s, by rewrite [erase_insert nains]; apply subset.refl) theorem erase_subset_of_subset_insert {a : α} {s t : finset α} (H : s ⊆ insert a t) : erase a s ⊆ t := subset.trans (erase_subset_erase _ H) (erase_insert_subset _ _) theorem insert_erase_subset (a : α) (s : finset α) : s ⊆ insert a (erase a s) := decidable.by_cases (λ ains : a ∈ s, by rewrite [insert_erase ains]; apply subset.refl) (λ nains : a ∉ s, by rewrite[erase_eq_of_not_mem nains]; apply subset_insert) theorem insert_subset_insert (a : α) {s t : finset α} (H : s ⊆ t) : insert a s ⊆ insert a t := begin apply subset_of_forall, intro x, repeat {rw mem_insert_eq}, intro H', cases H' with xeqa xins, exact (or.inl xeqa), exact (or.inr (mem_of_subset_of_mem H xins)) end theorem subset_insert_of_erase_subset {s t : finset α} {a : α} (H : erase a s ⊆ t) : s ⊆ insert a t := subset.trans (insert_erase_subset a s) (insert_subset_insert _ H) theorem subset_insert_iff (s t : finset α) (a : α) : s ⊆ insert a t ↔ erase a s ⊆ t := iff.intro erase_subset_of_subset_insert subset_insert_of_erase_subset end /- upto -/ section upto definition upto (n : nat) : finset nat := to_finset_of_nodup (list.upto n) (nodup_upto n) theorem card_upto : ∀ n, card (upto n) = n := list.length_upto theorem lt_of_mem_upto {n a : nat} : a ∈ upto n → a < n := @list.lt_of_mem_upto n a theorem mem_upto_succ_of_mem_upto {n a : nat} : a ∈ upto n → a ∈ upto (succ n) := list.mem_upto_succ_of_mem_upto theorem mem_upto_of_lt {n a : nat} : a < n → a ∈ upto n := @list.mem_upto_of_lt n a theorem mem_upto_iff (a n : nat) : a ∈ upto n ↔ a < n := iff.intro lt_of_mem_upto mem_upto_of_lt theorem mem_upto_eq (a n : nat) : a ∈ upto n = (a < n) := propext (mem_upto_iff _ _) end upto theorem upto_zero : upto 0 = empty := rfl theorem upto_succ (n : ℕ) : upto (succ n) = upto n ∪ '{n} := begin apply ext, intro x, rw [mem_union_iff], repeat {rw mem_upto_iff}, rw [mem_singleton_iff, ←le_iff_lt_or_eq], apply iff.intro, {intro h, apply le_of_lt_succ, exact h}, {apply lt_succ_of_le} end /- useful rules for calculations with quantifiers -/ theorem exists_mem_empty_iff {A : Type} (P : A → Prop) : (∃ x, mem x empty ∧ P x) ↔ false := iff.intro (λ H, let ⟨x,H1⟩ := H in not_mem_empty _ (H1.left)) (λ H, false.elim H) theorem exists_mem_empty_eq {A : Type} (P : A → Prop) : (∃ x, mem x empty ∧ P x) = false := propext (exists_mem_empty_iff _) theorem exists_mem_insert_iff {A : Type} [d : decidable_eq A] (a : A) (s : finset A) (P : A → Prop) : (∃ x, x ∈ insert a s ∧ P x) ↔ P a ∨ (∃ x, x ∈ s ∧ P x) := iff.intro (λ H, let ⟨x,H1,H2⟩ := H in or.elim (eq_or_mem_of_mem_insert H1) (λ l, or.inl (eq.subst l H2)) (λ r, or.inr ⟨x, ⟨r, H2⟩⟩)) (λ H, or.elim H (λ l, ⟨a, ⟨mem_insert _ _, l⟩⟩) (λ r, let ⟨x,H2,H3⟩ := r in ⟨x, ⟨mem_insert_of_mem _ H2, H3⟩⟩)) theorem exists_mem_insert_eq {A : Type} [d : decidable_eq A] (a : A) (s : finset A) (P : A → Prop) : (∃ x, x ∈ insert a s ∧ P x) = (P a ∨ (∃ x, x ∈ s ∧ P x)) := propext (exists_mem_insert_iff _ _ _) theorem forall_mem_empty_iff {A : Type} (P : A → Prop) : (∀ x, mem x empty → P x) ↔ true := iff.intro (λ H, trivial) (λ H x H', absurd H' (not_mem_empty _)) theorem forall_mem_empty_eq {A : Type} (P : A → Prop) : (∀ x, mem x empty → P x) = true := propext (forall_mem_empty_iff _) theorem forall_mem_insert_iff {A : Type} [d : decidable_eq A] (a : A) (s : finset A) (P : A → Prop) : (∀ x, x ∈ insert a s → P x) ↔ P a ∧ (∀ x, x ∈ s → P x) := iff.intro (λ H, and.intro (H _ (mem_insert _ _)) (λ x H', H _ (mem_insert_of_mem _ H'))) (λ H x, λ H' : x ∈ insert a s, or.elim (eq_or_mem_of_mem_insert H') (λ l, eq.subst (eq.symm l) H.left) (λ r, and.right H _ r)) theorem forall_mem_insert_eq {A : Type} [d : decidable_eq A] (a : A) (s : finset A) (P : A → Prop) : (∀ x, x ∈ insert a s → P x) = (P a ∧ (∀ x, x ∈ s → P x)) := propext (forall_mem_insert_iff _ _ _) end finset
fc081413f2fa2733ca2385201f324c84b576da50
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/field_theory/subfield.lean
15c5b61e29ab7d939f935599a382b6dea9f02414
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
4,968
lean
/- Copyright (c) 2018 Andreas Swerdlow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andreas Swerdlow -/ import deprecated.subring variables {F : Type*} [field F] (S : set F) section prio set_option default_priority 100 -- see Note [default priority] class is_subfield extends is_subring S : Prop := (inv_mem : ∀ {x : F}, x ∈ S → x⁻¹ ∈ S) end prio instance is_subfield.field [is_subfield S] : field S := { inv := λ x, ⟨x⁻¹, is_subfield.inv_mem x.2⟩, exists_pair_ne := ⟨0, 1, λ h, zero_ne_one (subtype.ext_iff_val.1 h)⟩, mul_inv_cancel := λ a ha, subtype.ext_iff_val.2 (mul_inv_cancel (λ h, ha $ subtype.ext_iff_val.2 h)), inv_zero := subtype.ext_iff_val.2 inv_zero, ..show comm_ring S, by apply_instance } instance univ.is_subfield : is_subfield (@set.univ F) := { inv_mem := by intros; trivial } /- note: in the next two declarations, if we let type-class inference figure out the instance `ring_hom.is_subring_preimage` then that instance only applies when particular instances of `is_add_subgroup _` and `is_submonoid _` are chosen (which are not the default ones). If we specify it explicitly, then it doesn't complain. -/ instance preimage.is_subfield {K : Type*} [field K] (f : F →+* K) (s : set K) [is_subfield s] : is_subfield (f ⁻¹' s) := { inv_mem := λ a (ha : f a ∈ s), show f a⁻¹ ∈ s, by { rw [f.map_inv], exact is_subfield.inv_mem ha }, ..f.is_subring_preimage s } instance image.is_subfield {K : Type*} [field K] (f : F →+* K) (s : set F) [is_subfield s] : is_subfield (f '' s) := { inv_mem := λ a ⟨x, xmem, ha⟩, ⟨x⁻¹, is_subfield.inv_mem xmem, ha ▸ f.map_inv _⟩, ..f.is_subring_image s } instance range.is_subfield {K : Type*} [field K] (f : F →+* K) : is_subfield (set.range f) := by { rw ← set.image_univ, apply_instance } namespace field /-- `field.closure s` is the minimal subfield that includes `s`. -/ def closure : set F := { x | ∃ y ∈ ring.closure S, ∃ z ∈ ring.closure S, y / z = x } variables {S} theorem ring_closure_subset : ring.closure S ⊆ closure S := λ x hx, ⟨x, hx, 1, is_submonoid.one_mem, div_one x⟩ instance closure.is_submonoid : is_submonoid (closure S) := { mul_mem := by rintros _ _ ⟨p, hp, q, hq, hq0, rfl⟩ ⟨r, hr, s, hs, hs0, rfl⟩; exact ⟨p * r, is_submonoid.mul_mem hp hr, q * s, is_submonoid.mul_mem hq hs, (div_mul_div _ _ _ _).symm⟩, one_mem := ring_closure_subset $ is_submonoid.one_mem } instance closure.is_subfield : is_subfield (closure S) := have h0 : (0:F) ∈ closure S, from ring_closure_subset $ is_add_submonoid.zero_mem, { add_mem := begin intros a b ha hb, rcases (id ha) with ⟨p, hp, q, hq, rfl⟩, rcases (id hb) with ⟨r, hr, s, hs, rfl⟩, classical, by_cases hq0 : q = 0, by simp [hb, hq0], by_cases hs0 : s = 0, by simp [ha, hs0], exact ⟨p * s + q * r, is_add_submonoid.add_mem (is_submonoid.mul_mem hp hs) (is_submonoid.mul_mem hq hr), q * s, is_submonoid.mul_mem hq hs, (div_add_div p r hq0 hs0).symm⟩ end, zero_mem := h0, neg_mem := begin rintros _ ⟨p, hp, q, hq, rfl⟩, exact ⟨-p, is_add_subgroup.neg_mem hp, q, hq, neg_div q p⟩ end, inv_mem := begin rintros _ ⟨p, hp, q, hq, rfl⟩, classical, by_cases hp0 : p = 0, by simp [hp0, h0], exact ⟨q, hq, p, hp, inv_div.symm⟩ end } theorem mem_closure {a : F} (ha : a ∈ S) : a ∈ closure S := ring_closure_subset $ ring.mem_closure ha theorem subset_closure : S ⊆ closure S := λ _, mem_closure theorem closure_subset {T : set F} [is_subfield T] (H : S ⊆ T) : closure S ⊆ T := by rintros _ ⟨p, hp, q, hq, hq0, rfl⟩; exact is_submonoid.mul_mem (ring.closure_subset H hp) (is_subfield.inv_mem $ ring.closure_subset H hq) theorem closure_subset_iff (s t : set F) [is_subfield t] : closure s ⊆ t ↔ s ⊆ t := ⟨set.subset.trans subset_closure, closure_subset⟩ theorem closure_mono {s t : set F} (H : s ⊆ t) : closure s ⊆ closure t := closure_subset $ set.subset.trans H subset_closure end field lemma is_subfield_Union_of_directed {ι : Type*} [hι : nonempty ι] (s : ι → set F) [∀ i, is_subfield (s i)] (directed : ∀ i j, ∃ k, s i ⊆ s k ∧ s j ⊆ s k) : is_subfield (⋃i, s i) := { inv_mem := λ x hx, let ⟨i, hi⟩ := set.mem_Union.1 hx in set.mem_Union.2 ⟨i, is_subfield.inv_mem hi⟩, to_is_subring := is_subring_Union_of_directed s directed } instance is_subfield.inter (S₁ S₂ : set F) [is_subfield S₁] [is_subfield S₂] : is_subfield (S₁ ∩ S₂) := { inv_mem := λ x hx, ⟨is_subfield.inv_mem hx.1, is_subfield.inv_mem hx.2⟩ } instance is_subfield.Inter {ι : Sort*} (S : ι → set F) [h : ∀ y : ι, is_subfield (S y)] : is_subfield (set.Inter S) := { inv_mem := λ x hx, set.mem_Inter.2 $ λ y, is_subfield.inv_mem $ set.mem_Inter.1 hx y }
0eb00ddd4a3555537946f7560c9a36d024f72193
246309748072bf9f8da313401699689ebbecd94d
/src/data/polynomial/monic.lean
cac9eb06ae7d34b5faccddbcd56dc64928934a78
[ "Apache-2.0" ]
permissive
YJMD/mathlib
b703a641e5f32a996f7842f7c0043bab2b462ee2
7310eab9fa8c1b1229dca42682f1fa6bfb7dbbf9
refs/heads/master
1,670,714,479,314
1,599,035,445,000
1,599,035,445,000
292,279,930
0
0
null
1,599,050,561,000
1,599,050,560,000
null
UTF-8
Lean
false
false
9,170
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.degree import algebra.associated import tactic.omega /-! # Theory of monic polynomials We give several tools for proving that polynomials are monic, e.g. `monic_mul`, `monic_map`. -/ noncomputable theory local attribute [instance, priority 100] classical.prop_decidable open finset open_locale big_operators namespace polynomial universes u v y variables {R : Type u} {S : Type v} {a b : R} {m n : ℕ} {ι : Type y} section semiring variables [semiring R] {p q r : polynomial R} lemma monic.as_sum {p : polynomial R} (hp : p.monic) : p = X^(p.nat_degree) + (∑ i in finset.range p.nat_degree, C (p.coeff i) * X^i) := begin conv_lhs { rw [p.as_sum, finset.sum_range_succ] }, suffices : C (p.coeff p.nat_degree) = 1, { rw [this, one_mul] }, exact congr_arg C hp end lemma ne_zero_of_monic_of_zero_ne_one (hp : monic p) (h : (0 : R) ≠ 1) : p ≠ 0 := mt (congr_arg leading_coeff) $ by rw [monic.def.1 hp, leading_coeff_zero]; cc lemma ne_zero_of_ne_zero_of_monic (hp : p ≠ 0) (hq : monic q) : q ≠ 0 := begin intro h, rw [h, monic.def, leading_coeff_zero] at hq, rw [← mul_one p, ← C_1, ← hq, C_0, mul_zero] at hp, exact hp rfl end lemma monic_map [semiring S] (f : R →+* S) (hp : monic p) : monic (p.map f) := if h : (0 : S) = 1 then by haveI := subsingleton_of_zero_eq_one h; exact subsingleton.elim _ _ else have f (leading_coeff p) ≠ 0, by rwa [show _ = _, from hp, is_semiring_hom.map_one f, ne.def, eq_comm], by begin rw [monic, leading_coeff, coeff_map], suffices : p.coeff (map f p).nat_degree = 1, simp [this], suffices : (map f p).nat_degree = p.nat_degree, rw this, exact hp, rwa nat_degree_eq_of_degree_eq (degree_map_eq_of_leading_coeff_ne_zero _ _), end theorem monic_of_degree_le (n : ℕ) (H1 : degree p ≤ n) (H2 : coeff p n = 1) : monic p := decidable.by_cases (assume H : degree p < n, eq_of_zero_eq_one (H2 ▸ (coeff_eq_zero_of_degree_lt H).symm) _ _) (assume H : ¬degree p < n, by rwa [monic, leading_coeff, nat_degree, (lt_or_eq_of_le H1).resolve_left H]) theorem monic_X_pow_add {n : ℕ} (H : degree p ≤ n) : monic (X ^ (n+1) + p) := have H1 : degree p < n+1, from lt_of_le_of_lt H (with_bot.coe_lt_coe.2 (nat.lt_succ_self n)), monic_of_degree_le (n+1) (le_trans (degree_add_le _ _) (max_le (degree_X_pow_le _) (le_of_lt H1))) (by rw [coeff_add, coeff_X_pow, if_pos rfl, coeff_eq_zero_of_degree_lt H1, add_zero]) theorem monic_X_add_C (x : R) : monic (X + C x) := pow_one (X : polynomial R) ▸ monic_X_pow_add degree_C_le lemma monic_mul (hp : monic p) (hq : monic q) : monic (p * q) := if h0 : (0 : R) = 1 then by haveI := subsingleton_of_zero_eq_one h0; exact subsingleton.elim _ _ else have leading_coeff p * leading_coeff q ≠ 0, by simp [monic.def.1 hp, monic.def.1 hq, ne.symm h0], by rw [monic.def, leading_coeff_mul' this, monic.def.1 hp, monic.def.1 hq, one_mul] lemma monic_pow (hp : monic p) : ∀ (n : ℕ), monic (p ^ n) | 0 := monic_one | (n+1) := monic_mul hp (monic_pow n) end semiring section comm_semiring variables [comm_semiring R] {p : polynomial R} lemma monic_prod_of_monic (s : finset ι) (f : ι → polynomial R) (hs : ∀ i ∈ s, monic (f i)) : monic (∏ i in s, f i) := prod_induction _ _ (@monic_mul _ _) monic_one hs lemma is_unit_C {x : R} : is_unit (C x) ↔ is_unit x := begin rw [is_unit_iff_dvd_one, is_unit_iff_dvd_one], split, { rintros ⟨g, hg⟩, replace hg := congr_arg (eval 0) hg, rw [eval_one, eval_mul, eval_C] at hg, exact ⟨g.eval 0, hg⟩ }, { rintros ⟨y, hy⟩, exact ⟨C y, by rw [← C_mul, ← hy, C_1]⟩ } end lemma eq_one_of_is_unit_of_monic (hm : monic p) (hpu : is_unit p) : p = 1 := have degree p ≤ 0, from calc degree p ≤ degree (1 : polynomial R) : let ⟨u, hu⟩ := is_unit_iff_dvd_one.1 hpu in if hu0 : u = 0 then begin rw [hu0, mul_zero] at hu, rw [← mul_one p, hu, mul_zero], simp end else have p.leading_coeff * u.leading_coeff ≠ 0, by rw [hm.leading_coeff, one_mul, ne.def, leading_coeff_eq_zero]; exact hu0, by rw [hu, degree_mul' this]; exact le_add_of_nonneg_right (degree_nonneg_iff_ne_zero.2 hu0) ... ≤ 0 : degree_one_le, by rw [eq_C_of_degree_le_zero this, ← nat_degree_eq_zero_iff_degree_le_zero.2 this, ← leading_coeff, hm.leading_coeff, C_1] end comm_semiring section comm_ring variables [comm_ring R] namespace monic lemma coeff_nat_degree {p : polynomial R} (hp : p.monic) : p.coeff (p.nat_degree) = 1 := hp @[simp] lemma degree_eq_zero_iff_eq_one {p : polynomial R} (hp : p.monic) : p.nat_degree = 0 ↔ p = 1 := begin split; intro h, swap, { rw h, exact nat_degree_one }, have : p = C (p.coeff 0), { rw ← polynomial.degree_le_zero_iff, rwa polynomial.nat_degree_eq_zero_iff_degree_le_zero at h }, rw this, convert C_1, rw ← h, apply hp, end lemma nat_degree_mul [nontrivial R] {p q : polynomial R} (hp : p.monic) (hq : q.monic) : (p * q).nat_degree = p.nat_degree + q.nat_degree := by { apply nat_degree_mul', rw [hp.leading_coeff, hq.leading_coeff], simp } lemma next_coeff_mul {p q : polynomial R} (hp : monic p) (hq : monic q) : next_coeff (p * q) = next_coeff p + next_coeff q := begin classical, by_cases h : nontrivial R, swap, { rw nontrivial_iff at h, push_neg at h, apply h, }, haveI := h, clear h, have := monic.nat_degree_mul hp hq, dsimp only [next_coeff], rw this, simp only [hp, hq, degree_eq_zero_iff_eq_one, add_eq_zero_iff], clear this, split_ifs; try { tauto <|> simp [h_1, h_2] }, rename h_1 hp0, rename h_2 hq0, clear h, rw ← degree_eq_zero_iff_eq_one at hp0 hq0, assumption', -- we've reduced to the case where the degrees dp and dq are nonzero set dp := p.nat_degree, set dq := q.nat_degree, rw coeff_mul, have : {(dp, dq - 1), (dp - 1, dq)} ⊆ nat.antidiagonal (dp + dq - 1), { rw insert_subset, split, work_on_goal 0 { rw [nat.mem_antidiagonal, nat.add_sub_assoc] }, work_on_goal 1 { simp only [singleton_subset_iff, nat.mem_antidiagonal], apply nat.sub_add_eq_add_sub }, all_goals { apply nat.succ_le_of_lt, apply nat.pos_of_ne_zero, assumption } }, rw ← sum_subset this, { rw [sum_insert, sum_singleton], iterate 2 { rw coeff_nat_degree }, ring, assumption', suffices : dp ≠ dp - 1, { rw mem_singleton, simp [this] }, omega }, clear this, intros x hx hx1, simp only [nat.mem_antidiagonal] at hx, simp only [mem_insert, mem_singleton] at hx1, suffices : p.coeff x.fst = 0 ∨ q.coeff x.snd = 0, cases this; simp [this], suffices : dp < x.fst ∨ dq < x.snd, cases this, { left, apply coeff_eq_zero_of_nat_degree_lt, assumption }, { right, apply coeff_eq_zero_of_nat_degree_lt, assumption }, by_cases h : dp < x.fst, { left, exact h }, push_neg at h, right, have : x.fst ≠ dp - 1, { contrapose! hx1, right, ext, assumption, dsimp only, omega }, have : x.fst ≠ dp, { contrapose! hx1, left, ext, assumption, dsimp only, omega }, omega, end lemma next_coeff_prod (s : finset ι) (f : ι → polynomial R) (h : ∀ i ∈ s, monic (f i)) : next_coeff (∏ i in s, f i) = ∑ i in s, next_coeff (f i) := begin classical, revert h, apply finset.induction_on s, { simp only [finset.not_mem_empty, forall_prop_of_true, forall_prop_of_false, finset.sum_empty, finset.prod_empty, not_false_iff, forall_true_iff], rw ← C_1, rw next_coeff_C_eq_zero }, { intros a s ha hs monic, rw finset.prod_insert ha, rw finset.sum_insert ha, rw next_coeff_mul (monic a (finset.mem_insert_self a s)), swap, { apply monic_prod_of_monic, intros b bs, apply monic, apply finset.mem_insert_of_mem bs }, { refine congr rfl (hs _), intros b bs, apply monic, apply finset.mem_insert_of_mem bs }} end end monic end comm_ring section ring variables [ring R] {p : polynomial R} theorem monic_X_sub_C (x : R) : monic (X - C x) := by simpa only [C_neg] using monic_X_add_C (-x) theorem monic_X_pow_sub {n : ℕ} (H : degree p ≤ n) : monic (X ^ (n+1) - p) := monic_X_pow_add ((degree_neg p).symm ▸ H) section injective open function variables [semiring S] {f : R →+* S} (hf : injective f) include hf lemma leading_coeff_of_injective (p : polynomial R) : leading_coeff (p.map f) = f (leading_coeff p) := begin delta leading_coeff, rw [coeff_map f, nat_degree_map' hf p] end lemma monic_of_injective {p : polynomial R} (hp : (p.map f).monic) : p.monic := begin apply hf, rw [← leading_coeff_of_injective hf, hp.leading_coeff, is_semiring_hom.map_one f] end end injective end ring section nonzero_semiring variables [semiring R] [nontrivial R] {p q : polynomial R} @[simp] lemma not_monic_zero : ¬monic (0 : polynomial R) := by simpa only [monic, leading_coeff_zero] using (zero_ne_one : (0 : R) ≠ 1) lemma ne_zero_of_monic (h : monic p) : p ≠ 0 := λ h₁, @not_monic_zero R _ _ (h₁ ▸ h) end nonzero_semiring end polynomial
0acdc78ecf82e8263c89190f15549fdea55d3f25
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/764.lean
6f4d0c5162ebb98d0d817a1e7a3c62e1f9fef3bb
[ "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
86
lean
#eval (5 > 2) == true #eval (2 > 5) == true variable (b : Bool) #check (5 > 2) == b
12416e477eb4a3554a618534cc4d4409d7584927
618003631150032a5676f229d13a079ac875ff77
/src/tactic/omega/lin_comb.lean
d4dbbf6659452fd8d4ac8eee8dab505dcb875b24
[ "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,154
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Seul Baek Linear combination of constraints. -/ import tactic.omega.clause namespace omega /-- Linear combination of constraints. The second argument is the list of constraints, and the first argument is the list of conefficients by which the constraints are multiplied -/ @[simp] def lin_comb : list nat → list term → term | [] [] := ⟨0,[]⟩ | [] (_::_) := ⟨0,[]⟩ | (_::_) [] := ⟨0,[]⟩ | (n::ns) (t::ts) := term.add (t.mul ↑n) (lin_comb ns ts) lemma lin_comb_holds {v : nat → int} : ∀ {ts} ns, (∀ t ∈ ts, 0 ≤ term.val v t) → (0 ≤ (lin_comb ns ts).val v) | [] [] h := by simp only [add_zero, term.val, lin_comb, coeffs.val_nil] | [] (_::_) h := by simp only [add_zero, term.val, lin_comb, coeffs.val_nil] | (_::_) [] h := by simp only [add_zero, term.val, lin_comb, coeffs.val_nil] | (t::ts) (n::ns) h := begin have : 0 ≤ ↑n * term.val v t + term.val v (lin_comb ns ts), { apply add_nonneg, { apply mul_nonneg, apply int.coe_nat_nonneg, apply h _ (or.inl rfl) }, { apply lin_comb_holds, apply list.forall_mem_of_forall_mem_cons h } }, simpa only [lin_comb, term.val_mul, term.val_add], end /-- `unsat_lin_comb ns ts` asserts that the linear combination `lin_comb ns ts` is unsatisfiable -/ def unsat_lin_comb (ns : list nat) (ts : list term) : Prop := (lin_comb ns ts).fst < 0 ∧ ∀ x ∈ (lin_comb ns ts).snd, x = (0 : int) lemma unsat_lin_comb_of (ns : list nat) (ts : list term) : (lin_comb ns ts).fst < 0 → (∀ x ∈ (lin_comb ns ts).snd, x = (0 : int)) → unsat_lin_comb ns ts := by {intros h1 h2, exact ⟨h1,h2⟩} lemma unsat_of_unsat_lin_comb (ns : list nat) (ts : list term) : (unsat_lin_comb ns ts) → clause.unsat ([], ts) := begin intros h1 h2, cases h2 with v h2, have h3 := lin_comb_holds ns h2.right, cases h1 with hl hr, cases (lin_comb ns ts) with b as, unfold term.val at h3, rw [coeffs.val_eq_zero hr, add_zero, ← not_lt] at h3, apply h3 hl end end omega
88305859f7aa85047614a461de71298f05f5878a
ee8cdbabf07f77e7be63a449b8483ce308d37218
/lean/src/valid/mathd-numbertheory-22.lean
d2541ec8c54737572c2f466c3ff9f8cab8fdb376
[ "MIT", "Apache-2.0" ]
permissive
zeta1999/miniF2F
6d66c75d1c18152e224d07d5eed57624f731d4b7
c1ba9629559c5273c92ec226894baa0c1ce27861
refs/heads/main
1,681,897,460,642
1,620,646,361,000
1,620,646,361,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
337
lean
/- Copyright (c) 2021 OpenAI. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kunhao Zheng -/ import data.real.basic import data.nat.basic example (b : ℕ) (h₀ : b < 10) (h₁ : nat.sqrt ( 10 * b + 6 ) * nat.sqrt ( 10 * b + 6 ) = 10 * b + 6 ) : b = 3 ∨ b = 1 := begin sorry end
955d63adeba824e37959bcfa1bc044976b6d8d71
9b9a16fa2cb737daee6b2785474678b6fa91d6d4
/src/category_theory/full_subcategory.lean
21705b5e04cad315717d8d07bb2bb31c14e39772
[ "Apache-2.0" ]
permissive
johoelzl/mathlib
253f46daa30b644d011e8e119025b01ad69735c4
592e3c7a2dfbd5826919b4605559d35d4d75938f
refs/heads/master
1,625,657,216,488
1,551,374,946,000
1,551,374,946,000
98,915,829
0
0
Apache-2.0
1,522,917,267,000
1,501,524,499,000
Lean
UTF-8
Lean
false
false
2,398
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison, Reid Barton import category_theory.fully_faithful namespace category_theory universes v u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation section induced /- Induced categories. Given a category D and a function F : C → D from a type C to the objects of D, there is an essentially unique way to give C a category structure such that F becomes a fully faithful functor, namely by taking Hom_C(X, Y) = Hom_D(FX, FY). We call this the category induced from D along F. As a special case, if C is a subtype of D, this produces the full subcategory of D on the objects belonging to C. In general the induced category is equivalent to the full subcategory of D on the image of F. -/ variables {C : Type u₁} {D : Type u₂} [𝒟 : category.{v u₂} D] include 𝒟 variables (F : C → D) include F def induced_category : Type u₁ := C instance induced_category.category : category.{v} (induced_category F) := { hom := λ X Y, F X ⟶ F Y, id := λ X, 𝟙 (F X), comp := λ _ _ _ f g, f ≫ g } def induced_functor : induced_category F ⥤ D := { obj := F, map := λ x y f, f } @[simp] lemma induced_functor.obj {X} : (induced_functor F).obj X = F X := rfl @[simp] lemma induced_functor.hom {X Y} {f : X ⟶ Y} : (induced_functor F).map f = f := rfl instance induced_category.fully_faithful : fully_faithful (induced_functor F) := { preimage := λ x y f, f } end induced section full_subcategory /- A full subcategory is the special case of an induced category with F = subtype.val. -/ variables {C : Type u₂} [𝒞 : category.{v} C] include 𝒞 variables (Z : C → Prop) instance full_subcategory : category.{v} {X : C // Z X} := induced_category.category subtype.val def full_subcategory_inclusion : {X : C // Z X} ⥤ C := induced_functor subtype.val @[simp] lemma full_subcategory_inclusion.obj {X} : (full_subcategory_inclusion Z).obj X = X.val := rfl @[simp] lemma full_subcategory_inclusion.map {X Y} {f : X ⟶ Y} : (full_subcategory_inclusion Z).map f = f := rfl instance full_subcategory.fully_faithful : fully_faithful (full_subcategory_inclusion Z) := induced_category.fully_faithful subtype.val end full_subcategory end category_theory
bf4ba597959fe6c9bb7cf3ca4fa9295732b9f944
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/hott/algebra/binary.hlean
dab145c8d53ec23cce7780ecaee082ba7aa17c8a
[ "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
4,768
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad General properties of binary operations. -/ open eq.ops function namespace binary section variable {A : Type} variables (op₁ : A → A → A) (inv : A → A) (one : A) local notation a * b := op₁ a b local notation a ⁻¹ := inv a definition commutative [reducible] := Πa b, a * b = b * a definition associative [reducible] := Πa b c, (a * b) * c = a * (b * c) definition left_identity [reducible] := Πa, one * a = a definition right_identity [reducible] := Πa, a * one = a definition left_inverse [reducible] := Πa, a⁻¹ * a = one definition right_inverse [reducible] := Πa, a * a⁻¹ = one definition left_cancelative [reducible] := Πa b c, a * b = a * c → b = c definition right_cancelative [reducible] := Πa b c, a * b = c * b → a = c definition inv_op_cancel_left [reducible] := Πa b, a⁻¹ * (a * b) = b definition op_inv_cancel_left [reducible] := Πa b, a * (a⁻¹ * b) = b definition inv_op_cancel_right [reducible] := Πa b, a * b⁻¹ * b = a definition op_inv_cancel_right [reducible] := Πa b, a * b * b⁻¹ = a variable (op₂ : A → A → A) local notation a + b := op₂ a b definition left_distributive [reducible] := Πa b c, a * (b + c) = a * b + a * c definition right_distributive [reducible] := Πa b c, (a + b) * c = a * c + b * c definition right_commutative [reducible] {B : Type} (f : B → A → B) := Π b a₁ a₂, f (f b a₁) a₂ = f (f b a₂) a₁ definition left_commutative [reducible] {B : Type} (f : A → B → B) := Π a₁ a₂ b, f a₁ (f a₂ b) = f a₂ (f a₁ b) end section variable {A : Type} variable {f : A → A → A} variable H_comm : commutative f variable H_assoc : associative f local infixl `*` := f theorem left_comm : left_commutative f := take a b c, calc a*(b*c) = (a*b)*c : H_assoc ... = (b*a)*c : H_comm ... = b*(a*c) : H_assoc theorem right_comm : right_commutative f := take a b c, calc (a*b)*c = a*(b*c) : H_assoc ... = a*(c*b) : H_comm ... = (a*c)*b : H_assoc theorem comm4 (a b c d : A) : a*b*(c*d) = a*c*(b*d) := calc a*b*(c*d) = a*b*c*d : H_assoc ... = a*c*b*d : right_comm H_comm H_assoc ... = a*c*(b*d) : H_assoc end section variable {A : Type} variable {f : A → A → A} variable H_assoc : associative f local infixl `*` := f theorem assoc4helper (a b c d) : (a*b)*(c*d) = a*((b*c)*d) := calc (a*b)*(c*d) = a*(b*(c*d)) : H_assoc ... = a*((b*c)*d) : H_assoc end definition right_commutative_compose_right [reducible] {A B : Type} (f : A → A → A) (g : B → A) (rcomm : right_commutative f) : right_commutative (compose_right f g) := λ a b₁ b₂, !rcomm definition left_commutative_compose_left [reducible] {A B : Type} (f : A → A → A) (g : B → A) (lcomm : left_commutative f) : left_commutative (compose_left f g) := λ a b₁ b₂, !lcomm end binary open eq namespace is_equiv definition inv_preserve_binary {A B : Type} (f : A → B) [H : is_equiv f] (mA : A → A → A) (mB : B → B → B) (H : Π(a a' : A), mB (f a) (f a') = f (mA a a')) (b b' : B) : f⁻¹ (mB b b') = mA (f⁻¹ b) (f⁻¹ b') := begin have H2 : f⁻¹ (mB (f (f⁻¹ b)) (f (f⁻¹ b'))) = f⁻¹ (f (mA (f⁻¹ b) (f⁻¹ b'))), from ap f⁻¹ !H, rewrite [+right_inv f at H2,left_inv f at H2,▸* at H2,H2] end definition preserve_binary_of_inv_preserve {A B : Type} (f : A → B) [H : is_equiv f] (mA : A → A → A) (mB : B → B → B) (H : Π(b b' : B), mA (f⁻¹ b) (f⁻¹ b') = f⁻¹ (mB b b')) (a a' : A) : f (mA a a') = mB (f a) (f a') := begin have H2 : f (mA (f⁻¹ (f a)) (f⁻¹ (f a'))) = f (f⁻¹ (mB (f a) (f a'))), from ap f !H, rewrite [right_inv f at H2,+left_inv f at H2,▸* at H2,H2] end end is_equiv namespace equiv open is_equiv equiv.ops definition inv_preserve_binary {A B : Type} (f : A ≃ B) (mA : A → A → A) (mB : B → B → B) (H : Π(a a' : A), mB (f a) (f a') = f (mA a a')) (b b' : B) : f⁻¹ (mB b b') = mA (f⁻¹ b) (f⁻¹ b') := inv_preserve_binary f mA mB H b b' definition preserve_binary_of_inv_preserve {A B : Type} (f : A ≃ B) (mA : A → A → A) (mB : B → B → B) (H : Π(b b' : B), mA (f⁻¹ b) (f⁻¹ b') = f⁻¹ (mB b b')) (a a' : A) : f (mA a a') = mB (f a) (f a') := preserve_binary_of_inv_preserve f mA mB H a a' end equiv
d827ab162f88f2d7eedecf906362d493b628adfd
b392eb79fb36952401156496daa60628ccb07438
/MathPort/Util.lean
73d0d67999d7703a8eb05f912780879302f3a08b
[ "Apache-2.0" ]
permissive
AurelienSaue/mathportsource
d9eabe74e3ab7774baa6a10a6dc8d4855ff92266
1a164e4fff7204c522c1f4ecc5024fd909be3b0b
refs/heads/master
1,685,214,377,305
1,623,621,223,000
1,623,621,223,000
364,191,042
0
0
null
null
null
null
UTF-8
Lean
false
false
5,423
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Daniel Selsam -/ import Lean partial def Array.write {α} [Inhabited α] : ∀ (arr : Array α) (i : Nat) (x : α), Array α | arr, i, x => if i = arr.size then arr.push x else if i > arr.size then write (arr.push arbitrary) i x else arr.set! i x def Array.take {α} (xs : Array α) (i : Nat) : Array α := (xs.toList.take i).toArray def Array.splitAt {α} (xs : Array α) (i : Nat) : Array α × Array α := ((xs.toList.take i).toArray, (xs.toList.drop i).toArray) def List.splitAt {α} (xs : List α) (i : Nat) : List α × List α := (xs.take i, xs.drop i) def Lean.Declaration.names : Lean.Declaration → List Lean.Name | axiomDecl v => [v.name] | defnDecl v => [v.name] | thmDecl v => [v.name] | opaqueDecl v => [v.name] | quotDecl => [] | mutualDefnDecl vs => vs.map (fun v => v.name) | inductDecl _ _ is _ => is.map (fun i => i.name) def Lean.Expr.replaceConstNames (f : Name → Name) (e : Expr) : Expr := let x := e.replace fun | e@(const n us _) => if f n == n then none else some (mkConst (f n) us) | _ => none x def parseName (n : String) : Lean.Name := (n.splitOn ".").foldl Lean.Name.mkStr Lean.Name.anonymous namespace Std.HashMap variable {α : Type u} {β : Type v} [BEq α] [Hashable α] -- TODO: faster version def insertWith (m : HashMap α β) (merge : β → β → β) (a : α) (b : β) : HashMap α β := match m.find? a with | none => m.insert a b | some c => m.insert a (merge c b) def fromList (kvs : List (α × β)) : HashMap α β := do let mut hm : HashMap α β := {} for (k, v) in kvs do hm := hm.insert k v return hm end Std.HashMap def createDirectoriesIfNotExists (outFilename : String) : IO Unit := do match System.FilePath.parent outFilename with | none => throw $ IO.userError "shouldn't happen" | some d => let s := { cmd := "mkdir", args := #["-p", d] } let status ← IO.Process.run s pure () section Loop structure Loop where variable {β : Type u} {m : Type u → Type v} [Monad m] @[inline] partial def Loop.forIn (loop : Loop) (init : β) (f : Unit → β → m (ForInStep β)) : m β := let rec @[specialize] loop (b : β) : m β := do match ← f () b with | ForInStep.done b => pure b | ForInStep.yield b => loop b loop init instance : ForIn m Loop Unit := ⟨Loop.forIn⟩ end Loop syntax "repeat " doSeq : doElem macro_rules | `(doElem| repeat $seq) => `(doElem| for _ in Loop.mk do $seq) syntax "while " termBeforeDo " do " doSeq : doElem macro_rules | `(doElem| while $cond do $seq) => `(doElem| repeat if $cond then $seq else break) namespace IO.FS variable [Monad m] [MonadLiftT IO m] @[inline] def forEachLine (fileName : String) (f : String → m Unit) : m Unit := IO.FS.withFile fileName IO.FS.Mode.read fun h => do while (not (← h.isEof)) do let line := (← h.getLine).dropRightWhile λ c => c == '\n' if line == "" then continue else f line end IO.FS section AutoParam open Lean Lean.Meta -- TODO: ToExpr instance for Syntax def obviouslySyntax : Expr := do mkAppN (mkConst `Lean.Syntax.ident) #[ mkConst `Lean.SourceInfo.none, mkApp (mkConst `String.toSubstring) (toExpr "obviously"), toExpr `Mathlib.obviously, toExpr ([] : List (Prod Name (List String))) ] end AutoParam section DecodeName open Lean -- Awkward: this section refers to names that are created during the port -- Alternatively, could do this more principledly in PrePort def decodeChar (e : Expr) : MetaM Char := do if e.isAppOfArity `Mathlib.char.mk 2 then match (e.getArg! 0).natLit? with | some n => Char.ofNat n | _ => throwError "[decodeChar] failed on {e}" else throwError "[decodeChar] failed on {e}" partial def decodeStringCore (e : Expr) : MetaM String := do if e.isAppOfArity `List.nil 1 then "" else if e.isAppOfArity `List.cons 3 then let s ← decodeStringCore (e.getArg! 2) let c ← decodeChar (e.getArg! 1) pure ⟨c :: s.data⟩ else throwError "[decodeStringCore] failed on {e}" def decodeUnsigned (e : Expr) : MetaM Nat := if e.isAppOfArity `Mathlib.fin.mk 2 then match (e.getArg! 0).natLit? with | some n => n | _ => throwError "[decodeUInt32] failed on {e}" else throwError "[decodeUInt32] failed on {e}" def decodeString (e : Expr) : MetaM String := do if e.isAppOfArity `Mathlib.string_imp.mk 1 then decodeStringCore (e.getArg! 0) else throwError "[decodeString] failed on {e}" partial def decodeName (e : Expr) : MetaM Name := do if e.isAppOfArity `Mathlib.name.anonymous 0 then Name.anonymous else if e.isAppOfArity `Mathlib.name.mk_string 2 then Name.mkStr (← decodeName (e.getArg! 1)) (← decodeString (e.getArg! 0)) else if e.isAppOfArity `Mathlib.name.mk_numeral 2 then Name.mkNum (← decodeName (e.getArg! 1)) (← decodeUnsigned (e.getArg! 0)) else throwError "[decodeName] failed on {e}" end DecodeName section Reducibility open Lean def reducibilityToName (status : ReducibilityStatus) : Name := match status with | ReducibilityStatus.reducible => `reducible | ReducibilityStatus.semireducible => `semireducible | ReducibilityStatus.irreducible => `irreducible end Reducibility
20c34c2ea579d7342090566e1cdf40b76800e199
b147e1312077cdcfea8e6756207b3fa538982e12
/tactic/split_ifs.lean
3a106b2a81582d514f8a00610e5b2c67f04c0c0b
[ "Apache-2.0" ]
permissive
SzJS/mathlib
07836ee708ca27cd18347e1e11ce7dd5afb3e926
23a5591fca0d43ee5d49d89f6f0ee07a24a6ca29
refs/heads/master
1,584,980,332,064
1,532,063,841,000
1,532,063,841,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,911
lean
/- Copyright (c) 2018 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner. Tactic to split if-then-else-expressions. -/ open expr tactic namespace tactic open interactive meta def find_if_cond : expr → option expr | e := e.fold none $ λ e _ acc, acc <|> do c ← match e with | `(@ite %%c %%_ _ _ _) := some c | `(@dite %%c %%_ _ _ _) := some c | _ := none end, guard ¬c.has_var, find_if_cond c <|> return c meta def find_if_cond_at (at_ : loc) : tactic (option expr) := do lctx ← at_.get_locals, lctx ← lctx.mmap infer_type, tgt ← target, let es := if at_.include_goal then tgt::lctx else lctx, return $ find_if_cond $ es.foldr app (default expr) run_cmd mk_simp_attr `split_if_reduction attribute [split_if_reduction] if_pos if_neg dif_pos dif_neg meta def reduce_ifs_at (at_ : loc) : tactic unit := do sls ← get_user_simp_lemmas `split_if_reduction, let cfg : simp_config := { fail_if_unchanged := ff }, let discharger := assumption <|> (applyc `not_not_intro >> assumption), hs ← at_.get_locals, hs.mmap' (λ h, simp_hyp sls [] h cfg discharger >> skip), when at_.include_goal (simp_target sls [] cfg discharger) meta def split_if1 (c : expr) (n : name) (at_ : loc) : tactic unit := by_cases c n; reduce_ifs_at at_ private meta def get_next_name (names : ref (list name)) : tactic name := do ns ← read_ref names, match ns with | [] := get_unused_name `h | n::ns := do write_ref names ns, return n end private meta def value_known (c : expr) : tactic bool := do lctx ← local_context, lctx ← lctx.mmap infer_type, return $ c ∈ lctx ∨ `(¬%%c) ∈ lctx private meta def split_ifs_core (at_ : loc) (names : ref (list name)) : tactic unit := do some cond ← find_if_cond_at at_ | fail "no if-then-else expressions to split", let cond := match cond with `(¬%%p) := p | p := p end, no_split ← value_known cond, if no_split then reduce_ifs_at at_; try split_ifs_core else do n ← get_next_name names, split_if1 cond n at_; try split_ifs_core meta def split_ifs (names : list name) (at_ : loc := loc.ns [none]) := using_new_ref names (split_ifs_core at_) namespace interactive open interactive interactive.types expr lean.parser /-- Splits all if-then-else-expressions into multiple goals. Given a goal of the form `g (if p then x else y)`, `split_ifs` will produce two goals: `p ⊢ g x` and `¬p ⊢ g y`. If there are multiple ite-expressions, then `split_ifs` will split them all, starting with a top-most one whose condition does not contain another ite-expression. `split_ifs at *` splits all ite-expressions in all hypotheses as well as the goal. `split_ifs with h₁ h₂ h₃` overrides the default names for the hypotheses. -/ meta def split_ifs (at_ : parse location) (names : parse with_ident_list) : tactic unit := tactic.split_ifs names at_ end interactive end tactic
92794ab9e32795386dbbe1ea069562c7ac44f895
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/normed_space/algebra.lean
62336f754f7b89142b5145ef260a0d107f544754
[ "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,650
lean
/- Copyright (c) 2022 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 topology.algebra.module.character_space import analysis.normed_space.weak_dual import analysis.normed_space.spectrum /-! # Normed algebras This file contains basic facts about normed algebras. ## Main results * We show that the character space of a normed algebra is compact using the Banach-Alaoglu theorem. ## TODO * Show compactness for topological vector spaces; this requires the TVS version of Banach-Alaoglu. ## Tags normed algebra, character space, continuous functional calculus -/ variables {𝕜 : Type*} {A : Type*} namespace weak_dual namespace character_space variables [nontrivially_normed_field 𝕜] [normed_ring A] [normed_algebra 𝕜 A] [complete_space A] lemma norm_le_norm_one (φ : character_space 𝕜 A) : ‖to_normed_dual (φ : weak_dual 𝕜 A)‖ ≤ ‖(1 : A)‖ := continuous_linear_map.op_norm_le_bound _ (norm_nonneg (1 : A)) $ λ a, mul_comm (‖a‖) (‖(1 : A)‖) ▸ spectrum.norm_le_norm_mul_of_mem (apply_mem_spectrum φ a) instance [proper_space 𝕜] : compact_space (character_space 𝕜 A) := begin rw [←is_compact_iff_compact_space], have h : character_space 𝕜 A ⊆ to_normed_dual ⁻¹' metric.closed_ball 0 (‖(1 : A)‖), { intros φ hφ, rw [set.mem_preimage, mem_closed_ball_zero_iff], exact (norm_le_norm_one ⟨φ, ⟨hφ.1, hφ.2⟩⟩ : _), }, exact is_compact_of_is_closed_subset (is_compact_closed_ball 𝕜 0 _) character_space.is_closed h, end end character_space end weak_dual
151258d67d64899207a2938ee2edb78f9ae98ef9
f7315930643edc12e76c229a742d5446dad77097
/library/data/rat/basic.lean
95e69df8c2173c33719d501a049e0e5ff1397202
[ "Apache-2.0" ]
permissive
bmalehorn/lean
8f77b762a76c59afff7b7403f9eb5fc2c3ce70c1
53653c352643751c4b62ff63ec5e555f11dae8eb
refs/heads/master
1,610,945,684,489
1,429,681,220,000
1,429,681,449,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,867
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: data.rat.basic Author: Jeremy Avigad The rational numbers as a field generated by the integers, defined as the usual quotient. -/ import data.int algebra.field open int quot eq.ops record prerat : Type := (num : ℤ) (denom : ℤ) (denom_pos : denom > 0) /- prerat: the representations of the rationals as integers num, denom, with denom > 0. note: names are not protected, because it is not expected that users will open prerat. -/ namespace prerat /- the equivalence relation -/ definition equiv (a b : prerat) : Prop := num a * denom b = num b * denom a local infix `≡` := equiv theorem equiv.refl (a : prerat) : a ≡ a := rfl theorem equiv.symm {a b : prerat} (H : a ≡ b) : b ≡ a := !eq.symm H calc_refl equiv.refl calc_symm equiv.symm theorem num_eq_zero_of_equiv {a b : prerat} (H : a ≡ b) (na_zero : num a = 0) : num b = 0 := have H1 : num a * denom b = 0, from !zero_mul ▸ na_zero ▸ rfl, have H2 : num b * denom a = 0, from H ▸ H1, show num b = 0, from or_resolve_left (eq_zero_or_eq_zero_of_mul_eq_zero H2) (ne_of_gt (denom_pos a)) theorem num_pos_of_equiv {a b : prerat} (H : a ≡ b) (na_pos : num a > 0) : num b > 0 := have H1 : num a * denom b > 0, from mul_pos na_pos (denom_pos b), have H2 : num b * denom a > 0, from H ▸ H1, show num b > 0, from pos_of_mul_pos_right H2 (le_of_lt (denom_pos a)) theorem num_neg_of_equiv {a b : prerat} (H : a ≡ b) (na_neg : num a < 0) : num b < 0 := have H1 : num a * denom b < 0, from mul_neg_of_neg_of_pos na_neg (denom_pos b), have H2 : -(-num b * denom a) < 0, from !neg_mul_eq_neg_mul⁻¹ ▸ !neg_neg⁻¹ ▸ H ▸ H1, have H3 : -num b > 0, from pos_of_mul_pos_right (pos_of_neg_neg H2) (le_of_lt (denom_pos a)), neg_of_neg_pos H3 theorem equiv_of_num_eq_zero {a b : prerat} (H1 : num a = 0) (H2 : num b = 0) : a ≡ b := by rewrite [↑equiv, H1, H2, *zero_mul] theorem equiv.trans {a b c : prerat} (H1 : a ≡ b) (H2 : b ≡ c) : a ≡ c := decidable.by_cases (assume b0 : num b = 0, have a0 : num a = 0, from num_eq_zero_of_equiv (equiv.symm H1) b0, have c0 : num c = 0, from num_eq_zero_of_equiv H2 b0, equiv_of_num_eq_zero a0 c0) (assume bn0 : num b ≠ 0, have H3 : num b * denom b ≠ 0, from mul_ne_zero bn0 (ne_of_gt (denom_pos b)), have H4 : (num b * denom b) * (num a * denom c) = (num b * denom b) * (num c * denom a), from calc (num b * denom b) * (num a * denom c) = (num a * denom b) * (num b * denom c) : by rewrite [*mul.assoc, *mul.left_comm (num a), *mul.left_comm (num b)] ... = (num b * denom a) * (num b * denom c) : {H1} ... = (num b * denom a) * (num c * denom b) : {H2} ... = (num b * denom b) * (num c * denom a) : by rewrite [*mul.assoc, *mul.left_comm (denom a), *mul.left_comm (denom b), mul.comm (denom a)], mul.cancel_left H3 H4) calc_refl equiv.refl calc_symm equiv.symm calc_trans equiv.trans theorem equiv.is_equivalence : equivalence equiv := mk_equivalence equiv equiv.refl @equiv.symm @equiv.trans definition setoid : setoid prerat := setoid.mk equiv equiv.is_equivalence /- field operations -/ private theorem of_nat_succ_pos (n : nat) : of_nat (nat.succ n) > 0 := of_nat_pos !nat.succ_pos definition of_int (i : int) : prerat := prerat.mk i 1 !of_nat_succ_pos definition zero : prerat := of_int 0 definition one : prerat := of_int 1 private theorem mul_denom_pos (a b : prerat) : denom a * denom b > 0 := mul_pos (denom_pos a) (denom_pos b) definition add (a b : prerat) : prerat := prerat.mk (num a * denom b + num b * denom a) (denom a * denom b) (mul_denom_pos a b) definition mul (a b : prerat) : prerat := prerat.mk (num a * num b) (denom a * denom b) (mul_denom_pos a b) definition neg (a : prerat) : prerat := prerat.mk (- num a) (denom a) (denom_pos a) definition inv : prerat → prerat | inv (prerat.mk nat.zero d dp) := zero | inv (prerat.mk (nat.succ n) d dp) := prerat.mk d (nat.succ n) !of_nat_succ_pos | inv (prerat.mk -[n +1] d dp) := prerat.mk (-d) (nat.succ n) !of_nat_succ_pos theorem equiv_zero_of_num_eq_zero {a : prerat} (H : num a = 0) : a ≡ zero := by rewrite [↑equiv, H, ↑zero, ↑num, ↑of_int, *zero_mul] theorem num_eq_zero_of_equiv_zero {a : prerat} : a ≡ zero → num a = 0 := by rewrite [↑equiv, ↑zero, ↑of_int, mul_one, zero_mul]; intro H; exact H theorem inv_zero {d : int} (dp : d > 0) : inv (mk nat.zero d dp) = zero := begin rewrite [↑inv, ↑int.cases_on, ↑cases_on, ▸*] end theorem inv_zero' : inv zero = zero := inv_zero (of_nat_succ_pos nat.zero) theorem inv_of_pos {n d : int} (np : n > 0) (dp : d > 0) : inv (mk n d dp) ≡ mk d n np := obtain (n' : nat) (Hn' : n = of_nat n'), from exists_eq_of_nat (le_of_lt np), have H1 : (#nat n' > nat.zero), from lt_of_of_nat_lt_of_nat (Hn' ▸ np), obtain (k : nat) (Hk : n' = nat.succ k), from nat.exists_eq_succ_of_lt H1, have H2 : d * n = d * nat.succ k, by rewrite [Hn', Hk], Hn'⁻¹ ▸ (Hk⁻¹ ▸ H2) theorem inv_neg {n d : int} (np : n > 0) (dp : d > 0) : inv (mk (-n) d dp) ≡ mk (-d) n np := obtain (n' : nat) (Hn' : n = of_nat n'), from exists_eq_of_nat (le_of_lt np), have H1 : (#nat n' > nat.zero), from lt_of_of_nat_lt_of_nat (Hn' ▸ np), obtain (k : nat) (Hk : n' = nat.succ k), from nat.exists_eq_succ_of_lt H1, have H2 : -d * n = -d * nat.succ k, by rewrite [Hn', Hk], have H3 : inv (mk -[k +1] d dp) ≡ mk (-d) n np, from H2, have H4 : -[k +1] = -n, from calc -[k +1] = -(nat.succ k) : rfl ... = -n : by rewrite [Hk⁻¹, Hn'], H4 ▸ H3 theorem inv_of_neg {n d : int} (nn : n < 0) (dp : d > 0) : inv (mk n d dp) ≡ mk (-d) (-n) (neg_pos_of_neg nn) := have H : inv (mk (-(-n)) d dp) ≡ mk (-d) (-n) (neg_pos_of_neg nn), from inv_neg (neg_pos_of_neg nn) dp, !neg_neg ▸ H /- operations respect equiv -/ theorem add_equiv_add {a1 b1 a2 b2 : prerat} (eqv1 : a1 ≡ a2) (eqv2 : b1 ≡ b2) : add a1 b1 ≡ add a2 b2 := calc (num a1 * denom b1 + num b1 * denom a1) * (denom a2 * denom b2) = num a1 * denom a2 * denom b1 * denom b2 + num b1 * denom b2 * denom a1 * denom a2 : by rewrite [mul.right_distrib, *mul.assoc, mul.left_comm (denom b1), mul.comm (denom b2), *mul.assoc] ... = num a2 * denom a1 * denom b1 * denom b2 + num b2 * denom b1 * denom a1 * denom a2 : by rewrite [↑equiv at *, eqv1, eqv2] ... = (num a2 * denom b2 + num b2 * denom a2) * (denom a1 * denom b1) : by rewrite [mul.right_distrib, *mul.assoc, *mul.left_comm (denom b2), *mul.comm (denom b1), *mul.assoc, mul.left_comm (denom a2)] theorem mul_equiv_mul {a1 b1 a2 b2 : prerat} (eqv1 : a1 ≡ a2) (eqv2 : b1 ≡ b2) : mul a1 b1 ≡ mul a2 b2 := calc (num a1 * num b1) * (denom a2 * denom b2) = (num a1 * denom a2) * (num b1 * denom b2) : by rewrite [*mul.assoc, mul.left_comm (num b1)] ... = (num a2 * denom a1) * (num b2 * denom b1) : by rewrite [↑equiv at *, eqv1, eqv2] ... = (num a2 * num b2) * (denom a1 * denom b1) : by rewrite [*mul.assoc, mul.left_comm (num b2)] theorem neg_equiv_neg {a b : prerat} (eqv : a ≡ b) : neg a ≡ neg b := calc -num a * denom b = -(num a * denom b) : neg_mul_eq_neg_mul ... = -(num b * denom a) : {eqv} ... = -num b * denom a : neg_mul_eq_neg_mul theorem inv_equiv_inv : ∀{a b : prerat}, a ≡ b → inv a ≡ inv b | (mk an ad adp) (mk bn bd bdp) := assume H, lt.by_cases (assume an_neg : an < 0, have bn_neg : bn < 0, from num_neg_of_equiv H an_neg, calc inv (mk an ad adp) ≡ mk (-ad) (-an) (neg_pos_of_neg an_neg) : inv_of_neg an_neg adp ... ≡ mk (-bd) (-bn) (neg_pos_of_neg bn_neg) : by rewrite [↑equiv at *, ▸*, *neg_mul_neg, mul.comm ad, mul.comm bd, H] ... ≡ inv (mk bn bd bdp) : inv_of_neg bn_neg bdp) (assume an_zero : an = 0, have bn_zero : bn = 0, from num_eq_zero_of_equiv H an_zero, eq.subst (calc inv (mk an ad adp) = inv (mk 0 ad adp) : {an_zero} ... = zero : inv_zero ... = inv (mk 0 bd bdp) : inv_zero ... = inv (mk bn bd bdp) : bn_zero) !equiv.refl) (assume an_pos : an > 0, have bn_pos : bn > 0, from num_pos_of_equiv H an_pos, calc inv (mk an ad adp) ≡ mk ad an an_pos : inv_of_pos an_pos adp ... ≡ mk bd bn bn_pos : by rewrite [↑equiv at *, ▸*, mul.comm ad, mul.comm bd, H] ... ≡ inv (mk bn bd bdp) : inv_of_pos bn_pos bdp) /- properties -/ theorem add.comm (a b : prerat) : add a b ≡ add b a := by rewrite [↑add, ↑equiv, ▸*, add.comm, mul.comm (denom a)] theorem add.assoc (a b c : prerat) : add (add a b) c ≡ add a (add b c) := by rewrite [↑add, ↑equiv, ▸*, *(mul.comm (num c)), *(λy, mul.comm y (denom a)), *mul.left_distrib, *mul.right_distrib, *mul.assoc, *add.assoc] theorem add_zero (a : prerat) : add a zero ≡ a := by rewrite [↑add, ↑equiv, ↑zero, ↑of_int, ▸*, *mul_one, zero_mul, add_zero] theorem add.left_inv (a : prerat) : add (neg a) a ≡ zero := by rewrite [↑add, ↑equiv, ↑neg, ↑zero, ↑of_int, ▸*, -neg_mul_eq_neg_mul, add.left_inv, *zero_mul] theorem mul.comm (a b : prerat) : mul a b ≡ mul b a := by rewrite [↑mul, ↑equiv, mul.comm (num a), mul.comm (denom a)] theorem mul.assoc (a b c : prerat) : mul (mul a b) c ≡ mul a (mul b c) := by rewrite [↑mul, ↑equiv, *mul.assoc] theorem mul_one (a : prerat) : mul a one ≡ a := by rewrite [↑mul, ↑one, ↑of_int, ↑equiv, ▸*, *mul_one] -- with the simplifier this will be easy theorem mul.left_distrib (a b c : prerat) : mul a (add b c) ≡ add (mul a b) (mul a c) := begin rewrite [↑mul, ↑add, ↑equiv, ▸*, *mul.left_distrib, *mul.right_distrib, -*int.mul.assoc], apply sorry end theorem mul_inv_cancel : ∀{a : prerat}, ¬ a ≡ zero → mul a (inv a) ≡ one | (mk an ad adp) := assume H, let a := mk an ad adp in lt.by_cases (assume an_neg : an < 0, let ia := mk (-ad) (-an) (neg_pos_of_neg an_neg) in calc mul a (inv a) ≡ mul a ia : mul_equiv_mul !equiv.refl (inv_of_neg an_neg adp) ... ≡ one : begin esimp [equiv, num, denom, one, mul, of_int], rewrite [*int.mul_one, *int.one_mul, int.mul.comm, neg_mul_comm] end) (assume an_zero : an = 0, absurd (equiv_zero_of_num_eq_zero an_zero) H) (assume an_pos : an > 0, let ia := mk ad an an_pos in calc mul a (inv a) ≡ mul a ia : mul_equiv_mul !equiv.refl (inv_of_pos an_pos adp) ... ≡ one : begin esimp [equiv, num, denom, one, mul, of_int], rewrite [*int.mul_one, *int.one_mul, int.mul.comm] end) theorem zero_not_equiv_one : ¬ zero ≡ one := begin esimp [equiv, zero, one, of_int], rewrite [zero_mul, int.mul_one], exact zero_ne_one end end prerat /- the rationals -/ definition rat : Type.{1} := quot prerat.setoid notation `ℚ` := rat local attribute prerat.setoid [instance] namespace rat /- operations -/ -- these coercions do not work: rat is not an inductive type definition of_int [coercion] (i : ℤ) : ℚ := ⟦prerat.of_int i⟧ definition of_nat [coercion] (n : ℕ) : ℚ := ⟦prerat.of_int n⟧ definition of_num [coercion] [reducible] (n : num) : ℚ := of_int (int.of_num n) definition add : ℚ → ℚ → ℚ := quot.lift₂ (λa b : prerat, ⟦prerat.add a b⟧) (take a1 a2 b1 b2, assume H1 H2, quot.sound (prerat.add_equiv_add H1 H2)) definition mul : ℚ → ℚ → ℚ := quot.lift₂ (λa b : prerat, ⟦prerat.mul a b⟧) (take a1 a2 b1 b2, assume H1 H2, quot.sound (prerat.mul_equiv_mul H1 H2)) definition neg : ℚ → ℚ := quot.lift (λa : prerat, ⟦prerat.neg a⟧) (take a1 a2, assume H, quot.sound (prerat.neg_equiv_neg H)) definition inv : ℚ → ℚ := quot.lift (λa : prerat, ⟦prerat.inv a⟧) (take a1 a2, assume H, quot.sound (prerat.inv_equiv_inv H)) definition zero := ⟦prerat.zero⟧ definition one := ⟦prerat.one⟧ infix `+` := rat.add infix `*` := rat.mul prefix `-` := rat.neg postfix `⁻¹` := rat.inv -- TODO: this is a workaround, since the coercions from numerals do not work local notation 0 := zero local notation 1 := one /- properties -/ theorem add.comm (a b : ℚ) : a + b = b + a := quot.induction_on₂ a b (take u v, quot.sound !prerat.add.comm) theorem add.assoc (a b c : ℚ) : a + b + c = a + (b + c) := quot.induction_on₃ a b c (take u v w, quot.sound !prerat.add.assoc) theorem add_zero (a : ℚ) : a + 0 = a := quot.induction_on a (take u, quot.sound !prerat.add_zero) theorem zero_add (a : ℚ) : 0 + a = a := !add.comm ▸ !add_zero theorem add.left_inv (a : ℚ) : -a + a = 0 := quot.induction_on a (take u, quot.sound !prerat.add.left_inv) theorem mul.comm (a b : ℚ) : a * b = b * a := quot.induction_on₂ a b (take u v, quot.sound !prerat.mul.comm) theorem mul.assoc (a b c : ℚ) : a * b * c = a * (b * c) := quot.induction_on₃ a b c (take u v w, quot.sound !prerat.mul.assoc) theorem mul_one (a : ℚ) : a * 1 = a := quot.induction_on a (take u, quot.sound !prerat.mul_one) theorem one_mul (a : ℚ) : 1 * a = a := !mul.comm ▸ !mul_one theorem mul.left_distrib (a b c : ℚ) : a * (b + c) = a * b + a * c := quot.induction_on₃ a b c (take u v w, quot.sound !prerat.mul.left_distrib) theorem mul.right_distrib (a b c : ℚ) : (a + b) * c = a * c + b * c := by rewrite [mul.comm, mul.left_distrib, *mul.comm c] theorem mul_inv_cancel {a : ℚ} : a ≠ 0 → a * a⁻¹ = 1 := quot.induction_on a (take u, assume H, quot.sound (!prerat.mul_inv_cancel (assume H1, H (quot.sound H1)))) theorem inv_mul_cancel {a : ℚ} (H : a ≠ 0) : a⁻¹ * a = 1 := !mul.comm ▸ mul_inv_cancel H theorem zero_ne_one : (#rat 0 ≠ 1) := assume H, prerat.zero_not_equiv_one (quot.exact H) definition has_decidable_eq [instance] : decidable_eq ℚ := take a b, quot.rec_on_subsingleton₂ a b (take u v, if H : prerat.num u * prerat.denom v = prerat.num v * prerat.denom u then decidable.inl (quot.sound H) else decidable.inr (assume H1, H (quot.exact H1))) theorem inv_zero : inv 0 = 0 := quot.sound (prerat.inv_zero' ▸ !prerat.equiv.refl) section open [classes] algebra protected definition discrete_field [instance] [reducible] : algebra.discrete_field rat := ⦃algebra.discrete_field, add := add, add_assoc := add.assoc, zero := 0, zero_add := zero_add, add_zero := add_zero, neg := neg, add_left_inv := add.left_inv, add_comm := add.comm, mul := mul, mul_assoc := mul.assoc, one := (of_num 1), one_mul := one_mul, mul_one := mul_one, left_distrib := mul.left_distrib, right_distrib := mul.right_distrib, mul_comm := mul.comm, mul_inv_cancel := @mul_inv_cancel, inv_mul_cancel := @inv_mul_cancel, zero_ne_one := zero_ne_one, inv_zero := inv_zero, has_decidable_eq := has_decidable_eq⦄ migrate from algebra with rat end end rat
4c45714f5c6a1b25497675c9fb0da6db645ceca6
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/ring_theory/nilpotent.lean
fa696e0fba5332d01a988e41942f042fa46eb179
[ "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,400
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import data.nat.choose.sum import algebra.algebra.basic /-! # Nilpotent elements ## Main definitions * `is_nilpotent` * `is_nilpotent_neg_iff` * `commute.is_nilpotent_add` * `commute.is_nilpotent_mul_left` * `commute.is_nilpotent_mul_right` * `commute.is_nilpotent_sub` -/ universes u v variables {R : Type u} {x y : R} /-- An element is said to be nilpotent if some natural-number-power of it equals zero. Note that we require only the bare minimum assumptions for the definition to make sense. Even `monoid_with_zero` is too strong since nilpotency is important in the study of rings that are only power-associative. -/ def is_nilpotent [has_zero R] [has_pow R ℕ] (x : R) : Prop := ∃ (n : ℕ), x^n = 0 lemma is_nilpotent.zero [monoid_with_zero R] : is_nilpotent (0 : R) := ⟨1, pow_one 0⟩ lemma is_nilpotent.neg [ring R] (h : is_nilpotent x) : is_nilpotent (-x) := begin obtain ⟨n, hn⟩ := h, use n, rw [neg_pow, hn, mul_zero], end @[simp] lemma is_nilpotent_neg_iff [ring R] : is_nilpotent (-x) ↔ is_nilpotent x := ⟨λ h, neg_neg x ▸ h.neg, λ h, h.neg⟩ lemma is_nilpotent.eq_zero [monoid_with_zero R] [no_zero_divisors R] (h : is_nilpotent x) : x = 0 := by { obtain ⟨n, hn⟩ := h, exact pow_eq_zero hn, } @[simp] lemma is_nilpotent_iff_eq_zero [monoid_with_zero R] [no_zero_divisors R] : is_nilpotent x ↔ x = 0 := ⟨λ h, h.eq_zero, λ h, h.symm ▸ is_nilpotent.zero⟩ namespace commute section semiring variables [semiring R] (h_comm : commute x y) include h_comm lemma is_nilpotent_add (hx : is_nilpotent x) (hy : is_nilpotent y) : is_nilpotent (x + y) := begin obtain ⟨n, hn⟩ := hx, obtain ⟨m, hm⟩ := hy, use n + m - 1, rw h_comm.add_pow', apply finset.sum_eq_zero, rintros ⟨i, j⟩ hij, suffices : x^i * y^j = 0, { simp only [this, nsmul_eq_mul, mul_zero], }, cases nat.le_or_le_of_add_eq_add_pred (finset.nat.mem_antidiagonal.mp hij) with hi hj, { rw [pow_eq_zero_of_le hi hn, zero_mul], }, { rw [pow_eq_zero_of_le hj hm, mul_zero], }, end lemma is_nilpotent_mul_left (h : is_nilpotent x) : is_nilpotent (x * y) := begin obtain ⟨n, hn⟩ := h, use n, rw [h_comm.mul_pow, hn, zero_mul], end lemma is_nilpotent_mul_right (h : is_nilpotent y) : is_nilpotent (x * y) := by { rw h_comm.eq, exact h_comm.symm.is_nilpotent_mul_left h, } end semiring section ring variables [ring R] (h_comm : commute x y) include h_comm lemma is_nilpotent_sub (hx : is_nilpotent x) (hy : is_nilpotent y) : is_nilpotent (x - y) := begin rw ← neg_right_iff at h_comm, rw ← is_nilpotent_neg_iff at hy, rw sub_eq_add_neg, exact h_comm.is_nilpotent_add hx hy, end end ring end commute namespace algebra variables (R) {A : Type v} [comm_semiring R] [semiring A] [algebra R A] @[simp] lemma is_nilpotent_lmul_left_iff (a : A) : is_nilpotent (lmul_left R a) ↔ is_nilpotent a := begin split; rintros ⟨n, hn⟩; use n; simp only [lmul_left_eq_zero_iff, pow_lmul_left] at ⊢ hn; exact hn, end @[simp] lemma is_nilpotent_lmul_right_iff (a : A) : is_nilpotent (lmul_right R a) ↔ is_nilpotent a := begin split; rintros ⟨n, hn⟩; use n; simp only [lmul_right_eq_zero_iff, pow_lmul_right] at ⊢ hn; exact hn, end end algebra
2b6855ea6e9312e351ff09c443d1c77ce69596e5
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/category_theory/arrow.lean
e95092f6dfb3fde6cabe9c1637db6027221c3144
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
7,722
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 category_theory.comma /-! # The category of arrows The category of arrows, with morphisms commutative squares. We set this up as a specialization of the comma category `comma L R`, where `L` and `R` are both the identity functor. We also define the typeclass `has_lift`, representing a choice of a lift of a commutative square (that is, a diagonal morphism making the two triangles commute). ## Tags comma, arrow -/ namespace category_theory universes v u -- morphism levels before object levels. See note [category_theory universes]. variables {T : Type u} [category.{v} T] section variables (T) /-- The arrow category of `T` has as objects all morphisms in `T` and as morphisms commutative squares in `T`. -/ @[derive category] def arrow := comma.{v v v} (𝟭 T) (𝟭 T) -- Satisfying the inhabited linter instance arrow.inhabited [inhabited T] : inhabited (arrow T) := { default := show comma (𝟭 T) (𝟭 T), from default } end namespace arrow @[simp] lemma id_left (f : arrow T) : comma_morphism.left (𝟙 f) = 𝟙 (f.left) := rfl @[simp] lemma id_right (f : arrow T) : comma_morphism.right (𝟙 f) = 𝟙 (f.right) := rfl /-- An object in the arrow category is simply a morphism in `T`. -/ @[simps] def mk {X Y : T} (f : X ⟶ Y) : arrow T := { left := X, right := Y, hom := f } @[simp] lemma mk_eq (f : arrow T) : arrow.mk f.hom = f := by { cases f, refl, } theorem mk_injective (A B : T) : function.injective (arrow.mk : (A ⟶ B) → arrow T) := λ f g h, by { cases h, refl } theorem mk_inj (A B : T) {f g : A ⟶ B} : arrow.mk f = arrow.mk g ↔ f = g := (mk_injective A B).eq_iff instance {X Y : T} : has_coe (X ⟶ Y) (arrow T) := ⟨mk⟩ /-- A morphism in the arrow category is a commutative square connecting two objects of the arrow category. -/ @[simps] def hom_mk {f g : arrow T} {u : f.left ⟶ g.left} {v : f.right ⟶ g.right} (w : u ≫ g.hom = f.hom ≫ v) : f ⟶ g := { left := u, right := v, w' := w } /-- We can also build a morphism in the arrow category out of any commutative square in `T`. -/ @[simps] def hom_mk' {X Y : T} {f : X ⟶ Y} {P Q : T} {g : P ⟶ Q} {u : X ⟶ P} {v : Y ⟶ Q} (w : u ≫ g = f ≫ v) : arrow.mk f ⟶ arrow.mk g := { left := u, right := v, w' := w } @[simp, reassoc] lemma w {f g : arrow T} (sq : f ⟶ g) : sq.left ≫ g.hom = f.hom ≫ sq.right := sq.w -- `w_mk_left` is not needed, as it is a consequence of `w` and `mk_hom`. @[simp, reassoc] lemma w_mk_right {f : arrow T} {X Y : T} {g : X ⟶ Y} (sq : f ⟶ mk g) : sq.left ≫ g = f.hom ≫ sq.right := sq.w lemma is_iso_of_iso_left_of_is_iso_right {f g : arrow T} (ff : f ⟶ g) [is_iso ff.left] [is_iso ff.right] : is_iso ff := { out := ⟨⟨inv ff.left, inv ff.right⟩, by { ext; dsimp; simp only [is_iso.hom_inv_id] }, by { ext; dsimp; simp only [is_iso.inv_hom_id] }⟩ } /-- Create an isomorphism between arrows, by providing isomorphisms between the domains and codomains, and a proof that the square commutes. -/ @[simps] def iso_mk {f g : arrow T} (l : f.left ≅ g.left) (r : f.right ≅ g.right) (h : l.hom ≫ g.hom = f.hom ≫ r.hom) : f ≅ g := comma.iso_mk l r h /-- A variant of `arrow.iso_mk` that creates an iso between two `arrow.mk`s with a better type signature. -/ abbreviation iso_mk' {W X Y Z : T} (f : W ⟶ X) (g : Y ⟶ Z) (e₁ : W ≅ Y) (e₂ : X ≅ Z) (h : e₁.hom ≫ g = f ≫ e₂.hom) : arrow.mk f ≅ arrow.mk g := arrow.iso_mk e₁ e₂ h section variables {f g : arrow T} (sq : f ⟶ g) instance is_iso_left [is_iso sq] : is_iso sq.left := { out := ⟨(inv sq).left, by simp only [← comma.comp_left, is_iso.hom_inv_id, is_iso.inv_hom_id, arrow.id_left, eq_self_iff_true, and_self]⟩ } instance is_iso_right [is_iso sq] : is_iso sq.right := { out := ⟨(inv sq).right, by simp only [← comma.comp_right, is_iso.hom_inv_id, is_iso.inv_hom_id, arrow.id_right, eq_self_iff_true, and_self]⟩ } @[simp] lemma inv_left [is_iso sq] : (inv sq).left = inv sq.left := is_iso.eq_inv_of_hom_inv_id $ by rw [← comma.comp_left, is_iso.hom_inv_id, id_left] @[simp] lemma inv_right [is_iso sq] : (inv sq).right = inv sq.right := is_iso.eq_inv_of_hom_inv_id $ by rw [← comma.comp_right, is_iso.hom_inv_id, id_right] @[simp] lemma left_hom_inv_right [is_iso sq] : sq.left ≫ g.hom ≫ inv sq.right = f.hom := by simp only [← category.assoc, is_iso.comp_inv_eq, w] -- simp proves this lemma inv_left_hom_right [is_iso sq] : inv sq.left ≫ f.hom ≫ sq.right = g.hom := by simp only [w, is_iso.inv_comp_eq] instance mono_left [mono sq] : mono sq.left := { right_cancellation := λ Z φ ψ h, begin let aux : (Z ⟶ f.left) → (arrow.mk (𝟙 Z) ⟶ f) := λ φ, { left := φ, right := φ ≫ f.hom }, show (aux φ).left = (aux ψ).left, congr' 1, rw ← cancel_mono sq, ext, { exact h }, { simp only [comma.comp_right, category.assoc, ← arrow.w], simp only [← category.assoc, h], }, end } instance epi_right [epi sq] : epi sq.right := { left_cancellation := λ Z φ ψ h, begin let aux : (g.right ⟶ Z) → (g ⟶ arrow.mk (𝟙 Z)) := λ φ, { right := φ, left := g.hom ≫ φ }, show (aux φ).right = (aux ψ).right, congr' 1, rw ← cancel_epi sq, ext, { simp only [comma.comp_left, category.assoc, arrow.w_assoc, h], }, { exact h }, end } end /-- Given a square from an arrow `i` to an isomorphism `p`, express the source part of `sq` in terms of the inverse of `p`. -/ @[simp] lemma square_to_iso_invert (i : arrow T) {X Y : T} (p : X ≅ Y) (sq : i ⟶ arrow.mk p.hom) : i.hom ≫ sq.right ≫ p.inv = sq.left := by simpa only [category.assoc] using (iso.comp_inv_eq p).mpr ((arrow.w_mk_right sq).symm) /-- Given a square from an isomorphism `i` to an arrow `p`, express the target part of `sq` in terms of the inverse of `i`. -/ lemma square_from_iso_invert {X Y : T} (i : X ≅ Y) (p : arrow T) (sq : arrow.mk i.hom ⟶ p) : i.inv ≫ sq.left ≫ p.hom = sq.right := by simp only [iso.inv_hom_id_assoc, arrow.w, arrow.mk_hom] variables {C : Type u} [category.{v} C] /-- A helper construction: given a square between `i` and `f ≫ g`, produce a square between `i` and `g`, whose top leg uses `f`: A → X ↓f ↓i Y --> A → Y ↓g ↓i ↓g B → Z B → Z -/ @[simps] def square_to_snd {X Y Z: C} {i : arrow C} {f : X ⟶ Y} {g : Y ⟶ Z} (sq : i ⟶ arrow.mk (f ≫ g)) : i ⟶ arrow.mk g := { left := sq.left ≫ f, right := sq.right } /-- The functor sending an arrow to its source. -/ @[simps] def left_func : arrow C ⥤ C := comma.fst _ _ /-- The functor sending an arrow to its target. -/ @[simps] def right_func : arrow C ⥤ C := comma.snd _ _ /-- The natural transformation from `left_func` to `right_func`, given by the arrow itself. -/ @[simps] def left_to_right : (left_func : arrow C ⥤ C) ⟶ right_func := { app := λ f, f.hom } end arrow namespace functor universes v₁ v₂ u₁ u₂ variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] /-- A functor `C ⥤ D` induces a functor between the corresponding arrow categories. -/ @[simps] def map_arrow (F : C ⥤ D) : arrow C ⥤ arrow D := { obj := λ a, { left := F.obj a.left, right := F.obj a.right, hom := F.map a.hom, }, map := λ a b f, { left := F.map f.left, right := F.map f.right, w' := by { have w := f.w, simp only [id_map] at w, dsimp, simp only [←F.map_comp, w], } } } end functor end category_theory
8d2e33a4ef49074181cac042ce2d49710df1ba5a
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/finset/n_ary.lean
f33d4ec74c78499ab2301cf15cad28986efe0f2d
[ "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
16,209
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.finset.prod /-! # N-ary images of finsets This file defines `finset.image₂`, the binary image of finsets. This is the finset version of `set.image2`. This is mostly useful to define pointwise operations. ## Notes This file is very similar to the n-ary section of `data.set.basic`, to `order.filter.n_ary` and to `data.option.n_ary`. Please keep them in sync. We do not define `finset.image₃` as its only purpose would be to prove properties of `finset.image₂` and `set.image2` already fulfills this task. -/ open function set namespace finset variables {α α' β β' γ γ' δ δ' ε ε' : Type*} [decidable_eq α'] [decidable_eq β'] [decidable_eq γ] [decidable_eq γ'] [decidable_eq δ] [decidable_eq δ'] [decidable_eq ε] [decidable_eq ε'] {f f' : α → β → γ} {g g' : α → β → γ → δ} {s s' : finset α} {t t' : finset β} {u u' : finset γ} {a a' : α} {b b' : β} {c : γ} /-- The image of a binary function `f : α → β → γ` as a function `finset α → finset β → finset γ`. Mathematically this should be thought of as the image of the corresponding function `α × β → γ`. -/ def image₂ (f : α → β → γ) (s : finset α) (t : finset β) : finset γ := (s ×ˢ t).image $ uncurry f @[simp] lemma mem_image₂ : c ∈ image₂ f s t ↔ ∃ a b, a ∈ s ∧ b ∈ t ∧ f a b = c := by simp [image₂, and_assoc] @[simp, norm_cast] lemma coe_image₂ (f : α → β → γ) (s : finset α) (t : finset β) : (image₂ f s t : set γ) = set.image2 f s t := set.ext $ λ _, mem_image₂ lemma card_image₂_le (f : α → β → γ) (s : finset α) (t : finset β) : (image₂ f s t).card ≤ s.card * t.card := card_image_le.trans_eq $ card_product _ _ lemma card_image₂_iff : (image₂ f s t).card = s.card * t.card ↔ (s ×ˢ t : set (α × β)).inj_on (λ x, f x.1 x.2) := by { rw [←card_product, ←coe_product], exact card_image_iff } lemma card_image₂ (hf : injective2 f) (s : finset α) (t : finset β) : (image₂ f s t).card = s.card * t.card := (card_image_of_injective _ hf.uncurry).trans $ card_product _ _ lemma mem_image₂_of_mem (ha : a ∈ s) (hb : b ∈ t) : f a b ∈ image₂ f s t := mem_image₂.2 ⟨a, b, ha, hb, rfl⟩ lemma mem_image₂_iff (hf : injective2 f) : f a b ∈ image₂ f s t ↔ a ∈ s ∧ b ∈ t := by rw [←mem_coe, coe_image₂, mem_image2_iff hf, mem_coe, mem_coe] lemma image₂_subset (hs : s ⊆ s') (ht : t ⊆ t') : image₂ f s t ⊆ image₂ f s' t' := by { rw [←coe_subset, coe_image₂, coe_image₂], exact image2_subset hs ht } lemma image₂_subset_left (ht : t ⊆ t') : image₂ f s t ⊆ image₂ f s t' := image₂_subset subset.rfl ht lemma image₂_subset_right (hs : s ⊆ s') : image₂ f s t ⊆ image₂ f s' t := image₂_subset hs subset.rfl lemma image_subset_image₂_left (hb : b ∈ t) : (λ a, f a b) '' s ⊆ image₂ f s t := ball_image_of_ball $ λ a ha, mem_image₂_of_mem ha hb lemma image_subset_image₂_right (ha : a ∈ s) : f a '' t ⊆ image₂ f s t := ball_image_of_ball $ λ b, mem_image₂_of_mem ha lemma forall_image₂_iff {p : γ → Prop} : (∀ z ∈ image₂ f s t, p z) ↔ ∀ (x ∈ s) (y ∈ t), p (f x y) := by simp_rw [←mem_coe, coe_image₂, forall_image2_iff] @[simp] lemma image₂_subset_iff : image₂ f s t ⊆ u ↔ ∀ (x ∈ s) (y ∈ t), f x y ∈ u := forall_image₂_iff @[simp] lemma image₂_nonempty_iff : (image₂ f s t).nonempty ↔ s.nonempty ∧ t.nonempty := by { rw [←coe_nonempty, coe_image₂], exact image2_nonempty_iff } lemma nonempty.image₂ (hs : s.nonempty) (ht : t.nonempty) : (image₂ f s t).nonempty := image₂_nonempty_iff.2 ⟨hs, ht⟩ lemma nonempty.of_image₂_left (h : (image₂ f s t).nonempty) : s.nonempty := (image₂_nonempty_iff.1 h).1 lemma nonempty.of_image₂_right (h : (image₂ f s t).nonempty) : t.nonempty := (image₂_nonempty_iff.1 h).2 @[simp] lemma image₂_empty_left : image₂ f ∅ t = ∅ := coe_injective $ by simp @[simp] lemma image₂_empty_right : image₂ f s ∅ = ∅ := coe_injective $ by simp @[simp] lemma image₂_eq_empty_iff : image₂ f s t = ∅ ↔ s = ∅ ∨ t = ∅ := by simp_rw [←not_nonempty_iff_eq_empty, image₂_nonempty_iff, not_and_distrib] @[simp] lemma image₂_singleton_left : image₂ f {a} t = t.image (λ b, f a b) := ext $ λ x, by simp @[simp] lemma image₂_singleton_right : image₂ f s {b} = s.image (λ a, f a b) := ext $ λ x, by simp lemma image₂_singleton_left' : image₂ f {a} t = t.image (f a) := image₂_singleton_left lemma image₂_singleton : image₂ f {a} {b} = {f a b} := by simp lemma image₂_union_left [decidable_eq α] : image₂ f (s ∪ s') t = image₂ f s t ∪ image₂ f s' t := coe_injective $ by { push_cast, exact image2_union_left } lemma image₂_union_right [decidable_eq β] : image₂ f s (t ∪ t') = image₂ f s t ∪ image₂ f s t' := coe_injective $ by { push_cast, exact image2_union_right } lemma image₂_inter_subset_left [decidable_eq α] : image₂ f (s ∩ s') t ⊆ image₂ f s t ∩ image₂ f s' t := coe_subset.1 $ by { push_cast, exact image2_inter_subset_left } lemma image₂_inter_subset_right [decidable_eq β] : image₂ f s (t ∩ t') ⊆ image₂ f s t ∩ image₂ f s t' := coe_subset.1 $ by { push_cast, exact image2_inter_subset_right } lemma image₂_congr (h : ∀ (a ∈ s) (b ∈ t), f a b = f' a b) : image₂ f s t = image₂ f' s t := coe_injective $ by { push_cast, exact image2_congr h } /-- A common special case of `image₂_congr` -/ lemma image₂_congr' (h : ∀ a b, f a b = f' a b) : image₂ f s t = image₂ f' s t := image₂_congr $ λ a _ b _, h a b lemma subset_image₂ {s : set α} {t : set β} (hu : ↑u ⊆ image2 f s t) : ∃ (s' : finset α) (t' : finset β), ↑s' ⊆ s ∧ ↑t' ⊆ t ∧ u ⊆ image₂ f s' t' := begin apply finset.induction_on' u, { exact ⟨∅, ∅, set.empty_subset _, set.empty_subset _, empty_subset _⟩ }, rintro a u ha _ _ ⟨s', t', hs, hs', h⟩, obtain ⟨x, y, hx, hy, ha⟩ := hu ha, haveI := classical.dec_eq α, haveI := classical.dec_eq β, refine ⟨insert x s', insert y t', _⟩, simp_rw [coe_insert, set.insert_subset], exact ⟨⟨hx, hs⟩, ⟨hy, hs'⟩, insert_subset.2 ⟨mem_image₂.2 ⟨x, y, mem_insert_self _ _, mem_insert_self _ _, ha⟩, h.trans $ image₂_subset (subset_insert _ _) $ subset_insert _ _⟩⟩, end variables (s t) lemma card_image₂_singleton_left (hf : injective (f a)) : (image₂ f {a} t).card = t.card := by rw [image₂_singleton_left, card_image_of_injective _ hf] lemma card_image₂_singleton_right (hf : injective (λ a, f a b)) : (image₂ f s {b}).card = s.card := by rw [image₂_singleton_right, card_image_of_injective _ hf] lemma image₂_singleton_inter [decidable_eq β] (t₁ t₂ : finset β) (hf : injective (f a)) : image₂ f {a} (t₁ ∩ t₂) = image₂ f {a} t₁ ∩ image₂ f {a} t₂ := by simp_rw [image₂_singleton_left, image_inter _ _ hf] lemma image₂_inter_singleton [decidable_eq α] (s₁ s₂ : finset α) (hf : injective (λ a, f a b)) : image₂ f (s₁ ∩ s₂) {b} = image₂ f s₁ {b} ∩ image₂ f s₂ {b} := by simp_rw [image₂_singleton_right, image_inter _ _ hf] lemma card_le_card_image₂_left {s : finset α} (hs : s.nonempty) (hf : ∀ a, injective (f a)) : t.card ≤ (image₂ f s t).card := begin obtain ⟨a, ha⟩ := hs, rw ←card_image₂_singleton_left _ (hf a), exact card_le_of_subset (image₂_subset_right $ singleton_subset_iff.2 ha), end lemma card_le_card_image₂_right {t : finset β} (ht : t.nonempty) (hf : ∀ b, injective (λ a, f a b)) : s.card ≤ (image₂ f s t).card := begin obtain ⟨b, hb⟩ := ht, rw ←card_image₂_singleton_right _ (hf b), exact card_le_of_subset (image₂_subset_left $ singleton_subset_iff.2 hb), end variables {s t} lemma bUnion_image_left : s.bUnion (λ a, t.image $ f a) = image₂ f s t := coe_injective $ by { push_cast, exact set.Union_image_left _ } lemma bUnion_image_right : t.bUnion (λ b, s.image $ λ a, f a b) = image₂ f s t := coe_injective $ by { push_cast, exact set.Union_image_right _ } /-! ### Algebraic replacement rules A collection of lemmas to transfer associativity, commutativity, distributivity, ... of operations to the associativity, commutativity, distributivity, ... of `finset.image₂` of those operations. The proof pattern is `image₂_lemma operation_lemma`. For example, `image₂_comm mul_comm` proves that `image₂ (*) f g = image₂ (*) g f` in a `comm_semigroup`. -/ lemma image_image₂ (f : α → β → γ) (g : γ → δ) : (image₂ f s t).image g = image₂ (λ a b, g (f a b)) s t := coe_injective $ by { push_cast, exact image_image2 _ _ } lemma image₂_image_left (f : γ → β → δ) (g : α → γ) : image₂ f (s.image g) t = image₂ (λ a b, f (g a) b) s t := coe_injective $ by { push_cast, exact image2_image_left _ _ } lemma image₂_image_right (f : α → γ → δ) (g : β → γ) : image₂ f s (t.image g) = image₂ (λ a b, f a (g b)) s t := coe_injective $ by { push_cast, exact image2_image_right _ _ } lemma image₂_swap (f : α → β → γ) (s : finset α) (t : finset β) : image₂ f s t = image₂ (λ a b, f b a) t s := coe_injective $ by { push_cast, exact image2_swap _ _ _ } @[simp] lemma image₂_mk_eq_product [decidable_eq α] [decidable_eq β] (s : finset α) (t : finset β) : image₂ prod.mk s t = s ×ˢ t := by ext; simp [prod.ext_iff] @[simp] lemma image₂_curry (f : α × β → γ) (s : finset α) (t : finset β) : image₂ (curry f) s t = (s ×ˢ t).image f := by { classical, rw [←image₂_mk_eq_product, image_image₂, curry] } @[simp] lemma image_uncurry_product (f : α → β → γ) (s : finset α) (t : finset β) : (s ×ˢ t).image (uncurry f) = image₂ f s t := by rw [←image₂_curry, curry_uncurry] @[simp] lemma image₂_left [decidable_eq α] (h : t.nonempty) : image₂ (λ x y, x) s t = s := coe_injective $ by { push_cast, exact image2_left h } @[simp] lemma image₂_right [decidable_eq β] (h : s.nonempty) : image₂ (λ x y, y) s t = t := coe_injective $ by { push_cast, exact image2_right h } lemma image₂_assoc {γ : Type*} {u : finset γ} {f : δ → γ → ε} {g : α → β → δ} {f' : α → ε' → ε} {g' : β → γ → ε'} (h_assoc : ∀ a b c, f (g a b) c = f' a (g' b c)) : image₂ f (image₂ g s t) u = image₂ f' s (image₂ g' t u) := coe_injective $ by { push_cast, exact image2_assoc h_assoc } lemma image₂_comm {g : β → α → γ} (h_comm : ∀ a b, f a b = g b a) : image₂ f s t = image₂ g t s := (image₂_swap _ _ _).trans $ by simp_rw h_comm lemma image₂_left_comm {γ : Type*} {u : finset γ} {f : α → δ → ε} {g : β → γ → δ} {f' : α → γ → δ'} {g' : β → δ' → ε} (h_left_comm : ∀ a b c, f a (g b c) = g' b (f' a c)) : image₂ f s (image₂ g t u) = image₂ g' t (image₂ f' s u) := coe_injective $ by { push_cast, exact image2_left_comm h_left_comm } lemma image₂_right_comm {γ : Type*} {u : finset γ} {f : δ → γ → ε} {g : α → β → δ} {f' : α → γ → δ'} {g' : δ' → β → ε} (h_right_comm : ∀ a b c, f (g a b) c = g' (f' a c) b) : image₂ f (image₂ g s t) u = image₂ g' (image₂ f' s u) t := coe_injective $ by { push_cast, exact image2_right_comm h_right_comm } lemma image_image₂_distrib {g : γ → δ} {f' : α' → β' → δ} {g₁ : α → α'} {g₂ : β → β'} (h_distrib : ∀ a b, g (f a b) = f' (g₁ a) (g₂ b)) : (image₂ f s t).image g = image₂ f' (s.image g₁) (t.image g₂) := coe_injective $ by { push_cast, exact image_image2_distrib h_distrib } /-- Symmetric statement to `finset.image₂_image_left_comm`. -/ lemma image_image₂_distrib_left {g : γ → δ} {f' : α' → β → δ} {g' : α → α'} (h_distrib : ∀ a b, g (f a b) = f' (g' a) b) : (image₂ f s t).image g = image₂ f' (s.image g') t := coe_injective $ by { push_cast, exact image_image2_distrib_left h_distrib } /-- Symmetric statement to `finset.image_image₂_right_comm`. -/ lemma image_image₂_distrib_right {g : γ → δ} {f' : α → β' → δ} {g' : β → β'} (h_distrib : ∀ a b, g (f a b) = f' a (g' b)) : (image₂ f s t).image g = image₂ f' s (t.image g') := coe_injective $ by { push_cast, exact image_image2_distrib_right h_distrib } /-- Symmetric statement to `finset.image_image₂_distrib_left`. -/ lemma image₂_image_left_comm {f : α' → β → γ} {g : α → α'} {f' : α → β → δ} {g' : δ → γ} (h_left_comm : ∀ a b, f (g a) b = g' (f' a b)) : image₂ f (s.image g) t = (image₂ f' s t).image g' := (image_image₂_distrib_left $ λ a b, (h_left_comm a b).symm).symm /-- Symmetric statement to `finset.image_image₂_distrib_right`. -/ lemma image_image₂_right_comm {f : α → β' → γ} {g : β → β'} {f' : α → β → δ} {g' : δ → γ} (h_right_comm : ∀ a b, f a (g b) = g' (f' a b)) : image₂ f s (t.image g) = (image₂ f' s t).image g' := (image_image₂_distrib_right $ λ a b, (h_right_comm a b).symm).symm /-- The other direction does not hold because of the `s`-`s` cross terms on the RHS. -/ lemma image₂_distrib_subset_left {γ : Type*} {u : finset γ} {f : α → δ → ε} {g : β → γ → δ} {f₁ : α → β → β'} {f₂ : α → γ → γ'} {g' : β' → γ' → ε} (h_distrib : ∀ a b c, f a (g b c) = g' (f₁ a b) (f₂ a c)) : image₂ f s (image₂ g t u) ⊆ image₂ g' (image₂ f₁ s t) (image₂ f₂ s u) := coe_subset.1 $ by { push_cast, exact set.image2_distrib_subset_left h_distrib } /-- The other direction does not hold because of the `u`-`u` cross terms on the RHS. -/ lemma image₂_distrib_subset_right {γ : Type*} {u : finset γ} {f : δ → γ → ε} {g : α → β → δ} {f₁ : α → γ → α'} {f₂ : β → γ → β'} {g' : α' → β' → ε} (h_distrib : ∀ a b c, f (g a b) c = g' (f₁ a c) (f₂ b c)) : image₂ f (image₂ g s t) u ⊆ image₂ g' (image₂ f₁ s u) (image₂ f₂ t u) := coe_subset.1 $ by { push_cast, exact set.image2_distrib_subset_right h_distrib } lemma image_image₂_antidistrib {g : γ → δ} {f' : β' → α' → δ} {g₁ : β → β'} {g₂ : α → α'} (h_antidistrib : ∀ a b, g (f a b) = f' (g₁ b) (g₂ a)) : (image₂ f s t).image g = image₂ f' (t.image g₁) (s.image g₂) := by { rw image₂_swap f, exact image_image₂_distrib (λ _ _, h_antidistrib _ _) } /-- Symmetric statement to `finset.image₂_image_left_anticomm`. -/ lemma image_image₂_antidistrib_left {g : γ → δ} {f' : β' → α → δ} {g' : β → β'} (h_antidistrib : ∀ a b, g (f a b) = f' (g' b) a) : (image₂ f s t).image g = image₂ f' (t.image g') s := coe_injective $ by { push_cast, exact image_image2_antidistrib_left h_antidistrib } /-- Symmetric statement to `finset.image_image₂_right_anticomm`. -/ lemma image_image₂_antidistrib_right {g : γ → δ} {f' : β → α' → δ} {g' : α → α'} (h_antidistrib : ∀ a b, g (f a b) = f' b (g' a)) : (image₂ f s t).image g = image₂ f' t (s.image g') := coe_injective $ by { push_cast, exact image_image2_antidistrib_right h_antidistrib } /-- Symmetric statement to `finset.image_image₂_antidistrib_left`. -/ lemma image₂_image_left_anticomm {f : α' → β → γ} {g : α → α'} {f' : β → α → δ} {g' : δ → γ} (h_left_anticomm : ∀ a b, f (g a) b = g' (f' b a)) : image₂ f (s.image g) t = (image₂ f' t s).image g' := (image_image₂_antidistrib_left $ λ a b, (h_left_anticomm b a).symm).symm /-- Symmetric statement to `finset.image_image₂_antidistrib_right`. -/ lemma image_image₂_right_anticomm {f : α → β' → γ} {g : β → β'} {f' : β → α → δ} {g' : δ → γ} (h_right_anticomm : ∀ a b, f a (g b) = g' (f' b a)) : image₂ f s (t.image g) = (image₂ f' t s).image g' := (image_image₂_antidistrib_right $ λ a b, (h_right_anticomm b a).symm).symm end finset
345f0635edf7f21bdfbe9ee32948e2355512bcf2
5756a081670ba9c1d1d3fca7bd47cb4e31beae66
/Mathport/Syntax/Translate/Tactic/Mathlib/Core.lean
fc01b3fec26db7835184cee914ed97c6c8b7cd99
[ "Apache-2.0" ]
permissive
leanprover-community/mathport
2c9bdc8292168febf59799efdc5451dbf0450d4a
13051f68064f7638970d39a8fecaede68ffbf9e1
refs/heads/master
1,693,841,364,079
1,693,813,111,000
1,693,813,111,000
379,357,010
27
10
Apache-2.0
1,691,309,132,000
1,624,384,521,000
Lean
UTF-8
Lean
false
false
2,767
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathport.Syntax.Translate.Tactic.Basic import Mathport.Syntax.Translate.Tactic.Lean3 open Lean namespace Mathport.Translate.Tactic open AST3 Parser -- # tactic.core @[tr_ni_tactic tactic.exact_dec_trivial] def trExactDecTrivial (_ : AST3.Expr) : M Syntax.Tactic := `(tactic| decide) @[tr_tactic fsplit] def trFSplit : TacM Syntax.Tactic := `(tactic| fconstructor) @[tr_tactic injections_and_clear] def trInjectionsAndClear : TacM Syntax.Tactic := `(tactic| injections) @[tr_user_cmd «run_parser»] def trRunParser : Parse1 Syntax.Command := parse0 do warn! "unsupported: run_parser" -- unattested @[tr_ni_tactic tactic.classical] def trNIClassical (_ : AST3.Expr) : M Syntax.Tactic := return mkBlockTransform fun args => `(tactic| classical $args*) @[tr_user_attr higher_order] def trHigherOrderAttr : Parse1 Syntax.Attr := parse1 (ident)? fun n => do `(attr| higher_order $(← liftM $ n.mapM mkIdentI)?) @[tr_user_attr interactive] def trInteractiveAttr : Parse1 Syntax.Attr := parse0 `(attr| interactive) @[tr_user_cmd «setup_tactic_parser»] def trSetupTacticParser : Parse1 Unit := parse1 emittedCodeHere fun _ => warn! "unsupported: setup_tactic_parser" open TSyntax.Compat in def trInterpolatedStr' := trInterpolatedStr fun stx => `(← $stx) @[tr_user_nota tactic.pformat_macro] def trPFormatMacro : TacM Syntax.Term := do `(f! $(← trInterpolatedStr')) @[tr_user_nota tactic.fail_macro] def trFailMacro : TacM Syntax.Term := do let stx ← trInterpolatedStr'; `(throwError $stx) @[tr_user_nota tactic.trace_macro] def trTraceMacro : TacM Syntax.Term := do let stx ← trInterpolatedStr'; `(← do dbg_trace $stx) @[tr_user_cmd «import_private»] def trImportPrivate : Parse1 Syntax.Command := parse1 (return (← ident, ← (tk "from" *> ident)?)) fun (n, fr) => do `(open private $(← mkIdentF n) $[from $(← liftM $ fr.mapM mkIdentI)]?) @[tr_user_cmd «mk_simp_attribute»] def trMkSimpAttribute : Parse1 Unit := parse1 (return (← ident, ← pExpr, ← (tk "with" *> ident*)?)) fun (n, d, withList) => do let descr ← match d.kind.unparen with | AST3.Expr.ident `none => pure s!"simp set for {n.toString}" | AST3.Expr.string s => pure s | _ => warn! "unsupported: weird string" let n := mkIdent n push (← `(command| $(trDocComment s!" {descr} "):docComment register_simp_attr $n)) let withList := withList.getD #[] unless withList.isEmpty do logComment "[mathport] port note: move this to another file, it won't work here" push (← `(command| attribute [$n:ident] $(← liftM $ withList.mapM mkIdentI)*))
a813b50935c1069bbfb9990738a65b242c631579
4950bf76e5ae40ba9f8491647d0b6f228ddce173
/src/group_theory/perm/subgroup.lean
92d98e00859c2384ca4b6cd5e97747dd4a60dd6d
[ "Apache-2.0" ]
permissive
ntzwq/mathlib
ca50b21079b0a7c6781c34b62199a396dd00cee2
36eec1a98f22df82eaccd354a758ef8576af2a7f
refs/heads/master
1,675,193,391,478
1,607,822,996,000
1,607,822,996,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,438
lean
/- Copyright (c) 2020 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import group_theory.perm.basic import group_theory.subgroup import group_theory.coset import data.fintype.basic /-! # Subgroups within the permutations (self-equivalences) of a type `α` This file defines some `subgroup`s that exist within `equiv.perm α`. Where possible, it provides `decidable` instances so that `subgroup.quotient` is computably finite. -/ namespace equiv namespace perm /-- The subgroup of permutations which do not exchange elements between `α` and `β`; those which are of the form `sum_congr sl sr`. -/ def sum_congr_subgroup (α β : Type*) : subgroup (perm (α ⊕ β)) := { carrier := λ σ, ∃ (sl : perm α) (sr : perm β), σ = sum_congr sl sr, one_mem' := ⟨1, 1, sum_congr_one.symm⟩, mul_mem' := λ σ₁ σ₂ ⟨sl₁₂, sr₁₂, h₁₂⟩ ⟨sl₂₃, sr₂₃, h₂₃⟩, ⟨sl₁₂ * sl₂₃, sr₁₂ * sr₂₃, h₂₃.symm ▸ h₁₂.symm ▸ sum_congr_mul sl₁₂ sr₁₂ sl₂₃ sr₂₃⟩, inv_mem' := λ σ₁ ⟨sl, sr, h⟩, ⟨sl⁻¹, sr⁻¹, h.symm ▸ sum_congr_inv sl sr⟩ } instance sum_congr_subgroup.left_rel_decidable {α β : Type*} [decidable_eq α] [decidable_eq β] [fintype α] [fintype β] : decidable_rel $ (quotient_group.left_rel (sum_congr_subgroup α β)).r := λ σ₁ σ₂, fintype.decidable_exists_fintype /-- The subgroup of permutations which do not exchange elements between fibers; those which are of the form `sigma_congr_right s`. -/ def sigma_congr_right_subgroup {α : Type*} (β : α → Type*) : subgroup (perm (Σ a, β a)) := { carrier := λ σ, ∃ (s : Π a, perm (β a)), σ = sigma_congr_right s, one_mem' := ⟨λ i, 1, sigma_congr_right_one.symm⟩, mul_mem' := λ σ₁ σ₂ ⟨s₁₂, h₁₂⟩ ⟨s₂₃, h₂₃⟩, ⟨λ i, s₁₂ i * s₂₃ i, h₂₃.symm ▸ h₁₂.symm ▸ sigma_congr_right_mul s₁₂ s₂₃⟩, inv_mem' := λ σ₁ ⟨s, h⟩, ⟨λ i, (s i)⁻¹, h.symm ▸ sigma_congr_right_inv s⟩ } instance sigma_congr_right_subgroup.left_rel_decidable {α : Type*} {β : α → Type*} [decidable_eq α] [∀ a, decidable_eq (β a)] [fintype α] [∀ a, fintype (β a)] : decidable_rel $ (quotient_group.left_rel (sigma_congr_right_subgroup β)).r := λ σ₁ σ₂, fintype.decidable_exists_fintype end perm end equiv
5deec5b994e33e8a5dfe2005d5ab4764deb41c24
b00eb947a9c4141624aa8919e94ce6dcd249ed70
/stage0/src/Lean/Meta/IndPredBelow.lean
a146abbc983dc47a6decc4bc1740e26701721141
[ "Apache-2.0" ]
permissive
gebner/lean4-old
a4129a041af2d4d12afb3a8d4deedabde727719b
ee51cdfaf63ee313c914d83264f91f414a0e3b6e
refs/heads/master
1,683,628,606,745
1,622,651,300,000
1,622,654,405,000
142,608,821
1
0
null
null
null
null
UTF-8
Lean
false
false
15,253
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Dany Fabian -/ import Lean.Util.Constructions import Lean.Meta.Transform import Lean.Meta.Tactic namespace Lean.Meta.IndPredBelow register_builtin_option maxBackwardChainingDepth : Nat := { defValue := 10 descr := "The maximum search depth used in the backwards chaining part of the proof of `brecOn` for inductive predicates." } /-- The context used in the creation of the `below` scheme for inductive predicates. -/ structure Context where motives : Array (Name × Expr) typeInfos : Array InductiveVal belowNames : Array Name headers : Array Expr numParams : Nat /-- Collection of variables used to keep track of the positions of binders in the construction of `below` motives and constructors. -/ structure Variables where target : Array Expr indVal : Array Expr params : Array Expr args : Array Expr motives : Array Expr innerType : Expr deriving Inhabited /-- Collection of variables used to keep track of the local context used in the `brecOn` proof. -/ structure BrecOnVariables where params : Array FVarId motives : Array FVarId indices : Array FVarId witness : FVarId indHyps : Array FVarId def mkContext (declName : Name) : MetaM Context := do let indVal ← getConstInfoInduct declName let typeInfos ← indVal.all.toArray.mapM getConstInfoInduct let motiveTypes ← typeInfos.mapM motiveType let motives ←motiveTypes.mapIdxM fun j motive => do (←motiveName motiveTypes j.val, motive) let headers := typeInfos.mapM $ mkHeader motives indVal.numParams return { motives := motives typeInfos := typeInfos numParams := indVal.numParams headers := ←headers belowNames := ←indVal.all.toArray.map (· ++ `below) } where motiveName (motiveTypes : Array Expr) (i : Nat) : MetaM Name := if motiveTypes.size > 1 then mkFreshUserName s!"motive_{i.succ}" else mkFreshUserName "motive" mkHeader (motives : Array (Name × Expr)) (numParams : Nat) (indVal : InductiveVal) : MetaM Expr := do let header ← forallTelescope indVal.type fun xs t => do withNewBinderInfos (xs.map fun x => (x.fvarId!, BinderInfo.implicit)) $ mkForallFVars xs $ ←mkArrow (mkAppN (mkIndValConst indVal) xs) t addMotives motives numParams header addMotives (motives : Array (Name × Expr)) (numParams : Nat) : Expr → MetaM Expr := motives.foldrM (fun (motiveName, motive) t => forallTelescope t fun xs s => do let motiveType ← instantiateForall motive xs[:numParams] withLocalDecl motiveName BinderInfo.implicit motiveType fun motive => do mkForallFVars (xs.insertAt numParams motive) s) motiveType (indVal : InductiveVal) : MetaM Expr := forallTelescope indVal.type fun xs t => do mkForallFVars xs $ ←mkArrow (mkAppN (mkIndValConst indVal) xs) (mkSort levelZero) mkIndValConst (indVal : InductiveVal) : Expr := mkConst indVal.name $ indVal.levelParams.map mkLevelParam partial def mkCtorType (ctx : Context) (belowIdx : Nat) (originalCtor : ConstructorVal) : MetaM Expr := forallTelescope originalCtor.type fun xs t => addHeaderVars { innerType := t indVal := #[] motives := #[] params := xs[:ctx.numParams] args := xs[ctx.numParams:] target := xs[:ctx.numParams] } where addHeaderVars (vars : Variables) := do let headersWithNames ← ctx.headers.mapIdxM fun idx header => (ctx.belowNames[idx], fun _ => pure header) withLocalDeclsD headersWithNames fun xs => addMotives { vars with indVal := xs } addMotives (vars : Variables) := do let motiveBuilders ← ctx.motives.mapM fun (motiveName, motiveType) => (motiveName, BinderInfo.implicit, fun _ => instantiateForall motiveType vars.params) withLocalDecls motiveBuilders fun xs => modifyBinders { vars with target := vars.target ++ xs, motives := xs } 0 modifyBinders (vars : Variables) (i : Nat) := do if i < vars.args.size then let binder := vars.args[i] let binderType ←inferType binder if ←checkCount binderType then mkBelowBinder vars binder binderType fun indValIdx x => mkMotiveBinder vars indValIdx binder binderType fun y => withNewBinderInfos #[(binder.fvarId!, BinderInfo.implicit)] do modifyBinders { vars with target := vars.target ++ #[binder, x, y]} i.succ else modifyBinders { vars with target := vars.target.push binder } i.succ else rebuild vars rebuild (vars : Variables) := vars.innerType.withApp fun f args => do let hApp := mkAppN (mkConst originalCtor.name $ ctx.typeInfos[0].levelParams.map mkLevelParam) (vars.params ++ vars.args) let innerType := mkAppN vars.indVal[belowIdx] $ vars.params ++ vars.motives ++ args[ctx.numParams:] ++ #[hApp] let x ← mkForallFVars vars.target innerType replaceTempVars vars x replaceTempVars (vars : Variables) (ctor : Expr) := let levelParams := ctx.typeInfos[0].levelParams.map mkLevelParam ctor.replaceFVars vars.indVal $ ctx.belowNames.map fun indVal => mkConst indVal levelParams checkCount (domain : Expr) : MetaM Bool := do let run (x : StateRefT Nat MetaM Expr) : MetaM (Expr × Nat) := StateRefT'.run x 0 let (_, cnt) ←run $ transform domain fun e => do if let some name := e.constName? then if let some idx := ctx.typeInfos.findIdx? fun indVal => indVal.name == name then let cnt ←get set $ cnt + 1 TransformStep.visit e if cnt > 1 then throwError "only arrows are allowed as premises. Multiple recursive occurrences detected:{indentExpr domain}" return cnt == 1 mkBelowBinder (vars : Variables) (binder : Expr) (domain : Expr) {α : Type} (k : Nat → Expr → MetaM α) : MetaM α := do forallTelescope domain fun xs t => do let fail _ := do throwError "only trivial inductive applications supported in premises:{indentExpr t}" t.withApp fun f args => do if let some name := f.constName? then if let some idx := ctx.typeInfos.findIdx? fun indVal => indVal.name == name then let indVal := ctx.typeInfos[idx] let hApp := mkAppN binder xs let t := mkAppN vars.indVal[idx] $ vars.params ++ vars.motives ++ args[ctx.numParams:] ++ #[hApp] let newDomain ← mkForallFVars xs t withLocalDecl (←copyVarName binder.fvarId!) binder.binderInfo newDomain (k idx) else fail () else fail () mkMotiveBinder (vars : Variables) (indValIdx : Nat) (binder : Expr) (domain : Expr) {α : Type} (k : Expr → MetaM α) : MetaM α := do forallTelescope domain fun xs t => do t.withApp fun f args => do let hApp := mkAppN binder xs let t := mkAppN vars.motives[indValIdx] $ args[ctx.numParams:] ++ #[hApp] let newDomain ← mkForallFVars xs t withLocalDecl (←copyVarName binder.fvarId!) binder.binderInfo newDomain k copyVarName (oldName : FVarId) : MetaM Name := do let binderDecl ← getLocalDecl oldName mkFreshUserName binderDecl.userName def mkConstructor (ctx : Context) (i : Nat) (ctor : Name) : MetaM Constructor := do let ctorInfo ← getConstInfoCtor ctor let name := ctor.updatePrefix ctx.belowNames[i] let type ← mkCtorType ctx i ctorInfo return { name := name type := type } def mkInductiveType (ctx : Context) (i : Fin ctx.typeInfos.size) (indVal : InductiveVal) : MetaM InductiveType := do return { name := ctx.belowNames[i] type := ctx.headers[i] ctors := ←indVal.ctors.mapM (mkConstructor ctx i) } def mkBelowDecl (ctx : Context) : MetaM Declaration := do let lparams := ctx.typeInfos[0].levelParams Declaration.inductDecl lparams (ctx.numParams + ctx.motives.size) (←ctx.typeInfos.mapIdxM $ mkInductiveType ctx).toList ctx.typeInfos[0].isUnsafe partial def proveBrecOn (ctx : Context) (indVal : InductiveVal) (type : Expr) : MetaM Expr := do let main ← mkFreshExprSyntheticOpaqueMVar type let (m, vars) ← intros main.mvarId! let [m] ← applyIH m vars | throwError "applying the induction hypothesis should only return one goal" let ms ← induction m vars let ms ← applyCtors ms let maxDepth := maxBackwardChainingDepth.get $ ←getOptions ms.forM (closeGoal vars maxDepth) instantiateMVars main where intros (m : MVarId) : MetaM (MVarId × BrecOnVariables) := do let (params, m) ← introNP m indVal.numParams let (motives, m) ← introNP m ctx.motives.size let (indices, m) ← introNP m indVal.numIndices let (witness, m) ← intro1P m let (indHyps, m) ← introNP m ctx.motives.size return (m, ⟨params, motives, indices, witness, indHyps⟩) applyIH (m : MVarId) (vars : BrecOnVariables) : MetaM (List MVarId) := do match ←vars.indHyps.findSomeM? (fun ih => do try some $ (←apply m $ mkFVar ih) catch ex => none) with | some goals => goals | none => throwError "cannot apply induction hypothesis: {MessageData.ofGoal m}" induction (m : MVarId) (vars : BrecOnVariables) : MetaM (List MVarId) := do let params := vars.params.map mkFVar let motives := vars.motives.map mkFVar let levelParams := indVal.levelParams.map mkLevelParam let motives ← ctx.motives.mapIdxM fun idx (_, motive) => do let motive ← instantiateForall motive params forallTelescope motive fun xs _ => do mkLambdaFVars xs $ mkAppN (mkConst ctx.belowNames[idx] levelParams) $ (params ++ motives ++ xs) let recursorInfo ← getConstInfo $ mkRecName indVal.name let recLevels := if recursorInfo.numLevelParams > levelParams.length then levelZero::levelParams else levelParams let recursor ← mkAppN (mkConst recursorInfo.name $ recLevels) $ params ++ motives apply m recursor applyCtors (ms : List MVarId) : MetaM $ List MVarId := do let mss ← ms.toArray.mapIdxM fun idx m => do let m ← introNPRec m (←getMVarType m).withApp fun below args => withMVarContext m do args.back.withApp fun ctor ctorArgs => do let ctorName := ctor.constName!.updatePrefix below.constName! let ctor := mkConst ctorName below.constLevels! let ctorInfo ← getConstInfoCtor ctorName let (mvars, _, t) ← forallMetaTelescope ctorInfo.type let ctor := mkAppN ctor mvars apply m ctor return mss.foldr List.append [] introNPRec (m : MVarId) : MetaM MVarId := do if (←getMVarType m).isForall then introNPRec (←intro1P m).2 else m closeGoal (vars : BrecOnVariables) (maxDepth : Nat) (m : MVarId) : MetaM Unit := do unless ←isExprMVarAssigned m do let m ← introNPRec m unless ←backwardsChaining m maxDepth do withMVarContext m do throwError "couldn't solve by backwards chaining ({``maxBackwardChainingDepth} = {maxDepth}): {MessageData.ofGoal m}" backwardsChaining (m : MVarId) (depth : Nat) : MetaM Bool := do if depth = 0 then false else withMVarContext m do let lctx ← getLCtx let mTy ← getMVarType m lctx.anyM fun localDecl => commitWhen do let (mvars, _, t) ← forallMetaTelescope localDecl.type if ←isDefEq mTy t then assignExprMVar m (mkAppN localDecl.toExpr mvars) mvars.allM fun v => do if ←isExprMVarAssigned v.mvarId! then true else backwardsChaining v.mvarId! (depth - 1) else false def mkBrecOnDecl (ctx : Context) (idx : Nat) : MetaM Declaration := do let type ← mkType let indVal := ctx.typeInfos[idx] let name := indVal.name ++ brecOnSuffix Declaration.thmDecl { name := name levelParams := indVal.levelParams type := type value := ←proveBrecOn ctx indVal type } where mkType : MetaM Expr := forallTelescope ctx.headers[idx] fun xs t => do let params := xs[:ctx.numParams] let motives := xs[ctx.numParams:ctx.numParams + ctx.motives.size].toArray let indices := xs[ctx.numParams + ctx.motives.size:] let motiveBinders ← ctx.motives.mapIdxM $ mkIH params motives withLocalDeclsD motiveBinders fun ys => do mkForallFVars (xs ++ ys) (mkAppN motives[idx] indices) mkIH (params : Array Expr) (motives : Array Expr) (idx : Fin ctx.motives.size) (motive : Name × Expr) : MetaM $ Name × (Array Expr → MetaM Expr) := do let name := if ctx.motives.size > 1 then mkFreshUserName s!"ih_{idx.val.succ}" else mkFreshUserName "ih" let ih ← instantiateForall motive.2 params let mkDomain _ := forallTelescope ih fun ys t => do let levels := ctx.typeInfos[idx].levelParams.map mkLevelParam let args := params ++ motives ++ ys let premise := mkAppN (mkConst ctx.belowNames[idx.val] levels) args let conclusion := mkAppN motives[idx] ys mkForallFVars ys (←mkArrow premise conclusion) (←name, mkDomain) /-- Given a constructor name, find the indices of the corresponding `below` version thereof. -/ partial def getBelowIndices (ctorName : Name) : MetaM $ Array Nat := do let ctorInfo ← getConstInfoCtor ctorName let belowCtorInfo ← getConstInfoCtor (ctorName.updatePrefix $ ctorInfo.induct ++ `below) let belowInductInfo ← getConstInfoInduct belowCtorInfo.induct forallTelescope ctorInfo.type fun xs t => do loop xs belowCtorInfo.type #[] 0 0 where loop (xs : Array Expr) (rest : Expr) (belowIndices : Array Nat) (xIdx yIdx : Nat) : MetaM $ Array Nat := do if xIdx ≥ xs.size then belowIndices else let x := xs[xIdx] let xTy ← inferType x let yTy := rest.bindingDomain! if ←isDefEq xTy yTy then let rest ← instantiateForall rest #[x] loop xs rest (belowIndices.push yIdx) (xIdx + 1) (yIdx + 1) else forallBoundedTelescope rest (some 1) fun ys rest => loop xs rest belowIndices xIdx (yIdx + 1) def mkBelow (declName : Name) : MetaM Unit := do if (←isInductivePredicate declName) then let x ← getConstInfoInduct declName if x.isRec then let ctx ← IndPredBelow.mkContext declName let decl ← IndPredBelow.mkBelowDecl ctx addDecl decl trace[Meta.IndPredBelow] "added {ctx.belowNames}" ctx.belowNames.forM Lean.mkCasesOn for i in [:ctx.typeInfos.size] do try let decl ← IndPredBelow.mkBrecOnDecl ctx i addDecl decl catch e => trace[Meta.IndPredBelow] "failed to prove brecOn for {ctx.belowNames[i]}\n{e.toMessageData}" else trace[Meta.IndPredBelow] "Not recursive" else trace[Meta.IndPredBelow] "Not inductive predicate" builtin_initialize registerTraceClass `Meta.IndPredBelow end Lean.Meta.IndPredBelow
acf4acd2b473139f0e2b9f5b78c1acd1fc140117
f3a5af2927397cf346ec0e24312bfff077f00425
/src/game/world10/level13.lean
447b8e29d38d941005c19c469ed2593ec679fc34
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/natural_number_game
05c39e1586408cfb563d1a12e1085a90726ab655
f29b6c2884299fc63fdfc81ae5d7daaa3219f9fd
refs/heads/master
1,688,570,964,990
1,636,908,242,000
1,636,908,242,000
195,403,790
277
84
Apache-2.0
1,694,547,955,000
1,562,328,792,000
Lean
UTF-8
Lean
false
false
1,019
lean
import game.world10.level12 -- hide namespace mynat -- hide /- # Inequality world. ## Level 13: `not_succ_le_self` Turns out that `¬ P` is *by definition* `P → false`, so you can just start this one with `intro h` if you like. ## Pro tip: ``` conv begin to_lhs, rw hc, end, ``` is an incantation which rewrites `hc` only on the left hand side of the goal. Look carefully at the commas. You don't need to use `conv` to solve this, but it's a helpful trick when `rw` is rewriting too much. -/ /- Lemma For all naturals $a$, $\operatorname{succ}(a)$ is not at most $a$. -/ theorem not_succ_le_self (a : mynat) : ¬ (succ a ≤ a) := begin [nat_num_game] intro h, cases h with c h, induction a with d hd, { rw succ_add at h, exact zero_ne_succ _ h, }, { rw succ_add at h, apply hd, apply succ_inj, exact h, } end end mynat -- hide -- thanks to Filip Szczepański for this proof (nicer than the original; I was doing -- hide -- induction a before cases h) -- hide
a110d8ea46bfe6d541db325d1f0c313f7fb44cc0
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/07_Induction_and_Recursion.org.20.lean
70328d071371fcda0bec31a7f18448471362be70
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
296
lean
/- page 108 -/ import standard open nat inductive finord : nat → Type := | fz : Π n, finord (succ n) | fs : Π {n}, finord n → finord (succ n) open finord definition to_nat : Π {n : nat}, finord n → nat | @to_nat ⌞n+1⌟ (fz n) := zero | @to_nat ⌞n+1⌟ (fs f) := succ (to_nat f)
16f19571ee3c810baa73d3315469196a52780682
59aed81a2ce7741e690907fc374be338f4f88b6f
/src/math-688/lectures/lec-23.lean
1fb7f05bd8039e60e025609b8d8cf7dc826d3b75
[]
no_license
agusakov/math-688-lean
c84d5e1423eb208a0281135f0214b91b30d0ef48
67dc27ebff55a74c6b5a1c469ba04e7981d2e550
refs/heads/main
1,679,699,340,788
1,616,602,782,000
1,616,602,782,000
332,894,454
0
0
null
null
null
null
UTF-8
Lean
false
false
77
lean
/- 23 Oct 2019 -/ -- matchings -- hall's marriage theorem in terms of graphs
2e75b57005ac4cd2b4a7df9c92d35c39b3a9c798
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/mv_polynomial/rename.lean
d41971d728798f2aee556cf8f9cac6a844a50761
[ "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,210
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, Johan Commelin, Mario Carneiro -/ import data.mv_polynomial.basic /-! # Renaming variables of polynomials This file establishes the `rename` operation on multivariate polynomials, which modifies the set of variables. ## Main declarations * `mv_polynomial.rename` * `mv_polynomial.rename_equiv` ## Notation As in other polynomial files, we typically use the notation: + `σ τ α : Type*` (indexing the variables) + `R S : Type*` `[comm_semiring R]` `[comm_semiring S]` (the coefficients) + `s : σ →₀ ℕ`, a function from `σ` to `ℕ` which is zero away from a finite set. This will give rise to a monomial in `mv_polynomial σ R` which mathematicians might call `X^s` + `r : R` elements of the coefficient ring + `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians + `p : mv_polynomial σ α` -/ noncomputable theory open_locale classical big_operators open set function finsupp add_monoid_algebra open_locale big_operators variables {σ τ α R S : Type*} [comm_semiring R] [comm_semiring S] namespace mv_polynomial section rename /-- Rename all the variables in a multivariable polynomial. -/ def rename (f : σ → τ) : mv_polynomial σ R →ₐ[R] mv_polynomial τ R := aeval (X ∘ f) @[simp] lemma rename_C (f : σ → τ) (r : R) : rename f (C r) = C r := eval₂_C _ _ _ @[simp] lemma rename_X (f : σ → τ) (i : σ) : rename f (X i : mv_polynomial σ R) = X (f i) := eval₂_X _ _ _ lemma map_rename (f : R →+* S) (g : σ → τ) (p : mv_polynomial σ R) : map f (rename g p) = rename g (map f p) := mv_polynomial.induction_on p (λ a, by simp only [map_C, rename_C]) (λ p q hp hq, by simp only [hp, hq, alg_hom.map_add, ring_hom.map_add]) (λ p n hp, by simp only [hp, rename_X, map_X, ring_hom.map_mul, alg_hom.map_mul]) @[simp] lemma rename_rename (f : σ → τ) (g : τ → α) (p : mv_polynomial σ R) : rename g (rename f p) = rename (g ∘ f) p := show rename g (eval₂ C (X ∘ f) p) = _, begin simp only [rename, aeval_eq_eval₂_hom], simp [eval₂_comp_left _ C (X ∘ f) p, (∘), eval₂_C, eval_X], apply eval₂_hom_congr _ rfl rfl, ext1, simp only [comp_app, ring_hom.coe_comp, eval₂_hom_C], end @[simp] lemma rename_id (p : mv_polynomial σ R) : rename id p = p := eval₂_eta p lemma rename_monomial (f : σ → τ) (d : σ →₀ ℕ) (r : R) : rename f (monomial d r) = monomial (d.map_domain f) r := begin rw [rename, aeval_monomial, monomial_eq, finsupp.prod_map_domain_index], { refl }, { exact assume n, pow_zero _ }, { exact assume n i₁ i₂, pow_add _ _ _ } end lemma rename_eq (f : σ → τ) (p : mv_polynomial σ R) : rename f p = finsupp.map_domain (finsupp.map_domain f) p := begin simp only [rename, aeval_def, eval₂, finsupp.map_domain, algebra_map_eq, X_pow_eq_monomial, ← monomial_finsupp_sum_index], refl end lemma rename_injective (f : σ → τ) (hf : function.injective f) : function.injective (rename f : mv_polynomial σ R → mv_polynomial τ R) := have (rename f : mv_polynomial σ R → mv_polynomial τ R) = finsupp.map_domain (finsupp.map_domain f) := funext (rename_eq f), begin rw this, exact finsupp.map_domain_injective (finsupp.map_domain_injective hf) end section variables (R) /-- `mv_polynomial.rename e` is an equivalence when `e` is. -/ @[simps apply] def rename_equiv (f : σ ≃ τ) : mv_polynomial σ R ≃ₐ[R] mv_polynomial τ R := { to_fun := rename f, inv_fun := rename f.symm, left_inv := λ p, by rw [rename_rename, f.symm_comp_self, rename_id], right_inv := λ p, by rw [rename_rename, f.self_comp_symm, rename_id], ..rename f} @[simp] lemma rename_equiv_refl : rename_equiv R (equiv.refl σ) = alg_equiv.refl := alg_equiv.ext rename_id @[simp] lemma rename_equiv_symm (f : σ ≃ τ) : (rename_equiv R f).symm = rename_equiv R f.symm := rfl @[simp] lemma rename_equiv_trans (e : σ ≃ τ) (f : τ ≃ α): (rename_equiv R e).trans (rename_equiv R f) = rename_equiv R (e.trans f) := alg_equiv.ext (rename_rename e f) end section variables (f : R →+* S) (k : σ → τ) (g : τ → S) (p : mv_polynomial σ R) lemma eval₂_rename : (rename k p).eval₂ f g = p.eval₂ f (g ∘ k) := by apply mv_polynomial.induction_on p; { intros, simp [*] } lemma eval₂_hom_rename : eval₂_hom f g (rename k p) = eval₂_hom f (g ∘ k) p := eval₂_rename _ _ _ _ lemma aeval_rename [algebra R S] : aeval g (rename k p) = aeval (g ∘ k) p := eval₂_hom_rename _ _ _ _ lemma rename_eval₂ (g : τ → mv_polynomial σ R) : rename k (p.eval₂ C (g ∘ k)) = (rename k p).eval₂ C (rename k ∘ g) := by apply mv_polynomial.induction_on p; { intros, simp [*] } lemma rename_prodmk_eval₂ (j : τ) (g : σ → mv_polynomial σ R) : rename (prod.mk j) (p.eval₂ C g) = p.eval₂ C (λ x, rename (prod.mk j) (g x)) := by apply mv_polynomial.induction_on p; { intros, simp [*] } lemma eval₂_rename_prodmk (g : σ × τ → S) (i : σ) (p : mv_polynomial τ R) : (rename (prod.mk i) p).eval₂ f g = eval₂ f (λ j, g (i, j)) p := by apply mv_polynomial.induction_on p; { intros, simp [*] } lemma eval_rename_prodmk (g : σ × τ → R) (i : σ) (p : mv_polynomial τ R) : eval g (rename (prod.mk i) p) = eval (λ j, g (i, j)) p := eval₂_rename_prodmk (ring_hom.id _) _ _ _ end /-- Every polynomial is a polynomial in finitely many variables. -/ theorem exists_finset_rename (p : mv_polynomial σ R) : ∃ (s : finset σ) (q : mv_polynomial {x // x ∈ s} R), p = rename coe q := begin apply induction_on p, { intro r, exact ⟨∅, C r, by rw rename_C⟩ }, { rintro p q ⟨s, p, rfl⟩ ⟨t, q, rfl⟩, refine ⟨s ∪ t, ⟨_, _⟩⟩, { refine rename (subtype.map id _) p + rename (subtype.map id _) q; simp only [id.def, true_or, or_true, finset.mem_union, forall_true_iff] {contextual := tt}, }, { simp only [rename_rename, alg_hom.map_add], refl, }, }, { rintro p n ⟨s, p, rfl⟩, refine ⟨insert n s, ⟨_, _⟩⟩, { refine rename (subtype.map id _) p * X ⟨n, s.mem_insert_self n⟩, simp only [id.def, or_true, finset.mem_insert, forall_true_iff] {contextual := tt}, }, { simp only [rename_rename, rename_X, subtype.coe_mk, alg_hom.map_mul], refl, }, }, end /-- Every polynomial is a polynomial in finitely many variables. -/ theorem exists_fin_rename (p : mv_polynomial σ R) : ∃ (n : ℕ) (f : fin n → σ) (hf : injective f) (q : mv_polynomial (fin n) R), p = rename f q := begin obtain ⟨s, q, rfl⟩ := exists_finset_rename p, let n := fintype.card {x // x ∈ s}, let e := fintype.equiv_fin {x // x ∈ s}, refine ⟨n, coe ∘ e.symm, subtype.val_injective.comp e.symm.injective, rename e q, _⟩, rw [← rename_rename, rename_rename e], simp only [function.comp, equiv.symm_apply_apply, rename_rename] end end rename lemma eval₂_cast_comp (f : σ → τ) (c : ℤ →+* R) (g : τ → R) (p : mv_polynomial σ ℤ) : eval₂ c (g ∘ f) p = eval₂ c g (rename f p) := mv_polynomial.induction_on p (λ n, by simp only [eval₂_C, rename_C]) (λ p q hp hq, by simp only [hp, hq, rename, eval₂_add, alg_hom.map_add]) (λ p n hp, by simp only [hp, rename, aeval_def, eval₂_X, eval₂_mul]) section coeff @[simp] lemma coeff_rename_map_domain (f : σ → τ) (hf : injective f) (φ : mv_polynomial σ R) (d : σ →₀ ℕ) : (rename f φ).coeff (d.map_domain f) = φ.coeff d := begin apply induction_on' φ, { intros u r, rw [rename_monomial, coeff_monomial, coeff_monomial], simp only [(finsupp.map_domain_injective hf).eq_iff] }, { intros, simp only [*, alg_hom.map_add, coeff_add], } end lemma coeff_rename_eq_zero (f : σ → τ) (φ : mv_polynomial σ R) (d : τ →₀ ℕ) (h : ∀ u : σ →₀ ℕ, u.map_domain f = d → φ.coeff u = 0) : (rename f φ).coeff d = 0 := begin rw [rename_eq, ← not_mem_support_iff], intro H, replace H := map_domain_support H, rw [finset.mem_image] at H, obtain ⟨u, hu, rfl⟩ := H, specialize h u rfl, simp at h hu, contradiction end lemma coeff_rename_ne_zero (f : σ → τ) (φ : mv_polynomial σ R) (d : τ →₀ ℕ) (h : (rename f φ).coeff d ≠ 0) : ∃ u : σ →₀ ℕ, u.map_domain f = d ∧ φ.coeff u ≠ 0 := by { contrapose! h, apply coeff_rename_eq_zero _ _ _ h } @[simp] lemma constant_coeff_rename {τ : Type*} (f : σ → τ) (φ : mv_polynomial σ R) : constant_coeff (rename f φ) = constant_coeff φ := begin apply φ.induction_on, { intro a, simp only [constant_coeff_C, rename_C]}, { intros p q hp hq, simp only [hp, hq, ring_hom.map_add, alg_hom.map_add] }, { intros p n hp, simp only [hp, rename_X, constant_coeff_X, ring_hom.map_mul, alg_hom.map_mul] } end end coeff section support lemma support_rename_of_injective {p : mv_polynomial σ R} {f : σ → τ} (h : function.injective f) : (rename f p).support = finset.image (map_domain f) p.support := begin rw rename_eq, exact finsupp.map_domain_support_of_injective (map_domain_injective h) _, end end support end mv_polynomial
45b86a9069ebaeb27b7eada6fe8ebcf79e3baab2
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/compiler/rbmap_library.lean
a35c09b01ad486506f6b0b4844920c4c20e5f079
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
2,287
lean
import Std open Std def check (b : Bool) : IO Unit := do unless b do IO.println "ERROR" def sz {α β : Type} {cmp : α → α → Ordering} (m : RBMap α β cmp) : Nat := m.fold (fun sz _ _ => sz+1) 0 def depth {α β : Type} {cmp : α → α → Ordering} (m : RBMap α β cmp) : Nat := m.depth Nat.max def tst1 : IO Unit := do let Map := RBMap String Nat compare let m : Map := {} let m := m.insert "hello" 0 let m := m.insert "world" 1 check (m.find? "hello" == some 0) check (m.find? "world" == some 1) let m := m.erase "hello" check (m.find? "hello" == none) check (m.find? "world" == some 1) pure () def tst2 : IO Unit := do let Map := RBMap Nat Nat compare let m : Map := {} let n : Nat := 10000 let mut m := n.fold (fun i (m : Map) => m.insert i (i*10)) m check (m.all (fun k v => v == k*10)) check (sz m == n) IO.println (">> " ++ toString (depth m) ++ ", " ++ toString (sz m)) for i in [:n/2] do m := m.erase (2*i) check (m.all (fun k v => v == k*10)) check (sz m == n / 2) IO.println (">> " ++ toString (depth m) ++ ", " ++ toString (sz m)) pure () abbrev Map := RBMap Nat Nat compare def mkRandMap (max : Nat) : Nat → Map → Array (Nat × Nat) → IO (Map × Array (Nat × Nat)) | 0, m, a => pure (m, a) | n+1, m, a => do let k ← IO.rand 0 max let v ← IO.rand 0 max if m.find? k == none then do let m := m.insert k v let a := a.push (k, v) mkRandMap max n m a else mkRandMap max n m a def tst3 (seed : Nat) (n : Nat) (max : Nat) : IO Unit := do IO.setRandSeed seed let mut (m, a) ← mkRandMap max n {} Array.empty check (sz m == a.size) check (a.all (fun ⟨k, v⟩ => m.find? k == some v)) IO.println ("tst3 size: " ++ toString a.size) let mut i := 0 for (k, b) in a do if i % 2 == 0 then m := m.erase k i := i + 1 check (sz m == a.size / 2) i := 0 for (k, v) in a do if i % 2 == 1 then check (m.find? k == some v) i := i + 1 IO.println ("tst3 after, depth: " ++ toString (depth m) ++ ", size: " ++ toString (sz m)) pure () def main (xs : List String) : IO Unit := tst1 *> tst2 *> tst3 1 1000 20000 *> tst3 2 1000 40000 *> tst3 3 100 4000 *> tst3 4 5000 100000 *> tst3 5 1000 40000 *> pure ()
d01ffbe63c8b5b59a5f6649c1186910304f52380
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/data/int/countable.lean
31fe14d12d34804154ad5c032200ef5c77d44e07
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
1,219
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ import data.equiv data.int.basic data.encodable data.countable open equiv bool sum namespace int definition int_equiv_bool_nat : int ≃ (bool × nat) := equiv.mk (λ i, match i with of_nat a := (tt, a) | neg_succ_of_nat a := (ff, a) end) (λ p, match p with (tt, a) := of_nat a | (ff, a) := neg_succ_of_nat a end) (λ i, begin cases i, repeat reflexivity end) (λ p, begin cases p with b a, cases b, repeat reflexivity end) definition int_equiv_nat : int ≃ nat := calc int ≃ (bool × nat) : int_equiv_bool_nat ... ≃ ((unit + unit) × nat) : prod_congr bool_equiv_unit_sum_unit !_root_.equiv.refl ... ≃ (unit × nat) + (unit × nat) : sum_prod_distrib ... ≃ nat + nat : sum_congr !prod_unit_left !prod_unit_left ... ≃ nat : nat_sum_nat_equiv_nat attribute [instance] definition encodable_int : encodable int := encodable_of_equiv (_root_.equiv.symm int_equiv_nat) lemma countable_int : countable int := countable_of_encodable encodable_int end int
1729bbf844e68e0351776e42b9c27772bc376faa
ebbdcbd7ddc89a9ef7c3b397b301d5f5272a918f
/qp/p1_categories/c2_limits/s1_limits.lean
f7914c0c5c823ed39e7c6f0e08a9c6151de95787
[]
no_license
intoverflow/qvr
34b9ef23604738381ca20b7d622fd0399d88f2dd
0cfcd33fe4bf8d93851a00cec5bfd21e77105d74
refs/heads/master
1,616,591,570,371
1,492,575,772,000
1,492,575,772,000
80,061,627
0
0
null
null
null
null
UTF-8
Lean
false
false
48,424
lean
/- ----------------------------------------------------------------------- Limits and co-limits. ----------------------------------------------------------------------- -/ import ..c1_basic namespace qp open stdaux universe variables ℓobjx ℓhomx ℓobj ℓhom ℓobj₁ ℓhom₁ ℓobj₂ ℓhom₂ ℓobj₃ ℓhom₃ /- ----------------------------------------------------------------------- Limits. ----------------------------------------------------------------------- -/ /-! #brief A limit of a functor. -/ @[class] definition HasLimit {X : Cat.{ℓobjx ℓhomx}} {C : Cat.{ℓobj₁ ℓhom₁}} (L : Fun X C) := HasFinal (ConeCat L) instance HasLimit.ConeCat_HasFinal {X : Cat.{ℓobjx ℓhomx}} {C : Cat.{ℓobj₁ ℓhom₁}} (L : Fun X C) [L_HasLimit : HasLimit L] : HasFinal (ConeCat L) := L_HasLimit /-! #brief Casting a HasLimit along heterogeneous equality. -/ definition HasLimit.heq : ∀ {X₁ X₂ : Cat.{ℓobjx ℓhomx}} (ωX : X₁ = X₂) {C₁ C₂ : Cat.{ℓobj₁ ℓhom₁}} (ωC : C₁ = C₂) {L₁ : Fun X₁ C₁} {L₂ : Fun X₂ C₂} (ωL : L₁ == L₂) , HasLimit L₁ = HasLimit L₂ | X .(X) (eq.refl .(X)) C .(C) (eq.refl .(C)) L .(L) (heq.refl .(L)) := rfl /-! #brief A category with all limits out of another category. -/ class HasAllLimitsFrom (C : Cat.{ℓobj₁ ℓhom₁}) (X : Cat.{ℓobjx ℓhomx}) := (has_limit : ∀ (L : Fun X C), HasLimit L) instance HasAllLimitsFrom.HasLimit (C : Cat.{ℓobj₁ ℓhom₁}) {X : Cat.{ℓobjx ℓhomx}} (L : Fun X C) [C_HasAllLimitsFrom_X : HasAllLimitsFrom C X] : HasLimit L := HasAllLimitsFrom.has_limit L /-! #brief A category with all limits. -/ class HasAllLimits (C : Cat.{ℓobj₁ ℓhom₁}) := (has_limit : ∀ {X : Cat.{ℓobjx ℓhomx}} (L : Fun X C) , HasLimit L) instance HasAllLimits.HasAllLimitsFrom (C : Cat.{ℓobj₁ ℓhom₁}) [C_HasAllLimits : HasAllLimits.{ℓobjx ℓhomx ℓobj₁ ℓhom₁} C] (X : Cat.{ℓobjx ℓhomx}) : HasAllLimitsFrom C X := { has_limit := λ L, HasAllLimits.has_limit L } instance HasAllLimits.HasLimit {C : Cat.{ℓobj₁ ℓhom₁}} [C_HasAllLimits : HasAllLimits.{ℓobjx ℓhomx ℓobj₁ ℓhom₁} C] {X : Cat.{ℓobjx ℓhomx}} (L : Fun X C) : HasLimit L := HasAllLimits.has_limit L /-! #brief Helper for showing a functor has a limit. -/ definition HasLimit.show {X : Cat.{ℓobjx ℓhomx}} {C : Cat.{ℓobj₁ ℓhom₁}} {L : Fun X C} (l : C^.obj) (out : ∀ (x : X^.obj), C^.hom l (L^.obj x)) (ωout : ∀ {x₁ x₂ : X^.obj} (f : X^.hom x₁ x₂) , out x₂ = C^.circ (L^.hom f) (out x₁)) (univ : ∀ (c : C^.obj) (hom : ∀ (x : X^.obj), C^.hom c (L^.obj x)) (comm : ∀ {x₁ x₂ : X^.obj} (f : X^.hom x₁ x₂) , hom x₂ = C^.circ (L^.hom f) (hom x₁)) , C^.hom c l) (ωuniv : ∀ (c : C^.obj) (hom : ∀ (x : X^.obj), C^.hom c (L^.obj x)) (comm : ∀ {x₁ x₂ : X^.obj} (f : X^.hom x₁ x₂) , hom x₂ = C^.circ (L^.hom f) (hom x₁)) (x : X^.obj) , hom x = C^.circ (out x) (univ c hom @comm)) (ωuniq : ∀ (c : C^.obj) (hom : ∀ (x : X^.obj), C^.hom c (L^.obj x)) (comm : ∀ {x₁ x₂ : X^.obj} (f : X^.hom x₁ x₂) , hom x₂ = C^.circ (L^.hom f) (hom x₁)) (f : C^.hom c l) (ωf : ∀ (x : X^.obj), hom x = C^.circ (out x) f) , f = univ c hom @comm) : HasLimit L := HasFinal.show { obj := l, hom := out, comm := @ωout } (λ cone, { mediate := univ cone^.obj cone^.hom (@Cone.comm _ _ _ cone) , factor := ωuniv cone^.obj cone^.hom (@Cone.comm _ _ _ cone) }) (λ cone cone_hom , ConeHom.eq (ωuniq cone^.obj cone^.hom (@Cone.comm _ _ _ cone) cone_hom^.mediate cone_hom^.factor)) /-! #brief Limits are cones. -/ definition limit.cone {X : Cat.{ℓobjx ℓhomx}} {C : Cat.{ℓobj₁ ℓhom₁}} (F : Fun X C) [F_HasLimit : HasLimit F] : Cone F := final (ConeCat F) /-! #brief The limit object of a functor. -/ definition limit {X : Cat.{ℓobjx ℓhomx}} {C : Cat.{ℓobj₁ ℓhom₁}} (F : Fun X C) [F_HasLimit : HasLimit F] : C^.obj := (limit.cone F)^.obj /-! #brief A map out of the limit. -/ definition limit.out {X : Cat.{ℓobjx ℓhomx}} {C : Cat.{ℓobj₁ ℓhom₁}} (F : Fun X C) [F_HasLimit : HasLimit F] (x : X^.obj) : C^.hom (limit F) (F^.obj x) := (final (ConeCat F))^.hom x /-! #brief The limit-out maps commute with the diagram. -/ theorem limit.out.comm {X : Cat.{ℓobjx ℓhomx}} {C : Cat.{ℓobj₁ ℓhom₁}} (F : Fun X C) [F_HasLimit : HasLimit F] {x₁ x₂ : X^.obj} (f : X^.hom x₁ x₂) : limit.out F x₂ = C^.circ (F^.hom f) (limit.out F x₁) := (final (ConeCat F))^.comm f /-! #brief Every cone is mediated through the limit. -/ definition limit.univ {X : Cat.{ℓobjx ℓhomx}} {C : Cat.{ℓobj₁ ℓhom₁}} (F : Fun X C) [F_HasLimit : HasLimit F] (c : Cone F) : C^.hom c^.obj (limit F) := (@final_hom (ConeCat F) _ c)^.mediate /-! #brief Every cone is mediated through the limit. -/ theorem limit.univ.mediates {X : Cat.{ℓobjx ℓhomx}} {C : Cat.{ℓobj₁ ℓhom₁}} {F : Fun X C} {F_HasLimit : HasLimit F} (c : Cone F) (x : X^.obj) : c^.hom x = C^.circ (limit.out F x) (limit.univ F c) := (@final_hom (ConeCat F) _ c)^.factor x /-! #brief The mediating map from a cone to the limit is unique. -/ theorem limit.univ.uniq {X : Cat.{ℓobjx ℓhomx}} {C : Cat.{ℓobj₁ ℓhom₁}} {F : Fun X C} {F_HasLimit : HasLimit F} (c : Cone F) (m : C^.hom c^.obj (limit F)) (ω : ∀ (x : X^.obj), c^.hom x = limit.out F x ∘∘ m) : m = limit.univ F c := let m' : ConeHom F c (limit.cone F) := { mediate := m , factor := ω } in let ωm' : m' = @final_hom (ConeCat F) _ c := final_hom.uniq (ConeCat F) in congr_arg ConeHom.mediate ωm' /-! #brief The unique iso between two limits of the same functor. -/ definition limit.iso {X : Cat.{ℓobjx ℓhomx}} {C : Cat.{ℓobj₁ ℓhom₁}} {F : Fun X C} (F_HasLimit₁ F_HasLimit₂ : HasLimit F) : C^.hom (@limit X C F F_HasLimit₁) (@limit X C F F_HasLimit₂) := @limit.univ X C F F_HasLimit₂ (@limit.cone X C F F_HasLimit₁) /-! #brief Limits are unique up-to unique isomorphism. -/ theorem limit.uniq {X : Cat.{ℓobjx ℓhomx}} {C : Cat.{ℓobj₁ ℓhom₁}} {F : Fun X C} (F_HasLimit₁ F_HasLimit₂ : HasLimit F) : Iso (limit.iso F_HasLimit₁ F_HasLimit₂) (limit.iso F_HasLimit₂ F_HasLimit₁) := { id₁ := eq.trans (eq.symm ConeHom.comp.simp_mediate) (congr_arg ConeHom.mediate (HasFinal_uniq F_HasLimit₁ F_HasLimit₂)^.id₁) , id₂ := eq.trans (eq.symm ConeHom.comp.simp_mediate) (congr_arg ConeHom.mediate (HasFinal_uniq F_HasLimit₁ F_HasLimit₂)^.id₂) } /-! #brief limit.univ absorbs compositions. -/ theorem limit.circ_univ {X : Cat.{ℓobjx ℓhomx}} {C : Cat.{ℓobj₁ ℓhom₁}} (F : Fun X C) {F_HasLimit : HasLimit F} (cone : Cone F) {c' : C^.obj} (f : C^.hom c' cone^.obj) : @limit.univ X C F F_HasLimit cone ∘∘ f = @limit.univ X C F F_HasLimit (cone^.circ f) := begin refine limit.univ.uniq (cone^.circ f) _ _, intro x, dsimp [Cone.circ], rw C^.circ_assoc, apply Cat.circ.congr_left, apply limit.univ.mediates end /- ----------------------------------------------------------------------- Preservation of limits by functors. ----------------------------------------------------------------------- -/ /-! #brief A functor which preserves a limit. -/ @[class] definition PresLimit {X : Cat.{ℓobjx ℓhomx}} {B : Cat.{ℓobj₁ ℓhom₁}} {C : Cat.{ℓobj₂ ℓhom₂}} (L : Fun X B) (F : Fun B C) := PresFinal (LeftConeFun F L) /-! #brief A functor which preserves colimits out of a given category. -/ class PresLimitsFrom {B : Cat.{ℓobj₁ ℓhom₁}} {C : Cat.{ℓobj₂ ℓhom₂}} (F : Fun B C) (X : Cat.{ℓobjx ℓhomx}) := (pres_limit : ∀ (L : Fun X B) , PresLimit L F) instance PresLimitsFrom.PresLimit {B : Cat.{ℓobj₁ ℓhom₁}} {C : Cat.{ℓobj₂ ℓhom₂}} (F : Fun B C) {X : Cat.{ℓobjx ℓhomx}} [F_PresLimitsFrom : PresLimitsFrom F X] (L : Fun X B) : PresLimit L F := PresLimitsFrom.pres_limit F L /-! #brief Functors which preserve limits yield instances of HasLimit. -/ instance PresLimit.HasLimit {X : Cat.{ℓobjx ℓhomx}} {B : Cat.{ℓobj₁ ℓhom₁}} {C : Cat.{ℓobj₂ ℓhom₂}} (L : Fun X B) [L_HasLimit : HasLimit L] (F : Fun B C) [F_PresLimit : PresLimit L F] : HasLimit (Fun.comp F L) := @PresFinal.HasFinal _ _ L_HasLimit (LeftConeFun F L) F_PresLimit /-! #brief Helper for showing that a functor preserves a limit. -/ definition PresLimit.show {X : Cat.{ℓobjx ℓhomx}} {B : Cat.{ℓobj₁ ℓhom₁}} {C : Cat.{ℓobj₂ ℓhom₂}} {L : Fun X B} {F : Fun B C} (mediate : ∀ [L_HasLimit : HasLimit L] (c : C^.obj) (hom : ∀ (x : X^.obj), C^.hom c (F^.obj (L^.obj x))) (ωcomm : ∀ {x₁ x₂ : X^.obj} (f : X^.hom x₁ x₂) , hom x₂ = C^.circ (F^.hom (L^.hom f)) (hom x₁)) , C^.hom c (F^.obj (limit L))) (ωmediate : ∀ [L_HasLimit : HasLimit L] (c : C^.obj) (hom : ∀ (x : X^.obj), C^.hom c (F^.obj (L^.obj x))) (ωcomm : ∀ {x₁ x₂ : X^.obj} (f : X^.hom x₁ x₂) , hom x₂ = C^.circ (F^.hom (L^.hom f)) (hom x₁)) (x : X^.obj) , hom x = F^.hom (limit.out L x) ∘∘ mediate c hom @ωcomm) (ωuniq : ∀ [L_HasLimit : HasLimit L] (c : C^.obj) (hom : ∀ (x : X^.obj), C^.hom c (F^.obj (L^.obj x))) (ωcomm : ∀ {x₁ x₂ : X^.obj} (f : X^.hom x₁ x₂) , hom x₂ = C^.circ (F^.hom (L^.hom f)) (hom x₁)) (f : C^.hom c (F^.obj (limit L))) (ωf : ∀ (x : X^.obj), hom x = C^.circ (F^.hom (limit.out L x)) f) , f = mediate c hom @ωcomm) : PresLimit L F := { hom := λ L_HasLimit cone , { mediate := @mediate L_HasLimit cone^.obj cone^.hom (@Cone.comm _ _ _ cone) , factor := @ωmediate L_HasLimit cone^.obj cone^.hom (@Cone.comm _ _ _ cone) } , pres := λ L_HasLimit , { hom_uniq := λ cone h, ConeHom.eq (@ωuniq L_HasLimit cone^.obj cone^.hom (@Cone.comm _ _ _ cone) h^.mediate h^.factor) } } /-! #brief Preservation of limits by compositions of functors. -/ definition PresLimit.comp {X : Cat.{ℓobjx ℓhomx}} {B : Cat.{ℓobj₁ ℓhom₁}} {C : Cat.{ℓobj₂ ℓhom₂}} {D : Cat.{ℓobj₃ ℓhom₃}} (L : Fun X B) (F : Fun B C) [F_PresLimit : PresLimit L F] (G : Fun C D) [G_PresLimit : PresLimit (Fun.comp F L) G] : PresLimit L (Fun.comp G F) := sorry -- TODO: prove by showing preservation of final composes. /-! #brief A limit of a functor. -/ theorem preslimit {X : Cat.{ℓobjx ℓhomx}} {B : Cat.{ℓobj₁ ℓhom₁}} {C : Cat.{ℓobj₂ ℓhom₂}} (L : Fun X B) [L_HasLimit : HasLimit L] (F : Fun B C) [F_PresLimit : PresLimit L F] : limit (Fun.comp F L) = F^.obj (limit L) := rfl /-! #brief A map out of the limit. -/ theorem preslimit.out {X : Cat.{ℓobjx ℓhomx}} {B : Cat.{ℓobj₁ ℓhom₁}} {C : Cat.{ℓobj₂ ℓhom₂}} (L : Fun X B) [L_HasLimit : HasLimit L] (F : Fun B C) [F_PresLimit : PresLimit L F] (x : X^.obj) : limit.out (Fun.comp F L) x = F^.hom (limit.out L x) := rfl /-! #brief Every cone is mediated through the limit. -/ definition preslimit.univ {X : Cat.{ℓobjx ℓhomx}} {B : Cat.{ℓobj₁ ℓhom₁}} {C : Cat.{ℓobj₂ ℓhom₂}} (L : Fun X B) [L_HasLimit : HasLimit L] (F : Fun B C) [F_PresLimit : PresLimit L F] (c : Cone L) : limit.univ _ ((LeftConeFun F L)^.obj c) = by exact F^.hom (limit.univ _ c) := begin apply eq.symm, apply limit.univ.uniq ((LeftConeFun F L)^.obj c), intro x, dsimp [LeftConeFun], rw preslimit.out, refine eq.trans _ F^.hom_circ, rw limit.univ.mediates c x, trivial end /- ----------------------------------------------------------------------- Final objects as limits. ----------------------------------------------------------------------- -/ /-! #brief If the initial functor has a limit, then the category has a final. -/ instance InitFun.HasLimit_HasFinal {C : Cat.{ℓobj ℓhom}} [InitFun_HasLimit : HasLimit (InitFun.{ℓobjx ℓhomx} C)] : HasFinal C := let mkcone : C^.obj → Cone (InitFun.{ℓobjx ℓhomx} C) := λ c, { obj := c , hom := λ e, by cases e , comm := λ e₁ e₂ f, by cases f } in HasFinal.show (limit (InitFun.{ℓobjx ℓhomx} C)) (λ c, limit.univ _ (mkcone c)) (λ c h, limit.univ.uniq (mkcone c) h (λ e, by cases e)) /-! #brief If the category has a final, then the initial functor has a limit. -/ definition InitFun.HasFinal_HasLimit {C : Cat.{ℓobj ℓhom}} [HasFinal C] : HasLimit (InitFun.{ℓobjx ℓhomx} C) := HasLimit.show (final C) (λ e, by cases e) (λ x₁ x₂ f, by cases f) (λ c hom ωcomm, final_hom c) (λ c hom ωcomm e, by cases e) (λ c hom ωcomm f e, final_hom.uniq C) /-! #brief Functors which preserve limits of the initial functor preserve final objects. -/ instance PresLimit.InitFun_PresFinal {C : Cat.{ℓobj₁ ℓhom₁}} {D : Cat.{ℓobj₂ ℓhom₂}} (F : Fun C D) [F_PresLimit : PresLimit (InitFun.{ℓobjx ℓhomx} C) F] : PresFinal F := let mk_cone : ∀ (d : D^.obj), Cone (F □□ InitFun.{ℓobjx ℓhomx} C) := λ d, { obj := d , hom := λ e, by cases e , comm := λ e₁ e₂ f, by cases f } in let mk_lim : ∀ (C_HasFinal : HasFinal C) , HasLimit (F □□ InitFun.{ℓobjx ℓhomx} C) := λ C_HasFinal, @PresLimit.HasLimit _ _ _ _ (@InitFun.HasFinal_HasLimit C C_HasFinal) _ F_PresLimit in { hom := λ C_HasFinal d, @limit.univ _ _ _ (mk_lim C_HasFinal) (mk_cone d) , pres := λ C_HasFinal , { hom_uniq := λ d h , begin apply (@limit.univ.uniq _ _ _ (mk_lim C_HasFinal) (mk_cone d) h _), { intro e, cases e } end } } /- ----------------------------------------------------------------------- The limit functor. ----------------------------------------------------------------------- -/ /-! #brief The cone used by the limit functor. -/ definition LimitFun.cone {X : Cat.{ℓobjx ℓhomx}} {C : Cat.{ℓobj ℓhom}} [C_HasAllLimitsFrom_X : HasAllLimitsFrom C X] (L₁ L₂ : Fun X C) (η : NatTrans L₁ L₂) : Cone L₂ := { obj := limit L₁ , hom := λ x, η^.com x ∘∘ limit.out L₁ x , comm := λ x₁ x₂ f , begin rw C^.circ_assoc, rw -(η^.natural f), rw -C^.circ_assoc, apply Cat.circ.congr_right, apply limit.out.comm end } /-! #brief The limit functor. -/ definition LimitFun {X : Cat.{ℓobjx ℓhomx}} {C : Cat.{ℓobj ℓhom}} [C_HasAllLimitsFrom_X : HasAllLimitsFrom C X] : Fun (FunCat X C) C := { obj := λ L, limit L , hom := λ L₁ L₂ η, limit.univ L₂ (LimitFun.cone L₁ L₂ η) , hom_id := λ L, begin apply eq.symm, apply limit.univ.uniq (LimitFun.cone L L (NatTrans.id L)), intro x, exact eq.trans C^.circ_id_left (eq.symm C^.circ_id_right) end , hom_circ := λ L₁ L₂ L₃ η₂₃ η₁₂ , begin apply eq.symm, apply limit.univ.uniq (LimitFun.cone L₁ L₃ (NatTrans.comp η₂₃ η₁₂)), intro x, refine eq.trans _ (eq.symm (Cat.circ.congr_right (limit.circ_univ L₃ (LimitFun.cone L₂ L₃ η₂₃) (limit.univ L₂ (LimitFun.cone L₁ L₂ η₁₂))))), refine eq.trans _ (limit.univ.mediates (Cone.circ (LimitFun.cone L₂ L₃ η₂₃) (limit.univ L₂ (LimitFun.cone L₁ L₂ η₁₂))) x), apply eq.trans (eq.symm C^.circ_assoc), refine eq.symm (eq.trans (eq.symm C^.circ_assoc) (eq.symm _)), apply Cat.circ.congr_right, exact limit.univ.mediates (LimitFun.cone L₁ L₂ η₁₂) x end } /- ----------------------------------------------------------------------- Limits in functor categories. ----------------------------------------------------------------------- -/ /-! #brief Projection for pointwise limits. -/ definition FunCat.HasLimit.out {C : Cat.{ℓobj₁ ℓhom₁}} {D : Cat.{ℓobj₂ ℓhom₂}} {X : Cat.{ℓobjx ℓhomx}} [D_HasAllLimitsFrom_X : HasAllLimitsFrom D X] (F : Fun X (FunCat C D)) (x : X^.obj) : NatTrans (LimitFun □□ Fun.swap F) (F^.obj x) := { com := λ c, limit.out (Fun.swap.obj F c) x , natural := λ c₁ c₂ f , eq.symm (limit.univ.mediates (LimitFun.cone (Fun.swap.obj F c₁) (Fun.swap.obj F c₂) (Fun.swap.hom F c₁ c₂ f)) x) } /-! #brief Cone used for pointwise universal maps. -/ definition FunCat.HasLimit.univ.cone {C : Cat.{ℓobj₁ ℓhom₁}} {D : Cat.{ℓobj₂ ℓhom₂}} {X : Cat.{ℓobjx ℓhomx}} [D_HasAllLimitsFrom_X : HasAllLimitsFrom D X] (F : Fun X (FunCat C D)) (L : Fun C D) (η : ∀ (x : X^.obj), NatTrans L (F^.obj x)) (ωη : ∀ {x₁ x₂ : X^.obj} (f : X^.hom x₁ x₂) , η x₂ = NatTrans.comp (F^.hom f) (η x₁)) (c : C^.obj) : Cone (Fun.swap.obj F c) := { obj := L^.obj c , hom := λ x, (η x)^.com c , comm := λ c₁ c₂ f , begin rw ωη f, trivial end } /-! #brief Universal map for pointwise limits. -/ definition FunCat.HasLimit.univ {C : Cat.{ℓobj₁ ℓhom₁}} {D : Cat.{ℓobj₂ ℓhom₂}} {X : Cat.{ℓobjx ℓhomx}} [D_HasAllLimitsFrom_X : HasAllLimitsFrom D X] (F : Fun X (FunCat C D)) (L : Fun C D) (η : ∀ (x : X^.obj), NatTrans L (F^.obj x)) (ωη : ∀ {x₁ x₂ : X^.obj} (f : X^.hom x₁ x₂) , η x₂ = NatTrans.comp (F^.hom f) (η x₁)) : NatTrans L (LimitFun □□ Fun.swap F) := { com := λ c, limit.univ (Fun.swap.obj F c) (FunCat.HasLimit.univ.cone F L η @ωη c) , natural := λ c₁ c₂ f , begin dsimp [LimitFun], apply eq.trans (limit.circ_univ (Fun.swap.obj F c₂) (FunCat.HasLimit.univ.cone F L η @ωη c₂) (L^.hom f)), apply eq.symm, apply eq.trans (limit.circ_univ ((Fun.swap F)^.obj c₂) (LimitFun.cone ((Fun.swap F)^.obj c₁) ((Fun.swap F)^.obj c₂) ((Fun.swap F)^.hom f)) (limit.univ (Fun.swap.obj F c₁) (FunCat.HasLimit.univ.cone F L η @ωη c₁))), apply limit.univ.uniq (Cone.circ (FunCat.HasLimit.univ.cone F L η @ωη c₂) (L^.hom f)), intro x, apply eq.trans ((η x)^.natural f), refine eq.trans _ (limit.univ.mediates (Cone.circ (LimitFun.cone ((Fun.swap F)^.obj c₁) ((Fun.swap F)^.obj c₂) ((Fun.swap F)^.hom f)) (limit.univ (Fun.swap.obj F c₁) (FunCat.HasLimit.univ.cone F L η @ωη c₁))) x), refine eq.symm (eq.trans (eq.symm D^.circ_assoc) (eq.symm _)), apply Cat.circ.congr_right, apply limit.univ.mediates (FunCat.HasLimit.univ.cone F L η @ωη c₁) x end } /-! #brief Limits in FunCat can be computed pointwise. -/ instance FunCat.HasLimit {C : Cat.{ℓobj₁ ℓhom₁}} {D : Cat.{ℓobj₂ ℓhom₂}} {X : Cat.{ℓobjx ℓhomx}} [D_HasAllLimitsFrom_X : HasAllLimitsFrom D X] (F : Fun X (FunCat C D)) : HasLimit F := HasLimit.show (LimitFun □□ F^.swap) (FunCat.HasLimit.out F) (λ x₁ x₂ f , begin apply NatTrans.eq, apply funext, intro c, apply limit.out.comm end) (FunCat.HasLimit.univ F) (λ L hom ωhom x , begin apply NatTrans.eq, apply funext, intro c, apply limit.univ.mediates (FunCat.HasLimit.univ.cone F L hom @ωhom c) end) (λ L hom ωhom h ωh , begin apply NatTrans.eq, apply funext, intro c, apply limit.univ.uniq (FunCat.HasLimit.univ.cone F L hom @ωhom c), intro x, apply NatTrans.congr_com (ωh x) end) /-! #brief Limits in functor categories can be computed pointwise. -/ instance FunCat.HasAllLimits {C : Cat.{ℓobj₁ ℓhom₁}} {D : Cat.{ℓobj₂ ℓhom₂}} [D_HasAllLimits : HasAllLimits.{ℓobjx ℓhomx} D] : HasAllLimits.{ℓobjx ℓhomx} (FunCat C D) := { has_limit := λ X L, @FunCat.HasLimit C D X (HasAllLimits.HasAllLimitsFrom D X) L } /- ----------------------------------------------------------------------- Limits and natural isomorphisms. ----------------------------------------------------------------------- -/ /-! #brief Natural isomorphism cast limits (cone used for universal). -/ definition NatIso.HasLimit.cone {X : Cat.{ℓobjx ℓhomx}} {C : Cat.{ℓobj₁ ℓhom₁}} {L₁ L₂ : Fun X C} {η₁₂ : NatTrans L₁ L₂} {η₂₁ : NatTrans L₂ L₁} (η_iso : NatIso η₁₂ η₂₁) [L₁_HasLimit : HasLimit L₁] (c : C^.obj) (hom : Π (x : ⟦X⟧), ⟦C : c →→ L₂^.obj x⟧) (ωhom : ∀ {x₁ x₂ : ⟦X⟧} (f : ⟦X : x₁ →→ x₂⟧), hom x₂ = L₂^.hom f ∘∘ hom x₁) : Cone L₁ := { obj := c , hom := λ x, η₂₁^.com x ∘∘ hom x , comm := λ x₁ x₂ f , begin rw C^.circ_assoc, rw -(η₂₁^.natural f), rw -C^.circ_assoc, apply Cat.circ.congr_right, apply ωhom end } /-! #brief Natural isomorphism cast limits. -/ definition NatIso.HasLimit₂ {X : Cat.{ℓobjx ℓhomx}} {C : Cat.{ℓobj₁ ℓhom₁}} {L₁ L₂ : Fun X C} {η₁₂ : NatTrans L₁ L₂} {η₂₁ : NatTrans L₂ L₁} (η_iso : NatIso η₁₂ η₂₁) [L₁_HasLimit : HasLimit L₁] : HasLimit L₂ := HasLimit.show (limit L₁) (λ x, η₁₂^.com x ∘∘ limit.out L₁ x) (λ x₁ x₂ f , begin rw C^.circ_assoc, rw -(η₁₂^.natural f), rw -C^.circ_assoc, apply Cat.circ.congr_right, apply limit.out.comm end) (λ c hom ωhom, limit.univ L₁ (NatIso.HasLimit.cone η_iso c hom @ωhom)) (λ c hom ωhom x , begin rw -C^.circ_assoc, apply eq.symm, apply eq.trans (eq.symm (Cat.circ.congr_right (limit.univ.mediates (NatIso.HasLimit.cone η_iso c hom @ωhom) x))), apply eq.trans C^.circ_assoc, apply eq.trans (Cat.circ.congr_left (NatTrans.congr_com η_iso^.id₂)), apply C^.circ_id_left end) (λ c hom ωhom h ωh , begin apply limit.univ.uniq (NatIso.HasLimit.cone η_iso c hom @ωhom), intro x, apply eq.trans (Cat.circ.congr_right (ωh x)), repeat { rw C^.circ_assoc }, apply Cat.circ.congr_left, apply eq.trans (Cat.circ.congr_left (NatTrans.congr_com η_iso^.id₁)), apply C^.circ_id_left end) /-! #brief Natural isomorphism cast limits. -/ definition NatIso.HasLimit₁ {X : Cat.{ℓobjx ℓhomx}} {C : Cat.{ℓobj₁ ℓhom₁}} {L₁ L₂ : Fun X C} {η₁₂ : NatTrans L₁ L₂} {η₂₁ : NatTrans L₂ L₁} (η_iso : NatIso η₁₂ η₂₁) [L₂_HasLimit : HasLimit L₂] : HasLimit L₁ := NatIso.HasLimit₂ η_iso^.flip /- ----------------------------------------------------------------------- Co-limits. ----------------------------------------------------------------------- -/ /-! #brief A co-limit of a functor. -/ @[class] definition HasCoLimit {X : Cat.{ℓobjx ℓhomx}} {C : Cat.{ℓobj₁ ℓhom₁}} (L : Fun X C) := HasLimit (OpFun L) instance HasCoLimit.Op_HasLimit {X : Cat.{ℓobjx ℓhomx}} {C : Cat.{ℓobj₁ ℓhom₁}} (L : Fun X C) [L_HasCoLimit : HasCoLimit L] : HasLimit (OpFun L) := L_HasCoLimit /-! #brief Casting a HasCoLimit along heterogeneous equality. -/ definition HasCoLimit.heq : ∀ {X₁ X₂ : Cat.{ℓobjx ℓhomx}} (ωX : X₁ = X₂) {C₁ C₂ : Cat.{ℓobj₁ ℓhom₁}} (ωC : C₁ = C₂) {L₁ : Fun X₁ C₁} {L₂ : Fun X₂ C₂} (ωL : L₁ == L₂) , HasCoLimit L₁ = HasCoLimit L₂ | X .(X) (eq.refl .(X)) C .(C) (eq.refl .(C)) L .(L) (heq.refl .(L)) := rfl /-! #brief A category with all co-limits. -/ class HasAllCoLimits (C : Cat.{ℓobj₁ ℓhom₁}) := (has_colimit : ∀ {X : Cat.{ℓobjx ℓhomx}} (L : Fun X C) , HasCoLimit L) instance HasAllCoLimits.HasCoLimit {C : Cat.{ℓobj₁ ℓhom₁}} [C_HasAllCoLimits : HasAllCoLimits.{ℓobjx ℓhomx ℓobj₁ ℓhom₁} C] {X : Cat.{ℓobjx ℓhomx}} (L : Fun X C) : HasCoLimit L := HasAllCoLimits.has_colimit L /-! #brief A category with all co-limits out of another category. -/ class HasAllCoLimitsFrom (C : Cat.{ℓobj₁ ℓhom₁}) (X : Cat.{ℓobjx ℓhomx}) := (has_colimit : ∀ (L : Fun X C), HasCoLimit L) instance HasAllCoLimitsFrom.HasCoLimit (C : Cat.{ℓobj₁ ℓhom₁}) {X : Cat.{ℓobjx ℓhomx}} (L : Fun X C) [C_HasAllCoLimitsFrom_X : HasAllCoLimitsFrom C X] : HasCoLimit L := HasAllCoLimitsFrom.has_colimit L instance HasAllCoLimits.HasAllCoLimitsFrom (C : Cat.{ℓobj₁ ℓhom₁}) [C_HasAllCoLimits : HasAllCoLimits.{ℓobjx ℓhomx} C] (X : Cat.{ℓobjx ℓhomx}) : HasAllCoLimitsFrom C X := { has_colimit := λ L, HasAllCoLimits.has_colimit L } /-! #brief Helper for showing a functor has a co-limit. -/ definition HasCoLimit.show {X : Cat.{ℓobjx ℓhomx}} {C : Cat.{ℓobj₁ ℓhom₁}} {L : Fun X C} (l : C^.obj) (into : ∀ (x : X^.obj), C^.hom (L^.obj x) l) (ωinto : ∀ {x₁ x₂ : X^.obj} (f : X^.hom x₁ x₂) , into x₁ = C^.circ (into x₂) (L^.hom f)) (univ : ∀ (c : C^.obj) (hom : ∀ (x : X^.obj), C^.hom (L^.obj x) c) (comm : ∀ {x₁ x₂ : X^.obj} (f : X^.hom x₁ x₂) , hom x₁ = C^.circ (hom x₂) (L^.hom f)) , C^.hom l c) (ωuniv : ∀ (c : C^.obj) (hom : ∀ (x : X^.obj), C^.hom (L^.obj x) c) (comm : ∀ {x₁ x₂ : X^.obj} (f : X^.hom x₁ x₂) , hom x₁ = C^.circ (hom x₂) (L^.hom f)) (x : X^.obj) , hom x = C^.circ (univ c hom @comm) (into x)) (ωuniq : ∀ (c : C^.obj) (hom : ∀ (x : X^.obj), C^.hom (L^.obj x) c) (comm : ∀ {x₁ x₂ : X^.obj} (f : X^.hom x₁ x₂) , hom x₁ = C^.circ (hom x₂) (L^.hom f)) (f : C^.hom l c) (ωf : ∀ (x : X^.obj), hom x = C^.circ f (into x)) , f = univ c hom @comm) : HasCoLimit L := HasLimit.show l into (λ x₂ x₁ f, ωinto f) (λ c hom comm, univ c hom (λ x₂ x₁ f, comm f)) (λ c hom comm, ωuniv c hom (λ x₂ x₁ f, comm f)) (λ c hom comm, ωuniq c hom (λ x₂ x₁ f, comm f)) /-! #brief Co-limits are co-cones. -/ definition colimit.cocone {X : Cat.{ℓobjx ℓhomx}} {C : Cat.{ℓobj₁ ℓhom₁}} (F : Fun X C) [F_HasCoLimit : HasCoLimit F] : CoCone F := limit.cone (OpFun F) /-! #brief The co-limit object of a functor. -/ definition colimit {X : Cat.{ℓobjx ℓhomx}} {C : Cat.{ℓobj₁ ℓhom₁}} (F : Fun X C) [F_HasCoLimit : HasCoLimit F] : C^.obj := @limit (OpCat X) (OpCat C) (OpFun F) F_HasCoLimit /-! #brief A map into the colimit. -/ definition colimit.in {X : Cat.{ℓobjx ℓhomx}} {C : Cat.{ℓobj₁ ℓhom₁}} (F : Fun X C) [F_HasCoLimit : HasCoLimit F] (x : X^.obj) : C^.hom (F^.obj x) (colimit F) := limit.out (OpFun F) x /-! #brief The co-limit-in maps commute with the diagram. -/ theorem colimit.in.comm {X : Cat.{ℓobjx ℓhomx}} {C : Cat.{ℓobj₁ ℓhom₁}} (F : Fun X C) [F_HasCoLimit : HasCoLimit F] {x₁ x₂ : X^.obj} (f : X^.hom x₁ x₂) : colimit.in F x₁ = C^.circ (colimit.in F x₂) (F^.hom f) := limit.out.comm (OpFun F) f /-! #brief Every co-cone is mediated through the co-limit. -/ definition colimit.univ {X : Cat.{ℓobjx ℓhomx}} {C : Cat.{ℓobj₁ ℓhom₁}} (F : Fun X C) {F_HasCoLimit : HasCoLimit F} (c : CoCone F) : C^.hom (colimit F) c^.obj := limit.univ _ c /-! #brief Every co-cone is mediated through the co-limit. -/ theorem colimit.univ.mediates {X : Cat.{ℓobjx ℓhomx}} {C : Cat.{ℓobj₁ ℓhom₁}} {F : Fun X C} {F_HasCoLimit : HasCoLimit F} (c : CoCone F) (x : X^.obj) : c^.hom x = C^.circ (colimit.univ F c) (colimit.in F x) := limit.univ.mediates c x /-! #brief The mediating map to a co-cone from the co-limit is unique. -/ theorem colimit.univ.uniq {X : Cat.{ℓobjx ℓhomx}} {C : Cat.{ℓobj₁ ℓhom₁}} {F : Fun X C} {F_HasCoLimit : HasCoLimit F} (c : CoCone F) (m : C^.hom (colimit F) c^.obj) (ω : ∀ (x : X^.obj), c^.hom x = m ∘∘ colimit.in F x) : m = colimit.univ F c := limit.univ.uniq c m ω /-! #brief The unique iso between two co-limits of the same functor. -/ definition colimit.iso {X : Cat.{ℓobjx ℓhomx}} {C : Cat.{ℓobj₁ ℓhom₁}} {F : Fun X C} (F_HasCoLimit₁ F_HasCoLimit₂ : HasCoLimit F) : C^.hom (@colimit X C F F_HasCoLimit₁) (@colimit X C F F_HasCoLimit₂) := limit.iso F_HasCoLimit₂ F_HasCoLimit₁ /-! #brief Co-limits are unique up-to unique isomorphism. -/ theorem colimit.uniq {X : Cat.{ℓobjx ℓhomx}} {C : Cat.{ℓobj₁ ℓhom₁}} {F : Fun X C} (F_HasCoLimit₁ F_HasCoLimit₂ : HasCoLimit F) : Iso (limit.iso F_HasCoLimit₁ F_HasCoLimit₂) (limit.iso F_HasCoLimit₂ F_HasCoLimit₁) := limit.uniq F_HasCoLimit₁ F_HasCoLimit₂ /-! #brief limit.univ absorbs compositions. -/ theorem colimit.circ_univ {X : Cat.{ℓobjx ℓhomx}} {C : Cat.{ℓobj₁ ℓhom₁}} (F : Fun X C) {F_HasCoLimit : HasCoLimit F} (ccone : CoCone F) {c' : C^.obj} (f : C^.hom ccone^.obj c') : f ∘∘ @colimit.univ X C F F_HasCoLimit ccone = @colimit.univ X C F F_HasCoLimit (ccone^.circ f) := begin refine colimit.univ.uniq (ccone^.circ f) _ _, intro x, apply eq.symm, apply eq.trans (eq.symm C^.circ_assoc), apply Cat.circ.congr_right, apply eq.symm, apply colimit.univ.mediates end /- ----------------------------------------------------------------------- Preservation of co-limits by functors. ----------------------------------------------------------------------- -/ /-! #brief A functor which preserves a co-limit. -/ @[class] definition PresCoLimit {X : Cat.{ℓobjx ℓhomx}} {B : Cat.{ℓobj₁ ℓhom₁}} {C : Cat.{ℓobj₂ ℓhom₂}} (L : Fun X B) (F : Fun B C) := PresLimit (OpFun L) (OpFun F) instance PresCoLimit.PresLimit {X : Cat.{ℓobjx ℓhomx}} {B : Cat.{ℓobj₁ ℓhom₁}} {C : Cat.{ℓobj₂ ℓhom₂}} (L : Fun X B) (F : Fun B C) [F_PresCoLimit : PresCoLimit L F] : PresLimit (OpFun L) (OpFun F) := F_PresCoLimit /-! #brief Functors which preserve co-limits yield instances of HasCoLimit. -/ instance PresCoLimit.HasCoLimit {X : Cat.{ℓobjx ℓhomx}} {B : Cat.{ℓobj₁ ℓhom₁}} {C : Cat.{ℓobj₂ ℓhom₂}} (L : Fun X B) [L_HasCoLimit : HasCoLimit L] (F : Fun B C) [F_PresCoLimit : PresCoLimit L F] : HasCoLimit (Fun.comp F L) := PresLimit.HasLimit (OpFun L) (OpFun F) /-! #brief A functor which preserves colimits out of a given category. -/ class PresCoLimitsFrom {B : Cat.{ℓobj₁ ℓhom₁}} {C : Cat.{ℓobj₂ ℓhom₂}} (F : Fun B C) (X : Cat.{ℓobjx ℓhomx}) := (pres_colimit : ∀ (L : Fun X B) , PresCoLimit L F) instance PresCoLimitsFrom.PresCoLimit {B : Cat.{ℓobj₁ ℓhom₁}} {C : Cat.{ℓobj₂ ℓhom₂}} (F : Fun B C) {X : Cat.{ℓobjx ℓhomx}} [F_PresCoLimitsFrom : PresCoLimitsFrom F X] (L : Fun X B) : PresCoLimit L F := PresCoLimitsFrom.pres_colimit F L /-! #brief Helper for showing that a functor preserves a co-limit. -/ definition PresCoLimit.show {X : Cat.{ℓobjx ℓhomx}} {B : Cat.{ℓobj₁ ℓhom₁}} {C : Cat.{ℓobj₂ ℓhom₂}} {L : Fun X B} {F : Fun B C} (mediate : ∀ [L_HasCoLimit : HasCoLimit L] (c : C^.obj) (hom : ∀ (x : X^.obj), C^.hom (F^.obj (L^.obj x)) c) (ωcomm : ∀ {x₁ x₂ : X^.obj} (f : X^.hom x₁ x₂) , hom x₁ = C^.circ (hom x₂) (F^.hom (L^.hom f))) , C^.hom (F^.obj (colimit L)) c) (ωmediate : ∀ [L_HasCoLimit : HasCoLimit L] (c : C^.obj) (hom : ∀ (x : X^.obj), C^.hom (F^.obj (L^.obj x)) c) (ωcomm : ∀ {x₁ x₂ : X^.obj} (f : X^.hom x₁ x₂) , hom x₁ = C^.circ (hom x₂) (F^.hom (L^.hom f))) (x : X^.obj) , hom x = mediate c hom @ωcomm ∘∘ F^.hom (colimit.in L x)) (ωuniq : ∀ [L_HasCoLimit : HasCoLimit L] (c : C^.obj) (hom : ∀ (x : X^.obj), C^.hom (F^.obj (L^.obj x)) c) (ωcomm : ∀ {x₁ x₂ : X^.obj} (f : X^.hom x₁ x₂) , hom x₁ = C^.circ (hom x₂) (F^.hom (L^.hom f))) (f : C^.hom (F^.obj (colimit L)) c) (ωf : ∀ (x : X^.obj), hom x = C^.circ f (F^.hom (colimit.in L x))) , f = mediate c hom @ωcomm) : PresCoLimit L F := PresLimit.show (λ L_HasCoLimit c hom ωcomm, @mediate L_HasCoLimit c hom (λ x₂ x₁ f, ωcomm f)) (λ L_HasCoLimit c hom ωcomm, @ωmediate L_HasCoLimit c hom (λ x₂ x₁ f, ωcomm f)) (λ L_HasCoLimit c hom ωcomm, @ωuniq L_HasCoLimit c hom (λ x₂ x₁ f, ωcomm f)) /-! #brief Preservation of co-limits by compositions of functors. -/ definition PresCoLimit.comp {X : Cat.{ℓobjx ℓhomx}} {B : Cat.{ℓobj₁ ℓhom₁}} {C : Cat.{ℓobj₂ ℓhom₂}} {D : Cat.{ℓobj₃ ℓhom₃}} (L : Fun X B) (F : Fun B C) [F_PresCoLimit : PresCoLimit L F] (G : Fun C D) [G_PresCoLimit : PresCoLimit (Fun.comp F L) G] : PresCoLimit L (Fun.comp G F) := @PresLimit.comp (OpCat X) (OpCat B) (OpCat C) (OpCat D) (OpFun L) (OpFun F) F_PresCoLimit (OpFun G) G_PresCoLimit /-! #brief A co-limit of a functor. -/ theorem prescolimit {X : Cat.{ℓobjx ℓhomx}} {B : Cat.{ℓobj₁ ℓhom₁}} {C : Cat.{ℓobj₂ ℓhom₂}} (L : Fun X B) [L_HasCoLimit : HasCoLimit L] (F : Fun B C) [F_PresCoLimit : PresCoLimit L F] : colimit (Fun.comp F L) = F^.obj (colimit L) := preslimit (OpFun L) (OpFun F) /-! #brief A map into the co-limit. -/ theorem prescolimit.in {X : Cat.{ℓobjx ℓhomx}} {B : Cat.{ℓobj₁ ℓhom₁}} {C : Cat.{ℓobj₂ ℓhom₂}} (L : Fun X B) [L_HasCoLimit : HasCoLimit L] (F : Fun B C) [F_PresCoLimit : PresCoLimit L F] (x : X^.obj) : colimit.in (Fun.comp F L) x = F^.hom (colimit.in L x) := preslimit.out (OpFun L) (OpFun F) x /-! #brief Every co-cone is mediated through the co-limit. -/ definition prescolimit.mediate {X : Cat.{ℓobjx ℓhomx}} {B : Cat.{ℓobj₁ ℓhom₁}} {C : Cat.{ℓobj₂ ℓhom₂}} (L : Fun X B) [L_HasCoLimit : HasCoLimit L] (F : Fun B C) [F_PresCoLimit : PresCoLimit L F] (c : CoCone L) : colimit.univ _ ((LeftCoConeFun F L)^.obj c) = by exact F^.hom (colimit.univ _ c) := preslimit.univ (OpFun L) (OpFun F) c /- ----------------------------------------------------------------------- Initial objects as co-limits. ----------------------------------------------------------------------- -/ /-! #brief If the initial functor has a co-limit, then the category has a final. -/ instance InitFun.HasCoLimit_HasInit {C : Cat.{ℓobj ℓhom}} [InitFun_HasCoLimit : HasCoLimit (InitFun.{ℓobjx ℓhomx} C)] : HasInit C := let mkcone : C^.obj → CoCone (InitFun.{ℓobjx ℓhomx} C) := λ c, { obj := c , hom := λ e, by cases e , comm := λ e₁ e₂ f, by cases f } in HasInit.show (colimit (InitFun.{ℓobjx ℓhomx} C)) (λ c, colimit.univ _ (mkcone c)) (λ c h, limit.univ.uniq (mkcone c) h (λ e, by cases e)) /-! #brief If the category has an initial, then the initial functor has a co-limit. -/ definition InitFun.HasInit_HasCoLimit {C : Cat.{ℓobj ℓhom}} [HasInit C] : HasCoLimit (InitFun.{ℓobjx ℓhomx} C) := HasCoLimit.show (init C) (λ e, by cases e) (λ x₁ x₂ f, by cases f) (λ c hom ωcomm, init_hom c) (λ c hom ωcomm e, by cases e) (λ c hom ωcomm f e, init_hom.uniq C) /-! #brief Functors which preserve co-limits of the initial functor preserve initial objects. -/ instance PresCoLimit.InitFun_PresInit {C : Cat.{ℓobj₁ ℓhom₁}} {D : Cat.{ℓobj₂ ℓhom₂}} (F : Fun C D) [F_PresCoLimit : PresCoLimit (InitFun.{ℓobjx ℓhomx} C) F] : PresInit F := let mk_cocone : ∀ (d : D^.obj), CoCone (F □□ InitFun.{ℓobjx ℓhomx} C) := λ d, { obj := d , hom := λ e, by cases e , comm := λ e₁ e₂ f, by cases f } in let mk_colim : ∀ (C_HasInit : HasInit C) , HasCoLimit (F □□ InitFun.{ℓobjx ℓhomx} C) := λ C_HasInit, @PresCoLimit.HasCoLimit _ _ _ _ (@InitFun.HasInit_HasCoLimit C C_HasInit) _ F_PresCoLimit in { hom := λ C_HasInit d, @colimit.univ _ _ _ (mk_colim C_HasInit) (mk_cocone d) , pres := λ C_HasInit , { hom_uniq := λ d h , begin apply (@colimit.univ.uniq _ _ _ (mk_colim C_HasInit) (mk_cocone d) h _), { intro e, cases e } end } } /- ----------------------------------------------------------------------- The co-limit functor. ----------------------------------------------------------------------- -/ /-! #brief The co-cone used by the co-limit functor. -/ definition CoLimitFun.cocone {X : Cat.{ℓobjx ℓhomx}} {C : Cat.{ℓobj ℓhom}} [C_HasAllCoLimitsFrom_X : HasAllCoLimitsFrom C X] (L₁ L₂ : Fun X C) (η : NatTrans L₁ L₂) : CoCone L₁ := CoCone.mk (colimit L₂) (λ x, colimit.in L₂ x ∘∘ η^.com x) (λ x₁ x₂ f , begin rw -C^.circ_assoc, rw (η^.natural f), rw C^.circ_assoc, apply Cat.circ.congr_left, apply colimit.in.comm end) /-! #brief The co-limit functor. -/ definition CoLimitFun {X : Cat.{ℓobjx ℓhomx}} {C : Cat.{ℓobj ℓhom}} [C_HasAllCoLimitsFrom_X : HasAllCoLimitsFrom C X] : Fun (FunCat X C) C := { obj := λ L, colimit L , hom := λ L₁ L₂ η, colimit.univ L₁ (CoLimitFun.cocone L₁ L₂ η) , hom_id := λ L, begin apply eq.symm, apply colimit.univ.uniq (CoLimitFun.cocone L L (NatTrans.id L)), intro x, exact eq.trans C^.circ_id_right (eq.symm C^.circ_id_left) end , hom_circ := λ L₁ L₂ L₃ η₂₃ η₁₂ , begin apply eq.symm, apply colimit.univ.uniq (CoLimitFun.cocone L₁ L₃ (NatTrans.comp η₂₃ η₁₂)), intro x, refine eq.trans _ (eq.symm (Cat.circ.congr_left (colimit.circ_univ L₁ (CoLimitFun.cocone L₁ L₂ η₁₂) (colimit.univ L₂ (CoLimitFun.cocone L₂ L₃ η₂₃))))), refine eq.trans _ (colimit.univ.mediates (Cone.circ (CoLimitFun.cocone L₁ L₂ η₁₂) (colimit.univ L₂ (CoLimitFun.cocone L₂ L₃ η₂₃))) x), apply eq.trans C^.circ_assoc, refine eq.symm (eq.trans C^.circ_assoc (eq.symm _)), apply Cat.circ.congr_left, exact colimit.univ.mediates (CoLimitFun.cocone L₂ L₃ η₂₃) x end } /- ----------------------------------------------------------------------- Co-limits in functor categories. ----------------------------------------------------------------------- -/ /-! #brief Inclusion for pointwise co-limits. -/ definition FunCat.HasCoLimit.in {C : Cat.{ℓobj₁ ℓhom₁}} {D : Cat.{ℓobj₂ ℓhom₂}} {X : Cat.{ℓobjx ℓhomx}} [D_HasAllCoLimitsFrom_X : HasAllCoLimitsFrom D X] (F : Fun X (FunCat C D)) (x : X^.obj) : NatTrans (F^.obj x) (CoLimitFun □□ Fun.swap F) := { com := λ c, colimit.in (Fun.swap.obj F c) x , natural := λ c₁ c₂ f , colimit.univ.mediates (CoLimitFun.cocone (Fun.swap.obj F c₁) (Fun.swap.obj F c₂) (Fun.swap.hom F c₁ c₂ f)) x } /-! #brief Co-cone used for pointwise universal maps. -/ definition FunCat.HasCoLimit.univ.cocone {C : Cat.{ℓobj₁ ℓhom₁}} {D : Cat.{ℓobj₂ ℓhom₂}} {X : Cat.{ℓobjx ℓhomx}} [D_HasAllCoLimitsFrom_X : HasAllCoLimitsFrom D X] (F : Fun X (FunCat C D)) (L : Fun C D) (η : ∀ (x : X^.obj), NatTrans (F^.obj x) L) (ωη : ∀ {x₁ x₂ : X^.obj} (f : X^.hom x₁ x₂) , η x₁ = NatTrans.comp (η x₂) (F^.hom f)) (c : C^.obj) : CoCone (Fun.swap.obj F c) := CoCone.mk (L^.obj c) (λ x, (η x)^.com c) (λ c₁ c₂ f , begin rw ωη f, trivial end) /-! #brief Universal map for pointwise limits. -/ definition FunCat.HasCoLimit.univ {C : Cat.{ℓobj₁ ℓhom₁}} {D : Cat.{ℓobj₂ ℓhom₂}} {X : Cat.{ℓobjx ℓhomx}} [D_HasAllCoLimitsFrom_X : HasAllCoLimitsFrom D X] (F : Fun X (FunCat C D)) (L : Fun C D) (η : ∀ (x : X^.obj), NatTrans (F^.obj x) L) (ωη : ∀ {x₁ x₂ : X^.obj} (f : X^.hom x₁ x₂) , η x₁ = NatTrans.comp (η x₂) (F^.hom f)) : NatTrans (CoLimitFun □□ Fun.swap F) L := { com := λ c, colimit.univ (Fun.swap.obj F c) (FunCat.HasCoLimit.univ.cocone F L η @ωη c) , natural := λ c₁ c₂ f , begin dsimp [CoLimitFun], apply eq.trans (colimit.circ_univ ((Fun.swap F)^.obj c₁) (CoLimitFun.cocone ((Fun.swap F)^.obj c₁) ((Fun.swap F)^.obj c₂) ((Fun.swap F)^.hom f)) (colimit.univ (Fun.swap.obj F c₂) (FunCat.HasCoLimit.univ.cocone F L η @ωη c₂))), apply eq.symm, apply eq.trans (colimit.circ_univ (Fun.swap.obj F c₁) (FunCat.HasCoLimit.univ.cocone F L η @ωη c₁) (L^.hom f)), apply eq.symm, apply colimit.univ.uniq (CoCone.circ (FunCat.HasCoLimit.univ.cocone F L η @ωη c₁) (L^.hom f)), intro x, apply eq.trans (eq.symm ((η x)^.natural f)), refine eq.trans _ (colimit.univ.mediates (CoCone.circ (CoLimitFun.cocone ((Fun.swap F)^.obj c₁) ((Fun.swap F)^.obj c₂) ((Fun.swap F)^.hom f)) (colimit.univ (Fun.swap.obj F c₂) (FunCat.HasCoLimit.univ.cocone F L η @ωη c₂))) x), refine eq.symm (eq.trans D^.circ_assoc (eq.symm _)), apply Cat.circ.congr_left, apply colimit.univ.mediates (FunCat.HasCoLimit.univ.cocone F L η @ωη c₂) x end } /-! #brief Co-limits in FunCat can be computed pointwise. -/ instance FunCat.HasCoLimit {C : Cat.{ℓobj₁ ℓhom₁}} {D : Cat.{ℓobj₂ ℓhom₂}} {X : Cat.{ℓobjx ℓhomx}} [D_HasAllCoLimitsFrom_X : HasAllCoLimitsFrom D X] (F : Fun X (FunCat C D)) : HasCoLimit F := HasCoLimit.show (CoLimitFun □□ F^.swap) (FunCat.HasCoLimit.in F) (λ x₁ x₂ f , begin apply NatTrans.eq, apply funext, intro c, apply colimit.in.comm (Fun.swap.obj F c) end) (FunCat.HasCoLimit.univ F) (λ L hom ωhom x , begin apply NatTrans.eq, apply funext, intro c, apply colimit.univ.mediates (FunCat.HasCoLimit.univ.cocone F L hom @ωhom c) end) (λ L hom ωhom h ωh , begin apply NatTrans.eq, apply funext, intro c, apply colimit.univ.uniq (FunCat.HasCoLimit.univ.cocone F L hom @ωhom c), intro x, apply NatTrans.congr_com (ωh x) end) /-! #brief Co-limits in functor categories can be computed pointwise. -/ instance FunCat.HasAllCoLimits {C : Cat.{ℓobj₁ ℓhom₁}} {D : Cat.{ℓobj₂ ℓhom₂}} [D_HasAllCoLimits : HasAllCoLimits.{ℓobjx ℓhomx} D] : HasAllCoLimits.{ℓobjx ℓhomx} (FunCat C D) := { has_colimit := λ X L, @FunCat.HasCoLimit C D X (HasAllCoLimits.HasAllCoLimitsFrom D X) L } /- ----------------------------------------------------------------------- Co-limits and natural isomorphisms. ----------------------------------------------------------------------- -/ /-! #brief Natural isomorphism cast co-limits. -/ definition NatIso.HasCoLimit₂ {X : Cat.{ℓobjx ℓhomx}} {C : Cat.{ℓobj₁ ℓhom₁}} {L₁ L₂ : Fun X C} {η₁₂ : NatTrans L₁ L₂} {η₂₁ : NatTrans L₂ L₁} (η_iso : NatIso η₁₂ η₂₁) [L₁_HasCoLimit : HasCoLimit L₁] : HasCoLimit L₂ := NatIso.HasLimit₁ (OpNatIso η_iso) /-! #brief Natural isomorphism cast co-limits. -/ definition NatIso.HasCoLimit₁ {X : Cat.{ℓobjx ℓhomx}} {C : Cat.{ℓobj₁ ℓhom₁}} {L₁ L₂ : Fun X C} {η₁₂ : NatTrans L₁ L₂} {η₂₁ : NatTrans L₂ L₁} (η_iso : NatIso η₁₂ η₂₁) [L₂_HasCoLimit : HasCoLimit L₂] : HasCoLimit L₁ := NatIso.HasCoLimit₂ η_iso^.flip /- ----------------------------------------------------------------------- Limits, colimits, and adjoints. ----------------------------------------------------------------------- -/ /-! #brief Right adjoints preserve all limits. -/ definition Adj.right.PresLimit {C : Cat.{ℓobj₁ ℓhom₁}} {D : Cat.{ℓobj₂ ℓhom₂}} {L : Fun C D} {R : Fun D C} (adj : Adj L R) {X : Cat.{ℓobjx ℓhomx}} (F : Fun X D) : PresLimit F R := PresLimit.show (λ F_HasLimit c hom ω , adj^.right_adj (@limit.univ _ _ F F_HasLimit { obj := L^.obj c , hom := λ x, adj^.left_adj (hom x) , comm := λ x₁ x₂ f, begin rw ω f, exact sorry end })) (λ F_HasLimit c hom ωcomm x, sorry) (λ F_HasLimit c hom ωcomm h ω, sorry) /-! #brief Left adjoints preserve all co-limits. -/ definition Adj.left.PresCoLimit {C : Cat.{ℓobj₁ ℓhom₁}} {D : Cat.{ℓobj₂ ℓhom₂}} {L : Fun C D} {R : Fun D C} (adj : Adj L R) {X : Cat.{ℓobjx ℓhomx}} (F : Fun X C) : PresCoLimit F L := PresCoLimit.show (λ F_HasLimit c hom ω , adj^.left_adj (@colimit.univ _ _ F F_HasLimit { obj := R^.obj c , hom := λ x, adj^.right_adj (hom x) , comm := λ x₁ x₂ f, begin rw ω f, exact sorry end })) (λ F_HasLimit c hom ωcomm x, sorry) (λ F_HasLimit c hom ωcomm h ω, sorry) end qp
4e0549288c4e552ec89a108c55284975734f5094
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/computedFieldsCode.lean
fd12fca63247bf0520dac8e05ba125f722015826
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
880
lean
set_option trace.compiler.ir.result true -- All generated case and ctor instructions should use the _impl version inductive Exp | var (i : UInt32) | app (a b : Exp) | a1 | a2 | a3 | a4 | a5 with @[computedField] hash : Exp → UInt64 | .var i => Hashable.hash i + 1000 | .app a b => mixHash (hash a) (hash b) | _ => 42 def f := Exp.hash (.app (.var 10) .a4) -- should use 'default →' case def g : Exp → Bool | .a3 => true | _ => false -- using the same matcher as in the computed field should work def hash' : Exp → Nat | .var i => i.toNat | .app a b => hash' a + hash' b | _ => 42 -- should not invoke Exp.var._override def getAppFn : Exp → Exp | .app f _ => getAppFn f | e => e -- should not call Exp.app._override def Exp.f (e : Exp) : Exp := match app e e with | var _ => e | app a _ => getAppFn a | e => e
5aeec3c44f2dee5588167f4ccfa979ce78b48140
d9ed0fce1c218297bcba93e046cb4e79c83c3af8
/library/init/meta/tactic.lean
94adcc62e9f3f31329722899ccc7bbe56c6f893b
[ "Apache-2.0" ]
permissive
leodemoura/lean_clone
005c63aa892a6492f2d4741ee3c2cb07a6be9d7f
cc077554b584d39bab55c360bc12a6fe7957afe6
refs/heads/master
1,610,506,475,484
1,482,348,354,000
1,482,348,543,000
77,091,586
0
0
null
null
null
null
UTF-8
Lean
false
false
29,089
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.function init.data.option.basic init.util import init.category.combinators init.category.monad init.category.alternative import init.data.nat.div init.meta.exceptional init.meta.format init.meta.environment import init.meta.pexpr init.data.to_string init.data.string.basic meta constant tactic_state : Type universe variables u v namespace tactic_state meta constant env : tactic_state → environment meta constant to_format : tactic_state → format /- Format expression with respect to the main goal in the tactic state. If the tactic state does not contain any goals, then format expression using an empty local context. -/ meta constant format_expr : tactic_state → expr → format meta constant get_options : tactic_state → options meta constant set_options : tactic_state → options → tactic_state end tactic_state meta instance : has_to_format tactic_state := ⟨tactic_state.to_format⟩ meta inductive tactic_result (α : Type u) | success : α → tactic_state → tactic_result | exception : (unit → format) → option expr → tactic_state → tactic_result open tactic_result section variables {α : Type u} variables [has_to_string α] meta def tactic_result_to_string : tactic_result α → string | (success a s) := to_string a | (exception .α t ref s) := "Exception: " ++ to_string (t ()) meta instance : has_to_string (tactic_result α) := ⟨tactic_result_to_string⟩ end attribute [reducible] meta def tactic (α : Type u) := tactic_state → tactic_result α section variables {α : Type u} {β : Type v} @[inline] meta def tactic_fmap (f : α → β) (t : tactic α) : tactic β := λ s, tactic_result.cases_on (t s) (λ a s', success (f a) s') (λ e s', exception β e s') @[inline] meta def tactic_bind (t₁ : tactic α) (t₂ : α → tactic β) : tactic β := λ s, tactic_result.cases_on (t₁ s) (λ a s', t₂ a s') (λ e s', exception β e s') @[inline] meta def tactic_return (a : α) : tactic α := λ s, success a s meta def tactic_orelse {α : Type u} (t₁ t₂ : tactic α) : tactic α := λ s, tactic_result.cases_on (t₁ s) success (λ e₁ ref₁ s', tactic_result.cases_on (t₂ s) success (exception α)) @[inline] meta def tactic_seq (t₁ : tactic α) (t₂ : tactic β) : tactic β := tactic_bind t₁ (λ a, t₂) infixl ` >>=[tactic] `:2 := tactic_bind infixl ` >>[tactic] `:2 := tactic_seq end meta instance : monad tactic := {map := @tactic_fmap, ret := @tactic_return, bind := @tactic_bind} meta def tactic.fail {α : Type u} {β : Type v} [has_to_format β] (msg : β) : tactic α := λ s, exception α (λ u, to_fmt msg) none s meta def tactic.failed {α : Type u} : tactic α := tactic.fail "failed" meta instance : alternative tactic := ⟨@tactic_fmap, (λ α a s, success a s), (@fapp _ _), @tactic.failed, @tactic_orelse⟩ meta def {u₁ u₂} tactic.up {α : Type u₂} (t : tactic α) : tactic (ulift.{u₁} α) := λ s, match t s with | success a s' := success (ulift.up a) s' | exception .α t ref s := exception (ulift α) t ref s end meta def {u₁ u₂} tactic.down {α : Type u₂} (t : tactic (ulift.{u₁} α)) : tactic α := λ s, match t s with | success (ulift.up a) s' := success a s' | exception .(ulift α) t ref s := exception α t ref s end namespace tactic variables {α : Type u} meta def try (t : tactic α) : tactic unit := λ s, tactic_result.cases_on (t s) (λ a, success ()) (λ e ref s', success () s) meta def skip : tactic unit := success () open list meta def foreach : list α → (α → tactic unit) → tactic unit | [] fn := skip | (e::es) fn := do fn e, foreach es fn open nat /- (repeat_at_most n t): repeat the given tactic at most n times or until t fails -/ meta def repeat_at_most : nat → tactic unit → tactic unit | 0 t := skip | (succ n) t := (do t, repeat_at_most n t) <|> skip /- (repeat_exactly n t) : execute t n times -/ meta def repeat_exactly : nat → tactic unit → tactic unit | 0 t := skip | (succ n) t := do t, repeat_exactly n t meta def repeat : tactic unit → tactic unit := repeat_at_most 100000 meta def returnex {α : Type 1} (e : exceptional α) : tactic α := λ s, match e with | (exceptional.success a) := tactic_result.success a s | (exceptional.exception .α f) := tactic_result.exception α (λ u, f options.mk) none s -- TODO(Leo): extract options from environment end meta def returnopt (e : option α) : tactic α := λ s, match e with | (some a) := tactic_result.success a s | none := tactic_result.exception α (λ u, to_fmt "failed") none s end /- Decorate t's exceptions with msg -/ meta def decorate_ex (msg : format) (t : tactic α) : tactic α := λ s, tactic_result.cases_on (t s) success (λ e, exception α (λ u, msg ++ format.nest 2 (format.line ++ e u))) attribute [inline] meta def write (s' : tactic_state) : tactic unit := λ s, success () s' attribute [inline] meta def read : tactic tactic_state := λ s, success s s end tactic meta def tactic_format_expr (e : expr) : tactic format := do s ← tactic.read, return (tactic_state.format_expr s e) meta class has_to_tactic_format (α : Type u) := (to_tactic_format : α → tactic format) meta instance : has_to_tactic_format expr := ⟨tactic_format_expr⟩ meta def tactic.pp {α : Type u} [has_to_tactic_format α] : α → tactic format := has_to_tactic_format.to_tactic_format open tactic format meta def list_to_tactic_format_aux {α : Type u} [has_to_tactic_format α] : bool → list α → tactic format | b [] := return $ to_fmt "" | b (x::xs) := do f₁ ← pp x, f₂ ← list_to_tactic_format_aux ff xs, return $ (if ¬ b then to_fmt "," ++ line else nil) ++ f₁ ++ f₂ meta def list_to_tactic_format {α : Type u} [has_to_tactic_format α] : list α → tactic format | [] := return $ to_fmt "[]" | (x::xs) := do f ← list_to_tactic_format_aux tt (x::xs), return $ to_fmt "[" ++ group (nest 1 f) ++ to_fmt "]" meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (list α) := ⟨list_to_tactic_format⟩ meta instance has_to_format_to_has_to_tactic_format (α : Type) [has_to_format α] : has_to_tactic_format α := ⟨(λ x, return x) ∘ to_fmt⟩ namespace tactic open tactic_state meta def get_env : tactic environment := do s ← read, return $ env s meta def get_decl (n : name) : tactic declaration := do s ← read, returnex $ environment.get (env s) n meta def trace {α : Type u} [has_to_tactic_format α] (a : α) : tactic unit := do fmt ← pp a, return $ _root_.trace_fmt fmt (λ u, ()) meta def trace_state : tactic unit := do s ← read, trace $ to_fmt s meta def get_options : tactic options := do s ← read, return s^.get_options inductive transparency | all | semireducible | reducible | none export transparency (reducible semireducible) /- (eval_expr α α_as_expr e) evaluates 'e' IF 'e' has type 'α'. 'α' must be a closed term. 'α_as_expr' is synthesized by the code generator. 'e' must be a closed expression at runtime. -/ meta constant eval_expr (α : Type u) {α_expr : pexpr} : expr → tactic α /- Return the partial term/proof constructed so far. Note that the resultant expression may contain variables that are not declarate in the current main goal. -/ meta constant result : tactic expr /- Display the partial term/proof constructed so far. This tactic is *not* equivalent to do { r ← result, s ← read, return (format_expr s r) } because this one will format the result with respect to the current goal, and trace_result will do it with respect to the initial goal. -/ meta constant format_result : tactic format /- Return target type of the main goal. Fail if tactic_state does not have any goal left. -/ meta constant target : tactic expr meta constant intro_core : name → tactic expr meta constant intron : nat → tactic unit meta constant rename : name → name → tactic unit /- Clear the given local constant. The tactic fails if the given expression is not a local constant. -/ meta constant clear : expr → tactic unit meta constant revert_lst : list expr → tactic nat meta constant whnf_core : transparency → expr → tactic expr /- eta expand the given expression -/ meta constant eta_expand : expr → tactic expr /- beta reduction -/ meta constant beta : expr → tactic expr /- zeta reduction -/ meta constant zeta : expr → tactic expr meta constant unify_core : transparency → expr → expr → tactic unit /- is_def_eq_core is similar to unify_core, but it treats metavariables as constants. -/ meta constant is_def_eq_core : transparency → expr → expr → tactic unit /- Infer the type of the given expression. Remark: transparency does not affect type inference -/ meta constant infer_type : expr → tactic expr meta constant get_local : name → tactic expr /- Resolve a name using the current local context, environment, aliases, etc. -/ meta constant resolve_name : name → tactic expr /- Return the hypothesis in the main goal. Fail if tactic_state does not have any goal left. -/ meta constant local_context : tactic (list expr) meta constant get_unused_name : name → option nat → tactic name /- Helper tactic for creating simple applications where some arguments are inferred using type inference. Example, given rel.{l_1 l_2} : Pi (α : Type.{l_1}) (β : α -> Type.{l_2}), (Pi x : α, β x) -> (Pi x : α, β x) -> , Prop nat : Type 1 real : Type 1 vec.{l} : Pi (α : Type l) (n : nat), Type.{l1} f g : Pi (n : nat), vec real n then mk_app_core semireducible "rel" [f, g] returns the application rel.{1 2} nat (fun n : nat, vec real n) f g -/ meta constant mk_app_core : transparency → name → list expr → tactic expr /- Similar to mk_app, but allows to specify which arguments are explicit/implicit. Example, given a b : nat then mk_mapp_core semireducible "ite" [some (a > b), none, none, some a, some b] returns the application @ite.{1} (a > b) (nat.decidable_gt a b) nat a b -/ meta constant mk_mapp_core : transparency → name → list (option expr) → tactic expr /- Given a local constant t, if t has type (lhs = rhs) apply susbstitution. Otherwise, try to find a local constant that has type of the form (t = t') or (t' = t). The tactic fails if the given expression is not a local constant. -/ meta constant subst : expr → tactic unit meta constant exact_core : transparency → expr → tactic unit /- Elaborate the given quoted expression with respect to the current main goal. If the boolean argument is tt, then metavariables are tolerated and become new goals. -/ meta constant to_expr_core : bool → pexpr → tactic expr /- Return true if the given expression is a type class. -/ meta constant is_class : expr → tactic bool /- Try to create an instance of the given type class. -/ meta constant mk_instance : expr → tactic expr /- Change the target of the main goal. The input expression must be definitionally equal to the current target. -/ meta constant change : expr → tactic unit /- (assert H T), adds a new goal for T, and the hypothesis (H : T) in the current goal. -/ meta constant assert : name → expr → tactic unit /- (assertv H T P), adds the hypothesis (H : T) in the current goal if P has type T. -/ meta constant assertv : name → expr → expr → tactic unit /- (define H T), adds a new goal for T, and the hypothesis (H : T := ?M) in the current goal. -/ meta constant define : name → expr → tactic unit /- (definev H T P), adds the hypothesis (H : T := P) in the current goal if P has type T. -/ meta constant definev : name → expr → expr → tactic unit /- rotate goals to the left -/ meta constant rotate_left : nat → tactic unit meta constant get_goals : tactic (list expr) meta constant set_goals : list expr → tactic unit /- (apply_core t approx all insts e), apply the expression e to the main goal, the unification is performed using the given transparency mode. If approx is tt, then fallback to first-order unification, and approximate context during unification. If all is tt, then all unassigned meta-variables are added as new goals. If insts is tt, then use type class resolution to instantiate unassigned meta-variables. -/ meta constant apply_core : transparency → bool → bool → bool → expr → tactic unit /- Create a fresh meta universe variable. -/ meta constant mk_meta_univ : tactic level /- Create a fresh meta-variable with the given type. The scope of the new meta-variable is the local context of the main goal. -/ meta constant mk_meta_var : expr → tactic expr /- Return the value assigned to the given universe meta-variable. Fail if argument is not an universe meta-variable or if it is not assigned. -/ meta constant get_univ_assignment : level → tactic level /- Return the value assigned to the given meta-variable. Fail if argument is not a meta-variable or if it is not assigned. -/ meta constant get_assignment : expr → tactic expr meta constant mk_fresh_name : tactic name /- Return a hash code for expr that ignores inst_implicit arguments, and proofs. -/ meta constant abstract_hash : expr → tactic nat /- Return the "weight" of the given expr while ignoring inst_implicit arguments, and proofs. -/ meta constant abstract_weight : expr → tactic nat meta constant abstract_eq : expr → expr → tactic bool /- (induction_core m H rec ns) induction on H using recursor rec, names for the new hypotheses are retrieved from ns. If ns does not have sufficient names, then use the internal binder names in the recursor. -/ meta constant induction_core : transparency → expr → name → list name → tactic unit /- (cases_core m H ns) apply cases_on recursor, names for the new hypotheses are retrieved from ns. H must be a local constant -/ meta constant cases_core : transparency → expr → list name → tactic unit /- (generalize_core m e n) -/ meta constant generalize_core : transparency → expr → name → tactic unit /- instantiate assigned metavariables in the given expression -/ meta constant instantiate_mvars : expr → tactic expr /- Add the given declaration to the environment -/ meta constant add_decl : declaration → tactic unit /- (doc_string env d k) return the doc string for d (if available) -/ meta constant doc_string : name → tactic string meta constant add_doc_string : name → string → tactic unit meta constant module_doc_strings : tactic (list (option name × string)) /- (set_basic_attribute_core attr_name c_name persistent prio) set attribute attr_name for constant c_name with the given priority. If the priority is none, then use default -/ meta constant set_basic_attribute_core : name → name → bool → option nat → tactic unit /- (unset_attribute attr_name c_name) -/ meta constant unset_attribute : name → name → tactic unit /- (has_attribute attr_name c_name) succeeds if the declaration `decl_name` has the attribute `attr_name`. The result is the priority. -/ meta constant has_attribute : name → name → tactic nat meta def set_basic_attribute : name → name → bool → tactic unit := λ a n p, set_basic_attribute_core a n p none /- (copy_attribute attr_name c_name d_name) copy attribute `attr_name` from `src` to `tgt` if it is defined for `src` -/ meta def copy_attribute (attr_name : name) (src : name) (p : bool) (tgt : name) : tactic unit := try $ do prio ← has_attribute attr_name src, set_basic_attribute_core attr_name tgt p (some prio) /- (save_type_info e ref) save (typeof e) at position associated with ref -/ meta constant save_type_info : expr → expr → tactic unit /- Return list of currently opened namespace -/ meta constant open_namespaces : tactic (list name) open list nat /- Remark: set_goals will erase any solved goal -/ meta def cleanup : tactic unit := get_goals >>= set_goals /- Auxiliary definition used to implement begin ... end blocks -/ meta def step {α : Type u} (t : tactic α) : tactic unit := t >>[tactic] cleanup /- Add (H : T := pr) to the current goal -/ meta def pose (n : name) (pr : expr) : tactic unit := do t ← infer_type pr, definev n t pr /- Add (H : T) to the current goal, given a proof (pr : T) -/ meta def note (n : name) (pr : expr) : tactic unit := do t ← infer_type pr, assertv n t pr meta def is_prop (e : expr) : tactic bool := do t ← infer_type e, return (to_bool (t = expr.prop)) meta def is_proof (e : expr) : tactic bool := infer_type e >>= is_prop meta def whnf : expr → tactic expr := whnf_core semireducible meta def whnf_no_delta : expr → tactic expr := whnf_core transparency.none meta def whnf_target : tactic unit := target >>= whnf >>= change meta def intro (n : name) : tactic expr := do t ← target, if expr.is_pi t ∨ expr.is_let t then intro_core n else whnf_target >> intro_core n meta def intro1 : tactic expr := intro `_ /- Remark: the unit argument is a trick to allow us to write a recursive definition. Lean3 only allows recursive functions when "equations" are used. -/ meta def intros_core : unit → tactic (list expr) | u := do t ← target, match t with | (expr.pi n bi d b) := do H ← intro1, Hs ← intros_core u, return (H :: Hs) | (expr.elet n t v b) := do H ← intro1, Hs ← intros_core u, return (H :: Hs) | e := return [] end meta def intros : tactic (list expr) := intros_core () meta def intro_lst : list name → tactic (list expr) | [] := return [] | (n::ns) := do H ← intro n, Hs ← intro_lst ns, return (H :: Hs) meta def mk_app : name → list expr → tactic expr := mk_app_core semireducible meta def mk_mapp : name → list (option expr) → tactic expr := mk_mapp_core semireducible meta def to_expr : pexpr → tactic expr := to_expr_core tt meta def to_expr_strict : pexpr → tactic expr := to_expr_core ff meta def revert (l : expr) : tactic nat := revert_lst [l] meta def clear_lst : list name → tactic unit | [] := skip | (n::ns) := do H ← get_local n, clear H, clear_lst ns meta def unify : expr → expr → tactic unit := unify_core semireducible meta def is_def_eq : expr → expr → tactic unit := is_def_eq_core semireducible meta def match_not (e : expr) : tactic expr := match (expr.is_not e) with | (some a) := return a | none := fail "expression is not a negation" end meta def match_eq (e : expr) : tactic (expr × expr) := match (expr.is_eq e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not an equality" end meta def match_ne (e : expr) : tactic (expr × expr) := match (expr.is_ne e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not a disequality" end meta def match_heq (e : expr) : tactic (expr × expr × expr × expr) := do match (expr.is_heq e) with | (some (α, lhs, β, rhs)) := return (α, lhs, β, rhs) | none := fail "expression is not a heterogeneous equality" end meta def match_refl_app (e : expr) : tactic (name × expr × expr) := do env ← get_env, match (environment.is_refl_app env e) with | (some (R, lhs, rhs)) := return (R, lhs, rhs) | none := fail "expression is not an application of a reflexive relation" end meta def get_local_type (n : name) : tactic expr := get_local n >>= infer_type meta def trace_result : tactic unit := format_result >>= trace meta def exact : expr → tactic unit := exact_core semireducible meta def rexact : expr → tactic unit := exact_core reducible /- (find_same_type t es) tries to find in es an expression with type definitionally equal to t -/ meta def find_same_type : expr → list expr → tactic expr | e [] := failed | e (H :: Hs) := do t ← infer_type H, (unify e t >> return H) <|> find_same_type e Hs meta def assumption : tactic unit := do { ctx ← local_context, t ← target, H ← find_same_type t ctx, exact H } <|> fail "assumption tactic failed" notation `‹` p `›` := show p, by assumption /- Swap first two goals, do nothing if tactic state does not have at least two goals. -/ meta def swap : tactic unit := do gs ← get_goals, match gs with | (g₁ :: g₂ :: rs) := set_goals (g₂ :: g₁ :: rs) | e := skip end /- Return the number of goals that need to be solved -/ meta def num_goals : tactic nat := do gs ← get_goals, return (length gs) /- We have to provide the instance argument `[has_mod nat]` because mod for nat was not defined yet -/ meta def rotate_right (n : nat) [has_mod nat] : tactic unit := do ng ← num_goals, if ng = 0 then skip else rotate_left (ng - n % ng) meta def rotate : nat → tactic unit := rotate_left /- first [t_1, ..., t_n] applies the first tactic that doesn't fail. The tactic fails if all t_i's fail. -/ meta def first {α : Type u} : list (tactic α) → tactic α | [] := fail "first tactic failed, no more alternatives" | (t::ts) := t <|> first ts /- Applies the given tactic to the main goal and fails if it is not solved. -/ meta def solve1 (tac : tactic unit) : tactic unit := do gs ← get_goals, match gs with | [] := fail "focus tactic failed, there isn't any goal left to focus" | (g::rs) := do set_goals [g], tac, gs' ← get_goals, match gs' with | [] := set_goals rs | gs := fail "focus tactic failed, focused goal has not been solved" end end /- solve [t_1, ... t_n] applies the first tactic that solves the main goal. -/ meta def solve (ts : list (tactic unit)) : tactic unit := first $ map solve1 ts private meta def focus_aux : list (tactic unit) → list expr → list expr → tactic unit | [] gs rs := set_goals $ gs ++ rs | (t::ts) (g::gs) rs := do set_goals [g], t, rs' ← get_goals, focus_aux ts gs (rs ++ rs') | (t::ts) [] rs := fail "focus tactic failed, insufficient number of goals" /- focus [t_1, ..., t_n] applies t_i to the i-th goal. Fails if there are less tha n goals. -/ meta def focus (ts : list (tactic unit)) : tactic unit := do gs ← get_goals, focus_aux ts gs [] private meta def all_goals_core : tactic unit → list expr → list expr → tactic unit | tac [] ac := set_goals ac | tac (g :: gs) ac := do set_goals [g], tac, new_gs ← get_goals, all_goals_core tac gs (ac ++ new_gs) /- Apply the given tactic to all goals. -/ meta def all_goals (tac : tactic unit) : tactic unit := do gs ← get_goals, all_goals_core tac gs [] /- LCF-style AND_THEN tactic. It applies tac1, and if succeed applies tac2 to each subgoal produced by tac1 -/ meta def seq (tac1 : tactic unit) (tac2 : tactic unit) : tactic unit := do g::gs ← get_goals | failed, set_goals [g], tac1, all_goals tac2, gs' ← get_goals, set_goals (gs' ++ gs) meta instance : has_andthen (tactic unit) := ⟨seq⟩ /- Applies tac if c holds -/ meta def when (c : Prop) [decidable c] (tac : tactic unit) : tactic unit := if c then tac else skip meta constant is_trace_enabled_for : name → bool /- Execute tac only if option trace.n is set to true. -/ meta def when_tracing (n : name) (tac : tactic unit) : tactic unit := when (is_trace_enabled_for n = tt) tac /- Fail if there are no remaining goals. -/ meta def fail_if_no_goals : tactic unit := do n ← num_goals, when (n = 0) (fail "tactic failed, there are no goals to be solved") /- Fail if there are unsolved goals. -/ meta def now : tactic unit := do n ← num_goals, when (n ≠ 0) (fail "now tactic failed, there are unsolved goals") meta def apply : expr → tactic unit := apply_core semireducible tt ff tt meta def fapply : expr → tactic unit := apply_core semireducible tt tt tt /- Try to solve the main goal using type class resolution. -/ meta def apply_instance : tactic unit := do tgt ← target, b ← is_class tgt, if b then mk_instance tgt >>= exact else fail "apply_instance tactic fail, target is not a type class" /- Create a list of universe meta-variables of the given size. -/ meta def mk_num_meta_univs : nat → tactic (list level) | 0 := return [] | (succ n) := do l ← mk_meta_univ, ls ← mk_num_meta_univs n, return (l::ls) /- Return (expr.const c [l_1, ..., l_n]) where l_i's are fresh universe meta-variables. -/ meta def mk_const (c : name) : tactic expr := do env ← get_env, decl ← returnex (environment.get env c), num ← return (length (declaration.univ_params decl)), ls ← mk_num_meta_univs num, return (expr.const c ls) /- Create a fresh universe ?u, a metavariable (?T : Type.{?u}), and return metavariable (?M : ?T). This action can be used to create a meta-variable when we don't know its type at creation time -/ meta def mk_mvar : tactic expr := do u ← mk_meta_univ, t ← mk_meta_var (expr.sort u), mk_meta_var t meta def mk_local' (pp_name : name) (bi : binder_info) (type : expr) : tactic expr := do uniq_name ← mk_fresh_name, return $ expr.local_const uniq_name pp_name bi type meta def mk_local_def (pp_name : name) (type : expr) : tactic expr := mk_local' pp_name binder_info.default type private meta def get_pi_arity_aux : expr → tactic nat | (expr.pi n bi d b) := do m ← mk_fresh_name, l ← return (expr.local_const m n bi d), new_b ← whnf (expr.instantiate_var b l), r ← get_pi_arity_aux new_b, return (r + 1) | e := return 0 /- Compute the arity of the given (Pi-)type -/ meta def get_pi_arity (type : expr) : tactic nat := whnf type >>= get_pi_arity_aux /- Compute the arity of the given function -/ meta def get_arity (fn : expr) : tactic nat := infer_type fn >>= get_pi_arity meta def triv : tactic unit := mk_const `trivial >>= exact notation `dec_trivial` := of_as_true (by tactic.triv) meta def by_contradiction (H : name) : tactic expr := do tgt : expr ← target, (match_not tgt >> return ()) <|> (mk_mapp `decidable.by_contradiction [some tgt, none] >>= apply) <|> fail "tactic by_contradiction failed, target is not a negation nor a decidable proposition (remark: when 'local attribute classical.prop_decidable [instance]' is used all propositions are decidable)", intro H meta def cases (H : expr) : tactic unit := cases_core semireducible H [] meta def cases_using : expr → list name → tactic unit := cases_core semireducible meta def generalize : expr → name → tactic unit := generalize_core semireducible meta def generalizes : list expr → tactic unit | [] := skip | (e::es) := generalize e `x >> generalizes es meta def refine (e : pexpr) : tactic unit := do tgt : expr ← target, to_expr `((%%e : %%tgt)) >>= exact /- (solve_aux type tac) synthesize an element of 'type' using tactic 'tac' -/ meta def solve_aux {α : Type} (type : expr) (tac : tactic α) : tactic (α × expr) := do m ← mk_meta_var type, gs ← get_goals, set_goals [m], a ← tac, set_goals gs, return (a, m) end tactic open tactic meta def nat.to_expr : nat → tactic expr | n := if n = 0 then to_expr `(0) else if n = 1 then to_expr `(1) else do r : expr ← nat.to_expr (n / 2), if n % 2 = 0 then to_expr `(bit0 %%r) else to_expr `(bit1 %%r) meta def char.to_expr : char → tactic expr | ⟨n, pr⟩ := do e ← n^.to_expr, to_expr `(char.of_nat %%e) meta def string.to_expr : string → tactic expr | [] := to_expr `(string.empty) | (c::cs) := do e ← c^.to_expr, es ← string.to_expr cs, to_expr `(string.str %%e %%es) meta def unsigned.to_expr : unsigned → tactic expr | ⟨n, pr⟩ := do e ← n^.to_expr, to_expr `(unsigned.of_nat %%e) meta def name.to_expr : name → tactic expr | name.anonymous := to_expr `(name.anonymous) | (name.mk_string s n) := do es ← s^.to_expr, en ← name.to_expr n, to_expr `(name.mk_string %%es %%en) | (name.mk_numeral i n) := do is ← i^.to_expr, en ← name.to_expr n, to_expr `(name.mk_string %%is %%en) notation `command`:max := tactic unit open tactic /- Define id_locked using meta-programming because we don't have syntax for setting reducibility_hints. See module init.meta.declaration. Remark: id_locked is used in the builtin implementation of tactic.change -/ run_command do l ← return $ level.param `l, Ty ← return $ expr.sort l, type ← to_expr `(Π {α : %%Ty}, α → α), val ← to_expr `(λ {α : %%Ty} (a : α), a), add_decl (declaration.defn `id_locked [`l] type val reducibility_hints.opaque tt) lemma id_locked_eq {α : Type u} (a : α) : id_locked a = a := rfl
d7f0b7c7f540e00773bc5a0d759a8aad7d21ec41
437dc96105f48409c3981d46fb48e57c9ac3a3e4
/src/ring_theory/ideals.lean
d3c7a27decdf00fa1c9af1bf3911b2fd0939aa99
[ "Apache-2.0" ]
permissive
dan-c-k/mathlib
08efec79bd7481ee6da9cc44c24a653bff4fbe0d
96efc220f6225bc7a5ed8349900391a33a38cc56
refs/heads/master
1,658,082,847,093
1,589,013,201,000
1,589,013,201,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,742
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Chris Hughes, Mario Carneiro -/ import algebra.associated import linear_algebra.basic import order.zorn universes u v variables {α : Type u} {β : Type v} {a b : α} open set function open_locale classical namespace ideal variables [comm_ring α] (I : ideal α) @[ext] lemma ext {I J : ideal α} (h : ∀ x, x ∈ I ↔ x ∈ J) : I = J := submodule.ext h theorem eq_top_of_unit_mem (x y : α) (hx : x ∈ I) (h : y * x = 1) : I = ⊤ := eq_top_iff.2 $ λ z _, calc z = z * (y * x) : by simp [h] ... = (z * y) * x : eq.symm $ mul_assoc z y x ... ∈ I : I.mul_mem_left hx theorem eq_top_of_is_unit_mem {x} (hx : x ∈ I) (h : is_unit x) : I = ⊤ := let ⟨y, hy⟩ := is_unit_iff_exists_inv'.1 h in eq_top_of_unit_mem I x y hx hy theorem eq_top_iff_one : I = ⊤ ↔ (1:α) ∈ I := ⟨by rintro rfl; trivial, λ h, eq_top_of_unit_mem _ _ 1 h (by simp)⟩ theorem ne_top_iff_one : I ≠ ⊤ ↔ (1:α) ∉ I := not_congr I.eq_top_iff_one def span (s : set α) : ideal α := submodule.span α s lemma subset_span {s : set α} : s ⊆ span s := submodule.subset_span lemma span_le {s : set α} {I} : span s ≤ I ↔ s ⊆ I := submodule.span_le lemma span_mono {s t : set α} : s ⊆ t → span s ≤ span t := submodule.span_mono @[simp] lemma span_eq : span (I : set α) = I := submodule.span_eq _ @[simp] lemma span_singleton_one : span ({1} : set α) = ⊤ := (eq_top_iff_one _).2 $ subset_span $ mem_singleton _ lemma mem_span_insert {s : set α} {x y} : x ∈ span (insert y s) ↔ ∃ a (z ∈ span s), x = a * y + z := submodule.mem_span_insert lemma mem_span_insert' {s : set α} {x y} : x ∈ span (insert y s) ↔ ∃a, x + a * y ∈ span s := submodule.mem_span_insert' lemma mem_span_singleton' {x y : α} : x ∈ span ({y} : set α) ↔ ∃ a, a * y = x := submodule.mem_span_singleton lemma mem_span_singleton {x y : α} : x ∈ span ({y} : set α) ↔ y ∣ x := mem_span_singleton'.trans $ exists_congr $ λ _, by rw [eq_comm, mul_comm]; refl lemma span_singleton_le_span_singleton {x y : α} : span ({x} : set α) ≤ span ({y} : set α) ↔ y ∣ x := span_le.trans $ singleton_subset_iff.trans mem_span_singleton lemma span_eq_bot {s : set α} : span s = ⊥ ↔ ∀ x ∈ s, (x:α) = 0 := submodule.span_eq_bot lemma span_singleton_eq_bot {x} : span ({x} : set α) = ⊥ ↔ x = 0 := submodule.span_singleton_eq_bot lemma span_singleton_eq_top {x} : span ({x} : set α) = ⊤ ↔ is_unit x := by rw [is_unit_iff_dvd_one, ← span_singleton_le_span_singleton, span_singleton_one, eq_top_iff] @[class] def is_prime (I : ideal α) : Prop := I ≠ ⊤ ∧ ∀ {x y : α}, x * y ∈ I → x ∈ I ∨ y ∈ I theorem is_prime.mem_or_mem {I : ideal α} (hI : I.is_prime) : ∀ {x y : α}, x * y ∈ I → x ∈ I ∨ y ∈ I := hI.2 theorem is_prime.mem_or_mem_of_mul_eq_zero {I : ideal α} (hI : I.is_prime) {x y : α} (h : x * y = 0) : x ∈ I ∨ y ∈ I := hI.2 (h.symm ▸ I.zero_mem) theorem is_prime.mem_of_pow_mem {I : ideal α} (hI : I.is_prime) {r : α} (n : ℕ) (H : r^n ∈ I) : r ∈ I := begin induction n with n ih, { exact (mt (eq_top_iff_one _).2 hI.1).elim H }, exact or.cases_on (hI.mem_or_mem H) id ih end theorem zero_ne_one_of_proper {I : ideal α} (h : I ≠ ⊤) : (0:α) ≠ 1 := λ hz, I.ne_top_iff_one.1 h $ hz ▸ I.zero_mem theorem span_singleton_prime {p : α} (hp : p ≠ 0) : is_prime (span ({p} : set α)) ↔ prime p := by simp [is_prime, prime, span_singleton_eq_top, hp, mem_span_singleton] @[class] def is_maximal (I : ideal α) : Prop := I ≠ ⊤ ∧ ∀ J, I < J → J = ⊤ theorem is_maximal_iff {I : ideal α} : I.is_maximal ↔ (1:α) ∉ I ∧ ∀ (J : ideal α) x, I ≤ J → x ∉ I → x ∈ J → (1:α) ∈ J := and_congr I.ne_top_iff_one $ forall_congr $ λ J, by rw [lt_iff_le_not_le]; exact ⟨λ H x h hx₁ hx₂, J.eq_top_iff_one.1 $ H ⟨h, not_subset.2 ⟨_, hx₂, hx₁⟩⟩, λ H ⟨h₁, h₂⟩, let ⟨x, xJ, xI⟩ := not_subset.1 h₂ in J.eq_top_iff_one.2 $ H x h₁ xI xJ⟩ theorem is_maximal.eq_of_le {I J : ideal α} (hI : I.is_maximal) (hJ : J ≠ ⊤) (IJ : I ≤ J) : I = J := eq_iff_le_not_lt.2 ⟨IJ, λ h, hJ (hI.2 _ h)⟩ theorem is_maximal.exists_inv {I : ideal α} (hI : I.is_maximal) {x} (hx : x ∉ I) : ∃ y, y * x - 1 ∈ I := begin cases is_maximal_iff.1 hI with H₁ H₂, rcases mem_span_insert'.1 (H₂ (span (insert x I)) x (set.subset.trans (subset_insert _ _) subset_span) hx (subset_span (mem_insert _ _))) with ⟨y, hy⟩, rw [span_eq, ← neg_mem_iff, add_comm, neg_add', neg_mul_eq_neg_mul] at hy, exact ⟨-y, hy⟩ end theorem is_maximal.is_prime {I : ideal α} (H : I.is_maximal) : I.is_prime := ⟨H.1, λ x y hxy, or_iff_not_imp_left.2 $ λ hx, begin cases H.exists_inv hx with z hz, have := I.mul_mem_left hz, rw [mul_sub, mul_one, mul_comm, mul_assoc] at this, exact I.neg_mem_iff.1 ((I.add_mem_iff_right $ I.mul_mem_left hxy).1 this) end⟩ @[priority 100] -- see Note [lower instance priority] instance is_maximal.is_prime' (I : ideal α) : ∀ [H : I.is_maximal], I.is_prime := is_maximal.is_prime theorem exists_le_maximal (I : ideal α) (hI : I ≠ ⊤) : ∃ M : ideal α, M.is_maximal ∧ I ≤ M := begin rcases zorn.zorn_partial_order₀ { J : ideal α | J ≠ ⊤ } _ I hI with ⟨M, M0, IM, h⟩, { refine ⟨M, ⟨M0, λ J hJ, by_contradiction $ λ J0, _⟩, IM⟩, cases h J J0 (le_of_lt hJ), exact lt_irrefl _ hJ }, { intros S SC cC I IS, refine ⟨Sup S, λ H, _, λ _, le_Sup⟩, obtain ⟨J, JS, J0⟩ : ∃ J ∈ S, (1 : α) ∈ J, from (submodule.mem_Sup_of_directed ⟨I, IS⟩ cC.directed_on).1 ((eq_top_iff_one _).1 H), exact SC JS ((eq_top_iff_one _).2 J0) } end def is_coprime (x y : α) : Prop := span ({x, y} : set α) = ⊤ theorem mem_span_pair {x y z : α} : z ∈ span (insert y {x} : set α) ↔ ∃ a b, a * x + b * y = z := begin simp only [mem_span_insert, mem_span_singleton', exists_prop], split, { rintros ⟨a, b, ⟨c, hc⟩, h⟩, exact ⟨c, a, by cc⟩ }, { rintro ⟨b, c, e⟩, exact ⟨c, b * x, ⟨b, rfl⟩, by cc⟩ } end theorem is_coprime_def {x y : α} : is_coprime x y ↔ ∀ z, ∃ a b, a * x + b * y = z := by simp [is_coprime, submodule.eq_top_iff', mem_span_pair] theorem is_coprime_self {x : α} : is_coprime x x ↔ is_unit x := by rw [← span_singleton_eq_top]; simp [is_coprime] lemma span_singleton_lt_span_singleton [integral_domain β] {x y : β} : span ({x} : set β) < span ({y} : set β) ↔ y ≠ 0 ∧ ∃ d : β, ¬ is_unit d ∧ x = y * d := by rw [lt_iff_le_not_le, span_singleton_le_span_singleton, span_singleton_le_span_singleton, dvd_and_not_dvd_iff] def quotient (I : ideal α) := I.quotient namespace quotient variables {I} {x y : α} def mk (I : ideal α) (a : α) : I.quotient := submodule.quotient.mk a protected theorem eq : mk I x = mk I y ↔ x - y ∈ I := submodule.quotient.eq I instance (I : ideal α) : has_one I.quotient := ⟨mk I 1⟩ @[simp] lemma mk_one (I : ideal α) : mk I 1 = 1 := rfl instance (I : ideal α) : has_mul I.quotient := ⟨λ a b, quotient.lift_on₂' a b (λ a b, mk I (a * b)) $ λ a₁ a₂ b₁ b₂ h₁ h₂, quot.sound $ begin refine calc a₁ * a₂ - b₁ * b₂ = a₂ * (a₁ - b₁) + (a₂ - b₂) * b₁ : _ ... ∈ I : I.add_mem (I.mul_mem_left h₁) (I.mul_mem_right h₂), rw [mul_sub, sub_mul, sub_add_sub_cancel, mul_comm, mul_comm b₁] end⟩ @[simp] theorem mk_mul : mk I (x * y) = mk I x * mk I y := rfl instance (I : ideal α) : comm_ring I.quotient := { mul := (*), one := 1, mul_assoc := λ a b c, quotient.induction_on₃' a b c $ λ a b c, congr_arg (mk _) (mul_assoc a b c), mul_comm := λ a b, quotient.induction_on₂' a b $ λ a b, congr_arg (mk _) (mul_comm a b), one_mul := λ a, quotient.induction_on' a $ λ a, congr_arg (mk _) (one_mul a), mul_one := λ a, quotient.induction_on' a $ λ a, congr_arg (mk _) (mul_one a), left_distrib := λ a b c, quotient.induction_on₃' a b c $ λ a b c, congr_arg (mk _) (left_distrib a b c), right_distrib := λ a b c, quotient.induction_on₃' a b c $ λ a b c, congr_arg (mk _) (right_distrib a b c), ..submodule.quotient.add_comm_group I } /-- `ideal.quotient.mk` as a `ring_hom` -/ def mk_hom (I : ideal α) : α →+* I.quotient := ⟨mk I, rfl, λ _ _, rfl, rfl, λ _ _, rfl⟩ def map_mk (I J : ideal α) : ideal I.quotient := { carrier := mk I '' J, zero := ⟨0, J.zero_mem, rfl⟩, add := by rintro _ _ ⟨x, hx, rfl⟩ ⟨y, hy, rfl⟩; exact ⟨x + y, J.add_mem hx hy, rfl⟩, smul := by rintro ⟨c⟩ _ ⟨x, hx, rfl⟩; exact ⟨c * x, J.mul_mem_left hx, rfl⟩ } @[simp] lemma mk_zero (I : ideal α) : mk I 0 = 0 := rfl @[simp] lemma mk_add (I : ideal α) (a b : α) : mk I (a + b) = mk I a + mk I b := rfl @[simp] lemma mk_neg (I : ideal α) (a : α) : mk I (-a : α) = -mk I a := rfl @[simp] lemma mk_sub (I : ideal α) (a b : α) : mk I (a - b : α) = mk I a - mk I b := rfl @[simp] lemma mk_pow (I : ideal α) (a : α) (n : ℕ) : mk I (a ^ n : α) = mk I a ^ n := (mk_hom I).map_pow a n lemma mk_prod {ι} (I : ideal α) (s : finset ι) (f : ι → α) : mk I (s.prod f) = s.prod (λ i, mk I (f i)) := (mk_hom I).map_prod f s lemma mk_sum {ι} (I : ideal α) (s : finset ι) (f : ι → α) : mk I (s.sum f) = s.sum (λ i, mk I (f i)) := (mk_hom I).map_sum f s lemma eq_zero_iff_mem {I : ideal α} : mk I a = 0 ↔ a ∈ I := by conv {to_rhs, rw ← sub_zero a }; exact quotient.eq' theorem zero_eq_one_iff {I : ideal α} : (0 : I.quotient) = 1 ↔ I = ⊤ := eq_comm.trans $ eq_zero_iff_mem.trans (eq_top_iff_one _).symm theorem zero_ne_one_iff {I : ideal α} : (0 : I.quotient) ≠ 1 ↔ I ≠ ⊤ := not_congr zero_eq_one_iff protected def nonzero_comm_ring {I : ideal α} (hI : I ≠ ⊤) : nonzero_comm_ring I.quotient := { zero_ne_one := zero_ne_one_iff.2 hI, ..quotient.comm_ring I } instance (I : ideal α) [hI : I.is_prime] : integral_domain I.quotient := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b, quotient.induction_on₂' a b $ λ a b hab, (hI.mem_or_mem (eq_zero_iff_mem.1 hab)).elim (or.inl ∘ eq_zero_iff_mem.2) (or.inr ∘ eq_zero_iff_mem.2), ..quotient.nonzero_comm_ring hI.1 } lemma exists_inv {I : ideal α} [hI : I.is_maximal] : ∀ {a : I.quotient}, a ≠ 0 → ∃ b : I.quotient, a * b = 1 := begin rintro ⟨a⟩ h, cases hI.exists_inv (mt eq_zero_iff_mem.2 h) with b hb, rw [mul_comm] at hb, exact ⟨mk _ b, quot.sound hb⟩ end /-- quotient by maximal ideal is a field. def rather than instance, since users will have computable inverses in some applications -/ protected noncomputable def field (I : ideal α) [hI : I.is_maximal] : field I.quotient := { inv := λ a, if ha : a = 0 then 0 else classical.some (exists_inv ha), mul_inv_cancel := λ a (ha : a ≠ 0), show a * dite _ _ _ = _, by rw dif_neg ha; exact classical.some_spec (exists_inv ha), inv_zero := dif_pos rfl, ..quotient.integral_domain I } variable [comm_ring β] /-- Given a ring homomorphism `f : α →+* β` sending all elements of an ideal to zero, lift it to the quotient by this ideal. -/ def lift (S : ideal α) (f : α →+* β) (H : ∀ (a : α), a ∈ S → f a = 0) : quotient S →+* β := { to_fun := λ x, quotient.lift_on' x f $ λ (a b) (h : _ ∈ _), eq_of_sub_eq_zero $ by rw [← f.map_sub, H _ h], map_one' := f.map_one, map_zero' := f.map_zero, map_add' := λ a₁ a₂, quotient.induction_on₂' a₁ a₂ f.map_add, map_mul' := λ a₁ a₂, quotient.induction_on₂' a₁ a₂ f.map_mul } @[simp] lemma lift_mk (S : ideal α) (f : α →+* β) (H : ∀ (a : α), a ∈ S → f a = 0) : lift S f H (mk S a) = f a := rfl end quotient /-- All ideals in a field are trivial. -/ lemma eq_bot_or_top {K : Type u} [field K] (I : ideal K) : I = ⊥ ∨ I = ⊤ := begin rw classical.or_iff_not_imp_right, change _ ≠ _ → _, rw ideal.ne_top_iff_one, intro h1, rw eq_bot_iff, intros r hr, by_cases H : r = 0, {simpa}, simpa [H, h1] using submodule.smul_mem I r⁻¹ hr, end lemma eq_bot_of_prime {K : Type u} [field K] (I : ideal K) [h : I.is_prime] : I = ⊥ := classical.or_iff_not_imp_right.mp I.eq_bot_or_top h.1 end ideal /-- The set of non-invertible elements of a monoid. -/ def nonunits (α : Type u) [monoid α] : set α := { a | ¬is_unit a } @[simp] theorem mem_nonunits_iff [comm_monoid α] : a ∈ nonunits α ↔ ¬ is_unit a := iff.rfl theorem mul_mem_nonunits_right [comm_monoid α] : b ∈ nonunits α → a * b ∈ nonunits α := mt is_unit_of_mul_is_unit_right theorem mul_mem_nonunits_left [comm_monoid α] : a ∈ nonunits α → a * b ∈ nonunits α := mt is_unit_of_mul_is_unit_left theorem zero_mem_nonunits [semiring α] : 0 ∈ nonunits α ↔ (0:α) ≠ 1 := not_congr is_unit_zero_iff @[simp] theorem one_not_mem_nonunits [monoid α] : (1:α) ∉ nonunits α := not_not_intro is_unit_one theorem coe_subset_nonunits [comm_ring α] {I : ideal α} (h : I ≠ ⊤) : (I : set α) ⊆ nonunits α := λ x hx hu, h $ I.eq_top_of_is_unit_mem hx hu lemma exists_max_ideal_of_mem_nonunits [comm_ring α] (h : a ∈ nonunits α) : ∃ I : ideal α, I.is_maximal ∧ a ∈ I := begin have : ideal.span ({a} : set α) ≠ ⊤, { intro H, rw ideal.span_singleton_eq_top at H, contradiction }, rcases ideal.exists_le_maximal _ this with ⟨I, Imax, H⟩, use [I, Imax], apply H, apply ideal.subset_span, exact set.mem_singleton a end section prio set_option default_priority 100 -- see Note [default priority] class local_ring (α : Type u) extends nonzero_comm_ring α := (is_local : ∀ (a : α), (is_unit a) ∨ (is_unit (1 - a))) end prio namespace local_ring variable [local_ring α] lemma is_unit_or_is_unit_one_sub_self (a : α) : (is_unit a) ∨ (is_unit (1 - a)) := is_local a lemma is_unit_of_mem_nonunits_one_sub_self (a : α) (h : (1 - a) ∈ nonunits α) : is_unit a := or_iff_not_imp_right.1 (is_local a) h lemma is_unit_one_sub_self_of_mem_nonunits (a : α) (h : a ∈ nonunits α) : is_unit (1 - a) := or_iff_not_imp_left.1 (is_local a) h lemma nonunits_add {x y} (hx : x ∈ nonunits α) (hy : y ∈ nonunits α) : x + y ∈ nonunits α := begin rintros ⟨u, hu⟩, apply hy, suffices : is_unit ((↑u⁻¹ : α) * y), { rcases this with ⟨s, hs⟩, use u * s, convert congr_arg (λ z, (u : α) * z) hs, rw ← mul_assoc, simp }, rw show (↑u⁻¹ * y) = (1 - ↑u⁻¹ * x), { rw eq_sub_iff_add_eq, replace hu := congr_arg (λ z, (↑u⁻¹ : α) * z) hu, simpa [mul_add, add_comm] using hu }, apply is_unit_one_sub_self_of_mem_nonunits, exact mul_mem_nonunits_right hx end variable (α) def nonunits_ideal : ideal α := { carrier := nonunits α, zero := zero_mem_nonunits.2 $ zero_ne_one, add := λ x y hx hy, nonunits_add hx hy, smul := λ a x, mul_mem_nonunits_right } instance nonunits_ideal.is_maximal : (nonunits_ideal α).is_maximal := begin rw ideal.is_maximal_iff, split, { intro h, apply h, exact is_unit_one }, { intros I x hI hx H, erw not_not at hx, rcases hx with ⟨u,rfl⟩, simpa using I.smul_mem ↑u⁻¹ H } end lemma max_ideal_unique : ∃! I : ideal α, I.is_maximal := ⟨nonunits_ideal α, nonunits_ideal.is_maximal α, λ I hI, hI.eq_of_le (nonunits_ideal.is_maximal α).1 $ λ x hx, hI.1 ∘ I.eq_top_of_is_unit_mem hx⟩ variable {α} @[simp] lemma mem_nonunits_ideal (x) : x ∈ nonunits_ideal α ↔ x ∈ nonunits α := iff.rfl end local_ring def is_local_ring (α : Type u) [comm_ring α] : Prop := ((0:α) ≠ 1) ∧ ∀ (a : α), (is_unit a) ∨ (is_unit (1 - a)) def local_of_is_local_ring [comm_ring α] (h : is_local_ring α) : local_ring α := { zero_ne_one := h.1, is_local := h.2, .. ‹comm_ring α› } def local_of_unit_or_unit_one_sub [comm_ring α] (hnze : (0:α) ≠ 1) (h : ∀ x : α, is_unit x ∨ is_unit (1 - x)) : local_ring α := local_of_is_local_ring ⟨hnze, h⟩ def local_of_nonunits_ideal [comm_ring α] (hnze : (0:α) ≠ 1) (h : ∀ x y ∈ nonunits α, x + y ∈ nonunits α) : local_ring α := local_of_is_local_ring ⟨hnze, λ x, or_iff_not_imp_left.mpr $ λ hx, begin by_contra H, apply h _ _ hx H, simp [-sub_eq_add_neg, add_sub_cancel'_right] end⟩ def local_of_unique_max_ideal [comm_ring α] (h : ∃! I : ideal α, I.is_maximal) : local_ring α := local_of_nonunits_ideal (let ⟨I, Imax, _⟩ := h in (λ (H : 0 = 1), Imax.1 $ I.eq_top_iff_one.2 $ H ▸ I.zero_mem)) $ λ x y hx hy H, let ⟨I, Imax, Iuniq⟩ := h in let ⟨Ix, Ixmax, Hx⟩ := exists_max_ideal_of_mem_nonunits hx in let ⟨Iy, Iymax, Hy⟩ := exists_max_ideal_of_mem_nonunits hy in have xmemI : x ∈ I, from ((Iuniq Ix Ixmax) ▸ Hx), have ymemI : y ∈ I, from ((Iuniq Iy Iymax) ▸ Hy), Imax.1 $ I.eq_top_of_is_unit_mem (I.add_mem xmemI ymemI) H section prio set_option default_priority 100 -- see Note [default priority] class is_local_ring_hom [semiring α] [semiring β] (f : α →+* β) : Prop := (map_nonunit : ∀ a, is_unit (f a) → is_unit a) end prio @[simp] lemma is_unit_of_map_unit [semiring α] [semiring β] (f : α →+* β) [is_local_ring_hom f] (a) (h : is_unit (f a)) : is_unit a := is_local_ring_hom.map_nonunit a h section open local_ring variables [local_ring α] [local_ring β] variables (f : α →+* β) [is_local_ring_hom f] lemma map_nonunit (a) (h : a ∈ nonunits_ideal α) : f a ∈ nonunits_ideal β := λ H, h $ is_unit_of_map_unit f a H end namespace local_ring variables [local_ring α] [local_ring β] variable (α) def residue_field := (nonunits_ideal α).quotient noncomputable instance residue_field.field : field (residue_field α) := ideal.quotient.field (nonunits_ideal α) /-- The quotient map from a local ring to it's residue field. -/ def residue : α →+* (residue_field α) := ideal.quotient.mk_hom _ namespace residue_field variables {α β} noncomputable def map (f : α →+* β) [is_local_ring_hom f] : residue_field α →+* residue_field β := ideal.quotient.lift (nonunits_ideal α) ((ideal.quotient.mk_hom _).comp f) $ λ a ha, begin erw ideal.quotient.eq_zero_iff_mem, exact map_nonunit f a ha end end residue_field end local_ring namespace field variables [field α] @[priority 100] -- see Note [lower instance priority] instance : local_ring α := { is_local := λ a, if h : a = 0 then or.inr (by rw [h, sub_zero]; exact is_unit_one) else or.inl $ is_unit_of_mul_eq_one a a⁻¹ $ div_self h } end field
1f5f403861c849d292ddd05b74bc3009f94b5430
367134ba5a65885e863bdc4507601606690974c1
/src/category_theory/simple.lean
2b71e823f1bdad8185cffefa14894db324cde3e8
[ "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,963
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel, Scott Morrison -/ import category_theory.limits.shapes.zero import category_theory.limits.shapes.kernels import category_theory.abelian.basic noncomputable theory open category_theory.limits namespace category_theory universes v u variables {C : Type u} [category.{v} C] section variables [has_zero_morphisms C] /-- An object is simple if monomorphisms into it are (exclusively) either isomorphisms or zero. -/ -- This is a constructive definition, from which we can extract an inverse for `f` given `f ≠ 0`. -- We show below that although it contains data, it is a subsingleton. class simple (X : C) : Type (max u v) := (mono_is_iso_equiv_nonzero : ∀ {Y : C} (f : Y ⟶ X) [mono f], is_iso f ≃ (f ≠ 0)) @[ext] lemma simple.ext {X : C} {a b : simple X} : a = b := begin casesI a, casesI b, congr, end instance subsingleton_simple (X : C) : subsingleton (simple X) := subsingleton.intro (@simple.ext _ _ _ X) /-- A nonzero monomorphism to a simple object is an isomorphism. -/ def is_iso_of_mono_of_nonzero {X Y : C} [simple Y] {f : X ⟶ Y} [mono f] (w : f ≠ 0) : is_iso f := (simple.mono_is_iso_equiv_nonzero f).symm w lemma kernel_zero_of_nonzero_from_simple {X Y : C} [simple X] {f : X ⟶ Y} [has_kernel f] (w : f ≠ 0) : kernel.ι f = 0 := begin classical, by_contradiction h, haveI := is_iso_of_mono_of_nonzero h, exact w (eq_zero_of_epi_kernel f), end lemma mono_to_simple_zero_of_not_iso {X Y : C} [simple Y] {f : X ⟶ Y} [mono f] (w : is_iso f → false) : f = 0 := begin classical, by_contradiction h, apply w, exact is_iso_of_mono_of_nonzero h, end lemma id_nonzero (X : C) [simple.{v} X] : 𝟙 X ≠ 0 := (simple.mono_is_iso_equiv_nonzero (𝟙 X)) (by apply_instance) section variable [has_zero_object C] local attribute [instance] has_zero_object.has_zero /-- We don't want the definition of 'simple' to include the zero object, so we check that here. -/ lemma zero_not_simple [simple (0 : C)] : false := (simple.mono_is_iso_equiv_nonzero (0 : (0 : C) ⟶ (0 : C))) { inv := 0, } rfl end end -- We next make the dual arguments, but for this we must be in an abelian category. section abelian variables [abelian C] /-- In an abelian category, an object satisfying the dual of the definition of a simple object is simple. -/ def simple_of_cosimple (X : C) (h : ∀ {Z : C} (f : X ⟶ Z) [epi f], is_iso f ≃ (f ≠ 0)) : simple X := ⟨λ Y f I, begin classical, apply equiv_of_subsingleton_of_subsingleton, { introsI, have hx := cokernel.π_of_epi f, by_contradiction h, push_neg at h, substI h, exact h _ (cokernel.π_of_zero _ _) hx }, { intro hf, suffices : epi f, { resetI, apply abelian.is_iso_of_mono_of_epi }, apply preadditive.epi_of_cokernel_zero, by_contradiction h', exact cokernel_not_iso_of_nonzero hf ((h _).symm h') } end⟩ /-- A nonzero epimorphism from a simple object is an isomorphism. -/ def is_iso_of_epi_of_nonzero {X Y : C} [simple X] {f : X ⟶ Y} [epi f] (w : f ≠ 0) : is_iso f := begin -- `f ≠ 0` means that `kernel.ι f` is not an iso, and hence zero, and hence `f` is a mono. haveI : mono f := preadditive.mono_of_kernel_zero (mono_to_simple_zero_of_not_iso (kernel_not_iso_of_nonzero w)), exact abelian.is_iso_of_mono_of_epi f, end lemma cokernel_zero_of_nonzero_to_simple {X Y : C} [simple Y] {f : X ⟶ Y} [has_cokernel f] (w : f ≠ 0) : cokernel.π f = 0 := begin classical, by_contradiction h, haveI := is_iso_of_epi_of_nonzero h, exact w (eq_zero_of_mono_cokernel f), end lemma epi_from_simple_zero_of_not_iso {X Y : C} [simple X] {f : X ⟶ Y} [epi f] (w : is_iso f → false) : f = 0 := begin classical, by_contradiction h, apply w, exact is_iso_of_epi_of_nonzero h, end end abelian end category_theory
d35762ce99fe1dc0ff519d55a6be6a22080d6cf2
c28b6af040437c3aecc5e9a23351205ba71d9394
/src/12_Sets/00_intro.lean
8a4568392984c0c7e77ec58ec0f2e8cadc1a19f3
[]
no_license
png/cs-dm-lean
1941672c4007745a6b45d5e3500e270296ec48b3
7437aa002cddf116836a425a10f08b4ccbe1c916
refs/heads/master
1,586,285,968,765
1,542,741,918,000
1,542,741,918,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
31,195
lean
import data.set open set /- Intuitively a set is a collection of objects. That said, if one is not careful about what one allows a set to be, paradoxes can arise, making the logical system inconsistent, and thus useless. For more details, search for an explanation of Russell's paradox. The work needed to repair Russell's original mistake led to Zermelo-Frankel set theory, the set theory of everyday mathematics, and also, at least indirectly to the type theory that underpins Lean and relate proof assistants. There are two things to know about how sets and operations involving sets are reprented in Lean. First, in Lean, set is what we call a type constructor. Second, sets are identified with membership predicates. We discuss each of these idea next. -/ -- Type Constructors: set /- First, set is a type constructor, not a type. It takes a type parameter as an argument and returns a type, one now specialized to the argument type. Because it takes a type and returns a type, set (and a type constructor more generally) is a function: one of type, Type → Type. So, for example, set int is the type of sets with int-valued elements. Lean tells us that the set type constructor can actually take a type in any type universe, i.e., Type (which is really Type 0), Type 1, Type 2, etc. We needn't be concerned with that here. -/ #check set -- Membership Predicates /- Second, sets in Lean are identified with membership predicates: of type T → Prop, where T is type of elements in a set. The membership predicate is true for values in the set and not true otherwise. -/ #check set nat #reduce set ℕ -- Example: the empty set of ℕ /- For example the empty set of ℕ values, also written as ∅ ℕ, is literally defined as the predicate, λ n : ℕ, false. This predicate is satisfied for no value of type ℕ, and so the set it defines is the empty set. -/ #check (∅ : set ℕ ) /- We think of the predicate that defines a set as specifying a property of elements of the kind in or not in the set. The type, set ℕ, is thus equated with a predicate on ℕ, which we consider as defining the property of being of being a member of the set. Sets (at least) in Lean are identified with their membership predicates. As an example, the empty set of ℕ is defined by the predicate that is false for every ℕ. No natural number satisfies this predicate. The set it denotes is the set of values that satisfy it, which is the empty set. Study the following code with care and understand it. -/ #reduce (∅ : set ℕ) /- The predicate that defines the empty set is, as we've already discussed, false(n): i.e., the function of type ℕ → Prop that for any value, n : ℕ, returns the proposition false. No ℕ can satisfy this predicate by making it anything other than false. The set it designates is the empty set. -/ -- Display Notation /- Let's bind and empty set of ℕ to the identifier, e. We can also write the empty set using curly braces, or what we call set display notation. -/ def e: set ℕ := { } /- The symbol, ∅, is often used to represent the empty set (of values of whatever type). -/ def e': set ℕ := ∅ /- We can't write "e : set := {}"", because then Lean would not have enough context to infer the type of the set elements. -/ /- EXERCISE: What is the property of natural numbers that characterizes e, the empty set of natural numbers? Give you answer as a predicate: a function from ℕ to Prop. Give a λ abstraction as an answer. -/ /- EXERCISE: What predicate defines the set of all ℕ values? -/ -- Set Builder Notation /- We can also represent the empty set using set builder notation. Set builder notation is also called set comprehension notation. -/ /- Here we define the empty set of ℕ again -/ def e'' : set ℕ := { n | false } /- Now we define the entire set of even ℕ -/ def evs : set ℕ := { n | ∃ m, m + m = n } -- Singleton Sets /- Here's another set of ℕ, containing only the number, 1. We call such a set a singleton set. -/ def x: set nat := { 1 } /- EXERCISE: What property of natural numbers defines the property of being in this set? Try to come up with the answer before you look! -/ #reduce x /- The answer is a little surprising. The predicate λ n, n = 1, would do to define this set, but instead Lean uses λ n, n = 1 ∨ false. Lean could have, and in some cases will, leave off the (∨ false) at the end. See it is so in the following example code. -/ def x' := { n | n = 1 } #reduce x' /- The two different notations give rise to slightly different but equivalent predicates, and thus to the same sets. -/ -- SET MEMBERSHIP /- So what does set membership mean? By the notation 1 ∈ x we mean the proposition that "1 is in, or is a member of the set, x." This is simply the proposition obtained by applying the predicate, x, to the value, 1. x is the set and it is the predicate that defines the set. In Lean they are the same thing. The proposition 1 ∈ x is definitionally the same as (x 1). The predicate, i.e., the set, x, is defined as λ (n : ℕ), n = 1. Applying this predicate/function to 1 yields the proposition that: 1 = 1 ∨ false. This proposition, in turn, is easy to prove, and so, yes, indeed, 1 is in the set x. -/ /- Reducing 1 ∈ x reveals the proposition obtained by applying the x predicate to the value 1 to get a membership proposition for 1. -/ #reduce 1 ∈ x /- In this case, the membership proposition, 1 ∈ x, is true, as we prove next. -/ example : 1 ∈ x := -- 1 = 1 ∨ false begin /- It can be easier to work with proofs about sets if you use the change tactic to ask Lean to show you the predicate that the goal represents. You can use #reduce to see the proposition that the goal using set notation denotes. -/ change 1 = 1 ∨ false, -- the rest is straightforward apply or.intro_left, exact rfl, end /- Here we use some shorthand tactics to make it easier to write the proof. It's good to learn this shortcuts. They make quick work of some proof goals. -/ example : 1 ∈ x := -- 1 = 1 begin change 1 = 1 ∨ false, -- now or.intro_left, but with a shortcut left, -- and now exact rfl, but with a shortcut trivial, end -- MORE EXAMPLE /- Here's two sets with three elements each. -/ def y : set nat := { 1, 2, 3 } def z : set nat := { 2, 3, 4 } /- EXERCISE: What is a predicate that characterizes membership in the set, y? -/ #reduce y /- EXERCISE: Define the same set, y, with the name, y', using set builder notation. -/ def y' : set nat := { n | n = 1 ∨ n = 2 ∨ n = 3 } #reduce y /- With these basics in hand, we can define, understand, and work with the full range of set operations. Set operations are like operations with numbers but their operands and results are sets. -/ -- SET UNION /- The union of two sets, y and z, which we denote as y ∪ z, is the combined set of values from y and z. An element is either in or not in a given, but cannot be in a more than one time (otherwise you have what is called a multiset). The union of y and z as defined above is thus the set { 1, 2, 3, 4 }. -/ def u := y ∪ z /- EXERCISE: What predicate defines the set that is the union of y and z? -/ #reduce u /- Answer: It is the predicate that defines what it means to be in y or to be in z. That is, it is the disjunction of the predicates that define y and z, respectively. Union corresponds to "or." -/ /- Let's prove that 3 ∈ u. Let's start by reminding ourselves of the predicate that defines u and of the proposition represented by 3 ∈ u. -/ #reduce u /- The set, u, is defined as a predicate that takes a : ℕ and returns the proposition that that a is one of the values in the set, expressed as a somewhat long disjunction. Lean selects the variable name, a, for purposes of printing out the value of u. There is no special meaning to a; it is just an otherwise unbound name. -/ /- Now that we know that 3 ∈ u is just a proposition involving a bunch of disjunctions, it's easy to prove. -/ example : 3 ∈ u := begin /- Notice again that Lean leaves the goal written using set membership notation. Just bear in mind that the goal is just the disjunction, (3 = 3 ∨ 3 = 2 ∨ 3 = 1 ∨ false) ∨ 3 = 4 ∨ 3 = 3 ∨ 3 = 2 ∨ false. -/ left, left, trivial, end #reduce 3 ∈ y ∪ z /- Or, if you prefer, make the goal explicit as a disjunction. -/ example : 3 ∈ y ∪ z := begin change (3 = 3 ∨ 3 = 2 ∨ 3 = 1 ∨ false) ∨ 3 = 4 ∨ 3 = 3 ∨ 3 = 2 ∨ false, apply or.inl, apply or.inl, trivial, end -- SET INTERSECTION /- The intersection of two sets, y and z, which we denote as y ∩ z, is the set containing those values that are in y and that are in z. Intersection thus corresponds to the conjunction of the predicates defining the two individual sets. -/ def w := y ∩ z #reduce w example : 2 ∈ y ∩ z := -- (a = 3 ∨ a = 2 ∨ a = 1 ∨ false) ∧ (a = 4 ∨ a = 3 ∨ a = 2 ∨ false) begin apply and.intro, -- 2 ∈ y right, left, trivial, -- 2 ∈ z right, right, left, trivial, end -- SET DIFFERENCE /- The set difference y - z, also writen as y \ z, is the set of values that are in y but not in z. Think of the subtraction as saying that from y you take away z, and the result is what is left of y. EXERCISE: What predicate defines a set difference, y \ z? -/ #reduce y \ z example : 1 ∈ y \ z := begin -- apply and.intro, split, -- 1 ∈ y right, right, left, trivial, /- The goal looks funny, but think about what it means. It is the predicate, (λ (a : ℕ), a ∉ z), applied to the value, 1, which is to say it's the proposition, 1 ∉ z. That in turn is ¬ 1 ∈ z. And that, in turn, is just the proposition that 1 ∈ z → false. So assume 1 ∈ z and show false to prove it. What is 1 ∈ z? It's the proposition that 1 is one of the elements in the set, written as a disjunction, so use case analysis! -/ -- 1 ∉ z assume pf, cases pf, /- Now we need a proof that 1 ≠ 4. The dec_trivial tactic defined in the Lean's standard library "decides" many purely arithmetic propositions. That is, it generates either a proof that such a proposition is true if it's true. It will also generate a proof that its negation is true if that is the case. The dec_trivial tactic implements a "decision procedure" for sufficiently simple propositions involved numbers. Here we use it to give us a proof of 1 ≠ 4. We can then use that to get a proof of false and use false elim to eliminate the current case on grounds that it is based on contradictory assumptions (and thus can't happen). -/ have h : 1 ≠ 4 := dec_trivial, /- The contradiction tactic looks for a explicit contradiction in the context and if it finds one, applies false.elim to finish proving the goal. -/ contradiction, cases pf, have h : 1 ≠ 3 := dec_trivial, contradiction, cases pf, have h : 1 ≠ 2 := dec_trivial, contradiction, have f : false := pf, contradiction, end -- SUMMARY SO FAR /- The examples in this summary require you to recall that previously in this file we defined x, y, and z to be the ℕ sets, { 1 }, { 1, 2, 3 }, and { 2, 3, 4 }. -/ #print x #print y #print z /- A set can be, and in Lean is, characterized by a predicate: one that is true for each member of the set and false otherwise. It is a "membership predicate". Consider, for example, what it means for 1 or for 2 to be in the set, x. We write these propositions as 1 ∈ x and as 2 ∈ x respectively. -/ #reduce 1 ∈ x #reduce 2 ∈ x #reduce 3 ∈ z /- The union of two sets is given by the disjunction (or, ∨) of the respective membership predicates: (a ∈ y ∪ z) means (a ∈ y) ∨ (a ∈ z). -/ #reduce 1 ∈ (y ∪ z) #reduce (1 ∈ y) ∨ (1 ∈ z) /- The intersection of two sets is defined by the conjunction of the respective membership predicates: (x ∈ y ∩ z) = (x ∈ y ∧ a ∈ z) -/ #reduce (1 ∈ y ∩ z) /-The difference of two sets, y \ z, is defined by the conjunction of the first and the negation of the second membership predicates for the sets: (a ∈ y \ z) = ( a ∈ y) ∧ (¬ a ∈ z). -/ #reduce 1 ∈ y \ z -- PART II /- Now we introduce additional basic set theory concepts: these include notions of subsets, set equality, power sets, product sets, tuples, and a function that simulates an element insertion operator for sets. In all cases, we see that these set operations can be understood as operations on the predicates that define sets. The connection of set theory to predicate logic is thus made clear and explicit. -/ -- SUBSET /- Subset, denoted ⊆, is a binary relation on sets, denoted X ⊆ Y, where X and Y are sets. Viewed as a predicate on such sets, it is satisfied (made true by X and Y) iff every member of X is also a member of Y. Logically, X is a subset of Y if the property of being in X implies the property of being in Y. -/ #check x ⊆ y #reduce x ⊆ y /- Note that what is displayed when you hover over the reduce line includes "script" curly brace characters. These indicate a slight variant on implicit arguments that we needn't get in any detail right now. Just think of them as indicating implicit arguments. -/ /- So, { 1, 2 } ⊆ { 1, 2, 3 }, for example, but is is not the case that { 1, 2 } ⊆ { 1, 3, 4}. In the first case, every element of the set, { 1, 2 }, is also in the set { 1, 2, 3 }, so { 1, 2 } is a subset of { 1, 2, 3 }; but that is not the case for { 1, 2 } and { 1, 3, 4 }. -/ /- EXERCISE: List all of the subsets of each of the following sets of ℕ. * ∅ * { 1 } * { 1, 2 } * { 1, 2, 3 } EXERCISE: How many subsets are there of a set containing n elements. Does your formula work even for the empty set? -/ /- We can now see that the subset relation on sets has a precise logical meaning. x ⊆ y means ∀ a, a ∈ x → a ∈ y. -/ #check x ⊆ y #reduce x ⊆ y /- A quick note on a pattern that appears often in predicate logic: Let's look at the definition of the subset relation again, for sets of ℕ values, x and y. Here is what it means for y ⊆ x. ∀ (a : ℕ), a ∈ y → a ∈ z. Let's translate this to logicky English. For any natural number, a, if a is in y then e is in z. That is what is means for y to be a subset of z. What's interesting in this formulation is the combination of a ∀, which picks out *all* elements of the ℕ type, followed by a conditional (implication), where the premise imposes a further constraint on the elements being considered. It need only be true that every ℕ that is *also* and element of y be a member of z for y to be a subset of z. This is a common pattern in logic. The general form is ∀ x : T, P x → Q x. It is read as saying that for any x *with property P*, some other property, Q, must hold. In effect it quantifies over the values of type T with property P, and then makes a statement about those values, in particular: here they they also have property Q. -/ /- Okay, so let assert and prove a proposition involving the subset relation. We'll show that x ⊆ y, i.e., { 1 } ⊆ { 1, 2, 3 }. To do it we have to proving that if a ∈ x then a ∈ y. Now remember what x and a ∈ x are. First, x is understood to be a set, but it is specifically a membership predicate, of type ℕ → Prop, and a ∈ x is a proposition, namely the one obtained by applying the membership predicate to a: (x a). If (x a), i.e., a ∈ x, is true, i.e., provable, then a is said to be a member of the set, x. -/ /- Let's have another look at what the proposition, x ⊆ y, means: for any a, if a ∈ x then a ∈ y. -/ #reduce x ⊆ y /- So let's prove it's true. -/ example : x ⊆ y := begin /- It's sometimes helpful to change from set notation to the equivalent propositional notation. The change tactic will do this for you, as long as what you're changing the goal is is "definitionally equal" to the current goal. You cand find out what the exact proposition is using reduce, as we did above. -/ change ∀ ⦃a : ℕ⦄, a = 1 ∨ false → a = 3 ∨ a = 2 ∨ a = 1 ∨ false, /- The rest is just an everyday proof. Note that we can quickly zero in on the disjunct we need using a series of left and right tactics. (You do need to remember that ∨ is right associative, so left gives you the left disjunct and right gives you everything else to the right of the leftmost disjunct. -/ assume a, intro h, cases h, -- case a = 1 right, right, left, assumption, -- case false contradiction, end section sets /- We temporarily assume, within this section, that T is an arbitrary type, x is an arbitrary value of type T, and that A, B, and C are arbitrary sets of T-type elements. -/ variable T : Type variable x : T variables A B C : set T /- We can confirm our understanding of the subset relation using this notation. Now A and B are sets, and in Lean that means that these sets are represented by their membership predicates. They are membership predicates. -/ #reduce A ⊆ B /- EXERCISE: Explain precisely what the message produced by #reduce is saying. What is another way that Lean could have written A a or B a? -/ -- SET EQUALITY (and extensionality) /- The "principle of extensionality" for sets stipulates that if one can show that ∀ e, (e ∈ A ↔ e ∈ B) → (A = B). -/ #check ext /-When faced with a goal of proving that two sets, A and B are equal, i.e., that A = B, one can apply this principle to reduce the goal to that of showing that ∀ e, e ∈ A ↔ e ∈ B. -/ -- set equality example : A = B := begin apply ext, intro x, apply iff.intro, intro, /- We can proceed no further here, as we have nothing to use to prove that A actually does equal B in this case. A and B are just arbitary sets, so not equal, in general. What the example is meant to show is how to use ext and how to proceed. As for this proof, we will just abandon it as not possible to prove. -/ end /- Let's prove that { 1, 2 } = { 2, 1 }. -/ def p : set ℕ := { 1, 2 } def q : set ℕ := { 2, 1 } #reduce 1 ∈ p theorem oo : p = q := begin apply ext, intro x, apply iff.intro, -- forward direction intro, -- remember that a is a disjunction cases a with first rest, /- We introduce a new tactic: rewrite, written as rw h or rw ←h. When applied to a proof, h : x = y or h : x ↔ y, of an equality or a bi-implication, it rewrites any occurrences of the left side, x, in the goal, with the right side, y. If you want to rewrite by replacing occurrences of the right side, y, with the left, x, use rw ←h. -/ rw first, right, left, apply rfl, cases rest, rw rest, apply or.inl, apply rfl, -- rest is now ((λ n, false) x) = false! apply false.elim rest, -- backward direction intro, cases a, rw a, right, left, apply rfl, cases a, rw a, left, apply rfl, apply false.elim a, end -- POWERSET /- The powerset of a set, A, is the set of all of the subsets of A. -/ #check A #check powerset A #check 𝒫 A #reduce 𝒫 A /- Note about implicit arguments. In the preceding definition we see {{ }} brackets, rendered using the characters, ⦃ ⦄. This states that the argument is to be inferred from context (is implicit) but is expected only when it appears before another implicit argument. This notation tells Lean not to "eagerly" consume the argument, as soon as it can, but to wait to consume it until it appears, implicitly, before another implicit argument in a list of arguments. This is a notational detail that it's not worth worry about at the moment. -/ /- There are two members we always know are in the powerset of A: the emptyset and A itself. Of course, if A is the emptyset, this is technically only one member, but the proofs are the same. -/ #check A #check 𝒫 A #reduce 𝒫 A /- We define the powerset of A, itself a set, as, λ (t : T → Prop), ∀ ⦃a : T⦄, t a → A a. Let's analyze this. First, we note that it is a predicate, as we would expect, given that we use predicates to define sets. In particular, this a predicate on values of type, T → Prop, which is to say, this is a predicate on predicates that define sets! It's a predicate that's true whenever its argument, a set defined by a predicate, is a subst of A, which is to say that it's true when any element in the argument (set) is also in A. When applied to a set, t, this predicate is satisfied (true) if and only if every a in t is also in A: formally, ∀ ⦃a : T⦄, t a → A a. -/ #reduce ∅ ∈ 𝒫 A /- Lean is helping us here. We need to show that if a ∈ ∅ then a ∈ a to show that ∅ is a subset of A. But a ∈ ∅ is literally false. To see it, work through the application of the predicate for ∅ to any value, a. Lean is simplifying a ∈ ∅ to false. -/ example: ∅ ∈ 𝒫 A := /- To show that the set, ∅, is in the set 𝒫 A, we have to show that ∅ is a subset of A. To do that, we have to show that any t that is in ∅ is also in A. -/ begin -- change goal to logical form change ∀ ⦃a : T⦄, false → A a, -- use forall introduction intro t, -- now it's a trivial proof assume t_in_emptyset, contradiction, end #reduce A ∈ 𝒫 A /- To prove this, we need to prove that A is subset of A, which is to say any a in A is also in A. It's as simple as that and the proof is of course trivial. -/ example: A ∈ 𝒫 A := begin change ∀ ⦃a : T⦄, A a → A a, assume t, assume t_in_A, assumption end /- Slightly more interesting cases are also easy to prove. There's nothing involved here beyond what you already understand. -/ #reduce ({1, 3}: set ℕ) ∈ 𝒫 ({1, 2, 3}: set ℕ) /- One again to prove that {1, 3} is in the power set of {1, 2, 3} it suffices to show that every element of {1, 3} is in {1, 2, 3}, because that is what it means to be a subset. The proof is straightforward. -/ example: ({1, 3}: set ℕ) ∈ 𝒫 ({1, 2, 3}: set ℕ) := begin change ∀ ⦃a : ℕ⦄, a = 3 ∨ a = 1 ∨ false → a = 3 ∨ a = 2 ∨ a = 1 ∨ false, -- forall introduction intro t, -- assume premise of implication to be proved assume pf_t_in_1_3, -- use or elimination on proof of premise cases pf_t_in_1_3 with pf_t_is_3 pf_t_in_1 , -- show 3 from {1, 3} is in {1, 2, 3} exact or.inl pf_t_is_3, -- show 1 from {1, 3} is in {1, 2, 3} right, -- an ever so slightly clever or intro exact or.inr pf_t_in_1, end -- a more involved example; study this one -- {{1, 2}, {1, 3}, {2, 3}} ⊆ 𝒫 {1, 2, 3} #reduce ({{1, 2}, {1, 3}, {2, 3}}: set (set nat)) ⊆ 𝒫 ({1, 2, 3}) example : ({{1, 2}, {1, 3}, {2, 3}}) ⊆ 𝒫 ({1, 2, 3} : set nat) := begin change ∀ ⦃a : ℕ → Prop⦄, (a = λ (b : ℕ), b = 3 ∨ b = 2 ∨ false) ∨ (a = λ (b : ℕ), b = 3 ∨ b = 1 ∨ false) ∨ (a = λ (b : ℕ), b = 2 ∨ b = 1 ∨ false) ∨ false → ∀ ⦃a_1 : ℕ⦄, a a_1 → a_1 = 3 ∨ a_1 = 2 ∨ a_1 = 1 ∨ false, intro s, assume pf_s_in_subset, cases pf_s_in_subset with pf_s_is_2_3, assume t, assume pf_t_in_s, cases pf_s_is_2_3 with pf_s_is_3, cases pf_t_in_s with pf_t_is_3 pf_t_in_2, exact or.inl pf_t_is_3, apply or.inr, cases pf_t_in_2 with pf_t_in_2 pf_t_in_emptyset, exact or.inl pf_t_in_2, exact false.elim pf_t_in_emptyset, cases pf_s_in_subset with pf_s_is_1_3, assume t, assume pf_t_in_s, cases pf_s_is_1_3 with pf_s_is_3, cases pf_t_in_s with pf_t_is_3 pf_t_in_1, exact or.inl pf_t_is_3, apply or.inr, apply or.inr, assumption, cases pf_s_in_subset with pf_s_is_1_2 pf_s_in_emptyset, assume t, assume pf_t_in_s, cases pf_s_is_1_2 with pf_s_is_2, cases pf_t_in_s with pf_t_is_2 pf_t_in_1, apply or.inr, exact or.inl pf_t_is_2, apply or.inr, apply or.inr, assumption, exact false.elim pf_s_in_emptyset, end -- Tuples /- If S and T are types, then the product type of S and T, written out as (prod S T) and in shorthand as S × T, has as its values all of 2-tuples, or ordered pairs, (s, t), where s : S, and t : T. -/ /- In the following code, we see that ℕ × ℕ is a type, and the 2-tuple, or ordered pair, (1, 2), is a value of this type. -/ #check ℕ × ℕ #check prod ℕ ℕ #check (1, 2) /- We can form product types from any two types. Note the type of this 2-tuple. -/ #check ("Hello Lean", 1) /- This ordered pair notation in Lean in shorthand for the appliation of the constructor, prod.mk, two two arguments. The constructor takes the type arguments implicitly. -/ #check prod.mk 1 2 -- long way to write (1, 2) example : prod.mk 1 2 = (1, 2) := rfl /- We can form 3- and larger tuples using nested 2-tuples. Note that × is right associative, as you can see by studying the type of this term. -/ #check ("Hello Lean", (10, (tt,1))) #check ((0,0),(0,0)) -- PRODUCT SET /- The Cartesian product set of two sets, A and B, denoted as A × B in everyday math, is the set of all ordered pairs, (a, b) (values of type prod A B), where a ∈ A and b ∈ B. In Lean, the set product of sets, A and B, is denoted as set.prod A B. There is no nice infix operator notation for set products at this time. Note carefully: there is a distinction here between product types and product sets. Product types are types, while product sets are sets. And sets are not types in Lean. Rather they're specified as properties. This is potentially confusing. It is made more confusing by the fact that Lean has a way to convert a set into a special type called a subset type: the type of elements in the set, along with proofs of membership. And if you apply prod to two sets, you'll get a subset type! -/ #check set.prod y z -- product set type #reduce set.prod y z -- product set property #check prod y z -- oops, a subset type #check y × z -- oops, same thing #reduce prod y z -- oops, not what we want /- A set product is just a set, which is to say it's defined by a predicate, s. Such a predicate is true for exactly the members of the set. That is, (s x) is a proposition that is true iff x ∈ s. The predicate that defines a product set is a predicate on ordered pairs. It's basically defined like this: -/ def mysetprod (S T : Type) (s : set S) (t : set T) : set (S × T) := { p : S × T | p.1 ∈ s ∧ p.2 ∈ t } /- What this says, then, is that the product set of s (a set of S-type values) and t (a set of T-type values) is the set of pairs, p, each of type (prod S T), and each thus an ordered pair, p = (p.1, p.2), where p.1 ∈ s and p.2 ∈ t. Lean provides this function as set.prod. -/ /- The product set of {1, 2} and {2, 3} is {(1, 2), (1, 3), (2, 2), and (2, 3)} The product set of {2, 3} and {1, 2} is {(2, 1), (2, 2), (3, 1), and (3, 2)} -/ example : (1, 2) ∈ set.prod y z := begin change (λ (p : ℕ × ℕ), (p.fst = 3 ∨ p.fst = 2 ∨ p.fst = 1 ∨ false) ∧ (p.snd = 4 ∨ p.snd = 3 ∨ p.snd = 2 ∨ false)) (1,2), split, right,right,left,apply rfl, right,right,left,apply rfl, end -- COMPLEMENT /- The complement of a set is the set of all values of the set's type that are not in that set. The complement is specified by the "-" sign -/ #check -y #reduce -y #reduce 5 ∈ -y example: 5 ∈ -y := begin change 5 = 3 ∨ 5 = 2 ∨ 5 = 1 ∨ false → false, assume pf_5_in_y, cases pf_5_in_y with pf_5_eq_3 h, have pf_5_ne_3: 5 ≠ 3 := dec_trivial, contradiction, cases h with pf_5_eq_2 h, have pf_5_ne_2: 5 ≠ 2 := dec_trivial, contradiction, cases h with pf_5_eq_1 h, have pf_5_ne_1: 5 ≠ 1 := dec_trivial, contradiction, assumption end -- INSERTION /- We can define an operation that we can think of as "inserting" an element into a set: as a function that takes an element and a set and returns the set containing that element along with the elements of the original set. Unlike in Python or Java, there's no change to a data structure in this case. In pure functional languages, such as Lean, there is no concept of a memory or of "mutable" objects. Rather, everything is defined by functions, here one that takes a set and a value and constructs a new set value just like the old one but with the new element included as well. -/ def myInsert { T : Type } (a : T) (s : set T) : set T := {b | b = a ∨ b ∈ s} /- The predicate for the set resulting from "inserting 5 into { 1, 2, 3, 5 }" admits that 5 is also a member of the result set. -/ #reduce myInsert 5 { 1, 2, 3, 4 } -- The Lean math library defines "insert" #reduce insert 5 { 1, 2, 3, 4 } -- MORE EXAMPLES /- Several of these examples are adapted from Jeremy Avigad's book, Logic and Proof. Prof. Avigad (CMU) is one of the main contributors to the development of Lean, and he leads the development of its mathematical libraries, including the one you're now using for sets, in particular. -/ /- A is a subset of A ∪ B -/ example : ∀ T : Type, ∀ s t: set T, s ⊆ s ∪ t := begin assume T s t x, assume h : x ∈ s, show x ∈ s ∪ t, change s x ∨ t x, change s x at h, from or.inl h end /- The empty set, ∅, is a subset of any set. -/ example : ∀ T : Type, ∀ s: set T, ∅ ⊆ s := begin assume T s x, assume h : x ∈ (∅ : set T), have f: false := h, contradiction, end /- Subset is a transitive relation on sets -/ example : ∀ T : Type, ∀ A B C: set T, A ⊆ B → B ⊆ C → A ⊆ C := begin assume T s t u, assume st tu, intro, intro, have z := st a_1, exact (tu z), end variable α: Type variable sa: set α variable sb: set α variable ea: α #reduce ea ∈ sa #reduce ea ∈ sa ∩ sb /- If an object is in both sets A and B then it is in their intersection. -/ example : ∀ T : Type, forall A B : set T, ∀ x, x ∈ A → x ∈ B → x ∈ A ∩ B := begin assume T A B x, assume hA : x ∈ A, assume hB : x ∈ B, change x ∈ A ∧ x ∈ B, show x ∈ A ∧ x ∈ B, from and.intro hA hB, end /- If an object is in set A or is in set B then it is in their union. -/ example : ∀ T : Type, forall A B : set T, ∀ x, x ∈ A ∨ x ∈ B → x ∈ A ∪ B := begin assume T A B x, intro dis, change x ∈ A ∨ x ∈ B, show x ∈ A ∨ x ∈ B, by assumption, end /- A minus B is a subset of A -/ example : A \ B ⊆ A := begin assume x, assume mem : x ∈ A \ B, cases mem, from mem_left, end /- A minus B is contained in the complement of B -/ example : A \ B ⊆ -B := begin assume x, assume mem : x ∈ A \ B, change x ∈ A ∧ ¬ x ∈ B at mem, change x ∉ B, exact mem.right, end /- A \ B is equal to the intersection of A with the complement of B. -/ example : A \ B = A ∩ -B := begin apply ext, intro, split, intro h, exact h, intro h, exact h, end end sets
52d3bd4d0d5f2a95fdb1954baa4e9f2805e79555
46125763b4dbf50619e8846a1371029346f4c3db
/src/tactic/tfae.lean
80e7d619bc4563458be84dfbe1dfdea5bcadc1c9
[ "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,086
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Reid Barton, Simon Hudon "The Following Are Equivalent" (tfae) : Tactic for proving the equivalence of a set of proposition using various implications between them. -/ import tactic.interactive data.list.basic import tactic.scc open expr tactic lean lean.parser namespace tactic open interactive interactive.types expr export list (tfae) namespace tfae @[derive has_reflect, derive inhabited] inductive arrow : Type | right : arrow | left_right : arrow | left : arrow meta def mk_implication : Π (re : arrow) (e₁ e₂ : expr), pexpr | arrow.right e₁ e₂ := ``(%%e₁ → %%e₂) | arrow.left_right e₁ e₂ := ``(%%e₁ ↔ %%e₂) | arrow.left e₁ e₂ := ``(%%e₂ → %%e₁) meta def mk_name : Π (re : arrow) (i₁ i₂ : nat), name | arrow.right i₁ i₂ := ("tfae_" ++ to_string i₁ ++ "_to_" ++ to_string i₂ : string) | arrow.left_right i₁ i₂ := ("tfae_" ++ to_string i₁ ++ "_iff_" ++ to_string i₂ : string) | arrow.left i₁ i₂ := ("tfae_" ++ to_string i₂ ++ "_to_" ++ to_string i₁ : string) end tfae namespace interactive open tactic.tfae list meta def parse_list : expr → option (list expr) | `([]) := pure [] | `(%%e :: %%es) := (::) e <$> parse_list es | _ := none /-- In a goal of the form `tfae [a₀, a₁, a₂]`, `tfae_have : i → j` creates the assertion `aᵢ → aⱼ`. The other possible notations are `tfae_have : i ← j` and `tfae_have : i ↔ j`. The user can also provide a label for the assertion, as with `have`: `tfae_have h : i ↔ j`. -/ meta def tfae_have (h : parse $ optional ident <* tk ":") (i₁ : parse (with_desc "i" small_nat)) (re : parse (((tk "→" <|> tk "->") *> return arrow.right) <|> ((tk "↔" <|> tk "<->") *> return arrow.left_right) <|> ((tk "←" <|> tk "<-") *> return arrow.left))) (i₂ : parse (with_desc "j" small_nat)) (discharger : tactic unit := tactic.solve_by_elim) : tactic unit := do `(tfae %%l) <- target, l ← parse_list l, e₁ ← list.nth l (i₁ - 1) <|> fail format!"index {i₁} is not between 1 and {l.length}", e₂ ← list.nth l (i₂ - 1) <|> fail format!"index {i₂} is not between 1 and {l.length}", type ← to_expr (tfae.mk_implication re e₁ e₂), let h := h.get_or_else (mk_name re i₁ i₂), tactic.assert h type, return () /-- Finds all implications and equivalences in the context to prove a goal of the form `tfae [...]`. -/ meta def tfae_finish : tactic unit := applyc ``tfae_nil <|> closure.with_new_closure (λ cl, do impl_graph.mk_scc cl, `(tfae %%l) ← target, l ← parse_list l, (_,r,_) ← cl.root l.head, refine ``(tfae_of_forall %%r _ _), thm ← mk_const ``forall_mem_cons, l.mmap' (λ e, do rewrite_target thm, split, (_,r',p) ← cl.root e, tactic.exact p ), applyc ``forall_mem_nil, pure ()) end interactive end tactic
b075ef3e9e3fdcff561ad667312c9d4076c7dfdb
94e33a31faa76775069b071adea97e86e218a8ee
/src/data/finsupp/basic.lean
e4b7bfbff3da9b3b95112840c48992b3da8de1ab
[ "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
116,999
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Scott Morrison -/ import algebra.hom.group_action import algebra.indicator_function import data.finset.preimage /-! # Type of functions with finite support For any type `α` and a type `M` with zero, we define the type `finsupp α M` (notation: `α →₀ M`) of finitely supported functions from `α` to `M`, i.e. the functions which are zero everywhere on `α` except on a finite set. Functions with finite support are used (at least) in the following parts of the library: * `monoid_algebra R M` and `add_monoid_algebra R M` are defined as `M →₀ R`; * polynomials and multivariate polynomials are defined as `add_monoid_algebra`s, hence they use `finsupp` under the hood; * the linear combination of a family of vectors `v i` with coefficients `f i` (as used, e.g., to define linearly independent family `linear_independent`) is defined as a map `finsupp.total : (ι → M) → (ι →₀ R) →ₗ[R] M`. Some other constructions are naturally equivalent to `α →₀ M` with some `α` and `M` but are defined in a different way in the library: * `multiset α ≃+ α →₀ ℕ`; * `free_abelian_group α ≃+ α →₀ ℤ`. Most of the theory assumes that the range is a commutative additive monoid. This gives us the big sum operator as a powerful way to construct `finsupp` elements. Many constructions based on `α →₀ M` use `semireducible` type tags to avoid reusing unwanted type instances. E.g., `monoid_algebra`, `add_monoid_algebra`, and types based on these two have non-pointwise multiplication. ## Main declarations * `finsupp`: The type of finitely supported functions from `α` to `β`. * `finsupp.single`: The `finsupp` which is nonzero in exactly one point. * `finsupp.update`: Changes one value of a `finsupp`. * `finsupp.erase`: Replaces one value of a `finsupp` by `0`. * `finsupp.on_finset`: The restriction of a function to a `finset` as a `finsupp`. * `finsupp.map_range`: Composition of a `zero_hom` with a `finsupp`. * `finsupp.emb_domain`: Maps the domain of a `finsupp` by an embedding. * `finsupp.map_domain`: Maps the domain of a `finsupp` by a function and by summing. * `finsupp.comap_domain`: Postcomposition of a `finsupp` with a function injective on the preimage of its support. * `finsupp.zip_with`: Postcomposition of two `finsupp`s with a function `f` such that `f 0 0 = 0`. * `finsupp.sum`: Sum of the values of a `finsupp`. * `finsupp.prod`: Product of the nonzero values of a `finsupp`. ## Notations This file adds `α →₀ M` as a global notation for `finsupp α M`. We also use the following convention for `Type*` variables in this file * `α`, `β`, `γ`: types with no additional structure that appear as the first argument to `finsupp` somewhere in the statement; * `ι` : an auxiliary index type; * `M`, `M'`, `N`, `P`: types with `has_zero` or `(add_)(comm_)monoid` structure; `M` is also used for a (semi)module over a (semi)ring. * `G`, `H`: groups (commutative or not, multiplicative or additive); * `R`, `S`: (semi)rings. ## Implementation notes This file is a `noncomputable theory` and uses classical logic throughout. ## TODO * This file is currently ~2.7K lines long, so it should be splitted into smaller chunks. One option would be to move all the sum and product stuff to `algebra.big_operators.finsupp` and move the definitions that depend on it to new files under `data.finsupp.`. * Expand the list of definitions and important lemmas to the module docstring. -/ noncomputable theory open finset function open_locale classical big_operators variables {α β γ ι M M' N P G H R S : Type*} /-- `finsupp α M`, denoted `α →₀ M`, is the type of functions `f : α → M` such that `f x = 0` for all but finitely many `x`. -/ structure finsupp (α : Type*) (M : Type*) [has_zero M] := (support : finset α) (to_fun : α → M) (mem_support_to_fun : ∀a, a ∈ support ↔ to_fun a ≠ 0) infixr ` →₀ `:25 := finsupp namespace finsupp /-! ### Basic declarations about `finsupp` -/ section basic variable [has_zero M] instance fun_like : fun_like (α →₀ M) α (λ _, M) := ⟨to_fun, begin rintro ⟨s, f, hf⟩ ⟨t, g, hg⟩ (rfl : f = g), congr', ext a, exact (hf _).trans (hg _).symm, end⟩ /-- Helper instance for when there are too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (α →₀ M) (λ _, α → M) := fun_like.has_coe_to_fun @[ext] lemma ext {f g : α →₀ M} (h : ∀ a, f a = g a) : f = g := fun_like.ext _ _ h /-- Deprecated. Use `fun_like.ext_iff` instead. -/ lemma ext_iff {f g : α →₀ M} : f = g ↔ ∀ a, f a = g a := fun_like.ext_iff /-- Deprecated. Use `fun_like.coe_fn_eq` instead. -/ lemma coe_fn_inj {f g : α →₀ M} : (f : α → M) = g ↔ f = g := fun_like.coe_fn_eq /-- Deprecated. Use `fun_like.coe_injective` instead. -/ lemma coe_fn_injective : @function.injective (α →₀ M) (α → M) coe_fn := fun_like.coe_injective /-- Deprecated. Use `fun_like.congr_fun` instead. -/ lemma congr_fun {f g : α →₀ M} (h : f = g) (a : α) : f a = g a := fun_like.congr_fun h _ @[simp] lemma coe_mk (f : α → M) (s : finset α) (h : ∀ a, a ∈ s ↔ f a ≠ 0) : ⇑(⟨s, f, h⟩ : α →₀ M) = f := rfl instance : has_zero (α →₀ M) := ⟨⟨∅, 0, λ _, ⟨false.elim, λ H, H rfl⟩⟩⟩ @[simp] lemma coe_zero : ⇑(0 : α →₀ M) = 0 := rfl lemma zero_apply {a : α} : (0 : α →₀ M) a = 0 := rfl @[simp] lemma support_zero : (0 : α →₀ M).support = ∅ := rfl instance : inhabited (α →₀ M) := ⟨0⟩ @[simp] lemma mem_support_iff {f : α →₀ M} : ∀{a:α}, a ∈ f.support ↔ f a ≠ 0 := f.mem_support_to_fun @[simp, norm_cast] lemma fun_support_eq (f : α →₀ M) : function.support f = f.support := set.ext $ λ x, mem_support_iff.symm lemma not_mem_support_iff {f : α →₀ M} {a} : a ∉ f.support ↔ f a = 0 := not_iff_comm.1 mem_support_iff.symm @[simp, norm_cast] lemma coe_eq_zero {f : α →₀ M} : (f : α → M) = 0 ↔ f = 0 := by rw [← coe_zero, coe_fn_inj] lemma ext_iff' {f g : α →₀ M} : f = g ↔ f.support = g.support ∧ ∀ x ∈ f.support, f x = g x := ⟨λ h, h ▸ ⟨rfl, λ _ _, rfl⟩, λ ⟨h₁, h₂⟩, ext $ λ a, if h : a ∈ f.support then h₂ a h else have hf : f a = 0, from not_mem_support_iff.1 h, have hg : g a = 0, by rwa [h₁, not_mem_support_iff] at h, by rw [hf, hg]⟩ @[simp] lemma support_eq_empty {f : α →₀ M} : f.support = ∅ ↔ f = 0 := by exact_mod_cast @function.support_eq_empty_iff _ _ _ f lemma support_nonempty_iff {f : α →₀ M} : f.support.nonempty ↔ f ≠ 0 := by simp only [finsupp.support_eq_empty, finset.nonempty_iff_ne_empty, ne.def] lemma nonzero_iff_exists {f : α →₀ M} : f ≠ 0 ↔ ∃ a : α, f a ≠ 0 := by simp [← finsupp.support_eq_empty, finset.eq_empty_iff_forall_not_mem] lemma card_support_eq_zero {f : α →₀ M} : card f.support = 0 ↔ f = 0 := by simp instance [decidable_eq α] [decidable_eq M] : decidable_eq (α →₀ M) := assume f g, decidable_of_iff (f.support = g.support ∧ (∀a∈f.support, f a = g a)) ext_iff'.symm lemma finite_support (f : α →₀ M) : set.finite (function.support f) := f.fun_support_eq.symm ▸ f.support.finite_to_set lemma support_subset_iff {s : set α} {f : α →₀ M} : ↑f.support ⊆ s ↔ (∀a∉s, f a = 0) := by simp only [set.subset_def, mem_coe, mem_support_iff]; exact forall_congr (assume a, not_imp_comm) /-- Given `fintype α`, `equiv_fun_on_fintype` is the `equiv` between `α →₀ β` and `α → β`. (All functions on a finite type are finitely supported.) -/ @[simps] def equiv_fun_on_fintype [fintype α] : (α →₀ M) ≃ (α → M) := ⟨λf a, f a, λf, mk (finset.univ.filter $ λa, f a ≠ 0) f (by simp only [true_and, finset.mem_univ, iff_self, finset.mem_filter, finset.filter_congr_decidable, forall_true_iff]), begin intro f, ext a, refl end, begin intro f, ext a, refl end⟩ @[simp] lemma equiv_fun_on_fintype_symm_coe {α} [fintype α] (f : α →₀ M) : equiv_fun_on_fintype.symm f = f := by { ext, simp [equiv_fun_on_fintype], } /-- If `α` has a unique term, then the type of finitely supported functions `α →₀ β` is equivalent to `β`. -/ @[simps] noncomputable def _root_.equiv.finsupp_unique {ι : Type*} [unique ι] : (ι →₀ M) ≃ M := finsupp.equiv_fun_on_fintype.trans (equiv.fun_unique ι M) end basic /-! ### Declarations about `single` -/ section single variables [has_zero M] {a a' : α} {b : M} /-- `single a b` is the finitely supported function which has value `b` at `a` and zero otherwise. -/ def single (a : α) (b : M) : α →₀ M := ⟨if b = 0 then ∅ else {a}, λ a', if a = a' then b else 0, λ a', begin by_cases hb : b = 0; by_cases a = a'; simp only [hb, h, if_pos, if_false, mem_singleton], { exact ⟨false.elim, λ H, H rfl⟩ }, { exact ⟨false.elim, λ H, H rfl⟩ }, { exact ⟨λ _, hb, λ _, rfl⟩ }, { exact ⟨λ H _, h H.symm, λ H, (H rfl).elim⟩ } end⟩ lemma single_apply [decidable (a = a')] : single a b a' = if a = a' then b else 0 := by convert rfl lemma single_eq_indicator : ⇑(single a b) = set.indicator {a} (λ _, b) := by { ext, simp [single_apply, set.indicator, @eq_comm _ a] } @[simp] lemma single_eq_same : (single a b : α →₀ M) a = b := if_pos rfl @[simp] lemma single_eq_of_ne (h : a ≠ a') : (single a b : α →₀ M) a' = 0 := if_neg h lemma single_eq_update [decidable_eq α] (a : α) (b : M) : ⇑(single a b) = function.update 0 a b := by rw [single_eq_indicator, ← set.piecewise_eq_indicator, set.piecewise_singleton] lemma single_eq_pi_single [decidable_eq α] (a : α) (b : M) : ⇑(single a b) = pi.single a b := single_eq_update a b @[simp] lemma single_zero (a : α) : (single a 0 : α →₀ M) = 0 := coe_fn_injective $ by simpa only [single_eq_update, coe_zero] using function.update_eq_self a (0 : α → M) lemma single_of_single_apply (a a' : α) (b : M) : single a ((single a' b) a) = single a' (single a' b) a := begin rw [single_apply, single_apply], ext, split_ifs, { rw h, }, { rw [zero_apply, single_apply, if_t_t], }, end lemma support_single_ne_zero (a : α) (hb : b ≠ 0) : (single a b).support = {a} := if_neg hb lemma support_single_subset : (single a b).support ⊆ {a} := show ite _ _ _ ⊆ _, by split_ifs; [exact empty_subset _, exact subset.refl _] lemma single_apply_mem (x) : single a b x ∈ ({0, b} : set M) := by rcases em (a = x) with (rfl|hx); [simp, simp [single_eq_of_ne hx]] lemma range_single_subset : set.range (single a b) ⊆ {0, b} := set.range_subset_iff.2 single_apply_mem /-- `finsupp.single a b` is injective in `b`. For the statement that it is injective in `a`, see `finsupp.single_left_injective` -/ lemma single_injective (a : α) : function.injective (single a : M → α →₀ M) := assume b₁ b₂ eq, have (single a b₁ : α →₀ M) a = (single a b₂ : α →₀ M) a, by rw eq, by rwa [single_eq_same, single_eq_same] at this lemma single_apply_eq_zero {a x : α} {b : M} : single a b x = 0 ↔ (x = a → b = 0) := by simp [single_eq_indicator] lemma single_apply_ne_zero {a x : α} {b : M} : single a b x ≠ 0 ↔ (x = a ∧ b ≠ 0) := by simp [single_apply_eq_zero] lemma mem_support_single (a a' : α) (b : M) : a ∈ (single a' b).support ↔ a = a' ∧ b ≠ 0 := by simp [single_apply_eq_zero, not_or_distrib] lemma eq_single_iff {f : α →₀ M} {a b} : f = single a b ↔ f.support ⊆ {a} ∧ f a = b := begin refine ⟨λ h, h.symm ▸ ⟨support_single_subset, single_eq_same⟩, _⟩, rintro ⟨h, rfl⟩, ext x, by_cases hx : a = x; simp only [hx, single_eq_same, single_eq_of_ne, ne.def, not_false_iff], exact not_mem_support_iff.1 (mt (λ hx, (mem_singleton.1 (h hx)).symm) hx) end lemma single_eq_single_iff (a₁ a₂ : α) (b₁ b₂ : M) : single a₁ b₁ = single a₂ b₂ ↔ ((a₁ = a₂ ∧ b₁ = b₂) ∨ (b₁ = 0 ∧ b₂ = 0)) := begin split, { assume eq, by_cases a₁ = a₂, { refine or.inl ⟨h, _⟩, rwa [h, (single_injective a₂).eq_iff] at eq }, { rw [ext_iff] at eq, have h₁ := eq a₁, have h₂ := eq a₂, simp only [single_eq_same, single_eq_of_ne h, single_eq_of_ne (ne.symm h)] at h₁ h₂, exact or.inr ⟨h₁, h₂.symm⟩ } }, { rintros (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩), { refl }, { rw [single_zero, single_zero] } } end /-- `finsupp.single a b` is injective in `a`. For the statement that it is injective in `b`, see `finsupp.single_injective` -/ lemma single_left_injective (h : b ≠ 0) : function.injective (λ a : α, single a b) := λ a a' H, (((single_eq_single_iff _ _ _ _).mp H).resolve_right $ λ hb, h hb.1).left lemma single_left_inj (h : b ≠ 0) : single a b = single a' b ↔ a = a' := (single_left_injective h).eq_iff lemma support_single_ne_bot (i : α) (h : b ≠ 0) : (single i b).support ≠ ⊥ := by simpa only [support_single_ne_zero _ h] using singleton_ne_empty _ lemma support_single_disjoint [decidable_eq α] {b' : M} (hb : b ≠ 0) (hb' : b' ≠ 0) {i j : α} : disjoint (single i b).support (single j b').support ↔ i ≠ j := by rw [support_single_ne_zero _ hb, support_single_ne_zero _ hb', disjoint_singleton] @[simp] lemma single_eq_zero : single a b = 0 ↔ b = 0 := by simp [ext_iff, single_eq_indicator] lemma single_swap (a₁ a₂ : α) (b : M) : single a₁ b a₂ = single a₂ b a₁ := by simp only [single_apply]; ac_refl instance [nonempty α] [nontrivial M] : nontrivial (α →₀ M) := begin inhabit α, rcases exists_ne (0 : M) with ⟨x, hx⟩, exact nontrivial_of_ne (single default x) 0 (mt single_eq_zero.1 hx) end lemma unique_single [unique α] (x : α →₀ M) : x = single default (x default) := ext $ unique.forall_iff.2 single_eq_same.symm @[ext] lemma unique_ext [unique α] {f g : α →₀ M} (h : f default = g default) : f = g := ext $ λ a, by rwa [unique.eq_default a] lemma unique_ext_iff [unique α] {f g : α →₀ M} : f = g ↔ f default = g default := ⟨λ h, h ▸ rfl, unique_ext⟩ @[simp] lemma unique_single_eq_iff [unique α] {b' : M} : single a b = single a' b' ↔ b = b' := by rw [unique_ext_iff, unique.eq_default a, unique.eq_default a', single_eq_same, single_eq_same] lemma support_eq_singleton {f : α →₀ M} {a : α} : f.support = {a} ↔ f a ≠ 0 ∧ f = single a (f a) := ⟨λ h, ⟨mem_support_iff.1 $ h.symm ▸ finset.mem_singleton_self a, eq_single_iff.2 ⟨subset_of_eq h, rfl⟩⟩, λ h, h.2.symm ▸ support_single_ne_zero _ h.1⟩ lemma support_eq_singleton' {f : α →₀ M} {a : α} : f.support = {a} ↔ ∃ b ≠ 0, f = single a b := ⟨λ h, let h := support_eq_singleton.1 h in ⟨_, h.1, h.2⟩, λ ⟨b, hb, hf⟩, hf.symm ▸ support_single_ne_zero _ hb⟩ lemma card_support_eq_one {f : α →₀ M} : card f.support = 1 ↔ ∃ a, f a ≠ 0 ∧ f = single a (f a) := by simp only [card_eq_one, support_eq_singleton] lemma card_support_eq_one' {f : α →₀ M} : card f.support = 1 ↔ ∃ a (b ≠ 0), f = single a b := by simp only [card_eq_one, support_eq_singleton'] lemma support_subset_singleton {f : α →₀ M} {a : α} : f.support ⊆ {a} ↔ f = single a (f a) := ⟨λ h, eq_single_iff.mpr ⟨h, rfl⟩, λ h, (eq_single_iff.mp h).left⟩ lemma support_subset_singleton' {f : α →₀ M} {a : α} : f.support ⊆ {a} ↔ ∃ b, f = single a b := ⟨λ h, ⟨f a, support_subset_singleton.mp h⟩, λ ⟨b, hb⟩, by rw [hb, support_subset_singleton, single_eq_same]⟩ lemma card_support_le_one [nonempty α] {f : α →₀ M} : card f.support ≤ 1 ↔ ∃ a, f = single a (f a) := by simp only [card_le_one_iff_subset_singleton, support_subset_singleton] lemma card_support_le_one' [nonempty α] {f : α →₀ M} : card f.support ≤ 1 ↔ ∃ a b, f = single a b := by simp only [card_le_one_iff_subset_singleton, support_subset_singleton'] @[simp] lemma equiv_fun_on_fintype_single [decidable_eq α] [fintype α] (x : α) (m : M) : (@finsupp.equiv_fun_on_fintype α M _ _) (finsupp.single x m) = pi.single x m := by { ext, simp [finsupp.single_eq_pi_single, finsupp.equiv_fun_on_fintype], } @[simp] lemma equiv_fun_on_fintype_symm_single [decidable_eq α] [fintype α] (x : α) (m : M) : (@finsupp.equiv_fun_on_fintype α M _ _).symm (pi.single x m) = finsupp.single x m := by { ext, simp [finsupp.single_eq_pi_single, finsupp.equiv_fun_on_fintype], } end single /-! ### Declarations about `update` -/ section update variables [has_zero M] (f : α →₀ M) (a : α) (b : M) (i : α) /-- Replace the value of a `α →₀ M` at a given point `a : α` by a given value `b : M`. If `b = 0`, this amounts to removing `a` from the `finsupp.support`. Otherwise, if `a` was not in the `finsupp.support`, it is added to it. This is the finitely-supported version of `function.update`. -/ def update : α →₀ M := ⟨if b = 0 then f.support.erase a else insert a f.support, function.update f a b, λ i, begin simp only [function.update_apply, ne.def], split_ifs with hb ha ha hb; simp [ha, hb] end⟩ @[simp] lemma coe_update [decidable_eq α] : (f.update a b : α → M) = function.update f a b := by convert rfl @[simp] lemma update_self : f.update a (f a) = f := by { ext, simp } lemma support_update [decidable_eq α] : support (f.update a b) = if b = 0 then f.support.erase a else insert a f.support := by convert rfl @[simp] lemma support_update_zero [decidable_eq α] : support (f.update a 0) = f.support.erase a := by convert if_pos rfl variables {b} lemma support_update_ne_zero [decidable_eq α] (h : b ≠ 0) : support (f.update a b) = insert a f.support := by convert if_neg h end update /-! ### Declarations about `on_finset` -/ section on_finset variables [has_zero M] /-- `on_finset s f hf` is the finsupp function representing `f` restricted to the finset `s`. The function needs to be `0` outside of `s`. Use this when the set needs to be filtered anyways, otherwise a better set representation is often available. -/ def on_finset (s : finset α) (f : α → M) (hf : ∀a, f a ≠ 0 → a ∈ s) : α →₀ M := ⟨s.filter (λa, f a ≠ 0), f, by simpa⟩ @[simp] lemma on_finset_apply {s : finset α} {f : α → M} {hf a} : (on_finset s f hf : α →₀ M) a = f a := rfl @[simp] lemma support_on_finset_subset {s : finset α} {f : α → M} {hf} : (on_finset s f hf).support ⊆ s := filter_subset _ _ @[simp] lemma mem_support_on_finset {s : finset α} {f : α → M} (hf : ∀ (a : α), f a ≠ 0 → a ∈ s) {a : α} : a ∈ (finsupp.on_finset s f hf).support ↔ f a ≠ 0 := by rw [finsupp.mem_support_iff, finsupp.on_finset_apply] lemma support_on_finset {s : finset α} {f : α → M} (hf : ∀ (a : α), f a ≠ 0 → a ∈ s) : (finsupp.on_finset s f hf).support = s.filter (λ a, f a ≠ 0) := rfl end on_finset section of_support_finite variables [has_zero M] /-- The natural `finsupp` induced by the function `f` given that it has finite support. -/ noncomputable def of_support_finite (f : α → M) (hf : (function.support f).finite) : α →₀ M := { support := hf.to_finset, to_fun := f, mem_support_to_fun := λ _, hf.mem_to_finset } lemma of_support_finite_coe {f : α → M} {hf : (function.support f).finite} : (of_support_finite f hf : α → M) = f := rfl instance : can_lift (α → M) (α →₀ M) := { coe := coe_fn, cond := λ f, (function.support f).finite, prf := λ f hf, ⟨of_support_finite f hf, rfl⟩ } end of_support_finite /-! ### Declarations about `map_range` -/ section map_range variables [has_zero M] [has_zero N] [has_zero P] /-- The composition of `f : M → N` and `g : α →₀ M` is `map_range f hf g : α →₀ N`, well-defined when `f 0 = 0`. This preserves the structure on `f`, and exists in various bundled forms for when `f` is itself bundled: * `finsupp.map_range.equiv` * `finsupp.map_range.zero_hom` * `finsupp.map_range.add_monoid_hom` * `finsupp.map_range.add_equiv` * `finsupp.map_range.linear_map` * `finsupp.map_range.linear_equiv` -/ def map_range (f : M → N) (hf : f 0 = 0) (g : α →₀ M) : α →₀ N := on_finset g.support (f ∘ g) $ assume a, by rw [mem_support_iff, not_imp_not]; exact λ H, (congr_arg f H).trans hf @[simp] lemma map_range_apply {f : M → N} {hf : f 0 = 0} {g : α →₀ M} {a : α} : map_range f hf g a = f (g a) := rfl @[simp] lemma map_range_zero {f : M → N} {hf : f 0 = 0} : map_range f hf (0 : α →₀ M) = 0 := ext $ λ a, by simp only [hf, zero_apply, map_range_apply] @[simp] lemma map_range_id (g : α →₀ M) : map_range id rfl g = g := ext $ λ _, rfl lemma map_range_comp (f : N → P) (hf : f 0 = 0) (f₂ : M → N) (hf₂ : f₂ 0 = 0) (h : (f ∘ f₂) 0 = 0) (g : α →₀ M) : map_range (f ∘ f₂) h g = map_range f hf (map_range f₂ hf₂ g) := ext $ λ _, rfl lemma support_map_range {f : M → N} {hf : f 0 = 0} {g : α →₀ M} : (map_range f hf g).support ⊆ g.support := support_on_finset_subset @[simp] lemma map_range_single {f : M → N} {hf : f 0 = 0} {a : α} {b : M} : map_range f hf (single a b) = single a (f b) := ext $ λ a', show f (ite _ _ _) = ite _ _ _, by split_ifs; [refl, exact hf] lemma support_map_range_of_injective {e : M → N} (he0 : e 0 = 0) (f : ι →₀ M) (he : function.injective e) : (finsupp.map_range e he0 f).support = f.support := begin ext, simp only [finsupp.mem_support_iff, ne.def, finsupp.map_range_apply], exact he.ne_iff' he0, end end map_range /-! ### Declarations about `emb_domain` -/ section emb_domain variables [has_zero M] [has_zero N] /-- Given `f : α ↪ β` and `v : α →₀ M`, `emb_domain f v : β →₀ M` is the finitely supported function whose value at `f a : β` is `v a`. For a `b : β` outside the range of `f`, it is zero. -/ def emb_domain (f : α ↪ β) (v : α →₀ M) : β →₀ M := begin refine ⟨v.support.map f, λa₂, if h : a₂ ∈ v.support.map f then v (v.support.choose (λa₁, f a₁ = a₂) _) else 0, _⟩, { rcases finset.mem_map.1 h with ⟨a, ha, rfl⟩, exact exists_unique.intro a ⟨ha, rfl⟩ (assume b ⟨_, hb⟩, f.injective hb) }, { assume a₂, split_ifs, { simp only [h, true_iff, ne.def], rw [← not_mem_support_iff, not_not], apply finset.choose_mem }, { simp only [h, ne.def, ne_self_iff_false] } } end @[simp] lemma support_emb_domain (f : α ↪ β) (v : α →₀ M) : (emb_domain f v).support = v.support.map f := rfl @[simp] lemma emb_domain_zero (f : α ↪ β) : (emb_domain f 0 : β →₀ M) = 0 := rfl @[simp] lemma emb_domain_apply (f : α ↪ β) (v : α →₀ M) (a : α) : emb_domain f v (f a) = v a := begin change dite _ _ _ = _, split_ifs; rw [finset.mem_map' f] at h, { refine congr_arg (v : α → M) (f.inj' _), exact finset.choose_property (λa₁, f a₁ = f a) _ _ }, { exact (not_mem_support_iff.1 h).symm } end lemma emb_domain_notin_range (f : α ↪ β) (v : α →₀ M) (a : β) (h : a ∉ set.range f) : emb_domain f v a = 0 := begin refine dif_neg (mt (assume h, _) h), rcases finset.mem_map.1 h with ⟨a, h, rfl⟩, exact set.mem_range_self a end lemma emb_domain_injective (f : α ↪ β) : function.injective (emb_domain f : (α →₀ M) → (β →₀ M)) := λ l₁ l₂ h, ext $ λ a, by simpa only [emb_domain_apply] using ext_iff.1 h (f a) @[simp] lemma emb_domain_inj {f : α ↪ β} {l₁ l₂ : α →₀ M} : emb_domain f l₁ = emb_domain f l₂ ↔ l₁ = l₂ := (emb_domain_injective f).eq_iff @[simp] lemma emb_domain_eq_zero {f : α ↪ β} {l : α →₀ M} : emb_domain f l = 0 ↔ l = 0 := (emb_domain_injective f).eq_iff' $ emb_domain_zero f lemma emb_domain_map_range (f : α ↪ β) (g : M → N) (p : α →₀ M) (hg : g 0 = 0) : emb_domain f (map_range g hg p) = map_range g hg (emb_domain f p) := begin ext a, by_cases a ∈ set.range f, { rcases h with ⟨a', rfl⟩, rw [map_range_apply, emb_domain_apply, emb_domain_apply, map_range_apply] }, { rw [map_range_apply, emb_domain_notin_range, emb_domain_notin_range, ← hg]; assumption } end lemma single_of_emb_domain_single (l : α →₀ M) (f : α ↪ β) (a : β) (b : M) (hb : b ≠ 0) (h : l.emb_domain f = single a b) : ∃ x, l = single x b ∧ f x = a := begin have h_map_support : finset.map f (l.support) = {a}, by rw [←support_emb_domain, h, support_single_ne_zero _ hb]; refl, have ha : a ∈ finset.map f (l.support), by simp only [h_map_support, finset.mem_singleton], rcases finset.mem_map.1 ha with ⟨c, hc₁, hc₂⟩, use c, split, { ext d, rw [← emb_domain_apply f l, h], by_cases h_cases : c = d, { simp only [eq.symm h_cases, hc₂, single_eq_same] }, { rw [single_apply, single_apply, if_neg, if_neg h_cases], by_contra hfd, exact h_cases (f.injective (hc₂.trans hfd)) } }, { exact hc₂ } end @[simp] lemma emb_domain_single (f : α ↪ β) (a : α) (m : M) : emb_domain f (single a m) = single (f a) m := begin ext b, by_cases h : b ∈ set.range f, { rcases h with ⟨a', rfl⟩, simp [single_apply], }, { simp only [emb_domain_notin_range, h, single_apply, not_false_iff], rw if_neg, rintro rfl, simpa using h, }, end end emb_domain /-! ### Declarations about `zip_with` -/ section zip_with variables [has_zero M] [has_zero N] [has_zero P] /-- `zip_with f hf g₁ g₂` is the finitely supported function satisfying `zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a)`, and it is well-defined when `f 0 0 = 0`. -/ def zip_with (f : M → N → P) (hf : f 0 0 = 0) (g₁ : α →₀ M) (g₂ : α →₀ N) : α →₀ P := on_finset (g₁.support ∪ g₂.support) (λa, f (g₁ a) (g₂ a)) $ λ a H, begin simp only [mem_union, mem_support_iff, ne], rw [← not_and_distrib], rintro ⟨h₁, h₂⟩, rw [h₁, h₂] at H, exact H hf end @[simp] lemma zip_with_apply {f : M → N → P} {hf : f 0 0 = 0} {g₁ : α →₀ M} {g₂ : α →₀ N} {a : α} : zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a) := rfl lemma support_zip_with [D : decidable_eq α] {f : M → N → P} {hf : f 0 0 = 0} {g₁ : α →₀ M} {g₂ : α →₀ N} : (zip_with f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support := by rw subsingleton.elim D; exact support_on_finset_subset end zip_with /-! ### Declarations about `erase` -/ section erase variables [has_zero M] /-- `erase a f` is the finitely supported function equal to `f` except at `a` where it is equal to `0`. -/ def erase (a : α) (f : α →₀ M) : α →₀ M := ⟨f.support.erase a, (λa', if a' = a then 0 else f a'), assume a', by rw [mem_erase, mem_support_iff]; split_ifs; [exact ⟨λ H _, H.1 h, λ H, (H rfl).elim⟩, exact and_iff_right h]⟩ @[simp] lemma support_erase [decidable_eq α] {a : α} {f : α →₀ M} : (f.erase a).support = f.support.erase a := by convert rfl @[simp] lemma erase_same {a : α} {f : α →₀ M} : (f.erase a) a = 0 := if_pos rfl @[simp] lemma erase_ne {a a' : α} {f : α →₀ M} (h : a' ≠ a) : (f.erase a) a' = f a' := if_neg h @[simp] lemma erase_single {a : α} {b : M} : (erase a (single a b)) = 0 := begin ext s, by_cases hs : s = a, { rw [hs, erase_same], refl }, { rw [erase_ne hs], exact single_eq_of_ne (ne.symm hs) } end lemma erase_single_ne {a a' : α} {b : M} (h : a ≠ a') : (erase a (single a' b)) = single a' b := begin ext s, by_cases hs : s = a, { rw [hs, erase_same, single_eq_of_ne (h.symm)] }, { rw [erase_ne hs] } end @[simp] lemma erase_of_not_mem_support {f : α →₀ M} {a} (haf : a ∉ f.support) : erase a f = f := begin ext b, by_cases hab : b = a, { rwa [hab, erase_same, eq_comm, ←not_mem_support_iff] }, { rw erase_ne hab } end @[simp] lemma erase_zero (a : α) : erase a (0 : α →₀ M) = 0 := by rw [← support_eq_empty, support_erase, support_zero, erase_empty] end erase /-! ### Declarations about `graph` -/ section graph variable [has_zero M] /-- The graph of a finitely supported function over its support, i.e. the finset of input and output pairs with non-zero outputs. -/ def graph (f : α →₀ M) : finset (α × M) := f.support.map ⟨λ a, prod.mk a (f a), λ x y h, (prod.mk.inj h).1⟩ lemma mk_mem_graph_iff {a : α} {m : M} {f : α →₀ M} : (a, m) ∈ f.graph ↔ f a = m ∧ m ≠ 0 := begin simp_rw [graph, mem_map, mem_support_iff], split, { rintro ⟨b, ha, rfl, -⟩, exact ⟨rfl, ha⟩ }, { rintro ⟨rfl, ha⟩, exact ⟨a, ha, rfl⟩ } end @[simp] lemma mem_graph_iff {c : α × M} {f : α →₀ M} : c ∈ f.graph ↔ f c.1 = c.2 ∧ c.2 ≠ 0 := by { cases c, exact mk_mem_graph_iff } lemma mk_mem_graph (f : α →₀ M) {a : α} (ha : a ∈ f.support) : (a, f a) ∈ f.graph := mk_mem_graph_iff.2 ⟨rfl, mem_support_iff.1 ha⟩ lemma apply_eq_of_mem_graph {a : α} {m : M} {f : α →₀ M} (h : (a, m) ∈ f.graph) : f a = m := (mem_graph_iff.1 h).1 @[simp] lemma not_mem_graph_snd_zero (a : α) (f : α →₀ M) : (a, (0 : M)) ∉ f.graph := λ h, (mem_graph_iff.1 h).2.irrefl @[simp] lemma image_fst_graph (f : α →₀ M) : f.graph.image prod.fst = f.support := by simp only [graph, map_eq_image, image_image, embedding.coe_fn_mk, (∘), image_id'] lemma graph_injective (α M) [has_zero M] : injective (@graph α M _) := begin intros f g h, have hsup : f.support = g.support, by rw [← image_fst_graph, h, image_fst_graph], refine ext_iff'.2 ⟨hsup, λ x hx, apply_eq_of_mem_graph $ h.symm ▸ _⟩, exact mk_mem_graph _ (hsup ▸ hx) end @[simp] lemma graph_inj {f g : α →₀ M} : f.graph = g.graph ↔ f = g := (graph_injective α M).eq_iff @[simp] lemma graph_zero : graph (0 : α →₀ M) = ∅ := by simp [graph] @[simp] lemma graph_eq_empty {f : α →₀ M} : f.graph = ∅ ↔ f = 0 := (graph_injective α M).eq_iff' graph_zero end graph /-! ### Declarations about `sum` and `prod` In most of this section, the domain `β` is assumed to be an `add_monoid`. -/ section sum_prod /-- `prod f g` is the product of `g a (f a)` over the support of `f`. -/ @[to_additive "`sum f g` is the sum of `g a (f a)` over the support of `f`. "] def prod [has_zero M] [comm_monoid N] (f : α →₀ M) (g : α → M → N) : N := ∏ a in f.support, g a (f a) variables [has_zero M] [has_zero M'] [comm_monoid N] @[to_additive] lemma prod_of_support_subset (f : α →₀ M) {s : finset α} (hs : f.support ⊆ s) (g : α → M → N) (h : ∀ i ∈ s, g i 0 = 1) : f.prod g = ∏ x in s, g x (f x) := finset.prod_subset hs $ λ x hxs hx, h x hxs ▸ congr_arg (g x) $ not_mem_support_iff.1 hx @[to_additive] lemma prod_fintype [fintype α] (f : α →₀ M) (g : α → M → N) (h : ∀ i, g i 0 = 1) : f.prod g = ∏ i, g i (f i) := f.prod_of_support_subset (subset_univ _) g (λ x _, h x) @[simp, to_additive] lemma prod_single_index {a : α} {b : M} {h : α → M → N} (h_zero : h a 0 = 1) : (single a b).prod h = h a b := calc (single a b).prod h = ∏ x in {a}, h x (single a b x) : prod_of_support_subset _ support_single_subset h $ λ x hx, (mem_singleton.1 hx).symm ▸ h_zero ... = h a b : by simp @[to_additive] lemma prod_map_range_index {f : M → M'} {hf : f 0 = 0} {g : α →₀ M} {h : α → M' → N} (h0 : ∀a, h a 0 = 1) : (map_range f hf g).prod h = g.prod (λa b, h a (f b)) := finset.prod_subset support_map_range $ λ _ _ H, by rw [not_mem_support_iff.1 H, h0] @[simp, to_additive] lemma prod_zero_index {h : α → M → N} : (0 : α →₀ M).prod h = 1 := rfl @[to_additive] lemma prod_comm (f : α →₀ M) (g : β →₀ M') (h : α → M → β → M' → N) : f.prod (λ x v, g.prod (λ x' v', h x v x' v')) = g.prod (λ x' v', f.prod (λ x v, h x v x' v')) := finset.prod_comm @[simp, to_additive] lemma prod_ite_eq [decidable_eq α] (f : α →₀ M) (a : α) (b : α → M → N) : f.prod (λ x v, ite (a = x) (b x v) 1) = ite (a ∈ f.support) (b a (f a)) 1 := by { dsimp [finsupp.prod], rw f.support.prod_ite_eq, } @[simp] lemma sum_ite_self_eq [decidable_eq α] {N : Type*} [add_comm_monoid N] (f : α →₀ N) (a : α) : f.sum (λ x v, ite (a = x) v 0) = f a := by { convert f.sum_ite_eq a (λ x, id), simp [ite_eq_right_iff.2 eq.symm] } /-- A restatement of `prod_ite_eq` with the equality test reversed. -/ @[simp, to_additive "A restatement of `sum_ite_eq` with the equality test reversed."] lemma prod_ite_eq' [decidable_eq α] (f : α →₀ M) (a : α) (b : α → M → N) : f.prod (λ x v, ite (x = a) (b x v) 1) = ite (a ∈ f.support) (b a (f a)) 1 := by { dsimp [finsupp.prod], rw f.support.prod_ite_eq', } @[simp] lemma sum_ite_self_eq' [decidable_eq α] {N : Type*} [add_comm_monoid N] (f : α →₀ N) (a : α) : f.sum (λ x v, ite (x = a) v 0) = f a := by { convert f.sum_ite_eq' a (λ x, id), simp [ite_eq_right_iff.2 eq.symm] } @[simp] lemma prod_pow [fintype α] (f : α →₀ ℕ) (g : α → N) : f.prod (λ a b, g a ^ b) = ∏ a, g a ^ (f a) := f.prod_fintype _ $ λ a, pow_zero _ /-- If `g` maps a second argument of 0 to 1, then multiplying it over the result of `on_finset` is the same as multiplying it over the original `finset`. -/ @[to_additive "If `g` maps a second argument of 0 to 0, summing it over the result of `on_finset` is the same as summing it over the original `finset`."] lemma on_finset_prod {s : finset α} {f : α → M} {g : α → M → N} (hf : ∀a, f a ≠ 0 → a ∈ s) (hg : ∀ a, g a 0 = 1) : (on_finset s f hf).prod g = ∏ a in s, g a (f a) := finset.prod_subset support_on_finset_subset $ by simp [*] { contextual := tt } /-- Taking a product over `f : α →₀ M` is the same as multiplying the value on a single element `y ∈ f.support` by the product over `erase y f`. -/ @[to_additive /-" Taking a sum over over `f : α →₀ M` is the same as adding the value on a single element `y ∈ f.support` to the sum over `erase y f`. "-/] lemma mul_prod_erase (f : α →₀ M) (y : α) (g : α → M → N) (hyf : y ∈ f.support) : g y (f y) * (erase y f).prod g = f.prod g := begin rw [finsupp.prod, finsupp.prod, ←finset.mul_prod_erase _ _ hyf, finsupp.support_erase, finset.prod_congr rfl], intros h hx, rw finsupp.erase_ne (ne_of_mem_erase hx), end /-- Generalization of `finsupp.mul_prod_erase`: if `g` maps a second argument of 0 to 1, then its product over `f : α →₀ M` is the same as multiplying the value on any element `y : α` by the product over `erase y f`. -/ @[to_additive /-" Generalization of `finsupp.add_sum_erase`: if `g` maps a second argument of 0 to 0, then its sum over `f : α →₀ M` is the same as adding the value on any element `y : α` to the sum over `erase y f`. "-/] lemma mul_prod_erase' (f : α →₀ M) (y : α) (g : α → M → N) (hg : ∀ (i : α), g i 0 = 1) : g y (f y) * (erase y f).prod g = f.prod g := begin classical, by_cases hyf : y ∈ f.support, { exact finsupp.mul_prod_erase f y g hyf }, { rw [not_mem_support_iff.mp hyf, hg y, erase_of_not_mem_support hyf, one_mul] }, end @[to_additive] lemma _root_.submonoid_class.finsupp_prod_mem {S : Type*} [set_like S N] [submonoid_class S N] (s : S) (f : α →₀ M) (g : α → M → N) (h : ∀ c, f c ≠ 0 → g c (f c) ∈ s) : f.prod g ∈ s := prod_mem $ λ i hi, h _ (finsupp.mem_support_iff.mp hi) @[to_additive] lemma prod_congr {f : α →₀ M} {g1 g2 : α → M → N} (h : ∀ x ∈ f.support, g1 x (f x) = g2 x (f x)) : f.prod g1 = f.prod g2 := finset.prod_congr rfl h end sum_prod /-! ### Additive monoid structure on `α →₀ M` -/ section add_zero_class variables [add_zero_class M] instance : has_add (α →₀ M) := ⟨zip_with (+) (add_zero 0)⟩ @[simp] lemma coe_add (f g : α →₀ M) : ⇑(f + g) = f + g := rfl lemma add_apply (g₁ g₂ : α →₀ M) (a : α) : (g₁ + g₂) a = g₁ a + g₂ a := rfl lemma support_add [decidable_eq α] {g₁ g₂ : α →₀ M} : (g₁ + g₂).support ⊆ g₁.support ∪ g₂.support := support_zip_with lemma support_add_eq [decidable_eq α] {g₁ g₂ : α →₀ M} (h : disjoint g₁.support g₂.support) : (g₁ + g₂).support = g₁.support ∪ g₂.support := le_antisymm support_zip_with $ assume a ha, (finset.mem_union.1 ha).elim (assume ha, have a ∉ g₂.support, from disjoint_left.1 h ha, by simp only [mem_support_iff, not_not] at *; simpa only [add_apply, this, add_zero]) (assume ha, have a ∉ g₁.support, from disjoint_right.1 h ha, by simp only [mem_support_iff, not_not] at *; simpa only [add_apply, this, zero_add]) @[simp] lemma single_add (a : α) (b₁ b₂ : M) : single a (b₁ + b₂) = single a b₁ + single a b₂ := ext $ assume a', begin by_cases h : a = a', { rw [h, add_apply, single_eq_same, single_eq_same, single_eq_same] }, { rw [add_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h, zero_add] } end instance : add_zero_class (α →₀ M) := fun_like.coe_injective.add_zero_class _ coe_zero coe_add /-- `finsupp.single` as an `add_monoid_hom`. See `finsupp.lsingle` for the stronger version as a linear map. -/ @[simps] def single_add_hom (a : α) : M →+ α →₀ M := ⟨single a, single_zero a, single_add a⟩ /-- Evaluation of a function `f : α →₀ M` at a point as an additive monoid homomorphism. See `finsupp.lapply` for the stronger version as a linear map. -/ @[simps apply] def apply_add_hom (a : α) : (α →₀ M) →+ M := ⟨λ g, g a, zero_apply, λ _ _, add_apply _ _ _⟩ /-- Coercion from a `finsupp` to a function type is an `add_monoid_hom`. -/ @[simps] noncomputable def coe_fn_add_hom : (α →₀ M) →+ (α → M) := { to_fun := coe_fn, map_zero' := coe_zero, map_add' := coe_add } lemma update_eq_single_add_erase (f : α →₀ M) (a : α) (b : M) : f.update a b = single a b + f.erase a := begin ext j, rcases eq_or_ne a j with rfl|h, { simp }, { simp [function.update_noteq h.symm, single_apply, h, erase_ne, h.symm] } end lemma update_eq_erase_add_single (f : α →₀ M) (a : α) (b : M) : f.update a b = f.erase a + single a b := begin ext j, rcases eq_or_ne a j with rfl|h, { simp }, { simp [function.update_noteq h.symm, single_apply, h, erase_ne, h.symm] } end lemma single_add_erase (a : α) (f : α →₀ M) : single a (f a) + f.erase a = f := by rw [←update_eq_single_add_erase, update_self] lemma erase_add_single (a : α) (f : α →₀ M) : f.erase a + single a (f a) = f := by rw [←update_eq_erase_add_single, update_self] @[simp] lemma erase_add (a : α) (f f' : α →₀ M) : erase a (f + f') = erase a f + erase a f' := begin ext s, by_cases hs : s = a, { rw [hs, add_apply, erase_same, erase_same, erase_same, add_zero] }, rw [add_apply, erase_ne hs, erase_ne hs, erase_ne hs, add_apply], end /-- `finsupp.erase` as an `add_monoid_hom`. -/ @[simps] def erase_add_hom (a : α) : (α →₀ M) →+ (α →₀ M) := { to_fun := erase a, map_zero' := erase_zero a, map_add' := erase_add a } @[elab_as_eliminator] protected theorem induction {p : (α →₀ M) → Prop} (f : α →₀ M) (h0 : p 0) (ha : ∀a b (f : α →₀ M), a ∉ f.support → b ≠ 0 → p f → p (single a b + f)) : p f := suffices ∀s (f : α →₀ M), f.support = s → p f, from this _ _ rfl, assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $ assume a s has ih f hf, suffices p (single a (f a) + f.erase a), by rwa [single_add_erase] at this, begin apply ha, { rw [support_erase, mem_erase], exact λ H, H.1 rfl }, { rw [← mem_support_iff, hf], exact mem_insert_self _ _ }, { apply ih _ _, rw [support_erase, hf, finset.erase_insert has] } end lemma induction₂ {p : (α →₀ M) → Prop} (f : α →₀ M) (h0 : p 0) (ha : ∀a b (f : α →₀ M), a ∉ f.support → b ≠ 0 → p f → p (f + single a b)) : p f := suffices ∀s (f : α →₀ M), f.support = s → p f, from this _ _ rfl, assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $ assume a s has ih f hf, suffices p (f.erase a + single a (f a)), by rwa [erase_add_single] at this, begin apply ha, { rw [support_erase, mem_erase], exact λ H, H.1 rfl }, { rw [← mem_support_iff, hf], exact mem_insert_self _ _ }, { apply ih _ _, rw [support_erase, hf, finset.erase_insert has] } end lemma induction_linear {p : (α →₀ M) → Prop} (f : α →₀ M) (h0 : p 0) (hadd : ∀ f g : α →₀ M, p f → p g → p (f + g)) (hsingle : ∀ a b, p (single a b)) : p f := induction₂ f h0 (λ a b f _ _ w, hadd _ _ w (hsingle _ _)) @[simp] lemma add_closure_set_of_eq_single : add_submonoid.closure {f : α →₀ M | ∃ a b, f = single a b} = ⊤ := top_unique $ λ x hx, finsupp.induction x (add_submonoid.zero_mem _) $ λ a b f ha hb hf, add_submonoid.add_mem _ (add_submonoid.subset_closure $ ⟨a, b, rfl⟩) hf /-- If two additive homomorphisms from `α →₀ M` are equal on each `single a b`, then they are equal. -/ lemma add_hom_ext [add_zero_class N] ⦃f g : (α →₀ M) →+ N⦄ (H : ∀ x y, f (single x y) = g (single x y)) : f = g := begin refine add_monoid_hom.eq_of_eq_on_mdense add_closure_set_of_eq_single _, rintro _ ⟨x, y, rfl⟩, apply H end /-- If two additive homomorphisms from `α →₀ M` are equal on each `single a b`, then they are equal. We formulate this using equality of `add_monoid_hom`s so that `ext` tactic can apply a type-specific extensionality lemma after this one. E.g., if the fiber `M` is `ℕ` or `ℤ`, then it suffices to verify `f (single a 1) = g (single a 1)`. -/ @[ext] lemma add_hom_ext' [add_zero_class N] ⦃f g : (α →₀ M) →+ N⦄ (H : ∀ x, f.comp (single_add_hom x) = g.comp (single_add_hom x)) : f = g := add_hom_ext $ λ x, add_monoid_hom.congr_fun (H x) lemma mul_hom_ext [mul_one_class N] ⦃f g : multiplicative (α →₀ M) →* N⦄ (H : ∀ x y, f (multiplicative.of_add $ single x y) = g (multiplicative.of_add $ single x y)) : f = g := monoid_hom.ext $ add_monoid_hom.congr_fun $ @add_hom_ext α M (additive N) _ _ f.to_additive'' g.to_additive'' H @[ext] lemma mul_hom_ext' [mul_one_class N] {f g : multiplicative (α →₀ M) →* N} (H : ∀ x, f.comp (single_add_hom x).to_multiplicative = g.comp (single_add_hom x).to_multiplicative) : f = g := mul_hom_ext $ λ x, monoid_hom.congr_fun (H x) lemma map_range_add [add_zero_class N] {f : M → N} {hf : f 0 = 0} (hf' : ∀ x y, f (x + y) = f x + f y) (v₁ v₂ : α →₀ M) : map_range f hf (v₁ + v₂) = map_range f hf v₁ + map_range f hf v₂ := ext $ λ a, by simp only [hf', add_apply, map_range_apply] /-- Bundle `emb_domain f` as an additive map from `α →₀ M` to `β →₀ M`. -/ @[simps] def emb_domain.add_monoid_hom (f : α ↪ β) : (α →₀ M) →+ β →₀ M := { to_fun := λ v, emb_domain f v, map_zero' := by simp, map_add' := λ v w, begin ext b, by_cases h : b ∈ set.range f, { rcases h with ⟨a, rfl⟩, simp, }, { simp [emb_domain_notin_range, h], }, end, } @[simp] lemma emb_domain_add (f : α ↪ β) (v w : α →₀ M) : emb_domain f (v + w) = emb_domain f v + emb_domain f w := (emb_domain.add_monoid_hom f).map_add v w end add_zero_class section add_monoid variables [add_monoid M] /-- Note the general `finsupp.has_smul` instance doesn't apply as `ℕ` is not distributive unless `β i`'s addition is commutative. -/ instance has_nat_scalar : has_smul ℕ (α →₀ M) := ⟨λ n v, v.map_range ((•) n) (nsmul_zero _)⟩ instance : add_monoid (α →₀ M) := fun_like.coe_injective.add_monoid _ coe_zero coe_add (λ _ _, rfl) end add_monoid end finsupp @[to_additive] lemma map_finsupp_prod [has_zero M] [comm_monoid N] [comm_monoid P] {H : Type*} [monoid_hom_class H N P] (h : H) (f : α →₀ M) (g : α → M → N) : h (f.prod g) = f.prod (λ a b, h (g a b)) := map_prod h _ _ /-- Deprecated, use `_root_.map_finsupp_prod` instead. -/ @[to_additive "Deprecated, use `_root_.map_finsupp_sum` instead."] protected lemma mul_equiv.map_finsupp_prod [has_zero M] [comm_monoid N] [comm_monoid P] (h : N ≃* P) (f : α →₀ M) (g : α → M → N) : h (f.prod g) = f.prod (λ a b, h (g a b)) := map_finsupp_prod h f g /-- Deprecated, use `_root_.map_finsupp_prod` instead. -/ @[to_additive "Deprecated, use `_root_.map_finsupp_sum` instead."] protected lemma monoid_hom.map_finsupp_prod [has_zero M] [comm_monoid N] [comm_monoid P] (h : N →* P) (f : α →₀ M) (g : α → M → N) : h (f.prod g) = f.prod (λ a b, h (g a b)) := map_finsupp_prod h f g /-- Deprecated, use `_root_.map_finsupp_sum` instead. -/ protected lemma ring_hom.map_finsupp_sum [has_zero M] [semiring R] [semiring S] (h : R →+* S) (f : α →₀ M) (g : α → M → R) : h (f.sum g) = f.sum (λ a b, h (g a b)) := map_finsupp_sum h f g /-- Deprecated, use `_root_.map_finsupp_prod` instead. -/ protected lemma ring_hom.map_finsupp_prod [has_zero M] [comm_semiring R] [comm_semiring S] (h : R →+* S) (f : α →₀ M) (g : α → M → R) : h (f.prod g) = f.prod (λ a b, h (g a b)) := map_finsupp_prod h f g @[to_additive] lemma monoid_hom.coe_finsupp_prod [has_zero β] [monoid N] [comm_monoid P] (f : α →₀ β) (g : α → β → N →* P) : ⇑(f.prod g) = f.prod (λ i fi, g i fi) := monoid_hom.coe_finset_prod _ _ @[simp, to_additive] lemma monoid_hom.finsupp_prod_apply [has_zero β] [monoid N] [comm_monoid P] (f : α →₀ β) (g : α → β → N →* P) (x : N) : f.prod g x = f.prod (λ i fi, g i fi x) := monoid_hom.finset_prod_apply _ _ _ namespace finsupp instance [add_comm_monoid M] : add_comm_monoid (α →₀ M) := fun_like.coe_injective.add_comm_monoid _ coe_zero coe_add (λ _ _, rfl) instance [add_group G] : has_neg (α →₀ G) := ⟨map_range (has_neg.neg) neg_zero⟩ @[simp] lemma coe_neg [add_group G] (g : α →₀ G) : ⇑(-g) = -g := rfl lemma neg_apply [add_group G] (g : α →₀ G) (a : α) : (- g) a = - g a := rfl instance [add_group G] : has_sub (α →₀ G) := ⟨zip_with has_sub.sub (sub_zero _)⟩ @[simp] lemma coe_sub [add_group G] (g₁ g₂ : α →₀ G) : ⇑(g₁ - g₂) = g₁ - g₂ := rfl lemma sub_apply [add_group G] (g₁ g₂ : α →₀ G) (a : α) : (g₁ - g₂) a = g₁ a - g₂ a := rfl /-- Note the general `finsupp.has_smul` instance doesn't apply as `ℤ` is not distributive unless `β i`'s addition is commutative. -/ instance has_int_scalar [add_group G] : has_smul ℤ (α →₀ G) := ⟨λ n v, v.map_range ((•) n) (zsmul_zero _)⟩ instance [add_group G] : add_group (α →₀ G) := fun_like.coe_injective.add_group _ coe_zero coe_add coe_neg coe_sub (λ _ _, rfl) (λ _ _, rfl) instance [add_comm_group G] : add_comm_group (α →₀ G) := fun_like.coe_injective.add_comm_group _ coe_zero coe_add coe_neg coe_sub (λ _ _, rfl) (λ _ _, rfl) lemma single_add_single_eq_single_add_single [add_comm_monoid M] {k l m n : α} {u v : M} (hu : u ≠ 0) (hv : v ≠ 0) : single k u + single l v = single m u + single n v ↔ (k = m ∧ l = n) ∨ (u = v ∧ k = n ∧ l = m) ∨ (u + v = 0 ∧ k = l ∧ m = n) := begin simp_rw [fun_like.ext_iff, coe_add, single_eq_pi_single, ←funext_iff], exact pi.single_add_single_eq_single_add_single hu hv, end lemma single_multiset_sum [add_comm_monoid M] (s : multiset M) (a : α) : single a s.sum = (s.map (single a)).sum := multiset.induction_on s (single_zero _) $ λ a s ih, by rw [multiset.sum_cons, single_add, ih, multiset.map_cons, multiset.sum_cons] lemma single_finset_sum [add_comm_monoid M] (s : finset ι) (f : ι → M) (a : α) : single a (∑ b in s, f b) = ∑ b in s, single a (f b) := begin transitivity, apply single_multiset_sum, rw [multiset.map_map], refl end lemma single_sum [has_zero M] [add_comm_monoid N] (s : ι →₀ M) (f : ι → M → N) (a : α) : single a (s.sum f) = s.sum (λd c, single a (f d c)) := single_finset_sum _ _ _ @[to_additive] lemma prod_neg_index [add_group G] [comm_monoid M] {g : α →₀ G} {h : α → G → M} (h0 : ∀a, h a 0 = 1) : (-g).prod h = g.prod (λa b, h a (- b)) := prod_map_range_index h0 @[simp] lemma support_neg [add_group G] (f : α →₀ G) : support (-f) = support f := finset.subset.antisymm support_map_range (calc support f = support (- (- f)) : congr_arg support (neg_neg _).symm ... ⊆ support (- f) : support_map_range) lemma support_sub [decidable_eq α] [add_group G] {f g : α →₀ G} : support (f - g) ⊆ support f ∪ support g := begin rw [sub_eq_add_neg, ←support_neg g], exact support_add, end lemma erase_eq_sub_single [add_group G] (f : α →₀ G) (a : α) : f.erase a = f - single a (f a) := begin ext a', rcases eq_or_ne a a' with rfl|h, { simp }, { simp [erase_ne h.symm, single_eq_of_ne h] } end lemma update_eq_sub_add_single [add_group G] (f : α →₀ G) (a : α) (b : G) : f.update a b = f - single a (f a) + single a b := by rw [update_eq_erase_add_single, erase_eq_sub_single] lemma finset_sum_apply [add_comm_monoid N] (S : finset ι) (f : ι → α →₀ N) (a : α) : (∑ i in S, f i) a = ∑ i in S, f i a := (apply_add_hom a : (α →₀ N) →+ _).map_sum _ _ @[simp] lemma sum_apply [has_zero M] [add_comm_monoid N] {f : α →₀ M} {g : α → M → β →₀ N} {a₂ : β} : (f.sum g) a₂ = f.sum (λa₁ b, g a₁ b a₂) := finset_sum_apply _ _ _ lemma coe_finset_sum [add_comm_monoid N] (S : finset ι) (f : ι → α →₀ N) : ⇑(∑ i in S, f i) = ∑ i in S, f i := (coe_fn_add_hom : (α →₀ N) →+ _).map_sum _ _ lemma coe_sum [has_zero M] [add_comm_monoid N] (f : α →₀ M) (g : α → M → β →₀ N) : ⇑(f.sum g) = f.sum (λ a₁ b, g a₁ b) := coe_finset_sum _ _ lemma support_sum [decidable_eq β] [has_zero M] [add_comm_monoid N] {f : α →₀ M} {g : α → M → (β →₀ N)} : (f.sum g).support ⊆ f.support.bUnion (λa, (g a (f a)).support) := have ∀ c, f.sum (λ a b, g a b c) ≠ 0 → (∃ a, f a ≠ 0 ∧ ¬ (g a (f a)) c = 0), from assume a₁ h, let ⟨a, ha, ne⟩ := finset.exists_ne_zero_of_sum_ne_zero h in ⟨a, mem_support_iff.mp ha, ne⟩, by simpa only [finset.subset_iff, mem_support_iff, finset.mem_bUnion, sum_apply, exists_prop] lemma support_finset_sum [decidable_eq β] [add_comm_monoid M] {s : finset α} {f : α → (β →₀ M)} : (finset.sum s f).support ⊆ s.bUnion (λ x, (f x).support) := begin rw ←finset.sup_eq_bUnion, induction s using finset.cons_induction_on with a s ha ih, { refl }, { rw [finset.sum_cons, finset.sup_cons], exact support_add.trans (finset.union_subset_union (finset.subset.refl _) ih), }, end @[simp] lemma sum_zero [has_zero M] [add_comm_monoid N] {f : α →₀ M} : f.sum (λa b, (0 : N)) = 0 := finset.sum_const_zero @[simp, to_additive] lemma prod_mul [has_zero M] [comm_monoid N] {f : α →₀ M} {h₁ h₂ : α → M → N} : f.prod (λa b, h₁ a b * h₂ a b) = f.prod h₁ * f.prod h₂ := finset.prod_mul_distrib @[simp, to_additive] lemma prod_inv [has_zero M] [comm_group G] {f : α →₀ M} {h : α → M → G} : f.prod (λa b, (h a b)⁻¹) = (f.prod h)⁻¹ := (map_prod ((monoid_hom.id G)⁻¹) _ _).symm @[simp] lemma sum_sub [has_zero M] [add_comm_group G] {f : α →₀ M} {h₁ h₂ : α → M → G} : f.sum (λa b, h₁ a b - h₂ a b) = f.sum h₁ - f.sum h₂ := finset.sum_sub_distrib /-- Taking the product under `h` is an additive-to-multiplicative homomorphism of finsupps, if `h` is an additive-to-multiplicative homomorphism on the support. This is a more general version of `finsupp.prod_add_index'`; the latter has simpler hypotheses. -/ @[to_additive "Taking the product under `h` is an additive homomorphism of finsupps, if `h` is an additive homomorphism on the support. This is a more general version of `finsupp.sum_add_index'`; the latter has simpler hypotheses."] lemma prod_add_index [add_zero_class M] [comm_monoid N] {f g : α →₀ M} {h : α → M → N} (h_zero : ∀ a ∈ f.support ∪ g.support, h a 0 = 1) (h_add : ∀ (a ∈ f.support ∪ g.support) b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : (f + g).prod h = f.prod h * g.prod h := begin rw [finsupp.prod_of_support_subset f (subset_union_left _ g.support) h h_zero, finsupp.prod_of_support_subset g (subset_union_right f.support _) h h_zero, ←finset.prod_mul_distrib, finsupp.prod_of_support_subset (f + g) finsupp.support_add h h_zero], exact finset.prod_congr rfl (λ x hx, (by apply h_add x hx)), end /-- Taking the product under `h` is an additive-to-multiplicative homomorphism of finsupps, if `h` is an additive-to-multiplicative homomorphism. This is a more specialized version of `finsupp.prod_add_index` with simpler hypotheses. -/ @[to_additive "Taking the sum under `h` is an additive homomorphism of finsupps, if `h` is an additive homomorphism. This is a more specific version of `finsupp.sum_add_index` with simpler hypotheses."] lemma prod_add_index' [add_zero_class M] [comm_monoid N] {f g : α →₀ M} {h : α → M → N} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : (f + g).prod h = f.prod h * g.prod h := prod_add_index (λ a ha, h_zero a) (λ a ha, h_add a) @[simp] lemma sum_hom_add_index [add_zero_class M] [add_comm_monoid N] {f g : α →₀ M} (h : α → M →+ N) : (f + g).sum (λ x, h x) = f.sum (λ x, h x) + g.sum (λ x, h x) := sum_add_index' (λ a, (h a).map_zero) (λ a, (h a).map_add) @[simp] lemma prod_hom_add_index [add_zero_class M] [comm_monoid N] {f g : α →₀ M} (h : α → multiplicative M →* N) : (f + g).prod (λ a b, h a (multiplicative.of_add b)) = f.prod (λ a b, h a (multiplicative.of_add b)) * g.prod (λ a b, h a (multiplicative.of_add b)) := prod_add_index' (λ a, (h a).map_one) (λ a, (h a).map_mul) /-- The canonical isomorphism between families of additive monoid homomorphisms `α → (M →+ N)` and monoid homomorphisms `(α →₀ M) →+ N`. -/ def lift_add_hom [add_zero_class M] [add_comm_monoid N] : (α → M →+ N) ≃+ ((α →₀ M) →+ N) := { to_fun := λ F, { to_fun := λ f, f.sum (λ x, F x), map_zero' := finset.sum_empty, map_add' := λ _ _, sum_add_index' (λ x, (F x).map_zero) (λ x, (F x).map_add) }, inv_fun := λ F x, F.comp $ single_add_hom x, left_inv := λ F, by { ext, simp }, right_inv := λ F, by { ext, simp }, map_add' := λ F G, by { ext, simp } } @[simp] lemma lift_add_hom_apply [add_comm_monoid M] [add_comm_monoid N] (F : α → M →+ N) (f : α →₀ M) : lift_add_hom F f = f.sum (λ x, F x) := rfl @[simp] lemma lift_add_hom_symm_apply [add_comm_monoid M] [add_comm_monoid N] (F : (α →₀ M) →+ N) (x : α) : lift_add_hom.symm F x = F.comp (single_add_hom x) := rfl lemma lift_add_hom_symm_apply_apply [add_comm_monoid M] [add_comm_monoid N] (F : (α →₀ M) →+ N) (x : α) (y : M) : lift_add_hom.symm F x y = F (single x y) := rfl @[simp] lemma lift_add_hom_single_add_hom [add_comm_monoid M] : lift_add_hom (single_add_hom : α → M →+ α →₀ M) = add_monoid_hom.id _ := lift_add_hom.to_equiv.apply_eq_iff_eq_symm_apply.2 rfl @[simp] lemma sum_single [add_comm_monoid M] (f : α →₀ M) : f.sum single = f := add_monoid_hom.congr_fun lift_add_hom_single_add_hom f @[simp] lemma sum_univ_single [add_comm_monoid M] [fintype α] (i : α) (m : M) : ∑ (j : α), (single i m) j = m := by simp [single] @[simp] lemma sum_univ_single' [add_comm_monoid M] [fintype α] (i : α) (m : M) : ∑ (j : α), (single j m) i = m := by simp [single] @[simp] lemma lift_add_hom_apply_single [add_comm_monoid M] [add_comm_monoid N] (f : α → M →+ N) (a : α) (b : M) : lift_add_hom f (single a b) = f a b := sum_single_index (f a).map_zero @[simp] lemma lift_add_hom_comp_single [add_comm_monoid M] [add_comm_monoid N] (f : α → M →+ N) (a : α) : (lift_add_hom f).comp (single_add_hom a) = f a := add_monoid_hom.ext $ λ b, lift_add_hom_apply_single f a b lemma comp_lift_add_hom [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] (g : N →+ P) (f : α → M →+ N) : g.comp (lift_add_hom f) = lift_add_hom (λ a, g.comp (f a)) := lift_add_hom.symm_apply_eq.1 $ funext $ λ a, by rw [lift_add_hom_symm_apply, add_monoid_hom.comp_assoc, lift_add_hom_comp_single] lemma sum_sub_index [add_comm_group β] [add_comm_group γ] {f g : α →₀ β} {h : α → β → γ} (h_sub : ∀a b₁ b₂, h a (b₁ - b₂) = h a b₁ - h a b₂) : (f - g).sum h = f.sum h - g.sum h := (lift_add_hom (λ a, add_monoid_hom.of_map_sub (h a) (h_sub a))).map_sub f g @[to_additive] lemma prod_emb_domain [has_zero M] [comm_monoid N] {v : α →₀ M} {f : α ↪ β} {g : β → M → N} : (v.emb_domain f).prod g = v.prod (λ a b, g (f a) b) := begin rw [prod, prod, support_emb_domain, finset.prod_map], simp_rw emb_domain_apply, end @[to_additive] lemma prod_finset_sum_index [add_comm_monoid M] [comm_monoid N] {s : finset ι} {g : ι → α →₀ M} {h : α → M → N} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : ∏ i in s, (g i).prod h = (∑ i in s, g i).prod h := finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih, sum_insert has, prod_add_index' h_zero h_add] @[to_additive] lemma prod_sum_index [add_comm_monoid M] [add_comm_monoid N] [comm_monoid P] {f : α →₀ M} {g : α → M → β →₀ N} {h : β → N → P} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : (f.sum g).prod h = f.prod (λa b, (g a b).prod h) := (prod_finset_sum_index h_zero h_add).symm lemma multiset_sum_sum_index [add_comm_monoid M] [add_comm_monoid N] (f : multiset (α →₀ M)) (h : α → M → N) (h₀ : ∀a, h a 0 = 0) (h₁ : ∀ (a : α) (b₁ b₂ : M), h a (b₁ + b₂) = h a b₁ + h a b₂) : (f.sum.sum h) = (f.map $ λg:α →₀ M, g.sum h).sum := multiset.induction_on f rfl $ assume a s ih, by rw [multiset.sum_cons, multiset.map_cons, multiset.sum_cons, sum_add_index' h₀ h₁, ih] lemma support_sum_eq_bUnion {α : Type*} {ι : Type*} {M : Type*} [add_comm_monoid M] {g : ι → α →₀ M} (s : finset ι) (h : ∀ i₁ i₂, i₁ ≠ i₂ → disjoint (g i₁).support (g i₂).support) : (∑ i in s, g i).support = s.bUnion (λ i, (g i).support) := begin apply finset.induction_on s, { simp }, { intros i s hi, simp only [hi, sum_insert, not_false_iff, bUnion_insert], intro hs, rw [finsupp.support_add_eq, hs], rw [hs], intros x hx, simp only [mem_bUnion, exists_prop, inf_eq_inter, ne.def, mem_inter] at hx, obtain ⟨hxi, j, hj, hxj⟩ := hx, have hn : i ≠ j := λ H, hi (H.symm ▸ hj), apply h _ _ hn, simp [hxi, hxj] } end lemma multiset_map_sum [has_zero M] {f : α →₀ M} {m : β → γ} {h : α → M → multiset β} : multiset.map m (f.sum h) = f.sum (λa b, (h a b).map m) := (multiset.map_add_monoid_hom m).map_sum _ f.support lemma multiset_sum_sum [has_zero M] [add_comm_monoid N] {f : α →₀ M} {h : α → M → multiset N} : multiset.sum (f.sum h) = f.sum (λa b, multiset.sum (h a b)) := (multiset.sum_add_monoid_hom : multiset N →+ N).map_sum _ f.support /-- For disjoint `f1` and `f2`, and function `g`, the product of the products of `g` over `f1` and `f2` equals the product of `g` over `f1 + f2` -/ @[to_additive "For disjoint `f1` and `f2`, and function `g`, the sum of the sums of `g` over `f1` and `f2` equals the sum of `g` over `f1 + f2`"] lemma prod_add_index_of_disjoint [add_comm_monoid M] {f1 f2 : α →₀ M} (hd : disjoint f1.support f2.support) {β : Type*} [comm_monoid β] (g : α → M → β) : (f1 + f2).prod g = f1.prod g * f2.prod g := have ∀ {f1 f2 : α →₀ M}, disjoint f1.support f2.support → ∏ x in f1.support, g x (f1 x + f2 x) = f1.prod g := λ f1 f2 hd, finset.prod_congr rfl (λ x hx, by simp only [not_mem_support_iff.mp (disjoint_left.mp hd hx), add_zero]), by simp_rw [← this hd, ← this hd.symm, add_comm (f2 _), finsupp.prod, support_add_eq hd, prod_union hd, add_apply] section map_range section equiv variables [has_zero M] [has_zero N] [has_zero P] /-- `finsupp.map_range` as an equiv. -/ @[simps apply] def map_range.equiv (f : M ≃ N) (hf : f 0 = 0) (hf' : f.symm 0 = 0) : (α →₀ M) ≃ (α →₀ N) := { to_fun := (map_range f hf : (α →₀ M) → (α →₀ N)), inv_fun := (map_range f.symm hf' : (α →₀ N) → (α →₀ M)), left_inv := λ x, begin rw ←map_range_comp _ _ _ _; simp_rw equiv.symm_comp_self, { exact map_range_id _ }, { refl }, end, right_inv := λ x, begin rw ←map_range_comp _ _ _ _; simp_rw equiv.self_comp_symm, { exact map_range_id _ }, { refl }, end } @[simp] lemma map_range.equiv_refl : map_range.equiv (equiv.refl M) rfl rfl = equiv.refl (α →₀ M) := equiv.ext map_range_id lemma map_range.equiv_trans (f : M ≃ N) (hf : f 0 = 0) (hf') (f₂ : N ≃ P) (hf₂ : f₂ 0 = 0) (hf₂') : (map_range.equiv (f.trans f₂) (by rw [equiv.trans_apply, hf, hf₂]) (by rw [equiv.symm_trans_apply, hf₂', hf']) : (α →₀ _) ≃ _) = (map_range.equiv f hf hf').trans (map_range.equiv f₂ hf₂ hf₂') := equiv.ext $ map_range_comp _ _ _ _ _ @[simp] lemma map_range.equiv_symm (f : M ≃ N) (hf hf') : ((map_range.equiv f hf hf').symm : (α →₀ _) ≃ _) = map_range.equiv f.symm hf' hf := equiv.ext $ λ x, rfl end equiv section zero_hom variables [has_zero M] [has_zero N] [has_zero P] /-- Composition with a fixed zero-preserving homomorphism is itself an zero-preserving homomorphism on functions. -/ @[simps] def map_range.zero_hom (f : zero_hom M N) : zero_hom (α →₀ M) (α →₀ N) := { to_fun := (map_range f f.map_zero : (α →₀ M) → (α →₀ N)), map_zero' := map_range_zero } @[simp] lemma map_range.zero_hom_id : map_range.zero_hom (zero_hom.id M) = zero_hom.id (α →₀ M) := zero_hom.ext map_range_id lemma map_range.zero_hom_comp (f : zero_hom N P) (f₂ : zero_hom M N) : (map_range.zero_hom (f.comp f₂) : zero_hom (α →₀ _) _) = (map_range.zero_hom f).comp (map_range.zero_hom f₂) := zero_hom.ext $ map_range_comp _ _ _ _ _ end zero_hom section add_monoid_hom variables [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] /-- Composition with a fixed additive homomorphism is itself an additive homomorphism on functions. -/ @[simps] def map_range.add_monoid_hom (f : M →+ N) : (α →₀ M) →+ (α →₀ N) := { to_fun := (map_range f f.map_zero : (α →₀ M) → (α →₀ N)), map_zero' := map_range_zero, map_add' := λ a b, map_range_add f.map_add _ _ } @[simp] lemma map_range.add_monoid_hom_id : map_range.add_monoid_hom (add_monoid_hom.id M) = add_monoid_hom.id (α →₀ M) := add_monoid_hom.ext map_range_id lemma map_range.add_monoid_hom_comp (f : N →+ P) (f₂ : M →+ N) : (map_range.add_monoid_hom (f.comp f₂) : (α →₀ _) →+ _) = (map_range.add_monoid_hom f).comp (map_range.add_monoid_hom f₂) := add_monoid_hom.ext $ map_range_comp _ _ _ _ _ @[simp] lemma map_range.add_monoid_hom_to_zero_hom (f : M →+ N) : (map_range.add_monoid_hom f).to_zero_hom = (map_range.zero_hom f.to_zero_hom : zero_hom (α →₀ _) _) := zero_hom.ext $ λ _, rfl lemma map_range_multiset_sum (f : M →+ N) (m : multiset (α →₀ M)) : map_range f f.map_zero m.sum = (m.map $ λx, map_range f f.map_zero x).sum := (map_range.add_monoid_hom f : (α →₀ _) →+ _).map_multiset_sum _ lemma map_range_finset_sum (f : M →+ N) (s : finset ι) (g : ι → (α →₀ M)) : map_range f f.map_zero (∑ x in s, g x) = ∑ x in s, map_range f f.map_zero (g x) := (map_range.add_monoid_hom f : (α →₀ _) →+ _).map_sum _ _ /-- `finsupp.map_range.add_monoid_hom` as an equiv. -/ @[simps apply] def map_range.add_equiv (f : M ≃+ N) : (α →₀ M) ≃+ (α →₀ N) := { to_fun := (map_range f f.map_zero : (α →₀ M) → (α →₀ N)), inv_fun := (map_range f.symm f.symm.map_zero : (α →₀ N) → (α →₀ M)), left_inv := λ x, begin rw ←map_range_comp _ _ _ _; simp_rw add_equiv.symm_comp_self, { exact map_range_id _ }, { refl }, end, right_inv := λ x, begin rw ←map_range_comp _ _ _ _; simp_rw add_equiv.self_comp_symm, { exact map_range_id _ }, { refl }, end, ..(map_range.add_monoid_hom f.to_add_monoid_hom) } @[simp] lemma map_range.add_equiv_refl : map_range.add_equiv (add_equiv.refl M) = add_equiv.refl (α →₀ M) := add_equiv.ext map_range_id lemma map_range.add_equiv_trans (f : M ≃+ N) (f₂ : N ≃+ P) : (map_range.add_equiv (f.trans f₂) : (α →₀ _) ≃+ _) = (map_range.add_equiv f).trans (map_range.add_equiv f₂) := add_equiv.ext $ map_range_comp _ _ _ _ _ @[simp] lemma map_range.add_equiv_symm (f : M ≃+ N) : ((map_range.add_equiv f).symm : (α →₀ _) ≃+ _) = map_range.add_equiv f.symm := add_equiv.ext $ λ x, rfl @[simp] lemma map_range.add_equiv_to_add_monoid_hom (f : M ≃+ N) : (map_range.add_equiv f : (α →₀ _) ≃+ _).to_add_monoid_hom = (map_range.add_monoid_hom f.to_add_monoid_hom : (α →₀ _) →+ _) := add_monoid_hom.ext $ λ _, rfl @[simp] lemma map_range.add_equiv_to_equiv (f : M ≃+ N) : (map_range.add_equiv f).to_equiv = (map_range.equiv f.to_equiv f.map_zero f.symm.map_zero : (α →₀ _) ≃ _) := equiv.ext $ λ _, rfl end add_monoid_hom end map_range /-! ### Declarations about `map_domain` -/ section map_domain variables [add_comm_monoid M] {v v₁ v₂ : α →₀ M} /-- Given `f : α → β` and `v : α →₀ M`, `map_domain f v : β →₀ M` is the finitely supported function whose value at `a : β` is the sum of `v x` over all `x` such that `f x = a`. -/ def map_domain (f : α → β) (v : α →₀ M) : β →₀ M := v.sum $ λa, single (f a) lemma map_domain_apply {f : α → β} (hf : function.injective f) (x : α →₀ M) (a : α) : map_domain f x (f a) = x a := begin rw [map_domain, sum_apply, sum, finset.sum_eq_single a, single_eq_same], { assume b _ hba, exact single_eq_of_ne (hf.ne hba) }, { assume h, rw [not_mem_support_iff.1 h, single_zero, zero_apply] } end lemma map_domain_notin_range {f : α → β} (x : α →₀ M) (a : β) (h : a ∉ set.range f) : map_domain f x a = 0 := begin rw [map_domain, sum_apply, sum], exact finset.sum_eq_zero (assume a' h', single_eq_of_ne $ assume eq, h $ eq ▸ set.mem_range_self _) end @[simp] lemma map_domain_id : map_domain id v = v := sum_single _ lemma map_domain_comp {f : α → β} {g : β → γ} : map_domain (g ∘ f) v = map_domain g (map_domain f v) := begin refine ((sum_sum_index _ _).trans _).symm, { intro, exact single_zero _ }, { intro, exact single_add _ }, refine sum_congr (λ _ _, sum_single_index _), { exact single_zero _ } end @[simp] lemma map_domain_single {f : α → β} {a : α} {b : M} : map_domain f (single a b) = single (f a) b := sum_single_index $ single_zero _ @[simp] lemma map_domain_zero {f : α → β} : map_domain f (0 : α →₀ M) = (0 : β →₀ M) := sum_zero_index lemma map_domain_congr {f g : α → β} (h : ∀x∈v.support, f x = g x) : v.map_domain f = v.map_domain g := finset.sum_congr rfl $ λ _ H, by simp only [h _ H] lemma map_domain_add {f : α → β} : map_domain f (v₁ + v₂) = map_domain f v₁ + map_domain f v₂ := sum_add_index' (λ _, single_zero _) (λ _, single_add _) @[simp] lemma map_domain_equiv_apply {f : α ≃ β} (x : α →₀ M) (a : β) : map_domain f x a = x (f.symm a) := begin conv_lhs { rw ←f.apply_symm_apply a }, exact map_domain_apply f.injective _ _, end /-- `finsupp.map_domain` is an `add_monoid_hom`. -/ @[simps] def map_domain.add_monoid_hom (f : α → β) : (α →₀ M) →+ (β →₀ M) := { to_fun := map_domain f, map_zero' := map_domain_zero, map_add' := λ _ _, map_domain_add} @[simp] lemma map_domain.add_monoid_hom_id : map_domain.add_monoid_hom id = add_monoid_hom.id (α →₀ M) := add_monoid_hom.ext $ λ _, map_domain_id lemma map_domain.add_monoid_hom_comp (f : β → γ) (g : α → β) : (map_domain.add_monoid_hom (f ∘ g) : (α →₀ M) →+ (γ →₀ M)) = (map_domain.add_monoid_hom f).comp (map_domain.add_monoid_hom g) := add_monoid_hom.ext $ λ _, map_domain_comp lemma map_domain_finset_sum {f : α → β} {s : finset ι} {v : ι → α →₀ M} : map_domain f (∑ i in s, v i) = ∑ i in s, map_domain f (v i) := (map_domain.add_monoid_hom f : (α →₀ M) →+ β →₀ M).map_sum _ _ lemma map_domain_sum [has_zero N] {f : α → β} {s : α →₀ N} {v : α → N → α →₀ M} : map_domain f (s.sum v) = s.sum (λa b, map_domain f (v a b)) := (map_domain.add_monoid_hom f : (α →₀ M) →+ β →₀ M).map_finsupp_sum _ _ lemma map_domain_support [decidable_eq β] {f : α → β} {s : α →₀ M} : (s.map_domain f).support ⊆ s.support.image f := finset.subset.trans support_sum $ finset.subset.trans (finset.bUnion_mono $ assume a ha, support_single_subset) $ by rw [finset.bUnion_singleton]; exact subset.refl _ lemma map_domain_apply' (S : set α) {f : α → β} (x : α →₀ M) (hS : (x.support : set α) ⊆ S) (hf : set.inj_on f S) {a : α} (ha : a ∈ S) : map_domain f x (f a) = x a := begin rw [map_domain, sum_apply, sum], simp_rw single_apply, have : ∀ (b : α) (ha1 : b ∈ x.support), (if f b = f a then x b else 0) = if f b = f a then x a else 0, { intros b hb, refine if_ctx_congr iff.rfl (λ hh, _) (λ _, rfl), rw hf (hS hb) ha hh, }, conv in (ite _ _ _) { rw [this _ H], }, by_cases ha : a ∈ x.support, { rw [← finset.add_sum_erase _ _ ha, if_pos rfl], convert add_zero _, have : ∀ i ∈ x.support.erase a, f i ≠ f a, { intros i hi, exact (finset.ne_of_mem_erase hi) ∘ (hf (hS $ finset.mem_of_mem_erase hi) (hS ha)), }, conv in (ite _ _ _) { rw if_neg (this x H), }, exact finset.sum_const_zero, }, { rw [mem_support_iff, not_not] at ha, simp [ha], } end lemma map_domain_support_of_inj_on [decidable_eq β] {f : α → β} (s : α →₀ M) (hf : set.inj_on f s.support) : (map_domain f s).support = finset.image f s.support := finset.subset.antisymm map_domain_support $ begin intros x hx, simp only [mem_image, exists_prop, mem_support_iff, ne.def] at hx, rcases hx with ⟨hx_w, hx_h_left, rfl⟩, simp only [mem_support_iff, ne.def], rw map_domain_apply' (↑s.support : set _) _ _ hf, { exact hx_h_left, }, { simp only [mem_coe, mem_support_iff, ne.def], exact hx_h_left, }, { exact subset.refl _, }, end lemma map_domain_support_of_injective [decidable_eq β] {f : α → β} (hf : function.injective f) (s : α →₀ M) : (map_domain f s).support = finset.image f s.support := map_domain_support_of_inj_on s (hf.inj_on _) @[to_additive] lemma prod_map_domain_index [comm_monoid N] {f : α → β} {s : α →₀ M} {h : β → M → N} (h_zero : ∀b, h b 0 = 1) (h_add : ∀b m₁ m₂, h b (m₁ + m₂) = h b m₁ * h b m₂) : (map_domain f s).prod h = s.prod (λa m, h (f a) m) := (prod_sum_index h_zero h_add).trans $ prod_congr $ λ _ _, prod_single_index (h_zero _) /-- A version of `sum_map_domain_index` that takes a bundled `add_monoid_hom`, rather than separate linearity hypotheses. -/ -- Note that in `prod_map_domain_index`, `M` is still an additive monoid, -- so there is no analogous version in terms of `monoid_hom`. @[simp] lemma sum_map_domain_index_add_monoid_hom [add_comm_monoid N] {f : α → β} {s : α →₀ M} (h : β → M →+ N) : (map_domain f s).sum (λ b m, h b m) = s.sum (λ a m, h (f a) m) := @sum_map_domain_index _ _ _ _ _ _ _ _ (λ b m, h b m) (λ b, (h b).map_zero) (λ b m₁ m₂, (h b).map_add _ _) lemma emb_domain_eq_map_domain (f : α ↪ β) (v : α →₀ M) : emb_domain f v = map_domain f v := begin ext a, by_cases a ∈ set.range f, { rcases h with ⟨a, rfl⟩, rw [map_domain_apply f.injective, emb_domain_apply] }, { rw [map_domain_notin_range, emb_domain_notin_range]; assumption } end @[to_additive] lemma prod_map_domain_index_inj [comm_monoid N] {f : α → β} {s : α →₀ M} {h : β → M → N} (hf : function.injective f) : (s.map_domain f).prod h = s.prod (λa b, h (f a) b) := by rw [←function.embedding.coe_fn_mk f hf, ←emb_domain_eq_map_domain, prod_emb_domain] lemma map_domain_injective {f : α → β} (hf : function.injective f) : function.injective (map_domain f : (α →₀ M) → (β →₀ M)) := begin assume v₁ v₂ eq, ext a, have : map_domain f v₁ (f a) = map_domain f v₂ (f a), { rw eq }, rwa [map_domain_apply hf, map_domain_apply hf] at this, end /-- When `f` is an embedding we have an embedding `(α →₀ ℕ) ↪ (β →₀ ℕ)` given by `map_domain`. -/ @[simps] def map_domain_embedding {α β : Type*} (f : α ↪ β) : (α →₀ ℕ) ↪ β →₀ ℕ := ⟨finsupp.map_domain f, finsupp.map_domain_injective f.injective⟩ lemma map_domain.add_monoid_hom_comp_map_range [add_comm_monoid N] (f : α → β) (g : M →+ N) : (map_domain.add_monoid_hom f).comp (map_range.add_monoid_hom g) = (map_range.add_monoid_hom g).comp (map_domain.add_monoid_hom f) := by { ext, simp } /-- When `g` preserves addition, `map_range` and `map_domain` commute. -/ lemma map_domain_map_range [add_comm_monoid N] (f : α → β) (v : α →₀ M) (g : M → N) (h0 : g 0 = 0) (hadd : ∀ x y, g (x + y) = g x + g y) : map_domain f (map_range g h0 v) = map_range g h0 (map_domain f v) := let g' : M →+ N := { to_fun := g, map_zero' := h0, map_add' := hadd} in add_monoid_hom.congr_fun (map_domain.add_monoid_hom_comp_map_range f g') v lemma sum_update_add [add_comm_monoid α] [add_comm_monoid β] (f : ι →₀ α) (i : ι) (a : α) (g : ι → α → β) (hg : ∀ i, g i 0 = 0) (hgg : ∀ (j : ι) (a₁ a₂ : α), g j (a₁ + a₂) = g j a₁ + g j a₂) : (f.update i a).sum g + g i (f i) = f.sum g + g i a := begin rw [update_eq_erase_add_single, sum_add_index' hg hgg], conv_rhs { rw ← finsupp.update_self f i }, rw [update_eq_erase_add_single, sum_add_index' hg hgg, add_assoc, add_assoc], congr' 1, rw [add_comm, sum_single_index (hg _), sum_single_index (hg _)], end lemma map_domain_inj_on (S : set α) {f : α → β} (hf : set.inj_on f S) : set.inj_on (map_domain f : (α →₀ M) → (β →₀ M)) {w | (w.support : set α) ⊆ S} := begin intros v₁ hv₁ v₂ hv₂ eq, ext a, by_cases h : a ∈ v₁.support ∪ v₂.support, { rw [← map_domain_apply' S _ hv₁ hf _, ← map_domain_apply' S _ hv₂ hf _, eq]; { apply set.union_subset hv₁ hv₂, exact_mod_cast h, }, }, { simp only [decidable.not_or_iff_and_not, mem_union, not_not, mem_support_iff] at h, simp [h], }, end end map_domain /-! ### Declarations about `comap_domain` -/ section comap_domain /-- Given `f : α → β`, `l : β →₀ M` and a proof `hf` that `f` is injective on the preimage of `l.support`, `comap_domain f l hf` is the finitely supported function from `α` to `M` given by composing `l` with `f`. -/ @[simps support] def comap_domain [has_zero M] (f : α → β) (l : β →₀ M) (hf : set.inj_on f (f ⁻¹' ↑l.support)) : α →₀ M := { support := l.support.preimage f hf, to_fun := (λ a, l (f a)), mem_support_to_fun := begin intros a, simp only [finset.mem_def.symm, finset.mem_preimage], exact l.mem_support_to_fun (f a), end } @[simp] lemma comap_domain_apply [has_zero M] (f : α → β) (l : β →₀ M) (hf : set.inj_on f (f ⁻¹' ↑l.support)) (a : α) : comap_domain f l hf a = l (f a) := rfl lemma sum_comap_domain [has_zero M] [add_comm_monoid N] (f : α → β) (l : β →₀ M) (g : β → M → N) (hf : set.bij_on f (f ⁻¹' ↑l.support) ↑l.support) : (comap_domain f l hf.inj_on).sum (g ∘ f) = l.sum g := begin simp only [sum, comap_domain_apply, (∘)], simp [comap_domain, finset.sum_preimage_of_bij f _ _ (λ x, g x (l x))], end lemma eq_zero_of_comap_domain_eq_zero [add_comm_monoid M] (f : α → β) (l : β →₀ M) (hf : set.bij_on f (f ⁻¹' ↑l.support) ↑l.support) : comap_domain f l hf.inj_on = 0 → l = 0 := begin rw [← support_eq_empty, ← support_eq_empty, comap_domain], simp only [finset.ext_iff, finset.not_mem_empty, iff_false, mem_preimage], assume h a ha, cases hf.2.2 ha with b hb, exact h b (hb.2.symm ▸ ha) end section f_injective section has_zero variables [has_zero M] /-- Note the `hif` argument is needed for this to work in `rw`. -/ @[simp] lemma comap_domain_zero (f : α → β) (hif : set.inj_on f (f ⁻¹' ↑((0 : β →₀ M).support)) := set.inj_on_empty _) : comap_domain f (0 : β →₀ M) hif = (0 : α →₀ M) := by { ext, refl } @[simp] lemma comap_domain_single (f : α → β) (a : α) (m : M) (hif : set.inj_on f (f ⁻¹' (single (f a) m).support)) : comap_domain f (finsupp.single (f a) m) hif = finsupp.single a m := begin rcases eq_or_ne m 0 with rfl | hm, { simp only [single_zero, comap_domain_zero] }, { rw [eq_single_iff, comap_domain_apply, comap_domain_support, ← finset.coe_subset, coe_preimage, support_single_ne_zero _ hm, coe_singleton, coe_singleton, single_eq_same], rw [support_single_ne_zero _ hm, coe_singleton] at hif, exact ⟨λ x hx, hif hx rfl hx, rfl⟩ } end end has_zero section add_zero_class variables [add_zero_class M] {f : α → β} lemma comap_domain_add (v₁ v₂ : β →₀ M) (hv₁ : set.inj_on f (f ⁻¹' ↑(v₁.support))) (hv₂ : set.inj_on f (f ⁻¹' ↑(v₂.support))) (hv₁₂ : set.inj_on f (f ⁻¹' ↑((v₁ + v₂).support))) : comap_domain f (v₁ + v₂) hv₁₂ = comap_domain f v₁ hv₁ + comap_domain f v₂ hv₂ := by { ext, simp only [comap_domain_apply, coe_add, pi.add_apply] } /-- A version of `finsupp.comap_domain_add` that's easier to use. -/ lemma comap_domain_add_of_injective (hf : function.injective f) (v₁ v₂ : β →₀ M) : comap_domain f (v₁ + v₂) (hf.inj_on _) = comap_domain f v₁ (hf.inj_on _) + comap_domain f v₂ (hf.inj_on _) := comap_domain_add _ _ _ _ _ /-- `finsupp.comap_domain` is an `add_monoid_hom`. -/ @[simps] def comap_domain.add_monoid_hom (hf : function.injective f) : (β →₀ M) →+ (α →₀ M) := { to_fun := λ x, comap_domain f x (hf.inj_on _), map_zero' := comap_domain_zero f, map_add' := comap_domain_add_of_injective hf } end add_zero_class variables [add_comm_monoid M] (f : α → β) lemma map_domain_comap_domain (hf : function.injective f) (l : β →₀ M) (hl : ↑l.support ⊆ set.range f) : map_domain f (comap_domain f l (hf.inj_on _)) = l := begin ext a, by_cases h_cases: a ∈ set.range f, { rcases set.mem_range.1 h_cases with ⟨b, hb⟩, rw [hb.symm, map_domain_apply hf, comap_domain_apply] }, { rw map_domain_notin_range _ _ h_cases, by_contra h_contr, apply h_cases (hl $ finset.mem_coe.2 $ mem_support_iff.2 $ λ h, h_contr h.symm) } end end f_injective end comap_domain section option /-- Restrict a finitely supported function on `option α` to a finitely supported function on `α`. -/ def some [has_zero M] (f : option α →₀ M) : α →₀ M := f.comap_domain option.some (λ _, by simp) @[simp] lemma some_apply [has_zero M] (f : option α →₀ M) (a : α) : f.some a = f (option.some a) := rfl @[simp] lemma some_zero [has_zero M] : (0 : option α →₀ M).some = 0 := by { ext, simp, } @[simp] lemma some_add [add_comm_monoid M] (f g : option α →₀ M) : (f + g).some = f.some + g.some := by { ext, simp, } @[simp] lemma some_single_none [has_zero M] (m : M) : (single none m : option α →₀ M).some = 0 := by { ext, simp, } @[simp] lemma some_single_some [has_zero M] (a : α) (m : M) : (single (option.some a) m : option α →₀ M).some = single a m := by { ext b, simp [single_apply], } @[to_additive] lemma prod_option_index [add_comm_monoid M] [comm_monoid N] (f : option α →₀ M) (b : option α → M → N) (h_zero : ∀ o, b o 0 = 1) (h_add : ∀ o m₁ m₂, b o (m₁ + m₂) = b o m₁ * b o m₂) : f.prod b = b none (f none) * f.some.prod (λ a, b (option.some a)) := begin apply induction_linear f, { simp [h_zero], }, { intros f₁ f₂ h₁ h₂, rw [finsupp.prod_add_index, h₁, h₂, some_add, finsupp.prod_add_index], simp only [h_add, pi.add_apply, finsupp.coe_add], rw mul_mul_mul_comm, all_goals { simp [h_zero, h_add], }, }, { rintros (_|a) m; simp [h_zero, h_add], } end lemma sum_option_index_smul [semiring R] [add_comm_monoid M] [module R M] (f : option α →₀ R) (b : option α → M) : f.sum (λ o r, r • b o) = f none • b none + f.some.sum (λ a r, r • b (option.some a)) := f.sum_option_index _ (λ _, zero_smul _ _) (λ _ _ _, add_smul _ _ _) end option /-! ### Declarations about `equiv_congr_left` -/ section equiv_congr_left variable [has_zero M] /-- Given `f : α ≃ β`, we can map `l : α →₀ M` to `equiv_map_domain f l : β →₀ M` (computably) by mapping the support forwards and the function backwards. -/ def equiv_map_domain (f : α ≃ β) (l : α →₀ M) : β →₀ M := { support := l.support.map f.to_embedding, to_fun := λ a, l (f.symm a), mem_support_to_fun := λ a, by simp only [finset.mem_map_equiv, mem_support_to_fun]; refl } @[simp] lemma equiv_map_domain_apply (f : α ≃ β) (l : α →₀ M) (b : β) : equiv_map_domain f l b = l (f.symm b) := rfl lemma equiv_map_domain_symm_apply (f : α ≃ β) (l : β →₀ M) (a : α) : equiv_map_domain f.symm l a = l (f a) := rfl @[simp] lemma equiv_map_domain_refl (l : α →₀ M) : equiv_map_domain (equiv.refl _) l = l := by ext x; refl lemma equiv_map_domain_refl' : equiv_map_domain (equiv.refl _) = @id (α →₀ M) := by ext x; refl lemma equiv_map_domain_trans (f : α ≃ β) (g : β ≃ γ) (l : α →₀ M) : equiv_map_domain (f.trans g) l = equiv_map_domain g (equiv_map_domain f l) := by ext x; refl lemma equiv_map_domain_trans' (f : α ≃ β) (g : β ≃ γ) : @equiv_map_domain _ _ M _ (f.trans g) = equiv_map_domain g ∘ equiv_map_domain f := by ext x; refl @[simp] lemma equiv_map_domain_single (f : α ≃ β) (a : α) (b : M) : equiv_map_domain f (single a b) = single (f a) b := by ext x; simp only [single_apply, equiv.apply_eq_iff_eq_symm_apply, equiv_map_domain_apply]; congr @[simp] lemma equiv_map_domain_zero {f : α ≃ β} : equiv_map_domain f (0 : α →₀ M) = (0 : β →₀ M) := by ext x; simp only [equiv_map_domain_apply, coe_zero, pi.zero_apply] lemma equiv_map_domain_eq_map_domain {M} [add_comm_monoid M] (f : α ≃ β) (l : α →₀ M) : equiv_map_domain f l = map_domain f l := by ext x; simp [map_domain_equiv_apply] /-- Given `f : α ≃ β`, the finitely supported function spaces are also in bijection: `(α →₀ M) ≃ (β →₀ M)`. This is the finitely-supported version of `equiv.Pi_congr_left`. -/ def equiv_congr_left (f : α ≃ β) : (α →₀ M) ≃ (β →₀ M) := by refine ⟨equiv_map_domain f, equiv_map_domain f.symm, λ f, _, λ f, _⟩; ext x; simp only [equiv_map_domain_apply, equiv.symm_symm, equiv.symm_apply_apply, equiv.apply_symm_apply] @[simp] lemma equiv_congr_left_apply (f : α ≃ β) (l : α →₀ M) : equiv_congr_left f l = equiv_map_domain f l := rfl @[simp] lemma equiv_congr_left_symm (f : α ≃ β) : (@equiv_congr_left _ _ M _ f).symm = equiv_congr_left f.symm := rfl end equiv_congr_left /-! ### Declarations about `filter` -/ section filter section has_zero variables [has_zero M] (p : α → Prop) (f : α →₀ M) /-- `filter p f` is the function which is `f a` if `p a` is true and 0 otherwise. -/ def filter (p : α → Prop) (f : α →₀ M) : α →₀ M := { to_fun := λ a, if p a then f a else 0, support := f.support.filter (λ a, p a), mem_support_to_fun := λ a, by split_ifs; { simp only [h, mem_filter, mem_support_iff], tauto } } lemma filter_apply (a : α) [D : decidable (p a)] : f.filter p a = if p a then f a else 0 := by rw subsingleton.elim D; refl lemma filter_eq_indicator : ⇑(f.filter p) = set.indicator {x | p x} f := rfl lemma filter_eq_zero_iff : f.filter p = 0 ↔ ∀ x, p x → f x = 0 := by simp only [fun_like.ext_iff, filter_eq_indicator, zero_apply, set.indicator_apply_eq_zero, set.mem_set_of_eq] lemma filter_eq_self_iff : f.filter p = f ↔ ∀ x, f x ≠ 0 → p x := by simp only [fun_like.ext_iff, filter_eq_indicator, set.indicator_apply_eq_self, set.mem_set_of_eq, not_imp_comm] @[simp] lemma filter_apply_pos {a : α} (h : p a) : f.filter p a = f a := if_pos h @[simp] lemma filter_apply_neg {a : α} (h : ¬ p a) : f.filter p a = 0 := if_neg h @[simp] lemma support_filter [D : decidable_pred p] : (f.filter p).support = f.support.filter p := by rw subsingleton.elim D; refl lemma filter_zero : (0 : α →₀ M).filter p = 0 := by rw [← support_eq_empty, support_filter, support_zero, finset.filter_empty] @[simp] lemma filter_single_of_pos {a : α} {b : M} (h : p a) : (single a b).filter p = single a b := (filter_eq_self_iff _ _).2 $ λ x hx, (single_apply_ne_zero.1 hx).1.symm ▸ h @[simp] lemma filter_single_of_neg {a : α} {b : M} (h : ¬ p a) : (single a b).filter p = 0 := (filter_eq_zero_iff _ _).2 $ λ x hpx, single_apply_eq_zero.2 $ λ hxa, absurd hpx (hxa.symm ▸ h) @[to_additive] lemma prod_filter_index [comm_monoid N] (g : α → M → N) : (f.filter p).prod g = ∏ x in (f.filter p).support, g x (f x) := begin refine finset.prod_congr rfl (λ x hx, _), rw [support_filter, finset.mem_filter] at hx, rw [filter_apply_pos _ _ hx.2] end @[simp, to_additive] lemma prod_filter_mul_prod_filter_not [comm_monoid N] (g : α → M → N) : (f.filter p).prod g * (f.filter (λ a, ¬ p a)).prod g = f.prod g := by simp_rw [prod_filter_index, support_filter, prod_filter_mul_prod_filter_not, finsupp.prod] @[simp, to_additive] lemma prod_div_prod_filter [comm_group G] (g : α → M → G) : f.prod g / (f.filter p).prod g = (f.filter (λ a, ¬p a)).prod g := div_eq_of_eq_mul' (prod_filter_mul_prod_filter_not _ _ _).symm end has_zero lemma filter_pos_add_filter_neg [add_zero_class M] (f : α →₀ M) (p : α → Prop) : f.filter p + f.filter (λa, ¬ p a) = f := coe_fn_injective $ set.indicator_self_add_compl {x | p x} f end filter /-! ### Declarations about `frange` -/ section frange variables [has_zero M] /-- `frange f` is the image of `f` on the support of `f`. -/ def frange (f : α →₀ M) : finset M := finset.image f f.support theorem mem_frange {f : α →₀ M} {y : M} : y ∈ f.frange ↔ y ≠ 0 ∧ ∃ x, f x = y := finset.mem_image.trans ⟨λ ⟨x, hx1, hx2⟩, ⟨hx2 ▸ mem_support_iff.1 hx1, x, hx2⟩, λ ⟨hy, x, hx⟩, ⟨x, mem_support_iff.2 (hx.symm ▸ hy), hx⟩⟩ theorem zero_not_mem_frange {f : α →₀ M} : (0:M) ∉ f.frange := λ H, (mem_frange.1 H).1 rfl theorem frange_single {x : α} {y : M} : frange (single x y) ⊆ {y} := λ r hr, let ⟨t, ht1, ht2⟩ := mem_frange.1 hr in ht2 ▸ (by rw single_apply at ht2 ⊢; split_ifs at ht2 ⊢; [exact finset.mem_singleton_self _, cc]) end frange /-! ### Declarations about `subtype_domain` -/ section subtype_domain section zero variables [has_zero M] {p : α → Prop} /-- `subtype_domain p f` is the restriction of the finitely supported function `f` to the subtype `p`. -/ def subtype_domain (p : α → Prop) (f : α →₀ M) : (subtype p →₀ M) := ⟨f.support.subtype p, f ∘ coe, λ a, by simp only [mem_subtype, mem_support_iff]⟩ @[simp] lemma support_subtype_domain [D : decidable_pred p] {f : α →₀ M} : (subtype_domain p f).support = f.support.subtype p := by rw subsingleton.elim D; refl @[simp] lemma subtype_domain_apply {a : subtype p} {v : α →₀ M} : (subtype_domain p v) a = v (a.val) := rfl @[simp] lemma subtype_domain_zero : subtype_domain p (0 : α →₀ M) = 0 := rfl lemma subtype_domain_eq_zero_iff' {f : α →₀ M} : f.subtype_domain p = 0 ↔ ∀ x, p x → f x = 0 := by simp_rw [← support_eq_empty, support_subtype_domain, subtype_eq_empty, not_mem_support_iff] lemma subtype_domain_eq_zero_iff {f : α →₀ M} (hf : ∀ x ∈ f.support , p x) : f.subtype_domain p = 0 ↔ f = 0 := subtype_domain_eq_zero_iff'.trans ⟨λ H, ext $ λ x, if hx : p x then H x hx else not_mem_support_iff.1 $ mt (hf x) hx, λ H x _, by simp [H]⟩ @[to_additive] lemma prod_subtype_domain_index [comm_monoid N] {v : α →₀ M} {h : α → M → N} (hp : ∀x∈v.support, p x) : (v.subtype_domain p).prod (λa b, h a b) = v.prod h := prod_bij (λp _, p.val) (λ _, mem_subtype.1) (λ _ _, rfl) (λ _ _ _ _, subtype.eq) (λ b hb, ⟨⟨b, hp b hb⟩, mem_subtype.2 hb, rfl⟩) end zero section add_zero_class variables [add_zero_class M] {p : α → Prop} {v v' : α →₀ M} @[simp] lemma subtype_domain_add {v v' : α →₀ M} : (v + v').subtype_domain p = v.subtype_domain p + v'.subtype_domain p := ext $ λ _, rfl /-- `subtype_domain` but as an `add_monoid_hom`. -/ def subtype_domain_add_monoid_hom : (α →₀ M) →+ subtype p →₀ M := { to_fun := subtype_domain p, map_zero' := subtype_domain_zero, map_add' := λ _ _, subtype_domain_add } /-- `finsupp.filter` as an `add_monoid_hom`. -/ def filter_add_hom (p : α → Prop) : (α →₀ M) →+ (α →₀ M) := { to_fun := filter p, map_zero' := filter_zero p, map_add' := λ f g, coe_fn_injective $ set.indicator_add {x | p x} f g } @[simp] lemma filter_add {v v' : α →₀ M} : (v + v').filter p = v.filter p + v'.filter p := (filter_add_hom p).map_add v v' end add_zero_class section comm_monoid variables [add_comm_monoid M] {p : α → Prop} lemma subtype_domain_sum {s : finset ι} {h : ι → α →₀ M} : (∑ c in s, h c).subtype_domain p = ∑ c in s, (h c).subtype_domain p := (subtype_domain_add_monoid_hom : _ →+ subtype p →₀ M).map_sum _ s lemma subtype_domain_finsupp_sum [has_zero N] {s : β →₀ N} {h : β → N → α →₀ M} : (s.sum h).subtype_domain p = s.sum (λc d, (h c d).subtype_domain p) := subtype_domain_sum lemma filter_sum (s : finset ι) (f : ι → α →₀ M) : (∑ a in s, f a).filter p = ∑ a in s, filter p (f a) := (filter_add_hom p : (α →₀ M) →+ _).map_sum f s lemma filter_eq_sum (p : α → Prop) [D : decidable_pred p] (f : α →₀ M) : f.filter p = ∑ i in f.support.filter p, single i (f i) := (f.filter p).sum_single.symm.trans $ finset.sum_congr (by rw subsingleton.elim D; refl) $ λ x hx, by rw [filter_apply_pos _ _ (mem_filter.1 hx).2] end comm_monoid section group variables [add_group G] {p : α → Prop} {v v' : α →₀ G} @[simp] lemma subtype_domain_neg : (- v).subtype_domain p = - v.subtype_domain p := ext $ λ _, rfl @[simp] lemma subtype_domain_sub : (v - v').subtype_domain p = v.subtype_domain p - v'.subtype_domain p := ext $ λ _, rfl @[simp] lemma single_neg (a : α) (b : G) : single a (-b) = -single a b := (single_add_hom a : G →+ _).map_neg b @[simp] lemma single_sub (a : α) (b₁ b₂ : G) : single a (b₁ - b₂) = single a b₁ - single a b₂ := (single_add_hom a : G →+ _).map_sub b₁ b₂ @[simp] lemma erase_neg (a : α) (f : α →₀ G) : erase a (-f) = -erase a f := (erase_add_hom a : (_ →₀ G) →+ _).map_neg f @[simp] lemma erase_sub (a : α) (f₁ f₂ : α →₀ G) : erase a (f₁ - f₂) = erase a f₁ - erase a f₂ := (erase_add_hom a : (_ →₀ G) →+ _).map_sub f₁ f₂ @[simp] lemma filter_neg (p : α → Prop) (f : α →₀ G) : filter p (-f) = -filter p f := (filter_add_hom p : (_ →₀ G) →+ _).map_neg f @[simp] lemma filter_sub (p : α → Prop) (f₁ f₂ : α →₀ G) : filter p (f₁ - f₂) = filter p f₁ - filter p f₂ := (filter_add_hom p : (_ →₀ G) →+ _).map_sub f₁ f₂ end group end subtype_domain lemma mem_support_multiset_sum [add_comm_monoid M] {s : multiset (α →₀ M)} (a : α) : a ∈ s.sum.support → ∃f∈s, a ∈ (f : α →₀ M).support := multiset.induction_on s false.elim begin assume f s ih ha, by_cases a ∈ f.support, { exact ⟨f, multiset.mem_cons_self _ _, h⟩ }, { simp only [multiset.sum_cons, mem_support_iff, add_apply, not_mem_support_iff.1 h, zero_add] at ha, rcases ih (mem_support_iff.2 ha) with ⟨f', h₀, h₁⟩, exact ⟨f', multiset.mem_cons_of_mem h₀, h₁⟩ } end lemma mem_support_finset_sum [add_comm_monoid M] {s : finset ι} {h : ι → α →₀ M} (a : α) (ha : a ∈ (∑ c in s, h c).support) : ∃ c ∈ s, a ∈ (h c).support := let ⟨f, hf, hfa⟩ := mem_support_multiset_sum a ha in let ⟨c, hc, eq⟩ := multiset.mem_map.1 hf in ⟨c, hc, eq.symm ▸ hfa⟩ /-! ### Declarations about `curry` and `uncurry` -/ section curry_uncurry variables [add_comm_monoid M] [add_comm_monoid N] /-- Given a finitely supported function `f` from a product type `α × β` to `γ`, `curry f` is the "curried" finitely supported function from `α` to the type of finitely supported functions from `β` to `γ`. -/ protected def curry (f : (α × β) →₀ M) : α →₀ (β →₀ M) := f.sum $ λp c, single p.1 (single p.2 c) @[simp] lemma curry_apply (f : (α × β) →₀ M) (x : α) (y : β) : f.curry x y = f (x, y) := begin have : ∀ (b : α × β), single b.fst (single b.snd (f b)) x y = if b = (x, y) then f b else 0, { rintros ⟨b₁, b₂⟩, simp [single_apply, ite_apply, prod.ext_iff, ite_and], split_ifs; simp [single_apply, *] }, rw [finsupp.curry, sum_apply, sum_apply, finsupp.sum, finset.sum_eq_single, this, if_pos rfl], { intros b hb b_ne, rw [this b, if_neg b_ne] }, { intros hxy, rw [this (x, y), if_pos rfl, not_mem_support_iff.mp hxy] } end lemma sum_curry_index (f : (α × β) →₀ M) (g : α → β → M → N) (hg₀ : ∀ a b, g a b 0 = 0) (hg₁ : ∀a b c₀ c₁, g a b (c₀ + c₁) = g a b c₀ + g a b c₁) : f.curry.sum (λa f, f.sum (g a)) = f.sum (λp c, g p.1 p.2 c) := begin rw [finsupp.curry], transitivity, { exact sum_sum_index (assume a, sum_zero_index) (assume a b₀ b₁, sum_add_index' (assume a, hg₀ _ _) (assume c d₀ d₁, hg₁ _ _ _ _)) }, congr, funext p c, transitivity, { exact sum_single_index sum_zero_index }, exact sum_single_index (hg₀ _ _) end /-- Given a finitely supported function `f` from `α` to the type of finitely supported functions from `β` to `M`, `uncurry f` is the "uncurried" finitely supported function from `α × β` to `M`. -/ protected def uncurry (f : α →₀ (β →₀ M)) : (α × β) →₀ M := f.sum $ λa g, g.sum $ λb c, single (a, b) c /-- `finsupp_prod_equiv` defines the `equiv` between `((α × β) →₀ M)` and `(α →₀ (β →₀ M))` given by currying and uncurrying. -/ def finsupp_prod_equiv : ((α × β) →₀ M) ≃ (α →₀ (β →₀ M)) := by refine ⟨finsupp.curry, finsupp.uncurry, λ f, _, λ f, _⟩; simp only [ finsupp.curry, finsupp.uncurry, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, prod.mk.eta, (single_sum _ _ _).symm, sum_single] lemma filter_curry (f : α × β →₀ M) (p : α → Prop) : (f.filter (λa:α×β, p a.1)).curry = f.curry.filter p := begin rw [finsupp.curry, finsupp.curry, finsupp.sum, finsupp.sum, filter_sum, support_filter, sum_filter], refine finset.sum_congr rfl _, rintros ⟨a₁, a₂⟩ ha, dsimp only, split_ifs, { rw [filter_apply_pos, filter_single_of_pos]; exact h }, { rwa [filter_single_of_neg] } end lemma support_curry [decidable_eq α] (f : α × β →₀ M) : f.curry.support ⊆ f.support.image prod.fst := begin rw ← finset.bUnion_singleton, refine finset.subset.trans support_sum _, refine finset.bUnion_mono (assume a _, support_single_subset) end end curry_uncurry section sum /-- `finsupp.sum_elim f g` maps `inl x` to `f x` and `inr y` to `g y`. -/ def sum_elim {α β γ : Type*} [has_zero γ] (f : α →₀ γ) (g : β →₀ γ) : α ⊕ β →₀ γ := on_finset ((f.support.map ⟨_, sum.inl_injective⟩) ∪ g.support.map ⟨_, sum.inr_injective⟩) (sum.elim f g) (λ ab h, by { cases ab with a b; simp only [sum.elim_inl, sum.elim_inr] at h; simpa }) @[simp] lemma coe_sum_elim {α β γ : Type*} [has_zero γ] (f : α →₀ γ) (g : β →₀ γ) : ⇑(sum_elim f g) = sum.elim f g := rfl lemma sum_elim_apply {α β γ : Type*} [has_zero γ] (f : α →₀ γ) (g : β →₀ γ) (x : α ⊕ β) : sum_elim f g x = sum.elim f g x := rfl lemma sum_elim_inl {α β γ : Type*} [has_zero γ] (f : α →₀ γ) (g : β →₀ γ) (x : α) : sum_elim f g (sum.inl x) = f x := rfl lemma sum_elim_inr {α β γ : Type*} [has_zero γ] (f : α →₀ γ) (g : β →₀ γ) (x : β) : sum_elim f g (sum.inr x) = g x := rfl /-- The equivalence between `(α ⊕ β) →₀ γ` and `(α →₀ γ) × (β →₀ γ)`. This is the `finsupp` version of `equiv.sum_arrow_equiv_prod_arrow`. -/ @[simps apply symm_apply] def sum_finsupp_equiv_prod_finsupp {α β γ : Type*} [has_zero γ] : ((α ⊕ β) →₀ γ) ≃ (α →₀ γ) × (β →₀ γ) := { to_fun := λ f, ⟨f.comap_domain sum.inl (sum.inl_injective.inj_on _), f.comap_domain sum.inr (sum.inr_injective.inj_on _)⟩, inv_fun := λ fg, sum_elim fg.1 fg.2, left_inv := λ f, by { ext ab, cases ab with a b; simp }, right_inv := λ fg, by { ext; simp } } lemma fst_sum_finsupp_equiv_prod_finsupp {α β γ : Type*} [has_zero γ] (f : (α ⊕ β) →₀ γ) (x : α) : (sum_finsupp_equiv_prod_finsupp f).1 x = f (sum.inl x) := rfl lemma snd_sum_finsupp_equiv_prod_finsupp {α β γ : Type*} [has_zero γ] (f : (α ⊕ β) →₀ γ) (y : β) : (sum_finsupp_equiv_prod_finsupp f).2 y = f (sum.inr y) := rfl lemma sum_finsupp_equiv_prod_finsupp_symm_inl {α β γ : Type*} [has_zero γ] (fg : (α →₀ γ) × (β →₀ γ)) (x : α) : (sum_finsupp_equiv_prod_finsupp.symm fg) (sum.inl x) = fg.1 x := rfl lemma sum_finsupp_equiv_prod_finsupp_symm_inr {α β γ : Type*} [has_zero γ] (fg : (α →₀ γ) × (β →₀ γ)) (y : β) : (sum_finsupp_equiv_prod_finsupp.symm fg) (sum.inr y) = fg.2 y := rfl variables [add_monoid M] /-- The additive equivalence between `(α ⊕ β) →₀ M` and `(α →₀ M) × (β →₀ M)`. This is the `finsupp` version of `equiv.sum_arrow_equiv_prod_arrow`. -/ @[simps apply symm_apply] def sum_finsupp_add_equiv_prod_finsupp {α β : Type*} : ((α ⊕ β) →₀ M) ≃+ (α →₀ M) × (β →₀ M) := { map_add' := by { intros, ext; simp only [equiv.to_fun_as_coe, prod.fst_add, prod.snd_add, add_apply, snd_sum_finsupp_equiv_prod_finsupp, fst_sum_finsupp_equiv_prod_finsupp] }, .. sum_finsupp_equiv_prod_finsupp } lemma fst_sum_finsupp_add_equiv_prod_finsupp {α β : Type*} (f : (α ⊕ β) →₀ M) (x : α) : (sum_finsupp_add_equiv_prod_finsupp f).1 x = f (sum.inl x) := rfl lemma snd_sum_finsupp_add_equiv_prod_finsupp {α β : Type*} (f : (α ⊕ β) →₀ M) (y : β) : (sum_finsupp_add_equiv_prod_finsupp f).2 y = f (sum.inr y) := rfl lemma sum_finsupp_add_equiv_prod_finsupp_symm_inl {α β : Type*} (fg : (α →₀ M) × (β →₀ M)) (x : α) : (sum_finsupp_add_equiv_prod_finsupp.symm fg) (sum.inl x) = fg.1 x := rfl lemma sum_finsupp_add_equiv_prod_finsupp_symm_inr {α β : Type*} (fg : (α →₀ M) × (β →₀ M)) (y : β) : (sum_finsupp_add_equiv_prod_finsupp.symm fg) (sum.inr y) = fg.2 y := rfl end sum section variables [has_zero M] [monoid_with_zero R] [mul_action_with_zero R M] @[simp] lemma single_smul (a b : α) (f : α → M) (r : R) : (single a r b) • (f a) = single a (r • f b) b := by by_cases a = b; simp [h] end section variables [monoid G] [mul_action G α] [add_comm_monoid M] /-- Scalar multiplication acting on the domain. This is not an instance as it would conflict with the action on the range. See the `instance_diamonds` test for examples of such conflicts. -/ def comap_has_smul : has_smul G (α →₀ M) := { smul := λ g, map_domain ((•) g) } local attribute [instance] comap_has_smul lemma comap_smul_def (g : G) (f : α →₀ M) : g • f = map_domain ((•) g) f := rfl @[simp] lemma comap_smul_single (g : G) (a : α) (b : M) : g • single a b = single (g • a) b := map_domain_single /-- `finsupp.comap_has_smul` is multiplicative -/ def comap_mul_action : mul_action G (α →₀ M) := { one_smul := λ f, by rw [comap_smul_def, one_smul_eq_id, map_domain_id], mul_smul := λ g g' f, by rw [comap_smul_def, comap_smul_def, comap_smul_def, ←comp_smul_left, map_domain_comp], } local attribute [instance] comap_mul_action /-- `finsupp.comap_has_smul` is distributive -/ def comap_distrib_mul_action : distrib_mul_action G (α →₀ M) := { smul_zero := λ g, by { ext, dsimp [(•)], simp, }, smul_add := λ g f f', by { ext, dsimp [(•)], simp [map_domain_add], }, } end section variables [group G] [mul_action G α] [add_comm_monoid M] local attribute [instance] comap_has_smul comap_mul_action comap_distrib_mul_action /-- When `G` is a group, `finsupp.comap_has_smul` acts by precomposition with the action of `g⁻¹`. -/ @[simp] lemma comap_smul_apply (g : G) (f : α →₀ M) (a : α) : (g • f) a = f (g⁻¹ • a) := begin conv_lhs { rw ←smul_inv_smul g a }, exact map_domain_apply (mul_action.injective g) _ (g⁻¹ • a), end end section instance [monoid R] [add_monoid M] [distrib_mul_action R M] : has_smul R (α →₀ M) := ⟨λa v, v.map_range ((•) a) (smul_zero _)⟩ /-! Throughout this section, some `monoid` and `semiring` arguments are specified with `{}` instead of `[]`. See note [implicit instance arguments]. -/ @[simp] lemma coe_smul {_ : monoid R} [add_monoid M] [distrib_mul_action R M] (b : R) (v : α →₀ M) : ⇑(b • v) = b • v := rfl lemma smul_apply {_ : monoid R} [add_monoid M] [distrib_mul_action R M] (b : R) (v : α →₀ M) (a : α) : (b • v) a = b • (v a) := rfl lemma _root_.is_smul_regular.finsupp {_ : monoid R} [add_monoid M] [distrib_mul_action R M] {k : R} (hk : is_smul_regular M k) : is_smul_regular (α →₀ M) k := λ _ _ h, ext $ λ i, hk (congr_fun h i) instance [monoid R] [nonempty α] [add_monoid M] [distrib_mul_action R M] [has_faithful_smul R M] : has_faithful_smul R (α →₀ M) := { eq_of_smul_eq_smul := λ r₁ r₂ h, let ⟨a⟩ := ‹nonempty α› in eq_of_smul_eq_smul $ λ m : M, by simpa using congr_fun (h (single a m)) a } variables (α M) instance [monoid R] [add_monoid M] [distrib_mul_action R M] : distrib_mul_action R (α →₀ M) := { smul := (•), smul_add := λ a x y, ext $ λ _, smul_add _ _ _, one_smul := λ x, ext $ λ _, one_smul _ _, mul_smul := λ r s x, ext $ λ _, mul_smul _ _ _, smul_zero := λ x, ext $ λ _, smul_zero _ } instance [monoid R] [monoid S] [add_monoid M] [distrib_mul_action R M] [distrib_mul_action S M] [has_smul R S] [is_scalar_tower R S M] : is_scalar_tower R S (α →₀ M) := { smul_assoc := λ r s a, ext $ λ _, smul_assoc _ _ _ } instance [monoid R] [monoid S] [add_monoid M] [distrib_mul_action R M] [distrib_mul_action S M] [smul_comm_class R S M] : smul_comm_class R S (α →₀ M) := { smul_comm := λ r s a, ext $ λ _, smul_comm _ _ _ } instance [monoid R] [add_monoid M] [distrib_mul_action R M] [distrib_mul_action Rᵐᵒᵖ M] [is_central_scalar R M] : is_central_scalar R (α →₀ M) := { op_smul_eq_smul := λ r a, ext $ λ _, op_smul_eq_smul _ _ } instance [semiring R] [add_comm_monoid M] [module R M] : module R (α →₀ M) := { smul := (•), zero_smul := λ x, ext $ λ _, zero_smul _ _, add_smul := λ a x y, ext $ λ _, add_smul _ _ _, .. finsupp.distrib_mul_action α M } variables {α M} {R} lemma support_smul {_ : monoid R} [add_monoid M] [distrib_mul_action R M] {b : R} {g : α →₀ M} : (b • g).support ⊆ g.support := λ a, by { simp only [smul_apply, mem_support_iff, ne.def], exact mt (λ h, h.symm ▸ smul_zero _) } @[simp] lemma support_smul_eq [semiring R] [add_comm_monoid M] [module R M] [no_zero_smul_divisors R M] {b : R} (hb : b ≠ 0) {g : α →₀ M} : (b • g).support = g.support := finset.ext (λ a, by simp [finsupp.smul_apply, hb]) section variables {p : α → Prop} @[simp] lemma filter_smul {_ : monoid R} [add_monoid M] [distrib_mul_action R M] {b : R} {v : α →₀ M} : (b • v).filter p = b • v.filter p := coe_fn_injective $ set.indicator_const_smul {x | p x} b v end lemma map_domain_smul {_ : monoid R} [add_comm_monoid M] [distrib_mul_action R M] {f : α → β} (b : R) (v : α →₀ M) : map_domain f (b • v) = b • map_domain f v := map_domain_map_range _ _ _ _ (smul_add b) @[simp] lemma smul_single {_ : monoid R} [add_monoid M] [distrib_mul_action R M] (c : R) (a : α) (b : M) : c • finsupp.single a b = finsupp.single a (c • b) := map_range_single @[simp] lemma smul_single' {_ : semiring R} (c : R) (a : α) (b : R) : c • finsupp.single a b = finsupp.single a (c * b) := smul_single _ _ _ lemma map_range_smul {_ : monoid R} [add_monoid M] [distrib_mul_action R M] [add_monoid N] [distrib_mul_action R N] {f : M → N} {hf : f 0 = 0} (c : R) (v : α →₀ M) (hsmul : ∀ x, f (c • x) = c • f x) : map_range f hf (c • v) = c • map_range f hf v := begin erw ←map_range_comp, have : (f ∘ (•) c) = ((•) c ∘ f) := funext hsmul, simp_rw this, apply map_range_comp, rw [function.comp_apply, smul_zero, hf], end lemma smul_single_one [semiring R] (a : α) (b : R) : b • single a 1 = single a b := by rw [smul_single, smul_eq_mul, mul_one] lemma comap_domain_smul [add_monoid M] [monoid R] [distrib_mul_action R M] {f : α → β} (r : R) (v : β →₀ M) (hfv : set.inj_on f (f ⁻¹' ↑(v.support))) (hfrv : set.inj_on f (f ⁻¹' ↑((r • v).support)) := hfv.mono $ set.preimage_mono $ finset.coe_subset.mpr support_smul): comap_domain f (r • v) hfrv = r • comap_domain f v hfv := by { ext, refl } /-- A version of `finsupp.comap_domain_smul` that's easier to use. -/ lemma comap_domain_smul_of_injective [add_monoid M] [monoid R] [distrib_mul_action R M] {f : α → β} (hf : function.injective f) (r : R) (v : β →₀ M) : comap_domain f (r • v) (hf.inj_on _) = r • comap_domain f v (hf.inj_on _) := comap_domain_smul _ _ _ _ end lemma sum_smul_index [semiring R] [add_comm_monoid M] {g : α →₀ R} {b : R} {h : α → R → M} (h0 : ∀i, h i 0 = 0) : (b • g).sum h = g.sum (λi a, h i (b * a)) := finsupp.sum_map_range_index h0 lemma sum_smul_index' [monoid R] [add_monoid M] [distrib_mul_action R M] [add_comm_monoid N] {g : α →₀ M} {b : R} {h : α → M → N} (h0 : ∀i, h i 0 = 0) : (b • g).sum h = g.sum (λi c, h i (b • c)) := finsupp.sum_map_range_index h0 /-- A version of `finsupp.sum_smul_index'` for bundled additive maps. -/ lemma sum_smul_index_add_monoid_hom [monoid R] [add_monoid M] [add_comm_monoid N] [distrib_mul_action R M] {g : α →₀ M} {b : R} {h : α → M →+ N} : (b • g).sum (λ a, h a) = g.sum (λ i c, h i (b • c)) := sum_map_range_index (λ i, (h i).map_zero) instance [semiring R] [add_comm_monoid M] [module R M] {ι : Type*} [no_zero_smul_divisors R M] : no_zero_smul_divisors R (ι →₀ M) := ⟨λ c f h, or_iff_not_imp_left.mpr (λ hc, finsupp.ext (λ i, (smul_eq_zero.mp (finsupp.ext_iff.mp h i)).resolve_left hc))⟩ section distrib_mul_action_hom variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid N] [distrib_mul_action R M] [distrib_mul_action R N] /-- `finsupp.single` as a `distrib_mul_action_hom`. See also `finsupp.lsingle` for the version as a linear map. -/ def distrib_mul_action_hom.single (a : α) : M →+[R] (α →₀ M) := { map_smul' := λ k m, by simp only [add_monoid_hom.to_fun_eq_coe, single_add_hom_apply, smul_single], .. single_add_hom a } lemma distrib_mul_action_hom_ext {f g : (α →₀ M) →+[R] N} (h : ∀ (a : α) (m : M), f (single a m) = g (single a m)) : f = g := distrib_mul_action_hom.to_add_monoid_hom_injective $ add_hom_ext h /-- See note [partially-applied ext lemmas]. -/ @[ext] lemma distrib_mul_action_hom_ext' {f g : (α →₀ M) →+[R] N} (h : ∀ (a : α), f.comp (distrib_mul_action_hom.single a) = g.comp (distrib_mul_action_hom.single a)) : f = g := distrib_mul_action_hom_ext $ λ a, distrib_mul_action_hom.congr_fun (h a) end distrib_mul_action_hom section variables [has_zero R] /-- The `finsupp` version of `pi.unique`. -/ instance unique_of_right [subsingleton R] : unique (α →₀ R) := { uniq := λ l, ext $ λ i, subsingleton.elim _ _, .. finsupp.inhabited } /-- The `finsupp` version of `pi.unique_of_is_empty`. -/ instance unique_of_left [is_empty α] : unique (α →₀ R) := { uniq := λ l, ext is_empty_elim, .. finsupp.inhabited } end /-- Given an `add_comm_monoid M` and `s : set α`, `restrict_support_equiv s M` is the `equiv` between the subtype of finitely supported functions with support contained in `s` and the type of finitely supported functions from `s`. -/ def restrict_support_equiv (s : set α) (M : Type*) [add_comm_monoid M] : {f : α →₀ M // ↑f.support ⊆ s } ≃ (s →₀ M) := begin refine ⟨λf, subtype_domain (λx, x ∈ s) f.1, λ f, ⟨f.map_domain subtype.val, _⟩, _, _⟩, { refine set.subset.trans (finset.coe_subset.2 map_domain_support) _, rw [finset.coe_image, set.image_subset_iff], exact assume x hx, x.2 }, { rintros ⟨f, hf⟩, apply subtype.eq, ext a, dsimp only, refine classical.by_cases (assume h : a ∈ set.range (subtype.val : s → α), _) (assume h, _), { rcases h with ⟨x, rfl⟩, rw [map_domain_apply subtype.val_injective, subtype_domain_apply] }, { convert map_domain_notin_range _ _ h, rw [← not_mem_support_iff], refine mt _ h, exact assume ha, ⟨⟨a, hf ha⟩, rfl⟩ } }, { assume f, ext ⟨a, ha⟩, dsimp only, rw [subtype_domain_apply, map_domain_apply subtype.val_injective] } end /-- Given `add_comm_monoid M` and `e : α ≃ β`, `dom_congr e` is the corresponding `equiv` between `α →₀ M` and `β →₀ M`. This is `finsupp.equiv_congr_left` as an `add_equiv`. -/ @[simps apply] protected def dom_congr [add_comm_monoid M] (e : α ≃ β) : (α →₀ M) ≃+ (β →₀ M) := { to_fun := equiv_map_domain e, inv_fun := equiv_map_domain e.symm, left_inv := λ v, begin simp only [← equiv_map_domain_trans, equiv.self_trans_symm], exact equiv_map_domain_refl _ end, right_inv := begin assume v, simp only [← equiv_map_domain_trans, equiv.symm_trans_self], exact equiv_map_domain_refl _ end, map_add' := λ a b, by simp only [equiv_map_domain_eq_map_domain]; exact map_domain_add } @[simp] lemma dom_congr_refl [add_comm_monoid M] : finsupp.dom_congr (equiv.refl α) = add_equiv.refl (α →₀ M) := add_equiv.ext $ λ _, equiv_map_domain_refl _ @[simp] lemma dom_congr_symm [add_comm_monoid M] (e : α ≃ β) : (finsupp.dom_congr e).symm = (finsupp.dom_congr e.symm : (β →₀ M) ≃+ (α →₀ M)):= add_equiv.ext $ λ _, rfl @[simp] lemma dom_congr_trans [add_comm_monoid M] (e : α ≃ β) (f : β ≃ γ) : (finsupp.dom_congr e).trans (finsupp.dom_congr f) = (finsupp.dom_congr (e.trans f) : (α →₀ M) ≃+ _) := add_equiv.ext $ λ _, (equiv_map_domain_trans _ _ _).symm end finsupp namespace finsupp /-! ### Declarations about sigma types -/ section sigma variables {αs : ι → Type*} [has_zero M] (l : (Σ i, αs i) →₀ M) /-- Given `l`, a finitely supported function from the sigma type `Σ (i : ι), αs i` to `M` and an index element `i : ι`, `split l i` is the `i`th component of `l`, a finitely supported function from `as i` to `M`. This is the `finsupp` version of `sigma.curry`. -/ def split (i : ι) : αs i →₀ M := l.comap_domain (sigma.mk i) (λ x1 x2 _ _ hx, heq_iff_eq.1 (sigma.mk.inj hx).2) lemma split_apply (i : ι) (x : αs i) : split l i x = l ⟨i, x⟩ := begin dunfold split, rw comap_domain_apply end /-- Given `l`, a finitely supported function from the sigma type `Σ (i : ι), αs i` to `β`, `split_support l` is the finset of indices in `ι` that appear in the support of `l`. -/ def split_support : finset ι := l.support.image sigma.fst lemma mem_split_support_iff_nonzero (i : ι) : i ∈ split_support l ↔ split l i ≠ 0 := begin rw [split_support, mem_image, ne.def, ← support_eq_empty, ← ne.def, ← finset.nonempty_iff_ne_empty, split, comap_domain, finset.nonempty], simp only [exists_prop, finset.mem_preimage, exists_and_distrib_right, exists_eq_right, mem_support_iff, sigma.exists, ne.def] end /-- Given `l`, a finitely supported function from the sigma type `Σ i, αs i` to `β` and an `ι`-indexed family `g` of functions from `(αs i →₀ β)` to `γ`, `split_comp` defines a finitely supported function from the index type `ι` to `γ` given by composing `g i` with `split l i`. -/ def split_comp [has_zero N] (g : Π i, (αs i →₀ M) → N) (hg : ∀ i x, x = 0 ↔ g i x = 0) : ι →₀ N := { support := split_support l, to_fun := λ i, g i (split l i), mem_support_to_fun := begin intros i, rw [mem_split_support_iff_nonzero, not_iff_not, hg], end } lemma sigma_support : l.support = l.split_support.sigma (λ i, (l.split i).support) := by simp only [finset.ext_iff, split_support, split, comap_domain, mem_image, mem_preimage, sigma.forall, mem_sigma]; tauto lemma sigma_sum [add_comm_monoid N] (f : (Σ (i : ι), αs i) → M → N) : l.sum f = ∑ i in split_support l, (split l i).sum (λ (a : αs i) b, f ⟨i, a⟩ b) := by simp only [sum, sigma_support, sum_sigma, split_apply] variables {η : Type*} [fintype η] {ιs : η → Type*} [has_zero α] /-- On a `fintype η`, `finsupp.split` is an equivalence between `(Σ (j : η), ιs j) →₀ α` and `Π j, (ιs j →₀ α)`. This is the `finsupp` version of `equiv.Pi_curry`. -/ noncomputable def sigma_finsupp_equiv_pi_finsupp : ((Σ j, ιs j) →₀ α) ≃ Π j, (ιs j →₀ α) := { to_fun := split, inv_fun := λ f, on_finset (finset.univ.sigma (λ j, (f j).support)) (λ ji, f ji.1 ji.2) (λ g hg, finset.mem_sigma.mpr ⟨finset.mem_univ _, mem_support_iff.mpr hg⟩), left_inv := λ f, by { ext, simp [split] }, right_inv := λ f, by { ext, simp [split] } } @[simp] lemma sigma_finsupp_equiv_pi_finsupp_apply (f : (Σ j, ιs j) →₀ α) (j i) : sigma_finsupp_equiv_pi_finsupp f j i = f ⟨j, i⟩ := rfl /-- On a `fintype η`, `finsupp.split` is an additive equivalence between `(Σ (j : η), ιs j) →₀ α` and `Π j, (ιs j →₀ α)`. This is the `add_equiv` version of `finsupp.sigma_finsupp_equiv_pi_finsupp`. -/ noncomputable def sigma_finsupp_add_equiv_pi_finsupp {α : Type*} {ιs : η → Type*} [add_monoid α] : ((Σ j, ιs j) →₀ α) ≃+ Π j, (ιs j →₀ α) := { map_add' := λ f g, by { ext, simp }, .. sigma_finsupp_equiv_pi_finsupp } @[simp] lemma sigma_finsupp_add_equiv_pi_finsupp_apply {α : Type*} {ιs : η → Type*} [add_monoid α] (f : (Σ j, ιs j) →₀ α) (j i) : sigma_finsupp_add_equiv_pi_finsupp f j i = f ⟨j, i⟩ := rfl end sigma end finsupp section cast_finsupp variables [has_zero M] (f : α →₀ M) namespace nat @[simp, norm_cast] lemma cast_finsupp_prod [comm_semiring R] (g : α → M → ℕ) : (↑(f.prod g) : R) = f.prod (λ a b, ↑(g a b)) := nat.cast_prod _ _ @[simp, norm_cast] lemma cast_finsupp_sum [comm_semiring R] (g : α → M → ℕ) : (↑(f.sum g) : R) = f.sum (λ a b, ↑(g a b)) := nat.cast_sum _ _ end nat namespace int @[simp, norm_cast] lemma cast_finsupp_prod [comm_ring R] (g : α → M → ℤ) : (↑(f.prod g) : R) = f.prod (λ a b, ↑(g a b)) := int.cast_prod _ _ @[simp, norm_cast] lemma cast_finsupp_sum [comm_ring R] (g : α → M → ℤ) : (↑(f.sum g) : R) = f.sum (λ a b, ↑(g a b)) := int.cast_sum _ _ end int namespace rat @[simp, norm_cast] lemma cast_finsupp_sum [division_ring R] [char_zero R] (g : α → M → ℚ) : (↑(f.sum g) : R) = f.sum (λ a b, g a b) := cast_sum _ _ @[simp, norm_cast] lemma cast_finsupp_prod [field R] [char_zero R] (g : α → M → ℚ) : (↑(f.prod g) : R) = f.prod (λ a b, g a b) := cast_prod _ _ end rat end cast_finsupp
0cdeee621d94f0cfa713fb9daa1bd2e8032f39e2
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/topology/uniform_space/abstract_completion.lean
f8d32562590540023cf0d726ecb8f3785bcae06e
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
11,141
lean
/- Copyright (c) 2019 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import topology.uniform_space.uniform_embedding /-! # Abstract theory of Hausdorff completions of uniform spaces This file characterizes Hausdorff completions of a uniform space α as complete Hausdorff spaces equipped with a map from α which has dense image and induce the original uniform structure on α. Assuming these properties we "extend" uniformly continuous maps from α to complete Hausdorff spaces to the completions of α. This is the universal property expected from a completion. It is then used to extend uniformly continuous maps from α to α' to maps between completions of α and α'. This file does not construct any such completion, it only study consequences of their existence. The first advantage is that formal properties are clearly highlighted without interference from construction details. The second advantage is that this framework can then be used to compare different completion constructions. See `topology/uniform_space/compare_reals` for an example. Of course the comparison comes from the universal property as usual. A general explicit construction of completions is done in `uniform_space/completion`, leading to a functor from uniform spaces to complete Hausdorff uniform spaces that is left adjoint to the inclusion, see `uniform_space/UniformSpace` for the category packaging. ## Implementation notes A tiny technical advantage of using a characteristic predicate such as the properties listed in `abstract_completion` instead of stating the universal property is that the universal property derived from the predicate is more universe polymorphic. ## References We don't know any traditional text discussing this. Real world mathematics simply silently identify the results of any two constructions that lead to something one could reasonnably call a completion. ## Tags uniform spaces, completion, universal property -/ noncomputable theory local attribute [instance, priority 10] classical.prop_decidable open filter set function universes u /-- A completion of `α` is the data of a complete separated uniform space (from the same universe) and a map from `α` with dense range and inducing the original uniform structure on `α`. -/ structure abstract_completion (α : Type u) [uniform_space α] := (space : Type u) (coe : α → space) (uniform_struct : uniform_space space) (complete : complete_space space) (separation : separated_space space) (uniform_inducing : uniform_inducing coe) (dense : dense_range coe) local attribute [instance] abstract_completion.uniform_struct abstract_completion.complete abstract_completion.separation namespace abstract_completion variables {α : Type*} [uniform_space α] (pkg : abstract_completion α) local notation `hatα` := pkg.space local notation `ι` := pkg.coe lemma closure_range : closure (range ι) = univ := pkg.dense.closure_range lemma dense_inducing : dense_inducing ι := ⟨pkg.uniform_inducing.inducing, pkg.dense⟩ lemma uniform_continuous_coe : uniform_continuous ι := uniform_inducing.uniform_continuous pkg.uniform_inducing lemma continuous_coe : continuous ι := pkg.uniform_continuous_coe.continuous @[elab_as_eliminator] lemma induction_on {p : hatα → Prop} (a : hatα) (hp : is_closed {a | p a}) (ih : ∀ a, p (ι a)) : p a := is_closed_property pkg.dense hp ih a variables {β : Type*} [uniform_space β] protected lemma funext [t2_space β] {f g : hatα → β} (hf : continuous f) (hg : continuous g) (h : ∀ a, f (ι a) = g (ι a)) : f = g := funext $ assume a, pkg.induction_on a (is_closed_eq hf hg) h section extend /-- Extension of maps to completions -/ protected def extend (f : α → β) : hatα → β := if uniform_continuous f then pkg.dense_inducing.extend f else λ x, f (pkg.dense.some x) variables {f : α → β} lemma extend_def (hf : uniform_continuous f) : pkg.extend f = pkg.dense_inducing.extend f := if_pos hf lemma extend_coe [t2_space β] (hf : uniform_continuous f) (a : α) : (pkg.extend f) (ι a) = f a := begin rw pkg.extend_def hf, exact pkg.dense_inducing.extend_eq hf.continuous a end variables [complete_space β] [separated_space β] lemma uniform_continuous_extend : uniform_continuous (pkg.extend f) := begin by_cases hf : uniform_continuous f, { rw pkg.extend_def hf, exact uniform_continuous_uniformly_extend (pkg.uniform_inducing) (pkg.dense) hf }, { change uniform_continuous (ite _ _ _), rw if_neg hf, exact uniform_continuous_of_const (assume a b, by congr) } end lemma continuous_extend : continuous (pkg.extend f) := pkg.uniform_continuous_extend.continuous lemma extend_unique (hf : uniform_continuous f) {g : hatα → β} (hg : uniform_continuous g) (h : ∀ a : α, f a = g (ι a)) : pkg.extend f = g := begin apply pkg.funext pkg.continuous_extend hg.continuous, simpa only [pkg.extend_coe hf] using h end @[simp] lemma extend_comp_coe {f : hatα → β} (hf : uniform_continuous f) : pkg.extend (f ∘ ι) = f := funext $ λ x, pkg.induction_on x (is_closed_eq pkg.continuous_extend hf.continuous) (λ y, pkg.extend_coe (hf.comp $ pkg.uniform_continuous_coe) y) end extend section map_sec variables (pkg' : abstract_completion β) local notation `hatβ` := pkg'.space local notation `ι'` := pkg'.coe /-- Lifting maps to completions -/ protected def map (f : α → β) : hatα → hatβ := pkg.extend (ι' ∘ f) local notation `map` := pkg.map pkg' variables (f : α → β) lemma uniform_continuous_map : uniform_continuous (map f) := pkg.uniform_continuous_extend lemma continuous_map : continuous (map f) := pkg.continuous_extend variables {f} @[simp] lemma map_coe (hf : uniform_continuous f) (a : α) : map f (ι a) = ι' (f a) := pkg.extend_coe (pkg'.uniform_continuous_coe.comp hf) a lemma map_unique {f : α → β} {g : hatα → hatβ} (hg : uniform_continuous g) (h : ∀ a, ι' (f a) = g (ι a)) : map f = g := pkg.funext (pkg.continuous_map _ _) hg.continuous $ begin intro a, change pkg.extend (ι' ∘ f) _ = _, simp only [(∘), h], rw [pkg.extend_coe (hg.comp pkg.uniform_continuous_coe)] end @[simp] lemma map_id : pkg.map pkg id = id := pkg.map_unique pkg uniform_continuous_id (assume a, rfl) variables {γ : Type*} [uniform_space γ] lemma extend_map [complete_space γ] [separated_space γ] {f : β → γ} {g : α → β} (hf : uniform_continuous f) (hg : uniform_continuous g) : pkg'.extend f ∘ map g = pkg.extend (f ∘ g) := pkg.funext (pkg'.continuous_extend.comp (pkg.continuous_map pkg' _)) pkg.continuous_extend $ λ a, by rw [pkg.extend_coe (hf.comp hg), comp_app, pkg.map_coe pkg' hg, pkg'.extend_coe hf] variables (pkg'' : abstract_completion γ) lemma map_comp {g : β → γ} {f : α → β} (hg : uniform_continuous g) (hf : uniform_continuous f) : (pkg'.map pkg'' g) ∘ (pkg.map pkg' f) = pkg.map pkg'' (g ∘ f) := pkg.extend_map pkg' (pkg''.uniform_continuous_coe.comp hg) hf end map_sec section compare -- We can now compare two completion packages for the same uniform space variables (pkg' : abstract_completion α) /-- The comparison map between two completions of the same uniform space. -/ def compare : pkg.space → pkg'.space := pkg.extend pkg'.coe lemma uniform_continuous_compare : uniform_continuous (pkg.compare pkg') := pkg.uniform_continuous_extend lemma compare_coe (a : α) : pkg.compare pkg' (pkg.coe a) = pkg'.coe a := pkg.extend_coe pkg'.uniform_continuous_coe a lemma inverse_compare : (pkg.compare pkg') ∘ (pkg'.compare pkg) = id := begin have uc := pkg.uniform_continuous_compare pkg', have uc' := pkg'.uniform_continuous_compare pkg, apply pkg'.funext (uc.comp uc').continuous continuous_id, intro a, rw [comp_app, pkg'.compare_coe pkg, pkg.compare_coe pkg'], refl end /-- The bijection between two completions of the same uniform space. -/ def compare_equiv : pkg.space ≃ pkg'.space := { to_fun := pkg.compare pkg', inv_fun := pkg'.compare pkg, left_inv := congr_fun (pkg'.inverse_compare pkg), right_inv := congr_fun (pkg.inverse_compare pkg') } lemma uniform_continuous_compare_equiv : uniform_continuous (pkg.compare_equiv pkg') := pkg.uniform_continuous_compare pkg' lemma uniform_continuous_compare_equiv_symm : uniform_continuous (pkg.compare_equiv pkg').symm := pkg'.uniform_continuous_compare pkg end compare section prod variables (pkg' : abstract_completion β) local notation `hatβ` := pkg'.space local notation `ι'` := pkg'.coe /-- Products of completions -/ protected def prod : abstract_completion (α × β) := { space := hatα × hatβ, coe := λ p, ⟨ι p.1, ι' p.2⟩, uniform_struct := prod.uniform_space, complete := by apply_instance, separation := by apply_instance, uniform_inducing := uniform_inducing.prod pkg.uniform_inducing pkg'.uniform_inducing, dense := pkg.dense.prod_map pkg'.dense } end prod section extension₂ variables (pkg' : abstract_completion β) local notation `hatβ` := pkg'.space local notation `ι'` := pkg'.coe variables {γ : Type*} [uniform_space γ] open function /-- Extend two variable map to completions. -/ protected def extend₂ (f : α → β → γ) : hatα → hatβ → γ := curry $ (pkg.prod pkg').extend (uncurry f) variables [separated_space γ] {f : α → β → γ} lemma extension₂_coe_coe (hf : uniform_continuous $ uncurry f) (a : α) (b : β) : pkg.extend₂ pkg' f (ι a) (ι' b) = f a b := show (pkg.prod pkg').extend (uncurry f) ((pkg.prod pkg').coe (a, b)) = uncurry f (a, b), from (pkg.prod pkg').extend_coe hf _ variables [complete_space γ] (f) lemma uniform_continuous_extension₂ : uniform_continuous₂ (pkg.extend₂ pkg' f) := begin rw [uniform_continuous₂_def, abstract_completion.extend₂, uncurry_curry], apply uniform_continuous_extend end end extension₂ section map₂ variables (pkg' : abstract_completion β) local notation `hatβ` := pkg'.space local notation `ι'` := pkg'.coe variables {γ : Type*} [uniform_space γ] (pkg'' : abstract_completion γ) local notation `hatγ` := pkg''.space local notation `ι''` := pkg''.coe local notation f `∘₂` g := bicompr f g /-- Lift two variable maps to completions. -/ protected def map₂ (f : α → β → γ) : hatα → hatβ → hatγ := pkg.extend₂ pkg' (pkg''.coe ∘₂ f) lemma uniform_continuous_map₂ (f : α → β → γ) : uniform_continuous₂ (pkg.map₂ pkg' pkg'' f) := pkg.uniform_continuous_extension₂ pkg' _ lemma continuous_map₂ {δ} [topological_space δ] {f : α → β → γ} {a : δ → hatα} {b : δ → hatβ} (ha : continuous a) (hb : continuous b) : continuous (λd:δ, pkg.map₂ pkg' pkg'' f (a d) (b d)) := ((pkg.uniform_continuous_map₂ pkg' pkg'' f).continuous.comp (continuous.prod_mk ha hb) : _) lemma map₂_coe_coe (a : α) (b : β) (f : α → β → γ) (hf : uniform_continuous₂ f) : pkg.map₂ pkg' pkg'' f (ι a) (ι' b) = ι'' (f a b) := pkg.extension₂_coe_coe pkg' (pkg''.uniform_continuous_coe.comp hf) a b end map₂ end abstract_completion
153e473ecaa9b8638ee080ae63f7ce926a274a3f
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/homotopy/equiv.lean
1e353c25bcae37b277117538e4d5551566ba3cb4
[ "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,139
lean
/- Copyright (c) 2021 Shing Tak Lam. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Shing Tak Lam -/ import topology.homotopy.basic /-! # Homotopy equivalences between topological spaces In this file, we define homotopy equivalences between topological spaces `X` and `Y` as a pair of functions `f : C(X, Y)` and `g : C(Y, X)` such that `f.comp g` and `g.comp f` are both homotopic to `id`. ## Main definitions - `continuous_map.homotopy_equiv` is the type of homotopy equivalences between topological spaces. ## Notation We introduce the notation `X ≃ₕ Y` for `continuous_map.homotopy_equiv X Y` in the `continuous_map` locale. -/ universes u v w variables {X : Type u} {Y : Type v} {Z : Type w} variables [topological_space X] [topological_space Y] [topological_space Z] namespace continuous_map /-- A homotopy equivalence between topological spaces `X` and `Y` are a pair of functions `to_fun : C(X, Y)` and `inv_fun : C(Y, X)` such that `to_fun.comp inv_fun` and `inv_fun.comp to_fun` are both homotopic to `id`. -/ @[ext] structure homotopy_equiv (X : Type u) (Y : Type v) [topological_space X] [topological_space Y] := (to_fun : C(X, Y)) (inv_fun : C(Y, X)) (left_inv : (inv_fun.comp to_fun).homotopic (continuous_map.id X)) (right_inv : (to_fun.comp inv_fun).homotopic (continuous_map.id Y)) localized "infix ` ≃ₕ `:25 := continuous_map.homotopy_equiv" in continuous_map namespace homotopy_equiv instance : has_coe_to_fun (homotopy_equiv X Y) (λ _, X → Y) := ⟨λ h, h.to_fun⟩ @[simp] lemma to_fun_eq_coe (h : homotopy_equiv X Y) : (h.to_fun : X → Y) = h := rfl @[continuity] lemma continuous (h : homotopy_equiv X Y) : continuous h := h.to_fun.continuous end homotopy_equiv end continuous_map open_locale continuous_map namespace homeomorph /-- Any homeomorphism is a homotopy equivalence. -/ def to_homotopy_equiv (h : X ≃ₜ Y) : X ≃ₕ Y := { to_fun := ⟨h⟩, inv_fun := ⟨h.symm⟩, left_inv := by { convert continuous_map.homotopic.refl _, ext, simp }, right_inv := by { convert continuous_map.homotopic.refl _, ext, simp } } @[simp] lemma coe_to_homotopy_equiv (h : X ≃ₜ Y) : ⇑(h.to_homotopy_equiv) = h := rfl end homeomorph namespace continuous_map namespace homotopy_equiv /-- If `X` is homotopy equivalent to `Y`, then `Y` is homotopy equivalent to `X`. -/ def symm (h : X ≃ₕ Y) : Y ≃ₕ X := { to_fun := h.inv_fun, inv_fun := h.to_fun, left_inv := h.right_inv, right_inv := h.left_inv } @[simp] lemma coe_inv_fun (h : homotopy_equiv X Y) : (⇑h.inv_fun : Y → X) = ⇑h.symm := rfl /-- See Note [custom simps projection]. We need to specify this projection explicitly in this case, because it is a composition of multiple projections. -/ def simps.apply (h : X ≃ₕ Y) : X → Y := h /-- See Note [custom simps projection]. We need to specify this projection explicitly in this case, because it is a composition of multiple projections. -/ def simps.symm_apply (h : X ≃ₕ Y) : Y → X := h.symm initialize_simps_projections homotopy_equiv (to_fun_to_fun -> apply, inv_fun_to_fun -> symm_apply, -to_fun, -inv_fun) /-- Any topological space is homotopy equivalent to itself. -/ @[simps] def refl (X : Type u) [topological_space X] : X ≃ₕ X := (homeomorph.refl X).to_homotopy_equiv instance : inhabited (homotopy_equiv unit unit) := ⟨refl unit⟩ /-- If `X` is homotopy equivalent to `Y`, and `Y` is homotopy equivalent to `Z`, then `X` is homotopy equivalent to `Z`. -/ @[simps] def trans (h₁ : X ≃ₕ Y) (h₂ : Y ≃ₕ Z) : X ≃ₕ Z := { to_fun := h₂.to_fun.comp h₁.to_fun, inv_fun := h₁.inv_fun.comp h₂.inv_fun, left_inv := begin refine homotopic.trans _ h₁.left_inv, change ((h₁.inv_fun.comp h₂.inv_fun).comp (h₂.to_fun.comp h₁.to_fun)) with h₁.inv_fun.comp ((h₂.inv_fun.comp h₂.to_fun).comp h₁.to_fun), refine homotopic.hcomp _ (homotopic.refl _), refine homotopic.trans ((homotopic.refl _).hcomp h₂.left_inv) _, -- simp, rw continuous_map.id_comp, end, right_inv := begin refine homotopic.trans _ h₂.right_inv, change ((h₂.to_fun.comp h₁.to_fun).comp (h₁.inv_fun.comp h₂.inv_fun)) with h₂.to_fun.comp ((h₁.to_fun.comp h₁.inv_fun).comp h₂.inv_fun), refine homotopic.hcomp _ (homotopic.refl _), refine homotopic.trans ((homotopic.refl _).hcomp h₁.right_inv) _, rw id_comp, end } lemma symm_trans (h₁ : X ≃ₕ Y) (h₂ : Y ≃ₕ Z) : (h₁.trans h₂).symm = h₂.symm.trans h₁.symm := by ext; refl end homotopy_equiv end continuous_map open continuous_map namespace homeomorph @[simp] lemma refl_to_homotopy_equiv (X : Type u) [topological_space X] : (homeomorph.refl X).to_homotopy_equiv = homotopy_equiv.refl X := rfl @[simp] lemma symm_to_homotopy_equiv (h : X ≃ₜ Y) : h.symm.to_homotopy_equiv = h.to_homotopy_equiv.symm := rfl @[simp] lemma trans_to_homotopy_equiv (h₀ : X ≃ₜ Y) (h₁ : Y ≃ₜ Z) : (h₀.trans h₁).to_homotopy_equiv = h₀.to_homotopy_equiv.trans h₁.to_homotopy_equiv := rfl end homeomorph
28e65304cf089f70e1a3f1429d37ccaf45676eae
c31182a012eec69da0a1f6c05f42b0f0717d212d
/src/for_mathlib/simplicial/complex.lean
da9f23ea6633ced10016477a949af008d9e6d4b3
[]
no_license
Ja1941/lean-liquid
fbec3ffc7fc67df1b5ca95b7ee225685ab9ffbdc
8e80ed0cbdf5145d6814e833a674eaf05a1495c1
refs/heads/master
1,689,437,983,362
1,628,362,719,000
1,628,362,719,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,308
lean
import data.fintype.card import algebra.module.hom import algebra.big_operators import algebraic_topology.simplicial_object import algebra.homology.homological_complex namespace category_theory variables {C : Type*} [category C] [preadditive C] (M : cosimplicial_object C) namespace cosimplicial_object open simplex_category finset add_monoid_hom category_theory.preadditive open_locale simplicial big_operators /-- The coboundary map in the alternating face map cochain complex. -/ def coboundary (n : ℕ) : M.obj [n] ⟶ M.obj [n+1] := ∑ i : fin (n+2), (-1:ℤ)^(i:ℕ) • (M.δ i) lemma coboundary_zero : coboundary M 0 = (M.δ 0) - (M.δ 1) := begin simp only [coboundary, fin.sum_univ_succ, fin.default_eq_zero, fin.coe_zero, one_gsmul, fin.coe_succ, univ_unique, neg_gsmul, pow_one, fin.succ_zero_eq_one, sum_singleton, pow_zero, sub_eq_add_neg] end @[reassoc] lemma coboundary_coboundary (n : ℕ) : coboundary M n ≫ coboundary M (n+1) = 0 := begin let s : finset (fin (n+2) × fin (n+3)) := univ.filter (λ ij, (ij.2:ℕ) ≤ ij.1), calc coboundary M n ≫ coboundary M (n+1) = comp_hom (∑ (i:fin (n+2)), (-1:ℤ)^(i:ℕ) • (M.δ i)) (∑ (i:fin (n+3)), (-1:ℤ)^(i:ℕ) • (M.δ i)) : rfl ... = ∑ (i : fin (n+2)) (j : fin (n+3)), (-1:ℤ)^(i+j:ℕ) • ((M.δ i) ≫ (M.δ j)) : _ ... = ∑ ij : fin (n+2) × fin (n+3), (-1:ℤ)^(ij.1+ij.2:ℕ) • ((M.δ ij.1) ≫ (M.δ ij.2)) : by rw [← univ_product_univ, sum_product] ... = (∑ ij in s, (-1:ℤ)^(ij.1+ij.2:ℕ) • ((M.δ ij.1) ≫ (M.δ ij.2))) + (∑ ij in sᶜ, (-1:ℤ)^(ij.1+ij.2:ℕ) • ((M.δ ij.1) ≫ (M.δ ij.2))) : by rw sum_add_sum_compl ... = 0 : _, { simp only [map_sum, map_gsmul, finset_sum_apply, smul_apply, smul_sum, pow_add, mul_smul], refl, }, erw [← eq_neg_iff_add_eq_zero, ← finset.sum_neg_distrib], -- The sums are equal because we can give a bijection -- between the indexing sets, such that corresponding terms are equal. -- We get 4 goals. All the substance is in the second goal. refine (finset.sum_bij (λ (ij : fin (n+2) × fin (n+3)) hij, (ij.2.cast_lt (lt_of_le_of_lt (mem_filter.mp hij).right ij.1.is_lt), ij.1.succ)) _ _ _ _), { -- Show that our function is well-defined rintro ⟨i,j⟩ hij, simp only [mem_filter, true_and, mem_univ, not_le, mem_compl, fin.coe_succ], dsimp [s] at hij ⊢, simp only [true_and, mem_filter, mem_univ] at hij, apply nat.lt_of_succ_le, apply nat.succ_le_succ, exact hij, }, { -- The core of the proof. -- After all, we have to use the simplicial identity somewhere. rintros ⟨i,j⟩ hij_aux, have hij := (mem_filter.mp hij_aux).2, dsimp at hij ⊢, rw [δ_comp_δ], swap, { rwa ← fin.coe_fin_le }, rw [← neg_gsmul], congr' 1, calc (-1) ^ (i + j : ℕ) = - (-1) ^ (i + j + 1 : ℕ) : _ ... = - (-1) ^ (j + (i + 1) : ℕ) : _ ... = _ : _, { rw [pow_succ, neg_one_mul, neg_neg] }, { rw [add_assoc, add_left_comm] }, { simp only [fin.coe_succ] } }, { -- Show that our function is injective rintro ⟨i₁, j₁⟩ ⟨i₂, j₂⟩ hij₁ hij₂ h, rw [prod.mk.inj_iff, fin.eq_iff_veq, fin.eq_iff_veq] at h ⊢, simp at h, rwa [and_comm] at h, }, { -- Show that our function is surjective rintro ⟨i,j⟩ hij, refine ⟨⟨j.pred _, i.cast_succ⟩, _, _⟩, { intro H, rw [H, mem_compl, mem_filter, not_and] at hij, exact hij (mem_univ _) (nat.zero_le _) }, { cases i, simp only [true_and, mem_compl, mem_filter, mem_univ, not_le, fin.coe_pred] at hij ⊢, exact nat.le_pred_of_lt hij, }, { ext; simp only [fin.succ_pred, fin.pred_succ, fin.cast_lt_cast_succ], }, }, end /-- Make a cochain complex from a cosimplicial object. -/ def to_cocomplex : cochain_complex C ℕ := cochain_complex.of (λ n, M.obj [n]) (λ n, M.coboundary n) M.coboundary_coboundary /-- A functorial version of `to_cocomplex`. -/ def cocomplex : cosimplicial_object C ⥤ cochain_complex C ℕ := { obj := to_cocomplex, map := λ M N f, { f := λ i, f.app _, comm' := begin rintro i j (rfl : i + 1 = j), dsimp [to_cocomplex, cochain_complex.of], simp only [if_pos rfl, category.comp_id, eq_to_hom_refl, coboundary, δ, preadditive.sum_comp, preadditive.comp_sum, comp_gsmul, gsmul_comp, nat_trans.naturality], end } } namespace augmented /-- The objects defining the cochain complex associated to an augmented cosimplicial object. -/ @[nolint unused_arguments] def to_cocomplex_obj (M : augmented C) : ℕ → C | 0 := augmented.point.obj M | (n+1) := (augmented.drop.obj M).obj [n] /-- The boundary maps defining the cochain complex associated to an augmented cosimplicial object.-/ def to_cocomplex_d {M : augmented C} : Π (n : ℕ), to_cocomplex_obj M n ⟶ to_cocomplex_obj M (n+1) | 0 := M.hom.app _ | (n+1) := (augmented.drop.obj M).coboundary _ /-- The cochain complex associated to an augmented cosimplicial object. -/ @[simps] def to_cocomplex (M : augmented C) : cochain_complex C ℕ := cochain_complex.of (to_cocomplex_obj M) to_cocomplex_d begin rintros (_|_), { dsimp [to_cocomplex_d], erw [coboundary_zero, preadditive.comp_sub, sub_eq_zero, ← M.hom.naturality, ← M.hom.naturality], refl }, { apply coboundary_coboundary } end /-- A functorial version of to_cocomplex. -/ def cocomplex : augmented C ⥤ cochain_complex C ℕ := { obj := to_cocomplex, map := λ M N f, { f := λ i, match i with | 0 := point.map f | (n+1) := (drop.map f).app _ end, comm' := begin rintro i j (rfl : i + 1 = j), dsimp [to_cocomplex, cochain_complex.of], simp only [if_pos rfl, eq_to_hom_refl, category.comp_id], cases i, { dsimp [to_cocomplex_d], erw [← nat_trans.comp_app, ← f.w], refl }, { dsimp [to_cocomplex_d, coboundary], simp only [preadditive.sum_comp, preadditive.comp_sum, comp_gsmul, gsmul_comp], apply fintype.sum_congr, intro i, erw (drop.map f).naturality, refl } end }, map_id' := λ M, by { ext (_|_), tidy }, map_comp' := λ M N K f g, by { ext (_|_), tidy } } end augmented end cosimplicial_object end category_theory
7654ec027d08faa177703534b000b13fc96661ef
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/ring_theory/subsemiring/pointwise.lean
89d82cf4ed11b38813dbdb245e47a5354fbb85d7
[ "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
4,443
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 ring_theory.subsemiring.basic import algebra.group_ring_action import algebra.pointwise /-! # Pointwise instances on `subsemiring`s This file provides the action `subsemiring.pointwise_mul_action` which matches the action of `mul_action_set`. This actions is available in the `pointwise` locale. ## Implementation notes This file is almost identical to `group_theory/submonoid/pointwise.lean`. Where possible, try to keep them in sync. -/ variables {M R : Type*} namespace subsemiring section monoid variables [monoid M] [semiring R] [mul_semiring_action M R] /-- The action on a subsemiring corresponding to applying the action to every element. This is available as an instance in the `pointwise` locale. -/ protected def pointwise_mul_action : mul_action M (subsemiring R) := { smul := λ a S, S.map (mul_semiring_action.to_ring_hom _ _ a), one_smul := λ S, (congr_arg (λ f, S.map f) (ring_hom.ext $ by exact one_smul M)).trans S.map_id, mul_smul := λ a₁ a₂ S, (congr_arg (λ f, S.map f) (ring_hom.ext $ by exact mul_smul _ _)).trans (S.map_map _ _).symm } localized "attribute [instance] subsemiring.pointwise_mul_action" in pointwise open_locale pointwise lemma pointwise_smul_def {a : M} (S : subsemiring R) : a • S = S.map (mul_semiring_action.to_ring_hom _ _ a) := rfl @[simp] lemma coe_pointwise_smul (m : M) (S : subsemiring R) : ↑(m • S) = m • (S : set R) := rfl @[simp] lemma pointwise_smul_to_add_submonoid (m : M) (S : subsemiring R) : (m • S).to_add_submonoid = m • S.to_add_submonoid := rfl lemma smul_mem_pointwise_smul (m : M) (r : R) (S : subsemiring R) : r ∈ S → m • r ∈ m • S := (set.smul_mem_smul_set : _ → _ ∈ m • (S : set R)) lemma mem_smul_pointwise_iff_exists (m : M) (r : R) (S : subsemiring R) : r ∈ m • S ↔ ∃ (s : R), s ∈ S ∧ m • s = r := (set.mem_smul_set : r ∈ m • (S : set R) ↔ _) instance pointwise_central_scalar [mul_semiring_action Mᵐᵒᵖ R] [is_central_scalar M R] : is_central_scalar M (subsemiring R) := ⟨λ a S, congr_arg (λ f, S.map f) $ ring_hom.ext $ by exact op_smul_eq_smul _⟩ end monoid section group variables [group M] [semiring R] [mul_semiring_action M R] open_locale pointwise @[simp] lemma smul_mem_pointwise_smul_iff {a : M} {S : subsemiring R} {x : R} : a • x ∈ a • S ↔ x ∈ S := smul_mem_smul_set_iff lemma mem_pointwise_smul_iff_inv_smul_mem {a : M} {S : subsemiring R} {x : R} : x ∈ a • S ↔ a⁻¹ • x ∈ S := mem_smul_set_iff_inv_smul_mem lemma mem_inv_pointwise_smul_iff {a : M} {S : subsemiring R} {x : R} : x ∈ a⁻¹ • S ↔ a • x ∈ S := mem_inv_smul_set_iff @[simp] lemma pointwise_smul_le_pointwise_smul_iff {a : M} {S T : subsemiring R} : a • S ≤ a • T ↔ S ≤ T := set_smul_subset_set_smul_iff lemma pointwise_smul_subset_iff {a : M} {S T : subsemiring R} : a • S ≤ T ↔ S ≤ a⁻¹ • T := set_smul_subset_iff lemma subset_pointwise_smul_iff {a : M} {S T : subsemiring R} : S ≤ a • T ↔ a⁻¹ • S ≤ T := subset_set_smul_iff /-! TODO: add `equiv_smul` like we have for subgroup. -/ end group section group_with_zero variables [group_with_zero M] [semiring R] [mul_semiring_action M R] open_locale pointwise @[simp] lemma smul_mem_pointwise_smul_iff₀ {a : M} (ha : a ≠ 0) (S : subsemiring R) (x : R) : a • x ∈ a • S ↔ x ∈ S := smul_mem_smul_set_iff₀ ha (S : set R) x lemma mem_pointwise_smul_iff_inv_smul_mem₀ {a : M} (ha : a ≠ 0) (S : subsemiring R) (x : R) : x ∈ a • S ↔ a⁻¹ • x ∈ S := mem_smul_set_iff_inv_smul_mem₀ ha (S : set R) x lemma mem_inv_pointwise_smul_iff₀ {a : M} (ha : a ≠ 0) (S : subsemiring R) (x : R) : x ∈ a⁻¹ • S ↔ a • x ∈ S := mem_inv_smul_set_iff₀ ha (S : set R) x @[simp] lemma pointwise_smul_le_pointwise_smul_iff₀ {a : M} (ha : a ≠ 0) {S T : subsemiring R} : a • S ≤ a • T ↔ S ≤ T := set_smul_subset_set_smul_iff₀ ha lemma pointwise_smul_le_iff₀ {a : M} (ha : a ≠ 0) {S T : subsemiring R} : a • S ≤ T ↔ S ≤ a⁻¹ • T := set_smul_subset_iff₀ ha lemma le_pointwise_smul_iff₀ {a : M} (ha : a ≠ 0) {S T : subsemiring R} : S ≤ a • T ↔ a⁻¹ • S ≤ T := subset_set_smul_iff₀ ha end group_with_zero end subsemiring
5d47779f9e2c19a7fca98296e37a9c482a0855ab
b7f22e51856f4989b970961f794f1c435f9b8f78
/library/data/nat/order.lean
1461486af9fcb857c7494e9cef57194c8d550f83
[ "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
20,607
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, Leonardo de Moura, Jeremy Avigad The order relation on the natural numbers. -/ import .basic algebra.ordered_ring open eq.ops namespace nat /- lt and le -/ protected theorem le_of_lt_or_eq {m n : ℕ} (H : m < n ∨ m = n) : m ≤ n := nat.le_of_eq_or_lt (or.swap H) protected theorem lt_or_eq_of_le {m n : ℕ} (H : m ≤ n) : m < n ∨ m = n := or.swap (nat.eq_or_lt_of_le H) protected theorem le_iff_lt_or_eq (m n : ℕ) : m ≤ n ↔ m < n ∨ m = n := iff.intro nat.lt_or_eq_of_le nat.le_of_lt_or_eq protected theorem lt_of_le_and_ne {m n : ℕ} (H1 : m ≤ n) : m ≠ n → m < n := or_resolve_right (nat.eq_or_lt_of_le H1) protected theorem lt_iff_le_and_ne (m n : ℕ) : m < n ↔ m ≤ n ∧ m ≠ n := iff.intro (take H, and.intro (nat.le_of_lt H) (take H1, !nat.lt_irrefl (H1 ▸ H))) (and.rec nat.lt_of_le_and_ne) theorem le_add_right (n k : ℕ) : n ≤ n + k := nat.rec !nat.le_refl (λ k, le_succ_of_le) k theorem le_add_left (n m : ℕ): n ≤ m + n := !add.comm ▸ !le_add_right theorem le.intro {n m k : ℕ} (h : n + k = m) : n ≤ m := h ▸ !le_add_right theorem le.elim {n m : ℕ} : n ≤ m → ∃ k, n + k = m := le.rec (exists.intro 0 rfl) (λm h, Exists.rec (λ k H, exists.intro (succ k) (H ▸ rfl))) protected theorem le_total {m n : ℕ} : m ≤ n ∨ n ≤ m := or.imp_left nat.le_of_lt !nat.lt_or_ge /- addition -/ protected theorem add_le_add_left {n m : ℕ} (H : n ≤ m) (k : ℕ) : k + n ≤ k + m := obtain l Hl, from le.elim H, le.intro (Hl ▸ !add.assoc) protected theorem add_le_add_right {n m : ℕ} (H : n ≤ m) (k : ℕ) : n + k ≤ m + k := !add.comm ▸ !add.comm ▸ nat.add_le_add_left H k protected theorem le_of_add_le_add_left {k n m : ℕ} (H : k + n ≤ k + m) : n ≤ m := obtain l Hl, from le.elim H, le.intro (nat.add_left_cancel (!add.assoc⁻¹ ⬝ Hl)) protected theorem lt_of_add_lt_add_left {k n m : ℕ} (H : k + n < k + m) : n < m := let H' := nat.le_of_lt H in nat.lt_of_le_and_ne (nat.le_of_add_le_add_left H') (assume Heq, !nat.lt_irrefl (Heq ▸ H)) protected theorem add_lt_add_left {n m : ℕ} (H : n < m) (k : ℕ) : k + n < k + m := lt_of_succ_le (!add_succ ▸ nat.add_le_add_left (succ_le_of_lt H) k) protected theorem add_lt_add_right {n m : ℕ} (H : n < m) (k : ℕ) : n + k < m + k := !add.comm ▸ !add.comm ▸ nat.add_lt_add_left H k protected theorem lt_add_of_pos_right {n k : ℕ} (H : k > 0) : n < n + k := !add_zero ▸ nat.add_lt_add_left H n /- multiplication -/ theorem mul_le_mul_left {n m : ℕ} (k : ℕ) (H : n ≤ m) : k * n ≤ k * m := obtain (l : ℕ) (Hl : n + l = m), from le.elim H, have k * n + k * l = k * m, by rewrite [-left_distrib, Hl], le.intro this theorem mul_le_mul_right {n m : ℕ} (k : ℕ) (H : n ≤ m) : n * k ≤ m * k := !mul.comm ▸ !mul.comm ▸ !mul_le_mul_left H protected theorem mul_le_mul {n m k l : ℕ} (H1 : n ≤ k) (H2 : m ≤ l) : n * m ≤ k * l := nat.le_trans (!nat.mul_le_mul_right H1) (!nat.mul_le_mul_left H2) protected theorem mul_lt_mul_of_pos_left {n m k : ℕ} (H : n < m) (Hk : k > 0) : k * n < k * m := nat.lt_of_lt_of_le (nat.lt_add_of_pos_right Hk) (!mul_succ ▸ nat.mul_le_mul_left k (succ_le_of_lt H)) protected theorem mul_lt_mul_of_pos_right {n m k : ℕ} (H : n < m) (Hk : k > 0) : n * k < m * k := !mul.comm ▸ !mul.comm ▸ nat.mul_lt_mul_of_pos_left H Hk /- nat is an instance of a linearly ordered semiring and a lattice -/ protected definition decidable_linear_ordered_semiring [trans_instance] : decidable_linear_ordered_semiring nat := ⦃ decidable_linear_ordered_semiring, nat.comm_semiring, add_left_cancel := @nat.add_left_cancel, add_right_cancel := @nat.add_right_cancel, lt := nat.lt, le := nat.le, le_refl := nat.le_refl, le_trans := @nat.le_trans, le_antisymm := @nat.le_antisymm, le_total := @nat.le_total, le_iff_lt_or_eq := @nat.le_iff_lt_or_eq, le_of_lt := @nat.le_of_lt, lt_irrefl := @nat.lt_irrefl, lt_of_lt_of_le := @nat.lt_of_lt_of_le, lt_of_le_of_lt := @nat.lt_of_le_of_lt, lt_of_add_lt_add_left := @nat.lt_of_add_lt_add_left, add_lt_add_left := @nat.add_lt_add_left, add_le_add_left := @nat.add_le_add_left, le_of_add_le_add_left := @nat.le_of_add_le_add_left, zero_lt_one := zero_lt_succ 0, mul_le_mul_of_nonneg_left := (take a b c H1 H2, nat.mul_le_mul_left c H1), mul_le_mul_of_nonneg_right := (take a b c H1 H2, nat.mul_le_mul_right c H1), mul_lt_mul_of_pos_left := @nat.mul_lt_mul_of_pos_left, mul_lt_mul_of_pos_right := @nat.mul_lt_mul_of_pos_right, decidable_lt := nat.decidable_lt ⦄ definition nat_has_dvd [instance] [priority nat.prio] : has_dvd nat := has_dvd.mk has_dvd.dvd theorem add_pos_left {a : ℕ} (H : 0 < a) (b : ℕ) : 0 < a + b := @add_pos_of_pos_of_nonneg _ _ a b H !zero_le theorem add_pos_right {a : ℕ} (H : 0 < a) (b : ℕ) : 0 < b + a := by rewrite add.comm; apply add_pos_left H b theorem add_eq_zero_iff_eq_zero_and_eq_zero {a b : ℕ} : a + b = 0 ↔ a = 0 ∧ b = 0 := @add_eq_zero_iff_eq_zero_and_eq_zero_of_nonneg_of_nonneg _ _ a b !zero_le !zero_le theorem le_add_of_le_left {a b c : ℕ} (H : b ≤ c) : b ≤ a + c := @le_add_of_nonneg_of_le _ _ a b c !zero_le H theorem le_add_of_le_right {a b c : ℕ} (H : b ≤ c) : b ≤ c + a := @le_add_of_le_of_nonneg _ _ a b c H !zero_le theorem lt_add_of_lt_left {b c : ℕ} (H : b < c) (a : ℕ) : b < a + c := @lt_add_of_nonneg_of_lt _ _ a b c !zero_le H theorem lt_add_of_lt_right {b c : ℕ} (H : b < c) (a : ℕ) : b < c + a := @lt_add_of_lt_of_nonneg _ _ a b c H !zero_le theorem lt_of_mul_lt_mul_left {a b c : ℕ} (H : c * a < c * b) : a < b := @lt_of_mul_lt_mul_left _ _ a b c H !zero_le theorem lt_of_mul_lt_mul_right {a b c : ℕ} (H : a * c < b * c) : a < b := @lt_of_mul_lt_mul_right _ _ a b c H !zero_le theorem pos_of_mul_pos_left {a b : ℕ} (H : 0 < a * b) : 0 < b := @pos_of_mul_pos_left _ _ a b H !zero_le theorem pos_of_mul_pos_right {a b : ℕ} (H : 0 < a * b) : 0 < a := @pos_of_mul_pos_right _ _ a b H !zero_le theorem zero_le_one : (0:nat) ≤ 1 := dec_trivial /- properties specific to nat -/ theorem lt_intro {n m k : ℕ} (H : succ n + k = m) : n < m := lt_of_succ_le (le.intro H) theorem lt_elim {n m : ℕ} (H : n < m) : ∃k, succ n + k = m := le.elim (succ_le_of_lt H) theorem lt_add_succ (n m : ℕ) : n < n + succ m := lt_intro !succ_add_eq_succ_add theorem eq_zero_of_le_zero {n : ℕ} (H : n ≤ 0) : n = 0 := obtain (k : ℕ) (Hk : n + k = 0), from le.elim H, eq_zero_of_add_eq_zero_right Hk /- succ and pred -/ theorem le_of_lt_succ {m n : nat} : m < succ n → m ≤ n := le_of_succ_le_succ theorem lt_iff_succ_le (m n : nat) : m < n ↔ succ m ≤ n := iff.rfl theorem lt_succ_iff_le (m n : nat) : m < succ n ↔ m ≤ n := iff.intro le_of_lt_succ lt_succ_of_le theorem self_le_succ (n : ℕ) : n ≤ succ n := le.intro !add_one theorem succ_le_or_eq_of_le {n m : ℕ} : n ≤ m → succ n ≤ m ∨ n = m := lt_or_eq_of_le theorem pred_le_of_le_succ {n m : ℕ} : n ≤ succ m → pred n ≤ m := pred_le_pred theorem succ_le_of_le_pred {n m : ℕ} : succ n ≤ m → n ≤ pred m := pred_le_pred theorem pred_le_pred_of_le {n m : ℕ} : n ≤ m → pred n ≤ pred m := pred_le_pred theorem pre_lt_of_lt {n m : ℕ} : n < m → pred n < m := lt_of_le_of_lt !pred_le theorem lt_of_pred_lt_pred {n m : ℕ} (H : pred n < pred m) : n < m := lt_of_not_ge (suppose m ≤ n, not_lt_of_ge (pred_le_pred_of_le this) H) theorem le_or_eq_succ_of_le_succ {n m : ℕ} (H : n ≤ succ m) : n ≤ m ∨ n = succ m := or.imp_left le_of_succ_le_succ (succ_le_or_eq_of_le H) theorem le_pred_self (n : ℕ) : pred n ≤ n := !pred_le theorem succ_pos (n : ℕ) : 0 < succ n := !zero_lt_succ theorem succ_pred_of_pos {n : ℕ} (H : n > 0) : succ (pred n) = n := (or_resolve_right (eq_zero_or_eq_succ_pred n) (ne.symm (ne_of_lt H)))⁻¹ theorem exists_eq_succ_of_lt {n : ℕ} : Π {m : ℕ}, n < m → ∃k, m = succ k | 0 H := absurd H !not_lt_zero | (succ k) H := exists.intro k rfl theorem lt_succ_self (n : ℕ) : n < succ n := lt.base n lemma lt_succ_of_lt {i j : nat} : i < j → i < succ j := assume Plt, lt.trans Plt (self_lt_succ j) lemma one_le_succ (n : ℕ) : 1 ≤ succ n := nat.succ_le_succ !zero_le lemma two_le_succ_succ (n : ℕ) : 2 ≤ succ (succ n) := nat.succ_le_succ !one_le_succ /- increasing and decreasing functions -/ section variables {A : Type} [strict_order A] {f : ℕ → A} theorem strictly_increasing_of_forall_lt_succ (H : ∀ i, f i < f (succ i)) : strictly_increasing f := take i j, nat.induction_on j (suppose i < 0, absurd this !not_lt_zero) (take j', assume ih, suppose i < succ j', or.elim (lt_or_eq_of_le (le_of_lt_succ this)) (suppose i < j', lt.trans (ih this) (H j')) (suppose i = j', by rewrite this; apply H)) theorem strictly_decreasing_of_forall_gt_succ (H : ∀ i, f i > f (succ i)) : strictly_decreasing f := take i j, nat.induction_on j (suppose i < 0, absurd this !not_lt_zero) (take j', assume ih, suppose i < succ j', or.elim (lt_or_eq_of_le (le_of_lt_succ this)) (suppose i < j', lt.trans (H j') (ih this)) (suppose i = j', by rewrite this; apply H)) end section variables {A : Type} [weak_order A] {f : ℕ → A} theorem nondecreasing_of_forall_le_succ (H : ∀ i, f i ≤ f (succ i)) : nondecreasing f := take i j, nat.induction_on j (suppose i ≤ 0, have i = 0, from eq_zero_of_le_zero this, by rewrite this; apply le.refl) (take j', assume ih, suppose i ≤ succ j', or.elim (le_or_eq_succ_of_le_succ this) (suppose i ≤ j', le.trans (ih this) (H j')) (suppose i = succ j', by rewrite this; apply le.refl)) theorem nonincreasing_of_forall_ge_succ (H : ∀ i, f i ≥ f (succ i)) : nonincreasing f := take i j, nat.induction_on j (suppose i ≤ 0, have i = 0, from eq_zero_of_le_zero this, by rewrite this; apply le.refl) (take j', assume ih, suppose i ≤ succ j', or.elim (le_or_eq_succ_of_le_succ this) (suppose i ≤ j', le.trans (H j') (ih this)) (suppose i = succ j', by rewrite this; apply le.refl)) end /- other forms of induction -/ protected definition strong_rec_on {P : nat → Type} (n : ℕ) (H : ∀n, (∀m, m < n → P m) → P n) : P n := nat.rec (λm h, absurd h !not_lt_zero) (λn' (IH : ∀ {m : ℕ}, m < n' → P m) m l, or.by_cases (lt_or_eq_of_le (le_of_lt_succ l)) IH (λ e, eq.rec (H n' @IH) e⁻¹)) (succ n) n !lt_succ_self protected theorem strong_induction_on {P : nat → Prop} (n : ℕ) (H : ∀n, (∀m, m < n → P m) → P n) : P n := nat.strong_rec_on n H protected theorem case_strong_induction_on {P : nat → Prop} (a : nat) (H0 : P 0) (Hind : ∀(n : nat), (∀m, m ≤ n → P m) → P (succ n)) : P a := nat.strong_induction_on a (take n, show (∀ m, m < n → P m) → P n, from nat.cases_on n (suppose (∀ m, m < 0 → P m), show P 0, from H0) (take n, suppose (∀ m, m < succ n → P m), show P (succ n), from Hind n (take m, assume H1 : m ≤ n, this _ (lt_succ_of_le H1)))) /- pos -/ theorem by_cases_zero_pos {P : ℕ → Prop} (y : ℕ) (H0 : P 0) (H1 : ∀ {y : nat}, y > 0 → P y) : P y := nat.cases_on y H0 (take y, H1 !succ_pos) theorem eq_zero_or_pos (n : ℕ) : n = 0 ∨ n > 0 := or_of_or_of_imp_left (or.swap (lt_or_eq_of_le !zero_le)) (suppose 0 = n, by subst n) theorem pos_of_ne_zero {n : ℕ} (H : n ≠ 0) : n > 0 := or.elim !eq_zero_or_pos (take H2 : n = 0, by contradiction) (take H2 : n > 0, H2) theorem ne_zero_of_pos {n : ℕ} (H : n > 0) : n ≠ 0 := ne.symm (ne_of_lt H) theorem exists_eq_succ_of_pos {n : ℕ} (H : n > 0) : ∃l, n = succ l := exists_eq_succ_of_lt H theorem pos_of_dvd_of_pos {m n : ℕ} (H1 : m ∣ n) (H2 : n > 0) : m > 0 := pos_of_ne_zero (suppose m = 0, have n = 0, from eq_zero_of_zero_dvd (this ▸ H1), ne_of_lt H2 (by subst n)) /- multiplication -/ theorem mul_lt_mul_of_le_of_lt {n m k l : ℕ} (Hk : k > 0) (H1 : n ≤ k) (H2 : m < l) : n * m < k * l := lt_of_le_of_lt (mul_le_mul_right m H1) (mul_lt_mul_of_pos_left H2 Hk) theorem mul_lt_mul_of_lt_of_le {n m k l : ℕ} (Hl : l > 0) (H1 : n < k) (H2 : m ≤ l) : n * m < k * l := lt_of_le_of_lt (mul_le_mul_left n H2) (mul_lt_mul_of_pos_right H1 Hl) theorem mul_lt_mul_of_le_of_le {n m k l : ℕ} (H1 : n < k) (H2 : m < l) : n * m < k * l := have H3 : n * m ≤ k * m, from mul_le_mul_right m (le_of_lt H1), have H4 : k * m < k * l, from mul_lt_mul_of_pos_left H2 (lt_of_le_of_lt !zero_le H1), lt_of_le_of_lt H3 H4 theorem eq_of_mul_eq_mul_left {m k n : ℕ} (Hn : n > 0) (H : n * m = n * k) : m = k := have n * m ≤ n * k, by rewrite H, have m ≤ k, from le_of_mul_le_mul_left this Hn, have n * k ≤ n * m, by rewrite H, have k ≤ m, from le_of_mul_le_mul_left this Hn, le.antisymm `m ≤ k` this theorem eq_of_mul_eq_mul_right {n m k : ℕ} (Hm : m > 0) (H : n * m = k * m) : n = k := eq_of_mul_eq_mul_left Hm (!mul.comm ▸ !mul.comm ▸ H) theorem eq_zero_or_eq_of_mul_eq_mul_left {n m k : ℕ} (H : n * m = n * k) : n = 0 ∨ m = k := or_of_or_of_imp_right !eq_zero_or_pos (assume Hn : n > 0, eq_of_mul_eq_mul_left Hn H) theorem eq_zero_or_eq_of_mul_eq_mul_right {n m k : ℕ} (H : n * m = k * m) : m = 0 ∨ n = k := eq_zero_or_eq_of_mul_eq_mul_left (!mul.comm ▸ !mul.comm ▸ H) theorem eq_one_of_mul_eq_one_right {n m : ℕ} (H : n * m = 1) : n = 1 := have H2 : n * m > 0, by rewrite H; apply succ_pos, or.elim (le_or_gt n 1) (suppose n ≤ 1, have n > 0, from pos_of_mul_pos_right H2, show n = 1, from le.antisymm `n ≤ 1` (succ_le_of_lt this)) (suppose n > 1, have m > 0, from pos_of_mul_pos_left H2, have n * m ≥ 2 * 1, from nat.mul_le_mul (succ_le_of_lt `n > 1`) (succ_le_of_lt this), have 1 ≥ 2, from !mul_one ▸ H ▸ this, absurd !lt_succ_self (not_lt_of_ge this)) theorem eq_one_of_mul_eq_one_left {n m : ℕ} (H : n * m = 1) : m = 1 := eq_one_of_mul_eq_one_right (!mul.comm ▸ H) theorem eq_one_of_mul_eq_self_left {n m : ℕ} (Hpos : n > 0) (H : m * n = n) : m = 1 := eq_of_mul_eq_mul_right Hpos (H ⬝ !one_mul⁻¹) theorem eq_one_of_mul_eq_self_right {n m : ℕ} (Hpos : m > 0) (H : m * n = m) : n = 1 := eq_one_of_mul_eq_self_left Hpos (!mul.comm ▸ H) theorem eq_one_of_dvd_one {n : ℕ} (H : n ∣ 1) : n = 1 := dvd.elim H (take m, suppose 1 = n * m, eq_one_of_mul_eq_one_right this⁻¹) /- min and max -/ open decidable theorem min_zero [simp] (a : ℕ) : min a 0 = 0 := by rewrite [min_eq_right !zero_le] theorem zero_min [simp] (a : ℕ) : min 0 a = 0 := by rewrite [min_eq_left !zero_le] theorem max_zero [simp] (a : ℕ) : max a 0 = a := by rewrite [max_eq_left !zero_le] theorem zero_max [simp] (a : ℕ) : max 0 a = a := by rewrite [max_eq_right !zero_le] theorem min_succ_succ [simp] (a b : ℕ) : min (succ a) (succ b) = succ (min a b) := or.elim !lt_or_ge (suppose a < b, by rewrite [min_eq_left_of_lt this, min_eq_left_of_lt (succ_lt_succ this)]) (suppose a ≥ b, by rewrite [min_eq_right this, min_eq_right (succ_le_succ this)]) theorem max_succ_succ [simp] (a b : ℕ) : max (succ a) (succ b) = succ (max a b) := or.elim !lt_or_ge (suppose a < b, by rewrite [max_eq_right_of_lt this, max_eq_right_of_lt (succ_lt_succ this)]) (suppose a ≥ b, by rewrite [max_eq_left this, max_eq_left (succ_le_succ this)]) /- In algebra.ordered_group, these next four are only proved for additive groups, not additive semigroups. -/ protected theorem min_add_add_left (a b c : ℕ) : min (a + b) (a + c) = a + min b c := decidable.by_cases (suppose b ≤ c, have a + b ≤ a + c, from add_le_add_left this _, by rewrite [min_eq_left `b ≤ c`, min_eq_left this]) (suppose ¬ b ≤ c, have c ≤ b, from le_of_lt (lt_of_not_ge this), have a + c ≤ a + b, from add_le_add_left this _, by rewrite [min_eq_right `c ≤ b`, min_eq_right this]) protected theorem min_add_add_right (a b c : ℕ) : min (a + c) (b + c) = min a b + c := by rewrite [add.comm a c, add.comm b c, add.comm _ c]; apply nat.min_add_add_left protected theorem max_add_add_left (a b c : ℕ) : max (a + b) (a + c) = a + max b c := decidable.by_cases (suppose b ≤ c, have a + b ≤ a + c, from add_le_add_left this _, by rewrite [max_eq_right `b ≤ c`, max_eq_right this]) (suppose ¬ b ≤ c, have c ≤ b, from le_of_lt (lt_of_not_ge this), have a + c ≤ a + b, from add_le_add_left this _, by rewrite [max_eq_left `c ≤ b`, max_eq_left this]) protected theorem max_add_add_right (a b c : ℕ) : max (a + c) (b + c) = max a b + c := by rewrite [add.comm a c, add.comm b c, add.comm _ c]; apply nat.max_add_add_left /- least and greatest -/ section least_and_greatest variable (P : ℕ → Prop) variable [decP : ∀ n, decidable (P n)] include decP -- returns the least i < n satisfying P, or n if there is none definition least : ℕ → ℕ | 0 := 0 | (succ n) := if P (least n) then least n else succ n theorem least_of_bound {n : ℕ} (H : P n) : P (least P n) := begin induction n with [m, ih], rewrite ↑least, apply H, rewrite ↑least, cases decidable.em (P (least P m)) with [Hlp, Hlp], rewrite [if_pos Hlp], apply Hlp, rewrite [if_neg Hlp], apply H end theorem least_le (n : ℕ) : least P n ≤ n:= begin induction n with [m, ih], {rewrite ↑least}, rewrite ↑least, cases decidable.em (P (least P m)) with [Psm, Pnsm], rewrite [if_pos Psm], apply le.trans ih !le_succ, rewrite [if_neg Pnsm] end theorem least_of_lt {i n : ℕ} (ltin : i < n) (H : P i) : P (least P n) := begin induction n with [m, ih], exact absurd ltin !not_lt_zero, rewrite ↑least, cases decidable.em (P (least P m)) with [Psm, Pnsm], rewrite [if_pos Psm], apply Psm, rewrite [if_neg Pnsm], cases (lt_or_eq_of_le (le_of_lt_succ ltin)) with [Hlt, Heq], exact absurd (ih Hlt) Pnsm, rewrite Heq at H, exact absurd (least_of_bound P H) Pnsm end theorem ge_least_of_lt {i n : ℕ} (ltin : i < n) (Hi : P i) : i ≥ least P n := begin induction n with [m, ih], exact absurd ltin !not_lt_zero, rewrite ↑least, cases decidable.em (P (least P m)) with [Psm, Pnsm], rewrite [if_pos Psm], cases (lt_or_eq_of_le (le_of_lt_succ ltin)) with [Hlt, Heq], apply ih Hlt, rewrite Heq, apply least_le, rewrite [if_neg Pnsm], cases (lt_or_eq_of_le (le_of_lt_succ ltin)) with [Hlt, Heq], apply absurd (least_of_lt P Hlt Hi) Pnsm, rewrite Heq at Hi, apply absurd (least_of_bound P Hi) Pnsm end theorem least_lt {n i : ℕ} (ltin : i < n) (Hi : P i) : least P n < n := lt_of_le_of_lt (ge_least_of_lt P ltin Hi) ltin -- returns the largest i < n satisfying P, or n if there is none. definition greatest : ℕ → ℕ | 0 := 0 | (succ n) := if P n then n else greatest n theorem greatest_of_lt {i n : ℕ} (ltin : i < n) (Hi : P i) : P (greatest P n) := begin induction n with [m, ih], {exact absurd ltin !not_lt_zero}, {cases (decidable.em (P m)) with [Psm, Pnsm], {rewrite [↑greatest, if_pos Psm]; exact Psm}, {rewrite [↑greatest, if_neg Pnsm], have neim : i ≠ m, from assume H : i = m, absurd (H ▸ Hi) Pnsm, have ltim : i < m, from lt_of_le_of_ne (le_of_lt_succ ltin) neim, apply ih ltim}} end theorem le_greatest_of_lt {i n : ℕ} (ltin : i < n) (Hi : P i) : i ≤ greatest P n := begin induction n with [m, ih], {exact absurd ltin !not_lt_zero}, {cases (decidable.em (P m)) with [Psm, Pnsm], {rewrite [↑greatest, if_pos Psm], apply le_of_lt_succ ltin}, {rewrite [↑greatest, if_neg Pnsm], have neim : i ≠ m, from assume H : i = m, absurd (H ▸ Hi) Pnsm, have ltim : i < m, from lt_of_le_of_ne (le_of_lt_succ ltin) neim, apply ih ltim}} end end least_and_greatest end nat
f2fb4e35c3351d4347280c51e77eaefa4c458ec8
0c1546a496eccfb56620165cad015f88d56190c5
/library/init/wf.lean
91d1e4f90065e4cbf2f07fb58d7c7ff16b198655
[ "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
6,820
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.data.nat.basic init.data.prod universe variables u v inductive acc {α : Type u} (r : α → α → Prop) : α → Prop | intro : ∀ x, (∀ y, r y x → acc y) → acc x namespace acc variables {α : Type u} {r : α → α → Prop} def inv {x y : α} (h₁ : acc r x) (h₂ : r y x) : acc r y := acc.rec_on h₁ (λ x₁ ac₁ ih h₂, ac₁ y h₂) h₂ -- dependent elimination for acc attribute [recursor] protected def drec {C : Π (a : α), acc r a → Sort v} (h₁ : Π (x : α) (acx : Π (y : α), r y x → acc r y), (Π (y : α) (ryx : r y x), C y (acx y ryx)) → C x (acc.intro x acx)) {a : α} (h₂ : acc r a) : C a h₂ := acc.rec (λ x acx ih h₂, h₁ x acx (λ y ryx, ih y ryx (acx y ryx))) h₂ h₂ end acc inductive well_founded {α : Type u} (r : α → α → Prop) : Prop | intro : (∀ a, acc r a) → well_founded namespace well_founded def apply {α : Type u} {r : α → α → Prop} (wf : well_founded r) : ∀ a, acc r a := take a, well_founded.rec_on wf (λ p, p) a section parameters {α : Type u} {r : α → α → Prop} local infix `≺`:50 := r hypothesis hwf : well_founded r lemma recursion {C : α → Sort v} (a : α) (h : Π x, (Π y, y ≺ x → C y) → C x) : C a := acc.rec_on (apply hwf a) (λ x₁ ac₁ ih, h x₁ ih) lemma induction {C : α → Prop} (a : α) (h : ∀ x, (∀ y, y ≺ x → C y) → C x) : C a := recursion a h variable {C : α → Sort v} variable F : Π x, (Π y, y ≺ x → C y) → C x def fix_F (x : α) (a : acc r x) : C x := acc.rec_on a (λ x₁ ac₁ ih, F x₁ ih) lemma fix_F_eq (x : α) (r : acc r x) : fix_F F x r = F x (λ (y : α) (p : y ≺ x), fix_F F y (acc.inv r p)) := acc.drec (λ x r ih, rfl) r end variables {α : Type u} {C : α → Sort v} {r : α → α → Prop} -- Well-founded fixpoint def fix (hwf : well_founded r) (F : Π x, (Π y, r y x → C y) → C x) (x : α) : C x := fix_F F x (apply hwf x) -- Well-founded fixpoint satisfies fixpoint equation lemma fix_eq (hwf : well_founded r) (F : Π x, (Π y, r y x → C y) → C x) (x : α) : fix hwf F x = F x (λ y h, fix hwf F y) := fix_F_eq F x (apply hwf x) end well_founded open well_founded -- Empty relation is well-founded def empty_wf {α : Type u} : well_founded empty_relation := well_founded.intro (λ (a : α), acc.intro a (λ (b : α) (lt : false), false.rec _ lt)) -- Subrelation of a well-founded relation is well-founded namespace subrelation section parameters {α : Type u} {r Q : α → α → Prop} parameters (h₁ : subrelation Q r) parameters (h₂ : well_founded r) def accessible {a : α} (ac : acc r a) : acc Q a := acc.rec_on ac (λ x ax ih, acc.intro x (λ (y : α) (lt : Q y x), ih y (h₁ lt))) def wf : well_founded Q := ⟨λ a, accessible (apply h₂ a)⟩ end end subrelation -- The inverse image of a well-founded relation is well-founded namespace inv_image section parameters {α : Type u} {β : Type v} {r : β → β → Prop} parameters (f : α → β) parameters (h : well_founded r) private def acc_aux {b : β} (ac : acc r b) : ∀ (x : α), f x = b → acc (inv_image r f) x := acc.rec_on ac (λ x acx ih z e, acc.intro z (λ y lt, eq.rec_on e (λ acx ih, ih (f y) lt y rfl) acx ih)) def accessible {a : α} (ac : acc r (f a)) : acc (inv_image r f) a := acc_aux ac a rfl def wf : well_founded (inv_image r f) := ⟨λ a, accessible (apply h (f a))⟩ end end inv_image -- The transitive closure of a well-founded relation is well-founded namespace tc section parameters {α : Type u} {r : α → α → Prop} local notation `r⁺` := tc r def accessible {z : α} (ac : acc r z) : acc (tc r) z := acc.rec_on ac (λ x acx ih, acc.intro x (λ y rel, tc.rec_on rel (λ a b rab acx ih, ih a rab) (λ a b c rab rbc ih₁ ih₂ acx ih, acc.inv (ih₂ acx ih) rab) acx ih)) def wf (h : well_founded r) : well_founded r⁺ := ⟨λ a, accessible (apply h a)⟩ end end tc -- less-than is well-founded def nat.lt_wf : well_founded nat.lt := ⟨nat.rec (acc.intro 0 (λ n h, absurd h (nat.not_lt_zero n))) (λ n ih, acc.intro (nat.succ n) (λ m h, or.elim (nat.eq_or_lt_of_le (nat.le_of_succ_le_succ h)) (λ e, eq.substr e ih) (acc.inv ih)))⟩ def measure {α : Type u} : (α → ℕ) → α → α → Prop := inv_image lt def measure_wf {α : Type u} (f : α → ℕ) : well_founded (measure f) := inv_image.wf f nat.lt_wf namespace prod open well_founded section variables {α : Type u} {β : Type v} variable (ra : α → α → Prop) variable (rb : β → β → Prop) -- Lexicographical order based on ra and rb inductive lex : α × β → α × β → Prop | left : ∀ {a₁} b₁ {a₂} b₂, ra a₁ a₂ → lex (a₁, b₁) (a₂, b₂) | right : ∀ a {b₁ b₂}, rb b₁ b₂ → lex (a, b₁) (a, b₂) -- relational product based on ra and rb inductive rprod : α × β → α × β → Prop | intro : ∀ {a₁ b₁ a₂ b₂}, ra a₁ a₂ → rb b₁ b₂ → rprod (a₁, b₁) (a₂, b₂) end section parameters {α : Type u} {β : Type v} parameters {ra : α → α → Prop} {rb : β → β → Prop} local infix `≺`:50 := lex ra rb def lex_accessible {a} (aca : acc ra a) (acb : ∀ b, acc rb b): ∀ b, acc (lex ra rb) (a, b) := acc.rec_on aca (λ xa aca iha b, acc.rec_on (acb b) (λ xb acb ihb, acc.intro (xa, xb) (λ p lt, have aux : xa = xa → xb = xb → acc (lex ra rb) p, from @prod.lex.rec_on α β ra rb (λ p₁ p₂, fst p₂ = xa → snd p₂ = xb → acc (lex ra rb) p₁) p (xa, xb) lt (λ a₁ b₁ a₂ b₂ h (eq₂ : a₂ = xa) (eq₃ : b₂ = xb), iha a₁ (eq.rec_on eq₂ h) b₁) (λ a b₁ b₂ h (eq₂ : a = xa) (eq₃ : b₂ = xb), eq.rec_on eq₂~>symm (ihb b₁ (eq.rec_on eq₃ h))), aux rfl rfl))) -- The lexicographical order of well founded relations is well-founded def lex_wf (ha : well_founded ra) (hb : well_founded rb) : well_founded (lex ra rb) := ⟨λ p, destruct p (λ a b, lex_accessible (apply ha a) (well_founded.apply hb) b)⟩ -- relational product is a subrelation of the lex def rprod_sub_lex : ∀ a b, rprod ra rb a b → lex ra rb a b := λ a b h, prod.rprod.rec_on h (λ a₁ b₁ a₂ b₂ h₁ h₂, lex.left rb b₁ b₂ h₁) -- The relational product of well founded relations is well-founded def rprod_wf (ha : well_founded ra) (hb : well_founded rb) : well_founded (rprod ra rb) := subrelation.wf (rprod_sub_lex) (lex_wf ha hb) end end prod
76d3e369e15f4d3c5076558828913cb7610e3242
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/run/eval_constant.lean
b7f862dc6b02ed655e85583ad375e73ea2482f42
[ "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
250
lean
open tactic run_command do e ← to_expr `(nat.add), fn ← eval_expr (nat → nat → nat) e, trace (fn 10 20) run_command do e ← to_expr `(λ x y : nat, x + x + y), fn ← eval_expr (nat → nat → nat) e, trace (fn 10 20)
62c7e04509d211d2c2805017d6dcbd2edec1715d
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/data/padics/ring_homs.lean
1c05995979ece612705ad4dcd147f1b623a0bb00
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
24,624
lean
/- Copyright (c) 2020 Johan Commelin and Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin and Robert Y. Lewis -/ import data.padics.padic_integers /-! # Relating `ℤ_[p]` to `zmod (p ^ n)` In this file we establish connections between the `p`-adic integers $\mathbb{Z}_p$ and the integers modulo powers of `p`, $\mathbb{Z}/p^n\mathbb{Z}$. ## Main declarations We show that $\mathbb{Z}_p$ has a ring hom to $\mathbb{Z}/p^n\mathbb{Z}$ for each `n`. The case for `n = 1` is handled separately, since it is used in the general construction and we may want to use it without the `^1` getting in the way. * `padic_int.to_zmod`: ring hom to `zmod p` * `padic_int.to_zmod_pow`: ring hom to `zmod (p^n)` * `padic_int.ker_to_zmod` / `padic_int.ker_to_zmod_pow`: the kernels of these maps are the ideals generated by `p^n` We also establish the universal property of $\mathbb{Z}_p$ as a projective limit. Given a family of compatible ring homs $f_k : R \to \mathbb{Z}/p^n\mathbb{Z}$, there is a unique limit $R \to \mathbb{Z}_p$. * `padic_int.lift`: the limit function * `padic_int.lift_spec` / `padic_int.lift_unique`: the universal property ## Implementation notes The ring hom constructions go through an auxiliary constructor `padic_int.to_zmod_hom`, which removes some boilerplate code. -/ noncomputable theory open_locale classical namespace padic_int open nat local_ring padic variables {p : ℕ} [hp_prime : fact (p.prime)] include hp_prime section ring_homs /-! ### Ring homomorphisms to `zmod p` and `zmod (p ^ n)` -/ variables (p) (r : ℚ) omit hp_prime /-- `mod_part p r` is an integer that satisfies `∥(r - mod_part p r : ℚ_[p])∥ < 1` when `∥(r : ℚ_[p])∥ ≤ 1`, see `padic_int.norm_sub_mod_part`. It is the unique non-negative integer that is `< p` with this property. (Note that this definition assumes `r : ℚ`. See `padic_int.zmod_repr` for a version that takes values in `ℕ` and works for arbitrary `x : ℤ_[p]`.) -/ def mod_part : ℤ := (r.num * gcd_a r.denom p) % p include hp_prime variable {p} lemma mod_part_lt_p : mod_part p r < p := begin convert int.mod_lt _ _, { simp }, { exact_mod_cast hp_prime.ne_zero } end lemma mod_part_nonneg : 0 ≤ mod_part p r := int.mod_nonneg _ $ by exact_mod_cast hp_prime.ne_zero lemma is_unit_denom (r : ℚ) (h : ∥(r : ℚ_[p])∥ ≤ 1) : is_unit (r.denom : ℤ_[p]) := begin rw is_unit_iff, apply le_antisymm (r.denom : ℤ_[p]).2, rw [← not_lt, val_eq_coe, coe_coe], intro norm_denom_lt, have hr : ∥(r * r.denom : ℚ_[p])∥ = ∥(r.num : ℚ_[p])∥, { rw_mod_cast @rat.mul_denom_eq_num r, refl, }, rw padic_norm_e.mul at hr, have key : ∥(r.num : ℚ_[p])∥ < 1, { calc _ = _ : hr.symm ... < 1 * 1 : mul_lt_mul' h norm_denom_lt (norm_nonneg _) zero_lt_one ... = 1 : mul_one 1 }, have : ↑p ∣ r.num ∧ (p : ℤ) ∣ r.denom, { simp only [← norm_int_lt_one_iff_dvd, ← padic_norm_e_of_padic_int], norm_cast, exact ⟨key, norm_denom_lt⟩ }, apply hp_prime.not_dvd_one, rwa [← r.cop.gcd_eq_one, nat.dvd_gcd_iff, ← int.coe_nat_dvd_left, ← int.coe_nat_dvd], end lemma norm_sub_mod_part_aux (r : ℚ) (h : ∥(r : ℚ_[p])∥ ≤ 1) : ↑p ∣ r.num - r.num * r.denom.gcd_a p % p * ↑(r.denom) := begin rw ← zmod.int_coe_zmod_eq_zero_iff_dvd, simp only [int.cast_coe_nat, zmod.cast_mod_nat p, int.cast_mul, int.cast_sub], have := congr_arg (coe : ℤ → zmod p) (gcd_eq_gcd_ab r.denom p), simp only [int.cast_coe_nat, add_zero, int.cast_add, zmod.cast_self, int.cast_mul, zero_mul] at this, push_cast, rw [mul_right_comm, mul_assoc, ←this], suffices rdcp : r.denom.coprime p, { rw rdcp.gcd_eq_one, simp only [mul_one, cast_one, sub_self], }, apply coprime.symm, apply (coprime_or_dvd_of_prime ‹_› _).resolve_right, rw [← int.coe_nat_dvd, ← norm_int_lt_one_iff_dvd, not_lt], apply ge_of_eq, rw ← is_unit_iff, exact is_unit_denom r h, end lemma norm_sub_mod_part (h : ∥(r : ℚ_[p])∥ ≤ 1) : ∥(⟨r,h⟩ - mod_part p r : ℤ_[p])∥ < 1 := begin let n := mod_part p r, by_cases aux : (⟨r,h⟩ - n : ℤ_[p]) = 0, { rw [aux, norm_zero], exact zero_lt_one, }, rw [norm_lt_one_iff_dvd, ← (is_unit_denom r h).dvd_mul_right], suffices : ↑p ∣ r.num - n * r.denom, { convert (int.cast_ring_hom ℤ_[p]).map_dvd this, simp only [sub_mul, int.cast_coe_nat, ring_hom.eq_int_cast, int.cast_mul, sub_left_inj, int.cast_sub], apply subtype.coe_injective, simp only [coe_mul, subtype.coe_mk, coe_coe], rw_mod_cast @rat.mul_denom_eq_num r, refl }, exact norm_sub_mod_part_aux r h end lemma exists_mem_range_of_norm_rat_le_one (h : ∥(r : ℚ_[p])∥ ≤ 1) : ∃ n : ℤ, 0 ≤ n ∧ n < p ∧ ∥(⟨r,h⟩ - n : ℤ_[p])∥ < 1 := ⟨mod_part p r, mod_part_nonneg _, mod_part_lt_p _, norm_sub_mod_part _ h⟩ lemma zmod_congr_of_sub_mem_span_aux (n : ℕ) (x : ℤ_[p]) (a b : ℤ) (ha : x - a ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) (hb : x - b ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) : (a : zmod (p ^ n)) = b := begin rw [ideal.mem_span_singleton] at ha hb, rw [← sub_eq_zero, ← int.cast_sub, zmod.int_coe_zmod_eq_zero_iff_dvd, int.coe_nat_pow], rw [← dvd_neg, neg_sub] at ha, have := dvd_add ha hb, rwa [sub_eq_add_neg, sub_eq_add_neg, add_assoc, neg_add_cancel_left, ← sub_eq_add_neg, ← int.cast_sub, pow_p_dvd_int_iff] at this, end lemma zmod_congr_of_sub_mem_span (n : ℕ) (x : ℤ_[p]) (a b : ℕ) (ha : x - a ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) (hb : x - b ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) : (a : zmod (p ^ n)) = b := zmod_congr_of_sub_mem_span_aux n x a b ha hb lemma zmod_congr_of_sub_mem_max_ideal (x : ℤ_[p]) (m n : ℕ) (hm : x - m ∈ maximal_ideal ℤ_[p]) (hn : x - n ∈ maximal_ideal ℤ_[p]) : (m : zmod p) = n := begin rw maximal_ideal_eq_span_p at hm hn, have := zmod_congr_of_sub_mem_span_aux 1 x m n, simp only [pow_one] at this, specialize this hm hn, apply_fun zmod.cast_hom (show p ∣ p ^ 1, by rw pow_one) (zmod p) at this, simpa only [ring_hom.map_int_cast], end variable (x : ℤ_[p]) lemma exists_mem_range : ∃ n : ℕ, n < p ∧ (x - n ∈ maximal_ideal ℤ_[p]) := begin simp only [maximal_ideal_eq_span_p, ideal.mem_span_singleton, ← norm_lt_one_iff_dvd], obtain ⟨r, hr⟩ := rat_dense (x : ℚ_[p]) zero_lt_one, have H : ∥(r : ℚ_[p])∥ ≤ 1, { rw norm_sub_rev at hr, calc _ = ∥(r : ℚ_[p]) - x + x∥ : by ring ... ≤ _ : padic_norm_e.nonarchimedean _ _ ... ≤ _ : max_le (le_of_lt hr) x.2 }, obtain ⟨n, hzn, hnp, hn⟩ := exists_mem_range_of_norm_rat_le_one r H, lift n to ℕ using hzn, use n, split, {exact_mod_cast hnp}, simp only [norm_def, coe_sub, subtype.coe_mk, coe_coe] at hn ⊢, rw show (x - n : ℚ_[p]) = (x - r) + (r - n), by ring, apply lt_of_le_of_lt (padic_norm_e.nonarchimedean _ _), apply max_lt hr, simpa using hn end /-- `zmod_repr x` is the unique natural number smaller than `p` satisfying `∥(x - zmod_repr x : ℤ_[p])∥ < 1`. -/ def zmod_repr : ℕ := classical.some (exists_mem_range x) lemma zmod_repr_spec : zmod_repr x < p ∧ (x - zmod_repr x ∈ maximal_ideal ℤ_[p]) := classical.some_spec (exists_mem_range x) lemma zmod_repr_lt_p : zmod_repr x < p := (zmod_repr_spec _).1 lemma sub_zmod_repr_mem : (x - zmod_repr x ∈ maximal_ideal ℤ_[p]) := (zmod_repr_spec _).2 /-- `to_zmod_hom` is an auxiliary constructor for creating ring homs from `ℤ_[p]` to `zmod v`. -/ def to_zmod_hom (v : ℕ) (f : ℤ_[p] → ℕ) (f_spec : ∀ x, x - f x ∈ (ideal.span {v} : ideal ℤ_[p])) (f_congr : ∀ (x : ℤ_[p]) (a b : ℕ), x - a ∈ (ideal.span {v} : ideal ℤ_[p]) → x - b ∈ (ideal.span {v} : ideal ℤ_[p]) → (a : zmod v) = b) : ℤ_[p] →+* zmod v := { to_fun := λ x, f x, map_zero' := begin rw [f_congr (0 : ℤ_[p]) _ 0, cast_zero], { exact f_spec _ }, { simp only [sub_zero, cast_zero, submodule.zero_mem], } end, map_one' := begin rw [f_congr (1 : ℤ_[p]) _ 1, cast_one], { exact f_spec _ }, { simp only [sub_self, cast_one, submodule.zero_mem], } end, map_add' := begin intros x y, rw [f_congr (x + y) _ (f x + f y), cast_add], { exact f_spec _ }, { convert ideal.add_mem _ (f_spec x) (f_spec y), rw cast_add, ring, } end, map_mul' := begin intros x y, rw [f_congr (x * y) _ (f x * f y), cast_mul], { exact f_spec _ }, { let I : ideal ℤ_[p] := ideal.span {v}, convert I.add_mem (I.mul_mem_left x (f_spec y)) (I.mul_mem_right (f y) (f_spec x)), rw cast_mul, ring, } end, } /-- `to_zmod` is a ring hom from `ℤ_[p]` to `zmod p`, with the equality `to_zmod x = (zmod_repr x : zmod p)`. -/ def to_zmod : ℤ_[p] →+* zmod p := to_zmod_hom p zmod_repr (by { rw ←maximal_ideal_eq_span_p, exact sub_zmod_repr_mem }) (by { rw ←maximal_ideal_eq_span_p, exact zmod_congr_of_sub_mem_max_ideal } ) /-- `z - (to_zmod z : ℤ_[p])` is contained in the maximal ideal of `ℤ_[p]`, for every `z : ℤ_[p]`. The coercion from `zmod p` to `ℤ_[p]` is `zmod.has_coe_t`, which coerces `zmod p` into artibrary rings. This is unfortunate, but a consequence of the fact that we allow `zmod p` to coerce to rings of arbitrary characteristic, instead of only rings of characteristic `p`. This coercion is only a ring homomorphism if it coerces into a ring whose characteristic divides `p`. While this is not the case here we can still make use of the coercion. -/ lemma to_zmod_spec (z : ℤ_[p]) : z - (to_zmod z : ℤ_[p]) ∈ maximal_ideal ℤ_[p] := begin convert sub_zmod_repr_mem z using 2, dsimp [to_zmod, to_zmod_hom], unfreezingI { rcases (exists_eq_add_of_lt (hp_prime.pos)) with ⟨p', rfl⟩ }, change ↑(zmod.val _) = _, simp only [zmod.val_cast_nat, add_zero, add_def, cast_inj, zero_add], apply mod_eq_of_lt, simpa only [zero_add] using zmod_repr_lt_p z, end lemma ker_to_zmod : (to_zmod : ℤ_[p] →+* zmod p).ker = maximal_ideal ℤ_[p] := begin ext x, rw ring_hom.mem_ker, split, { intro h, simpa only [h, zmod.cast_zero, sub_zero] using to_zmod_spec x, }, { intro h, rw ← sub_zero x at h, dsimp [to_zmod, to_zmod_hom], convert zmod_congr_of_sub_mem_max_ideal x _ 0 _ h, apply sub_zmod_repr_mem, } end /-- `appr n x` gives a value `v : ℕ` such that `x` and `↑v : ℤ_p` are congruent mod `p^n`. See `appr_spec`. -/ noncomputable def appr : ℤ_[p] → ℕ → ℕ | x 0 := 0 | x (n+1) := let y := x - appr x n in if hy : y = 0 then appr x n else let u := unit_coeff hy in appr x n + p ^ n * (to_zmod ((u : ℤ_[p]) * (p ^ (y.valuation - n).nat_abs))).val lemma appr_lt (x : ℤ_[p]) (n : ℕ) : x.appr n < p ^ n := begin induction n with n ih generalizing x, { simp only [appr, succ_pos', pow_zero], }, simp only [appr, ring_hom.map_nat_cast, zmod.cast_self, ring_hom.map_pow, int.nat_abs, ring_hom.map_mul], have hp : p ^ n < p ^ (n + 1), { apply pow_lt_pow hp_prime.one_lt (lt_add_one n) }, split_ifs with h, { apply lt_trans (ih _) hp, }, { calc _ < p ^ n + p ^ n * (p - 1) : _ ... = p ^ (n + 1) : _, { apply add_lt_add_of_lt_of_le (ih _), apply nat.mul_le_mul_left, apply le_pred_of_lt, apply zmod.val_lt }, { rw [nat.mul_sub_left_distrib, mul_one, ← pow_succ'], apply nat.add_sub_cancel' (le_of_lt hp) } } end lemma appr_mono (x : ℤ_[p]) : monotone x.appr := begin apply monotone_of_monotone_nat, intro n, dsimp [appr], split_ifs, { refl, }, apply nat.le_add_right, end lemma dvd_appr_sub_appr (x : ℤ_[p]) (m n : ℕ) (h : m ≤ n) : p ^ m ∣ x.appr n - x.appr m := begin obtain ⟨k, rfl⟩ := nat.exists_eq_add_of_le h, clear h, induction k with k ih, { simp only [add_zero, nat.sub_self, dvd_zero], }, rw [nat.succ_eq_add_one, ← add_assoc], dsimp [appr], split_ifs with h, { exact ih }, rw [add_comm, nat.add_sub_assoc (appr_mono _ (nat.le_add_right m k))], apply dvd_add _ ih, apply dvd_mul_of_dvd_left, apply pow_dvd_pow _ (nat.le_add_right m k), end lemma appr_spec (n : ℕ) : ∀ (x : ℤ_[p]), x - appr x n ∈ (ideal.span {p^n} : ideal ℤ_[p]) := begin simp only [ideal.mem_span_singleton], induction n with n ih, { simp only [is_unit_one, is_unit.dvd, pow_zero, forall_true_iff], }, { intro x, dsimp only [appr], split_ifs with h, { rw h, apply dvd_zero }, { push_cast, rw sub_add_eq_sub_sub, obtain ⟨c, hc⟩ := ih x, simp only [ring_hom.map_nat_cast, zmod.cast_self, ring_hom.map_pow, ring_hom.map_mul, zmod.nat_cast_val], have hc' : c ≠ 0, { rintro rfl, simp only [mul_zero] at hc, contradiction }, conv_rhs { congr, simp only [hc], }, rw show (x - ↑(appr x n)).valuation = (↑p ^ n * c).valuation, { rw hc }, rw [valuation_p_pow_mul _ _ hc', add_sub_cancel', pow_succ', ← mul_sub], apply mul_dvd_mul_left, by_cases hc0 : c.valuation.nat_abs = 0, { simp only [hc0, mul_one, pow_zero], rw [mul_comm, unit_coeff_spec h] at hc, suffices : c = unit_coeff h, { rw [← this, ← ideal.mem_span_singleton, ← maximal_ideal_eq_span_p], apply to_zmod_spec }, obtain ⟨c, rfl⟩ : is_unit c, -- TODO: write a can_lift instance for units { rw int.nat_abs_eq_zero at hc0, rw [is_unit_iff, norm_eq_pow_val hc', hc0, neg_zero, fpow_zero], }, rw discrete_valuation_ring.unit_mul_pow_congr_unit _ _ _ _ _ hc, exact irreducible_p }, { rw [zero_pow (nat.pos_of_ne_zero hc0)], simp only [sub_zero, zmod.cast_zero, mul_zero], rw unit_coeff_spec hc', apply dvd_mul_of_dvd_right, apply dvd_pow (dvd_refl _), exact hc0 } } } end attribute [irreducible] appr /-- A ring hom from `ℤ_[p]` to `zmod (p^n)`, with underlying function `padic_int.appr n`. -/ def to_zmod_pow (n : ℕ) : ℤ_[p] →+* zmod (p ^ n) := to_zmod_hom (p^n) (λ x, appr x n) (by { intros, convert appr_spec n _ using 1, simp }) (by { intros x a b ha hb, apply zmod_congr_of_sub_mem_span n x a b, { simpa using ha }, { simpa using hb } }) lemma ker_to_zmod_pow (n : ℕ) : (to_zmod_pow n : ℤ_[p] →+* zmod (p ^ n)).ker = ideal.span {p ^ n} := begin ext x, rw ring_hom.mem_ker, split, { intro h, suffices : x.appr n = 0, { convert appr_spec n x, simp only [this, sub_zero, cast_zero], }, dsimp [to_zmod_pow, to_zmod_hom] at h, rw zmod.nat_coe_zmod_eq_zero_iff_dvd at h, apply eq_zero_of_dvd_of_lt h (appr_lt _ _), }, { intro h, rw ← sub_zero x at h, dsimp [to_zmod_pow, to_zmod_hom], rw [zmod_congr_of_sub_mem_span n x _ 0 _ h, cast_zero], apply appr_spec, } end @[simp] lemma zmod_cast_comp_to_zmod_pow (m n : ℕ) (h : m ≤ n) : (zmod.cast_hom (pow_dvd_pow p h) (zmod (p ^ m))).comp (to_zmod_pow n) = to_zmod_pow m := begin apply zmod.ring_hom_eq_of_ker_eq, ext x, rw [ring_hom.mem_ker, ring_hom.mem_ker], simp only [function.comp_app, zmod.cast_hom_apply, ring_hom.coe_comp], simp only [to_zmod_pow, to_zmod_hom, ring_hom.coe_mk], rw [zmod.cast_nat_cast (pow_dvd_pow p h), zmod_congr_of_sub_mem_span m (x.appr n) (x.appr n) (x.appr m)], { rw [sub_self], apply ideal.zero_mem _, }, { rw ideal.mem_span_singleton, rcases dvd_appr_sub_appr x m n h with ⟨c, hc⟩, use c, rw [← nat.cast_sub (appr_mono _ h), hc, nat.cast_mul, nat.cast_pow], }, { apply_instance } end @[simp] lemma cast_to_zmod_pow (m n : ℕ) (h : m ≤ n) (x : ℤ_[p]) : ↑(to_zmod_pow n x) = to_zmod_pow m x := by { rw ← zmod_cast_comp_to_zmod_pow _ _ h, refl } lemma dense_range_nat_cast : dense_range (nat.cast : ℕ → ℤ_[p]) := begin intro x, rw metric.mem_closure_range_iff, intros ε hε, obtain ⟨n, hn⟩ := exists_pow_neg_lt p hε, use (x.appr n), rw dist_eq_norm, apply lt_of_le_of_lt _ hn, rw norm_le_pow_iff_mem_span_pow, apply appr_spec, end lemma dense_range_int_cast : dense_range (int.cast : ℤ → ℤ_[p]) := begin intro x, apply dense_range_nat_cast.induction_on x, { exact is_closed_closure, }, { intro a, change (a.cast : ℤ_[p]) with (a : ℤ).cast, apply subset_closure, exact set.mem_range_self _ } end end ring_homs section lift /-! ### Universal property as projective limit -/ open cau_seq padic_seq variables {R : Type*} [comm_ring R] (f : Π k : ℕ, R →+* zmod (p^k)) (f_compat : ∀ k1 k2 (hk : k1 ≤ k2), (zmod.cast_hom (pow_dvd_pow p hk) _).comp (f k2) = f k1) omit hp_prime /-- Given a family of ring homs `f : Π n : ℕ, R →+* zmod (p ^ n)`, `nth_hom f r` is an integer-valued sequence whose `n`th value is the unique integer `k` such that `0 ≤ k < p ^ n` and `f n r = (k : zmod (p ^ n))`. -/ def nth_hom (r : R) : ℕ → ℤ := λ n, (f n r : zmod (p^n)).val @[simp] lemma nth_hom_zero : nth_hom f 0 = 0 := by simp [nth_hom]; refl variable {f} include hp_prime include f_compat lemma pow_dvd_nth_hom_sub (r : R) (i j : ℕ) (h : i ≤ j) : ↑p ^ i ∣ nth_hom f r j - nth_hom f r i := begin specialize f_compat (i) (j) h, rw [← int.coe_nat_pow, ← zmod.int_coe_zmod_eq_zero_iff_dvd, int.cast_sub], dsimp [nth_hom], rw [← f_compat, ring_hom.comp_apply], have : fact (p ^ (i) > 0) := pow_pos (nat.prime.pos ‹_›) _, have : fact (p ^ (j) > 0) := pow_pos (nat.prime.pos ‹_›) _, unfreezingI { simp only [zmod.cast_id, zmod.cast_hom_apply, sub_self, zmod.nat_cast_val], }, end lemma is_cau_seq_nth_hom (r : R): is_cau_seq (padic_norm p) (λ n, nth_hom f r n) := begin intros ε hε, obtain ⟨k, hk⟩ : ∃ k : ℕ, (p ^ - (↑(k : ℕ) : ℤ) : ℚ) < ε := exists_pow_neg_lt_rat p hε, use k, intros j hj, refine lt_of_le_of_lt _ hk, norm_cast, rw ← padic_norm.dvd_iff_norm_le, exact_mod_cast pow_dvd_nth_hom_sub f_compat r k j hj end /-- `nth_hom_seq f_compat r` bundles `padic_int.nth_hom f r` as a Cauchy sequence of rationals with respect to the `p`-adic norm. The `n`th value of the sequence is `((f n r).val : ℚ)`. -/ def nth_hom_seq (r : R) : padic_seq p := ⟨λ n, nth_hom f r n, is_cau_seq_nth_hom f_compat r⟩ lemma nth_hom_seq_one : nth_hom_seq f_compat 1 ≈ 1 := begin intros ε hε, change _ < _ at hε, use 1, intros j hj, haveI : fact (1 < p^j) := nat.one_lt_pow _ _ (by linarith) (nat.prime.one_lt ‹_›), simp [nth_hom_seq, nth_hom, zmod.val_one, hε], end lemma nth_hom_seq_add (r s : R) : nth_hom_seq f_compat (r + s) ≈ nth_hom_seq f_compat r + nth_hom_seq f_compat s := begin intros ε hε, obtain ⟨n, hn⟩ := exists_pow_neg_lt_rat p hε, use n, intros j hj, dsimp [nth_hom_seq], apply lt_of_le_of_lt _ hn, rw [← int.cast_add, ← int.cast_sub, ← padic_norm.dvd_iff_norm_le, ← zmod.int_coe_zmod_eq_zero_iff_dvd], dsimp [nth_hom], have : fact (p ^ n > 0) := pow_pos (nat.prime.pos ‹_›) _, have : fact (p ^ j > 0) := pow_pos (nat.prime.pos ‹_›) _, unfreezingI { simp only [int.cast_coe_nat, int.cast_add, ring_hom.map_add, int.cast_sub, zmod.nat_cast_val] }, rw [zmod.cast_add (show p ^ n ∣ p ^ j, from _), sub_self], { apply_instance }, { apply pow_dvd_pow, linarith only [hj] }, end lemma nth_hom_seq_mul (r s : R) : nth_hom_seq f_compat (r * s) ≈ nth_hom_seq f_compat r * nth_hom_seq f_compat s := begin intros ε hε, obtain ⟨n, hn⟩ := exists_pow_neg_lt_rat p hε, use n, intros j hj, dsimp [nth_hom_seq], apply lt_of_le_of_lt _ hn, rw [← int.cast_mul, ← int.cast_sub, ← padic_norm.dvd_iff_norm_le, ← zmod.int_coe_zmod_eq_zero_iff_dvd], dsimp [nth_hom], have : fact (p ^ n > 0) := pow_pos (nat.prime.pos ‹_›) _, have : fact (p ^ j > 0) := pow_pos (nat.prime.pos ‹_›) _, unfreezingI { simp only [int.cast_coe_nat, int.cast_mul, int.cast_sub, ring_hom.map_mul, zmod.nat_cast_val] }, rw [zmod.cast_mul (show p ^ n ∣ p ^ j, from _), sub_self], { apply_instance }, { apply pow_dvd_pow, linarith only [hj] }, end /-- `lim_nth_hom f_compat r` is the limit of a sequence `f` of compatible ring homs `R →+* zmod (p^k)`. This is itself a ring hom: see `padic_int.lift`. -/ def lim_nth_hom (r : R) : ℤ_[p] := of_int_seq (nth_hom f r) (is_cau_seq_nth_hom f_compat r) lemma lim_nth_hom_spec (r : R) : ∀ ε : ℝ, 0 < ε → ∃ N : ℕ, ∀ n ≥ N, ∥lim_nth_hom f_compat r - nth_hom f r n∥ < ε := begin intros ε hε, obtain ⟨ε', hε'0, hε'⟩ : ∃ v : ℚ, (0 : ℝ) < v ∧ ↑v < ε := exists_rat_btwn hε, norm_cast at hε'0, obtain ⟨N, hN⟩ := padic_norm_e.defn (nth_hom_seq f_compat r) hε'0, use N, intros n hn, apply lt_trans _ hε', change ↑(padic_norm_e _) < _, norm_cast, convert hN _ hn, simp [nth_hom, lim_nth_hom, nth_hom_seq, of_int_seq], end lemma lim_nth_hom_zero : lim_nth_hom f_compat 0 = 0 := by simp [lim_nth_hom]; refl lemma lim_nth_hom_one : lim_nth_hom f_compat 1 = 1 := subtype.ext $ quot.sound $ nth_hom_seq_one _ lemma lim_nth_hom_add (r s : R) : lim_nth_hom f_compat (r + s) = lim_nth_hom f_compat r + lim_nth_hom f_compat s := subtype.ext $ quot.sound $ nth_hom_seq_add _ _ _ lemma lim_nth_hom_mul (r s : R) : lim_nth_hom f_compat (r * s) = lim_nth_hom f_compat r * lim_nth_hom f_compat s := subtype.ext $ quot.sound $ nth_hom_seq_mul _ _ _ -- TODO: generalize this to arbitrary complete discrete valuation rings /-- `lift f_compat` is the limit of a sequence `f` of compatible ring homs `R →+* zmod (p^k)`, with the equality `lift f_compat r = padic_int.lim_nth_hom f_compat r`. -/ def lift : R →+* ℤ_[p] := { to_fun := lim_nth_hom f_compat, map_one' := lim_nth_hom_one f_compat, map_mul' := lim_nth_hom_mul f_compat, map_zero' := lim_nth_hom_zero f_compat, map_add' := lim_nth_hom_add f_compat } omit f_compat lemma lift_sub_val_mem_span (r : R) (n : ℕ) : (lift f_compat r - (f n r).val) ∈ (ideal.span {↑p ^ n} : ideal ℤ_[p]) := begin obtain ⟨k, hk⟩ := lim_nth_hom_spec f_compat r _ (show (0 : ℝ) < p ^ (-n : ℤ), from nat.fpow_pos_of_pos hp_prime.pos _), have := le_of_lt (hk (max n k) (le_max_right _ _)), rw norm_le_pow_iff_mem_span_pow at this, dsimp [lift], rw sub_eq_sub_add_sub (lim_nth_hom f_compat r) _ ↑(nth_hom f r (max n k)), apply ideal.add_mem _ _ this, rw [ideal.mem_span_singleton], simpa only [ring_hom.eq_int_cast, ring_hom.map_pow, int.cast_sub] using (int.cast_ring_hom ℤ_[p]).map_dvd (pow_dvd_nth_hom_sub f_compat r n (max n k) (le_max_left _ _)), end /-- One part of the universal property of `ℤ_[p]` as a projective limit. See also `padic_int.lift_unique`. -/ lemma lift_spec (n : ℕ) : (to_zmod_pow n).comp (lift f_compat) = f n := begin ext r, haveI : fact (0 < p ^ n) := pow_pos (nat.prime.pos ‹_›) n, rw [ring_hom.comp_apply, ← zmod.cast_val (f n r), ← (to_zmod_pow n).map_nat_cast, ← sub_eq_zero, ← ring_hom.map_sub, ← ring_hom.mem_ker, ker_to_zmod_pow], apply lift_sub_val_mem_span, end /-- One part of the universal property of `ℤ_[p]` as a projective limit. See also `padic_int.lift_spec`. -/ lemma lift_unique (g : R →+* ℤ_[p]) (hg : ∀ n, (to_zmod_pow n).comp g = f n) : lift f_compat = g := begin ext1 r, apply eq_of_forall_dist_le, intros ε hε, obtain ⟨n, hn⟩ := exists_pow_neg_lt p hε, apply le_trans _ (le_of_lt hn), rw [dist_eq_norm, norm_le_pow_iff_mem_span_pow, ← ker_to_zmod_pow, ring_hom.mem_ker, ring_hom.map_sub, ← ring_hom.comp_apply, ← ring_hom.comp_apply, lift_spec, hg, sub_self], end @[simp] lemma lift_self (z : ℤ_[p]) : @lift p _ ℤ_[p] _ to_zmod_pow zmod_cast_comp_to_zmod_pow z = z := begin show _ = ring_hom.id _ z, rw @lift_unique p _ ℤ_[p] _ _ zmod_cast_comp_to_zmod_pow (ring_hom.id ℤ_[p]), intro, rw ring_hom.comp_id, end end lift lemma ext_of_to_zmod_pow {x y : ℤ_[p]} : (∀ n, to_zmod_pow n x = to_zmod_pow n y) ↔ x = y := begin split, { intro h, rw [← lift_self x, ← lift_self y], simp [lift, lim_nth_hom, nth_hom, h] }, { rintro rfl _, refl } end lemma to_zmod_pow_eq_iff_ext {R : Type*} [comm_ring R] {g g' : R →+* ℤ_[p]} : (∀ n, (to_zmod_pow n).comp g = (to_zmod_pow n).comp g') ↔ g = g' := begin split, { intro hg, ext x : 1, apply ext_of_to_zmod_pow.mp, intro n, show (to_zmod_pow n).comp g x = (to_zmod_pow n).comp g' x, rw hg n }, { rintro rfl _, refl } end end padic_int
baf5ca7daaaac6fa426a7fcfc57f27b66e372f35
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Meta/Basic.lean
16e3f020ed913ac42292ce0083d044c66ee31c05
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
73,480
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.Data.LOption import Lean.Environment import Lean.Class import Lean.ReducibilityAttrs import Lean.Util.Trace import Lean.Util.RecDepth import Lean.Util.PPExt import Lean.Util.ReplaceExpr import Lean.Util.OccursCheck import Lean.Util.MonadBacktrack import Lean.Compiler.InlineAttrs import Lean.Meta.TransparencyMode import Lean.Meta.DiscrTreeTypes import Lean.Eval import Lean.CoreM /-! This module provides four (mutually dependent) goodies that are needed for building the elaborator and tactic frameworks. 1- Weak head normal form computation with support for metavariables and transparency modes. 2- Definitionally equality checking with support for metavariables (aka unification modulo definitional equality). 3- Type inference. 4- Type class resolution. They are packed into the MetaM monad. -/ namespace Lean.Meta builtin_initialize isDefEqStuckExceptionId : InternalExceptionId ← registerInternalExceptionId `isDefEqStuck /-- Configuration flags for the `MetaM` monad. Many of them are used to control the `isDefEq` function that checks whether two terms are definitionally equal or not. Recall that when `isDefEq` is trying to check whether `?m@C a₁ ... aₙ` and `t` are definitionally equal (`?m@C a₁ ... aₙ =?= t`), where `?m@C` as a shorthand for `C |- ?m : t` where `t` is the type of `?m`. We solve it using the assignment `?m := fun a₁ ... aₙ => t` if 1) `a₁ ... aₙ` are pairwise distinct free variables that are ​*not*​ let-variables. 2) `a₁ ... aₙ` are not in `C` 3) `t` only contains free variables in `C` and/or `{a₁, ..., aₙ}` 4) For every metavariable `?m'@C'` occurring in `t`, `C'` is a subprefix of `C` 5) `?m` does not occur in `t` -/ structure Config where /-- If `foApprox` is set to true, and some `aᵢ` is not a free variable, then we use first-order unification ``` ?m a_1 ... a_i a_{i+1} ... a_{i+k} =?= f b_1 ... b_k ``` reduces to ``` ?m a_1 ... a_i =?= f a_{i+1} =?= b_1 ... a_{i+k} =?= b_k ``` -/ foApprox : Bool := false /-- When `ctxApprox` is set to true, we relax condition 4, by creating an auxiliary metavariable `?n'` with a smaller context than `?m'`. -/ ctxApprox : Bool := false /-- When `quasiPatternApprox` is set to true, we ignore condition 2. -/ quasiPatternApprox : Bool := false /-- When `constApprox` is set to true, we solve `?m t =?= c` using `?m := fun _ => c` when `?m t` is not a higher-order pattern and `c` is not an application as -/ constApprox : Bool := false /-- When the following flag is set, `isDefEq` throws the exeption `Exeption.isDefEqStuck` whenever it encounters a constraint `?m ... =?= t` where `?m` is read only. This feature is useful for type class resolution where we may want to notify the caller that the TC problem may be solveable later after it assigns `?m`. -/ isDefEqStuckEx : Bool := false /-- Controls which definitions and theorems can be unfolded by `isDefEq` and `whnf`. -/ transparency : TransparencyMode := TransparencyMode.default /-- If zetaNonDep == false, then non dependent let-decls are not zeta expanded. -/ zetaNonDep : Bool := true /-- When `trackZeta == true`, we store zetaFVarIds all free variables that have been zeta-expanded. -/ trackZeta : Bool := false /-- Enable/disable the unification hints feature. -/ unificationHints : Bool := true /-- Enables proof irrelevance at `isDefEq` -/ proofIrrelevance : Bool := true /-- By default synthetic opaque metavariables are not assigned by `isDefEq`. Motivation: we want to make sure typing constraints resolved during elaboration should not "fill" holes that are supposed to be filled using tactics. However, this restriction is too restrictive for tactics such as `exact t`. When elaborating `t`, we dot not fill named holes when solving typing constraints or TC resolution. But, we ignore the restriction when we try to unify the type of `t` with the goal target type. We claim this is not a hack and is defensible behavior because this last unification step is not really part of the term elaboration. -/ assignSyntheticOpaque : Bool := false /-- When `ignoreLevelDepth` is `false`, only universe level metavariables with depth == metavariable context depth can be assigned. We used to have `ignoreLevelDepth == false` always, but this setting produced counterintuitive behavior in a few cases. Recall that universe levels are often ignored by users, they may not even be aware they exist. We still use this restriction for regular metavariables. See discussion at the beginning of `MetavarContext.lean`. We claim it is reasonable to ignore this restriction for universe metavariables because their values are often contrained by the terms is instances and simp theorems. TODO: we should delete this configuration option and the method `isReadOnlyLevelMVar` after we have more tests. -/ ignoreLevelMVarDepth : Bool := true /-- Enable/Disable support for offset constraints such as `?x + 1 =?= e` -/ offsetCnstrs : Bool := true /-- Eta for structures configuration mode. -/ etaStruct : EtaStructMode := .all /-- Function parameter information cache. -/ structure ParamInfo where /-- The binder annotation for the parameter. -/ binderInfo : BinderInfo := BinderInfo.default /-- `hasFwdDeps` is true if there is another parameter whose type depends on this one. -/ hasFwdDeps : Bool := false /-- `backDeps` contains the backwards dependencies. That is, the (0-indexed) position of previous parameters that this one depends on. -/ backDeps : Array Nat := #[] /-- `isProp` is true if the parameter is always a proposition. -/ isProp : Bool := false /-- `isDecInst` is true if the parameter's type is of the form `Decidable ...`. This information affects the generation of congruence theorems. -/ isDecInst : Bool := false /-- `higherOrderOutParam` is true if this parameter is a higher-order output parameter of local instance. Example: ``` getElem : {cont : Type u_1} → {idx : Type u_2} → {elem : Type u_3} → {dom : cont → idx → Prop} → [self : GetElem cont idx elem dom] → (xs : cont) → (i : idx) → dom xs i → elem ``` This flag is true for the parameter `dom` because it is output parameter of `[self : GetElem cont idx elem dom]` -/ higherOrderOutParam : Bool := false /-- `dependsOnHigherOrderOutParam` is true if the type of this parameter depends on the higher-order output parameter of a previous local instance. Example: ``` getElem : {cont : Type u_1} → {idx : Type u_2} → {elem : Type u_3} → {dom : cont → idx → Prop} → [self : GetElem cont idx elem dom] → (xs : cont) → (i : idx) → dom xs i → elem ``` This flag is true for the parameter with type `dom xs i` since `dom` is an output parameter of the instance `[self : GetElem cont idx elem dom]` -/ dependsOnHigherOrderOutParam : Bool := false deriving Inhabited def ParamInfo.isImplicit (p : ParamInfo) : Bool := p.binderInfo == BinderInfo.implicit def ParamInfo.isInstImplicit (p : ParamInfo) : Bool := p.binderInfo == BinderInfo.instImplicit def ParamInfo.isStrictImplicit (p : ParamInfo) : Bool := p.binderInfo == BinderInfo.strictImplicit def ParamInfo.isExplicit (p : ParamInfo) : Bool := p.binderInfo == BinderInfo.default || p.binderInfo == BinderInfo.auxDecl /-- Function information cache. See `ParamInfo`. -/ structure FunInfo where /-- Parameter information cache. -/ paramInfo : Array ParamInfo := #[] /-- `resultDeps` contains the function result type backwards dependencies. That is, the (0-indexed) position of parameters that the result type depends on. -/ resultDeps : Array Nat := #[] /-- Key for the function information cache. -/ structure InfoCacheKey where /-- The transparency mode used to compute the `FunInfo`. -/ transparency : TransparencyMode /-- The function being cached information about. It is quite often an `Expr.const`. -/ expr : Expr /-- `nargs? = some n` if the cached information was computed assuming the function has arity `n`. If `nargs? = none`, then the cache information consumed the arrow type as much as possible unsing the current transparency setting. X-/ nargs? : Option Nat deriving Inhabited, BEq namespace InfoCacheKey instance : Hashable InfoCacheKey := ⟨fun ⟨transparency, expr, nargs⟩ => mixHash (hash transparency) <| mixHash (hash expr) (hash nargs)⟩ end InfoCacheKey open Std (PersistentArray PersistentHashMap) abbrev SynthInstanceCache := PersistentHashMap Expr (Option Expr) abbrev InferTypeCache := PersistentExprStructMap Expr abbrev FunInfoCache := PersistentHashMap InfoCacheKey FunInfo abbrev WhnfCache := PersistentExprStructMap Expr /-- A mapping `(s, t) ↦ isDefEq s t`. TODO: consider more efficient representations (e.g., a proper set) and caching policies (e.g., imperfect cache). We should also investigate the impact on memory consumption. -/ abbrev DefEqCache := PersistentHashMap (Expr × Expr) Bool /-- Cache datastructures for type inference, type class resolution, whnf, and definitional equality. -/ structure Cache where inferType : InferTypeCache := {} funInfo : FunInfoCache := {} synthInstance : SynthInstanceCache := {} whnfDefault : WhnfCache := {} -- cache for closed terms and `TransparencyMode.default` whnfAll : WhnfCache := {} -- cache for closed terms and `TransparencyMode.all` defEq : DefEqCache := {} deriving Inhabited /-- "Context" for a postponed universe constraint. `lhs` and `rhs` are the surrounding `isDefEq` call when the postponed constraint was created. -/ structure DefEqContext where lhs : Expr rhs : Expr lctx : LocalContext localInstances : LocalInstances /-- Auxiliary structure for representing postponed universe constraints. Remark: the fields `ref` and `rootDefEq?` are used for error message generation only. Remark: we may consider improving the error message generation in the future. -/ structure PostponedEntry where /-- We save the `ref` at entry creation time. This is used for reporting errors back to the user. -/ ref : Syntax lhs : Level rhs : Level /-- Context for the surrounding `isDefEq` call when entry was created. -/ ctx? : Option DefEqContext deriving Inhabited /-- `MetaM` monad state. -/ structure State where mctx : MetavarContext := {} cache : Cache := {} /-- When `trackZeta == true`, then any let-decl free variable that is zeta expansion performed by `MetaM` is stored in `zetaFVarIds`. -/ zetaFVarIds : FVarIdSet := {} /-- Array of postponed universe level constraints -/ postponed : PersistentArray PostponedEntry := {} deriving Inhabited /-- Backtrackable state for the `MetaM` monad. -/ structure SavedState where core : Core.State meta : State deriving Inhabited /-- Contextual information for the `MetaM` monad. -/ structure Context where config : Config := {} /-- Local context -/ lctx : LocalContext := {} /-- Local instances in `lctx`. -/ localInstances : LocalInstances := #[] /-- Not `none` when inside of an `isDefEq` test. See `PostponedEntry`. -/ defEqCtx? : Option DefEqContext := none /-- Track the number of nested `synthPending` invocations. Nested invocations can happen when the type class resolution invokes `synthPending`. Remark: in the current implementation, `synthPending` fails if `synthPendingDepth > 0`. We will add a configuration option if necessary. -/ synthPendingDepth : Nat := 0 /-- A predicate to control whether a constant can be unfolded or not at `whnf`. Note that we do not cache results at `whnf` when `canUnfold?` is not `none`. -/ canUnfold? : Option (Config → ConstantInfo → CoreM Bool) := none abbrev MetaM := ReaderT Context $ StateRefT State CoreM -- 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 MetaM := let i := inferInstanceAs (Monad MetaM); { pure := i.pure, bind := i.bind } instance : Inhabited (MetaM α) where default := fun _ _ => default instance : MonadLCtx MetaM where getLCtx := return (← read).lctx instance : MonadMCtx MetaM where getMCtx := return (← get).mctx modifyMCtx f := modify fun s => { s with mctx := f s.mctx } instance : MonadEnv MetaM where getEnv := return (← getThe Core.State).env modifyEnv f := do modifyThe Core.State fun s => { s with env := f s.env, cache := {} }; modify fun s => { s with cache := {} } instance : AddMessageContext MetaM where addMessageContext := addMessageContextFull protected def saveState : MetaM SavedState := return { core := (← getThe Core.State), meta := (← get) } /-- Restore backtrackable parts of the state. -/ def SavedState.restore (b : SavedState) : MetaM Unit := do Core.restore b.core modify fun s => { s with mctx := b.meta.mctx, zetaFVarIds := b.meta.zetaFVarIds, postponed := b.meta.postponed } instance : MonadBacktrack SavedState MetaM where saveState := Meta.saveState restoreState s := s.restore @[inline] def MetaM.run (x : MetaM α) (ctx : Context := {}) (s : State := {}) : CoreM (α × State) := x ctx |>.run s @[inline] def MetaM.run' (x : MetaM α) (ctx : Context := {}) (s : State := {}) : CoreM α := Prod.fst <$> x.run ctx s @[inline] def MetaM.toIO (x : MetaM α) (ctxCore : Core.Context) (sCore : Core.State) (ctx : Context := {}) (s : State := {}) : IO (α × Core.State × State) := do let ((a, s), sCore) ← (x.run ctx s).toIO ctxCore sCore pure (a, sCore, s) instance [MetaEval α] : MetaEval (MetaM α) := ⟨fun env opts x _ => MetaEval.eval env opts x.run' true⟩ protected def throwIsDefEqStuck : MetaM α := throw <| Exception.internal isDefEqStuckExceptionId builtin_initialize registerTraceClass `Meta registerTraceClass `Meta.debug export Core (instantiateTypeLevelParams instantiateValueLevelParams) @[inline] def liftMetaM [MonadLiftT MetaM m] (x : MetaM α) : m α := liftM x @[inline] def mapMetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, MetaM α → MetaM α) {α} (x : m α) : m α := controlAt MetaM fun runInBase => f <| runInBase x @[inline] def map1MetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, (β → MetaM α) → MetaM α) {α} (k : β → m α) : m α := controlAt MetaM fun runInBase => f fun b => runInBase <| k b @[inline] def map2MetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, (β → γ → MetaM α) → MetaM α) {α} (k : β → γ → m α) : m α := controlAt MetaM fun runInBase => f fun b c => runInBase <| k b c section Methods variable [MonadControlT MetaM n] [Monad n] @[inline] def modifyCache (f : Cache → Cache) : MetaM Unit := modify fun ⟨mctx, cache, zetaFVarIds, postponed⟩ => ⟨mctx, f cache, zetaFVarIds, postponed⟩ @[inline] def modifyInferTypeCache (f : InferTypeCache → InferTypeCache) : MetaM Unit := modifyCache fun ⟨ic, c1, c2, c3, c4, c5⟩ => ⟨f ic, c1, c2, c3, c4, c5⟩ @[inline] def modifyDefEqCache (f : DefEqCache → DefEqCache) : MetaM Unit := modifyCache fun ⟨c1, c2, c3, c4, c5, defeq⟩ => ⟨c1, c2, c3, c4, c5, f defeq⟩ def getLocalInstances : MetaM LocalInstances := return (← read).localInstances def getConfig : MetaM Config := return (← read).config def resetZetaFVarIds : MetaM Unit := modify fun s => { s with zetaFVarIds := {} } def getZetaFVarIds : MetaM FVarIdSet := return (← get).zetaFVarIds /-- Return the array of postponed universe level constraints. -/ def getPostponed : MetaM (PersistentArray PostponedEntry) := return (← get).postponed /-- Set the array of postponed universe level constraints. -/ def setPostponed (postponed : PersistentArray PostponedEntry) : MetaM Unit := modify fun s => { s with postponed := postponed } /-- Modify the array of postponed universe level constraints. -/ @[inline] def modifyPostponed (f : PersistentArray PostponedEntry → PersistentArray PostponedEntry) : MetaM Unit := modify fun s => { s with postponed := f s.postponed } /-- `useEtaStruct inductName` return `true` if we eta for structures is enabled for for the inductive datatype `inductName`. Recall we have three different settings: `.none` (never use it), `.all` (always use it), `.notClasses` (enabled only for structure-like inductive types that are not classes). The parameter `inductName` affects the result only if the current setting is `.notClasses`. -/ def useEtaStruct (inductName : Name) : MetaM Bool := do match (← getConfig).etaStruct with | .none => return false | .all => return true | .notClasses => return !isClass (← getEnv) inductName /-! WARNING: The following 4 constants are a hack for simulating forward declarations. They are defined later using the `export` attribute. This is hackish because we have to hard-code the true arity of these definitions here, and make sure the C names match. We have used another hack based on `IO.Ref`s in the past, it was safer but less efficient. -/ /-- Reduces an expression to its Weak Head Normal Form. This is when the topmost expression has been fully reduced, but may contain subexpressions which have not been reduced. -/ @[extern 6 "lean_whnf"] opaque whnf : Expr → MetaM Expr /-- Returns the inferred type of the given expression, or fails if it is not type-correct. -/ @[extern 6 "lean_infer_type"] opaque inferType : Expr → MetaM Expr @[extern 7 "lean_is_expr_def_eq"] opaque isExprDefEqAux : Expr → Expr → MetaM Bool @[extern 7 "lean_is_level_def_eq"] opaque isLevelDefEqAux : Level → Level → MetaM Bool @[extern 6 "lean_synth_pending"] protected opaque synthPending : MVarId → MetaM Bool def whnfForall (e : Expr) : MetaM Expr := do let e' ← whnf e if e'.isForall then pure e' else pure e -- withIncRecDepth for a monad `n` such that `[MonadControlT MetaM n]` protected def withIncRecDepth (x : n α) : n α := mapMetaM (withIncRecDepth (m := MetaM)) x private def mkFreshExprMVarAtCore (mvarId : MVarId) (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (kind : MetavarKind) (userName : Name) (numScopeArgs : Nat) : MetaM Expr := do modifyMCtx fun mctx => mctx.addExprMVarDecl mvarId userName lctx localInsts type kind numScopeArgs; return mkMVar mvarId def mkFreshExprMVarAt (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (kind : MetavarKind := MetavarKind.natural) (userName : Name := Name.anonymous) (numScopeArgs : Nat := 0) : MetaM Expr := do mkFreshExprMVarAtCore (← mkFreshMVarId) lctx localInsts type kind userName numScopeArgs def mkFreshLevelMVar : MetaM Level := do let mvarId ← mkFreshLMVarId modifyMCtx fun mctx => mctx.addLevelMVarDecl mvarId; return mkLevelMVar mvarId private def mkFreshExprMVarCore (type : Expr) (kind : MetavarKind) (userName : Name) : MetaM Expr := do mkFreshExprMVarAt (← getLCtx) (← getLocalInstances) type kind userName private def mkFreshExprMVarImpl (type? : Option Expr) (kind : MetavarKind) (userName : Name) : MetaM Expr := match type? with | some type => mkFreshExprMVarCore type kind userName | none => do let u ← mkFreshLevelMVar let type ← mkFreshExprMVarCore (mkSort u) MetavarKind.natural Name.anonymous mkFreshExprMVarCore type kind userName def mkFreshExprMVar (type? : Option Expr) (kind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr := mkFreshExprMVarImpl type? kind userName def mkFreshTypeMVar (kind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr := do let u ← mkFreshLevelMVar mkFreshExprMVar (mkSort u) kind userName /-- Low-level version of `MkFreshExprMVar` which allows users to create/reserve a `mvarId` using `mkFreshId`, and then later create the metavar using this method. -/ private def mkFreshExprMVarWithIdCore (mvarId : MVarId) (type : Expr) (kind : MetavarKind := MetavarKind.natural) (userName : Name := Name.anonymous) (numScopeArgs : Nat := 0) : MetaM Expr := do mkFreshExprMVarAtCore mvarId (← getLCtx) (← getLocalInstances) type kind userName numScopeArgs def mkFreshExprMVarWithId (mvarId : MVarId) (type? : Option Expr := none) (kind : MetavarKind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr := match type? with | some type => mkFreshExprMVarWithIdCore mvarId type kind userName | none => do let u ← mkFreshLevelMVar let type ← mkFreshExprMVar (mkSort u) mkFreshExprMVarWithIdCore mvarId type kind userName def mkFreshLevelMVars (num : Nat) : MetaM (List Level) := num.foldM (init := []) fun _ us => return (← mkFreshLevelMVar)::us def mkFreshLevelMVarsFor (info : ConstantInfo) : MetaM (List Level) := mkFreshLevelMVars info.numLevelParams /-- Create a constant with the given name and new universe metavariables. Example: ``mkConstWithFreshMVarLevels `Monad`` returns `@Monad.{?u, ?v}` -/ def mkConstWithFreshMVarLevels (declName : Name) : MetaM Expr := do let info ← getConstInfo declName return mkConst declName (← mkFreshLevelMVarsFor info) /-- Return current transparency setting/mode. -/ def getTransparency : MetaM TransparencyMode := return (← getConfig).transparency def shouldReduceAll : MetaM Bool := return (← getTransparency) == TransparencyMode.all def shouldReduceReducibleOnly : MetaM Bool := return (← getTransparency) == TransparencyMode.reducible /-- Return `some mvarDecl` where `mvarDecl` is `mvarId` declaration in the current metavariable context. Return `none` if `mvarId` has no declaration in the current metavariable context. -/ def _root_.Lean.MVarId.findDecl? (mvarId : MVarId) : MetaM (Option MetavarDecl) := return (← getMCtx).findDecl? mvarId @[deprecated MVarId.findDecl?] def findMVarDecl? (mvarId : MVarId) : MetaM (Option MetavarDecl) := mvarId.findDecl? /-- Return `mvarId` declaration in the current metavariable context. Throw an exception if `mvarId` is not declarated in the current metavariable context. -/ def _root_.Lean.MVarId.getDecl (mvarId : MVarId) : MetaM MetavarDecl := do match (← mvarId.findDecl?) with | some d => pure d | none => throwError "unknown metavariable '?{mvarId.name}'" @[deprecated MVarId.getDecl] def getMVarDecl (mvarId : MVarId) : MetaM MetavarDecl := do mvarId.getDecl /-- Return `mvarId` kind. Throw an exception if `mvarId` is not declarated in the current metavariable context. -/ def _root_.Lean.MVarId.getKind (mvarId : MVarId) : MetaM MetavarKind := return (← mvarId.getDecl).kind @[deprecated MVarId.getKind] def getMVarDeclKind (mvarId : MVarId) : MetaM MetavarKind := mvarId.getKind /-- Reture `true` if `e` is a synthetic (or synthetic opaque) metavariable -/ def isSyntheticMVar (e : Expr) : MetaM Bool := do if e.isMVar then return (← e.mvarId!.getKind) matches .synthetic | .syntheticOpaque else return false /-- Set `mvarId` kind in the current metavariable context. -/ def _root_.Lean.MVarId.setKind (mvarId : MVarId) (kind : MetavarKind) : MetaM Unit := modifyMCtx fun mctx => mctx.setMVarKind mvarId kind @[deprecated MVarId.setKind] def setMVarKind (mvarId : MVarId) (kind : MetavarKind) : MetaM Unit := mvarId.setKind kind /-- Update the type of the given metavariable. This function assumes the new type is definitionally equal to the current one -/ def _root_.Lean.MVarId.setType (mvarId : MVarId) (type : Expr) : MetaM Unit := do modifyMCtx fun mctx => mctx.setMVarType mvarId type @[deprecated MVarId.setType] def setMVarType (mvarId : MVarId) (type : Expr) : MetaM Unit := do mvarId.setType type /-- Return true if the given metavariable is "read-only". That is, its `depth` is different from the current metavariable context depth. -/ def _root_.Lean.MVarId.isReadOnly (mvarId : MVarId) : MetaM Bool := do return (← mvarId.getDecl).depth != (← getMCtx).depth @[deprecated MVarId.isReadOnly] def isReadOnlyExprMVar (mvarId : MVarId) : MetaM Bool := do mvarId.isReadOnly /-- Return true if `mvarId.isReadOnly` return true or if `mvarId` is a synthetic opaque metavariable. Recall `isDefEq` will not assign a value to `mvarId` if `mvarId.isReadOnlyOrSyntheticOpaque`. -/ def _root_.Lean.MVarId.isReadOnlyOrSyntheticOpaque (mvarId : MVarId) : MetaM Bool := do let mvarDecl ← mvarId.getDecl match mvarDecl.kind with | MetavarKind.syntheticOpaque => return !(← getConfig).assignSyntheticOpaque | _ => return mvarDecl.depth != (← getMCtx).depth @[deprecated MVarId.isReadOnlyOrSyntheticOpaque] def isReadOnlyOrSyntheticOpaqueExprMVar (mvarId : MVarId) : MetaM Bool := do mvarId.isReadOnlyOrSyntheticOpaque /-- Return the level of the given universe level metavariable. -/ def _root_.Lean.LMVarId.getLevel (mvarId : LMVarId) : MetaM Nat := do match (← getMCtx).findLevelDepth? mvarId with | some depth => return depth | _ => throwError "unknown universe metavariable '?{mvarId.name}'" @[deprecated LMVarId.getLevel] def getLevelMVarDepth (mvarId : LMVarId) : MetaM Nat := mvarId.getLevel /-- Return true if the given universe metavariable is "read-only". That is, its `depth` is different from the current metavariable context depth. -/ def _root_.Lean.LMVarId.isReadOnly (mvarId : LMVarId) : MetaM Bool := do if (← getConfig).ignoreLevelMVarDepth then return false else return (← mvarId.getLevel) != (← getMCtx).depth @[deprecated LMVarId.isReadOnly] def isReadOnlyLevelMVar (mvarId : LMVarId) : MetaM Bool := do mvarId.isReadOnly /-- Set the user-facing name for the given metavariable. -/ def _root_.Lean.MVarId.setUserName (mvarId : MVarId) (newUserName : Name) : MetaM Unit := modifyMCtx fun mctx => mctx.setMVarUserName mvarId newUserName @[deprecated MVarId.setUserName] def setMVarUserName (mvarId : MVarId) (userNameNew : Name) : MetaM Unit := mvarId.setUserName userNameNew /-- Throw an exception saying `fvarId` is not declared in the current local context. -/ def _root_.Lean.FVarId.throwUnknown (fvarId : FVarId) : CoreM α := throwError "unknown free variable '{mkFVar fvarId}'" @[deprecated FVarId.throwUnknown] def throwUnknownFVar (fvarId : FVarId) : MetaM α := fvarId.throwUnknown /-- Return `some decl` if `fvarId` is declared in the current local context. -/ def _root_.Lean.FVarId.findDecl? (fvarId : FVarId) : MetaM (Option LocalDecl) := return (← getLCtx).find? fvarId @[deprecated FVarId.findDecl?] def findLocalDecl? (fvarId : FVarId) : MetaM (Option LocalDecl) := fvarId.findDecl? /-- Return the local declaration for the given free variable. Throw an exception if local declaration is not in the current local context. -/ def _root_.Lean.FVarId.getDecl (fvarId : FVarId) : MetaM LocalDecl := do match (← getLCtx).find? fvarId with | some d => return d | none => fvarId.throwUnknown @[deprecated FVarId.getDecl] def getLocalDecl (fvarId : FVarId) : MetaM LocalDecl := do fvarId.getDecl /-- Return the type of the given free variable. -/ def _root_.Lean.FVarId.getType (fvarId : FVarId) : MetaM Expr := return (← fvarId.getDecl).type /-- Return the binder information for the given free variable. -/ def _root_.Lean.FVarId.getBinderInfo (fvarId : FVarId) : MetaM BinderInfo := return (← fvarId.getDecl).binderInfo /-- Return `some value` if the given free variable is a let-declaration, and `none` otherwise. -/ def _root_.Lean.FVarId.getValue? (fvarId : FVarId) : MetaM (Option Expr) := return (← fvarId.getDecl).value? /-- Return the user-facing name for the given free variable. -/ def _root_.Lean.FVarId.getUserName (fvarId : FVarId) : MetaM Name := return (← fvarId.getDecl).userName /-- Return `true` is the free variable is a let-variable. -/ def _root_.Lean.FVarId.isLetVar (fvarId : FVarId) : MetaM Bool := return (← fvarId.getDecl).isLet /-- Get the local declaration associated to the given `Expr` in the current local context. Fails if the given expression is not a fvar or if no such declaration exists. -/ def getFVarLocalDecl (fvar : Expr) : MetaM LocalDecl := fvar.fvarId!.getDecl /-- Given a user-facing name for a free variable, return its declaration in the current local context. Throw an exception if free variable is not declared. -/ def getLocalDeclFromUserName (userName : Name) : MetaM LocalDecl := do match (← getLCtx).findFromUserName? userName with | some d => pure d | none => throwError "unknown local declaration '{userName}'" /-- Lift a `MkBindingM` monadic action `x` to `MetaM`. -/ @[inline] def liftMkBindingM (x : MetavarContext.MkBindingM α) : MetaM α := do match x { lctx := (← getLCtx), mainModule := (← getEnv).mainModule } { mctx := (← getMCtx), ngen := (← getNGen), nextMacroScope := (← getThe Core.State).nextMacroScope } with | .ok e sNew => do setMCtx sNew.mctx modifyThe Core.State fun s => { s with ngen := sNew.ngen, nextMacroScope := sNew.nextMacroScope } pure e | .error (.revertFailure ..) sNew => do setMCtx sNew.mctx modifyThe Core.State fun s => { s with ngen := sNew.ngen, nextMacroScope := sNew.nextMacroScope } throwError "failed to create binder due to failure when reverting variable dependencies" /-- Similar to `abstracM` but consider only the first `min n xs.size` entries in `xs` It is also similar to `Expr.abstractRange`, but handles metavariables correctly. It uses `elimMVarDeps` to ensure `e` and the type of the free variables `xs` do not contain a metavariable `?m` s.t. local context of `?m` contains a free variable in `xs`. -/ def _root_.Lean.Expr.abstractRangeM (e : Expr) (n : Nat) (xs : Array Expr) : MetaM Expr := liftMkBindingM <| MetavarContext.abstractRange e n xs @[deprecated Expr.abstractRangeM] def abstractRange (e : Expr) (n : Nat) (xs : Array Expr) : MetaM Expr := e.abstractRangeM n xs /-- Replace free (or meta) variables `xs` with loose bound variables. Similar to `Expr.abstract`, but handles metavariables correctly. -/ def _root_.Lean.Expr.abstractM (e : Expr) (xs : Array Expr) : MetaM Expr := e.abstractRangeM xs.size xs @[deprecated Expr.abstractM] def abstract (e : Expr) (xs : Array Expr) : MetaM Expr := e.abstractM xs /-- Collect forward dependencies for the free variables in `toRevert`. Recall that when reverting free variables `xs`, we must also revert their forward dependencies. -/ def collectForwardDeps (toRevert : Array Expr) (preserveOrder : Bool) : MetaM (Array Expr) := do liftMkBindingM <| MetavarContext.collectForwardDeps toRevert preserveOrder /-- Takes an array `xs` of free variables or metavariables and a term `e` that may contain those variables, and abstracts and binds them as universal quantifiers. - if `usedOnly = true` then only variables that the expression body depends on will appear. - if `usedLetOnly = true` same as `usedOnly` except for let-bound variables. (That is, local constants which have been assigned a value.) -/ def mkForallFVars (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) (binderInfoForMVars := BinderInfo.implicit) : MetaM Expr := if xs.isEmpty then return e else liftMkBindingM <| MetavarContext.mkForall xs e usedOnly usedLetOnly binderInfoForMVars /-- Takes an array `xs` of free variables and metavariables and a body term `e` and creates `fun ..xs => e`, suitably abstracting `e` and the types in `xs`. -/ def mkLambdaFVars (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) (binderInfoForMVars := BinderInfo.implicit) : MetaM Expr := if xs.isEmpty then return e else liftMkBindingM <| MetavarContext.mkLambda xs e usedOnly usedLetOnly binderInfoForMVars def mkLetFVars (xs : Array Expr) (e : Expr) (usedLetOnly := true) (binderInfoForMVars := BinderInfo.implicit) : MetaM Expr := mkLambdaFVars xs e (usedLetOnly := usedLetOnly) (binderInfoForMVars := binderInfoForMVars) /-- `fun _ : Unit => a` -/ def mkFunUnit (a : Expr) : MetaM Expr := return Lean.mkLambda (← mkFreshUserName `x) BinderInfo.default (mkConst ``Unit) a def elimMVarDeps (xs : Array Expr) (e : Expr) (preserveOrder : Bool := false) : MetaM Expr := if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.elimMVarDeps xs e preserveOrder /-- `withConfig f x` executes `x` using the updated configuration object obtained by applying `f`. -/ @[inline] def withConfig (f : Config → Config) : n α → n α := mapMetaM <| withReader (fun ctx => { ctx with config := f ctx.config }) @[inline] def withTrackingZeta (x : n α) : n α := withConfig (fun cfg => { cfg with trackZeta := true }) x @[inline] def withoutProofIrrelevance (x : n α) : n α := withConfig (fun cfg => { cfg with proofIrrelevance := false }) x @[inline] def withTransparency (mode : TransparencyMode) : n α → n α := mapMetaM <| withConfig (fun config => { config with transparency := mode }) /-- `withDefault x` excutes `x` using the default transparency setting. -/ @[inline] def withDefault (x : n α) : n α := withTransparency TransparencyMode.default x /-- `withReducible x` excutes `x` using the reducible transparency setting. In this setting only definitions tagged as `[reducible]` are unfolded. -/ @[inline] def withReducible (x : n α) : n α := withTransparency TransparencyMode.reducible x /-- `withReducibleAndInstances x` excutes `x` using the `.instances` transparency setting. In this setting only definitions tagged as `[reducible]` or type class instances are unfolded. -/ @[inline] def withReducibleAndInstances (x : n α) : n α := withTransparency TransparencyMode.instances x /-- Execute `x` ensuring the transparency setting is at least `mode`. Recall that `.all > .default > .instances > .reducible`. -/ @[inline] def withAtLeastTransparency (mode : TransparencyMode) (x : n α) : n α := withConfig (fun config => let oldMode := config.transparency let mode := if oldMode.lt mode then mode else oldMode { config with transparency := mode }) x /-- Execute `x` allowing `isDefEq` to assign synthetic opaque metavariables. -/ @[inline] def withAssignableSyntheticOpaque (x : n α) : n α := withConfig (fun config => { config with assignSyntheticOpaque := true }) x /-- Save cache, execute `x`, restore cache -/ @[inline] private def savingCacheImpl (x : MetaM α) : MetaM α := do let savedCache := (← get).cache try x finally modify fun s => { s with cache := savedCache } @[inline] def savingCache : n α → n α := mapMetaM savingCacheImpl def getTheoremInfo (info : ConstantInfo) : MetaM (Option ConstantInfo) := do if (← shouldReduceAll) then return some info else return none private def getDefInfoTemp (info : ConstantInfo) : MetaM (Option ConstantInfo) := do match (← getTransparency) with | TransparencyMode.all => return some info | TransparencyMode.default => return some info | _ => if (← isReducible info.name) then return some info else return none /-- Remark: we later define `getConst?` at `GetConst.lean` after we define `Instances.lean`. This method is only used to implement `isClassQuickConst?`. It is very similar to `getConst?`, but it returns none when `TransparencyMode.instances` and `constName` is an instance. This difference should be irrelevant for `isClassQuickConst?`. -/ private def getConstTemp? (constName : Name) : MetaM (Option ConstantInfo) := do match (← getEnv).find? constName with | some (info@(ConstantInfo.thmInfo _)) => getTheoremInfo info | some (info@(ConstantInfo.defnInfo _)) => getDefInfoTemp info | some info => pure (some info) | none => throwUnknownConstant constName private def isClassQuickConst? (constName : Name) : MetaM (LOption Name) := do if isClass (← getEnv) constName then return .some constName else match (← getConstTemp? constName) with | some (.defnInfo ..) => return .undef -- We may be able to unfold the definition | _ => return .none private partial def isClassQuick? : Expr → MetaM (LOption Name) | .bvar .. => return .none | .lit .. => return .none | .fvar .. => return .none | .sort .. => return .none | .lam .. => return .none | .letE .. => return .undef | .proj .. => return .undef | .forallE _ _ b _ => isClassQuick? b | .mdata _ e => isClassQuick? e | .const n _ => isClassQuickConst? n | .mvar mvarId => do match (← getExprMVarAssignment? mvarId) with | some val => isClassQuick? val | none => return .none | .app f _ => match f.getAppFn with | .const n .. => isClassQuickConst? n | .lam .. => return .undef | _ => return .none def saveAndResetSynthInstanceCache : MetaM SynthInstanceCache := do let savedSythInstance := (← get).cache.synthInstance modifyCache fun c => { c with synthInstance := {} } return savedSythInstance def restoreSynthInstanceCache (cache : SynthInstanceCache) : MetaM Unit := modifyCache fun c => { c with synthInstance := cache } @[inline] private def resettingSynthInstanceCacheImpl (x : MetaM α) : MetaM α := do let savedSythInstance ← saveAndResetSynthInstanceCache try x finally restoreSynthInstanceCache savedSythInstance /-- Reset `synthInstance` cache, execute `x`, and restore cache -/ @[inline] def resettingSynthInstanceCache : n α → n α := mapMetaM resettingSynthInstanceCacheImpl @[inline] def resettingSynthInstanceCacheWhen (b : Bool) (x : n α) : n α := if b then resettingSynthInstanceCache x else x private def withNewLocalInstanceImp (className : Name) (fvar : Expr) (k : MetaM α) : MetaM α := do let localDecl ← getFVarLocalDecl fvar /- Recall that we use `auxDecl` binderInfo when compiling recursive declarations. -/ match localDecl.binderInfo with | .auxDecl => k | _ => resettingSynthInstanceCache <| withReader (fun ctx => { ctx with localInstances := ctx.localInstances.push { className := className, fvar := fvar } }) k /-- Add entry `{ className := className, fvar := fvar }` to localInstances, and then execute continuation `k`. It resets the type class cache using `resettingSynthInstanceCache`. -/ def withNewLocalInstance (className : Name) (fvar : Expr) : n α → n α := mapMetaM <| withNewLocalInstanceImp className fvar private def fvarsSizeLtMaxFVars (fvars : Array Expr) (maxFVars? : Option Nat) : Bool := match maxFVars? with | some maxFVars => fvars.size < maxFVars | none => true mutual /-- `withNewLocalInstances isClassExpensive fvars j k` updates the vector or local instances using free variables `fvars[j] ... fvars.back`, and execute `k`. - `isClassExpensive` is defined later. - The type class chache is reset whenever a new local instance is found. - `isClassExpensive` uses `whnf` which depends (indirectly) on the set of local instances. Thus, each new local instance requires a new `resettingSynthInstanceCache`. -/ private partial def withNewLocalInstancesImp (fvars : Array Expr) (i : Nat) (k : MetaM α) : MetaM α := do if h : i < fvars.size then let fvar := fvars.get ⟨i, h⟩ let decl ← getFVarLocalDecl fvar match (← isClassQuick? decl.type) with | .none => withNewLocalInstancesImp fvars (i+1) k | .undef => match (← isClassExpensive? decl.type) with | none => withNewLocalInstancesImp fvars (i+1) k | some c => withNewLocalInstance c fvar <| withNewLocalInstancesImp fvars (i+1) k | .some c => withNewLocalInstance c fvar <| withNewLocalInstancesImp fvars (i+1) k else k /-- `forallTelescopeAuxAux lctx fvars j type` Remarks: - `lctx` is the `MetaM` local context extended with declarations for `fvars`. - `type` is the type we are computing the telescope for. It contains only dangling bound variables in the range `[j, fvars.size)` - if `reducing? == true` and `type` is not `forallE`, we use `whnf`. - when `type` is not a `forallE` nor it can't be reduced to one, we excute the continuation `k`. Here is an example that demonstrates the `reducing?`. Suppose we have ``` abbrev StateM s a := s -> Prod a s ``` Now, assume we are trying to build the telescope for ``` forall (x : Nat), StateM Int Bool ``` if `reducing == true`, the function executes `k #[(x : Nat) (s : Int)] Bool`. if `reducing == false`, the function executes `k #[(x : Nat)] (StateM Int Bool)` if `maxFVars?` is `some max`, then we interrupt the telescope construction when `fvars.size == max` -/ private partial def forallTelescopeReducingAuxAux (reducing : Bool) (maxFVars? : Option Nat) (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := do let rec process (lctx : LocalContext) (fvars : Array Expr) (j : Nat) (type : Expr) : MetaM α := do match type with | .forallE n d b bi => if fvarsSizeLtMaxFVars fvars maxFVars? then let d := d.instantiateRevRange j fvars.size fvars let fvarId ← mkFreshFVarId let lctx := lctx.mkLocalDecl fvarId n d bi let fvar := mkFVar fvarId let fvars := fvars.push fvar process lctx fvars j b else let type := type.instantiateRevRange j fvars.size fvars; withReader (fun ctx => { ctx with lctx := lctx }) do withNewLocalInstancesImp fvars j do k fvars type | _ => let type := type.instantiateRevRange j fvars.size fvars; withReader (fun ctx => { ctx with lctx := lctx }) do withNewLocalInstancesImp fvars j do if reducing && fvarsSizeLtMaxFVars fvars maxFVars? then let newType ← whnf type if newType.isForall then process lctx fvars fvars.size newType else k fvars type else k fvars type process (← getLCtx) #[] 0 type private partial def forallTelescopeReducingAux (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → MetaM α) : MetaM α := do match maxFVars? with | some 0 => k #[] type | _ => do let newType ← whnf type if newType.isForall then forallTelescopeReducingAuxAux true maxFVars? newType k else k #[] type private partial def isClassExpensive? (type : Expr) : MetaM (Option Name) := withReducible do -- when testing whether a type is a type class, we only unfold reducible constants. forallTelescopeReducingAux type none fun _ type => do let env ← getEnv match type.getAppFn with | .const c _ => do if isClass env c then return some c else -- make sure abbreviations are unfolded match (← whnf type).getAppFn with | .const c _ => return if isClass env c then some c else none | _ => return none | _ => return none private partial def isClassImp? (type : Expr) : MetaM (Option Name) := do match (← isClassQuick? type) with | .none => return none | .some c => return (some c) | .undef => isClassExpensive? type end /-- `isClass? type` return `some ClsName` if `type` is an instance of the class `ClsName`. Example: ``` #eval do let x ← mkAppM ``Inhabited #[mkConst ``Nat] IO.println (← isClass? x) -- (some Inhabited) ``` -/ def isClass? (type : Expr) : MetaM (Option Name) := try isClassImp? type catch _ => return none private def withNewLocalInstancesImpAux (fvars : Array Expr) (j : Nat) : n α → n α := mapMetaM <| withNewLocalInstancesImp fvars j partial def withNewLocalInstances (fvars : Array Expr) (j : Nat) : n α → n α := mapMetaM <| withNewLocalInstancesImpAux fvars j @[inline] private def forallTelescopeImp (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := do forallTelescopeReducingAuxAux (reducing := false) (maxFVars? := none) type k /-- Given `type` of the form `forall xs, A`, execute `k xs A`. This combinator will declare local declarations, create free variables for them, execute `k` with updated local context, and make sure the cache is restored after executing `k`. -/ def forallTelescope (type : Expr) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => forallTelescopeImp type k) k private def forallTelescopeReducingImp (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := forallTelescopeReducingAux type (maxFVars? := none) k /-- Similar to `forallTelescope`, but given `type` of the form `forall xs, A`, it reduces `A` and continues bulding the telescope if it is a `forall`. -/ def forallTelescopeReducing (type : Expr) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => forallTelescopeReducingImp type k) k private def forallBoundedTelescopeImp (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → MetaM α) : MetaM α := forallTelescopeReducingAux type maxFVars? k /-- Similar to `forallTelescopeReducing`, stops constructing the telescope when it reaches size `maxFVars`. -/ def forallBoundedTelescope (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => forallBoundedTelescopeImp type maxFVars? k) k private partial def lambdaTelescopeImp (e : Expr) (consumeLet : Bool) (k : Array Expr → Expr → MetaM α) : MetaM α := do process consumeLet (← getLCtx) #[] 0 e where process (consumeLet : Bool) (lctx : LocalContext) (fvars : Array Expr) (j : Nat) (e : Expr) : MetaM α := do match consumeLet, e with | _, .lam n d b bi => let d := d.instantiateRevRange j fvars.size fvars let fvarId ← mkFreshFVarId let lctx := lctx.mkLocalDecl fvarId n d bi let fvar := mkFVar fvarId process consumeLet lctx (fvars.push fvar) j b | true, .letE n t v b _ => do let t := t.instantiateRevRange j fvars.size fvars let v := v.instantiateRevRange j fvars.size fvars let fvarId ← mkFreshFVarId let lctx := lctx.mkLetDecl fvarId n t v let fvar := mkFVar fvarId process true lctx (fvars.push fvar) j b | _, e => let e := e.instantiateRevRange j fvars.size fvars withReader (fun ctx => { ctx with lctx := lctx }) do withNewLocalInstancesImp fvars j do k fvars e /-- Similar to `lambdaTelescope` but for lambda and let expressions. -/ def lambdaLetTelescope (e : Expr) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => lambdaTelescopeImp e true k) k /-- Given `e` of the form `fun ..xs => A`, execute `k xs A`. This combinator will declare local declarations, create free variables for them, execute `k` with updated local context, and make sure the cache is restored after executing `k`. -/ def lambdaTelescope (e : Expr) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => lambdaTelescopeImp e false k) k /-- Return the parameter names for the given global declaration. -/ def getParamNames (declName : Name) : MetaM (Array Name) := do forallTelescopeReducing (← getConstInfo declName).type fun xs _ => do xs.mapM fun x => do let localDecl ← x.fvarId!.getDecl return localDecl.userName -- `kind` specifies the metavariable kind for metavariables not corresponding to instance implicit `[ ... ]` arguments. private partial def forallMetaTelescopeReducingAux (e : Expr) (reducing : Bool) (maxMVars? : Option Nat) (kind : MetavarKind) : MetaM (Array Expr × Array BinderInfo × Expr) := process #[] #[] 0 e where process (mvars : Array Expr) (bis : Array BinderInfo) (j : Nat) (type : Expr) : MetaM (Array Expr × Array BinderInfo × Expr) := do if maxMVars?.isEqSome mvars.size then let type := type.instantiateRevRange j mvars.size mvars; return (mvars, bis, type) else match type with | .forallE n d b bi => let d := d.instantiateRevRange j mvars.size mvars let k := if bi.isInstImplicit then MetavarKind.synthetic else kind let mvar ← mkFreshExprMVar d k n let mvars := mvars.push mvar let bis := bis.push bi process mvars bis j b | _ => let type := type.instantiateRevRange j mvars.size mvars; if reducing then do let newType ← whnf type; if newType.isForall then process mvars bis mvars.size newType else return (mvars, bis, type) else return (mvars, bis, type) /-- Given `e` of the form `forall ..xs, A`, this combinator will create a new metavariable for each `x` in `xs` and instantiate `A` with these. Returns a product containing - the new metavariables - the binder info for the `xs` - the instantiated `A` -/ def forallMetaTelescope (e : Expr) (kind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) := forallMetaTelescopeReducingAux e (reducing := false) (maxMVars? := none) kind /-- Similar to `forallMetaTelescope`, but if `e = forall ..xs, A` it will reduce `A` to construct further mvars. -/ def forallMetaTelescopeReducing (e : Expr) (maxMVars? : Option Nat := none) (kind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) := forallMetaTelescopeReducingAux e (reducing := true) maxMVars? kind /-- Similar to `forallMetaTelescopeReducing`, stops constructing the telescope when it reaches size `maxMVars`. -/ def forallMetaBoundedTelescope (e : Expr) (maxMVars : Nat) (kind : MetavarKind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) := forallMetaTelescopeReducingAux e (reducing := true) (maxMVars? := some maxMVars) (kind := kind) /-- Similar to `forallMetaTelescopeReducingAux` but for lambda expressions. -/ partial def lambdaMetaTelescope (e : Expr) (maxMVars? : Option Nat := none) : MetaM (Array Expr × Array BinderInfo × Expr) := process #[] #[] 0 e where process (mvars : Array Expr) (bis : Array BinderInfo) (j : Nat) (type : Expr) : MetaM (Array Expr × Array BinderInfo × Expr) := do let finalize : Unit → MetaM (Array Expr × Array BinderInfo × Expr) := fun _ => do let type := type.instantiateRevRange j mvars.size mvars return (mvars, bis, type) if maxMVars?.isEqSome mvars.size then finalize () else match type with | .lam _ d b bi => let d := d.instantiateRevRange j mvars.size mvars let mvar ← mkFreshExprMVar d let mvars := mvars.push mvar let bis := bis.push bi process mvars bis j b | _ => finalize () private def withNewFVar (fvar fvarType : Expr) (k : Expr → MetaM α) : MetaM α := do match (← isClass? fvarType) with | none => k fvar | some c => withNewLocalInstance c fvar <| k fvar private def withLocalDeclImp (n : Name) (bi : BinderInfo) (type : Expr) (k : Expr → MetaM α) : MetaM α := do let fvarId ← mkFreshFVarId let ctx ← read let lctx := ctx.lctx.mkLocalDecl fvarId n type bi let fvar := mkFVar fvarId withReader (fun ctx => { ctx with lctx := lctx }) do withNewFVar fvar type k /-- Create a free variable `x` with name, binderInfo and type, add it to the context and run in `k`. Then revert the context. -/ def withLocalDecl (name : Name) (bi : BinderInfo) (type : Expr) (k : Expr → n α) : n α := map1MetaM (fun k => withLocalDeclImp name bi type k) k def withLocalDeclD (name : Name) (type : Expr) (k : Expr → n α) : n α := withLocalDecl name BinderInfo.default type k /-- Append an array of free variables `xs` to the local context and execute `k xs`. declInfos takes the form of an array consisting of: - the name of the variable - the binder info of the variable - a type constructor for the variable, where the array consists of all of the free variables defined prior to this one. This is needed because the type of the variable may depend on prior variables. -/ partial def withLocalDecls [Inhabited α] (declInfos : Array (Name × BinderInfo × (Array Expr → n Expr))) (k : (xs : Array Expr) → n α) : n α := loop #[] where loop [Inhabited α] (acc : Array Expr) : n α := do if acc.size < declInfos.size then let (name, bi, typeCtor) := declInfos[acc.size]! withLocalDecl name bi (←typeCtor acc) fun x => loop (acc.push x) else k acc def withLocalDeclsD [Inhabited α] (declInfos : Array (Name × (Array Expr → n Expr))) (k : (xs : Array Expr) → n α) : n α := withLocalDecls (declInfos.map (fun (name, typeCtor) => (name, BinderInfo.default, typeCtor))) k private def withNewBinderInfosImp (bs : Array (FVarId × BinderInfo)) (k : MetaM α) : MetaM α := do let lctx := bs.foldl (init := (← getLCtx)) fun lctx (fvarId, bi) => lctx.setBinderInfo fvarId bi withReader (fun ctx => { ctx with lctx := lctx }) k def withNewBinderInfos (bs : Array (FVarId × BinderInfo)) (k : n α) : n α := mapMetaM (fun k => withNewBinderInfosImp bs k) k /-- Execute `k` using a local context where any `x` in `xs` that is tagged as instance implicit is treated as a regular implicit. -/ def withInstImplicitAsImplict (xs : Array Expr) (k : MetaM α) : MetaM α := do let newBinderInfos ← xs.filterMapM fun x => do let bi ← x.fvarId!.getBinderInfo if bi == .instImplicit then return some (x.fvarId!, .implicit) else return none withNewBinderInfos newBinderInfos k private def withLetDeclImp (n : Name) (type : Expr) (val : Expr) (k : Expr → MetaM α) : MetaM α := do let fvarId ← mkFreshFVarId let ctx ← read let lctx := ctx.lctx.mkLetDecl fvarId n type val let fvar := mkFVar fvarId withReader (fun ctx => { ctx with lctx := lctx }) do withNewFVar fvar type k /-- Add the local declaration `<name> : <type> := <val>` to the local context and execute `k x`, where `x` is a new free variable corresponding to the `let`-declaration. After executing `k x`, the local context is restored. -/ def withLetDecl (name : Name) (type : Expr) (val : Expr) (k : Expr → n α) : n α := map1MetaM (fun k => withLetDeclImp name type val k) k def withLocalInstancesImp (decls : List LocalDecl) (k : MetaM α) : MetaM α := do let localInsts := (← read).localInstances let size := localInsts.size let localInstsNew ← decls.foldlM (init := localInsts) fun localInstsNew decl => do match (← isClass? decl.type) with | none => return localInstsNew | some className => return localInstsNew.push { className, fvar := decl.toExpr } if localInstsNew.size == size then k else resettingSynthInstanceCache <| withReader (fun ctx => { ctx with localInstances := localInstsNew }) k /-- Register any local instance in `decls` -/ def withLocalInstances (decls : List LocalDecl) : n α → n α := mapMetaM <| withLocalInstancesImp decls private def withExistingLocalDeclsImp (decls : List LocalDecl) (k : MetaM α) : MetaM α := do let ctx ← read let lctx := decls.foldl (fun (lctx : LocalContext) decl => lctx.addDecl decl) ctx.lctx withReader (fun ctx => { ctx with lctx := lctx }) do withLocalInstancesImp decls k /-- `withExistingLocalDecls decls k`, adds the given local declarations to the local context, and then executes `k`. This method assumes declarations in `decls` have valid `FVarId`s. After executing `k`, the local context is restored. Remark: this method is used, for example, to implement the `match`-compiler. Each `match`-alternative commes with a local declarations (corresponding to pattern variables), and we use `withExistingLocalDecls` to add them to the local context before we process them. -/ def withExistingLocalDecls (decls : List LocalDecl) : n α → n α := mapMetaM <| withExistingLocalDeclsImp decls private def withNewMCtxDepthImp (x : MetaM α) : MetaM α := do let saved ← get modify fun s => { s with mctx := s.mctx.incDepth, postponed := {} } try x finally modify fun s => { s with mctx := saved.mctx, postponed := saved.postponed } /-- Save cache and `MetavarContext`, bump the `MetavarContext` depth, execute `x`, and restore saved data. Metavariable context depths are used to control which metavariables may be assigned in `isDefEq`. See the docstring of `isDefEq` for more information. -/ def withNewMCtxDepth : n α → n α := mapMetaM withNewMCtxDepthImp private def withLocalContextImp (lctx : LocalContext) (localInsts : LocalInstances) (x : MetaM α) : MetaM α := do let localInstsCurr ← getLocalInstances withReader (fun ctx => { ctx with lctx := lctx, localInstances := localInsts }) do if localInsts == localInstsCurr then x else resettingSynthInstanceCache x /-- `withLCtx lctx localInsts k` replaces the local context and local instances, and then executes `k`. The local context and instances are restored after executing `k`. This method assumes that the local instances in `localInsts` are in the local context `lctx`. -/ def withLCtx (lctx : LocalContext) (localInsts : LocalInstances) : n α → n α := mapMetaM <| withLocalContextImp lctx localInsts private def withMVarContextImp (mvarId : MVarId) (x : MetaM α) : MetaM α := do let mvarDecl ← mvarId.getDecl withLocalContextImp mvarDecl.lctx mvarDecl.localInstances x /-- Execute `x` using the given metavariable `LocalContext` and `LocalInstances`. The type class resolution cache is flushed when executing `x` if its `LocalInstances` are different from the current ones. -/ def _root_.Lean.MVarId.withContext (mvarId : MVarId) : n α → n α := mapMetaM <| withMVarContextImp mvarId @[deprecated MVarId.withContext] def withMVarContext (mvarId : MVarId) : n α → n α := mvarId.withContext private def withMCtxImp (mctx : MetavarContext) (x : MetaM α) : MetaM α := do let mctx' ← getMCtx setMCtx mctx try x finally setMCtx mctx' /-- `withMCtx mctx k` replaces the metavariable context and then executes `k`. The metavariable context is restored after executing `k`. This method is used to implement the type class resolution procedure. -/ def withMCtx (mctx : MetavarContext) : n α → n α := mapMetaM <| withMCtxImp mctx @[inline] private def approxDefEqImp (x : MetaM α) : MetaM α := withConfig (fun config => { config with foApprox := true, ctxApprox := true, quasiPatternApprox := true}) x /-- Execute `x` using approximate unification: `foApprox`, `ctxApprox` and `quasiPatternApprox`. -/ @[inline] def approxDefEq : n α → n α := mapMetaM approxDefEqImp @[inline] private def fullApproxDefEqImp (x : MetaM α) : MetaM α := withConfig (fun config => { config with foApprox := true, ctxApprox := true, quasiPatternApprox := true, constApprox := true }) x /-- Similar to `approxDefEq`, but uses all available approximations. We don't use `constApprox` by default at `approxDefEq` because it often produces undesirable solution for monadic code. For example, suppose we have `pure (x > 0)` which has type `?m Prop`. We also have the goal `[Pure ?m]`. Now, assume the expected type is `IO Bool`. Then, the unification constraint `?m Prop =?= IO Bool` could be solved as `?m := fun _ => IO Bool` using `constApprox`, but this spurious solution would generate a failure when we try to solve `[Pure (fun _ => IO Bool)]` -/ @[inline] def fullApproxDefEq : n α → n α := mapMetaM fullApproxDefEqImp /-- Instantiate assigned universe metavariables in `u`, and then normalize it. -/ def normalizeLevel (u : Level) : MetaM Level := do let u ← instantiateLevelMVars u pure u.normalize /-- `whnf` with reducible transparency.-/ def whnfR (e : Expr) : MetaM Expr := withTransparency TransparencyMode.reducible <| whnf e /-- `whnf` with default transparency.-/ def whnfD (e : Expr) : MetaM Expr := withTransparency TransparencyMode.default <| whnf e /-- `whnf` with instances transparency.-/ def whnfI (e : Expr) : MetaM Expr := withTransparency TransparencyMode.instances <| whnf e /-- Mark declaration `declName` with the attribute `[inline]`. This method does not check whether the given declaration is a definition. Recall that this attribute can only be set in the same module where `declName` has been declared. -/ def setInlineAttribute (declName : Name) (kind := Compiler.InlineAttributeKind.inline): MetaM Unit := do let env ← getEnv match Compiler.setInlineAttribute env declName kind with | .ok env => setEnv env | .error msg => throwError msg private partial def instantiateForallAux (ps : Array Expr) (i : Nat) (e : Expr) : MetaM Expr := do if h : i < ps.size then let p := ps.get ⟨i, h⟩ match (← whnf e) with | .forallE _ _ b _ => instantiateForallAux ps (i+1) (b.instantiate1 p) | _ => throwError "invalid instantiateForall, too many parameters" else return e /-- Given `e` of the form `forall (a_1 : A_1) ... (a_n : A_n), B[a_1, ..., a_n]` and `p_1 : A_1, ... p_n : A_n`, return `B[p_1, ..., p_n]`. -/ def instantiateForall (e : Expr) (ps : Array Expr) : MetaM Expr := instantiateForallAux ps 0 e private partial def instantiateLambdaAux (ps : Array Expr) (i : Nat) (e : Expr) : MetaM Expr := do if h : i < ps.size then let p := ps.get ⟨i, h⟩ match (← whnf e) with | .lam _ _ b _ => instantiateLambdaAux ps (i+1) (b.instantiate1 p) | _ => throwError "invalid instantiateLambda, too many parameters" else return e /-- Given `e` of the form `fun (a_1 : A_1) ... (a_n : A_n) => t[a_1, ..., a_n]` and `p_1 : A_1, ... p_n : A_n`, return `t[p_1, ..., p_n]`. It uses `whnf` to reduce `e` if it is not a lambda -/ def instantiateLambda (e : Expr) (ps : Array Expr) : MetaM Expr := instantiateLambdaAux ps 0 e /-- Pretty-print the given expression. -/ def ppExpr (e : Expr) : MetaM Format := do let ctxCore ← readThe Core.Context Lean.ppExpr { env := (← getEnv), mctx := (← getMCtx), lctx := (← getLCtx), opts := (← getOptions), currNamespace := ctxCore.currNamespace, openDecls := ctxCore.openDecls } e @[inline] protected def orElse (x : MetaM α) (y : Unit → MetaM α) : MetaM α := do let s ← saveState try x catch _ => s.restore; y () instance : OrElse (MetaM α) := ⟨Meta.orElse⟩ instance : Alternative MetaM where failure := fun {_} => throwError "failed" orElse := Meta.orElse @[inline] private def orelseMergeErrorsImp (x y : MetaM α) (mergeRef : Syntax → Syntax → Syntax := fun r₁ _ => r₁) (mergeMsg : MessageData → MessageData → MessageData := fun m₁ m₂ => m₁ ++ Format.line ++ m₂) : MetaM α := do let env ← getEnv let mctx ← getMCtx try x catch ex => setEnv env setMCtx mctx match ex with | Exception.error ref₁ m₁ => try y catch | Exception.error ref₂ m₂ => throw <| Exception.error (mergeRef ref₁ ref₂) (mergeMsg m₁ m₂) | ex => throw ex | ex => throw ex /-- Similar to `orelse`, but merge errors. Note that internal errors are not caught. The default `mergeRef` uses the `ref` (position information) for the first message. The default `mergeMsg` combines error messages using `Format.line ++ Format.line` as a separator. -/ @[inline] def orelseMergeErrors [MonadControlT MetaM m] [Monad m] (x y : m α) (mergeRef : Syntax → Syntax → Syntax := fun r₁ _ => r₁) (mergeMsg : MessageData → MessageData → MessageData := fun m₁ m₂ => m₁ ++ Format.line ++ Format.line ++ m₂) : m α := do controlAt MetaM fun runInBase => orelseMergeErrorsImp (runInBase x) (runInBase y) mergeRef mergeMsg /-- Execute `x`, and apply `f` to the produced error message -/ def mapErrorImp (x : MetaM α) (f : MessageData → MessageData) : MetaM α := do try x catch | Exception.error ref msg => throw <| Exception.error ref <| f msg | ex => throw ex @[inline] def mapError [MonadControlT MetaM m] [Monad m] (x : m α) (f : MessageData → MessageData) : m α := controlAt MetaM fun runInBase => mapErrorImp (runInBase x) f /-- Sort free variables using an order `x < y` iff `x` was defined before `y`. If a free variable is not in the local context, we use their id. -/ def sortFVarIds (fvarIds : Array FVarId) : MetaM (Array FVarId) := do let lctx ← getLCtx return 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₁.name fvarId₂.name end Methods /-- Return `true` if `declName` is an inductive predicate. That is, `inductive` type in `Prop`. -/ def isInductivePredicate (declName : Name) : MetaM Bool := do match (← getEnv).find? declName with | some (.inductInfo { type := type, ..}) => forallTelescopeReducing type fun _ type => do match (← whnfD type) with | .sort u .. => return u == levelZero | _ => return false | _ => return false def isListLevelDefEqAux : List Level → List Level → MetaM Bool | [], [] => return true | u::us, v::vs => isLevelDefEqAux u v <&&> isListLevelDefEqAux us vs | _, _ => return false def getNumPostponed : MetaM Nat := do return (← getPostponed).size def getResetPostponed : MetaM (PersistentArray PostponedEntry) := do let ps ← getPostponed setPostponed {} return ps /-- Annotate any constant and sort in `e` that satisfies `p` with `pp.universes true` -/ private def exposeRelevantUniverses (e : Expr) (p : Level → Bool) : Expr := e.replace fun | .const _ us => if us.any p then some (e.setPPUniverses true) else none | .sort u => if p u then some (e.setPPUniverses true) else none | _ => none private def mkLeveErrorMessageCore (header : String) (entry : PostponedEntry) : MetaM MessageData := do match entry.ctx? with | none => return m!"{header}{indentD m!"{entry.lhs} =?= {entry.rhs}"}" | some ctx => withLCtx ctx.lctx ctx.localInstances do let s := entry.lhs.collectMVars entry.rhs.collectMVars /- `p u` is true if it contains a universe metavariable in `s` -/ let p (u : Level) := u.any fun | .mvar m => s.contains m | _ => false let lhs := exposeRelevantUniverses (← instantiateMVars ctx.lhs) p let rhs := exposeRelevantUniverses (← instantiateMVars ctx.rhs) p try addMessageContext m!"{header}{indentD m!"{entry.lhs} =?= {entry.rhs}"}\nwhile trying to unify{indentD m!"{lhs} : {← inferType lhs}"}\nwith{indentD m!"{rhs} : {← inferType rhs}"}" catch _ => addMessageContext m!"{header}{indentD m!"{entry.lhs} =?= {entry.rhs}"}\nwhile trying to unify{indentD lhs}\nwith{indentD rhs}" def mkLevelStuckErrorMessage (entry : PostponedEntry) : MetaM MessageData := do mkLeveErrorMessageCore "stuck at solving universe constraint" entry def mkLevelErrorMessage (entry : PostponedEntry) : MetaM MessageData := do mkLeveErrorMessageCore "failed to solve universe constraint" entry private def processPostponedStep (exceptionOnFailure : Bool) : MetaM Bool := traceCtx `Meta.isLevelDefEq.postponed.step do let ps ← getResetPostponed for p in ps do unless (← withReader (fun ctx => { ctx with defEqCtx? := p.ctx? }) <| isLevelDefEqAux p.lhs p.rhs) do if exceptionOnFailure then withRef p.ref do throwError (← mkLevelErrorMessage p) else return false return true partial def processPostponed (mayPostpone : Bool := true) (exceptionOnFailure := false) : MetaM Bool := do if (← getNumPostponed) == 0 then return true else traceCtx `Meta.isLevelDefEq.postponed do let rec loop : MetaM Bool := do let numPostponed ← getNumPostponed if numPostponed == 0 then return true else trace[Meta.isLevelDefEq.postponed] "processing #{numPostponed} postponed is-def-eq level constraints" if !(← processPostponedStep exceptionOnFailure) then return false else let numPostponed' ← getNumPostponed if numPostponed' == 0 then return true else if numPostponed' < numPostponed then loop else trace[Meta.isLevelDefEq.postponed] "no progress solving pending is-def-eq level constraints" return mayPostpone loop /-- `checkpointDefEq x` executes `x` and process all postponed universe level constraints produced by `x`. We keep the modifications only if `processPostponed` return true and `x` returned `true`. If `mayPostpone == false`, all new postponed universe level constraints must be solved before returning. We currently try to postpone universe constraints as much as possible, even when by postponing them we are not sure whether `x` really succeeded or not. -/ @[specialize] def checkpointDefEq (x : MetaM Bool) (mayPostpone : Bool := true) : MetaM Bool := do let s ← saveState /- It is not safe to use the `isDefEq` cache between different `isDefEq` calls. Reason: different configuration settings, and result depends on the state of the `MetavarContext` We have tried in the past to track when the result was independent of the `MetavarContext` state but it was not effective. It is more important to cache aggressively inside of a single `isDefEq` call because some of the heuristics create many similar subproblems. See issue #1102 for an example that triggers an exponential blowup if we don't use this more aggresive form of caching. -/ modifyDefEqCache fun _ => {} let postponed ← getResetPostponed try if (← x) then if (← processPostponed mayPostpone) then let newPostponed ← getPostponed setPostponed (postponed ++ newPostponed) return true else s.restore return false else s.restore return false catch ex => s.restore throw ex /-- Determines whether two universe level expressions are definitionally equal to each other. -/ def isLevelDefEq (u v : Level) : MetaM Bool := traceCtx `Meta.isLevelDefEq do let b ← checkpointDefEq (mayPostpone := true) <| Meta.isLevelDefEqAux u v trace[Meta.isLevelDefEq] "{u} =?= {v} ... {if b then "success" else "failure"}" return b /-- See `isDefEq`. -/ def isExprDefEq (t s : Expr) : MetaM Bool := traceCtx `Meta.isDefEq <| withReader (fun ctx => { ctx with defEqCtx? := some { lhs := t, rhs := s, lctx := ctx.lctx, localInstances := ctx.localInstances } }) do let b ← checkpointDefEq (mayPostpone := true) <| Meta.isExprDefEqAux t s trace[Meta.isDefEq] "{t} =?= {s} ... {if b then "success" else "failure"}" return b /-- Determines whether two expressions are definitionally equal to each other. To control how metavariables are assigned and unified, metavariables and their context have a "depth". Given a metavariable `?m` and a `MetavarContext` `mctx`, `?m` is not assigned if `?m.depth != mctx.depth`. The combinator `withNewMCtxDepth x` will bump the depth while executing `x`. So, `withNewMCtxDepth (isDefEq a b)` is `isDefEq` without any mvar assignment happening whereas `isDefEq a b` will assign any metavariables of the current depth in `a` and `b` to unify them. For matching (where only mvars in `b` should be assigned), we create the term inside the `withNewMCtxDepth`. For an example, see [Lean.Meta.Simp.tryTheoremWithExtraArgs?](https://github.com/leanprover/lean4/blob/master/src/Lean/Meta/Tactic/Simp/Rewrite.lean#L100-L106) -/ abbrev isDefEq (t s : Expr) : MetaM Bool := isExprDefEq t s def isExprDefEqGuarded (a b : Expr) : MetaM Bool := do try isExprDefEq a b catch _ => return false /-- Similar to `isDefEq`, but returns `false` if an exception has been thrown. -/ abbrev isDefEqGuarded (t s : Expr) : MetaM Bool := isExprDefEqGuarded t s def isDefEqNoConstantApprox (t s : Expr) : MetaM Bool := approxDefEq <| isDefEq t s /-- Eta expand the given expression. Example: ``` etaExpand (mkConst ``Nat.add) ``` produces `fun x y => Nat.add x y` -/ def etaExpand (e : Expr) : MetaM Expr := withDefault do forallTelescopeReducing (← inferType e) fun xs _ => mkLambdaFVars xs (mkAppN e xs) end Meta builtin_initialize registerTraceClass `Meta.isLevelDefEq.postponed export Meta (MetaM) end Lean
b44178d79f13b3a4fc1b04a0225d01730b686c9f
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/finset/finsupp.lean
cc04edb25c1a6846ee3de96818989eb0fa671ca1
[ "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
3,141
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.finsupp.indicator /-! # Finitely supported product of finsets This file defines the finitely supported product of finsets as a `finset (ι →₀ α)`. ## Main declarations * `finset.finsupp`: Finitely supported product of finsets. `s.finset t` is the product of the `t i` over all `i ∈ s`. * `finsupp.pi`: `f.pi` is the finset of `finsupp`s whose `i`-th value lies in `f i`. This is the special case of `finset.finsupp` where we take the product of the `f i` over the support of `f`. ## Implementation notes We make heavy use of the fact that `0 : finset α` is `{0}`. This scalar actions convention turns out to be precisely what we want here too. -/ noncomputable theory open finsupp open_locale big_operators classical pointwise variables {ι α : Type*} [has_zero α] {s : finset ι} {f : ι →₀ α} namespace finset /-- Finitely supported product of finsets. -/ protected def finsupp (s : finset ι) (t : ι → finset α) : finset (ι →₀ α) := (s.pi t).map ⟨indicator s, indicator_injective s⟩ lemma mem_finsupp_iff {t : ι → finset α} : f ∈ s.finsupp t ↔ f.support ⊆ s ∧ ∀ i ∈ s, f i ∈ t i := begin refine mem_map.trans ⟨_, _⟩, { rintro ⟨f, hf, rfl⟩, refine ⟨support_indicator_subset _ _, λ i hi, _⟩, convert mem_pi.1 hf i hi, exact indicator_of_mem hi _ }, { refine λ h, ⟨λ i _, f i, mem_pi.2 h.2, _⟩, ext i, exact ite_eq_left_iff.2 (λ hi, (not_mem_support_iff.1 $ λ H, hi $ h.1 H).symm) } end /-- When `t` is supported on `s`, `f ∈ s.finsupp t` precisely means that `f` is pointwise in `t`. -/ @[simp] lemma mem_finsupp_iff_of_support_subset {t : ι →₀ finset α} (ht : t.support ⊆ s) : f ∈ s.finsupp t ↔ ∀ i, f i ∈ t i := begin refine mem_finsupp_iff.trans (forall_and_distrib.symm.trans $ forall_congr $ λ i, ⟨λ h, _, λ h, ⟨λ hi, ht $ mem_support_iff.2 $ λ H, mem_support_iff.1 hi _, λ _, h⟩⟩), { by_cases hi : i ∈ s, { exact h.2 hi }, { rw [not_mem_support_iff.1 (mt h.1 hi), not_mem_support_iff.1 (λ H, hi $ ht H)], exact zero_mem_zero } }, { rwa [H, mem_zero] at h } end @[simp] lemma card_finsupp (s : finset ι) (t : ι → finset α) : (s.finsupp t).card = ∏ i in s, (t i).card := (card_map _).trans $ card_pi _ _ end finset open finset namespace finsupp /-- Given a finitely supported function `f : ι →₀ finset α`, one can define the finset `f.pi` of all finitely supported functions whose value at `i` is in `f i` for all `i`. -/ def pi (f : ι →₀ finset α) : finset (ι →₀ α) := f.support.finsupp f @[simp] lemma mem_pi {f : ι →₀ finset α} {g : ι →₀ α} : g ∈ f.pi ↔ ∀ i, g i ∈ f i := mem_finsupp_iff_of_support_subset $ subset.refl _ @[simp] lemma card_pi (f : ι →₀ finset α) : f.pi.card = f.prod (λ i, (f i).card) := begin rw [pi, card_finsupp], exact finset.prod_congr rfl (λ i _, by simp only [pi.nat_apply, nat.cast_id]), end end finsupp
5d4f5885fceade40c0b17981d54e73f7831ae521
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/continued_fractions/terminated_stable.lean
51577cb248dd3114154f1eeea1297ffef5a2732e
[ "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
4,652
lean
/- Copyright (c) 2020 Kevin Kappelmann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Kappelmann -/ import algebra.continued_fractions.translations /-! # Stabilisation of gcf Computations Under Termination ## Summary We show that the continuants and convergents of a gcf stabilise once the gcf terminates. -/ namespace generalized_continued_fraction open generalized_continued_fraction as gcf variables {K : Type*} {g : gcf K} {n m : ℕ} /-- If a gcf terminated at position `n`, it also terminated at `m ≥ n`.-/ lemma terminated_stable (n_le_m : n ≤ m) (terminated_at_n : g.terminated_at n) : g.terminated_at m := g.s.terminated_stable n_le_m terminated_at_n variable [division_ring K] lemma continuants_aux_stable_step_of_terminated (terminated_at_n : g.terminated_at n) : g.continuants_aux (n + 2) = g.continuants_aux (n + 1) := by { rw [terminated_at_iff_s_none] at terminated_at_n, simp only [terminated_at_n, continuants_aux] } lemma continuants_aux_stable_of_terminated (succ_n_le_m : (n + 1) ≤ m) (terminated_at_n : g.terminated_at n) : g.continuants_aux m = g.continuants_aux (n + 1) := begin induction succ_n_le_m with m succ_n_le_m IH, { refl }, { have : g.continuants_aux (m + 1) = g.continuants_aux m, by { have : n ≤ m - 1, from nat.le_pred_of_lt succ_n_le_m, have : g.terminated_at (m - 1), from terminated_stable this terminated_at_n, have stable_step : g.continuants_aux (m - 1 + 2) = g.continuants_aux (m - 1 + 1), from continuants_aux_stable_step_of_terminated this, have one_le_m : 1 ≤ m, from nat.one_le_of_lt succ_n_le_m, have : m - 1 + 2 = m + 2 - 1, from (nat.sub_add_comm one_le_m).symm, have : m - 1 + 1 = m + 1 - 1, from (nat.sub_add_comm one_le_m).symm, simpa [*] using stable_step }, exact (eq.trans this IH) } end lemma convergents'_aux_stable_step_of_terminated {s : seq $ gcf.pair K} (terminated_at_n : s.terminated_at n) : convergents'_aux s (n + 1) = convergents'_aux s n := begin change s.nth n = none at terminated_at_n, induction n with n IH generalizing s, case nat.zero { simp only [convergents'_aux, terminated_at_n, seq.head] }, case nat.succ { cases s_head_eq : s.head with gp_head, case option.none { simp only [convergents'_aux, s_head_eq] }, case option.some { have : s.tail.terminated_at n, by simp only [seq.terminated_at, s.nth_tail, terminated_at_n], simp only [convergents'_aux, s_head_eq, (IH this)] } } end lemma convergents'_aux_stable_of_terminated {s : seq $ gcf.pair K} (n_le_m : n ≤ m) (terminated_at_n : s.terminated_at n) : convergents'_aux s m = convergents'_aux s n := begin induction n_le_m with m n_le_m IH generalizing s, { refl }, { cases s_head_eq : s.head with gp_head, case option.none { cases n; simp only [convergents'_aux, s_head_eq] }, case option.some { have : convergents'_aux s (n + 1) = convergents'_aux s n, from convergents'_aux_stable_step_of_terminated terminated_at_n, rw [←this], have : s.tail.terminated_at n, by simpa only [seq.terminated_at, seq.nth_tail] using (s.le_stable n.le_succ terminated_at_n), have : convergents'_aux s.tail m = convergents'_aux s.tail n, from IH this, simp only [convergents'_aux, s_head_eq, this] } } end lemma continuants_stable_of_terminated (n_le_m : n ≤ m) (terminated_at_n : g.terminated_at n) : g.continuants m = g.continuants n := by simp only [nth_cont_eq_succ_nth_cont_aux, (continuants_aux_stable_of_terminated (nat.pred_le_iff.elim_left n_le_m) terminated_at_n)] lemma numerators_stable_of_terminated (n_le_m : n ≤ m) (terminated_at_n : g.terminated_at n) : g.numerators m = g.numerators n := by simp only [num_eq_conts_a, (continuants_stable_of_terminated n_le_m terminated_at_n)] lemma denominators_stable_of_terminated (n_le_m : n ≤ m) (terminated_at_n : g.terminated_at n) : g.denominators m = g.denominators n := by simp only [denom_eq_conts_b, (continuants_stable_of_terminated n_le_m terminated_at_n)] lemma convergents_stable_of_terminated (n_le_m : n ≤ m) (terminated_at_n : g.terminated_at n) : g.convergents m = g.convergents n := by simp only [convergents, (denominators_stable_of_terminated n_le_m terminated_at_n), (numerators_stable_of_terminated n_le_m terminated_at_n)] lemma convergents'_stable_of_terminated (n_le_m : n ≤ m) (terminated_at_n : g.terminated_at n) : g.convergents' m = g.convergents' n := by simp only [convergents', (convergents'_aux_stable_of_terminated n_le_m terminated_at_n)] end generalized_continued_fraction
8e7a48505b08c89ce888806173a547bba57ff59c
0ce335c3cee4b6a212935fdfd1a5270985454648
/src/tactic/core.lean
aea4a06491d7de9df1f1e7910e9ad562d4bc9d2d
[ "Apache-2.0" ]
permissive
yashen32768/mathlib
191f6113ccd0ef74091c3f5951ae84c0aa85516f
f54463254784b400da2e33dfa58f94775e3de845
refs/heads/master
1,598,060,530,541
1,571,523,082,000
1,571,523,082,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
45,917
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek -/ import data.dlist.basic category.basic meta.expr meta.rb_map data.bool namespace expr open tactic attribute [derive has_reflect] binder_info protected meta def of_nat (α : expr) : ℕ → tactic expr := nat.binary_rec (tactic.mk_mapp ``has_zero.zero [some α, none]) (λ b n tac, if n = 0 then mk_mapp ``has_one.one [some α, none] else do e ← tac, tactic.mk_app (cond b ``bit1 ``bit0) [e]) protected meta def of_int (α : expr) : ℤ → tactic expr | (n : ℕ) := expr.of_nat α n | -[1+ n] := do e ← expr.of_nat α (n+1), tactic.mk_app ``has_neg.neg [e] /- only traverses the direct descendents -/ meta def {u} traverse {m : Type → Type u} [applicative m] {elab elab' : bool} (f : expr elab → m (expr elab')) : expr elab → m (expr elab') | (var v) := pure $ var v | (sort l) := pure $ sort l | (const n ls) := pure $ const n ls | (mvar n n' e) := mvar n n' <$> f e | (local_const n n' bi e) := local_const n n' bi <$> f e | (app e₀ e₁) := app <$> f e₀ <*> f e₁ | (lam n bi e₀ e₁) := lam n bi <$> f e₀ <*> f e₁ | (pi n bi e₀ e₁) := pi n bi <$> f e₀ <*> f e₁ | (elet n e₀ e₁ e₂) := elet n <$> f e₀ <*> f e₁ <*> f e₂ | (macro mac es) := macro mac <$> list.traverse f es meta def mfoldl {α : Type} {m} [monad m] (f : α → expr → m α) : α → expr → m α | x e := prod.snd <$> (state_t.run (e.traverse $ λ e', (get >>= monad_lift ∘ flip f e' >>= put) $> e') x : m _) end expr namespace interaction_monad open result meta def get_result {σ α} (tac : interaction_monad σ α) : interaction_monad σ (interaction_monad.result σ α) | s := match tac s with | r@(success _ s') := success r s' | r@(exception _ _ s') := success r s' end end interaction_monad namespace lean.parser open lean interaction_monad.result meta def of_tactic' {α} (tac : tactic α) : parser α := do r ← of_tactic (interaction_monad.get_result tac), match r with | (success a _) := return a | (exception f pos _) := exception f pos end -- Override the builtin `lean.parser.of_tactic` coe, which is broken. -- (See test/tactics.lean for a failure case.) @[priority 2000] meta instance has_coe' {α} : has_coe (tactic α) (parser α) := ⟨of_tactic'⟩ meta def emit_command_here (str : string) : lean.parser string := do (_, left) ← with_input command_like str, return left -- Emit a source code string at the location being parsed. meta def emit_code_here : string → lean.parser unit | str := do left ← emit_command_here str, if left.length = 0 then return () else emit_code_here left end lean.parser namespace format meta def intercalate (x : format) : list format → format := format.join ∘ list.intersperse x end format namespace tactic meta def eval_expr' (α : Type*) [_inst_1 : reflected α] (e : expr) : tactic α := mk_app ``id [e] >>= eval_expr α -- `mk_fresh_name` returns identifiers starting with underscores, -- which are not legal when emitted by tactic programs. Turn the -- useful source of random names provided by `mk_fresh_name` into -- names which are usable by tactic programs. -- -- The returned name has four components which are all strings. meta def mk_user_fresh_name : tactic name := do nm ← mk_fresh_name, return $ `user__ ++ nm.pop_prefix.sanitize_name ++ `user__ /-- `has_attribute n n'` checks whether n' has attribute n. -/ meta def has_attribute' : name → name → tactic bool | n n' := succeeds (has_attribute n n') /-- Checks whether the name is a simp lemma -/ meta def is_simp_lemma : name → tactic bool := has_attribute' `simp /-- Checks whether the name is an instance. -/ meta def is_instance : name → tactic bool := has_attribute' `instance meta def local_decls : tactic (name_map declaration) := do e ← tactic.get_env, let xs := e.fold native.mk_rb_map (λ d s, if environment.in_current_file' e d.to_name then s.insert d.to_name d else s), pure xs /-- If `{nm}_{n}` doesn't exist in the environment, returns that, otherwise tries `{nm}_{n+1}` -/ meta def get_unused_decl_name_aux (e : environment) (nm : name) : ℕ → tactic name | n := let nm' := nm.append_suffix ("_" ++ to_string n) in if e.contains nm' then get_unused_decl_name_aux (n+1) else return nm' /-- Return a name which doesn't already exist in the environment. If `nm` doesn't exist, it returns that, otherwise it tries nm_2, nm_3, ... -/ meta def get_unused_decl_name (nm : name) : tactic name := get_env >>= λ e, if e.contains nm then get_unused_decl_name_aux e nm 2 else return nm /-- Returns a pair (e, t), where `e ← mk_const d.to_name`, and `t = d.type` but with universe params updated to match the fresh universe metavariables in `e`. This should have the same effect as just ``` do e ← mk_const d.to_name, t ← infer_type e, return (e, t) ``` but is hopefully faster. -/ meta def decl_mk_const (d : declaration) : tactic (expr × expr) := do subst ← d.univ_params.mmap $ λ u, prod.mk u <$> mk_meta_univ, let e : expr := expr.const d.to_name (prod.snd <$> subst), return (e, d.type.instantiate_univ_params subst) meta def simp_lemmas_from_file : tactic name_set := do s ← local_decls, let s := s.map (expr.list_constant ∘ declaration.value), xs ← s.to_list.mmap ((<$>) name_set.of_list ∘ mfilter tactic.is_simp_lemma ∘ name_set.to_list ∘ prod.snd), return $ name_set.filter (λ x, ¬ s.contains x) (xs.foldl name_set.union mk_name_set) meta def file_simp_attribute_decl (attr : name) : tactic unit := do s ← simp_lemmas_from_file, trace format!"run_cmd mk_simp_attr `{attr}", let lmms := format.join $ list.intersperse " " $ s.to_list.map to_fmt, trace format!"local attribute [{attr}] {lmms}" meta def mk_local (n : name) : expr := expr.local_const n n binder_info.default (expr.const n []) meta def local_def_value (e : expr) : tactic expr := do do (v,_) ← solve_aux `(true) (do (expr.elet n t v _) ← (revert e >> target) | fail format!"{e} is not a local definition", return v), return v meta def check_defn (n : name) (e : pexpr) : tactic unit := do (declaration.defn _ _ _ d _ _) ← get_decl n, e' ← to_expr e, guard (d =ₐ e') <|> trace d >> failed -- meta def compile_eqn (n : name) (univ : list name) (args : list expr) (val : expr) (num : ℕ) : tactic unit := -- do let lhs := (expr.const n $ univ.map level.param).mk_app args, -- stmt ← mk_app `eq [lhs,val], -- let vs := stmt.list_local_const, -- let stmt := stmt.pis vs, -- (_,pr) ← solve_aux stmt (tactic.intros >> reflexivity), -- add_decl $ declaration.thm (n <.> "equations" <.> to_string (format!"_eqn_{num}")) univ stmt (pure pr) meta def to_implicit : expr → expr | (expr.local_const uniq n bi t) := expr.local_const uniq n binder_info.implicit t | e := e meta def pis : list expr → expr → tactic expr | (e@(expr.local_const uniq pp info _) :: es) f := do t ← infer_type e, f' ← pis es f, pure $ expr.pi pp info t (expr.abstract_local f' uniq) | _ f := pure f meta def lambdas : list expr → expr → tactic expr | (e@(expr.local_const uniq pp info _) :: es) f := do t ← infer_type e, f' ← lambdas es f, pure $ expr.lam pp info t (expr.abstract_local f' uniq) | _ f := pure f meta def extract_def (n : name) (trusted : bool) (elab_def : tactic unit) : tactic unit := do cxt ← list.map to_implicit <$> local_context, t ← target, (eqns,d) ← solve_aux t elab_def, d ← instantiate_mvars d, t' ← pis cxt t, d' ← lambdas cxt d, let univ := t'.collect_univ_params, add_decl $ declaration.defn n univ t' d' (reducibility_hints.regular 1 tt) trusted, applyc n meta def exact_dec_trivial : tactic unit := `[exact dec_trivial] /-- Runs a tactic for a result, reverting the state after completion -/ meta def retrieve {α} (tac : tactic α) : tactic α := λ s, result.cases_on (tac s) (λ a s', result.success a s) result.exception /-- Repeat a tactic at least once, calling it recursively on all subgoals, until it fails. This tactic fails if the first invocation fails. -/ meta def repeat1 (t : tactic unit) : tactic unit := t; repeat t /-- `iterate_range m n t`: Repeat the given tactic at least `m` times and at most `n` times or until `t` fails. Fails if `t` does not run at least m times. -/ meta def iterate_range : ℕ → ℕ → tactic unit → tactic unit | 0 0 t := skip | 0 (n+1) t := try (t >> iterate_range 0 n t) | (m+1) n t := t >> iterate_range m (n-1) t meta def replace_at (tac : expr → tactic (expr × expr)) (hs : list expr) (tgt : bool) : tactic bool := do to_remove ← hs.mfilter $ λ h, do { h_type ← infer_type h, succeeds $ do (new_h_type, pr) ← tac h_type, assert h.local_pp_name new_h_type, mk_eq_mp pr h >>= tactic.exact }, goal_simplified ← succeeds $ do { guard tgt, (new_t, pr) ← target >>= tac, replace_target new_t pr }, to_remove.mmap' (λ h, try (clear h)), return (¬ to_remove.empty ∨ goal_simplified) meta def simp_bottom_up' (post : expr → tactic (expr × expr)) (e : expr) (cfg : simp_config := {}) : tactic (expr × expr) := prod.snd <$> simplify_bottom_up () (λ _, (<$>) (prod.mk ()) ∘ post) e cfg meta structure instance_cache := (α : expr) (univ : level) (inst : name_map expr) meta def mk_instance_cache (α : expr) : tactic instance_cache := do u ← mk_meta_univ, infer_type α >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, return ⟨α, u, mk_name_map⟩ namespace instance_cache meta def get (c : instance_cache) (n : name) : tactic (instance_cache × expr) := match c.inst.find n with | some i := return (c, i) | none := do e ← mk_app n [c.α] >>= mk_instance, return (⟨c.α, c.univ, c.inst.insert n e⟩, e) end open expr meta def append_typeclasses : expr → instance_cache → list expr → tactic (instance_cache × list expr) | (pi _ binder_info.inst_implicit (app (const n _) (var _)) body) c l := do (c, p) ← c.get n, return (c, p :: l) | _ c l := return (c, l) meta def mk_app (c : instance_cache) (n : name) (l : list expr) : tactic (instance_cache × expr) := do d ← get_decl n, (c, l) ← append_typeclasses d.type.binding_body c l, return (c, (expr.const n [c.univ]).mk_app (c.α :: l)) end instance_cache meta def match_head (e : expr) : expr → tactic unit | e' := unify e e' <|> do `(_ → %%e') ← whnf e', v ← mk_mvar, match_head (e'.instantiate_var v) meta def find_matching_head : expr → list expr → tactic (list expr) | e [] := return [] | e (H :: Hs) := do t ← infer_type H, ((::) H <$ match_head e t <|> pure id) <*> find_matching_head e Hs meta def subst_locals (s : list (expr × expr)) (e : expr) : expr := (e.abstract_locals (s.map (expr.local_uniq_name ∘ prod.fst)).reverse).instantiate_vars (s.map prod.snd) meta def set_binder : expr → list binder_info → expr | e [] := e | (expr.pi v _ d b) (bi :: bs) := expr.pi v bi d (set_binder b bs) | e _ := e meta def last_explicit_arg : expr → tactic expr | (expr.app f e) := do t ← infer_type f >>= whnf, if t.binding_info = binder_info.default then pure e else last_explicit_arg f | e := pure e private meta def get_expl_pi_arity_aux : expr → tactic nat | (expr.pi n bi d b) := do m ← mk_fresh_name, let l := expr.local_const m n bi d, new_b ← whnf (expr.instantiate_var b l), r ← get_expl_pi_arity_aux new_b, if bi = binder_info.default then return (r + 1) else return r | e := return 0 /-- Compute the arity of explicit arguments of the given (Pi-)type -/ meta def get_expl_pi_arity (type : expr) : tactic nat := whnf type >>= get_expl_pi_arity_aux /-- Compute the arity of explicit arguments of the given function -/ meta def get_expl_arity (fn : expr) : tactic nat := infer_type fn >>= get_expl_pi_arity /-- Auxilliary defintion for `get_pi_binders`. -/ meta def get_pi_binders_aux : list binder → expr → tactic (list binder × expr) | es (expr.pi n bi d b) := do m ← mk_fresh_name, let l := expr.local_const m n bi d, let new_b := expr.instantiate_var b l, get_pi_binders_aux (⟨n, bi, d⟩::es) new_b | es e := return (es, e) /-- Get the binders and target of a pi-type. Instantiates bound variables by local constants. -/ meta def get_pi_binders : expr → tactic (list binder × expr) | e := do (es, e) ← get_pi_binders_aux [] e, return (es.reverse, e) /-- variation on `assert` where a (possibly incomplete) proof of the assertion is provided as a parameter. ``(h,gs) ← local_proof `h p tac`` creates a local `h : p` and use `tac` to (partially) construct a proof for it. `gs` is the list of remaining goals in the proof of `h`. The benefits over assert are: - unlike with ``h ← assert `h p, tac`` , `h` cannot be used by `tac`; - when `tac` does not complete the proof of `h`, returning the list of goals allows one to write a tactic using `h` and with the confidence that a proof will not boil over to goals left over from the proof of `h`, unlike what would be the case when using `tactic.swap`. -/ meta def local_proof (h : name) (p : expr) (tac₀ : tactic unit) : tactic (expr × list expr) := focus1 $ do h' ← assert h p, [g₀,g₁] ← get_goals, set_goals [g₀], tac₀, gs ← get_goals, set_goals [g₁], return (h', gs) meta def var_names : expr → list name | (expr.pi n _ _ b) := n :: var_names b | _ := [] meta def drop_binders : expr → tactic expr | (expr.pi n bi t b) := b.instantiate_var <$> mk_local' n bi t >>= drop_binders | e := pure e meta def subobject_names (struct_n : name) : tactic (list name × list name) := do env ← get_env, [c] ← pure $ env.constructors_of struct_n | fail "too many constructors", vs ← var_names <$> (mk_const c >>= infer_type), fields ← env.structure_fields struct_n, return $ fields.partition (λ fn, ↑("_" ++ fn.to_string) ∈ vs) meta def expanded_field_list' : name → tactic (dlist $ name × name) | struct_n := do (so,fs) ← subobject_names struct_n, ts ← so.mmap (λ n, do e ← mk_const (n.update_prefix struct_n) >>= infer_type >>= drop_binders, expanded_field_list' $ e.get_app_fn.const_name), return $ dlist.join ts ++ dlist.of_list (fs.map $ prod.mk struct_n) open functor function meta def expanded_field_list (struct_n : name) : tactic (list $ name × name) := dlist.to_list <$> expanded_field_list' struct_n meta def get_classes (e : expr) : tactic (list name) := attribute.get_instances `class >>= list.mfilter (λ n, succeeds $ mk_app n [e] >>= mk_instance) open nat meta def mk_mvar_list : ℕ → tactic (list expr) | 0 := pure [] | (succ n) := (::) <$> mk_mvar <*> mk_mvar_list n /-- Returns the only goal, or fails if there isn't just one goal. -/ meta def get_goal : tactic expr := do gs ← get_goals, match gs with | [a] := return a | [] := fail "there are no goals" | _ := fail "there are too many goals" end /--`iterate_at_most_on_all_goals n t`: repeat the given tactic at most `n` times on all goals, or until it fails. Always succeeds. -/ meta def iterate_at_most_on_all_goals : nat → tactic unit → tactic unit | 0 tac := trace "maximal iterations reached" | (succ n) tac := tactic.all_goals $ (do tac, iterate_at_most_on_all_goals n tac) <|> skip /--`iterate_at_most_on_subgoals n t`: repeat the tactic `t` at most `n` times on the first goal and on all subgoals thus produced, or until it fails. Fails iff `t` fails on current goal. -/ meta def iterate_at_most_on_subgoals : nat → tactic unit → tactic unit | 0 tac := trace "maximal iterations reached" | (succ n) tac := focus1 (do tac, iterate_at_most_on_all_goals n tac) /--`apply_list l`: try to apply the tactics in the list `l` on the first goal, and fail if none succeeds -/ meta def apply_list_expr : list expr → tactic unit | [] := fail "no matching rule" | (h::t) := do interactive.concat_tags (apply h) <|> apply_list_expr t /-- constructs a list of expressions given a list of p-expressions, as follows: - if the p-expression is the name of a theorem, use `i_to_expr_for_apply` on it - if the p-expression is a user attribute, add all the theorems with this attribute to the list.-/ meta def build_list_expr_for_apply : list pexpr → tactic (list expr) | [] := return [] | (h::t) := do tail ← build_list_expr_for_apply t, a ← i_to_expr_for_apply h, (do l ← attribute.get_instances (expr.const_name a), m ← list.mmap mk_const l, return (m.append tail)) <|> return (a::tail) /--`apply_rules hs n`: apply the list of rules `hs` (given as pexpr) and `assumption` on the first goal and the resulting subgoals, iteratively, at most `n` times -/ meta def apply_rules (hs : list pexpr) (n : nat) : tactic unit := do l ← build_list_expr_for_apply hs, iterate_at_most_on_subgoals n (assumption <|> apply_list_expr l) meta def replace (h : name) (p : pexpr) : tactic unit := do h' ← get_local h, p ← to_expr p, note h none p, clear h' /-- Auxiliary function for `iff_mp` and `iff_mpr`. Takes a name, which should be either `` `iff.mp`` or `` `iff.mpr``. If the passed expression is an iterated function type eventually producing an `iff`, returns an expression with the `iff` converted to either the forwards or backwards implication, as requested. -/ meta def mk_iff_mp_app (iffmp : name) : expr → (nat → expr) → option expr | (expr.pi n bi e t) f := expr.lam n bi e <$> mk_iff_mp_app t (λ n, f (n+1) (expr.var n)) | `(%%a ↔ %%b) f := some $ @expr.const tt iffmp [] a b (f 0) | _ f := none meta def iff_mp_core (e ty: expr) : option expr := mk_iff_mp_app `iff.mp ty (λ_, e) meta def iff_mpr_core (e ty: expr) : option expr := mk_iff_mp_app `iff.mpr ty (λ_, e) /-- Given an expression whose type is (a possibly iterated function producing) an `iff`, create the expression which is the forward implication. -/ meta def iff_mp (e : expr) : tactic expr := do t ← infer_type e, iff_mp_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`" /-- Given an expression whose type is (a possibly iterated function producing) an `iff`, create the expression which is the reverse implication. -/ meta def iff_mpr (e : expr) : tactic expr := do t ← infer_type e, iff_mpr_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`" /-- Attempts to apply `e`, and if that fails, if `e` is an `iff`, try applying both directions separately. -/ meta def apply_iff (e : expr) : tactic (list (name × expr)) := let ap e := tactic.apply e {new_goals := new_goals.non_dep_only} in ap e <|> (iff_mp e >>= ap) <|> (iff_mpr e >>= ap) meta def symm_apply (e : expr) (cfg : apply_cfg := {}) : tactic (list (name × expr)) := tactic.apply e cfg <|> (symmetry >> tactic.apply e cfg) meta def apply_assumption (asms : tactic (list expr) := local_context) (tac : tactic unit := skip) : tactic unit := do { ctx ← asms, ctx.any_of (λ H, symm_apply H >> tac) } <|> do { exfalso, ctx ← asms, ctx.any_of (λ H, symm_apply H >> tac) } <|> fail "assumption tactic failed" meta def change_core (e : expr) : option expr → tactic unit | none := tactic.change e | (some h) := do num_reverted : ℕ ← revert h, expr.pi n bi d b ← target, tactic.change $ expr.pi n bi e b, intron num_reverted /-- assuming olde and newe are defeq when elaborated, replaces occurences of olde with newe at hypothesis h. -/ meta def change_with_at (olde newe : pexpr) (hyp : name) : tactic unit := do h ← get_local hyp, tp ← infer_type h, olde ← to_expr olde, newe ← to_expr newe, let repl_tp := tp.replace (λ a n, if a = olde then some newe else none), change_core repl_tp (some h) meta def metavariables : tactic (list expr) := do r ← result, pure (r.list_meta_vars) /-- Succeeds only if the current goal is a proposition. -/ meta def propositional_goal : tactic unit := do goals ← get_goals, p ← is_proof goals.head, guard p /-- Succeeds only if we can construct an instance showing the current goal is a subsingleton type. -/ meta def subsingleton_goal : tactic unit := do goals ← get_goals, ty ← infer_type goals.head >>= instantiate_mvars, to_expr ``(subsingleton %%ty) >>= mk_instance >> skip /-- Succeeds only if the current goal is "terminal", in the sense that no other goals depend on it. -/ meta def terminal_goal : tactic unit := -- We can't merely test for subsingletons, as sometimes in the presence of metavariables -- `propositional_goal` succeeds while `subsingleton_goal` does not. propositional_goal <|> subsingleton_goal <|> do g₀ :: _ ← get_goals, mvars ← (λ L, list.erase L g₀) <$> metavariables, mvars.mmap' $ λ g, do t ← infer_type g >>= instantiate_mvars, d ← kdepends_on t g₀, monad.whenb d $ pp t >>= λ s, fail ("The current goal is not terminal: " ++ s.to_string ++ " depends on it.") meta def triv' : tactic unit := do c ← mk_const `trivial, exact c reducible variable {α : Type} private meta def iterate_aux (t : tactic α) : list α → tactic (list α) | L := (do r ← t, iterate_aux (r :: L)) <|> return L /-- Apply a tactic as many times as possible, collecting the results in a list. -/ meta def iterate' (t : tactic α) : tactic (list α) := list.reverse <$> iterate_aux t [] /-- Like iterate', but fail if the tactic does not succeed at least once. -/ meta def iterate1 (t : tactic α) : tactic (α × list α) := do r ← decorate_ex "iterate1 failed: tactic did not succeed" t, L ← iterate' t, return (r, L) meta def intros1 : tactic (list expr) := iterate1 intro1 >>= λ p, return (p.1 :: p.2) /-- `successes` invokes each tactic in turn, returning the list of successful results. -/ meta def successes (tactics : list (tactic α)) : tactic (list α) := list.filter_map id <$> monad.sequence (tactics.map (λ t, try_core t)) /-- Return target after instantiating metavars and whnf -/ private meta def target' : tactic expr := target >>= instantiate_mvars >>= whnf /-- Just like `split`, `fsplit` applies the constructor when the type of the target is an inductive data type with one constructor. However it does not reorder goals or invoke `auto_param` tactics. -/ -- FIXME check if we can remove `auto_param := ff` meta def fsplit : tactic unit := do [c] ← target' >>= get_constructors_for | tactic.fail "fsplit tactic failed, target is not an inductive datatype with only one constructor", mk_const c >>= λ e, apply e {new_goals := new_goals.all, auto_param := ff} >> skip run_cmd add_interactive [`fsplit] /-- Calls `injection` on each hypothesis, and then, for each hypothesis on which `injection` succeeds, clears the old hypothesis. -/ meta def injections_and_clear : tactic unit := do l ← local_context, results ← successes $ l.map $ λ e, injection e >> clear e, when (results.empty) (fail "could not use `injection` then `clear` on any hypothesis") run_cmd add_interactive [`injections_and_clear] /-- calls `cases` on every local hypothesis, succeeding if it succeeds on at least one hypothesis. -/ meta def case_bash : tactic unit := do l ← local_context, r ← successes (l.reverse.map (λ h, cases h >> skip)), when (r.empty) failed /-- given a proof `pr : t`, adds `h : t` to the current context, where the name `h` is fresh. -/ meta def note_anon (e : expr) : tactic expr := do n ← get_unused_name "lh", note n none e /-- `find_local t` returns a local constant with type t, or fails if none exists. -/ meta def find_local (t : pexpr) : tactic expr := do t' ← to_expr t, prod.snd <$> solve_aux t' assumption /-- `dependent_pose_core l`: introduce dependent hypothesis, where the proofs depend on the values of the previous local constants. `l` is a list of local constants and their values. -/ meta def dependent_pose_core (l : list (expr × expr)) : tactic unit := do let lc := l.map prod.fst, let lm := l.map (λ⟨l, v⟩, (l.local_uniq_name, v)), t ← target, new_goal ← mk_meta_var (t.pis lc), old::other_goals ← get_goals, set_goals (old :: new_goal :: other_goals), exact ((new_goal.mk_app lc).instantiate_locals lm), return () /-- like `mk_local_pis` but translating into weak head normal form before checking if it is a Π. -/ meta def mk_local_pis_whnf : expr → tactic (list expr × expr) | e := do (expr.pi n bi d b) ← whnf e | return ([], e), p ← mk_local' n bi d, (ps, r) ← mk_local_pis (expr.instantiate_var b p), return ((p :: ps), r) /-- Changes `(h : ∀xs, ∃a:α, p a) ⊢ g` to `(d : ∀xs, a) (s : ∀xs, p (d xs) ⊢ g` -/ meta def choose1 (h : expr) (data : name) (spec : name) : tactic expr := do t ← infer_type h, (ctxt, t) ← mk_local_pis_whnf t, `(@Exists %%α %%p) ← whnf t transparency.all | fail "expected a term of the shape ∀xs, ∃a, p xs a", α_t ← infer_type α, expr.sort u ← whnf α_t transparency.all, value ← mk_local_def data (α.pis ctxt), t' ← head_beta (p.app (value.mk_app ctxt)), spec ← mk_local_def spec (t'.pis ctxt), dependent_pose_core [ (value, ((((expr.const `classical.some [u]).app α).app p).app (h.mk_app ctxt)).lambdas ctxt), (spec, ((((expr.const `classical.some_spec [u]).app α).app p).app (h.mk_app ctxt)).lambdas ctxt)], try (tactic.clear h), intro1, intro1 /-- Changes `(h : ∀xs, ∃as, p as) ⊢ g` to a list of functions `as`, an a final hypothesis on `p as` -/ meta def choose : expr → list name → tactic unit | h [] := fail "expect list of variables" | h [n] := do cnt ← revert h, intro n, intron (cnt - 1), return () | h (n::ns) := do v ← get_unused_name >>= choose1 h n, choose v ns /-- Instantiates metavariables that appear in the current goal. -/ meta def instantiate_mvars_in_target : tactic unit := target >>= instantiate_mvars >>= change /-- Instantiates metavariables in all goals. -/ meta def instantiate_mvars_in_goals : tactic unit := all_goals $ instantiate_mvars_in_target /-- This makes sure that the execution of the tactic does not change the tactic state. This can be helpful while using rewrite, apply, or expr munging. Remember to instantiate your metavariables before you're done! -/ meta def lock_tactic_state {α} (t : tactic α) : tactic α | s := match t s with | result.success a s' := result.success a s | result.exception msg pos s' := result.exception msg pos s end /-- similar to `mk_local_pis` but make meta variables instead of local constants -/ meta def mk_meta_pis : expr → tactic (list expr × expr) | (expr.pi n bi d b) := do p ← mk_meta_var d, (ps, r) ← mk_meta_pis (expr.instantiate_var b p), return ((p :: ps), r) | e := return ([], e) /-- Hole command used to fill in a structure's field when specifying an instance. In the following: ``` instance : monad id := {! !} ``` invoking hole command `Instance Stub` produces: ``` instance : monad id := { map := _, map_const := _, pure := _, seq := _, seq_left := _, seq_right := _, bind := _ } ``` -/ @[hole_command] meta def instance_stub : hole_command := { name := "Instance Stub", descr := "Generate a skeleton for the structure under construction.", action := λ _, do tgt ← target >>= whnf, let cl := tgt.get_app_fn.const_name, env ← get_env, fs ← expanded_field_list cl, let fs := fs.map prod.snd, let fs := format.intercalate (",\n " : format) $ fs.map (λ fn, format!"{fn} := _"), let out := format.to_string format!"{{ {fs} }", return [(out,"")] } /-- Like `resolve_name` except when the list of goals is empty. In that situation `resolve_name` fails whereas `resolve_name'` simply proceeds on a dummy goal -/ meta def resolve_name' (n : name) : tactic pexpr := do [] ← get_goals | resolve_name n, g ← mk_mvar, set_goals [g], resolve_name n <* set_goals [] meta def strip_prefix' (n : name) : list string → name → tactic name | s name.anonymous := pure $ s.foldl (flip name.mk_string) name.anonymous | s (name.mk_string a p) := do let n' := s.foldl (flip name.mk_string) name.anonymous, do { n'' ← tactic.resolve_constant n', if n'' = n then pure n' else strip_prefix' (a :: s) p } <|> strip_prefix' (a :: s) p | s n@(name.mk_numeral a p) := pure $ s.foldl (flip name.mk_string) n meta def strip_prefix : name → tactic name | n@(name.mk_string a a_1) := if (`_private).is_prefix_of n then let n' := n.update_prefix name.anonymous in n' <$ resolve_name' n' <|> pure n else strip_prefix' n [a] a_1 | n := pure n meta def local_binding_info : expr → binder_info | (expr.local_const _ _ bi _) := bi | _ := binder_info.default meta def is_default_local : expr → bool | (expr.local_const _ _ binder_info.default _) := tt | _ := ff meta def mk_patterns (t : expr) : tactic (list format) := do let cl := t.get_app_fn.const_name, env ← get_env, let fs := env.constructors_of cl, fs.mmap $ λ f, do { (vs,_) ← mk_const f >>= infer_type >>= mk_local_pis, let vs := vs.filter (λ v, is_default_local v), vs ← vs.mmap (λ v, do v' ← get_unused_name v.local_pp_name, pose v' none `(()), pure v' ), vs.mmap' $ λ v, get_local v >>= clear, let args := list.intersperse (" " : format) $ vs.map to_fmt, f ← strip_prefix f, if args.empty then pure $ format!"| {f} := _\n" else pure format!"| ({f} {format.join args}) := _\n" } /-- Hole command used to generate a `match` expression. In the following: ``` meta def foo (e : expr) : tactic unit := {! e !} ``` invoking hole command `Match Stub` produces: ``` meta def foo (e : expr) : tactic unit := match e with | (expr.var a) := _ | (expr.sort a) := _ | (expr.const a a_1) := _ | (expr.mvar a a_1 a_2) := _ | (expr.local_const a a_1 a_2 a_3) := _ | (expr.app a a_1) := _ | (expr.lam a a_1 a_2 a_3) := _ | (expr.pi a a_1 a_2 a_3) := _ | (expr.elet a a_1 a_2 a_3) := _ | (expr.macro a a_1) := _ end ``` -/ @[hole_command] meta def match_stub : hole_command := { name := "Match Stub", descr := "Generate a list of equations for a `match` expression.", action := λ es, do [e] ← pure es | fail "expecting one expression", e ← to_expr e, t ← infer_type e >>= whnf, fs ← mk_patterns t, e ← pp e, let out := format.to_string format!"match {e} with\n{format.join fs}end\n", return [(out,"")] } /-- Hole command used to generate a `match` expression. In the following: ``` meta def foo : {! expr → tactic unit !} -- `:=` is omitted ``` invoking hole command `Equations Stub` produces: ``` meta def foo : expr → tactic unit | (expr.var a) := _ | (expr.sort a) := _ | (expr.const a a_1) := _ | (expr.mvar a a_1 a_2) := _ | (expr.local_const a a_1 a_2 a_3) := _ | (expr.app a a_1) := _ | (expr.lam a a_1 a_2 a_3) := _ | (expr.pi a a_1 a_2 a_3) := _ | (expr.elet a a_1 a_2 a_3) := _ | (expr.macro a a_1) := _ ``` A similar result can be obtained by invoking `Equations Stub` on the following: ``` meta def foo : expr → tactic unit := -- do not forget to write `:=`!! {! !} ``` ``` meta def foo : expr → tactic unit := -- don't forget to erase `:=`!! | (expr.var a) := _ | (expr.sort a) := _ | (expr.const a a_1) := _ | (expr.mvar a a_1 a_2) := _ | (expr.local_const a a_1 a_2 a_3) := _ | (expr.app a a_1) := _ | (expr.lam a a_1 a_2 a_3) := _ | (expr.pi a a_1 a_2 a_3) := _ | (expr.elet a a_1 a_2 a_3) := _ | (expr.macro a a_1) := _ ``` -/ @[hole_command] meta def eqn_stub : hole_command := { name := "Equations Stub", descr := "Generate a list of equations for a recursive definition.", action := λ es, do t ← match es with | [t] := to_expr t | [] := target | _ := fail "expecting one type" end, e ← whnf t, (v :: _,_) ← mk_local_pis e | fail "expecting a Pi-type", t' ← infer_type v, fs ← mk_patterns t', t ← pp t, let out := if es.empty then format.to_string format!"-- do not forget to erase `:=`!!\n{format.join fs}" else format.to_string format!"{t}\n{format.join fs}", return [(out,"")] } /-- This command lists the constructors that can be used to satisfy the expected type. When used in the following hole: ``` def foo : ℤ ⊕ ℕ := {! !} ``` the command will produce: ``` def foo : ℤ ⊕ ℕ := {! sum.inl, sum.inr !} ``` and will display: ``` sum.inl : ℤ → ℤ ⊕ ℕ sum.inr : ℕ → ℤ ⊕ ℕ ``` -/ @[hole_command] meta def list_constructors_hole : hole_command := { name := "List Constructors", descr := "Show the list of constructors of the expected type.", action := λ es, do t ← target >>= whnf, (_,t) ← mk_local_pis t, let cl := t.get_app_fn.const_name, let args := t.get_app_args, env ← get_env, let cs := env.constructors_of cl, ts ← cs.mmap $ λ c, do { e ← mk_const c, t ← infer_type (e.mk_app args) >>= pp, c ← strip_prefix c, pure format!"\n{c} : {t}\n" }, fs ← format.intercalate ", " <$> cs.mmap (strip_prefix >=> pure ∘ to_fmt), let out := format.to_string format!"{{! {fs} !}", trace (format.join ts).to_string, return [(out,"")] } meta def classical : tactic unit := do h ← get_unused_name `_inst, mk_const `classical.prop_decidable >>= note h none, reset_instance_cache open expr meta def add_prime : name → name | (name.mk_string s p) := name.mk_string (s ++ "'") p | n := (name.mk_string "x'" n) meta def mk_comp (v : expr) : expr → tactic expr | (app f e) := if e = v then pure f else do guard (¬ v.occurs f) <|> fail "bad guard", e' ← mk_comp e >>= instantiate_mvars, f ← instantiate_mvars f, mk_mapp ``function.comp [none,none,none,f,e'] | e := do guard (e = v), t ← infer_type e, mk_mapp ``id [t] meta def mk_higher_order_type : expr → tactic expr | (pi n bi d b@(pi _ _ _ _)) := do v ← mk_local_def n d, let b' := (b.instantiate_var v), (pi n bi d ∘ flip abstract_local v.local_uniq_name) <$> mk_higher_order_type b' | (pi n bi d b) := do v ← mk_local_def n d, let b' := (b.instantiate_var v), (l,r) ← match_eq b' <|> fail format!"not an equality {b'}", l' ← mk_comp v l, r' ← mk_comp v r, mk_app ``eq [l',r'] | e := failed open lean.parser interactive.types @[user_attribute] meta def higher_order_attr : user_attribute unit (option name) := { name := `higher_order, parser := optional ident, descr := "From a lemma of the shape `f (g x) = h x` derive an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions.", after_set := some $ λ lmm _ _, do env ← get_env, decl ← env.get lmm, let num := decl.univ_params.length, let lvls := (list.iota num).map (`l).append_after, let l : expr := expr.const lmm $ lvls.map level.param, t ← infer_type l >>= instantiate_mvars, t' ← mk_higher_order_type t, (_,pr) ← solve_aux t' $ do { intros, applyc ``_root_.funext, intro1, applyc lmm; assumption }, pr ← instantiate_mvars pr, lmm' ← higher_order_attr.get_param lmm, lmm' ← (flip name.update_prefix lmm.get_prefix <$> lmm') <|> pure (add_prime lmm), add_decl $ declaration.thm lmm' lvls t' (pure pr), copy_attribute `simp lmm tt lmm', copy_attribute `functor_norm lmm tt lmm' } attribute [higher_order map_comp_pure] map_pure private meta def tactic.use_aux (h : pexpr) : tactic unit := (focus1 (refine h >> done)) <|> (fconstructor >> tactic.use_aux) protected meta def use (l : list pexpr) : tactic unit := focus1 $ seq (l.mmap' $ λ h, tactic.use_aux h <|> fail format!"failed to instantiate goal with {h}") instantiate_mvars_in_target meta def clear_aux_decl_aux : list expr → tactic unit | [] := skip | (e::l) := do cond e.is_aux_decl (tactic.clear e) skip, clear_aux_decl_aux l meta def clear_aux_decl : tactic unit := local_context >>= clear_aux_decl_aux /-- `apply_at_aux e et [] h ht` (with `et` the type of `e` and `ht` the type of `h`) finds a list of expressions `vs` and returns (e.mk_args (vs ++ [h]), vs) -/ meta def apply_at_aux (arg t : expr) : list expr → expr → expr → tactic (expr × list expr) | vs e (pi n bi d b) := do { v ← mk_meta_var d, apply_at_aux (v :: vs) (e v) (b.instantiate_var v) } <|> (e arg, vs) <$ unify d t | vs e _ := failed /-- `apply_at e h` applies implication `e` on hypothesis `h` and replaces `h` with the result -/ meta def apply_at (e h : expr) : tactic unit := do ht ← infer_type h, et ← infer_type e, (h', gs') ← apply_at_aux h ht [] e et, note h.local_pp_name none h', clear h, gs' ← gs'.mfilter is_assigned, (g :: gs) ← get_goals, set_goals (g :: gs' ++ gs) /-- `symmetry_hyp h` applies symmetry on hypothesis `h` -/ meta def symmetry_hyp (h : expr) (md := semireducible) : tactic unit := do tgt ← infer_type h, env ← get_env, let r := get_app_fn tgt, match env.symm_for (const_name r) with | (some symm) := do s ← mk_const symm, apply_at s h | none := fail "symmetry tactic failed, target is not a relation application with the expected property." end precedence `setup_tactic_parser`:0 @[user_command] meta def setup_tactic_parser_cmd (_ : interactive.parse $ tk "setup_tactic_parser") : lean.parser unit := emit_code_here " open lean open lean.parser open interactive interactive.types local postfix `?`:9001 := optional local postfix *:9001 := many . " meta def trace_error (msg : string) (t : tactic α) : tactic α | s := match t s with | (result.success r s') := result.success r s' | (result.exception (some msg') p s') := (trace msg >> trace (msg' ()) >> result.exception (some msg') p) s' | (result.exception none p s') := result.exception none p s' end /-- This combinator is for testing purposes. It succeeds if `t` fails with message `msg`, and fails otherwise. -/ meta def {u} success_if_fail_with_msg {α : Type u} (t : tactic α) (msg : string) : tactic unit := λ s, match t s with | (interaction_monad.result.exception msg' _ s') := if msg = (msg'.iget ()).to_string then result.success () s else mk_exception "failure messages didn't match" none s | (interaction_monad.result.success a s) := mk_exception "success_if_fail_with_msg combinator failed, given tactic succeeded" none s end open lean interactive meta def pformat := tactic format meta def pformat.mk (fmt : format) : pformat := pure fmt meta def to_pfmt {α} [has_to_tactic_format α] (x : α) : pformat := pp x meta instance pformat.has_to_tactic_format : has_to_tactic_format pformat := ⟨ id ⟩ meta instance : has_append pformat := ⟨ λ x y, (++) <$> x <*> y ⟩ meta instance tactic.has_to_tactic_format [has_to_tactic_format α] : has_to_tactic_format (tactic α) := ⟨ λ x, x >>= to_pfmt ⟩ private meta def parse_pformat : string → list char → parser pexpr | acc [] := pure ``(to_pfmt %%(reflect acc)) | acc ('\n'::s) := do f ← parse_pformat "" s, pure ``(to_pfmt %%(reflect acc) ++ pformat.mk format.line ++ %%f) | acc ('{'::'{'::s) := parse_pformat (acc ++ "{") s | acc ('{'::s) := do (e, s) ← with_input (lean.parser.pexpr 0) s.as_string, '}'::s ← return s.to_list | fail "'}' expected", f ← parse_pformat "" s, pure ``(to_pfmt %%(reflect acc) ++ to_pfmt %%e ++ %%f) | acc (c::s) := parse_pformat (acc.str c) s reserve prefix `pformat! `:100 /-- See `format!` in `init/meta/interactive_base.lean`. The main differences are that `pp` is called instead of `to_fmt` and that we can use arguments of type `tactic α` in the quotations. Now, consider the following: ``` e ← to_expr ``(3 + 7), trace format!"{e}" -- outputs `has_add.add.{0} nat nat.has_add (bit1.{0} nat nat.has_one nat.has_add (has_one.one.{0} nat nat.has_one)) ...` trace pformat!"{e}" -- outputs `3 + 7` ``` The difference is significant. And now, the following is expressible: ``` e ← to_expr ``(3 + 7), trace pformat!"{e} : {infer_type e}" -- outputs `3 + 7 : ℕ` ``` See also: `trace!` and `fail!` -/ @[user_notation] meta def pformat_macro (_ : parse $ tk "pformat!") (s : string) : parser pexpr := do e ← parse_pformat "" s.to_list, return ``(%%e : pformat) reserve prefix `fail! `:100 /-- the combination of `pformat` and `fail` -/ @[user_notation] meta def fail_macro (_ : parse $ tk "fail!") (s : string) : parser pexpr := do e ← pformat_macro () s, pure ``((%%e : pformat) >>= fail) reserve prefix `trace! `:100 /-- the combination of `pformat` and `fail` -/ @[user_notation] meta def trace_macro (_ : parse $ tk "trace!") (s : string) : parser pexpr := do e ← pformat_macro () s, pure ``((%%e : pformat) >>= trace) /-- A hackish way to get the `src` directory of mathlib. -/ meta def get_mathlib_dir : tactic string := do e ← get_env, s ← e.decl_olean `tactic.reset_instance_cache, return $ s.popn_back 17 /-- Checks whether a declaration with the given name is declared in mathlib. If you want to run this tactic many times, you should use `environment.is_prefix_of_file` instead, since it is expensive to execute `get_mathlib_dir` many times. -/ meta def is_in_mathlib (n : name) : tactic bool := do ml ← get_mathlib_dir, e ← get_env, return $ e.is_prefix_of_file ml n /-- auxiliary function for apply_under_pis -/ private meta def apply_under_pis_aux (func arg : pexpr) : ℕ → expr → pexpr | n (expr.pi nm bi tp bd) := expr.pi nm bi (pexpr.of_expr tp) (apply_under_pis_aux (n+1) bd) | n _ := let vars := ((list.range n).reverse.map (@expr.var ff)), bd := vars.foldl expr.app arg.mk_explicit in func bd /-- Assumes `pi_expr` is of the form `Π x1 ... xn, _`. Creates a pexpr of the form `Π x1 ... xn, func (arg x1 ... xn)`. All arguments (implicit and explicit) to `arg` should be supplied. -/ meta def apply_under_pis (func arg : pexpr) (pi_expr : expr) : pexpr := apply_under_pis_aux func arg 0 pi_expr /-- Tries to derive instances by unfolding the newly introduced type and applying type class resolution. For example, ``` @[derive ring] def new_int : Type := ℤ ``` adds an instance `ring new_int`, defined to be the instance of `ring ℤ` found by `apply_instance`. Multiple instances can be added with `@[derive [ring, module ℝ]]`. This derive handler applies only to declarations made using `def`, and will fail on such a declaration if it is unable to derive an instance. It is run with higher priority than the built-in handlers, which will fail on `def`s. -/ @[derive_handler, priority 2000] meta def delta_instance : derive_handler := λ cls new_decl_name, do env ← get_env, if env.is_inductive new_decl_name then return ff else do new_decl_type ← declaration.type <$> get_decl new_decl_name, new_decl_pexpr ← resolve_name new_decl_name, tgt ← to_expr $ apply_under_pis cls new_decl_pexpr new_decl_type, (_, inst) ← solve_aux tgt (intros >> reset_instance_cache >> delta_target [new_decl_name] >> apply_instance >> done), inst ← instantiate_mvars inst, tgt ← instantiate_mvars tgt, nm ← get_unused_decl_name $ new_decl_name ++ match cls with -- the postfix is needed because we can't protect this name. using nm.last directly can -- conflict with open namespaces | (expr.const nm _) := (nm.last ++ "_1" : string) | _ := "inst" end, add_decl $ mk_definition nm inst.collect_univ_params tgt inst, set_basic_attribute `instance nm tt, return tt /-- `find_private_decl n none` finds a private declaration named `n` in any of the imported files. `find_private_decl n (some m)` finds a private declaration named `n` in the same file where a declaration named `m` can be found. -/ meta def find_private_decl (n : name) (fr : option name) : tactic name := do env ← get_env, fn ← option_t.run (do fr ← option_t.mk (return fr), d ← monad_lift $ get_decl fr, option_t.mk (return $ env.decl_olean d.to_name) ), let p : string → bool := match fn with | (some fn) := λ x, fn = x | none := λ _, tt end, let xs := env.decl_filter_map (λ d, do fn ← env.decl_olean d.to_name, guard ((`_private).is_prefix_of d.to_name ∧ p fn ∧ d.to_name.update_prefix name.anonymous = n), pure d.to_name), match xs with | [n] := pure n | [] := fail "no such private found" | _ := fail "many matches found" end open lean.parser interactive /-- `import_private foo from bar` finds a private declaration `foo` in the same file as `bar` and creates a local notation to refer to it. `import_private foo`, looks for `foo` in all imported files. -/ @[user_command] meta def import_private_cmd (_ : parse $ tk "import_private") : lean.parser unit := do n ← ident, fr ← optional (tk "from" *> ident), n ← find_private_decl n fr, c ← resolve_constant n, d ← get_decl n, let c := @expr.const tt c d.univ_levels, new_n ← new_aux_decl_name, add_decl $ declaration.defn new_n d.univ_params d.type c reducibility_hints.abbrev d.is_trusted, let new_not := sformat!"local notation `{n.update_prefix name.anonymous}` := {new_n}", emit_command_here $ new_not, skip . end tactic
af414bea912464e9e4f8b7f6946de32b6a132db5
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/order/filter/extr.lean
66b3a8e4208218784d1ee31a1427e659013394ea
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
21,292
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_sets' $ λ _, le_refl _ lemma is_max_filter_const {b : β} : is_max_filter (λ _, b) l a := univ_mem_sets' $ λ _, 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_sets_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_sets_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_sets_of_superset (inter_mem_sets 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_sets_of_superset (inter_mem_sets 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
f8772167bfb7012ee64982187ad1e0cdab8fce47
c777c32c8e484e195053731103c5e52af26a25d1
/src/algebraic_geometry/ringed_space.lean
9018859254f69e468a3491ed4e75b2f2eb3cbf05
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
6,951
lean
/- Copyright (c) 2021 Justus Springer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Justus Springer, Andrew Yang -/ import algebra.category.Ring.filtered_colimits import algebraic_geometry.sheafed_space import topology.sheaves.stalks import algebra.category.Ring.colimits import algebra.category.Ring.limits /-! # Ringed spaces We introduce the category of ringed spaces, as an alias for `SheafedSpace CommRing`. The facts collected in this file are typically stated for locally ringed spaces, but never actually make use of the locality of stalks. See for instance <https://stacks.math.columbia.edu/tag/01HZ>. -/ universe v open category_theory open topological_space open opposite open Top open Top.presheaf namespace algebraic_geometry /-- The type of Ringed spaces, as an abbreviation for `SheafedSpace CommRing`. -/ abbreviation RingedSpace : Type* := SheafedSpace CommRing namespace RingedSpace open SheafedSpace variables (X : RingedSpace.{v}) /-- If the germ of a section `f` is a unit in the stalk at `x`, then `f` must be a unit on some small neighborhood around `x`. -/ lemma is_unit_res_of_is_unit_germ (U : opens X) (f : X.presheaf.obj (op U)) (x : U) (h : is_unit (X.presheaf.germ x f)) : ∃ (V : opens X) (i : V ⟶ U) (hxV : x.1 ∈ V), is_unit (X.presheaf.map i.op f) := begin obtain ⟨g', heq⟩ := h.exists_right_inv, obtain ⟨V, hxV, g, rfl⟩ := X.presheaf.germ_exist x.1 g', let W := U ⊓ V, have hxW : x.1 ∈ W := ⟨x.2, hxV⟩, erw [← X.presheaf.germ_res_apply (opens.inf_le_left U V) ⟨x.1, hxW⟩ f, ← X.presheaf.germ_res_apply (opens.inf_le_right U V) ⟨x.1, hxW⟩ g, ← ring_hom.map_mul, ← ring_hom.map_one (X.presheaf.germ (⟨x.1, hxW⟩ : W))] at heq, obtain ⟨W', hxW', i₁, i₂, heq'⟩ := X.presheaf.germ_eq x.1 hxW hxW _ _ heq, use [W', i₁ ≫ opens.inf_le_left U V, hxW'], rw [ring_hom.map_one, ring_hom.map_mul, ← comp_apply, ← X.presheaf.map_comp, ← op_comp] at heq', exact is_unit_of_mul_eq_one _ _ heq', end /-- If a section `f` is a unit in each stalk, `f` must be a unit. -/ lemma is_unit_of_is_unit_germ (U : opens X) (f : X.presheaf.obj (op U)) (h : ∀ x : U, is_unit (X.presheaf.germ x f)) : is_unit f := begin -- We pick a cover of `U` by open sets `V x`, such that `f` is a unit on each `V x`. choose V iVU m h_unit using λ x : U, X.is_unit_res_of_is_unit_germ U f x (h x), have hcover : U ≤ supr V, { intros x hxU, rw [opens.mem_supr], exact ⟨⟨x, hxU⟩, m ⟨x, hxU⟩⟩ }, -- Let `g x` denote the inverse of `f` in `U x`. choose g hg using λ x : U, is_unit.exists_right_inv (h_unit x), -- We claim that these local inverses glue together to a global inverse of `f`. obtain ⟨gl, gl_spec, -⟩ := X.sheaf.exists_unique_gluing' V U iVU hcover g _, swap, { intros x y, apply section_ext X.sheaf (V x ⊓ V y), rintro ⟨z, hzVx, hzVy⟩, rw [germ_res_apply, germ_res_apply], apply (is_unit.mul_right_inj (h ⟨z, (iVU x).le hzVx⟩)).mp, erw [← X.presheaf.germ_res_apply (iVU x) ⟨z, hzVx⟩ f, ← ring_hom.map_mul, congr_arg (X.presheaf.germ (⟨z, hzVx⟩ : V x)) (hg x), germ_res_apply, ← X.presheaf.germ_res_apply (iVU y) ⟨z, hzVy⟩ f, ← ring_hom.map_mul, congr_arg (X.presheaf.germ (⟨z, hzVy⟩ : V y)) (hg y), ring_hom.map_one, ring_hom.map_one] }, apply is_unit_of_mul_eq_one f gl, apply X.sheaf.eq_of_locally_eq' V U iVU hcover, intro i, rw [ring_hom.map_one, ring_hom.map_mul, gl_spec], exact hg i, end /-- The basic open of a section `f` is the set of all points `x`, such that the germ of `f` at `x` is a unit. -/ def basic_open {U : opens X} (f : X.presheaf.obj (op U)) : opens X := { carrier := coe '' { x : U | is_unit (X.presheaf.germ x f) }, is_open' := begin rw is_open_iff_forall_mem_open, rintros _ ⟨x, hx, rfl⟩, obtain ⟨V, i, hxV, hf⟩ := X.is_unit_res_of_is_unit_germ U f x hx, use V.1, refine ⟨_, V.2, hxV⟩, intros y hy, use (⟨y, i.le hy⟩ : U), rw set.mem_set_of_eq, split, { convert ring_hom.is_unit_map (X.presheaf.germ ⟨y, hy⟩) hf, exact (X.presheaf.germ_res_apply i ⟨y, hy⟩ f).symm }, { refl } end } @[simp] lemma mem_basic_open {U : opens X} (f : X.presheaf.obj (op U)) (x : U) : ↑x ∈ X.basic_open f ↔ is_unit (X.presheaf.germ x f) := begin split, { rintro ⟨x, hx, a⟩, cases subtype.eq a, exact hx }, { intro h, exact ⟨x, h, rfl⟩ }, end @[simp] lemma mem_top_basic_open (f : X.presheaf.obj (op ⊤)) (x : X) : x ∈ X.basic_open f ↔ is_unit (X.presheaf.germ ⟨x, show x ∈ (⊤ : opens X), by trivial⟩ f) := mem_basic_open X f ⟨x, _⟩ lemma basic_open_le {U : opens X} (f : X.presheaf.obj (op U)) : X.basic_open f ≤ U := by { rintros _ ⟨x, hx, rfl⟩, exact x.2 } /-- The restriction of a section `f` to the basic open of `f` is a unit. -/ lemma is_unit_res_basic_open {U : opens X} (f : X.presheaf.obj (op U)) : is_unit (X.presheaf.map (@hom_of_le (opens X) _ _ _ (X.basic_open_le f)).op f) := begin apply is_unit_of_is_unit_germ, rintro ⟨_, ⟨x, hx, rfl⟩⟩, convert hx, rw germ_res_apply, refl, end @[simp] lemma basic_open_res {U V : (opens X)ᵒᵖ} (i : U ⟶ V) (f : X.presheaf.obj U) : @basic_open X (unop V) (X.presheaf.map i f) = (unop V) ⊓ @basic_open X (unop U) f := begin induction U using opposite.rec, induction V using opposite.rec, let g := i.unop, have : i = g.op := rfl, clear_value g, subst this, ext, split, { rintro ⟨x, (hx : is_unit _), rfl⟩, rw germ_res_apply at hx, exact ⟨x.2, g x, hx, rfl⟩ }, { rintros ⟨hxV, x, hx, rfl⟩, refine ⟨⟨x, hxV⟩, (_ : is_unit _), rfl⟩, rwa germ_res_apply } end -- This should fire before `basic_open_res`. @[simp, priority 1100] lemma basic_open_res_eq {U V : (opens X)ᵒᵖ} (i : U ⟶ V) [is_iso i] (f : X.presheaf.obj U) : @basic_open X (unop V) (X.presheaf.map i f) = @RingedSpace.basic_open X (unop U) f := begin apply le_antisymm, { rw X.basic_open_res i f, exact inf_le_right }, { have := X.basic_open_res (inv i) (X.presheaf.map i f), rw [← comp_apply, ← X.presheaf.map_comp, is_iso.hom_inv_id, X.presheaf.map_id] at this, erw this, exact inf_le_right } end @[simp] lemma basic_open_mul {U : opens X} (f g : X.presheaf.obj (op U)) : X.basic_open (f * g) = X.basic_open f ⊓ X.basic_open g := begin ext1, dsimp [RingedSpace.basic_open], rw ←set.image_inter subtype.coe_injective, congr, ext, simp_rw map_mul, exact is_unit.mul_iff, end lemma basic_open_of_is_unit {U : opens X} {f : X.presheaf.obj (op U)} (hf : is_unit f) : X.basic_open f = U := begin apply le_antisymm, { exact X.basic_open_le f }, intros x hx, erw X.mem_basic_open f (⟨x, hx⟩ : U), exact ring_hom.is_unit_map _ hf end end RingedSpace end algebraic_geometry
edbd579d0fec29d5588fc8acf68284f1e5c14e81
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/data/real/cau_seq_completion.lean
c573439e6899629dceea5dccf0887d8885a868a0
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,894
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Robert Y. Lewis Generalizes the Cauchy completion of (ℚ, abs) to the completion of a commutative ring with absolute value. -/ import data.real.cau_seq namespace cau_seq.completion open cau_seq section parameters {α : Type*} [linear_ordered_field α] parameters {β : Type*} [comm_ring β] {abv : β → α} [is_absolute_value abv] def Cauchy := @quotient (cau_seq _ abv) cau_seq.equiv def mk : cau_seq _ abv → Cauchy := quotient.mk @[simp] theorem mk_eq_mk (f) : @eq Cauchy ⟦f⟧ (mk f) := rfl theorem mk_eq {f g} : mk f = mk g ↔ f ≈ g := quotient.eq def of_rat (x : β) : Cauchy := mk (const abv x) instance : has_zero Cauchy := ⟨of_rat 0⟩ instance : has_one Cauchy := ⟨of_rat 1⟩ instance : inhabited Cauchy := ⟨0⟩ theorem of_rat_zero : of_rat 0 = 0 := rfl theorem of_rat_one : of_rat 1 = 1 := rfl @[simp] theorem mk_eq_zero {f} : mk f = 0 ↔ lim_zero f := by have : mk f = 0 ↔ lim_zero (f - 0) := quotient.eq; rwa sub_zero at this instance : has_add Cauchy := ⟨λ x y, quotient.lift_on₂ x y (λ f g, mk (f + g)) $ λ f₁ g₁ f₂ g₂ hf hg, quotient.sound $ by simpa [(≈), setoid.r, sub_eq_add_neg, add_comm, add_left_comm, add_assoc] using add_lim_zero hf hg⟩ @[simp] theorem mk_add (f g : cau_seq β abv) : mk f + mk g = mk (f + g) := rfl instance : has_neg Cauchy := ⟨λ x, quotient.lift_on x (λ f, mk (-f)) $ λ f₁ f₂ hf, quotient.sound $ by simpa [(≈), setoid.r] using neg_lim_zero hf⟩ @[simp] theorem mk_neg (f : cau_seq β abv) : -mk f = mk (-f) := rfl instance : has_mul Cauchy := ⟨λ x y, quotient.lift_on₂ x y (λ f g, mk (f * g)) $ λ f₁ g₁ f₂ g₂ hf hg, quotient.sound $ by simpa [(≈), setoid.r, mul_add, mul_comm, add_assoc, sub_eq_add_neg] using add_lim_zero (mul_lim_zero_right g₁ hf) (mul_lim_zero_right f₂ hg)⟩ @[simp] theorem mk_mul (f g : cau_seq β abv) : mk f * mk g = mk (f * g) := rfl instance : has_sub Cauchy := ⟨λ x y, quotient.lift_on₂ x y (λ f g, mk (f - g)) $ λ f₁ g₁ f₂ g₂ hf hg, quotient.sound $ show ((f₁ - g₁) - (f₂ - g₂)).lim_zero, by simpa [sub_eq_add_neg, add_assoc, add_comm, add_left_comm] using sub_lim_zero hf hg⟩ @[simp] theorem mk_sub (f g : cau_seq β abv) : mk f - mk g = mk (f - g) := rfl theorem of_rat_add (x y : β) : of_rat (x + y) = of_rat x + of_rat y := congr_arg mk (const_add _ _) theorem of_rat_neg (x : β) : of_rat (-x) = -of_rat x := congr_arg mk (const_neg _) theorem of_rat_mul (x y : β) : of_rat (x * y) = of_rat x * of_rat y := congr_arg mk (const_mul _ _) private lemma zero_def : 0 = mk 0 := rfl private lemma one_def : 1 = mk 1 := rfl instance : comm_ring Cauchy := by refine { neg := has_neg.neg, sub := has_sub.sub, sub_eq_add_neg := _, add := (+), zero := 0, mul := (*), one := 1, .. }; { repeat {refine λ a, quotient.induction_on a (λ _, _)}, simp [zero_def, one_def, mul_left_comm, mul_comm, mul_add, add_comm, add_left_comm, sub_eq_add_neg] } theorem of_rat_sub (x y : β) : of_rat (x - y) = of_rat x - of_rat y := congr_arg mk (const_sub _ _) end open_locale classical section parameters {α : Type*} [linear_ordered_field α] parameters {β : Type*} [field β] {abv : β → α} [is_absolute_value abv] local notation `Cauchy` := @Cauchy _ _ _ _ abv _ noncomputable instance : has_inv Cauchy := ⟨λ x, quotient.lift_on x (λ f, mk $ if h : lim_zero f then 0 else inv f h) $ λ f g fg, begin have := lim_zero_congr fg, by_cases hf : lim_zero f, { simp [hf, this.1 hf, setoid.refl] }, { have hg := mt this.2 hf, simp [hf, hg], have If : mk (inv f hf) * mk f = 1 := mk_eq.2 (inv_mul_cancel hf), have Ig : mk (inv g hg) * mk g = 1 := mk_eq.2 (inv_mul_cancel hg), rw [mk_eq.2 fg, ← Ig] at If, rw mul_comm at Ig, rw [← mul_one (mk (inv f hf)), ← Ig, ← mul_assoc, If, mul_assoc, Ig, mul_one] } end⟩ @[simp] theorem inv_zero : (0 : Cauchy)⁻¹ = 0 := congr_arg mk $ by rw dif_pos; [refl, exact zero_lim_zero] @[simp] theorem inv_mk {f} (hf) : (@mk α _ β _ abv _ f)⁻¹ = mk (inv f hf) := congr_arg mk $ by rw dif_neg lemma cau_seq_zero_ne_one : ¬ (0 : cau_seq _ abv) ≈ 1 := λ h, have lim_zero (1 - 0), from setoid.symm h, have lim_zero 1, by simpa, one_ne_zero $ const_lim_zero.1 this lemma zero_ne_one : (0 : Cauchy) ≠ 1 := λ h, cau_seq_zero_ne_one $ mk_eq.1 h protected theorem inv_mul_cancel {x : Cauchy} : x ≠ 0 → x⁻¹ * x = 1 := quotient.induction_on x $ λ f hf, begin simp at hf, simp [hf], exact quotient.sound (cau_seq.inv_mul_cancel hf) end noncomputable def field : field Cauchy := { inv := has_inv.inv, mul_inv_cancel := λ x x0, by rw [mul_comm, cau_seq.completion.inv_mul_cancel x0], exists_pair_ne := ⟨0, 1, zero_ne_one⟩, inv_zero := inv_zero, .. Cauchy.comm_ring } local attribute [instance] field theorem of_rat_inv (x : β) : of_rat (x⁻¹) = ((of_rat x)⁻¹ : Cauchy) := congr_arg mk $ by split_ifs with h; [simp [const_lim_zero.1 h], refl] theorem of_rat_div (x y : β) : of_rat (x / y) = (of_rat x / of_rat y : Cauchy) := by simp only [div_eq_inv_mul, of_rat_inv, of_rat_mul] end end cau_seq.completion variables {α : Type*} [linear_ordered_field α] namespace cau_seq section variables (β : Type*) [ring β] (abv : β → α) [is_absolute_value abv] class is_complete := (is_complete : ∀ s : cau_seq β abv, ∃ b : β, s ≈ const abv b) end section variables {β : Type*} [ring β] {abv : β → α} [is_absolute_value abv] variable [is_complete β abv] lemma complete : ∀ s : cau_seq β abv, ∃ b : β, s ≈ const abv b := is_complete.is_complete noncomputable def lim (s : cau_seq β abv) := classical.some (complete s) lemma equiv_lim (s : cau_seq β abv) : s ≈ const abv (lim s) := classical.some_spec (complete s) lemma eq_lim_of_const_equiv {f : cau_seq β abv} {x : β} (h : cau_seq.const abv x ≈ f) : x = lim f := const_equiv.mp $ setoid.trans h $ equiv_lim f lemma lim_eq_of_equiv_const {f : cau_seq β abv} {x : β} (h : f ≈ cau_seq.const abv x) : lim f = x := (eq_lim_of_const_equiv $ setoid.symm h).symm lemma lim_eq_lim_of_equiv {f g : cau_seq β abv} (h : f ≈ g) : lim f = lim g := lim_eq_of_equiv_const $ setoid.trans h $ equiv_lim g @[simp] lemma lim_const (x : β) : lim (const abv x) = x := lim_eq_of_equiv_const $ setoid.refl _ lemma lim_add (f g : cau_seq β abv) : lim f + lim g = lim (f + g) := eq_lim_of_const_equiv $ show lim_zero (const abv (lim f + lim g) - (f + g)), by rw [const_add, add_sub_comm]; exact add_lim_zero (setoid.symm (equiv_lim f)) (setoid.symm (equiv_lim g)) lemma lim_mul_lim (f g : cau_seq β abv) : lim f * lim g = lim (f * g) := eq_lim_of_const_equiv $ show lim_zero (const abv (lim f * lim g) - f * g), from have h : const abv (lim f * lim g) - f * g = (const abv (lim f) - f) * g + const abv (lim f) * (const abv (lim g) - g) := by simp [const_mul (lim f), mul_add, add_mul, sub_eq_add_neg, add_comm, add_left_comm], by rw h; exact add_lim_zero (mul_lim_zero_left _ (setoid.symm (equiv_lim _))) (mul_lim_zero_right _ (setoid.symm (equiv_lim _))) lemma lim_mul (f : cau_seq β abv) (x : β) : lim f * x = lim (f * const abv x) := by rw [← lim_mul_lim, lim_const] lemma lim_neg (f : cau_seq β abv) : lim (-f) = -lim f := lim_eq_of_equiv_const (show lim_zero (-f - const abv (-lim f)), by rw [const_neg, sub_neg_eq_add, add_comm, ← sub_eq_add_neg]; exact setoid.symm (equiv_lim f)) lemma lim_eq_zero_iff (f : cau_seq β abv) : lim f = 0 ↔ lim_zero f := ⟨assume h, by have hf := equiv_lim f; rw h at hf; exact (lim_zero_congr hf).mpr (const_lim_zero.mpr rfl), assume h, have h₁ : f = (f - const abv 0) := ext (λ n, by simp [sub_apply, const_apply]), by rw h₁ at h; exact lim_eq_of_equiv_const h ⟩ end section variables {β : Type*} [field β] {abv : β → α} [is_absolute_value abv] [is_complete β abv] lemma lim_inv {f : cau_seq β abv} (hf : ¬ lim_zero f) : lim (inv f hf) = (lim f)⁻¹ := have hl : lim f ≠ 0 := by rwa ← lim_eq_zero_iff at hf, lim_eq_of_equiv_const $ show lim_zero (inv f hf - const abv (lim f)⁻¹), from have h₁ : ∀ (g f : cau_seq β abv) (hf : ¬ lim_zero f), lim_zero (g - f * inv f hf * g) := λ g f hf, by rw [← one_mul g, ← mul_assoc, ← sub_mul, mul_one, mul_comm, mul_comm f]; exact mul_lim_zero_right _ (setoid.symm (cau_seq.inv_mul_cancel _)), have h₂ : lim_zero ((inv f hf - const abv (lim f)⁻¹) - (const abv (lim f) - f) * (inv f hf * const abv (lim f)⁻¹)) := by rw [sub_mul, ← sub_add, sub_sub, sub_add_eq_sub_sub, sub_right_comm, sub_add]; exact show lim_zero (inv f hf - const abv (lim f) * (inv f hf * const abv (lim f)⁻¹) - (const abv (lim f)⁻¹ - f * (inv f hf * const abv (lim f)⁻¹))), from sub_lim_zero (by rw [← mul_assoc, mul_right_comm, const_inv hl]; exact h₁ _ _ _) (by rw [← mul_assoc]; exact h₁ _ _ _), (lim_zero_congr h₂).mpr $ mul_lim_zero_left _ (setoid.symm (equiv_lim f)) end section variables [is_complete α abs] lemma lim_le {f : cau_seq α abs} {x : α} (h : f ≤ cau_seq.const abs x) : lim f ≤ x := cau_seq.const_le.1 $ cau_seq.le_of_eq_of_le (setoid.symm (equiv_lim f)) h lemma le_lim {f : cau_seq α abs} {x : α} (h : cau_seq.const abs x ≤ f) : x ≤ lim f := cau_seq.const_le.1 $ cau_seq.le_of_le_of_eq h (equiv_lim f) lemma lt_lim {f : cau_seq α abs} {x : α} (h : cau_seq.const abs x < f) : x < lim f := cau_seq.const_lt.1 $ cau_seq.lt_of_lt_of_eq h (equiv_lim f) lemma lim_lt {f : cau_seq α abs} {x : α} (h : f < cau_seq.const abs x) : lim f < x := cau_seq.const_lt.1 $ cau_seq.lt_of_eq_of_lt (setoid.symm (equiv_lim f)) h end end cau_seq
26aa0736f40a658b160839c07344a3ede7661a90
94e33a31faa76775069b071adea97e86e218a8ee
/src/linear_algebra/free_module/finite/basic.lean
bf561f6dcd798c760b81c2882f55fa31cc94c887
[ "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
3,293
lean
/- Copyright (c) 2021 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca -/ import linear_algebra.free_module.basic import linear_algebra.matrix.to_lin import ring_theory.finiteness /-! # Finite and free modules We provide some instances for finite and free modules. ## Main results * `module.free.choose_basis_index.fintype` : If a free module is finite, then any basis is finite. * `module.free.linear_map.free ` : if `M` and `N` are finite and free, then `M →ₗ[R] N` is free. * `module.finite.of_basis` : A free module with a basis indexed by a `fintype` is finite. * `module.free.linear_map.module.finite` : if `M` and `N` are finite and free, then `M →ₗ[R] N` is finite. -/ universes u v w variables (R : Type u) (M : Type v) (N : Type w) namespace module.free section ring variables [ring R] [add_comm_group M] [module R M] [module.free R M] /-- If a free module is finite, then any basis is finite. -/ noncomputable instance [nontrivial R] [module.finite R M] : fintype (module.free.choose_basis_index R M) := begin obtain ⟨h⟩ := id ‹module.finite R M›, choose s hs using h, exact basis_fintype_of_finite_spans ↑s hs (choose_basis _ _), end end ring section comm_ring variables [comm_ring R] [add_comm_group M] [module R M] [module.free R M] variables [add_comm_group N] [module R N] [module.free R N] instance linear_map [module.finite R M] [module.finite R N] : module.free R (M →ₗ[R] N) := begin casesI subsingleton_or_nontrivial R, { apply module.free.of_subsingleton' }, classical, exact of_equiv (linear_map.to_matrix (module.free.choose_basis R M) (module.free.choose_basis R N)).symm, end variables {R M} /-- A free module with a basis indexed by a `fintype` is finite. -/ lemma _root_.module.finite.of_basis {R : Type*} {M : Type*} {ι : Type*} [comm_ring R] [add_comm_group M] [module R M] [fintype ι] (b : basis ι R M) : module.finite R M := begin classical, refine ⟨⟨finset.univ.image b, _⟩⟩, simp only [set.image_univ, finset.coe_univ, finset.coe_image, basis.span_eq], end instance _root_.module.finite.matrix {ι₁ : Type*} [fintype ι₁] {ι₂ : Type*} [fintype ι₂] : module.finite R (matrix ι₁ ι₂ R) := module.finite.of_basis $ pi.basis $ λ i, pi.basis_fun R _ variables (M) instance _root_.module.finite.linear_map [module.finite R M] [module.finite R N] : module.finite R (M →ₗ[R] N) := begin casesI subsingleton_or_nontrivial R, { apply_instance }, classical, have f := (linear_map.to_matrix (choose_basis R M) (choose_basis R N)).symm, exact module.finite.of_surjective f.to_linear_map (linear_equiv.surjective f), end end comm_ring section integer variables [add_comm_group M] [module.finite ℤ M] [module.free ℤ M] variables [add_comm_group N] [module.finite ℤ N] [module.free ℤ N] instance _root_.module.finite.add_monoid_hom : module.finite ℤ (M →+ N) := module.finite.equiv (add_monoid_hom_lequiv_int ℤ).symm instance add_monoid_hom : module.free ℤ (M →+ N) := begin letI : module.free ℤ (M →ₗ[ℤ] N) := module.free.linear_map _ _ _, exact module.free.of_equiv (add_monoid_hom_lequiv_int ℤ).symm end end integer end module.free
e4dda1041114a6cfc03aeb46223fe029cebfbf5c
b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77
/src/topology/instances/complex.lean
50786e01ac6bde68b07e5552d5cf821d4372c79a
[ "Apache-2.0" ]
permissive
molodiuc/mathlib
cae2ba3ef1601c1f42ca0b625c79b061b63fef5b
98ebe5a6739fbe254f9ee9d401882d4388f91035
refs/heads/master
1,674,237,127,059
1,606,353,533,000
1,606,353,533,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,105
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Topology of the complex numbers. -/ import data.complex.basic import topology.instances.real noncomputable theory open filter metric open_locale topological_space namespace complex -- TODO(Mario): these proofs are all copied from analysis/real. Generalize -- to normed fields instance : metric_space ℂ := { dist := λx y, (x - y).abs, dist_self := by simp [abs_zero], eq_of_dist_eq_zero := by simp [sub_eq_zero], dist_comm := assume x y, complex.abs_sub _ _, dist_triangle := assume x y z, complex.abs_sub_le _ _ _ } theorem dist_eq (x y : ℂ) : dist x y = (x - y).abs := rfl theorem uniform_continuous_add : uniform_continuous (λp : ℂ × ℂ, p.1 + p.2) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_add_continuous_lemma abs ε0 in ⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ h₁ h₂⟩ theorem uniform_continuous_neg : uniform_continuous (@has_neg.neg ℂ _) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h, by rw dist_comm at h; simpa [dist_eq] using h⟩ instance : uniform_add_group ℂ := uniform_add_group.mk' uniform_continuous_add uniform_continuous_neg instance : topological_add_group ℂ := by apply_instance -- short-circuit type class inference lemma uniform_continuous_inv (s : set ℂ) {r : ℝ} (r0 : 0 < r) (H : ∀ x ∈ s, r ≤ abs x) : uniform_continuous (λp:s, p.1⁻¹) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_inv_continuous_lemma abs ε0 r0 in ⟨δ, δ0, λ a b h, Hδ (H _ a.2) (H _ b.2) h⟩ lemma uniform_continuous_abs : uniform_continuous (abs : ℂ → ℝ) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨ε, ε0, λ a b, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _)⟩ lemma continuous_abs : continuous (abs : ℂ → ℝ) := uniform_continuous_abs.continuous lemma tendsto_inv {r : ℂ} (r0 : r ≠ 0) : tendsto (λq, q⁻¹) (𝓝 r) (𝓝 r⁻¹) := by rw ← abs_pos at r0; exact tendsto_of_uniform_continuous_subtype (uniform_continuous_inv {x | abs r / 2 < abs x} (half_pos r0) (λ x h, le_of_lt h)) (mem_nhds_sets ((is_open_lt' (abs r / 2)).preimage continuous_abs) (half_lt_self r0)) lemma continuous_inv : continuous (λa:{r:ℂ // r ≠ 0}, a.val⁻¹) := continuous_iff_continuous_at.mpr $ assume ⟨r, hr⟩, tendsto.comp (tendsto_inv hr) (continuous_iff_continuous_at.mp continuous_subtype_val _) lemma continuous.inv {α} [topological_space α] {f : α → ℂ} (h : ∀a, f a ≠ 0) (hf : continuous f) : continuous (λa, (f a)⁻¹) := show continuous ((has_inv.inv ∘ @subtype.val ℂ (λr, r ≠ 0)) ∘ λa, ⟨f a, h a⟩), from continuous_inv.comp (continuous_subtype_mk _ hf) lemma uniform_continuous_mul_const {x : ℂ} : uniform_continuous ((*) x) := metric.uniform_continuous_iff.2 $ λ ε ε0, begin cases no_top (abs x) with y xy, have y0 := lt_of_le_of_lt (abs_nonneg _) xy, refine ⟨_, div_pos ε0 y0, λ a b h, _⟩, rw [dist_eq, ← mul_sub, abs_mul, ← mul_div_cancel' ε (ne_of_gt y0)], exact mul_lt_mul' (le_of_lt xy) h (abs_nonneg _) y0 end lemma uniform_continuous_mul (s : set (ℂ × ℂ)) {r₁ r₂ : ℝ} (H : ∀ x ∈ s, abs (x : ℂ × ℂ).1 < r₁ ∧ abs x.2 < r₂) : uniform_continuous (λp:s, p.1.1 * p.1.2) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_mul_continuous_lemma abs ε0 in ⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ (H _ a.2).1 (H _ b.2).2 h₁ h₂⟩ protected lemma continuous_mul : continuous (λp : ℂ × ℂ, p.1 * p.2) := continuous_iff_continuous_at.2 $ λ ⟨a₁, a₂⟩, tendsto_of_uniform_continuous_subtype (uniform_continuous_mul ({x | abs x < abs a₁ + 1}.prod {x | abs x < abs a₂ + 1}) (λ x, id)) (mem_nhds_sets (((is_open_gt' (abs a₁ + 1)).preimage continuous_abs).prod ((is_open_gt' (abs a₂ + 1)).preimage continuous_abs)) ⟨lt_add_one (abs a₁), lt_add_one (abs a₂)⟩) local attribute [semireducible] real.le lemma uniform_continuous_re : uniform_continuous re := metric.uniform_continuous_iff.2 (λ ε ε0, ⟨ε, ε0, λ _ _, lt_of_le_of_lt (abs_re_le_abs _)⟩) lemma continuous_re : continuous re := uniform_continuous_re.continuous lemma uniform_continuous_im : uniform_continuous im := metric.uniform_continuous_iff.2 (λ ε ε0, ⟨ε, ε0, λ _ _, lt_of_le_of_lt (abs_im_le_abs _)⟩) lemma continuous_im : continuous im := uniform_continuous_im.continuous lemma uniform_continuous_of_real : uniform_continuous of_real := metric.uniform_continuous_iff.2 (λ ε ε0, ⟨ε, ε0, λ _ _, by rw [real.dist_eq, complex.dist_eq, of_real_eq_coe, of_real_eq_coe, ← of_real_sub, abs_of_real]; exact id⟩) lemma continuous_of_real : continuous of_real := uniform_continuous_of_real.continuous instance : topological_ring ℂ := { continuous_mul := complex.continuous_mul, ..complex.topological_add_group } instance : topological_semiring ℂ := by apply_instance -- short-circuit type class inference /-- `ℂ` is homeomorphic to the real plane with `max` norm. -/ def real_prod_homeo : ℂ ≃ₜ (ℝ × ℝ) := { to_equiv := equiv_real_prod, continuous_to_fun := continuous_re.prod_mk continuous_im, continuous_inv_fun := show continuous (λ p : ℝ × ℝ, complex.mk p.1 p.2), by simp only [mk_eq_add_mul_I]; exact (continuous_of_real.comp continuous_fst).add ((continuous_of_real.comp continuous_snd).mul continuous_const) } instance : proper_space ℂ := ⟨λx r, begin refine real_prod_homeo.symm.compact_preimage.1 (compact_of_is_closed_subset ((proper_space.compact_ball x.re r).prod (proper_space.compact_ball x.im r)) (continuous_iff_is_closed.1 real_prod_homeo.symm.continuous _ is_closed_ball) _), exact λ p h, ⟨ le_trans (abs_re_le_abs (⟨p.1, p.2⟩ - x)) h, le_trans (abs_im_le_abs (⟨p.1, p.2⟩ - x)) h⟩ end⟩ end complex
bcb1b2ad692b36698afd346de7959ed9792ffb59
c31182a012eec69da0a1f6c05f42b0f0717d212d
/src/thm95/col_exact.lean
cc4272a70b72eda7a3a3c8c8133d33db9461aed3
[]
no_license
Ja1941/lean-liquid
fbec3ffc7fc67df1b5ca95b7ee225685ab9ffbdc
8e80ed0cbdf5145d6814e833a674eaf05a1495c1
refs/heads/master
1,689,437,983,362
1,628,362,719,000
1,628,362,719,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
56,857
lean
import category_theory.products.basic import category_theory.limits.concrete_category import for_mathlib.Cech.adjunction import for_mathlib.simplicial.iso import polyhedral_lattice.cosimplicial_extra import prop_92.prop_92 import normed_snake_dual import thm95.double_complex import thm95.col_exact_prep import thm95.polyhedral_iso import thm95.pfpng_iso noncomputable theory open_locale nnreal big_operators nat open category_theory opposite simplex_category local attribute [instance] type_pow universe variables u u₀ uₘ -- set_option pp.universes true namespace thm95 variables (BD : breen_deligne.data) (κ : ℕ → ℝ≥0) [BD.suitable κ] variables (r r' : ℝ≥0) [fact (0 < r)] [fact (0 < r')] [fact (r < r')] [fact (r' < 1)] variables (V : SemiNormedGroup.{u}) variables (Λ : PolyhedralLattice.{u}) (M : ProFiltPseuNormGrpWithTinv.{u} r') variables (N : ℕ) [fact (0 < N)] (n : ℕ) @[simps obj map] def scale_factorial : system_of_complexes.{u} ⥤ system_of_complexes.{u} := (whiskering_right _ _ _).obj $ homological_complex.modify_functor (λ m, SemiNormedGroup.rescale m!) (λ m₁ m₂, SemiNormedGroup.scale _ _) . namespace scale_factorial open system_of_complexes SemiNormedGroup homological_complex lemma is_weak_bounded_exact {C : system_of_complexes} {k K : ℝ≥0} [fact (1 ≤ k)] {m : ℕ} {c₀ : ℝ≥0} (hC : C.is_weak_bounded_exact k K m c₀) : (scale_factorial.obj C).is_weak_bounded_exact k (K * (m + 1)) m c₀ := begin intros c hc i hi x ε hε, let δ := ε * i!, have hδ : 0 < δ := mul_pos hε (nat.cast_pos.2 (nat.factorial_pos i)), have hifact : ¬(↑(i!) : ℝ) = 0 := by exact_mod_cast nat.factorial_ne_zero _, have him : 1 ≤ (↑m + 1) * ((↑i : ℝ) + 1)⁻¹, { refine le_trans _ (mul_le_mul_of_nonneg_right (show (↑i : ℝ) + 1 ≤ (↑m + 1), by rwa [add_le_add_iff_right, nat.cast_le]) (inv_nonneg.2 (add_nonneg ((@nat.cast_nonneg ℝ _ i)) zero_le_one))), rw mul_inv_cancel (ne_of_lt (add_pos_of_nonneg_of_pos (@nat.cast_nonneg ℝ _ i) zero_lt_one)).symm }, obtain ⟨_, _, rfl, rfl, y, hy⟩ := hC c hc i hi ((of_rescale i!).app _ x) δ hδ, refine ⟨_, _, rfl, rfl, ((SemiNormedGroup.to_rescale (i - 1)!).app _ y), _⟩, erw [rescale.norm_def, rescale.norm_def], simp only [nnreal.coe_nat_cast, nnreal.coe_add, nat.cast_succ, nat.factorial_succ, nat.cast_mul, nnreal.coe_one, nnreal.coe_mul, div_eq_mul_inv], rw [mul_inv_le_iff], swap, { exact_mod_cast nat.factorial_pos i }, refine hy.trans _, rw [left_distrib, mul_inv', ← mul_assoc ↑i!, mul_comm ↑i!, mul_assoc _ ↑i!, mul_comm ↑i!, mul_assoc _ _ ↑i!, inv_mul_cancel_right' hifact, mul_comm _ ε, add_le_add_iff_right, mul_assoc ↑K], refine mul_le_mul_of_nonneg_left _ (nnreal.coe_nonneg _), rw [mul_comm _ ((↑i : ℝ) + 1)⁻¹, ← mul_assoc], refine le_trans (le_mul_of_one_le_left (by simp only [one_mul, norm_nonneg]) him) (mul_le_mul_of_nonneg_left _ (mul_nonneg (add_nonneg (nat.cast_nonneg m) zero_le_one) (inv_nonneg.2 (add_nonneg (nat.cast_nonneg i) zero_le_one)))), simpa using le_refl _ end end scale_factorial section open PolyhedralLattice def CLCFP' : (ProFiltPseuNormGrpWithTinv r')ᵒᵖ ⥤ ℝ≥0ᵒᵖ ⥤ SemiNormedGroup := (ProFiltPseuNormGrpWithTinv.Pow r' n ⋙ (_root_.Filtration r').flip).op ⋙ functor.op_hom _ _ ⋙ (whiskering_right ℝ≥0ᵒᵖ Profiniteᵒᵖ _).obj (CLC V) lemma CLCFP'_map_app {M₁ M₂ : (ProFiltPseuNormGrpWithTinv r')ᵒᵖ} (f : M₁ ⟶ M₂) (c : ℝ≥0ᵒᵖ) : ((CLCFP' r' V n).map f).app c = (CLCFP V r' c.unop n).map f := rfl lemma CLCFP'_obj_map (M₁ : (ProFiltPseuNormGrpWithTinv r')ᵒᵖ) (c₁ c₂ : ℝ≥0ᵒᵖ) (h : c₁ ⟶ c₂) : ((CLCFP' r' V n).obj M₁).map h = (by haveI : fact (c₂.unop ≤ c₁.unop) := ⟨le_of_hom h.unop⟩; exact (CLCFP.res V r' c₁.unop c₂.unop n).app M₁) := rfl def Cech_nerve' : cosimplicial_object.augmented (ℝ≥0ᵒᵖ ⥤ SemiNormedGroup) := (cosimplicial_object.augmented.whiskering_obj.{u} _ _ (CLCFP' r' V n)).obj (Cech_nerve r' Λ M N) lemma Cech_nerve'_hom_zero : (Cech_nerve'.{u} r' V Λ M N n).hom.app (mk.{u} 0) = (CLCFP' r' V n).map (Cech_augmentation_map.{u} r' Λ M N).op := begin dsimp only [Cech_nerve', cosimplicial_object.augmented.whiskering_obj], simp only [whisker_right_app, category.id_comp, functor.right_op_map, nat_trans.comp_app, functor.const_comp_inv_app, Cech_nerve_hom_zero], end @[simps obj map] def Cech_nerve_level : ℝ≥0 ⥤ simplicial_object.augmented Profinite.{u} := (ProFiltPseuNormGrpWithTinv.Pow r' n ⋙ (Filtration r').flip).flip ⋙ (simplicial_object.augmented.whiskering _ _).flip.obj (Cech_nerve.{u} r' Λ M N).left_op . lemma Cech_nerve_level_left_map (c : ℝ≥0) (i j : simplex_categoryᵒᵖ) (g : i ⟶ j) : ((Cech_nerve_level r' Λ M N n).obj c).left.map g = ((Filtration r').obj c).map ((ProFiltPseuNormGrpWithTinv.Pow r' n).map ((Hom M).map ((Cech_conerve (Λ.diagonal_embedding N)).map g.unop).op)) := rfl lemma Cech_nerve_level_left_map' (c : ℝ≥0) (i j : simplex_categoryᵒᵖ) (g : i ⟶ j) (x : ((Cech_nerve_level r' Λ M N n).obj c).left.obj i) (k : fin n) : (((Cech_nerve_level r' Λ M N n).obj c).left.map g x).1 k = add_monoid_hom.comp (x.1 k) (polyhedral_lattice.conerve.map (Λ.diagonal_embedding N) ⇑(hom.to_preorder_hom g.unop)).to_add_monoid_hom := rfl lemma Cech_nerve_level_hom_app (c : ℝ≥0) : ((Cech_nerve_level r' Λ M N n).obj c).hom.app (op (mk 0)) = ((Filtration r').obj c).map ((ProFiltPseuNormGrpWithTinv.Pow r' n).map (Cech_augmentation_map r' Λ M N)) := begin dsimp only [Cech_nerve_level_obj, nat_trans.comp_app, whisker_right_app, functor.const_comp_hom_app], erw [category.comp_id], dsimp only [nat_trans.left_op_app, unop_op], rw [Cech_nerve_hom_zero], dsimp only [functor.flip_obj_map, functor.comp_map, quiver.hom.unop_op, functor.flip_map_app], refl end @[simps X d] def col_complex_aux : cochain_complex (ℝ≥0ᵒᵖ ⥤ SemiNormedGroup) ℕ := (Cech_nerve' r' V Λ M N n).to_cocomplex . @[simps obj obj_d map] def col_complex_level : system_of_complexes := ((whiskering_right _ _ _).obj $ FLC_functor' V).obj (Cech_nerve_level r' Λ M N n).op . @[simps obj obj_d map] def col_complex : system_of_complexes := (col_complex_aux r' V Λ M N n).as_functor . def col_complex_level_iso_obj_X (c : ℝ≥0ᵒᵖ) : Π (i : ℕ), ((col_complex_level r' V Λ M N n).obj c).X i ≅ ((col_complex r' V Λ M N n).obj c).X i | 0 := iso.refl _ | (i+1) := iso.refl _ lemma col_complex_level_iso_obj_comm (c : ℝ≥0ᵒᵖ) (i : ℕ) : (col_complex_level_iso_obj_X r' V Λ M N n c i).hom ≫ ((col_complex r' V Λ M N n).obj c).d i (i + 1) = ((col_complex_level r' V Λ M N n).obj c).d i (i + 1) ≫ (col_complex_level_iso_obj_X r' V Λ M N n c (i + 1)).hom := begin cases i, all_goals { dsimp only [col_complex_level_iso_obj_X], simp only [iso.refl_hom, category.id_comp, category.comp_id], dsimp only [col_complex_obj_d, col_complex_level_obj_d, cosimplicial_object.augmented.cocomplex, cosimplicial_object.augmented.to_cocomplex_d_2, cosimplicial_object.augmented.to_cocomplex_d, functor.const_comp_hom_app, functor.const_comp_inv_app, nat_trans.comp_app, whisker_right_app, nat_trans.right_op_app, nat_trans.left_op_app, cosimplicial_object.augmented.drop_obj, cosimplicial_object.coboundary, cosimplicial_object.δ, cosimplicial_object.whiskering_obj_obj_map], rw [dif_pos rfl, eq_to_hom_refl, category.comp_id, dif_pos rfl, eq_to_hom_refl, category.comp_id], }, { erw [Cech_nerve'_hom_zero, SemiNormedGroup.LCC_obj_map', category.id_comp], dsimp only [unop_op], erw [Cech_nerve_hom_zero, op_id, category.id_comp], refl }, { simp only [nat_trans.app_sum, nat_trans.app_gsmul], apply fintype.sum_congr, intro j, congr' 1, rw [SemiNormedGroup.LCC_obj_map'], refl, } end def col_complex_level_iso_obj (c : ℝ≥0ᵒᵖ) : (col_complex_level r' V Λ M N n).obj c ≅ (col_complex r' V Λ M N n).obj c := homological_complex.hom.iso_of_components (col_complex_level_iso_obj_X r' V Λ M N n c) (by { rintro i j (rfl : i + 1 = j), apply col_complex_level_iso_obj_comm }) lemma col_complex_level_iso_comm (c₁ c₂ : ℝ≥0ᵒᵖ) (h : c₁ ⟶ c₂) (i : ℕ) : ((col_complex_level r' V Λ M N n).map h ≫ (col_complex_level_iso_obj r' V Λ M N n c₂).hom).f i = ((col_complex_level_iso_obj r' V Λ M N n c₁).hom ≫ (col_complex r' V Λ M N n).map h).f i := begin cases i, all_goals { dsimp only [col_complex_level_iso_obj, col_complex_level_iso_obj_X, homological_complex.comp_f, homological_complex.hom.iso_of_components_hom_f, iso.refl_hom], rw [category.id_comp, category.comp_id], dsimp only [col_complex_level_map, col_complex_map, whisker_right_app, cosimplicial_object.augmented.cocomplex, cosimplicial_object.augmented.point_map, cosimplicial_object.augmented.drop_map], rw [SemiNormedGroup.LCC_obj_map'], refl }, end def col_complex_level_iso : col_complex_level r' V Λ M N n ≅ col_complex r' V Λ M N n := nat_iso.of_components (col_complex_level_iso_obj r' V Λ M N n) (by { intros c₁ c₂ h, ext i : 2, apply col_complex_level_iso_comm }) lemma col_complex_level_iso_strict (c : ℝ≥0ᵒᵖ) (i : ℕ) : isometry (((col_complex_level_iso r' V Λ M N n).hom.app c).f i) := by { cases i; exact isometry_id } def aug_map := ((ProFiltPseuNormGrpWithTinv.Pow r' n).map (Cech_augmentation_map r' Λ M N)) .to_profinitely_filtered_pseudo_normed_group_hom section open profinitely_filtered_pseudo_normed_group_with_Tinv_hom lemma aug_map_strict : (aug_map r' Λ M N n).strict := to_profinitely_filtered_pseudo_normed_group_hom_strict _ end section open category_theory.simplicial_object @[simps left right] def Cech_nerve_level_hom' (c : ℝ≥0) : augmented.to_arrow.obj ((Cech_nerve_level r' Λ M N n).obj c) ⟶ FLC_complex_arrow _ (aug_map_strict r' Λ M N n) c := @arrow.hom_mk _ _ (augmented.to_arrow.obj ((Cech_nerve_level r' Λ M N n).obj c)) (FLC_complex_arrow _ (aug_map_strict r' Λ M N n) c) (𝟙 _) (𝟙 _) begin erw [category.comp_id, category.id_comp, augmented.to_arrow_obj_hom], dsimp only [Cech_nerve_level_obj, nat_trans.comp_app, whisker_right_app, functor.const_comp_hom_app, nat_trans.left_op_app, unop_op, functor.flip_obj_map, functor.comp_map, functor.flip_map_app], erw [category.comp_id, Cech_nerve_hom_zero], refl, end @[simps left right] def Cech_nerve_level_inv' (c : ℝ≥0) : FLC_complex_arrow _ (aug_map_strict r' Λ M N n) c ⟶ augmented.to_arrow.obj ((Cech_nerve_level r' Λ M N n).obj c) := @arrow.hom_mk _ _ (FLC_complex_arrow _ (aug_map_strict r' Λ M N n) c) (augmented.to_arrow.obj ((Cech_nerve_level r' Λ M N n).obj c)) (𝟙 _) (𝟙 _) begin erw [category.comp_id, category.id_comp, augmented.to_arrow_obj_hom], dsimp only [Cech_nerve_level_obj, nat_trans.comp_app, whisker_right_app, functor.const_comp_hom_app, nat_trans.left_op_app, unop_op, functor.flip_obj_map, functor.comp_map, functor.flip_map_app], erw [category.comp_id, Cech_nerve_hom_zero], refl, end @[simps left right] def Cech_nerve_level_hom (c : ℝ≥0) : (Cech_nerve_level r' Λ M N n).obj c ⟶ (FLC_complex_arrow _ (aug_map_strict r' Λ M N n) c).augmented_cech_nerve := equivalence_left_to_right _ _ $ Cech_nerve_level_hom' _ _ _ _ _ _ . lemma Cech_nerve_level_hom_injective' (c : ℝ≥0) (i : simplex_categoryᵒᵖ) (x y: ((((Cech_nerve_level r' Λ M N n).obj c).left.obj i))) (h : ∀ (j : ulift (fin ((unop i).len + 1))), (((Cech_nerve_level r' Λ M N n).obj c).left.map ((unop i).const j.down).op) x = (((Cech_nerve_level r' Λ M N n).obj c).left.map ((unop i).const j.down).op) y) : x = y := begin ext j : 2, let π := (polyhedral_lattice.conerve.π (Λ.diagonal_embedding N) (i.unop.len + 1)).to_add_monoid_hom, have hπ : function.surjective π := polyhedral_lattice.conerve.π_surjective _ _, rw ← add_monoid_hom.cancel_right hπ, -- Bingo! apply finsupp.add_hom_ext', intro k, specialize h ⟨k⟩, rw subtype.ext_iff at h, replace h := congr_fun h j, rw add_monoid_hom.ext_iff at h ⊢, intro l, specialize h ((Cech_conerve.obj_zero_iso _).inv l), dsimp only [Cech_nerve_level_obj, Cech_nerve_level_map, whiskering_obj_obj_map, functor.flip_obj_map, functor.flip_map_app, functor.comp_map, functor.left_op_map, quiver.hom.unop_op, Cech_nerve, cosimplicial_object.augmented.whiskering_obj, cosimplicial_object.whiskering, whiskering_right_obj_obj, whiskering_right_obj_map, functor.right_op_map, unop_op, cosimplicial_object.augmented.drop_obj, cosimplicial_object.augmented.drop_map, augmented_cosimplicial, augmented_Cech_conerve, cosimplicial_object.augment_right, Cech_conerve_map, Filtration_obj_map_to_fun, ProFiltPseuNormGrpWithTinv.Pow_map, Hom_obj, Hom_map_to_fun, polyhedral_lattice.Hom, profinitely_filtered_pseudo_normed_group_with_Tinv_hom.level, profinitely_filtered_pseudo_normed_group_with_Tinv.pi_map_to_fun, profinitely_filtered_pseudo_normed_group_with_Tinv.pi_lift_to_fun, profinitely_filtered_pseudo_normed_group_with_Tinv_hom.comp_to_fun, pseudo_normed_group.level, finsupp.single_add_hom_apply, subtype.coe_mk, add_monoid_hom.coe_mk_from_pi, add_monoid_hom.comp_apply] at h ⊢, erw [Cech_conerve.map_const_obj_zero_iso] at h, exact h, end . open category_theory.limits.wide_pullback lemma Cech_nerve_level_hom_injective (c : ℝ≥0) (i : simplex_categoryᵒᵖ) : function.injective ⇑((Cech_nerve_level_hom r' Λ M N n c).left.app i) := begin let F := FLC_complex_arrow _ (aug_map_strict r' Λ M N n) c, let G := (Cech_nerve_level_hom r' Λ M N n c).left.app i, intros x y h, replace h : ∀ j, π (λ i, F.hom) j (G x) = π (λ i, F.hom) j (G y), { intros j, rw h }, have aux := λ j, (augmented_cech_nerve.left_map_comp_obj_zero_iso F i.unop j).symm, dsimp only [unop_op] at aux, simp only [← comp_apply, aux] at h, have aux' := (Cech_nerve_level_hom r' Λ M N n c).left.naturality, simp only [← category.assoc, ← aux'] at h, clear aux aux', simp only [category.assoc, Cech_nerve_level_hom, augmented_cech_nerve.left_obj_zero_iso_hom, equivalence_left_to_right_left_app_zero_comp_π, Cech_nerve_level_hom'_left, coe_comp, function.comp, id_apply] at h, apply Cech_nerve_level_hom_injective', exact h end . namespace Cech_nerve_level_hom /-! The goal is to build a section to `Cech_nerve_level_hom` -/ variables {r' Λ M N n} variables {c : ℝ≥0} {i : simplex_category.{u}ᵒᵖ} variables (y : (FLC_complex_arrow _ (aug_map_strict r' Λ M N n) c).augmented_cech_nerve.left.obj i) def z₀' := limits.wide_pullback.base (λ _, (FLC_complex_arrow _ (aug_map_strict r' Λ M N n) c).hom) y def z' := λ j, limits.wide_pullback.π (λ _, (FLC_complex_arrow _ (aug_map_strict r' Λ M N n) c).hom) j y lemma hz' : ∀ j, ((FLC_complex_arrow _ (aug_map_strict r' Λ M N n) c).hom (z' y j)) = z₀' y := begin intro j, dsimp only [z₀', z'], rw [← comp_apply, limits.wide_pullback.π_arrow], end def z₀ := (Cech_nerve_level_inv' r' Λ M N n c).right (z₀' y) def z := λ j, (Cech_nerve_level_inv' r' Λ M N n c).left (z' y j) lemma hz : ∀ j, (augmented.to_arrow.obj ((Cech_nerve_level r' Λ M N n).obj c)).hom (z y j) = z₀ y := begin intro j, dsimp only [z₀, z], have := (Cech_nerve_level_inv' r' Λ M N n c).w, simp only [functor.id_map, augmented.to_arrow_obj_hom] at this, erw [← comp_apply, this, comp_apply, hz'], refl end def s' (y : (FLC_complex_arrow _ (aug_map_strict r' Λ M N n) c).augmented_cech_nerve.left.obj i) : (ProFiltPseuNormGrpWithTinv.Pow r' n).obj ((augmented.drop.obj (Cech_nerve r' Λ M N).left_op).obj i) := begin refine λ k, cosimplicial_lift Λ N _ ((z₀ y).1 k) (λ j, add_monoid_hom.comp ((z y ⟨j⟩).1 k) (Cech_conerve.obj_zero_iso (Λ.diagonal_embedding N)).inv.to_add_monoid_hom) _, intros j l, dsimp only [add_monoid_hom.comp_apply, subtype.coe_mk, polyhedral_lattice_hom.coe_to_add_monoid_hom], rw [← hz y ⟨j⟩], dsimp only [augmented.to_arrow_obj_hom], rw [Cech_nerve_level_hom_app], dsimp only [Filtration_obj_map_to_fun, Cech_augmentation_map, profinitely_filtered_pseudo_normed_group_with_Tinv_hom.level, pseudo_normed_group.level, ProFiltPseuNormGrpWithTinv.Pow_map, profinitely_filtered_pseudo_normed_group_with_Tinv.pi_map_to_fun, cosimplicial_augmentation_map, Hom_map_to_fun, add_monoid_hom.comp_apply, subtype.coe_mk, polyhedral_lattice_hom.coe_to_add_monoid_hom, quiver.hom.unop_op, PolyhedralLattice.Cech_augmentation_map], refl, end . def s (y : (FLC_complex_arrow _ (aug_map_strict r' Λ M N n) c).augmented_cech_nerve.left.obj i) : ((Cech_nerve_level r' Λ M N n).obj c).left.obj i := begin refine ⟨s' y, _⟩, intros k, apply cosimplicial_lift_mem_filtration, intros j c' l hl, dsimp only [add_monoid_hom.comp_apply, polyhedral_lattice_hom.coe_to_add_monoid_hom], apply (z y ⟨j⟩).property, rw [semi_normed_group.mem_filtration_iff] at hl ⊢, refine le_trans _ hl, exact (Cech_conerve.obj_zero_iso (Λ.diagonal_embedding N)).inv.strict l end . lemma surjective (c : ℝ≥0) (i : simplex_categoryᵒᵖ) : function.surjective ⇑((Cech_nerve_level_hom r' Λ M N n c).left.app i) := begin let F := FLC_complex_arrow (aug_map r' Λ M N n) _ c, intro y, refine ⟨Cech_nerve_level_hom.s y, _⟩, { apply limits.concrete.wide_pullback_ext' (λ i, F.hom), rotate, { apply_instance }, { apply_instance }, intro j, erw [← augmented_cech_nerve.left_map_comp_obj_zero_iso _ _ j, ← comp_apply, ← category.assoc, ← (Cech_nerve_level_hom r' Λ M N n c).left.naturality, augmented_cech_nerve.left_map_comp_obj_zero_iso _ _ j, category.assoc], dsimp only [Cech_nerve_level_hom, augmented_cech_nerve.left_obj_zero_iso], erw [equivalence_left_to_right_left_app_zero_comp_π, Cech_nerve_level_hom'_left, category.comp_id], ext k : 2, have := Cech_nerve_level_left_map' r' Λ M N n c i _ (i.unop.const j.down).op, simp only [subtype.val_eq_coe] at this, erw this _ k, clear this, ext1 l', obtain ⟨l, rfl⟩ : ∃ l, quotient_add_group.mk l = l', { exact quotient.surjective_quotient_mk' l' }, dsimp only [z₀, z, s', s, add_monoid_hom.comp_apply, subtype.coe_mk, polyhedral_lattice_hom.coe_to_add_monoid_hom, polyhedral_lattice.conerve.map_apply, add_monoid_hom.to_fun_eq_coe, polyhedral_lattice.conerve.map_add_hom_mk, cosimplicial_lift, polyhedral_lattice.conerve.lift'], refine (quotient_add_group.lift_mk' (polyhedral_lattice.conerve.L (Λ.diagonal_embedding N) ((unop i).len + 1)) _ _).trans _, dsimp only [finsupp.lift_add_hom_apply, finsupp.map_domain.add_monoid_hom_apply, unop_op], rw [finsupp.sum_map_domain_index_add_monoid_hom, finsupp.sum_fintype, fin.sum_univ_succ, finset.sum_eq_zero, add_zero], swap, { intros m hm, exfalso, change fin 0 at m, exact nat.not_lt_zero m m.2 }, swap, { intro, rw add_monoid_hom.map_zero }, dsimp only [add_monoid_hom.comp_apply, subtype.coe_mk, polyhedral_lattice_hom.coe_to_add_monoid_hom, Cech_nerve_level_inv'_left, Cech_conerve.obj_zero_iso, iso.trans_inv, subtype.val_eq_coe, quiver.hom.unop_op], rw [id_apply, comp_apply, Cech_conerve.obj_zero_iso'_inv, Cech_conerve.finsupp_fin_one_iso_inv], suffices : finsupp.single_add_hom 0 (l 0) = l, { cases j, rw this, refl }, ext m o, change fin 1 at m, have hm : m = 0, { exact subsingleton.elim _ _ }, simp only [hm, finsupp.single_add_hom_apply, finsupp.single_apply, if_pos rfl], } end end Cech_nerve_level_hom instance Cech_nerve_level_hom_is_iso (c : ℝ≥0) : is_iso (Cech_nerve_level_hom r' Λ M N n c) := begin refine @simplicial_object.augmented.is_iso_of _ _ _ _ _ (id _) (id _), swap, { exact is_iso.id _ }, intro i, apply Profinite.is_iso_of_bijective, exact ⟨Cech_nerve_level_hom_injective r' Λ M N n c i, Cech_nerve_level_hom.surjective c i⟩, end def Cech_nerve_level_iso (c : ℝ≥0) : (Cech_nerve_level r' Λ M N n).obj c ≅ (FLC_complex_arrow _ (aug_map_strict r' Λ M N n) c).augmented_cech_nerve := as_iso (Cech_nerve_level_hom r' Λ M N n c) def FLC_complex_aug_iso_obj (c : ℝ≥0ᵒᵖ) : (FLC_complex V _ (aug_map_strict r' Λ M N n)).obj c ≅ (col_complex_level r' V Λ M N n).obj c := (FLC_functor' V).map_iso (Cech_nerve_level_iso r' Λ M N n c.unop).op def FLC_complex_aug_iso : FLC_complex V _ (aug_map_strict r' Λ M N n) ≅ col_complex_level r' V Λ M N n := nat_iso.of_components (FLC_complex_aug_iso_obj r' V Λ M N n) begin intros c₁ c₂ h, dsimp only [FLC_complex, col_complex_level, FLC_functor, FLC_complex_aug_iso_obj, functor.comp_map, functor.map_iso_hom, whiskering_right_obj_obj, Cech_nerve_level_iso, iso.op_hom, as_iso_hom, functor.op_map], simp only [← category_theory.functor.map_comp, ← op_comp, quiver.hom.unop_op], congr' 2, apply simplicial_object.hom_ext, { dsimp only [unop_op], let f := FLC_complex_arrow _ (aug_map_strict r' Λ M N n) (unop c₁), rw ← cancel_mono (augmented_cech_nerve.left_obj_zero_iso f).hom, dsimp only [comma.comp_left, nat_trans.comp_app, Cech_nerve_level_hom, augmented_cech_nerve_map_left, cech_nerve_map_app, arrow.hom_mk_right, arrow.hom_mk_left, augmented_cech_nerve.left_obj_zero_iso_hom], simp only [category.assoc, limits.wide_pullback.lift_π, simplicial_object.equivalence_left_to_right_left_app_zero_comp_π], erw [← category.assoc, simplicial_object.equivalence_left_to_right_left_app_zero_comp_π], refl, }, { dsimp only [equivalence_right_to_left_right, comma.comp_right, Cech_nerve_level_hom_right], erw [category.comp_id, category.id_comp], refl, } end end lemma FLC_complex_aug_iso_strict (c : ℝ≥0ᵒᵖ) (i : ℕ) : isometry (((FLC_complex_aug_iso r' V Λ M N n).hom.app c).f i) := begin rw [← iso.app_hom, ← homological_complex.hom.iso_app_hom], refine SemiNormedGroup.iso_isometry_of_norm_noninc _ _ _; [ rw [homological_complex.hom.iso_app_hom, iso.app_hom], rw [homological_complex.hom.iso_app_inv, iso.app_inv] ]; { apply cosimplicial_object.augmented.cocomplex_map_norm_noninc; intros; apply SemiNormedGroup.LCC_obj_map_norm_noninc, }, end def col_complex_obj_iso_X_zero (c : ℝ≥0ᵒᵖ) : ((col_complex r' V Λ M N n).obj c).X 0 ≅ ((FLC_functor V).obj (op $ FLC_complex_arrow _ (aug_map_strict r' Λ M N n) (c.unop))).X 0 := iso.refl _ section open profinitely_filtered_pseudo_normed_group def FLC_arrow_iso_aux : ((ProFiltPseuNormGrpWithTinv.Pow r' n).obj (unop ((Cech_nerve r' Λ M N).right.obj (mk 0)))) ≅ ProFiltPseuNormGrpWithTinv.of r' (rescale ↑N (((↥Λ →+ ↥M) ^ n) ^ N)) := (ProFiltPseuNormGrpWithTinv.Pow r' n).map_iso (Hom_cosimplicial_zero_iso Λ N r' M N rfl) ≪≫ (ProFiltPseuNormGrpWithTinv.Pow_rescale_Pow_iso.{u u} r' N N n).app (polyhedral_lattice.Hom ↥Λ ↥M) . section open ProFiltPseuNormGrpWithTinv lemma FLC_arrow_hom' {M₁ M₂ : ProFiltPseuNormGrpWithTinv r'} (f : M₁ ⟶ M₂) (c : ℝ≥0) : (FLC_complex_arrow f.to_profinitely_filtered_pseudo_normed_group_hom f.strict c).hom = ((Filtration r').obj c).map f := rfl --move this attribute [simps] linear_equiv.to_add_equiv lemma FLC_arrow_iso_w (c : ℝ≥0) : ((((Filtration r').obj c).map_iso (FLC_arrow_iso_aux r' Λ M N n)).hom ≫ (FLC_complex_arrow _ (sum_hom_strict ((↥Λ →+ ↥M) ^ n) N) c).hom : _) = ((FLC_complex_arrow _ (aug_map_strict r' Λ M N n) c).hom) := begin rw [← iso.eq_inv_comp], ext x i l, dsimp only [FLC_arrow_iso_aux, iso.trans_inv, functor.map_iso_inv, aug_map, Pow_rescale_Pow_iso, iso.app_inv, iso.symm_inv, nat_trans.comp_app, functor.associator_hom_app, functor.associator_inv_app, iso_whisker_left_inv, iso_whisker_right_inv, whisker_left_app, whisker_right_app, Pow_comm, Pow_rescale, FLC_arrow_hom'], erw [category.id_comp, category.id_comp, FLC_arrow_hom', ← ((Filtration r').obj c).map_comp, category.assoc, ← (Pow r' n).map_comp, Cech_augmentation_map_eq_Hom_sum], dsimp only [FLC_complex_arrow, arrow.mk_hom, Filtration_obj_map_to_fun, comp_apply, continuous_map.coe_mk, pseudo_normed_group.level, subtype.coe_mk, profinitely_filtered_pseudo_normed_group_with_Tinv_hom.to_profinitely_filtered_pseudo_normed_group_hom, profinitely_filtered_pseudo_normed_group_hom.mk_of_strict, profinitely_filtered_pseudo_normed_group_hom.mk_of_bound, profinitely_filtered_pseudo_normed_group_hom.coe_mk, add_monoid_hom.to_fun_eq_coe, profinitely_filtered_pseudo_normed_group_with_Tinv_hom.coe_to_add_monoid_hom, ProFiltPseuNormGrpWithTinv.Pow_map, nat_iso.of_components.hom_app, id, profinitely_filtered_pseudo_normed_group_with_Tinv_hom.level_coe], erw [comp_apply, comp_apply, iso_of_equiv_of_strict'_hom_apply], dsimp only [profinitely_filtered_pseudo_normed_group_with_Tinv.pi_map_to_fun, ProFiltPseuNormGrpWithTinv.Pow_mul_inv, Pow_comm, Pow_mul_comm, Pow_mul_comm_obj_hom_to_fun, Pow_mul_comm_obj_inv_to_fun, nat_iso.of_components.inv_app, Pow_rescale_aux_apply], simp only [comp_apply, rescale.of, equiv.refl_apply, equiv.refl_symm, nat_iso.of_components.inv_app, id, iso_of_equiv_of_strict'_inv_apply, rescale_map_to_fun, ProFiltPseuNormGrpWithTinv.Pow_mul_hom, equiv.symm_apply_apply, ProFiltPseuNormGrpWithTinv.Pow_Pow_X_hom_to_fun, ProFiltPseuNormGrpWithTinv.Pow_Pow_X_inv_to_fun, Pow_Pow_X_equiv_apply, Pow_Pow_X_equiv_symm_apply, Pow_mul_comm_obj_hom_to_fun, Pow_mul_comm_obj_inv_to_fun], rw [sum_hom_apply, Hom_sum_apply, finset.sum_apply], congr' 1, refine fintype.sum_congr _ _ _, intro j, simp only [Pow_Pow_X_equiv_apply, Pow_Pow_X_equiv_symm_apply, Pow_mul_comm_obj_hom_to_fun, Pow_mul_comm_obj_inv_to_fun, equiv.symm_trans_apply, equiv.symm_symm, equiv.curry_apply, equiv.curry_symm_apply, function.curry, function.uncurry, equiv.arrow_congr_symm, equiv.arrow_congr_apply, function.comp, equiv.refl_apply, equiv.refl_symm, equiv.trans_apply, linear_equiv.to_add_equiv_symm_apply, equiv.prod_comm_apply, linear_equiv.inv_fun_eq_symm, equiv.inv_fun_as_coe, linear_equiv.trans_apply, linear_equiv.symm_apply_apply, linear_equiv.symm_trans_apply, linear_map.fun_congr_left_symm, linear_map.fun_congr_left_apply, linear_map.fun_left_apply, equiv.symm_apply_apply, equiv.apply_symm_apply, equiv.prod_comm_symm], refl end end def FLC_arrow_iso (c : ℝ≥0) : FLC_complex_arrow _ (aug_map_strict r' Λ M N n) c ≅ FLC_complex_arrow _ (sum_hom_strict ((↥Λ →+ ↥M) ^ n) N) c := arrow.iso_mk (((Filtration r').obj c).map_iso (FLC_arrow_iso_aux r' Λ M N n)) (iso.refl _) begin erw [functor.map_iso_hom, iso.refl_hom, category.comp_id], exact (FLC_arrow_iso_w r' Λ M N n c : _), end -- lemma FLC_arrow_iso_left_eq (c₁ c₂ : ℝ≥0) {_ : fact (c₁ ≤ c₂)} -- (x : ((FLC_complex_arrow _ (aug_map_strict r' Λ M N n) c₁).left.to_Top)) : -- pseudo_normed_group.cast_le (((FLC_arrow_iso r' Λ M N n c₁).hom.left) x) = -- ((FLC_arrow_iso r' Λ M N n c₂).hom.left) (pseudo_normed_group.cast_le x) := -- by admit -- lemma FLC_arrow_iso_right_eq (c₁ c₂ : ℝ≥0) {_ : fact (c₁ ≤ c₂)} -- (x : ((FLC_complex_arrow _ (aug_map_strict r' Λ M N n) c₁).right.to_Top)) : -- pseudo_normed_group.cast_le (((FLC_arrow_iso r' Λ M N n c₁).hom.right) x) = -- ((FLC_arrow_iso r' Λ M N n c₂).hom.right) (pseudo_normed_group.cast_le x) := -- by admit def col_complex_iso_obj (c : ℝ≥0ᵒᵖ) : (FLC_complex V _ (sum_hom_strict ((↥Λ →+ ↥M) ^ n) N)).obj c ≅ (FLC_complex V _ (aug_map_strict r' Λ M N n)).obj c := begin refine (cosimplicial_object.augmented.cocomplex.map_iso _), refine functor.map_iso _ _, refine functor.map_iso _ _, refine functor.map_iso _ _, refine iso.op _, exact FLC_arrow_iso r' Λ M N n c.unop end def col_complex_iso_aux2 : FLC_complex V _ (sum_hom_strict ((↥Λ →+ ↥M) ^ n) N) ≅ FLC_complex V _ (aug_map_strict r' Λ M N n) := nat_iso.of_components (col_complex_iso_obj r' V Λ M N n) begin intros c₁ c₂ h, dsimp only [FLC_complex, FLC_functor, FLC_functor', col_complex_iso_obj, functor.comp_map, functor.map_iso_hom, iso.op_hom], simp only [← category_theory.functor.map_comp, ← op_comp], refl end section open cosimplicial_object lemma col_complex_iso_aux2_strict (c : ℝ≥0ᵒᵖ) (i : ℕ) : isometry (((col_complex_iso_aux2 r' V Λ M N n).hom.app c).f i) := begin rw [← iso.app_hom, ← homological_complex.hom.iso_app_hom], refine SemiNormedGroup.iso_isometry_of_norm_noninc _ _ _; [ rw [homological_complex.hom.iso_app_hom, iso.app_hom], rw [homological_complex.hom.iso_app_inv, iso.app_inv] ]; { dsimp only [col_complex_iso_aux2, col_complex_iso_obj, nat_iso.of_components, functor.comp_map, functor.map_iso_hom, iso.op_hom, quiver.hom.unop_op, functor.op_map, cosimplicial_object.augmented.whiskering_obj_2, cosimplicial_object.augmented.whiskering_obj], apply augmented.cocomplex_map_norm_noninc; { intros, apply SemiNormedGroup.LCC_obj_map_norm_noninc, }, }, end end def col_complex_iso : FLC_complex V _ (sum_hom_strict ((↥Λ →+ ↥M)^n) N) ≅ col_complex r' V Λ M N n := col_complex_iso_aux2 r' V Λ M N n ≪≫ FLC_complex_aug_iso r' V Λ M N n ≪≫ col_complex_level_iso r' V Λ M N n lemma col_complex_iso_strict (c : ℝ≥0ᵒᵖ) (i : ℕ) : isometry (((col_complex_iso r' V Λ M N n).hom.app c).f i) := begin refine isometry.comp _ (col_complex_iso_aux2_strict r' V Λ M N n c i), exact (col_complex_level_iso_strict r' V Λ M N n c i).comp (FLC_complex_aug_iso_strict r' V Λ M N n c i), end end lemma col_complex.is_weak_bounded_exact (d : ℝ≥0) [pseudo_normed_group.splittable ((Λ →+ M)^n) N d] (k : ℝ≥0) [fact (1 ≤ k)] (m : ℕ) (c₀ : ℝ≥0) (hdkc₀N : d ≤ (k - 1) * c₀ / N) : (col_complex r' V Λ M N n).is_weak_bounded_exact k 1 m c₀ := begin have key := FLC_complex.weak_bounded_exact V ((Λ →+ M)^n) N d k m c₀ hdkc₀N, exact key.of_iso _ (λ c, col_complex_iso_strict r' V Λ M N n (op c)), end @[simps obj map] def col_complex_rescaled : system_of_complexes := scale_factorial.obj (col_complex r' V Λ M N n) . lemma col_complex_rescaled.is_weak_bounded_exact (d : ℝ≥0) [pseudo_normed_group.splittable ((Λ →+ M)^n) N d] (k : ℝ≥0) [fact (1 ≤ k)] (m : ℕ) (c₀ : ℝ≥0) (hdkc₀N : d ≤ (k - 1) * c₀ / N) : (col_complex_rescaled r' V Λ M N n).is_weak_bounded_exact k (m+1) m c₀ := begin have := scale_factorial.is_weak_bounded_exact (col_complex.is_weak_bounded_exact r' V Λ M N n d k m c₀ hdkc₀N), rwa [one_mul] at this, end end namespace col_complex_rescaled open polyhedral_lattice (Hom) open PolyhedralLattice (cosimplicial) instance move_pls (r' : ℝ≥0) (c : ℝ≥0ᵒᵖ) : fact (unop (r'.MulLeft.op.obj c) ≤ r' * unop c) := ⟨le_rfl⟩ instance move_pls2 (c : ℝ≥0ᵒᵖ) : fact (unop (r'.MulLeft.op.obj c) ≤ unop c) := by { dsimp [nnreal.MulLeft], apply_instance } def T_inv_sub_Tinv_f_succ [normed_with_aut r V] (c : ℝ≥0ᵒᵖ) (i : ℕ) : ((col_complex_rescaled.{u} r' V Λ M N n).obj c).X (i + 1) ⟶ (((col_complex_rescaled.{u} r' V Λ M N n).scale_index_left r').obj c).X (i + 1) := (SemiNormedGroup.rescale (i+1)!).map $ (CLCFP.T_inv_sub_Tinv r r' V _ _ n).app _ def T_inv_sub_Tinv_f [normed_with_aut r V] (c : ℝ≥0ᵒᵖ) : Π i, ((col_complex_rescaled.{u} r' V Λ M N n).obj c).X i ⟶ (((col_complex_rescaled.{u} r' V Λ M N n).scale_index_left r').obj c).X i | 0 := (SemiNormedGroup.rescale 0!).map $ (CLCFP.T_inv_sub_Tinv r r' V _ _ n).app _ | (i+1) := T_inv_sub_Tinv_f_succ r r' V Λ M N n c i section open system_of_complexes category_theory.preadditive category_theory.cosimplicial_object homological_complex lemma T_inv_sub_Tinv_comm_zero [normed_with_aut r V] (c : ℝ≥0ᵒᵖ) : T_inv_sub_Tinv_f r r' V Λ M N n c 0 ≫ (((col_complex_rescaled r' V Λ M N n).scale_index_left r').obj c).d 0 1 = ((col_complex_rescaled r' V Λ M N n).obj c).d 0 1 ≫ T_inv_sub_Tinv_f r r' V Λ M N n c 1 := begin dsimp only [T_inv_sub_Tinv_f, T_inv_sub_Tinv_f_succ, scale_index_left, col_complex_rescaled], refine SemiNormedGroup.scale_comm _ _ _ _ _ _ _, dsimp, rw [if_pos rfl, category.comp_id], dsimp only [augmented.to_cocomplex_d], erw [Cech_nerve'_hom_zero], dsimp only [CLCFP'_map_app], erw nat_trans.naturality, refl end . lemma T_inv_sub_Tinv_comm_succ [normed_with_aut r V] (c : ℝ≥0ᵒᵖ) (i : ℕ) : T_inv_sub_Tinv_f r r' V Λ M N n c (i+1) ≫ (((col_complex_rescaled r' V Λ M N n).scale_index_left r').obj c).d (i+1) (i+2) = ((col_complex_rescaled r' V Λ M N n).obj c).d (i+1) (i+2) ≫ T_inv_sub_Tinv_f r r' V Λ M N n c (i+2) := begin dsimp only [T_inv_sub_Tinv_f, T_inv_sub_Tinv_f_succ, scale_index_left, col_complex_rescaled], refine SemiNormedGroup.scale_comm _ _ _ _ _ _ _, dsimp, rw [if_pos rfl, category.comp_id], dsimp only [augmented.to_cocomplex_d, coboundary, augmented.drop_obj, Cech_nerve', augmented.whiskering_obj_2, augmented.whiskering_obj, cosimplicial_object.δ, whiskering_obj_obj_map], simp only [nat_trans.app_sum, nat_trans.app_gsmul, sum_comp, comp_sum, gsmul_comp, comp_gsmul], apply fintype.sum_congr, intro j, congr' 1, dsimp only [CLCFP'_map_app], erw nat_trans.naturality, refl, end . lemma T_inv_sub_Tinv_naturality_zero [normed_with_aut r V] (c₁ c₂ : ℝ≥0ᵒᵖ) (h : c₁ ⟶ c₂) : ((col_complex_rescaled r' V Λ M N n).map h).f 0 ≫ T_inv_sub_Tinv_f r r' V Λ M N n c₂ 0 = T_inv_sub_Tinv_f r r' V Λ M N n c₁ 0 ≫ (((col_complex_rescaled r' V Λ M N n).scale_index_left r').map h).f 0 := begin dsimp only [T_inv_sub_Tinv_f, scale_index_left, ScaleIndexLeft_obj_map, col_complex_rescaled, scale_factorial_obj, functor.comp_map, modify_functor_map_f, col_complex_map, augmented.to_cocomplex_obj, augmented.point_obj, Cech_nerve', augmented.whiskering_obj], simp only [← category_theory.functor.map_comp], congr' 1, dsimp only [CLCFP'_obj_map, CLCFP.T_inv_sub_Tinv, nnreal.MulLeft, functor.op_obj, unop_op], simp only [nat_trans.app_sub, comp_sub, sub_comp, ← nat_trans.comp_app], congr' 2, { rw [category.assoc, ← CLCFP.res_comp_T_inv], haveI : fact (c₂.unop ≤ c₁.unop) := ⟨le_of_hom h.unop⟩, simp only [← category.assoc, CLCFP.res_comp_res], }, { dsimp only [CLCFP.Tinv, CLCFP.res, CLC, LC], simp only [← whisker_right_comp, ← nat_trans.op_comp], refl, } end . lemma T_inv_sub_Tinv_naturality_succ [normed_with_aut r V] (c₁ c₂ : ℝ≥0ᵒᵖ) (h : c₁ ⟶ c₂) (i : ℕ) : ((col_complex_rescaled r' V Λ M N n).map h).f (i+1) ≫ T_inv_sub_Tinv_f r r' V Λ M N n c₂ (i+1) = T_inv_sub_Tinv_f r r' V Λ M N n c₁ (i+1) ≫ (((col_complex_rescaled r' V Λ M N n).scale_index_left r').map h).f (i+1) := begin dsimp only [T_inv_sub_Tinv_f, T_inv_sub_Tinv_f_succ, scale_index_left, ScaleIndexLeft_obj_map, col_complex_rescaled, scale_factorial_obj, functor.comp_map, modify_functor_map_f, col_complex_map, augmented.to_cocomplex_obj, augmented.drop_obj, Cech_nerve', augmented.whiskering_obj, whiskering_obj_obj_obj], simp only [← category_theory.functor.map_comp], congr' 1, dsimp only [CLCFP'_obj_map, CLCFP.T_inv_sub_Tinv, nnreal.MulLeft, functor.op_obj, unop_op], simp only [nat_trans.app_sub, comp_sub, sub_comp], erw [← nat_trans.comp_app, ← nat_trans.comp_app, ← nat_trans.comp_app, ← nat_trans.comp_app], congr' 2, { rw [category.assoc, ← CLCFP.res_comp_T_inv], haveI : fact (c₂.unop ≤ c₁.unop) := ⟨le_of_hom h.unop⟩, simp only [← category.assoc, CLCFP.res_comp_res], }, { dsimp only [CLCFP.Tinv, CLCFP.res, CLC, LC], simp only [← whisker_right_comp, ← nat_trans.op_comp], refl, } end end def T_inv_sub_Tinv [normed_with_aut r V] : col_complex_rescaled r' V Λ M N n ⟶ (col_complex_rescaled r' V Λ M N n).scale_index_left r' := { app := λ c, { f := T_inv_sub_Tinv_f r r' V Λ M N n c, comm' := begin rintros i j (rfl : i + 1 = j), cases i, { apply T_inv_sub_Tinv_comm_zero }, { apply T_inv_sub_Tinv_comm_succ } end }, naturality' := begin intros c₁ c₂ h, ext i : 2, cases i, { apply T_inv_sub_Tinv_naturality_zero }, { apply T_inv_sub_Tinv_naturality_succ }, end } def T_inv_sub_Tinv' (c : ℝ≥0) [normed_with_aut r V] := (system_of_complexes.ScaleIndexRight c).map (col_complex_rescaled.T_inv_sub_Tinv r r' V Λ M N n) end col_complex_rescaled namespace double_complex open polyhedral_lattice (Hom) local attribute [semireducible] CLCFPTinv CLCFPTinv₂ CLCFP -- CLCTinv @[simps obj map] def col'_aux [normed_with_aut r V] (n : ℕ) : system_of_complexes := (double_complex' BD κ r r' V Λ M N).col n @[simps obj map] def col' [normed_with_aut r V] (n : ℕ) : system_of_complexes := scale_factorial.obj (col'_aux BD κ r r' V Λ M N n) . def col_iso_obj_X [normed_with_aut r V] (c : ℝ≥0ᵒᵖ) : Π m, (((double_complex.{u} BD κ r r' V Λ M N).col n).obj c).X m ≅ ((col'.{u} BD κ r r' V Λ M N n).obj c).X m | 0 := (SemiNormedGroup.iso_rescale _).app _ | 1 := (SemiNormedGroup.iso_rescale _).app _ | (m+2) := iso.refl _ section open homological_complex system_of_complexes lemma col_iso_comm₁_0 [normed_with_aut r V] (c : ℝ≥0ᵒᵖ) : (col_iso_obj_X BD κ r r' V Λ M N n c 0).hom ≫ ((col' BD κ r r' V Λ M N n).obj c).d 0 1 = (((double_complex BD κ r r' V Λ M N).col n).obj c).d 0 1 ≫ (col_iso_obj_X BD κ r r' V Λ M N n c 1).hom := by { dsimp only [col_iso_obj_X], ext, refl } . lemma col_iso_comm₁_1 [normed_with_aut r V] (c : ℝ≥0ᵒᵖ) : (col_iso_obj_X BD κ r r' V Λ M N n c 1).hom ≫ ((col' BD κ r r' V Λ M N n).obj c).d 1 2 = (((double_complex BD κ r r' V Λ M N).col n).obj c).d 1 2 ≫ (col_iso_obj_X BD κ r r' V Λ M N n c 2).hom := begin delta col_iso_obj_X, simp only [iso.refl_hom, nat.rec_add_one, category.id_comp, category.comp_id, system_of_double_complexes.col_obj_d], dsimp only [col'_obj, col'_aux_obj, double_complex', double_complex, double_complex_aux_rescaled, as_functor_obj, modify_d, eval_obj, eval_map, functor.map_homological_complex_obj_d, functor.map_homological_complex_obj_X, nat_trans.comp_app, comp_f, rescale_functor, rescale_nat_trans, system_of_complexes.rescale, scale], refl end . lemma col_iso_comm₂_0 [normed_with_aut r V] (c₁ c₂ : ℝ≥0ᵒᵖ) (h : c₁ ⟶ c₂) : (((double_complex.{u} BD κ r r' V Λ M N).col n).map h).f 0 ≫ (col_iso_obj_X BD κ r r' V Λ M N n c₂ 0).hom = (col_iso_obj_X BD κ r r' V Λ M N n c₁ 0).hom ≫ ((col'.{u} BD κ r r' V Λ M N n).map h).f 0 := by { dsimp only [col_iso_obj_X], ext, refl } . lemma col_iso_comm₂_1 [normed_with_aut r V] (c₁ c₂ : ℝ≥0ᵒᵖ) (h : c₁ ⟶ c₂) : (((double_complex.{u} BD κ r r' V Λ M N).col n).map h).f 1 ≫ (col_iso_obj_X BD κ r r' V Λ M N n c₂ 1).hom = (col_iso_obj_X BD κ r r' V Λ M N n c₁ 1).hom ≫ ((col'.{u} BD κ r r' V Λ M N n).map h).f 1 := by { dsimp only [col_iso_obj_X], ext, refl } . local attribute [irreducible] CLCFPTinv CLCFPTinv₂ CLCFP SemiNormedGroup.rescale SemiNormedGroup.scale double_complex_aux lemma col_iso_comm₁_succ [normed_with_aut r V] (c : ℝ≥0ᵒᵖ) (i : ℕ) : (col_iso_obj_X BD κ r r' V Λ M N n c i.succ.succ).hom ≫ ((col'.{u} BD κ r r' V Λ M N n).obj c).d i.succ.succ (i.succ.succ + 1) = (((double_complex.{u} BD κ r r' V Λ M N).col n).obj c).d i.succ.succ (i.succ.succ + 1) ≫ (col_iso_obj_X BD κ r r' V Λ M N n c (i.succ.succ + 1)).hom := begin dsimp only [col_iso_obj_X, iso.refl_hom], simp only [category.id_comp, category.comp_id, system_of_double_complexes.col_obj_d], refl, end . lemma col_iso_comm₂_succ [normed_with_aut r V] (c₁ c₂ : ℝ≥0ᵒᵖ) (h : c₁ ⟶ c₂) (i : ℕ) : (((double_complex.{u} BD κ r r' V Λ M N).col n).map h).f (i+2) ≫ (col_iso_obj_X BD κ r r' V Λ M N n c₂ (i+2)).hom = (col_iso_obj_X BD κ r r' V Λ M N n c₁ (i+2)).hom ≫ ((col'.{u} BD κ r r' V Λ M N n).map h).f (i+2) := begin dsimp only [col_iso_obj_X, iso.refl_hom], simp only [category.id_comp, category.comp_id, system_of_double_complexes.col_obj_d], refl end lemma col_iso_comm₂ [normed_with_aut r V] (c₁ c₂ : ℝ≥0ᵒᵖ) (h : c₁ ⟶ c₂) : ∀ i, (((double_complex.{u} BD κ r r' V Λ M N).col n).map h).f i ≫ (col_iso_obj_X BD κ r r' V Λ M N n c₂ i).hom = (col_iso_obj_X BD κ r r' V Λ M N n c₁ i).hom ≫ ((col'.{u} BD κ r r' V Λ M N n).map h).f i | 0 := col_iso_comm₂_0 _ _ _ _ _ _ _ _ _ _ _ _ | 1 := col_iso_comm₂_1 _ _ _ _ _ _ _ _ _ _ _ _ | (i+2) := col_iso_comm₂_succ _ _ _ _ _ _ _ _ _ _ _ _ _ . end section open homological_complex -- set_option pp.universes true @[simps] def col_iso [normed_with_aut r V] : (double_complex.{u} BD κ r r' V Λ M N).col n ≅ col'.{u} BD κ r r' V Λ M N n := nat_iso.of_components (λ c, hom.iso_of_components (col_iso_obj_X.{u} BD κ r r' V Λ M N n _) begin rintro i j (rfl : i + 1 = j), cases i, { exact col_iso_comm₁_0 BD κ r r' V Λ M N n c, }, cases i, { exact col_iso_comm₁_1 BD κ r r' V Λ M N n c, }, { exact col_iso_comm₁_succ BD κ r r' V Λ M N n c i, }, end) begin intros c₁ c₂ h, ext i : 2, dsimp only [comp_f, hom.iso_of_components_hom_f], exact col_iso_comm₂ BD κ r r' V Λ M N n c₁ c₂ h i, end . lemma col_iso_strict [normed_with_aut r V] (c : ℝ≥0ᵒᵖ) (i : ℕ) : isometry (hom.iso_app ((col_iso BD κ r r' V Λ M N n).app c) i).hom := begin dsimp only [hom.iso_app_hom, nat_iso.app_hom, col_iso_hom_app_f], cases i, { delta col_iso_obj_X, apply SemiNormedGroup.iso_rescale_isometry, exact nat.cast_one }, cases i, { delta col_iso_obj_X, apply SemiNormedGroup.iso_rescale_isometry, exact nat.cast_one }, { delta col_iso_obj_X, exact isometry_id } end lemma col_iso_inv_strict [normed_with_aut r V] (c : ℝ≥0ᵒᵖ) (i : ℕ) : isometry (hom.iso_app ((col_iso BD κ r r' V Λ M N n).app c) i).inv := (col_iso_strict BD κ r r' V Λ M N n c i).right_inv $ λ x, by rw [← comp_apply, iso.inv_hom_id, id_apply] end lemma col_obj_X_zero [normed_with_aut r V] (c : ℝ≥0ᵒᵖ) : (((double_complex BD κ r r' V Λ M N).col n).obj c).X 0 = (CLCFPTinv r V r' (c.unop * κ n) (BD.X n)).obj (op $ Hom Λ M) := rfl -- local attribute [semireducible] opposite def col_ι_f_succ [normed_with_aut r V] (c : ℝ≥0ᵒᵖ) (i : ℕ) : ((col'.{u} BD κ r r' V Λ M N n).obj c).X (i+1) ⟶ (((col_complex_rescaled.{u} r' V Λ M N (BD.X n)).scale_index_right (κ n)).obj c).X (i+1) := (SemiNormedGroup.rescale (i+1)!).map (CLCTinv.ι r V _ _) def col_ι_f [normed_with_aut r V] (c : ℝ≥0ᵒᵖ) : Π i, ((col'.{u} BD κ r r' V Λ M N n).obj c).X i ⟶ (((col_complex_rescaled.{u} r' V Λ M N (BD.X n)).scale_index_right (κ n)).obj c).X i | 0 := (SemiNormedGroup.rescale 0!).map (CLCTinv.ι r V _ _) | (i+1) := col_ι_f_succ _ _ _ _ _ _ _ _ _ _ i section open homological_complex system_of_complexes breen_deligne lemma col_ι_f_comm_zero [normed_with_aut r V] (c : ℝ≥0ᵒᵖ) : col_ι_f BD κ r r' V Λ M N n c 0 ≫ (((col_complex_rescaled r' V Λ M N (BD.X n)).scale_index_right (κ n)).obj c).d 0 1 = ((col' BD κ r r' V Λ M N n).obj c).d 0 1 ≫ col_ι_f BD κ r r' V Λ M N n c 1 := begin dsimp only [col_ι_f, col_ι_f_succ, col'_obj, functor.map_homological_complex_obj_d, modify_d, eval_map, scale_index_right, ScaleIndexRight_obj_obj, col_complex_rescaled_obj, scale'_app], refine SemiNormedGroup.scale_comm _ _ _ _ _ _ _, rw [dif_pos rfl, dif_pos rfl], simp only [cosimplicial_object.augmented.to_cocomplex_d, eq_to_hom_refl, category.comp_id], erw [Cech_nerve'_hom_zero, cosimplicial_system_of_complexes_hom_zero], dsimp only [data.system_map, data.complex, data.complex₂_map_f, CLCFPTinv₂, CLCTinv.F_map], symmetry, apply CLCTinv.map_comp_ι, end section open category_theory.preadditive lemma col_ι_f_comm_succ [normed_with_aut r V] (c : ℝ≥0ᵒᵖ) (i : ℕ) : col_ι_f BD κ r r' V Λ M N n c (i + 1) ≫ (((col_complex_rescaled r' V Λ M N (BD.X n)).scale_index_right (κ n)).obj c).d (i+1) (i+2) = ((col' BD κ r r' V Λ M N n).obj c).d (i + 1) (i + 2) ≫ col_ι_f BD κ r r' V Λ M N n c (i+2) := begin dsimp only [col_ι_f, col_ι_f_succ, col'_obj, functor.map_homological_complex_obj_d, modify_d, eval_map, scale_index_right, ScaleIndexRight_obj_obj, col_complex_rescaled_obj, scale'_app], refine SemiNormedGroup.scale_comm _ _ _ _ _ _ _, rw [dif_pos rfl, dif_pos rfl], simp only [cosimplicial_object.augmented.to_cocomplex_d, eq_to_hom_refl, category.comp_id, cosimplicial_object.coboundary, nat_trans.app_sum, nat_trans.app_gsmul, ← homological_complex.hom.f_add_monoid_hom_apply, add_monoid_hom.map_sum, add_monoid_hom.map_gsmul, sum_comp, comp_sum, gsmul_comp, comp_gsmul], symmetry, apply fintype.sum_congr, intro j, refl, end end lemma col_ι_f_comm [normed_with_aut r V] (c : ℝ≥0ᵒᵖ) : ∀ i, col_ι_f BD κ r r' V Λ M N n c i ≫ (((col_complex_rescaled r' V Λ M N (BD.X n)).scale_index_right (κ n)).obj c).d i (i + 1) = ((col' BD κ r r' V Λ M N n).obj c).d i (i + 1) ≫ col_ι_f BD κ r r' V Λ M N n c (i + 1) | 0 := by apply col_ι_f_comm_zero | (i+1) := by apply col_ι_f_comm_succ section open category_theory.cosimplicial_object lemma col_ι_naturality_zero [normed_with_aut r V] (c₁ c₂ : ℝ≥0ᵒᵖ) (h : c₁ ⟶ c₂) : ((col' BD κ r r' V Λ M N n).map h).f 0 ≫ col_ι_f BD κ r r' V Λ M N n c₂ 0 = col_ι_f BD κ r r' V Λ M N n c₁ 0 ≫ (((col_complex_rescaled r' V Λ M N (BD.X n)).scale_index_right (κ n)).map h).f 0 := begin dsimp only [col'_map, functor.map_homological_complex_map_f, eval_map, modify_functor_map_f, col_ι_f, scale_index_right, ScaleIndexRight_obj_map, col_complex_rescaled_map], simp only [← category_theory.functor.map_comp], congr' 1, dsimp only [augmented.to_cocomplex_obj, augmented.point_obj, cosimplicial_system_of_complexes, Cech_nerve', augmented.whiskering_obj, CLCFP', data.system_obj, data.complex, data.complex₂_obj_X, CLCFPTinv₂.res, CLCTinv.map_nat, functor.comp_obj, functor.comp_map, functor.op_obj, functor.op_map, whiskering_right_obj_obj, functor.op_hom_obj, unop_op, functor.flip_obj_map], apply CLCTinv.map_comp_ι, end . lemma col_ι_naturality_succ [normed_with_aut r V] (c₁ c₂ : ℝ≥0ᵒᵖ) (h : c₁ ⟶ c₂) (i : ℕ) : ((col' BD κ r r' V Λ M N n).map h).f (i+1) ≫ col_ι_f BD κ r r' V Λ M N n c₂ (i+1) = col_ι_f BD κ r r' V Λ M N n c₁ (i+1) ≫ (((col_complex_rescaled r' V Λ M N (BD.X n)).scale_index_right (κ n)).map h).f (i+1) := begin dsimp only [col'_map, functor.map_homological_complex_map_f, eval_map, modify_functor_map_f, col_ι_f, col_ι_f_succ, scale_index_right, ScaleIndexRight_obj_map, col_complex_rescaled_map], simp only [← category_theory.functor.map_comp], congr' 1, dsimp only [augmented.to_cocomplex_obj, augmented.drop_obj, cosimplicial_system_of_complexes, Cech_nerve', augmented.whiskering_obj, CLCFP', whiskering_obj_obj_obj, data.system_obj, data.complex, data.complex₂_obj_X, CLCFPTinv₂.res, CLCTinv.map_nat, functor.comp_obj, functor.comp_map, functor.op_obj, functor.op_map, whiskering_right_obj_obj, functor.op_hom_obj, unop_op, functor.flip_obj_map], apply CLCTinv.map_comp_ι, end . end end def col_ι [normed_with_aut r V] : col'.{u} BD κ r r' V Λ M N n ⟶ (col_complex_rescaled.{u} r' V Λ M N (BD.X n)).scale_index_right (κ n) := { app := λ c, { f := col_ι_f BD κ r r' V Λ M N n c, comm' := by { rintro i j (rfl : i + 1 = j), apply col_ι_f_comm } }, naturality' := begin intros c₁ c₂ h, ext i : 2, cases i, { apply col_ι_naturality_zero }, { apply col_ι_naturality_succ }, end } variables [normed_with_aut r V] (c : ℝ≥0ᵒᵖ) (i : ℕ) lemma col_ι_range : (((double_complex.col_ι BD κ r r' V Λ M N n).app c).f i).range = (((col_complex_rescaled.T_inv_sub_Tinv' r r' V Λ M N (BD.X n) (κ n)).app c).f i).ker := begin cases i; { refine SemiNormedGroup.rescale_exact _ _ _ _, rw CLCTinv.ι_range', ext1 x, refl, }, end lemma col_ι_isometry : isometry (((double_complex.col_ι BD κ r r' V Λ M N n).app c).f i) := begin cases i; { refine SemiNormedGroup.rescale_map_isometry _ _, apply normed_group_hom.isometry_of_norm, intro, refl }, end end double_complex namespace col_complex_rescaled lemma d_zero_norm_noninc (c : ℝ≥0) : (@system_of_complexes.d (col_complex_rescaled r' V Λ M N n) c 0 1).norm_noninc := begin apply normed_group_hom.norm_noninc.norm_noninc_iff_norm_le_one.2, refine normed_group_hom.norm_comp_le_of_le' (1:ℕ) _ 1 _ (SemiNormedGroup.norm_scale_le _ _ _) _, { simp only [mul_one, nat.factorial_zero, nat.factorial_one, nat.cast_one, div_one, nnreal.coe_one]}, apply SemiNormedGroup.norm_rescale_map_le, have : (1 : ℝ) = ∑ i : fin 1, 1, { simp only [finset.card_fin, mul_one, finset.sum_const, nsmul_eq_mul, nat.cast_id, nat.cast_bit1, nat.cast_add, nat.cast_one] }, dsimp [system_of_complexes.rescale_functor, double_complex_aux, cosimplicial_object.augmented.to_cocomplex_d], erw [category.comp_id, if_pos rfl, Cech_nerve'_hom_zero, zero_add], apply normed_group_hom.norm_noninc.norm_noninc_iff_norm_le_one.1, apply CLC.map_norm_noninc, end lemma d_succ_norm_noninc (c : ℝ≥0) (p : ℕ) : (@system_of_complexes.d (col_complex_rescaled r' V Λ M N n) c (p+1) (p+2)).norm_noninc := begin apply normed_group_hom.norm_noninc.norm_noninc_iff_norm_le_one.2, refine normed_group_hom.norm_comp_le_of_le' (p+2:ℕ) _ 1 _ (SemiNormedGroup.norm_scale_le _ _ _) _, { norm_cast, rw [mul_comm, ← mul_div_assoc, eq_comm, ← nat.cast_mul, nat.factorial_succ], apply div_self, norm_num [nat.factorial_ne_zero] }, apply SemiNormedGroup.norm_rescale_map_le, have : (p+1+1 : ℝ) = ∑ i : fin (p+1+1), 1, { simp only [finset.card_fin, mul_one, finset.sum_const, nsmul_eq_mul, nat.cast_id, nat.cast_bit1, nat.cast_add, nat.cast_one] }, dsimp [system_of_complexes.rescale_functor, double_complex_aux, cosimplicial_object.augmented.to_cocomplex_d], erw [category.comp_id, if_pos rfl], dsimp [cosimplicial_object.coboundary], simp only [← nat_trans.app_hom_apply, add_monoid_hom.map_sum, add_monoid_hom.map_gsmul, ← homological_complex.hom.f_add_monoid_hom_apply, this], apply norm_sum_le_of_le, rintro i -, refine le_trans (norm_gsmul_le _ _) _, rw [← int.norm_cast_real, int.cast_pow, normed_field.norm_pow, int.cast_neg, int.cast_one, norm_neg, norm_one, one_pow, one_mul], apply normed_group_hom.norm_noninc.norm_noninc_iff_norm_le_one.1, apply CLC.map_norm_noninc end lemma admissible : (col_complex_rescaled r' V Λ M N n).admissible := { d_norm_noninc' := begin rintro c i j rfl, cases i, { apply d_zero_norm_noninc, }, { apply d_succ_norm_noninc, } end, res_norm_noninc := begin intros c₁ c₂ i h, apply normed_group_hom.norm_noninc.norm_noninc_iff_norm_le_one.2, cases i; { apply SemiNormedGroup.norm_rescale_map_le, apply normed_group_hom.norm_noninc.norm_noninc_iff_norm_le_one.1, apply CLC.map_norm_noninc, }, end } end col_complex_rescaled lemma col_exact'_aux1 [normed_with_aut r V] (c : ℝ≥0ᵒᵖ) (i : ℕ) : ∀ x, ∥(((col_complex_rescaled.T_inv_sub_Tinv' r r' V Λ M N (BD.X n) (κ n)).app c).f i) x∥ ≤ (1 + r⁻¹) * ∥x∥ := begin intro x, cases i; { apply normed_group_hom.le_of_op_norm_le, refine @SemiNormedGroup.norm_rescale_map_le _ _ _ _ _ (1 + r⁻¹) _, exact CLCFP.norm_T_inv_sub_Tinv_le _ _ _ _ _ _ _ } end lemma col_exact'_aux2 [normed_with_aut r V] (c : ℝ≥0ᵒᵖ) (i : ℕ) : ∀ y, ∃ x, (((col_complex_rescaled.T_inv_sub_Tinv' r r' V Λ M N (BD.X n) (κ n)).app c).f i) x = y ∧ ∥x∥ ≤ ↑(r / (1 - r) + 1) * ∥y∥ := begin haveI : fact (r < 1) := ⟨@lt_trans _ _ r r' 1 (fact.out _) (fact.out _)⟩, cases i; { refine SemiNormedGroup.rescale_exists_norm_le _ _ _ _, intro y, obtain ⟨x, h1, h2⟩ := CLCFP.T_inv_sub_Tinv_exists_preimage r r' y 1 zero_lt_one, refine ⟨x, h1, _⟩, rwa [nnreal.coe_add, nnreal.coe_div, nnreal.coe_sub], exact fact.out _ } end lemma col_exact' [normed_with_aut r V] [fact (r < 1)] (d : ℝ≥0) [pseudo_normed_group.splittable (Λ →+ M) N d] (k : ℝ≥0) [fact (1 ≤ k)] (m : ℕ) (c₀ : ℝ≥0) (hdkc₀N : d ≤ (k - 1) * c₀ / N) (k' K' : ℝ≥0) [fact (1 ≤ k')] (hk' : k * k ≤ k') (hK' : (m + 2 + (r + 1) / (r * (1 - r)) * (m + 2)^2 : ℝ≥0) ≤ K') (c₁ c₂ : ℝ≥0) [fact (c₀ ≤ r' * c₁)] [fact (c₀ ≤ κ n * c₂)] [fact (c₁ ≤ κ n * c₂)] : (double_complex.col'.{u} BD κ r r' V Λ M N n).is_weak_bounded_exact k' K' m c₂ := begin have adm := (col_complex_rescaled.admissible.{u} r' V Λ M N (BD.X n)), have adm2 := adm.scale_index_left r', let T_T := col_complex_rescaled.T_inv_sub_Tinv' r r' V Λ M N (BD.X n) (κ n), have H := (col_complex_rescaled.is_weak_bounded_exact.{u} r' V Λ M N (BD.X n) d k (m+1) c₀ hdkc₀N), have H1 := H.scale_index_right _ c₂ (κ n) adm, have H2 := (H.scale_index_left _ c₁ r' adm).scale_index_right _ c₂ (κ n) adm2, have key := weak_normed_snake_dual (double_complex.col'.{u} BD κ r r' V Λ M N n) _ _ (double_complex.col_ι BD κ r r' V Λ M N n) T_T k _ ((m + 1) + 1) _ (1 + r⁻¹) (r / (1 - r) + 1) H1 H2 (adm.scale_index_right _), have h_isom : _ := _, apply (key _ _ _ h_isom).of_le _ ⟨hk'⟩ _ le_rfl ⟨le_rfl⟩, any_goals { clear key adm2 H1 H2 }, { intros, apply col_exact'_aux1 }, { intros, apply col_exact'_aux2 }, { intros c i, apply double_complex.col_ι_range }, { apply system_of_complexes.admissible_of_isometry (adm.scale_index_right _) h_isom, }, { refine ⟨le_trans (le_of_eq _) hK'⟩, rw [pow_two, ← mul_assoc], simp only [nat.cast_add, nat.cast_one, bit0, ← add_assoc, or_false, add_eq_zero_iff, one_ne_zero, add_right_inj, mul_eq_mul_right_iff, and_false, div_eq_mul_inv], have hr0 : r ≠ 0, { exact ne_of_gt (fact.out _) }, have h1r : 1 - r ≠ 0, { rw [← nnreal.coe_injective.ne_iff, nnreal.coe_sub, nnreal.coe_zero, sub_ne_zero], { norm_cast, exact ne_of_gt (fact.out _) }, { exact fact.out _ } }, calc (1 + r⁻¹) * (r * (1 - r)⁻¹ + 1) = (1 + r⁻¹) * (r * (1 - r)⁻¹ + (1 - r) * (1 - r)⁻¹) : by rw [mul_inv_cancel h1r] ... = (1 + r⁻¹) * (1 - r)⁻¹ : congr_arg _ _ ... = (1 + r⁻¹) * (r * r⁻¹) * (1 - r)⁻¹ : by rw [mul_inv_cancel hr0, mul_one] ... = ((1 + r⁻¹) * r) * (r⁻¹ * (1 - r)⁻¹) : by simp only [mul_assoc] ... = (r + 1) * (r * (1 - r))⁻¹ : _, { rw [← add_mul, add_comm, nnreal.sub_add_cancel_of_le, one_mul], exact fact.out _ }, { rw [add_mul, one_mul, inv_mul_cancel, mul_inv'], exact ne_of_gt (fact.out _) } }, { intros c i, apply double_complex.col_ι_isometry, } end lemma col_exact [normed_with_aut r V] [fact (r < 1)] (d : ℝ≥0) [pseudo_normed_group.splittable (Λ →+ M) N d] (k : ℝ≥0) [fact (1 ≤ k)] (m : ℕ) (c₀ : ℝ≥0) (hdkc₀N : d ≤ (k - 1) * c₀ / N) (k' K' : ℝ≥0) [fact (1 ≤ k')] (hk' : k * k ≤ k') (hK' : (m + 2 + (r + 1) / (r * (1 - r)) * (m + 2)^2 : ℝ≥0) ≤ K') (c₁ c₂ : ℝ≥0) (_ : fact (c₀ ≤ r' * c₁)) (_ : fact (c₀ ≤ κ n * c₂)) (_ : fact (c₁ ≤ κ n * c₂)) : ((double_complex.{u} BD κ r r' V Λ M N).col n).is_weak_bounded_exact k' K' m c₂ := begin have key := col_exact' BD κ r r' V Λ M N n d k m c₀ hdkc₀N k' K' hk' hK' c₁ c₂, apply key.of_iso (double_complex.col_iso BD κ r r' V Λ M N n).symm, intros, apply double_complex.col_iso_inv_strict end end thm95
e4c93b2b5b2b175eac6d2554479b047f781fda03
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/474.lean
cd0df285d55f89854e5518ccf9c37748210837a0
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,610
lean
import Lean open Lean Meta #eval do let e ← withLetDecl `y (mkConst ``Nat) (mkConst ``Nat.zero) fun y => do let m ← mkFreshExprMVar (mkConst ``Nat) m.mvarId!.assign y let e := mkApp2 (mkConst ``Nat.add) m y -- goal: construct λ y, e dbg_trace (← ppExpr (← mkLambdaFVars #[y] e)) -- doesn't work: creates let dbg_trace (← ppExpr (← instantiateMVars <| -- doesn't work: contains free variable mkLambda `y BinderInfo.default (mkConst ``Nat) (e.abstract #[y]))) instantiateMVars <| -- doesn't work: contains free variable mkLambda `y BinderInfo.default (mkConst ``Nat) (e.abstract #[y]) dbg_trace (← ppExpr e) #eval withLetDecl `y (mkConst ``Nat) (mkConst ``Nat.zero) fun y => do let m ← mkFreshExprMVar (mkConst ``Nat) m.mvarId!.assign y let e := mkApp2 (mkConst ``Nat.add) m y -- goal: construct λ y, e dbg_trace (← instantiateMVars <| -- doesn't work: contains free variable mkLambda `y BinderInfo.default (mkConst ``Nat) (← e.abstractM #[y])) #eval do let (e, _) ← withLetDecl `y (mkConst ``Nat) (mkConst ``Nat.zero) fun y => do let m ← mkFreshExprMVar (mkConst ``Nat) (kind := MetavarKind.syntheticOpaque) let e := mkApp2 (mkConst ``Nat.add) m y dbg_trace (← ppExpr e) dbg_trace (← ppExpr (← e.abstractM #[y])) let e ← instantiateMVars <| -- doesn't work: contains free variable mkLambda `y BinderInfo.default (mkConst ``Nat) (← e.abstractM #[y]) m.mvarId!.assign (mkApp2 (mkConst ``Nat.add) y y) return (e, m) dbg_trace (← ppExpr (← instantiateMVars e))
8499c8a7808147b12fe5229606ca4fd59f2b248a
d751a70f46ed26dc0111a87f5bbe83e5c6648904
/Code/src/timed/basic.lean
3108096a76a9a54b18b6bf8f4fcdce1cf64f9e21
[]
no_license
marcusrossel/bachelors-thesis
92cb12ae8436c10fbfab9bfe4929a0081e615b37
d1ec2c2b5c3c6700a506f2e3cc93f1160e44b422
refs/heads/main
1,682,873,547,703
1,619,795,735,000
1,619,795,735,000
306,041,494
2
0
null
null
null
null
UTF-8
Lean
false
false
6,646
lean
import inst.network.basic open reactor.ports -- The type of opaque values that underlie TPAs. -- Their equality has to be decidable, but beyond that their values are of no interest. variables (υ : Type*) [decidable_eq υ] -- A tag is a logical timestamp: the first component is the time value, the second component is -- the microstep index. Their ordering is lexicographical. @[derive has_le] def tag := lex ℕ ℕ -- A tpa is a set of tag-value pairs. They are the primitive values used in timed reactor networks. @[derive has_union, derive has_emptyc, derive has_sep (tag × option υ), derive has_mem (tag × option υ)] def tpa := finset (tag × option υ) variable {υ} -- Merges a given TPA *onto* another TPA. -- Any tags that are assigned in both TPAs are made unique by choosing the assignment from the first TPA. def tpa.merge : option (tpa υ) → option (tpa υ) → option (tpa υ) | none none := none | (some t) none := some t | none (some t') := some t' | (some t) (some t') := some (t ∪ (t'.filter (λ tv, tv.1 ∉ t.image (prod.fst)))) -- Returns a TPA that only contains at most the tag-value pair for a given tag (if there is one). def tpa.at_tag : option (tpa υ) → tag → option (tpa υ) | none _ := none | (some t) g := let t' := t.filter (λ tv, tv.1 = g) in if t' = ∅ then none else some t' -- An action edge connects an output action port (OAP) to an input action port (IAP). @[ext] structure timed.network.action_edge := (oap : port.id) (iap : port.id) open timed.network -- Action edges' equality is non-constructively decidable. noncomputable instance timed.network.action_edge_dec_eq : decidable_eq action_edge := classical.dec_eq _ -- The proposition that there can be at most one action edge per OAP. def finset.are_many_to_one (es : finset action_edge) : Prop := ∀ e e' : action_edge, e ∈ es → e' ∈ es → e.oap = e'.oap → e = e' -- The proposition that action edges don't connect between different reactors. def finset.are_local (es : finset action_edge) : Prop := ∀ e : action_edge, e ∈ es → e.oap.rtr = e.iap.rtr -- The proposition that an OAP has at most one incoming connection. def finset.have_unique_source_in (es : finset action_edge) (σ : inst.network (tpa υ)) : Prop := ∀ (e : action_edge) (r r' : reaction.id), e ∈ es → (e.oap ∈ σ.η.deps r role.output) → (e.oap ∈ σ.η.deps r' role.output) → r = r -- The proposition that a reaction can not connect to the same IAP through multiple OAPs. def finset.are_functionally_unique_in (es : finset action_edge) (σ : inst.network (tpa υ)) : Prop := ∀ (e e' : action_edge) (r : reaction.id), e ∈ es → e' ∈ es → (e.oap ∈ σ.η.deps r role.output) → (e'.oap ∈ σ.η.deps r role.output) → e.iap = e'.iap → e.oap = e'.oap -- The proposition that action ports do not also behave as regular ports (by being connected -- with network graph edges). def finset.are_separate_from (es : finset action_edge) (σ : inst.network (tpa υ)) : Prop := ∀ (ae : action_edge) (ne : inst.network.graph.edge), ae ∈ es → ne ∈ σ.η.edges → ae.iap ≠ ne.dst ∧ ae.oap ≠ ne.src -- A given set of action edges (and by extension action ports) is well-formed for a given -- instantaneous network, if all of the properties above hold. def finset.are_well_formed_for (es : finset action_edge) (σ : inst.network (tpa υ)) : Prop := es.are_many_to_one ∧ es.are_local ∧ es.have_unique_source_in σ ∧ es.are_functionally_unique_in σ ∧ es.are_separate_from σ -- Wellformedness of action edges is retained under equivalence of instantaneous reactor networks. lemma timed.network.equiv_inst_network_wf (es : finset action_edge) {σ σ' : inst.network (tpa υ)} (hq : σ' ≈ σ) (hw : es.are_well_formed_for σ) : es.are_well_formed_for σ' := begin unfold finset.are_well_formed_for at hw ⊢, simp only [(≈)] at hq, repeat { split }, simp [hw], simp [hw], { unfold finset.have_unique_source_in inst.network.graph.deps inst.network.graph.rcn, intros e i i', rw [(hq.right.right i.rtr).right, (hq.right.right i'.rtr).right], exact hw.right.right.left e i i' }, { unfold finset.are_functionally_unique_in inst.network.graph.deps inst.network.graph.rcn, intros e e' i, rw (hq.right.right i.rtr).right, exact hw.right.right.right.left e e' i }, { unfold finset.are_separate_from, rw hq.left, exact hw.right.right.right.right } end variable (υ) -- A timed reactor network wraps an instantaneous reactor network and equips it with actions -- (via action-ports and -edges), as well as timed execution. structure timed.network := (σ : inst.network (tpa υ)) (time : tag) (event_queue : list tag) (actions : finset action_edge) (well_formed : actions.are_well_formed_for σ) namespace timed namespace network variable {υ} -- The input action ports for a given timed network. noncomputable def iaps (τ : timed.network υ) : finset port.id := τ.actions.image (λ e, e.iap) -- The output action ports for a given timed network. noncomputable def oaps (τ : timed.network υ) : finset port.id := τ.actions.image (λ e, e.oap) -- The priority of a given action edge is the priority of the reaction its OAP is connected to. -- By the property `are_functionally_unique_in`, there is at most one of those reactions. -- If there is none, `none` is returned. noncomputable def action_edge.priority_in (ae : action_edge) (σ : inst.network (tpa υ)) : option ℕ := let rtr := (σ.η.rtr ae.oap.rtr) in let rcns := rtr.priorities.filter (λ p, p ∈ (rtr.reactions ae.oap.prt).deps role.output) in if h : rcns.card = 1 then (finset.card_eq_one.mp h).some else none -- The order of action edges is determined by their priorities (`action_edge.priority_in`). -- If there is no priority for an edge, it is considered smaller than all other edges. -- Comparing these values across different reactors doesn't really make sense. def action_priority_ge (σ : inst.network (tpa υ)) : action_edge → action_edge → Prop := λ e e', match e.priority_in σ, e'.priority_in σ with | some p, some p' := p ≥ p' | _, none := true | none, _ := false end -- The `action_priority_ge` relation is non-constructively decidable. noncomputable instance {σ : inst.network (tpa υ)} : decidable_rel (action_priority_ge σ) := classical.dec_rel _ end network end timed
3cc0cc0db568effff9c1627c8c191dff4d8408f4
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/dec_trivial_tactic.lean
fbff5126a55f29805a9841602986b7cd8eae2c63
[ "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
500
lean
import data.nat.basic example (n : ℕ) (h : n < 2) : n = 0 ∨ n = 1 := by dec_trivial! example (n : ℕ) (h : n < 3) : true := begin let k : ℕ := n - 1, have : ∀ i < k, i = 0 ∨ i = 1, by dec_trivial!, trivial end example (b : bool) (h : b = tt) : true := begin let b₁ : bool := b, have : ∀ b₂ : bool, b₂ ≠ b₁ → b₂ = ff, by dec_trivial!, trivial end example (n : ℕ) : (0 : fin (n+1)) + 0 = 0 := begin success_if_fail { dec_trivial! }, dec_trivial end
8eaec7467c0b2677e5dd71e24cfb4348ba05cc6d
f5f7e6fae601a5fe3cac7cc3ed353ed781d62419
/src/data/multiset.lean
8f31933ee945ab9bcdb63bb24bf47a269c6e111f
[ "Apache-2.0" ]
permissive
EdAyers/mathlib
9ecfb2f14bd6caad748b64c9c131befbff0fb4e0
ca5d4c1f16f9c451cf7170b10105d0051db79e1b
refs/heads/master
1,626,189,395,845
1,555,284,396,000
1,555,284,396,000
144,004,030
0
0
Apache-2.0
1,533,727,664,000
1,533,727,663,000
null
UTF-8
Lean
false
false
127,973
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Multisets. -/ import logic.function order.boolean_algebra data.list.basic data.list.perm data.list.sort data.quot data.string algebra.order_functions algebra.group_power algebra.ordered_group category.traversable.lemmas tactic.interactive category.traversable.instances category.basic open list subtype nat lattice variables {α : Type*} {β : Type*} {γ : Type*} local infix ` • ` := add_monoid.smul instance list.perm.setoid (α : Type*) : setoid (list α) := setoid.mk perm ⟨perm.refl, @perm.symm _, @perm.trans _⟩ /-- `multiset α` is the quotient of `list α` by list permutation. The result is a type of finite sets with duplicates allowed. -/ def {u} multiset (α : Type u) : Type u := quotient (list.perm.setoid α) namespace multiset instance : has_coe (list α) (multiset α) := ⟨quot.mk _⟩ @[simp] theorem quot_mk_to_coe (l : list α) : @eq (multiset α) ⟦l⟧ l := rfl @[simp] theorem quot_mk_to_coe' (l : list α) : @eq (multiset α) (quot.mk (≈) l) l := rfl @[simp] theorem quot_mk_to_coe'' (l : list α) : @eq (multiset α) (quot.mk setoid.r l) l := rfl @[simp] theorem coe_eq_coe {l₁ l₂ : list α} : (l₁ : multiset α) = l₂ ↔ l₁ ~ l₂ := quotient.eq instance has_decidable_eq [decidable_eq α] : decidable_eq (multiset α) | s₁ s₂ := quotient.rec_on_subsingleton₂ s₁ s₂ $ λ l₁ l₂, decidable_of_iff' _ quotient.eq /- empty multiset -/ /-- `0 : multiset α` is the empty set -/ protected def zero : multiset α := @nil α instance : has_zero (multiset α) := ⟨multiset.zero⟩ instance : has_emptyc (multiset α) := ⟨0⟩ instance : inhabited (multiset α) := ⟨0⟩ @[simp] theorem coe_nil_eq_zero : (@nil α : multiset α) = 0 := rfl @[simp] theorem empty_eq_zero : (∅ : multiset α) = 0 := rfl theorem coe_eq_zero (l : list α) : (l : multiset α) = 0 ↔ l = [] := iff.trans coe_eq_coe perm_nil /- cons -/ /-- `cons a s` is the multiset which contains `s` plus one more instance of `a`. -/ def cons (a : α) (s : multiset α) : multiset α := quot.lift_on s (λ l, (a :: l : multiset α)) (λ l₁ l₂ p, quot.sound ((perm_cons a).2 p)) notation a :: b := cons a b instance : has_insert α (multiset α) := ⟨cons⟩ @[simp] theorem insert_eq_cons (a : α) (s : multiset α) : insert a s = a::s := rfl @[simp] theorem cons_coe (a : α) (l : list α) : (a::l : multiset α) = (a::l : list α) := rfl theorem singleton_coe (a : α) : (a::0 : multiset α) = ([a] : list α) := rfl @[simp] theorem cons_inj_left {a b : α} (s : multiset α) : a::s = b::s ↔ a = b := ⟨quot.induction_on s $ λ l e, have [a] ++ l ~ [b] ++ l, from quotient.exact e, eq_singleton_of_perm $ (perm_app_right_iff _).1 this, congr_arg _⟩ @[simp] theorem cons_inj_right (a : α) : ∀{s t : multiset α}, a::s = a::t ↔ s = t := by rintros ⟨l₁⟩ ⟨l₂⟩; simp [perm_cons] @[recursor 5] protected theorem induction {p : multiset α → Prop} (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a :: s)) : ∀s, p s := by rintros ⟨l⟩; induction l with _ _ ih; [exact h₁, exact h₂ ih] @[elab_as_eliminator] protected theorem induction_on {p : multiset α → Prop} (s : multiset α) (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a :: s)) : p s := multiset.induction h₁ h₂ s theorem cons_swap (a b : α) (s : multiset α) : a :: b :: s = b :: a :: s := quot.induction_on s $ λ l, quotient.sound $ perm.swap _ _ _ section rec variables {C : multiset α → Sort*} /-- Dependent recursor on multisets. TODO: should be @[recursor 6], but then the definition of `multiset.pi` failes with a stack overflow in `whnf`. -/ protected def rec (C_0 : C 0) (C_cons : Πa m, C m → C (a::m)) (C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)) (m : multiset α) : C m := quotient.hrec_on m (@list.rec α (λl, C ⟦l⟧) C_0 (λa l b, C_cons a ⟦l⟧ b)) $ assume l l' h, list.rec_heq_of_perm h (assume a l l' b b' hl, have ⟦l⟧ = ⟦l'⟧, from quot.sound hl, by cc) (assume a a' l, C_cons_heq a a' ⟦l⟧) @[elab_as_eliminator] protected def rec_on (m : multiset α) (C_0 : C 0) (C_cons : Πa m, C m → C (a::m)) (C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)) : C m := multiset.rec C_0 C_cons C_cons_heq m variables {C_0 : C 0} {C_cons : Πa m, C m → C (a::m)} {C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)} @[simp] lemma rec_on_0 : @multiset.rec_on α C (0:multiset α) C_0 C_cons C_cons_heq = C_0 := rfl @[simp] lemma rec_on_cons (a : α) (m : multiset α) : (a :: m).rec_on C_0 C_cons C_cons_heq = C_cons a m (m.rec_on C_0 C_cons C_cons_heq) := quotient.induction_on m $ assume l, rfl end rec section mem /-- `a ∈ s` means that `a` has nonzero multiplicity in `s`. -/ def mem (a : α) (s : multiset α) : Prop := quot.lift_on s (λ l, a ∈ l) (λ l₁ l₂ (e : l₁ ~ l₂), propext $ mem_of_perm e) instance : has_mem α (multiset α) := ⟨mem⟩ @[simp] lemma mem_coe {a : α} {l : list α} : a ∈ (l : multiset α) ↔ a ∈ l := iff.rfl instance decidable_mem [decidable_eq α] (a : α) (s : multiset α) : decidable (a ∈ s) := quot.rec_on_subsingleton s $ list.decidable_mem a @[simp] theorem mem_cons {a b : α} {s : multiset α} : a ∈ b :: s ↔ a = b ∨ a ∈ s := quot.induction_on s $ λ l, iff.rfl lemma mem_cons_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ b :: s := mem_cons.2 $ or.inr h @[simp] theorem mem_cons_self (a : α) (s : multiset α) : a ∈ a :: s := mem_cons.2 (or.inl rfl) theorem exists_cons_of_mem {s : multiset α} {a : α} : a ∈ s → ∃ t, s = a :: t := quot.induction_on s $ λ l (h : a ∈ l), let ⟨l₁, l₂, e⟩ := mem_split h in e.symm ▸ ⟨(l₁++l₂ : list α), quot.sound perm_middle⟩ @[simp] theorem not_mem_zero (a : α) : a ∉ (0 : multiset α) := id theorem eq_zero_of_forall_not_mem {s : multiset α} : (∀x, x ∉ s) → s = 0 := quot.induction_on s $ λ l H, by rw eq_nil_iff_forall_not_mem.mpr H; refl theorem exists_mem_of_ne_zero {s : multiset α} : s ≠ 0 → ∃ a : α, a ∈ s := quot.induction_on s $ assume l hl, match l, hl with | [] := assume h, false.elim $ h rfl | (a :: l) := assume _, ⟨a, by simp⟩ end @[simp] lemma zero_ne_cons {a : α} {m : multiset α} : 0 ≠ a :: m := assume h, have a ∈ (0:multiset α), from h.symm ▸ mem_cons_self _ _, not_mem_zero _ this @[simp] lemma cons_ne_zero {a : α} {m : multiset α} : a :: m ≠ 0 := zero_ne_cons.symm lemma cons_eq_cons {a b : α} {as bs : multiset α} : a :: as = b :: bs ↔ ((a = b ∧ as = bs) ∨ (a ≠ b ∧ ∃cs, as = b :: cs ∧ bs = a :: cs)) := begin haveI : decidable_eq α := classical.dec_eq α, split, { assume eq, by_cases a = b, { subst h, simp * at * }, { have : a ∈ b :: bs, from eq ▸ mem_cons_self _ _, have : a ∈ bs, by simpa [h], rcases exists_cons_of_mem this with ⟨cs, hcs⟩, simp [h, hcs], have : a :: as = b :: a :: cs, by simp [eq, hcs], have : a :: as = a :: b :: cs, by rwa [cons_swap], simpa using this } }, { assume h, rcases h with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩, { simp * }, { simp [*, cons_swap a b] } } end end mem /- subset -/ section subset /-- `s ⊆ t` is the lift of the list subset relation. It means that any element with nonzero multiplicity in `s` has nonzero multiplicity in `t`, but it does not imply that the multiplicity of `a` in `s` is less or equal than in `t`; see `s ≤ t` for this relation. -/ protected def subset (s t : multiset α) : Prop := ∀ ⦃a : α⦄, a ∈ s → a ∈ t instance : has_subset (multiset α) := ⟨multiset.subset⟩ @[simp] theorem coe_subset {l₁ l₂ : list α} : (l₁ : multiset α) ⊆ l₂ ↔ l₁ ⊆ l₂ := iff.rfl @[simp] theorem subset.refl (s : multiset α) : s ⊆ s := λ a h, h theorem subset.trans {s t u : multiset α} : s ⊆ t → t ⊆ u → s ⊆ u := λ h₁ h₂ a m, h₂ (h₁ m) theorem subset_iff {s t : multiset α} : s ⊆ t ↔ (∀⦃x⦄, x ∈ s → x ∈ t) := iff.rfl theorem mem_of_subset {s t : multiset α} {a : α} (h : s ⊆ t) : a ∈ s → a ∈ t := @h _ @[simp] theorem zero_subset (s : multiset α) : 0 ⊆ s := λ a, (not_mem_nil a).elim @[simp] theorem cons_subset {a : α} {s t : multiset α} : (a :: s) ⊆ t ↔ a ∈ t ∧ s ⊆ t := by simp [subset_iff, or_imp_distrib, forall_and_distrib] theorem eq_zero_of_subset_zero {s : multiset α} (h : s ⊆ 0) : s = 0 := eq_zero_of_forall_not_mem h theorem subset_zero {s : multiset α} : s ⊆ 0 ↔ s = 0 := ⟨eq_zero_of_subset_zero, λ xeq, xeq.symm ▸ subset.refl 0⟩ end subset /- multiset order -/ /-- `s ≤ t` means that `s` is a sublist of `t` (up to permutation). Equivalently, `s ≤ t` means that `count a s ≤ count a t` for all `a`. -/ protected def le (s t : multiset α) : Prop := quotient.lift_on₂ s t (<+~) $ λ v₁ v₂ w₁ w₂ p₁ p₂, propext (p₂.subperm_left.trans p₁.subperm_right) instance : partial_order (multiset α) := { le := multiset.le, le_refl := by rintros ⟨l⟩; exact subperm.refl _, le_trans := by rintros ⟨l₁⟩ ⟨l₂⟩ ⟨l₃⟩; exact @subperm.trans _ _ _ _, le_antisymm := by rintros ⟨l₁⟩ ⟨l₂⟩ h₁ h₂; exact quot.sound (subperm.antisymm h₁ h₂) } theorem subset_of_le {s t : multiset α} : s ≤ t → s ⊆ t := quotient.induction_on₂ s t $ λ l₁ l₂, subset_of_subperm theorem mem_of_le {s t : multiset α} {a : α} (h : s ≤ t) : a ∈ s → a ∈ t := mem_of_subset (subset_of_le h) @[simp] theorem coe_le {l₁ l₂ : list α} : (l₁ : multiset α) ≤ l₂ ↔ l₁ <+~ l₂ := iff.rfl @[elab_as_eliminator] theorem le_induction_on {C : multiset α → multiset α → Prop} {s t : multiset α} (h : s ≤ t) (H : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → C l₁ l₂) : C s t := quotient.induction_on₂ s t (λ l₁ l₂ ⟨l, p, s⟩, (show ⟦l⟧ = ⟦l₁⟧, from quot.sound p) ▸ H s) h theorem zero_le (s : multiset α) : 0 ≤ s := quot.induction_on s $ λ l, subperm_of_sublist $ nil_sublist l theorem le_zero {s : multiset α} : s ≤ 0 ↔ s = 0 := ⟨λ h, le_antisymm h (zero_le _), le_of_eq⟩ theorem lt_cons_self (s : multiset α) (a : α) : s < a :: s := quot.induction_on s $ λ l, suffices l <+~ a :: l ∧ (¬l ~ a :: l), by simpa [lt_iff_le_and_ne], ⟨subperm_of_sublist (sublist_cons _ _), λ p, ne_of_lt (lt_succ_self (length l)) (perm_length p)⟩ theorem le_cons_self (s : multiset α) (a : α) : s ≤ a :: s := le_of_lt $ lt_cons_self _ _ theorem cons_le_cons_iff (a : α) {s t : multiset α} : a :: s ≤ a :: t ↔ s ≤ t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_cons a theorem cons_le_cons (a : α) {s t : multiset α} : s ≤ t → a :: s ≤ a :: t := (cons_le_cons_iff a).2 theorem le_cons_of_not_mem {a : α} {s t : multiset α} (m : a ∉ s) : s ≤ a :: t ↔ s ≤ t := begin refine ⟨_, λ h, le_trans h $ le_cons_self _ _⟩, suffices : ∀ {t'} (_ : s ≤ t') (_ : a ∈ t'), a :: s ≤ t', { exact λ h, (cons_le_cons_iff a).1 (this h (mem_cons_self _ _)) }, introv h, revert m, refine le_induction_on h _, introv s m₁ m₂, rcases mem_split m₂ with ⟨r₁, r₂, rfl⟩, exact perm_middle.subperm_left.2 ((subperm_cons _).2 $ subperm_of_sublist $ (sublist_or_mem_of_sublist s).resolve_right m₁) end /- cardinality -/ /-- The cardinality of a multiset is the sum of the multiplicities of all its elements, or simply the length of the underlying list. -/ def card (s : multiset α) : ℕ := quot.lift_on s length $ λ l₁ l₂, perm_length @[simp] theorem coe_card (l : list α) : card (l : multiset α) = length l := rfl @[simp] theorem card_zero : @card α 0 = 0 := rfl @[simp] theorem card_cons (a : α) (s : multiset α) : card (a :: s) = card s + 1 := quot.induction_on s $ λ l, rfl @[simp] theorem card_singleton (a : α) : card (a::0) = 1 := by simp theorem card_le_of_le {s t : multiset α} (h : s ≤ t) : card s ≤ card t := le_induction_on h $ λ l₁ l₂, length_le_of_sublist theorem eq_of_le_of_card_le {s t : multiset α} (h : s ≤ t) : card t ≤ card s → s = t := le_induction_on h $ λ l₁ l₂ s h₂, congr_arg coe $ eq_of_sublist_of_length_le s h₂ theorem card_lt_of_lt {s t : multiset α} (h : s < t) : card s < card t := lt_of_not_ge $ λ h₂, ne_of_lt h $ eq_of_le_of_card_le (le_of_lt h) h₂ theorem lt_iff_cons_le {s t : multiset α} : s < t ↔ ∃ a, a :: s ≤ t := ⟨quotient.induction_on₂ s t $ λ l₁ l₂ h, subperm.exists_of_length_lt (le_of_lt h) (card_lt_of_lt h), λ ⟨a, h⟩, lt_of_lt_of_le (lt_cons_self _ _) h⟩ @[simp] theorem card_eq_zero {s : multiset α} : card s = 0 ↔ s = 0 := ⟨λ h, (eq_of_le_of_card_le (zero_le _) (le_of_eq h)).symm, λ e, by simp [e]⟩ theorem card_pos {s : multiset α} : 0 < card s ↔ s ≠ 0 := pos_iff_ne_zero.trans $ not_congr card_eq_zero theorem card_pos_iff_exists_mem {s : multiset α} : 0 < card s ↔ ∃ a, a ∈ s := quot.induction_on s $ λ l, length_pos_iff_exists_mem @[elab_as_eliminator] def strong_induction_on {p : multiset α → Sort*} : ∀ (s : multiset α), (∀ s, (∀t < s, p t) → p s) → p s | s := λ ih, ih s $ λ t h, have card t < card s, from card_lt_of_lt h, strong_induction_on t ih using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf card⟩]} theorem strong_induction_eq {p : multiset α → Sort*} (s : multiset α) (H) : @strong_induction_on _ p s H = H s (λ t h, @strong_induction_on _ p t H) := by rw [strong_induction_on] @[elab_as_eliminator] lemma case_strong_induction_on {p : multiset α → Prop} (s : multiset α) (h₀ : p 0) (h₁ : ∀ a s, (∀t ≤ s, p t) → p (a :: s)) : p s := multiset.strong_induction_on s $ assume s, multiset.induction_on s (λ _, h₀) $ λ a s _ ih, h₁ _ _ $ λ t h, ih _ $ lt_of_le_of_lt h $ lt_cons_self _ _ /- singleton -/ @[simp] theorem singleton_eq_singleton (a : α) : singleton a = a::0 := rfl @[simp] theorem mem_singleton {a b : α} : b ∈ a::0 ↔ b = a := by simp theorem mem_singleton_self (a : α) : a ∈ (a::0 : multiset α) := mem_cons_self _ _ theorem singleton_inj {a b : α} : a::0 = b::0 ↔ a = b := cons_inj_left _ @[simp] theorem singleton_ne_zero (a : α) : a::0 ≠ 0 := ne_of_gt (lt_cons_self _ _) @[simp] theorem singleton_le {a : α} {s : multiset α} : a::0 ≤ s ↔ a ∈ s := ⟨λ h, mem_of_le h (mem_singleton_self _), λ h, let ⟨t, e⟩ := exists_cons_of_mem h in e.symm ▸ cons_le_cons _ (zero_le _)⟩ theorem card_eq_one {s : multiset α} : card s = 1 ↔ ∃ a, s = a::0 := ⟨quot.induction_on s $ λ l h, (list.length_eq_one.1 h).imp $ λ a, congr_arg coe, λ ⟨a, e⟩, e.symm ▸ rfl⟩ /- add -/ /-- The sum of two multisets is the lift of the list append operation. This adds the multiplicities of each element, i.e. `count a (s + t) = count a s + count a t`. -/ protected def add (s₁ s₂ : multiset α) : multiset α := quotient.lift_on₂ s₁ s₂ (λ l₁ l₂, ((l₁ ++ l₂ : list α) : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_app p₁ p₂ instance : has_add (multiset α) := ⟨multiset.add⟩ @[simp] theorem coe_add (s t : list α) : (s + t : multiset α) = (s ++ t : list α) := rfl protected theorem add_comm (s t : multiset α) : s + t = t + s := quotient.induction_on₂ s t $ λ l₁ l₂, quot.sound perm_app_comm protected theorem zero_add (s : multiset α) : 0 + s = s := quot.induction_on s $ λ l, rfl theorem singleton_add (a : α) (s : multiset α) : ↑[a] + s = a::s := rfl protected theorem add_le_add_left (s) {t u : multiset α} : s + t ≤ s + u ↔ t ≤ u := quotient.induction_on₃ s t u $ λ l₁ l₂ l₃, subperm_app_left _ protected theorem add_left_cancel (s) {t u : multiset α} (h : s + t = s + u) : t = u := le_antisymm ((multiset.add_le_add_left _).1 (le_of_eq h)) ((multiset.add_le_add_left _).1 (le_of_eq h.symm)) instance : ordered_cancel_comm_monoid (multiset α) := { zero := 0, add := (+), add_comm := multiset.add_comm, add_assoc := λ s₁ s₂ s₃, quotient.induction_on₃ s₁ s₂ s₃ $ λ l₁ l₂ l₃, congr_arg coe $ append_assoc l₁ l₂ l₃, zero_add := multiset.zero_add, add_zero := λ s, by rw [multiset.add_comm, multiset.zero_add], add_left_cancel := multiset.add_left_cancel, add_right_cancel := λ s₁ s₂ s₃ h, multiset.add_left_cancel s₂ $ by simpa [multiset.add_comm] using h, add_le_add_left := λ s₁ s₂ h s₃, (multiset.add_le_add_left _).2 h, le_of_add_le_add_left := λ s₁ s₂ s₃, (multiset.add_le_add_left _).1, ..@multiset.partial_order α } @[simp] theorem cons_add (a : α) (s t : multiset α) : a :: s + t = a :: (s + t) := by rw [← singleton_add, ← singleton_add, add_assoc] @[simp] theorem add_cons (a : α) (s t : multiset α) : s + a :: t = a :: (s + t) := by rw [add_comm, cons_add, add_comm] theorem le_add_right (s t : multiset α) : s ≤ s + t := by simpa using add_le_add_left (zero_le t) s theorem le_add_left (s t : multiset α) : s ≤ t + s := by simpa using add_le_add_right (zero_le t) s @[simp] theorem card_add (s t : multiset α) : card (s + t) = card s + card t := quotient.induction_on₂ s t length_append lemma card_smul (s : multiset α) (n : ℕ) : (n • s).card = n * s.card := by induction n; simp [succ_smul, *, nat.succ_mul] @[simp] theorem mem_add {a : α} {s t : multiset α} : a ∈ s + t ↔ a ∈ s ∨ a ∈ t := quotient.induction_on₂ s t $ λ l₁ l₂, mem_append theorem le_iff_exists_add {s t : multiset α} : s ≤ t ↔ ∃ u, t = s + u := ⟨λ h, le_induction_on h $ λ l₁ l₂ s, let ⟨l, p⟩ := exists_perm_append_of_sublist s in ⟨l, quot.sound p⟩, λ⟨u, e⟩, e.symm ▸ le_add_right s u⟩ instance : canonically_ordered_monoid (multiset α) := { lt_of_add_lt_add_left := @lt_of_add_lt_add_left _ _, le_iff_exists_add := @le_iff_exists_add _, bot := 0, bot_le := multiset.zero_le, ..multiset.ordered_cancel_comm_monoid } /- repeat -/ /-- `repeat a n` is the multiset containing only `a` with multiplicity `n`. -/ def repeat (a : α) (n : ℕ) : multiset α := repeat a n @[simp] lemma repeat_zero (a : α) : repeat a 0 = 0 := rfl @[simp] lemma repeat_succ (a : α) (n) : repeat a (n+1) = a :: repeat a n := by simp [repeat] @[simp] lemma repeat_one (a : α) : repeat a 1 = a :: 0 := by simp @[simp] lemma card_repeat : ∀ (a : α) n, card (repeat a n) = n := length_repeat theorem eq_of_mem_repeat {a b : α} {n} : b ∈ repeat a n → b = a := eq_of_mem_repeat theorem eq_repeat' {a : α} {s : multiset α} : s = repeat a s.card ↔ ∀ b ∈ s, b = a := quot.induction_on s $ λ l, iff.trans ⟨λ h, (perm_repeat.1 $ (quotient.exact h).symm).symm, congr_arg coe⟩ eq_repeat' theorem eq_repeat_of_mem {a : α} {s : multiset α} : (∀ b ∈ s, b = a) → s = repeat a s.card := eq_repeat'.2 theorem eq_repeat {a : α} {n} {s : multiset α} : s = repeat a n ↔ card s = n ∧ ∀ b ∈ s, b = a := ⟨λ h, h.symm ▸ ⟨card_repeat _ _, λ b, eq_of_mem_repeat⟩, λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩ theorem repeat_subset_singleton : ∀ (a : α) n, repeat a n ⊆ a::0 := repeat_subset_singleton theorem repeat_le_coe {a : α} {n} {l : list α} : repeat a n ≤ l ↔ list.repeat a n <+ l := ⟨λ ⟨l', p, s⟩, (perm_repeat.1 p.symm).symm ▸ s, subperm_of_sublist⟩ /- range -/ /-- `range n` is the multiset lifted from the list `range n`, that is, the set `{0, 1, ..., n-1}`. -/ def range (n : ℕ) : multiset ℕ := range n @[simp] theorem range_zero : range 0 = 0 := rfl @[simp] theorem range_succ (n : ℕ) : range (succ n) = n :: range n := by rw [range, range_concat, ← coe_add, add_comm]; refl @[simp] theorem card_range (n : ℕ) : card (range n) = n := length_range _ theorem range_subset {m n : ℕ} : range m ⊆ range n ↔ m ≤ n := range_subset @[simp] theorem mem_range {m n : ℕ} : m ∈ range n ↔ m < n := mem_range @[simp] theorem not_mem_range_self {n : ℕ} : n ∉ range n := not_mem_range_self /- erase -/ section erase variables [decidable_eq α] {s t : multiset α} {a b : α} /-- `erase s a` is the multiset that subtracts 1 from the multiplicity of `a`. -/ def erase (s : multiset α) (a : α) : multiset α := quot.lift_on s (λ l, (l.erase a : multiset α)) (λ l₁ l₂ p, quot.sound (erase_perm_erase a p)) @[simp] theorem coe_erase (l : list α) (a : α) : erase (l : multiset α) a = l.erase a := rfl @[simp] theorem erase_zero (a : α) : (0 : multiset α).erase a = 0 := rfl @[simp] theorem erase_cons_head (a : α) (s : multiset α) : (a :: s).erase a = s := quot.induction_on s $ λ l, congr_arg coe $ erase_cons_head a l @[simp] theorem erase_cons_tail {a b : α} (s : multiset α) (h : b ≠ a) : (b::s).erase a = b :: s.erase a := quot.induction_on s $ λ l, congr_arg coe $ erase_cons_tail l h @[simp] theorem erase_of_not_mem {a : α} {s : multiset α} : a ∉ s → s.erase a = s := quot.induction_on s $ λ l h, congr_arg coe $ erase_of_not_mem h @[simp] theorem cons_erase {s : multiset α} {a : α} : a ∈ s → a :: s.erase a = s := quot.induction_on s $ λ l h, quot.sound (perm_erase h).symm theorem le_cons_erase (s : multiset α) (a : α) : s ≤ a :: s.erase a := if h : a ∈ s then le_of_eq (cons_erase h).symm else by rw erase_of_not_mem h; apply le_cons_self @[simp] theorem card_erase_of_mem {a : α} {s : multiset α} : a ∈ s → card (s.erase a) = pred (card s) := quot.induction_on s $ λ l, length_erase_of_mem theorem erase_add_left_pos {a : α} {s : multiset α} (t) : a ∈ s → (s + t).erase a = s.erase a + t := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_left l₂ h theorem erase_add_right_pos {a : α} (s) {t : multiset α} (h : a ∈ t) : (s + t).erase a = s + t.erase a := by rw [add_comm, erase_add_left_pos s h, add_comm] theorem erase_add_right_neg {a : α} {s : multiset α} (t) : a ∉ s → (s + t).erase a = s + t.erase a := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_right l₂ h theorem erase_add_left_neg {a : α} (s) {t : multiset α} (h : a ∉ t) : (s + t).erase a = s.erase a + t := by rw [add_comm, erase_add_right_neg s h, add_comm] theorem erase_le (a : α) (s : multiset α) : s.erase a ≤ s := quot.induction_on s $ λ l, subperm_of_sublist (erase_sublist a l) @[simp] theorem erase_lt {a : α} {s : multiset α} : s.erase a < s ↔ a ∈ s := ⟨λ h, not_imp_comm.1 erase_of_not_mem (ne_of_lt h), λ h, by simpa [h] using lt_cons_self (s.erase a) a⟩ theorem erase_subset (a : α) (s : multiset α) : s.erase a ⊆ s := subset_of_le (erase_le a s) theorem mem_erase_of_ne {a b : α} {s : multiset α} (ab : a ≠ b) : a ∈ s.erase b ↔ a ∈ s := quot.induction_on s $ λ l, list.mem_erase_of_ne ab theorem mem_of_mem_erase {a b : α} {s : multiset α} : a ∈ s.erase b → a ∈ s := mem_of_subset (erase_subset _ _) theorem erase_comm (s : multiset α) (a b : α) : (s.erase a).erase b = (s.erase b).erase a := quot.induction_on s $ λ l, congr_arg coe $ l.erase_comm a b theorem erase_le_erase {s t : multiset α} (a : α) (h : s ≤ t) : s.erase a ≤ t.erase a := le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist (erase_sublist_erase _ h) theorem erase_le_iff_le_cons {s t : multiset α} {a : α} : s.erase a ≤ t ↔ s ≤ a :: t := ⟨λ h, le_trans (le_cons_erase _ _) (cons_le_cons _ h), λ h, if m : a ∈ s then by rw ← cons_erase m at h; exact (cons_le_cons_iff _).1 h else le_trans (erase_le _ _) ((le_cons_of_not_mem m).1 h)⟩ end erase @[simp] theorem coe_reverse (l : list α) : (reverse l : multiset α) = l := quot.sound $ reverse_perm _ /- map -/ /-- `map f s` is the lift of the list `map` operation. The multiplicity of `b` in `map f s` is the number of `a ∈ s` (counting multiplicity) such that `f a = b`. -/ def map (f : α → β) (s : multiset α) : multiset β := quot.lift_on s (λ l : list α, (l.map f : multiset β)) (λ l₁ l₂ p, quot.sound (perm_map f p)) @[simp] theorem coe_map (f : α → β) (l : list α) : map f ↑l = l.map f := rfl @[simp] theorem map_zero (f : α → β) : map f 0 = 0 := rfl @[simp] theorem map_cons (f : α → β) (a s) : map f (a::s) = f a :: map f s := quot.induction_on s $ λ l, rfl @[simp] lemma map_singleton (f : α → β) (a : α) : ({a} : multiset α).map f = {f a} := rfl @[simp] theorem map_add (f : α → β) (s t) : map f (s + t) = map f s + map f t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ map_append _ _ _ instance (f : α → β) : is_add_monoid_hom (map f) := { map_add := map_add _, map_zero := map_zero _ } @[simp] theorem mem_map {f : α → β} {b : β} {s : multiset α} : b ∈ map f s ↔ ∃ a, a ∈ s ∧ f a = b := quot.induction_on s $ λ l, mem_map @[simp] theorem card_map (f : α → β) (s) : card (map f s) = card s := quot.induction_on s $ λ l, length_map _ _ theorem mem_map_of_mem (f : α → β) {a : α} {s : multiset α} (h : a ∈ s) : f a ∈ map f s := mem_map.2 ⟨_, h, rfl⟩ @[simp] theorem mem_map_of_inj {f : α → β} (H : function.injective f) {a : α} {s : multiset α} : f a ∈ map f s ↔ a ∈ s := quot.induction_on s $ λ l, mem_map_of_inj H @[simp] theorem map_map (g : β → γ) (f : α → β) (s : multiset α) : map g (map f s) = map (g ∘ f) s := quot.induction_on s $ λ l, congr_arg coe $ list.map_map _ _ _ @[simp] theorem map_id (s : multiset α) : map id s = s := quot.induction_on s $ λ l, congr_arg coe $ map_id _ @[simp] lemma map_id' (s : multiset α) : map (λx, x) s = s := map_id s @[simp] theorem map_const (s : multiset α) (b : β) : map (function.const α b) s = repeat b s.card := quot.induction_on s $ λ l, congr_arg coe $ map_const _ _ @[congr] theorem map_congr {f g : α → β} {s : multiset α} : (∀ x ∈ s, f x = g x) → map f s = map g s := quot.induction_on s $ λ l H, congr_arg coe $ map_congr H lemma map_hcongr {β' : Type*} {m : multiset α} {f : α → β} {f' : α → β'} (h : β = β') (hf : ∀a∈m, f a == f' a) : map f m == map f' m := begin subst h, simp at hf, simp [map_congr hf] end theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ := eq_of_mem_repeat $ by rwa map_const at h @[simp] theorem map_le_map {f : α → β} {s t : multiset α} (h : s ≤ t) : map f s ≤ map f t := le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist $ map_sublist_map f h @[simp] theorem map_subset_map {f : α → β} {s t : multiset α} (H : s ⊆ t) : map f s ⊆ map f t := λ b m, let ⟨a, h, e⟩ := mem_map.1 m in mem_map.2 ⟨a, H h, e⟩ /- fold -/ /-- `foldl f H b s` is the lift of the list operation `foldl f b l`, which folds `f` over the multiset. It is well defined when `f` is right-commutative, that is, `f (f b a₁) a₂ = f (f b a₂) a₁`. -/ def foldl (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : β := quot.lift_on s (λ l, foldl f b l) (λ l₁ l₂ p, foldl_eq_of_perm H p b) @[simp] theorem foldl_zero (f : β → α → β) (H b) : foldl f H b 0 = b := rfl @[simp] theorem foldl_cons (f : β → α → β) (H b a s) : foldl f H b (a :: s) = foldl f H (f b a) s := quot.induction_on s $ λ l, rfl @[simp] theorem foldl_add (f : β → α → β) (H b s t) : foldl f H b (s + t) = foldl f H (foldl f H b s) t := quotient.induction_on₂ s t $ λ l₁ l₂, foldl_append _ _ _ _ /-- `foldr f H b s` is the lift of the list operation `foldr f b l`, which folds `f` over the multiset. It is well defined when `f` is left-commutative, that is, `f a₁ (f a₂ b) = f a₂ (f a₁ b)`. -/ def foldr (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : β := quot.lift_on s (λ l, foldr f b l) (λ l₁ l₂ p, foldr_eq_of_perm H p b) @[simp] theorem foldr_zero (f : α → β → β) (H b) : foldr f H b 0 = b := rfl @[simp] theorem foldr_cons (f : α → β → β) (H b a s) : foldr f H b (a :: s) = f a (foldr f H b s) := quot.induction_on s $ λ l, rfl @[simp] theorem foldr_add (f : α → β → β) (H b s t) : foldr f H b (s + t) = foldr f H (foldr f H b t) s := quotient.induction_on₂ s t $ λ l₁ l₂, foldr_append _ _ _ _ @[simp] theorem coe_foldr (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) : foldr f H b l = l.foldr f b := rfl @[simp] theorem coe_foldl (f : β → α → β) (H : right_commutative f) (b : β) (l : list α) : foldl f H b l = l.foldl f b := rfl theorem coe_foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) : foldr f H b l = l.foldl (λ x y, f y x) b := (congr_arg (foldr f H b) (coe_reverse l)).symm.trans $ foldr_reverse _ _ _ theorem foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : foldr f H b s = foldl (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s := quot.induction_on s $ λ l, coe_foldr_swap _ _ _ _ theorem foldl_swap (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : foldl f H b s = foldr (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s := (foldr_swap _ _ _ _).symm /-- Product of a multiset given a commutative monoid structure on `α`. `prod {a, b, c} = a * b * c` -/ def prod [comm_monoid α] : multiset α → α := foldr (*) (λ x y z, by simp [mul_left_comm]) 1 attribute [to_additive multiset.sum._proof_1] prod._proof_1 attribute [to_additive multiset.sum] prod @[to_additive multiset.sum_eq_foldr] theorem prod_eq_foldr [comm_monoid α] (s : multiset α) : prod s = foldr (*) (λ x y z, by simp [mul_left_comm]) 1 s := rfl @[to_additive multiset.sum_eq_foldl] theorem prod_eq_foldl [comm_monoid α] (s : multiset α) : prod s = foldl (*) (λ x y z, by simp [mul_right_comm]) 1 s := (foldr_swap _ _ _ _).trans (by simp [mul_comm]) @[simp, to_additive multiset.coe_sum] theorem coe_prod [comm_monoid α] (l : list α) : prod ↑l = l.prod := prod_eq_foldl _ @[simp, to_additive multiset.sum_zero] theorem prod_zero [comm_monoid α] : @prod α _ 0 = 1 := rfl @[simp, to_additive multiset.sum_cons] theorem prod_cons [comm_monoid α] (a : α) (s) : prod (a :: s) = a * prod s := foldr_cons _ _ _ _ _ @[to_additive multiset.sum_singleton] theorem prod_singleton [comm_monoid α] (a : α) : prod (a :: 0) = a := by simp @[simp, to_additive multiset.sum_add] theorem prod_add [comm_monoid α] (s t : multiset α) : prod (s + t) = prod s * prod t := quotient.induction_on₂ s t $ λ l₁ l₂, by simp instance sum.is_add_monoid_hom [add_comm_monoid α] : is_add_monoid_hom (sum : multiset α → α) := { map_add := sum_add, map_zero := sum_zero } lemma prod_smul {α : Type*} [comm_monoid α] (m : multiset α) : ∀n, (add_monoid.smul n m).prod = m.prod ^ n | 0 := rfl | (n + 1) := by rw [add_monoid.add_smul, add_monoid.one_smul, _root_.pow_add, _root_.pow_one, prod_add, prod_smul n] @[simp] theorem prod_repeat [comm_monoid α] (a : α) (n : ℕ) : prod (multiset.repeat a n) = a ^ n := by simp [repeat, list.prod_repeat] @[simp] theorem sum_repeat [add_comm_monoid α] : ∀ (a : α) (n : ℕ), sum (multiset.repeat a n) = n • a := @prod_repeat (multiplicative α) _ attribute [to_additive multiset.sum_repeat] prod_repeat @[simp] lemma prod_map_one [comm_monoid γ] {m : multiset α} : prod (m.map (λa, (1 : γ))) = (1 : γ) := multiset.induction_on m (by simp) (by simp) @[simp] lemma sum_map_zero [add_comm_monoid γ] {m : multiset α} : sum (m.map (λa, (0 : γ))) = (0 : γ) := multiset.induction_on m (by simp) (by simp) attribute [to_additive multiset.sum_map_zero] prod_map_one @[simp, to_additive multiset.sum_map_add] lemma prod_map_mul [comm_monoid γ] {m : multiset α} {f g : α → γ} : prod (m.map $ λa, f a * g a) = prod (m.map f) * prod (m.map g) := multiset.induction_on m (by simp) (assume a m ih, by simp [ih]; cc) lemma prod_map_prod_map [comm_monoid γ] (m : multiset α) (n : multiset β) {f : α → β → γ} : prod (m.map $ λa, prod $ n.map $ λb, f a b) = prod (n.map $ λb, prod $ m.map $ λa, f a b) := multiset.induction_on m (by simp) (assume a m ih, by simp [ih]) lemma sum_map_sum_map [add_comm_monoid γ] : ∀ (m : multiset α) (n : multiset β) {f : α → β → γ}, sum (m.map $ λa, sum $ n.map $ λb, f a b) = sum (n.map $ λb, sum $ m.map $ λa, f a b) := @prod_map_prod_map _ _ (multiplicative γ) _ attribute [to_additive multiset.sum_map_sum_map] prod_map_prod_map lemma sum_map_mul_left [semiring β] {b : β} {s : multiset α} {f : α → β} : sum (s.map (λa, b * f a)) = b * sum (s.map f) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, mul_add]) lemma sum_map_mul_right [semiring β] {b : β} {s : multiset α} {f : α → β} : sum (s.map (λa, f a * b)) = sum (s.map f) * b := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, add_mul]) lemma prod_hom [comm_monoid α] [comm_monoid β] (f : α → β) [is_monoid_hom f] (s : multiset α) : (s.map f).prod = f s.prod := multiset.induction_on s (by simp [is_monoid_hom.map_one f]) (by simp [is_monoid_hom.map_mul f] {contextual := tt}) lemma dvd_prod [comm_semiring α] {a : α} {s : multiset α} : a ∈ s → a ∣ s.prod := quotient.induction_on s (λ l a h, by simpa using list.dvd_prod h) a lemma sum_hom [add_comm_monoid α] [add_comm_monoid β] (f : α → β) [is_add_monoid_hom f] (s : multiset α) : (s.map f).sum = f s.sum := multiset.induction_on s (by simp [is_add_monoid_hom.map_zero f]) (by simp [is_add_monoid_hom.map_add f] {contextual := tt}) attribute [to_additive multiset.sum_hom] multiset.prod_hom lemma le_sum_of_subadditive [add_comm_monoid α] [ordered_comm_monoid β] (f : α → β) (h_zero : f 0 = 0) (h_add : ∀x y, f (x + y) ≤ f x + f y) (s : multiset α) : f s.sum ≤ (s.map f).sum := multiset.induction_on s (le_of_eq h_zero) $ assume a s ih, by rw [sum_cons, map_cons, sum_cons]; from le_trans (h_add a s.sum) (add_le_add_left' ih) lemma abs_sum_le_sum_abs [discrete_linear_ordered_field α] {s : multiset α} : abs s.sum ≤ (s.map abs).sum := le_sum_of_subadditive _ abs_zero abs_add s /- join -/ /-- `join S`, where `S` is a multiset of multisets, is the lift of the list join operation, that is, the union of all the sets. join {{1, 2}, {1, 2}, {0, 1}} = {0, 1, 1, 1, 2, 2} -/ def join : multiset (multiset α) → multiset α := sum theorem coe_join : ∀ L : list (list α), join (L.map (@coe _ (multiset α) _) : multiset (multiset α)) = L.join | [] := rfl | (l :: L) := congr_arg (λ s : multiset α, ↑l + s) (coe_join L) @[simp] theorem join_zero : @join α 0 = 0 := rfl @[simp] theorem join_cons (s S) : @join α (s :: S) = s + join S := sum_cons _ _ @[simp] theorem join_add (S T) : @join α (S + T) = join S + join T := sum_add _ _ @[simp] theorem mem_join {a S} : a ∈ @join α S ↔ ∃ s ∈ S, a ∈ s := multiset.induction_on S (by simp) $ by simp [or_and_distrib_right, exists_or_distrib] {contextual := tt} @[simp] theorem card_join (S) : card (@join α S) = sum (map card S) := multiset.induction_on S (by simp) (by simp) /- bind -/ /-- `bind s f` is the monad bind operation, defined as `join (map f s)`. It is the union of `f a` as `a` ranges over `s`. -/ def bind (s : multiset α) (f : α → multiset β) : multiset β := join (map f s) @[simp] theorem coe_bind (l : list α) (f : α → list β) : @bind α β l (λ a, f a) = l.bind f := by rw [list.bind, ← coe_join, list.map_map]; refl @[simp] theorem zero_bind (f : α → multiset β) : bind 0 f = 0 := rfl @[simp] theorem cons_bind (a s) (f : α → multiset β) : bind (a::s) f = f a + bind s f := by simp [bind] @[simp] theorem add_bind (s t) (f : α → multiset β) : bind (s + t) f = bind s f + bind t f := by simp [bind] @[simp] theorem bind_zero (s : multiset α) : bind s (λa, 0 : α → multiset β) = 0 := by simp [bind, -map_const, join] @[simp] theorem bind_add (s : multiset α) (f g : α → multiset β) : bind s (λa, f a + g a) = bind s f + bind s g := by simp [bind, join] @[simp] theorem bind_cons (s : multiset α) (f : α → β) (g : α → multiset β) : bind s (λa, f a :: g a) = map f s + bind s g := multiset.induction_on s (by simp) (by simp {contextual := tt}) @[simp] theorem mem_bind {b s} {f : α → multiset β} : b ∈ bind s f ↔ ∃ a ∈ s, b ∈ f a := by simp [bind]; simp [-exists_and_distrib_right, exists_and_distrib_right.symm]; rw exists_swap; simp [and_assoc] @[simp] theorem card_bind (s) (f : α → multiset β) : card (bind s f) = sum (map (card ∘ f) s) := by simp [bind] lemma bind_congr {f g : α → multiset β} {m : multiset α} : (∀a∈m, f a = g a) → bind m f = bind m g := by simp [bind] {contextual := tt} lemma bind_hcongr {β' : Type*} {m : multiset α} {f : α → multiset β} {f' : α → multiset β'} (h : β = β') (hf : ∀a∈m, f a == f' a) : bind m f == bind m f' := begin subst h, simp at hf, simp [bind_congr hf] end lemma map_bind (m : multiset α) (n : α → multiset β) (f : β → γ) : map f (bind m n) = bind m (λa, map f (n a)) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_map (m : multiset α) (n : β → multiset γ) (f : α → β) : bind (map f m) n = bind m (λa, n (f a)) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_assoc {s : multiset α} {f : α → multiset β} {g : β → multiset γ} : (s.bind f).bind g = s.bind (λa, (f a).bind g) := multiset.induction_on s (by simp) (by simp {contextual := tt}) lemma bind_bind (m : multiset α) (n : multiset β) {f : α → β → multiset γ} : (bind m $ λa, bind n $ λb, f a b) = (bind n $ λb, bind m $ λa, f a b) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_map_comm (m : multiset α) (n : multiset β) {f : α → β → γ} : (bind m $ λa, n.map $ λb, f a b) = (bind n $ λb, m.map $ λa, f a b) := multiset.induction_on m (by simp) (by simp {contextual := tt}) @[simp, to_additive multiset.sum_bind] lemma prod_bind [comm_monoid β] (s : multiset α) (t : α → multiset β) : prod (bind s t) = prod (s.map $ λa, prod (t a)) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, cons_bind]) /- product -/ /-- The multiplicity of `(a, b)` in `product s t` is the product of the multiplicity of `a` in `s` and `b` in `t`. -/ def product (s : multiset α) (t : multiset β) : multiset (α × β) := s.bind $ λ a, t.map $ prod.mk a @[simp] theorem coe_product (l₁ : list α) (l₂ : list β) : @product α β l₁ l₂ = l₁.product l₂ := by rw [product, list.product, ← coe_bind]; simp @[simp] theorem zero_product (t) : @product α β 0 t = 0 := rfl @[simp] theorem cons_product (a : α) (s : multiset α) (t : multiset β) : product (a :: s) t = map (prod.mk a) t + product s t := by simp [product] @[simp] theorem product_singleton (a : α) (b : β) : product (a::0) (b::0) = (a,b)::0 := rfl @[simp] theorem add_product (s t : multiset α) (u : multiset β) : product (s + t) u = product s u + product t u := by simp [product] @[simp] theorem product_add (s : multiset α) : ∀ t u : multiset β, product s (t + u) = product s t + product s u := multiset.induction_on s (λ t u, rfl) $ λ a s IH t u, by rw [cons_product, IH]; simp @[simp] theorem mem_product {s t} : ∀ {p : α × β}, p ∈ @product α β s t ↔ p.1 ∈ s ∧ p.2 ∈ t | (a, b) := by simp [product, and.left_comm] @[simp] theorem card_product (s : multiset α) (t : multiset β) : card (product s t) = card s * card t := by simp [product, repeat, (∘), mul_comm] /- sigma -/ section variable {σ : α → Type*} /-- `sigma s t` is the dependent version of `product`. It is the sum of `(a, b)` as `a` ranges over `s` and `b` ranges over `t a`. -/ protected def sigma (s : multiset α) (t : Π a, multiset (σ a)) : multiset (Σ a, σ a) := s.bind $ λ a, (t a).map $ sigma.mk a @[simp] theorem coe_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) : @multiset.sigma α σ l₁ (λ a, l₂ a) = l₁.sigma l₂ := by rw [multiset.sigma, list.sigma, ← coe_bind]; simp @[simp] theorem zero_sigma (t) : @multiset.sigma α σ 0 t = 0 := rfl @[simp] theorem cons_sigma (a : α) (s : multiset α) (t : Π a, multiset (σ a)) : (a :: s).sigma t = map (sigma.mk a) (t a) + s.sigma t := by simp [multiset.sigma] @[simp] theorem sigma_singleton (a : α) (b : α → β) : (a::0).sigma (λ a, b a::0) = ⟨a, b a⟩::0 := rfl @[simp] theorem add_sigma (s t : multiset α) (u : Π a, multiset (σ a)) : (s + t).sigma u = s.sigma u + t.sigma u := by simp [multiset.sigma] @[simp] theorem sigma_add (s : multiset α) : ∀ t u : Π a, multiset (σ a), s.sigma (λ a, t a + u a) = s.sigma t + s.sigma u := multiset.induction_on s (λ t u, rfl) $ λ a s IH t u, by rw [cons_sigma, IH]; simp @[simp] theorem mem_sigma {s t} : ∀ {p : Σ a, σ a}, p ∈ @multiset.sigma α σ s t ↔ p.1 ∈ s ∧ p.2 ∈ t p.1 | ⟨a, b⟩ := by simp [multiset.sigma, and_assoc, and.left_comm] @[simp] theorem card_sigma (s : multiset α) (t : Π a, multiset (σ a)) : card (s.sigma t) = sum (map (λ a, card (t a)) s) := by simp [multiset.sigma, (∘)] end /- map for partial functions -/ /-- Lift of the list `pmap` operation. Map a partial function `f` over a multiset `s` whose elements are all in the domain of `f`. -/ def pmap {p : α → Prop} (f : Π a, p a → β) (s : multiset α) : (∀ a ∈ s, p a) → multiset β := quot.rec_on s (λ l H, ↑(pmap f l H)) $ λ l₁ l₂ (pp : l₁ ~ l₂), funext $ λ (H₂ : ∀ a ∈ l₂, p a), have H₁ : ∀ a ∈ l₁, p a, from λ a h, H₂ a ((mem_of_perm pp).1 h), have ∀ {s₂ e H}, @eq.rec (multiset α) l₁ (λ s, (∀ a ∈ s, p a) → multiset β) (λ _, ↑(pmap f l₁ H₁)) s₂ e H = ↑(pmap f l₁ H₁), by intros s₂ e _; subst e, this.trans $ quot.sound $ perm_pmap f pp @[simp] theorem coe_pmap {p : α → Prop} (f : Π a, p a → β) (l : list α) (H : ∀ a ∈ l, p a) : pmap f l H = l.pmap f H := rfl @[simp] lemma pmap_zero {p : α → Prop} (f : Π a, p a → β) (h : ∀a∈(0:multiset α), p a) : pmap f 0 h = 0 := rfl @[simp] lemma pmap_cons {p : α → Prop} (f : Π a, p a → β) (a : α) (m : multiset α) : ∀(h : ∀b∈a::m, p b), pmap f (a :: m) h = f a (h a (mem_cons_self a m)) :: pmap f m (λa ha, h a $ mem_cons_of_mem ha) := quotient.induction_on m $ assume l h, rfl /-- "Attach" a proof that `a ∈ s` to each element `a` in `s` to produce a multiset on `{x // x ∈ s}`. -/ def attach (s : multiset α) : multiset {x // x ∈ s} := pmap subtype.mk s (λ a, id) @[simp] theorem coe_attach (l : list α) : @eq (multiset {x // x ∈ l}) (@attach α l) l.attach := rfl theorem pmap_eq_map (p : α → Prop) (f : α → β) (s : multiset α) : ∀ H, @pmap _ _ p (λ a _, f a) s H = map f s := quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map p f l H theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β} (s : multiset α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) : pmap f s H₁ = pmap g s H₂ := quot.induction_on s (λ l H₁ H₂, congr_arg coe $ pmap_congr l h) H₁ H₂ theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β) (s) : ∀ H, map g (pmap f s H) = pmap (λ a h, g (f a h)) s H := quot.induction_on s $ λ l H, congr_arg coe $ map_pmap g f l H theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β) (s) : ∀ H, pmap f s H = s.attach.map (λ x, f x.1 (H _ x.2)) := quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map_attach f l H theorem attach_map_val (s : multiset α) : s.attach.map subtype.val = s := quot.induction_on s $ λ l, congr_arg coe $ attach_map_val l @[simp] theorem mem_attach (s : multiset α) : ∀ x, x ∈ s.attach := quot.induction_on s $ λ l, mem_attach _ @[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β} {s H b} : b ∈ pmap f s H ↔ ∃ a (h : a ∈ s), f a (H a h) = b := quot.induction_on s (λ l H, mem_pmap) H @[simp] theorem card_pmap {p : α → Prop} (f : Π a, p a → β) (s H) : card (pmap f s H) = card s := quot.induction_on s (λ l H, length_pmap) H @[simp] theorem card_attach {m : multiset α} : card (attach m) = card m := card_pmap _ _ _ @[simp] lemma attach_zero : (0 : multiset α).attach = 0 := rfl lemma attach_cons (a : α) (m : multiset α) : (a :: m).attach = ⟨a, mem_cons_self a m⟩ :: (m.attach.map $ λp, ⟨p.1, mem_cons_of_mem p.2⟩) := quotient.induction_on m $ assume l, congr_arg coe $ congr_arg (list.cons _) $ by rw [list.map_pmap]; exact list.pmap_congr _ (assume a' h₁ h₂, subtype.eq rfl) section decidable_pi_exists variables {m : multiset α} protected def decidable_forall_multiset {p : α → Prop} [hp : ∀a, decidable (p a)] : decidable (∀a∈m, p a) := quotient.rec_on_subsingleton m (λl, decidable_of_iff (∀a∈l, p a) $ by simp) instance decidable_dforall_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] : decidable (∀a (h : a ∈ m), p a h) := decidable_of_decidable_of_iff (@multiset.decidable_forall_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _) (iff.intro (assume h a ha, h ⟨a, ha⟩ (mem_attach _ _)) (assume h ⟨a, ha⟩ _, h _ _)) /-- decidable equality for functions whose domain is bounded by multisets -/ instance decidable_eq_pi_multiset {β : α → Type*} [h : ∀a, decidable_eq (β a)] : decidable_eq (Πa∈m, β a) := assume f g, decidable_of_iff (∀a (h : a ∈ m), f a h = g a h) (by simp [function.funext_iff]) def decidable_exists_multiset {p : α → Prop} [decidable_pred p] : decidable (∃ x ∈ m, p x) := quotient.rec_on_subsingleton m list.decidable_exists_mem instance decidable_dexists_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] : decidable (∃a (h : a ∈ m), p a h) := decidable_of_decidable_of_iff (@multiset.decidable_exists_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _) (iff.intro (λ ⟨⟨a, ha₁⟩, _, ha₂⟩, ⟨a, ha₁, ha₂⟩) (λ ⟨a, ha₁, ha₂⟩, ⟨⟨a, ha₁⟩, mem_attach _ _, ha₂⟩)) end decidable_pi_exists /- subtraction -/ section variables [decidable_eq α] {s t u : multiset α} {a b : α} /-- `s - t` is the multiset such that `count a (s - t) = count a s - count a t` for all `a`. -/ protected def sub (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.diff l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_diff_right w₁ p₂ ▸ perm_diff_left _ p₁ instance : has_sub (multiset α) := ⟨multiset.sub⟩ @[simp] theorem coe_sub (s t : list α) : (s - t : multiset α) = (s.diff t : list α) := rfl theorem sub_eq_fold_erase (s t : multiset α) : s - t = foldl erase erase_comm s t := quotient.induction_on₂ s t $ λ l₁ l₂, show ↑(l₁.diff l₂) = foldl erase erase_comm ↑l₁ ↑l₂, by rw diff_eq_foldl l₁ l₂; exact foldl_hom _ _ _ _ (λ x y, rfl) _ @[simp] theorem sub_zero (s : multiset α) : s - 0 = s := quot.induction_on s $ λ l, rfl @[simp] theorem sub_cons (a : α) (s t : multiset α) : s - a::t = s.erase a - t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ diff_cons _ _ _ theorem add_sub_of_le (h : s ≤ t) : s + (t - s) = t := begin revert t, refine multiset.induction_on s (by simp) (λ a s IH t h, _), have := cons_erase (mem_of_le h (mem_cons_self _ _)), rw [cons_add, sub_cons, IH, this], exact (cons_le_cons_iff a).1 (this.symm ▸ h) end theorem sub_add' : s - (t + u) = s - t - u := quotient.induction_on₃ s t u $ λ l₁ l₂ l₃, congr_arg coe $ diff_append _ _ _ theorem sub_add_cancel (h : t ≤ s) : s - t + t = s := by rw [add_comm, add_sub_of_le h] @[simp] theorem add_sub_cancel_left (s : multiset α) : ∀ t, s + t - s = t := multiset.induction_on s (by simp) (λ a s IH t, by rw [cons_add, sub_cons, erase_cons_head, IH]) @[simp] theorem add_sub_cancel (s t : multiset α) : s + t - t = s := by rw [add_comm, add_sub_cancel_left] theorem sub_le_sub_right (h : s ≤ t) (u) : s - u ≤ t - u := by revert s t h; exact multiset.induction_on u (by simp {contextual := tt}) (λ a u IH s t h, by simp [IH, erase_le_erase a h]) theorem sub_le_sub_left (h : s ≤ t) : ∀ u, u - t ≤ u - s := le_induction_on h $ λ l₁ l₂ h, begin induction h with l₁ l₂ a s IH l₁ l₂ a s IH; intro u, { refl }, { rw [← cons_coe, sub_cons], exact le_trans (sub_le_sub_right (erase_le _ _) _) (IH u) }, { rw [← cons_coe, sub_cons, ← cons_coe, sub_cons], exact IH _ } end theorem sub_le_iff_le_add : s - t ≤ u ↔ s ≤ u + t := by revert s; exact multiset.induction_on t (by simp) (λ a t IH s, by simp [IH, erase_le_iff_le_cons]) theorem le_sub_add (s t : multiset α) : s ≤ s - t + t := sub_le_iff_le_add.1 (le_refl _) theorem sub_le_self (s t : multiset α) : s - t ≤ s := sub_le_iff_le_add.2 (le_add_right _ _) @[simp] theorem card_sub {s t : multiset α} (h : t ≤ s) : card (s - t) = card s - card t := (nat.sub_eq_of_eq_add $ by rw [add_comm, ← card_add, sub_add_cancel h]).symm /- union -/ /-- `s ∪ t` is the lattice join operation with respect to the multiset `≤`. The multiplicity of `a` in `s ∪ t` is the maximum of the multiplicities in `s` and `t`. -/ def union (s t : multiset α) : multiset α := s - t + t instance : has_union (multiset α) := ⟨union⟩ theorem union_def (s t : multiset α) : s ∪ t = s - t + t := rfl theorem le_union_left (s t : multiset α) : s ≤ s ∪ t := le_sub_add _ _ theorem le_union_right (s t : multiset α) : t ≤ s ∪ t := le_add_left _ _ theorem eq_union_left : t ≤ s → s ∪ t = s := sub_add_cancel theorem union_le_union_right (h : s ≤ t) (u) : s ∪ u ≤ t ∪ u := add_le_add_right (sub_le_sub_right h _) u theorem union_le (h₁ : s ≤ u) (h₂ : t ≤ u) : s ∪ t ≤ u := by rw ← eq_union_left h₂; exact union_le_union_right h₁ t @[simp] theorem mem_union : a ∈ s ∪ t ↔ a ∈ s ∨ a ∈ t := ⟨λ h, (mem_add.1 h).imp_left (mem_of_le $ sub_le_self _ _), or.rec (mem_of_le $ le_union_left _ _) (mem_of_le $ le_union_right _ _)⟩ @[simp] theorem map_union [decidable_eq β] {f : α → β} (finj : function.injective f) {s t : multiset α} : map f (s ∪ t) = map f s ∪ map f t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe (by rw [list.map_append f, list.map_diff finj]) /- inter -/ /-- `s ∩ t` is the lattice meet operation with respect to the multiset `≤`. The multiplicity of `a` in `s ∩ t` is the minimum of the multiplicities in `s` and `t`. -/ def inter (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.bag_inter l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_bag_inter_right w₁ p₂ ▸ perm_bag_inter_left _ p₁ instance : has_inter (multiset α) := ⟨inter⟩ @[simp] theorem inter_zero (s : multiset α) : s ∩ 0 = 0 := quot.induction_on s $ λ l, congr_arg coe l.bag_inter_nil @[simp] theorem zero_inter (s : multiset α) : 0 ∩ s = 0 := quot.induction_on s $ λ l, congr_arg coe l.nil_bag_inter @[simp] theorem cons_inter_of_pos {a} (s : multiset α) {t} : a ∈ t → (a :: s) ∩ t = a :: s ∩ t.erase a := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ cons_bag_inter_of_pos _ h @[simp] theorem cons_inter_of_neg {a} (s : multiset α) {t} : a ∉ t → (a :: s) ∩ t = s ∩ t := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ cons_bag_inter_of_neg _ h theorem inter_le_left (s t : multiset α) : s ∩ t ≤ s := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_of_sublist $ bag_inter_sublist_left _ _ theorem inter_le_right (s : multiset α) : ∀ t, s ∩ t ≤ t := multiset.induction_on s (λ t, (zero_inter t).symm ▸ zero_le _) $ λ a s IH t, if h : a ∈ t then by simpa [h] using cons_le_cons a (IH (t.erase a)) else by simp [h, IH] theorem le_inter (h₁ : s ≤ t) (h₂ : s ≤ u) : s ≤ t ∩ u := begin revert s u, refine multiset.induction_on t _ (λ a t IH, _); intros, { simp [h₁] }, by_cases a ∈ u, { rw [cons_inter_of_pos _ h, ← erase_le_iff_le_cons], exact IH (erase_le_iff_le_cons.2 h₁) (erase_le_erase _ h₂) }, { rw cons_inter_of_neg _ h, exact IH ((le_cons_of_not_mem $ mt (mem_of_le h₂) h).1 h₁) h₂ } end @[simp] theorem mem_inter : a ∈ s ∩ t ↔ a ∈ s ∧ a ∈ t := ⟨λ h, ⟨mem_of_le (inter_le_left _ _) h, mem_of_le (inter_le_right _ _) h⟩, λ ⟨h₁, h₂⟩, by rw [← cons_erase h₁, cons_inter_of_pos _ h₂]; apply mem_cons_self⟩ instance : lattice (multiset α) := { sup := (∪), sup_le := @union_le _ _, le_sup_left := le_union_left, le_sup_right := le_union_right, inf := (∩), le_inf := @le_inter _ _, inf_le_left := inter_le_left, inf_le_right := inter_le_right, ..@multiset.partial_order α } @[simp] theorem sup_eq_union (s t : multiset α) : s ⊔ t = s ∪ t := rfl @[simp] theorem inf_eq_inter (s t : multiset α) : s ⊓ t = s ∩ t := rfl @[simp] theorem le_inter_iff : s ≤ t ∩ u ↔ s ≤ t ∧ s ≤ u := le_inf_iff @[simp] theorem union_le_iff : s ∪ t ≤ u ↔ s ≤ u ∧ t ≤ u := sup_le_iff instance : semilattice_inf_bot (multiset α) := { bot := 0, bot_le := zero_le, ..multiset.lattice.lattice } theorem union_comm (s t : multiset α) : s ∪ t = t ∪ s := sup_comm theorem inter_comm (s t : multiset α) : s ∩ t = t ∩ s := inf_comm theorem eq_union_right (h : s ≤ t) : s ∪ t = t := by rw [union_comm, eq_union_left h] theorem union_le_union_left (h : s ≤ t) (u) : u ∪ s ≤ u ∪ t := sup_le_sup_left h _ theorem union_le_add (s t : multiset α) : s ∪ t ≤ s + t := union_le (le_add_right _ _) (le_add_left _ _) theorem union_add_distrib (s t u : multiset α) : (s ∪ t) + u = (s + u) ∪ (t + u) := by simpa [(∪), union, eq_comm] using show s + u - (t + u) = s - t, by rw [add_comm t, sub_add', add_sub_cancel] theorem add_union_distrib (s t u : multiset α) : s + (t ∪ u) = (s + t) ∪ (s + u) := by rw [add_comm, union_add_distrib, add_comm s, add_comm s] theorem cons_union_distrib (a : α) (s t : multiset α) : a :: (s ∪ t) = (a :: s) ∪ (a :: t) := by simpa using add_union_distrib (a::0) s t theorem inter_add_distrib (s t u : multiset α) : (s ∩ t) + u = (s + u) ∩ (t + u) := begin by_contra h, cases lt_iff_cons_le.1 (lt_of_le_of_ne (le_inter (add_le_add_right (inter_le_left s t) u) (add_le_add_right (inter_le_right s t) u)) h) with a hl, rw ← cons_add at hl, exact not_le_of_lt (lt_cons_self (s ∩ t) a) (le_inter (le_of_add_le_add_right (le_trans hl (inter_le_left _ _))) (le_of_add_le_add_right (le_trans hl (inter_le_right _ _)))) end theorem add_inter_distrib (s t u : multiset α) : s + (t ∩ u) = (s + t) ∩ (s + u) := by rw [add_comm, inter_add_distrib, add_comm s, add_comm s] theorem cons_inter_distrib (a : α) (s t : multiset α) : a :: (s ∩ t) = (a :: s) ∩ (a :: t) := by simp theorem union_add_inter (s t : multiset α) : s ∪ t + s ∩ t = s + t := begin apply le_antisymm, { rw union_add_distrib, refine union_le (add_le_add_left (inter_le_right _ _) _) _, rw add_comm, exact add_le_add_right (inter_le_left _ _) _ }, { rw [add_comm, add_inter_distrib], refine le_inter (add_le_add_right (le_union_right _ _) _) _, rw add_comm, exact add_le_add_right (le_union_left _ _) _ } end theorem sub_add_inter (s t : multiset α) : s - t + s ∩ t = s := begin rw [inter_comm], revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _), by_cases a ∈ s, { rw [cons_inter_of_pos _ h, sub_cons, add_cons, IH, cons_erase h] }, { rw [cons_inter_of_neg _ h, sub_cons, erase_of_not_mem h, IH] } end theorem sub_inter (s t : multiset α) : s - (s ∩ t) = s - t := add_right_cancel $ by rw [sub_add_inter s t, sub_add_cancel (inter_le_left _ _)] end /- filter -/ section variables {p : α → Prop} [decidable_pred p] /-- `filter p s` returns the elements in `s` (with the same multiplicities) which satisfy `p`, and removes the rest. -/ def filter (p : α → Prop) [h : decidable_pred p] (s : multiset α) : multiset α := quot.lift_on s (λ l, (filter p l : multiset α)) (λ l₁ l₂ h, quot.sound $ perm_filter p h) @[simp] theorem coe_filter (p : α → Prop) [h : decidable_pred p] (l : list α) : filter p (↑l) = l.filter p := rfl @[simp] theorem filter_zero (p : α → Prop) [h : decidable_pred p] : filter p 0 = 0 := rfl @[simp] theorem filter_cons_of_pos {a : α} (s) : p a → filter p (a::s) = a :: filter p s := quot.induction_on s $ λ l h, congr_arg coe $ filter_cons_of_pos l h @[simp] theorem filter_cons_of_neg {a : α} (s) : ¬ p a → filter p (a::s) = filter p s := quot.induction_on s $ λ l h, @congr_arg _ _ _ _ coe $ filter_cons_of_neg l h lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q] {s : multiset α} : (∀ x ∈ s, p x ↔ q x) → filter p s = filter q s := quot.induction_on s $ λ l h, congr_arg coe $ filter_congr h @[simp] theorem filter_add (s t : multiset α) : filter p (s + t) = filter p s + filter p t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ filter_append _ _ @[simp] theorem filter_le (s : multiset α) : filter p s ≤ s := quot.induction_on s $ λ l, subperm_of_sublist $ filter_sublist _ @[simp] theorem filter_subset (s : multiset α) : filter p s ⊆ s := subset_of_le $ filter_le _ @[simp] theorem mem_filter {a : α} {s} : a ∈ filter p s ↔ a ∈ s ∧ p a := quot.induction_on s $ λ l, mem_filter theorem of_mem_filter {a : α} {s} (h : a ∈ filter p s) : p a := (mem_filter.1 h).2 theorem mem_of_mem_filter {a : α} {s} (h : a ∈ filter p s) : a ∈ s := (mem_filter.1 h).1 theorem mem_filter_of_mem {a : α} {l} (m : a ∈ l) (h : p a) : a ∈ filter p l := mem_filter.2 ⟨m, h⟩ theorem filter_eq_self {s} : filter p s = s ↔ ∀ a ∈ s, p a := quot.induction_on s $ λ l, iff.trans ⟨λ h, eq_of_sublist_of_length_eq (filter_sublist _) (@congr_arg _ _ _ _ card h), congr_arg coe⟩ filter_eq_self theorem filter_eq_nil {s} : filter p s = 0 ↔ ∀ a ∈ s, ¬p a := quot.induction_on s $ λ l, iff.trans ⟨λ h, eq_nil_of_length_eq_zero (@congr_arg _ _ _ _ card h), congr_arg coe⟩ filter_eq_nil theorem filter_le_filter {s t} (h : s ≤ t) : filter p s ≤ filter p t := le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist $ filter_sublist_filter h theorem le_filter {s t} : s ≤ filter p t ↔ s ≤ t ∧ ∀ a ∈ s, p a := ⟨λ h, ⟨le_trans h (filter_le _), λ a m, of_mem_filter (mem_of_le h m)⟩, λ ⟨h, al⟩, filter_eq_self.2 al ▸ filter_le_filter h⟩ @[simp] theorem filter_sub [decidable_eq α] (s t : multiset α) : filter p (s - t) = filter p s - filter p t := begin revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _), rw [sub_cons, IH], by_cases p a, { rw [filter_cons_of_pos _ h, sub_cons], congr, by_cases m : a ∈ s, { rw [← cons_inj_right a, ← filter_cons_of_pos _ h, cons_erase (mem_filter_of_mem m h), cons_erase m] }, { rw [erase_of_not_mem m, erase_of_not_mem (mt mem_of_mem_filter m)] } }, { rw [filter_cons_of_neg _ h], by_cases m : a ∈ s, { rw [(by rw filter_cons_of_neg _ h : filter p (erase s a) = filter p (a :: erase s a)), cons_erase m] }, { rw [erase_of_not_mem m] } } end @[simp] theorem filter_union [decidable_eq α] (s t : multiset α) : filter p (s ∪ t) = filter p s ∪ filter p t := by simp [(∪), union] @[simp] theorem filter_inter [decidable_eq α] (s t : multiset α) : filter p (s ∩ t) = filter p s ∩ filter p t := le_antisymm (le_inter (filter_le_filter $ inter_le_left _ _) (filter_le_filter $ inter_le_right _ _)) $ le_filter.2 ⟨inf_le_inf (filter_le _) (filter_le _), λ a h, of_mem_filter (mem_of_le (inter_le_left _ _) h)⟩ @[simp] theorem filter_filter {q} [decidable_pred q] (s : multiset α) : filter p (filter q s) = filter (λ a, p a ∧ q a) s := quot.induction_on s $ λ l, congr_arg coe $ filter_filter l theorem filter_add_filter {q} [decidable_pred q] (s : multiset α) : filter p s + filter q s = filter (λ a, p a ∨ q a) s + filter (λ a, p a ∧ q a) s := multiset.induction_on s rfl $ λ a s IH, by by_cases p a; by_cases q a; simp * theorem filter_add_not (s : multiset α) : filter p s + filter (λ a, ¬ p a) s = s := by rw [filter_add_filter, filter_eq_self.2, filter_eq_nil.2]; simp [decidable.em] /- filter_map -/ /-- `filter_map f s` is a combination filter/map operation on `s`. The function `f : α → option β` is applied to each element of `s`; if `f a` is `some b` then `b` is added to the result, otherwise `a` is removed from the resulting multiset. -/ def filter_map (f : α → option β) (s : multiset α) : multiset β := quot.lift_on s (λ l, (filter_map f l : multiset β)) (λ l₁ l₂ h, quot.sound $perm_filter_map f h) @[simp] theorem coe_filter_map (f : α → option β) (l : list α) : filter_map f l = l.filter_map f := rfl @[simp] theorem filter_map_zero (f : α → option β) : filter_map f 0 = 0 := rfl @[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (s : multiset α) (h : f a = none) : filter_map f (a :: s) = filter_map f s := quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_none a l h @[simp] theorem filter_map_cons_some (f : α → option β) (a : α) (s : multiset α) {b : β} (h : f a = some b) : filter_map f (a :: s) = b :: filter_map f s := quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_some f a l h theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f := funext $ λ s, quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_map f) l theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] : filter_map (option.guard p) = filter p := funext $ λ s, quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_filter p) l theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (s : multiset α) : filter_map g (filter_map f s) = filter_map (λ x, (f x).bind g) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter_map f g l theorem map_filter_map (f : α → option β) (g : β → γ) (s : multiset α) : map g (filter_map f s) = filter_map (λ x, (f x).map g) s := quot.induction_on s $ λ l, congr_arg coe $ map_filter_map f g l theorem filter_map_map (f : α → β) (g : β → option γ) (s : multiset α) : filter_map g (map f s) = filter_map (g ∘ f) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_map f g l theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (s : multiset α) : filter p (filter_map f s) = filter_map (λ x, (f x).filter p) s := quot.induction_on s $ λ l, congr_arg coe $ filter_filter_map f p l theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (s : multiset α) : filter_map f (filter p s) = filter_map (λ x, if p x then f x else none) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter p f l @[simp] theorem filter_map_some (s : multiset α) : filter_map some s = s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_some l @[simp] theorem mem_filter_map (f : α → option β) (s : multiset α) {b : β} : b ∈ filter_map f s ↔ ∃ a, a ∈ s ∧ f a = some b := quot.induction_on s $ λ l, mem_filter_map f l theorem map_filter_map_of_inv (f : α → option β) (g : β → α) (H : ∀ x : α, (f x).map g = some x) (s : multiset α) : map g (filter_map f s) = s := quot.induction_on s $ λ l, congr_arg coe $ map_filter_map_of_inv f g H l theorem filter_map_le_filter_map (f : α → option β) {s t : multiset α} (h : s ≤ t) : filter_map f s ≤ filter_map f t := le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist $ filter_map_sublist_filter_map _ h /- powerset -/ def powerset_aux (l : list α) : list (multiset α) := 0 :: sublists_aux l (λ x y, x :: y) theorem powerset_aux_eq_map_coe {l : list α} : powerset_aux l = (sublists l).map coe := by simp [powerset_aux, sublists]; rw [← show @sublists_aux₁ α (multiset α) l (λ x, [↑x]) = sublists_aux l (λ x, list.cons ↑x), from sublists_aux₁_eq_sublists_aux _ _, sublists_aux_cons_eq_sublists_aux₁, ← bind_ret_eq_map, sublists_aux₁_bind]; refl @[simp] theorem mem_powerset_aux {l : list α} {s} : s ∈ powerset_aux l ↔ s ≤ ↑l := quotient.induction_on s $ by simp [powerset_aux_eq_map_coe, subperm, and.comm] def powerset_aux' (l : list α) : list (multiset α) := (sublists' l).map coe theorem powerset_aux_perm_powerset_aux' {l : list α} : powerset_aux l ~ powerset_aux' l := by rw powerset_aux_eq_map_coe; exact perm_map _ (sublists_perm_sublists' _) @[simp] theorem powerset_aux'_nil : powerset_aux' (@nil α) = [0] := rfl @[simp] theorem powerset_aux'_cons (a : α) (l : list α) : powerset_aux' (a::l) = powerset_aux' l ++ list.map (cons a) (powerset_aux' l) := by simp [powerset_aux']; refl theorem powerset_aux'_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : powerset_aux' l₁ ~ powerset_aux' l₂ := begin induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp}, { simp, exact perm_app IH (perm_map _ IH) }, { simp, apply perm_app_right, rw [← append_assoc, ← append_assoc, (by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)], exact perm_app_left _ perm_app_comm }, { exact IH₁.trans IH₂ } end theorem powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : powerset_aux l₁ ~ powerset_aux l₂ := powerset_aux_perm_powerset_aux'.trans $ (powerset_aux'_perm p).trans powerset_aux_perm_powerset_aux'.symm def powerset (s : multiset α) : multiset (multiset α) := quot.lift_on s (λ l, (powerset_aux l : multiset (multiset α))) (λ l₁ l₂ h, quot.sound (powerset_aux_perm h)) theorem powerset_coe (l : list α) : @powerset α l = ((sublists l).map coe : list (multiset α)) := congr_arg coe powerset_aux_eq_map_coe @[simp] theorem powerset_coe' (l : list α) : @powerset α l = ((sublists' l).map coe : list (multiset α)) := quot.sound powerset_aux_perm_powerset_aux' @[simp] theorem powerset_zero : @powerset α 0 = 0::0 := rfl @[simp] theorem powerset_cons (a : α) (s) : powerset (a::s) = powerset s + map (cons a) (powerset s) := quotient.induction_on s $ λ l, by simp; refl @[simp] theorem mem_powerset {s t : multiset α} : s ∈ powerset t ↔ s ≤ t := quotient.induction_on₂ s t $ by simp [subperm, and.comm] theorem map_single_le_powerset (s : multiset α) : s.map (λ a, a::0) ≤ powerset s := quotient.induction_on s $ λ l, begin simp [powerset_coe], show l.map (coe ∘ list.ret) <+~ (sublists l).map coe, rw ← list.map_map, exact subperm_of_sublist (map_sublist_map _ (map_ret_sublist_sublists _)) end @[simp] theorem card_powerset (s : multiset α) : card (powerset s) = 2 ^ card s := quotient.induction_on s $ by simp /- diagonal -/ theorem revzip_powerset_aux {l : list α} ⦃s t⦄ (h : (s, t) ∈ revzip (powerset_aux l)) : s + t = ↑l := begin rw [revzip, powerset_aux_eq_map_coe, ← map_reverse, zip_map, ← revzip] at h, simp at h, rcases h with ⟨l₁, l₂, h, rfl, rfl⟩, exact quot.sound (revzip_sublists _ _ _ h) end theorem revzip_powerset_aux' {l : list α} ⦃s t⦄ (h : (s, t) ∈ revzip (powerset_aux' l)) : s + t = ↑l := begin rw [revzip, powerset_aux', ← map_reverse, zip_map, ← revzip] at h, simp at h, rcases h with ⟨l₁, l₂, h, rfl, rfl⟩, exact quot.sound (revzip_sublists' _ _ _ h) end theorem revzip_powerset_aux_lemma [decidable_eq α] (l : list α) {l' : list (multiset α)} (H : ∀ ⦃s t⦄, (s, t) ∈ revzip l' → s + t = ↑l) : revzip l' = l'.map (λ x, (x, ↑l - x)) := begin have : forall₂ (λ (p : multiset α × multiset α) (s : multiset α), p = (s, ↑l - s)) (revzip l') ((revzip l').map prod.fst), { rw forall₂_map_right_iff, apply forall₂_same, rintro ⟨s, t⟩ h, dsimp, rw [← H h, add_sub_cancel_left] }, rw [← forall₂_eq_eq_eq, forall₂_map_right_iff], simpa end theorem revzip_powerset_aux_perm_aux' {l : list α} : revzip (powerset_aux l) ~ revzip (powerset_aux' l) := begin haveI := classical.dec_eq α, rw [revzip_powerset_aux_lemma l revzip_powerset_aux, revzip_powerset_aux_lemma l revzip_powerset_aux'], exact perm_map _ powerset_aux_perm_powerset_aux', end theorem revzip_powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : revzip (powerset_aux l₁) ~ revzip (powerset_aux l₂) := begin haveI := classical.dec_eq α, simp [λ l:list α, revzip_powerset_aux_lemma l revzip_powerset_aux, coe_eq_coe.2 p], exact perm_map _ (powerset_aux_perm p) end def diagonal (s : multiset α) : multiset (multiset α × multiset α) := quot.lift_on s (λ l, (revzip (powerset_aux l) : multiset (multiset α × multiset α))) (λ l₁ l₂ h, quot.sound (revzip_powerset_aux_perm h)) theorem diagonal_coe (l : list α) : @diagonal α l = revzip (powerset_aux l) := rfl @[simp] theorem diagonal_coe' (l : list α) : @diagonal α l = revzip (powerset_aux' l) := quot.sound revzip_powerset_aux_perm_aux' @[simp] theorem mem_diagonal {s₁ s₂ t : multiset α} : (s₁, s₂) ∈ diagonal t ↔ s₁ + s₂ = t := quotient.induction_on t $ λ l, begin simp [diagonal_coe], refine ⟨λ h, revzip_powerset_aux h, λ h, _⟩, haveI := classical.dec_eq α, simp [revzip_powerset_aux_lemma l revzip_powerset_aux, h.symm], exact ⟨_, le_add_right _ _, rfl, add_sub_cancel_left _ _⟩ end @[simp] theorem diagonal_map_fst (s : multiset α) : (diagonal s).map prod.fst = powerset s := quotient.induction_on s $ λ l, by simp [powerset_aux'] @[simp] theorem diagonal_map_snd (s : multiset α) : (diagonal s).map prod.snd = powerset s := quotient.induction_on s $ λ l, by simp [powerset_aux'] @[simp] theorem diagonal_zero : @diagonal α 0 = (0, 0)::0 := rfl @[simp] theorem diagonal_cons (a : α) (s) : diagonal (a::s) = map (prod.map id (cons a)) (diagonal s) + map (prod.map (cons a) id) (diagonal s) := quotient.induction_on s $ λ l, begin simp [revzip, reverse_append], rw [← zip_map, ← zip_map, zip_append, (_ : _++_=_)], {congr; simp}, {simp} end @[simp] theorem card_diagonal (s : multiset α) : card (diagonal s) = 2 ^ card s := by have := card_powerset s; rwa [← diagonal_map_fst, card_map] at this lemma prod_map_add [comm_semiring β] {s : multiset α} {f g : α → β} : prod (s.map (λa, f a + g a)) = sum ((diagonal s).map (λp, (p.1.map f).prod * (p.2.map g).prod)) := begin refine s.induction_on _ _, { simp }, { assume a s ih, simp [ih, add_mul, mul_comm, mul_left_comm, mul_assoc, sum_map_mul_left.symm] }, end /- countp -/ /-- `countp p s` counts the number of elements of `s` (with multiplicity) that satisfy `p`. -/ def countp (p : α → Prop) [decidable_pred p] (s : multiset α) : ℕ := quot.lift_on s (countp p) (λ l₁ l₂, perm_countp p) @[simp] theorem coe_countp (l : list α) : countp p l = l.countp p := rfl @[simp] theorem countp_zero (p : α → Prop) [decidable_pred p] : countp p 0 = 0 := rfl @[simp] theorem countp_cons_of_pos {a : α} (s) : p a → countp p (a::s) = countp p s + 1 := quot.induction_on s countp_cons_of_pos @[simp] theorem countp_cons_of_neg {a : α} (s) : ¬ p a → countp p (a::s) = countp p s := quot.induction_on s countp_cons_of_neg theorem countp_eq_card_filter (s) : countp p s = card (filter p s) := quot.induction_on s $ λ l, countp_eq_length_filter _ @[simp] theorem countp_add (s t) : countp p (s + t) = countp p s + countp p t := by simp [countp_eq_card_filter] instance countp.is_add_monoid_hom : is_add_monoid_hom (countp p : multiset α → ℕ) := { map_add := countp_add, map_zero := countp_zero _ } theorem countp_pos {s} : 0 < countp p s ↔ ∃ a ∈ s, p a := by simp [countp_eq_card_filter, card_pos_iff_exists_mem] @[simp] theorem countp_sub [decidable_eq α] {s t : multiset α} (h : t ≤ s) : countp p (s - t) = countp p s - countp p t := by simp [countp_eq_card_filter, h, filter_le_filter] theorem countp_pos_of_mem {s a} (h : a ∈ s) (pa : p a) : 0 < countp p s := countp_pos.2 ⟨_, h, pa⟩ theorem countp_le_of_le {s t} (h : s ≤ t) : countp p s ≤ countp p t := by simpa [countp_eq_card_filter] using card_le_of_le (filter_le_filter h) @[simp] theorem countp_filter {q} [decidable_pred q] (s : multiset α) : countp p (filter q s) = countp (λ a, p a ∧ q a) s := by simp [countp_eq_card_filter] end /- count -/ section variable [decidable_eq α] /-- `count a s` is the multiplicity of `a` in `s`. -/ def count (a : α) : multiset α → ℕ := countp (eq a) @[simp] theorem coe_count (a : α) (l : list α) : count a (↑l) = l.count a := coe_countp _ @[simp] theorem count_zero (a : α) : count a 0 = 0 := rfl @[simp] theorem count_cons_self (a : α) (s : multiset α) : count a (a::s) = succ (count a s) := countp_cons_of_pos _ rfl @[simp] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (s : multiset α) : count a (b::s) = count a s := countp_cons_of_neg _ h theorem count_le_of_le (a : α) {s t} : s ≤ t → count a s ≤ count a t := countp_le_of_le theorem count_le_count_cons (a b : α) (s : multiset α) : count a s ≤ count a (b :: s) := count_le_of_le _ (le_cons_self _ _) theorem count_singleton (a : α) : count a (a::0) = 1 := by simp @[simp] theorem count_add (a : α) : ∀ s t, count a (s + t) = count a s + count a t := countp_add instance count.is_add_monoid_hom (a : α) : is_add_monoid_hom (count a : multiset α → ℕ) := countp.is_add_monoid_hom @[simp] theorem count_smul (a : α) (n s) : count a (n • s) = n * count a s := by induction n; simp [*, succ_smul', succ_mul] theorem count_pos {a : α} {s : multiset α} : 0 < count a s ↔ a ∈ s := by simp [count, countp_pos] @[simp] theorem count_eq_zero_of_not_mem {a : α} {s : multiset α} (h : a ∉ s) : count a s = 0 := by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h') theorem count_eq_zero {a : α} {s : multiset α} : count a s = 0 ↔ a ∉ s := iff_not_comm.1 $ count_pos.symm.trans pos_iff_ne_zero @[simp] theorem count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n := by simp [repeat] @[simp] theorem count_erase_self (a : α) (s : multiset α) : count a (erase s a) = pred (count a s) := begin by_cases a ∈ s, { rw [(by rw cons_erase h : count a s = count a (a::erase s a)), count_cons_self]; refl }, { rw [erase_of_not_mem h, count_eq_zero.2 h]; refl } end @[simp] theorem count_erase_of_ne {a b : α} (ab : a ≠ b) (s : multiset α) : count a (erase s b) = count a s := begin by_cases b ∈ s, { rw [← count_cons_of_ne ab, cons_erase h] }, { rw [erase_of_not_mem h] } end @[simp] theorem count_sub (a : α) (s t : multiset α) : count a (s - t) = count a s - count a t := begin revert s, refine multiset.induction_on t (by simp) (λ b t IH s, _), rw [sub_cons, IH], by_cases ab : a = b, { subst b, rw [count_erase_self, count_cons_self, sub_succ, pred_sub] }, { rw [count_erase_of_ne ab, count_cons_of_ne ab] } end @[simp] theorem count_union (a : α) (s t : multiset α) : count a (s ∪ t) = max (count a s) (count a t) := by simp [(∪), union, sub_add_eq_max, -add_comm] @[simp] theorem count_inter (a : α) (s t : multiset α) : count a (s ∩ t) = min (count a s) (count a t) := begin apply @nat.add_left_cancel (count a (s - t)), rw [← count_add, sub_add_inter, count_sub, sub_add_min], end lemma count_bind {m : multiset β} {f : β → multiset α} {a : α} : count a (bind m f) = sum (m.map $ λb, count a $ f b) := multiset.induction_on m (by simp) (by simp) theorem le_count_iff_repeat_le {a : α} {s : multiset α} {n : ℕ} : n ≤ count a s ↔ repeat a n ≤ s := quot.induction_on s $ λ l, le_count_iff_repeat_sublist.trans repeat_le_coe.symm @[simp] theorem count_filter {p} [decidable_pred p] {a} {s : multiset α} (h : p a) : count a (filter p s) = count a s := quot.induction_on s $ λ l, count_filter h theorem ext {s t : multiset α} : s = t ↔ ∀ a, count a s = count a t := quotient.induction_on₂ s t $ λ l₁ l₂, quotient.eq.trans perm_iff_count @[extensionality] theorem ext' {s t : multiset α} : (∀ a, count a s = count a t) → s = t := ext.2 @[simp] theorem coe_inter (s t : list α) : (s ∩ t : multiset α) = (s.bag_inter t : list α) := by ext; simp theorem le_iff_count {s t : multiset α} : s ≤ t ↔ ∀ a, count a s ≤ count a t := ⟨λ h a, count_le_of_le a h, λ al, by rw ← (ext.2 (λ a, by simp [max_eq_right (al a)]) : s ∪ t = t); apply le_union_left⟩ instance : distrib_lattice (multiset α) := { le_sup_inf := λ s t u, le_of_eq $ eq.symm $ ext.2 $ λ a, by simp [max_min_distrib_left], ..multiset.lattice.lattice } instance : semilattice_sup_bot (multiset α) := { bot := 0, bot_le := zero_le, ..multiset.lattice.lattice } end /- relator -/ section rel /-- `rel r s t` -- lift the relation `r` between two elements to a relation between `s` and `t`, s.t. there is a one-to-one mapping betweem elements in `s` and `t` following `r`. -/ inductive rel (r : α → β → Prop) : multiset α → multiset β → Prop | zero {} : rel 0 0 | cons {a b as bs} : r a b → rel as bs → rel (a :: as) (b :: bs) run_cmd tactic.mk_iff_of_inductive_prop `multiset.rel `multiset.rel_iff variables {δ : Type*} {r : α → β → Prop} {p : γ → δ → Prop} private lemma rel_flip_aux {s t} (h : rel r s t) : rel (flip r) t s := rel.rec_on h rel.zero (assume _ _ _ _ h₀ h₁ ih, rel.cons h₀ ih) lemma rel_flip {s t} : rel (flip r) s t ↔ rel r t s := ⟨rel_flip_aux, rel_flip_aux⟩ lemma rel_eq_refl {s : multiset α} : rel (=) s s := multiset.induction_on s rel.zero (assume a s, rel.cons rfl) lemma rel_eq {s t : multiset α} : rel (=) s t ↔ s = t := begin split, { assume h, induction h; simp * }, { assume h, subst h, exact rel_eq_refl } end lemma rel.mono {p : α → β → Prop} {s t} (h : ∀a b, r a b → p a b) (hst : rel r s t) : rel p s t := begin induction hst, case rel.zero { exact rel.zero }, case rel.cons : a b s t hab hst ih { exact ih.cons (h a b hab) } end lemma rel.add {s t u v} (hst : rel r s t) (huv : rel r u v) : rel r (s + u) (t + v) := begin induction hst, case rel.zero { simpa using huv }, case rel.cons : a b s t hab hst ih { simpa using ih.cons hab } end lemma rel_flip_eq {s t : multiset α} : rel (λa b, b = a) s t ↔ s = t := show rel (flip (=)) s t ↔ s = t, by rw [rel_flip, rel_eq, eq_comm] @[simp] lemma rel_zero_left {b : multiset β} : rel r 0 b ↔ b = 0 := by rw [rel_iff]; simp @[simp] lemma rel_zero_right {a : multiset α} : rel r a 0 ↔ a = 0 := by rw [rel_iff]; simp lemma rel_cons_left {a as bs} : rel r (a :: as) bs ↔ (∃b bs', r a b ∧ rel r as bs' ∧ bs = b :: bs') := begin split, { generalize hm : a :: as = m, assume h, induction h generalizing as, case rel.zero { simp at hm, contradiction }, case rel.cons : a' b as' bs ha'b h ih { rcases cons_eq_cons.1 hm with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩, { subst eq₁, subst eq₂, exact ⟨b, bs, ha'b, h, rfl⟩ }, { rcases ih eq₂.symm with ⟨b', bs', h₁, h₂, eq⟩, exact ⟨b', b::bs', h₁, eq₁.symm ▸ rel.cons ha'b h₂, eq.symm ▸ cons_swap _ _ _⟩ } } }, { exact assume ⟨b, bs', hab, h, eq⟩, eq.symm ▸ rel.cons hab h } end lemma rel_cons_right {as b bs} : rel r as (b :: bs) ↔ (∃a as', r a b ∧ rel r as' bs ∧ as = a :: as') := begin rw [← rel_flip, rel_cons_left], apply exists_congr, assume a, apply exists_congr, assume as', rw [rel_flip, flip] end lemma rel_add_left {as₀ as₁} : ∀{bs}, rel r (as₀ + as₁) bs ↔ (∃bs₀ bs₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ bs = bs₀ + bs₁) := multiset.induction_on as₀ (by simp) begin assume a s ih bs, simp only [ih, cons_add, rel_cons_left], split, { assume h, rcases h with ⟨b, bs', hab, h, rfl⟩, rcases h with ⟨bs₀, bs₁, h₀, h₁, rfl⟩, exact ⟨b :: bs₀, bs₁, ⟨b, bs₀, hab, h₀, rfl⟩, h₁, by simp⟩ }, { assume h, rcases h with ⟨bs₀, bs₁, h, h₁, rfl⟩, rcases h with ⟨b, bs, hab, h₀, rfl⟩, exact ⟨b, bs + bs₁, hab, ⟨bs, bs₁, h₀, h₁, rfl⟩, by simp⟩ } end lemma rel_add_right {as bs₀ bs₁} : rel r as (bs₀ + bs₁) ↔ (∃as₀ as₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ as = as₀ + as₁) := by rw [← rel_flip, rel_add_left]; simp [rel_flip] lemma rel_map_left {s : multiset γ} {f : γ → α} : ∀{t}, rel r (s.map f) t ↔ rel (λa b, r (f a) b) s t := multiset.induction_on s (by simp) (by simp [rel_cons_left] {contextual := tt}) lemma rel_map_right {s : multiset α} {t : multiset γ} {f : γ → β} : rel r s (t.map f) ↔ rel (λa b, r a (f b)) s t := by rw [← rel_flip, rel_map_left, ← rel_flip]; refl lemma rel_join {s t} (h : rel (rel r) s t) : rel r s.join t.join := begin induction h, case rel.zero { simp }, case rel.cons : a b s t hab hst ih { simpa using hab.add ih } end lemma rel_map {p : γ → δ → Prop} {s t} {f : α → γ} {g : β → δ} (h : (r ⇒ p) f g) (hst : rel r s t) : rel p (s.map f) (t.map g) := by rw [rel_map_left, rel_map_right]; exact hst.mono (assume a b, h) lemma rel_bind {p : γ → δ → Prop} {s t} {f : α → multiset γ} {g : β → multiset δ} (h : (r ⇒ rel p) f g) (hst : rel r s t) : rel p (s.bind f) (t.bind g) := by apply rel_join; apply rel_map; assumption lemma card_eq_card_of_rel {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) : card s = card t := by induction h; simp [*] lemma exists_mem_of_rel_of_mem {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) : ∀ {a : α} (ha : a ∈ s), ∃ b ∈ t, r a b := begin induction h with x y s t hxy hst ih, { simp }, { assume a ha, cases mem_cons.1 ha with ha ha, { exact ⟨y, mem_cons_self _ _, ha.symm ▸ hxy⟩ }, { rcases ih ha with ⟨b, hbt, hab⟩, exact ⟨b, mem_cons.2 (or.inr hbt), hab⟩ } } end end rel section map theorem map_eq_map {f : α → β} (hf : function.injective f) {s t : multiset α} : s.map f = t.map f ↔ s = t := by rw [← rel_eq, ← rel_eq, rel_map_left, rel_map_right]; simp [hf.eq_iff] theorem injective_map {f : α → β} (hf : function.injective f) : function.injective (multiset.map f) := assume x y, (map_eq_map hf).1 end map section quot theorem map_mk_eq_map_mk_of_rel {r : α → α → Prop} {s t : multiset α} (hst : s.rel r t) : s.map (quot.mk r) = t.map (quot.mk r) := rel.rec_on hst rfl $ assume a b s t hab hst ih, by simp [ih, quot.sound hab] theorem exists_multiset_eq_map_quot_mk {r : α → α → Prop} (s : multiset (quot r)) : ∃t:multiset α, s = t.map (quot.mk r) := multiset.induction_on s ⟨0, rfl⟩ $ assume a s ⟨t, ht⟩, quot.induction_on a $ assume a, ht.symm ▸ ⟨a::t, (map_cons _ _ _).symm⟩ theorem induction_on_multiset_quot {r : α → α → Prop} {p : multiset (quot r) → Prop} (s : multiset (quot r)) : (∀s:multiset α, p (s.map (quot.mk r))) → p s := match s, exists_multiset_eq_map_quot_mk s with _, ⟨t, rfl⟩ := assume h, h _ end end quot /- disjoint -/ /-- `disjoint s t` means that `s` and `t` have no elements in common. -/ def disjoint (s t : multiset α) : Prop := ∀ ⦃a⦄, a ∈ s → a ∈ t → false @[simp] theorem coe_disjoint (l₁ l₂ : list α) : @disjoint α l₁ l₂ ↔ l₁.disjoint l₂ := iff.rfl theorem disjoint.symm {s t : multiset α} (d : disjoint s t) : disjoint t s | a i₂ i₁ := d i₁ i₂ @[simp] theorem disjoint_comm {s t : multiset α} : disjoint s t ↔ disjoint t s := ⟨disjoint.symm, disjoint.symm⟩ theorem disjoint_left {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := iff.rfl theorem disjoint_right {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s := disjoint_comm theorem disjoint_iff_ne {s t : multiset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b := by simp [disjoint_left, imp_not_comm] theorem disjoint_of_subset_left {s t u : multiset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t | x m₁ := d (h m₁) theorem disjoint_of_subset_right {s t u : multiset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t | x m m₁ := d m (h m₁) theorem disjoint_of_le_left {s t u : multiset α} (h : s ≤ u) : disjoint u t → disjoint s t := disjoint_of_subset_left (subset_of_le h) theorem disjoint_of_le_right {s t u : multiset α} (h : t ≤ u) : disjoint s u → disjoint s t := disjoint_of_subset_right (subset_of_le h) @[simp] theorem zero_disjoint (l : multiset α) : disjoint 0 l | a := (not_mem_nil a).elim @[simp] theorem singleton_disjoint {l : multiset α} {a : α} : disjoint (a::0) l ↔ a ∉ l := by simp [disjoint]; refl @[simp] theorem disjoint_singleton {l : multiset α} {a : α} : disjoint l (a::0) ↔ a ∉ l := by rw disjoint_comm; simp @[simp] theorem disjoint_add_left {s t u : multiset α} : disjoint (s + t) u ↔ disjoint s u ∧ disjoint t u := by simp [disjoint, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_add_right {s t u : multiset α} : disjoint s (t + u) ↔ disjoint s t ∧ disjoint s u := disjoint_comm.trans $ by simp [disjoint_append_left] @[simp] theorem disjoint_cons_left {a : α} {s t : multiset α} : disjoint (a::s) t ↔ a ∉ t ∧ disjoint s t := (@disjoint_add_left _ (a::0) s t).trans $ by simp @[simp] theorem disjoint_cons_right {a : α} {s t : multiset α} : disjoint s (a::t) ↔ a ∉ s ∧ disjoint s t := disjoint_comm.trans $ by simp [disjoint_cons_left] theorem inter_eq_zero_iff_disjoint [decidable_eq α] {s t : multiset α} : s ∩ t = 0 ↔ disjoint s t := by rw ← subset_zero; simp [subset_iff, disjoint] @[simp] theorem disjoint_union_left [decidable_eq α] {s t u : multiset α} : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := by simp [disjoint, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_union_right [decidable_eq α] {s t u : multiset α} : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := by simp [disjoint, or_imp_distrib, forall_and_distrib] lemma disjoint_map_map {f : α → γ} {g : β → γ} {s : multiset α} {t : multiset β} : disjoint (s.map f) (t.map g) ↔ (∀a∈s, ∀b∈t, f a ≠ g b) := begin simp [disjoint], split, from assume h a ha b hb eq, h _ ha rfl _ hb eq.symm, from assume h c a ha eq₁ b hb eq₂, h _ ha _ hb (eq₂.symm ▸ eq₁) end /-- `pairwise r m` states that there exists a list of the elements s.t. `r` holds pairwise on this list. -/ def pairwise (r : α → α → Prop) (m : multiset α) : Prop := ∃l:list α, m = l ∧ l.pairwise r lemma pairwise_coe_iff_pairwise {r : α → α → Prop} (hr : symmetric r) {l : list α} : multiset.pairwise r l ↔ l.pairwise r := iff.intro (assume ⟨l', eq, h⟩, (list.perm_pairwise hr (quotient.exact eq)).2 h) (assume h, ⟨l, rfl, h⟩) /- 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 $ perm_nodup p) @[simp] theorem coe_nodup {l : list α} : @nodup α l ↔ l.nodup := iff.rfl @[simp] theorem forall_mem_ne {a : α} {l : list α} : (∀ (a' : α), a' ∈ l → ¬a = a') ↔ a ∉ l := ⟨λ h m, h _ m rfl, λ h a' m e, h (e.symm ▸ m)⟩ @[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 theorem nodup_cons_of_nodup {a : α} {s : multiset α} (m : a ∉ s) (n : nodup s) : nodup (a::s) := nodup_cons.2 ⟨m, n⟩ theorem nodup_singleton : ∀ a : α, nodup (a::0) := nodup_singleton theorem nodup_of_nodup_cons {a : α} {s : multiset α} (h : nodup (a::s)) : nodup s := (nodup_cons.1 h).2 theorem not_mem_of_nodup_cons {a : α} {s : multiset α} (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_of_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 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 pairwise_of_nodup {r : α → α → Prop} {s : multiset α} : (∀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 forall_of_pairwise {r : α → α → Prop} (H : symmetric r) {s : multiset α} (hs : pairwise r s) : (∀a∈s, ∀b∈s, a ≠ b → r a b) := let ⟨l, hl₁, hl₂⟩ := hs in hl₁.symm ▸ list.forall_of_pairwise H hl₂ 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 theorem nodup_add_of_nodup {s t : multiset α} (d₁ : nodup s) (d₂ : nodup t) : nodup (s + t) ↔ disjoint s t := by simp [nodup_add, d₁, d₂] theorem nodup_of_nodup_map (f : α → β) {s : multiset α} : nodup (map f s) → nodup s := quot.induction_on s $ λ l, nodup_of_nodup_map f theorem nodup_map_on {f : α → β} {s : multiset α} : (∀x∈s, ∀y∈s, f x = f y → x = y) → nodup s → nodup (map f s) := quot.induction_on s $ λ l, nodup_map_on theorem nodup_map {f : α → β} {s : multiset α} (hf : function.injective f) : nodup s → nodup (map f s) := nodup_map_on (λ x _ y _ h, hf h) theorem 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 theorem 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 theorem 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 $ nodup_erase_eq_filter a d theorem nodup_erase_of_nodup [decidable_eq α] (a : α) {l} : nodup l → nodup (l.erase a) := nodup_of_le (erase_le _ _) theorem mem_erase_iff_of_nodup [decidable_eq α] {a b : α} {l} (d : nodup l) : a ∈ l.erase b ↔ a ≠ b ∧ a ∈ l := by rw nodup_erase_eq_filter b d; simp [and_comm] theorem mem_erase_of_nodup [decidable_eq α] {a : α} {l} (h : nodup l) : a ∉ l.erase a := by rw mem_erase_iff_of_nodup h; simp theorem nodup_product {s : multiset α} {t : multiset β} : nodup s → nodup t → nodup (product s t) := quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, by simp [nodup_product d₁ d₂] theorem nodup_sigma {σ : α → Type*} {s : multiset α} {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 theorem nodup_filter_map (f : α → option β) {s : multiset α} (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 _ theorem nodup_inter_left [decidable_eq α] {s : multiset α} (t) : nodup s → nodup (s ∩ t) := nodup_of_le $ inter_le_left _ _ theorem nodup_inter_right [decidable_eq α] (s) {t : multiset α} : 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_nodup_map _ (nodup_of_le (map_single_le_powerset _) h), quotient.induction_on s $ λ l h, by simp; refine list.nodup_map_on _ (nodup_sublists'.2 h); exact λ x sx y sy e, (perm_ext_sublist_nodup h (mem_sublists'.1 sx) (mem_sublists'.1 sy)).1 (quotient.exact e)⟩ @[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] theorem 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, subperm_of_subset_nodup d⟩ 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 (sub_le_self _ _) h, λ h', by refine count_eq_zero.1 _ h; rw [count_sub a s t, nat.sub_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_sub_add _ _) h₁) h₂⟩ section variable [decidable_eq α] /- erase_dup -/ /-- `erase_dup s` removes duplicates from `s`, yielding a `nodup` multiset. -/ def erase_dup (s : multiset α) : multiset α := quot.lift_on s (λ l, (l.erase_dup : multiset α)) (λ s t p, quot.sound (perm_erase_dup_of_perm p)) @[simp] theorem coe_erase_dup (l : list α) : @erase_dup α _ l = l.erase_dup := rfl @[simp] theorem erase_dup_zero : @erase_dup α _ 0 = 0 := rfl @[simp] theorem mem_erase_dup {a : α} {s : multiset α} : a ∈ erase_dup s ↔ a ∈ s := quot.induction_on s $ λ l, mem_erase_dup @[simp] theorem erase_dup_cons_of_mem {a : α} {s : multiset α} : a ∈ s → erase_dup (a::s) = erase_dup s := quot.induction_on s $ λ l m, @congr_arg _ _ _ _ coe $ erase_dup_cons_of_mem m @[simp] theorem erase_dup_cons_of_not_mem {a : α} {s : multiset α} : a ∉ s → erase_dup (a::s) = a :: erase_dup s := quot.induction_on s $ λ l m, congr_arg coe $ erase_dup_cons_of_not_mem m theorem erase_dup_le (s : multiset α) : erase_dup s ≤ s := quot.induction_on s $ λ l, subperm_of_sublist $ erase_dup_sublist _ theorem erase_dup_subset (s : multiset α) : erase_dup s ⊆ s := subset_of_le $ erase_dup_le _ theorem subset_erase_dup (s : multiset α) : s ⊆ erase_dup s := λ a, mem_erase_dup.2 @[simp] theorem erase_dup_subset' {s t : multiset α} : erase_dup s ⊆ t ↔ s ⊆ t := ⟨subset.trans (subset_erase_dup _), subset.trans (erase_dup_subset _)⟩ @[simp] theorem subset_erase_dup' {s t : multiset α} : s ⊆ erase_dup t ↔ s ⊆ t := ⟨λ h, subset.trans h (erase_dup_subset _), λ h, subset.trans h (subset_erase_dup _)⟩ @[simp] theorem nodup_erase_dup (s : multiset α) : nodup (erase_dup s) := quot.induction_on s nodup_erase_dup theorem erase_dup_eq_self {s : multiset α} : erase_dup s = s ↔ nodup s := ⟨λ e, e ▸ nodup_erase_dup s, quot.induction_on s $ λ l h, congr_arg coe $ erase_dup_eq_self.2 h⟩ theorem erase_dup_eq_zero {s : multiset α} : erase_dup s = 0 ↔ s = 0 := ⟨λ h, eq_zero_of_subset_zero $ h ▸ subset_erase_dup _, λ h, h.symm ▸ erase_dup_zero⟩ @[simp] theorem erase_dup_singleton {a : α} : erase_dup (a :: 0) = a :: 0 := erase_dup_eq_self.2 $ nodup_singleton _ theorem le_erase_dup {s t : multiset α} : s ≤ erase_dup t ↔ s ≤ t ∧ nodup s := ⟨λ h, ⟨le_trans h (erase_dup_le _), nodup_of_le h (nodup_erase_dup _)⟩, λ ⟨l, d⟩, (le_iff_subset d).2 $ subset.trans (subset_of_le l) (subset_erase_dup _)⟩ theorem erase_dup_ext {s t : multiset α} : erase_dup s = erase_dup t ↔ ∀ a, a ∈ s ↔ a ∈ t := by simp [nodup_ext] theorem erase_dup_map_erase_dup_eq [decidable_eq β] (f : α → β) (s : multiset α) : erase_dup (map f (erase_dup s)) = erase_dup (map f s) := by simp [erase_dup_ext] /- finset insert -/ /-- `ndinsert a s` is the lift of the list `insert` operation. This operation does not respect multiplicities, unlike `cons`, but it is suitable as an insert operation on `finset`. -/ def ndinsert (a : α) (s : multiset α) : multiset α := quot.lift_on s (λ l, (l.insert a : multiset α)) (λ s t p, quot.sound (perm_insert a p)) @[simp] theorem coe_ndinsert (a : α) (l : list α) : ndinsert a l = (insert a l : list α) := rfl @[simp] theorem ndinsert_zero (a : α) : ndinsert a 0 = a::0 := rfl @[simp] theorem ndinsert_of_mem {a : α} {s : multiset α} : a ∈ s → ndinsert a s = s := quot.induction_on s $ λ l h, congr_arg coe $ insert_of_mem h @[simp] theorem ndinsert_of_not_mem {a : α} {s : multiset α} : a ∉ s → ndinsert a s = a :: s := quot.induction_on s $ λ l h, congr_arg coe $ insert_of_not_mem h @[simp] theorem mem_ndinsert {a b : α} {s : multiset α} : a ∈ ndinsert b s ↔ a = b ∨ a ∈ s := quot.induction_on s $ λ l, mem_insert_iff @[simp] theorem le_ndinsert_self (a : α) (s : multiset α) : s ≤ ndinsert a s := quot.induction_on s $ λ l, subperm_of_sublist $ sublist_of_suffix $ suffix_insert _ _ @[simp] theorem mem_ndinsert_self (a : α) (s : multiset α) : a ∈ ndinsert a s := mem_ndinsert.2 (or.inl rfl) @[simp] theorem mem_ndinsert_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ ndinsert b s := mem_ndinsert.2 (or.inr h) @[simp] theorem length_ndinsert_of_mem {a : α} [decidable_eq α] {s : multiset α} (h : a ∈ s) : card (ndinsert a s) = card s := by simp [h] @[simp] theorem length_ndinsert_of_not_mem {a : α} [decidable_eq α] {s : multiset α} (h : a ∉ s) : card (ndinsert a s) = card s + 1 := by simp [h] theorem erase_dup_cons {a : α} {s : multiset α} : erase_dup (a::s) = ndinsert a (erase_dup s) := by by_cases a ∈ s; simp [h] theorem nodup_ndinsert (a : α) {s : multiset α} : nodup s → nodup (ndinsert a s) := quot.induction_on s $ λ l, nodup_insert theorem ndinsert_le {a : α} {s t : multiset α} : ndinsert a s ≤ t ↔ s ≤ t ∧ a ∈ t := ⟨λ h, ⟨le_trans (le_ndinsert_self _ _) h, mem_of_le h (mem_ndinsert_self _ _)⟩, λ ⟨l, m⟩, if h : a ∈ s then by simp [h, l] else by rw [ndinsert_of_not_mem h, ← cons_erase m, cons_le_cons_iff, ← le_cons_of_not_mem h, cons_erase m]; exact l⟩ lemma attach_ndinsert (a : α) (s : multiset α) : (s.ndinsert a).attach = ndinsert ⟨a, mem_ndinsert_self a s⟩ (s.attach.map $ λp, ⟨p.1, mem_ndinsert_of_mem p.2⟩) := have eq : ∀h : ∀(p : {x // x ∈ s}), p.1 ∈ s, (λ (p : {x // x ∈ s}), ⟨p.val, h p⟩ : {x // x ∈ s} → {x // x ∈ s}) = id, from assume h, funext $ assume p, subtype.eq rfl, have ∀t (eq : s.ndinsert a = t), t.attach = ndinsert ⟨a, eq ▸ mem_ndinsert_self a s⟩ (s.attach.map $ λp, ⟨p.1, eq ▸ mem_ndinsert_of_mem p.2⟩), begin intros t ht, by_cases a ∈ s, { rw [ndinsert_of_mem h] at ht, subst ht, rw [eq, map_id, ndinsert_of_mem (mem_attach _ _)] }, { rw [ndinsert_of_not_mem h] at ht, subst ht, simp [attach_cons, h] } end, this _ rfl @[simp] theorem disjoint_ndinsert_left {a : α} {s t : multiset α} : disjoint (ndinsert a s) t ↔ a ∉ t ∧ disjoint s t := iff.trans (by simp [disjoint]) disjoint_cons_left @[simp] theorem disjoint_ndinsert_right {a : α} {s t : multiset α} : disjoint s (ndinsert a t) ↔ a ∉ s ∧ disjoint s t := disjoint_comm.trans $ by simp /- finset union -/ /-- `ndunion s t` is the lift of the list `union` operation. This operation does not respect multiplicities, unlike `s ∪ t`, but it is suitable as a union operation on `finset`. (`s ∪ t` would also work as a union operation on finset, but this is more efficient.) -/ def ndunion (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.union l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_union p₁ p₂ @[simp] theorem coe_ndunion (l₁ l₂ : list α) : @ndunion α _ l₁ l₂ = (l₁ ∪ l₂ : list α) := rfl @[simp] theorem zero_ndunion (s : multiset α) : ndunion 0 s = s := quot.induction_on s $ λ l, rfl @[simp] theorem cons_ndunion (s t : multiset α) (a : α) : ndunion (a :: s) t = ndinsert a (ndunion s t) := quotient.induction_on₂ s t $ λ l₁ l₂, rfl @[simp] theorem mem_ndunion {s t : multiset α} {a : α} : a ∈ ndunion s t ↔ a ∈ s ∨ a ∈ t := quotient.induction_on₂ s t $ λ l₁ l₂, list.mem_union theorem le_ndunion_right (s t : multiset α) : t ≤ ndunion s t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_of_sublist $ sublist_of_suffix $ suffix_union_right _ _ theorem ndunion_le_add (s t : multiset α) : ndunion s t ≤ s + t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_of_sublist $ union_sublist_append _ _ theorem ndunion_le {s t u : multiset α} : ndunion s t ≤ u ↔ s ⊆ u ∧ t ≤ u := multiset.induction_on s (by simp) (by simp [ndinsert_le, and_comm, and.left_comm] {contextual := tt}) theorem subset_ndunion_left (s t : multiset α) : s ⊆ ndunion s t := λ a h, mem_ndunion.2 $ or.inl h theorem le_ndunion_left {s} (t : multiset α) (d : nodup s) : s ≤ ndunion s t := (le_iff_subset d).2 $ subset_ndunion_left _ _ theorem ndunion_le_union (s t : multiset α) : ndunion s t ≤ s ∪ t := ndunion_le.2 ⟨subset_of_le (le_union_left _ _), le_union_right _ _⟩ theorem nodup_ndunion (s : multiset α) {t : multiset α} : nodup t → nodup (ndunion s t) := quotient.induction_on₂ s t $ λ l₁ l₂, list.nodup_union _ @[simp] theorem ndunion_eq_union {s t : multiset α} (d : nodup s) : ndunion s t = s ∪ t := le_antisymm (ndunion_le_union _ _) $ union_le (le_ndunion_left _ d) (le_ndunion_right _ _) theorem erase_dup_add (s t : multiset α) : erase_dup (s + t) = ndunion s (erase_dup t) := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ erase_dup_append _ _ /- finset inter -/ /-- `ndinter s t` is the lift of the list `∩` operation. This operation does not respect multiplicities, unlike `s ∩ t`, but it is suitable as an intersection operation on `finset`. (`s ∩ t` would also work as a union operation on finset, but this is more efficient.) -/ def ndinter (s t : multiset α) : multiset α := filter (∈ t) s @[simp] theorem coe_ndinter (l₁ l₂ : list α) : @ndinter α _ l₁ l₂ = (l₁ ∩ l₂ : list α) := rfl @[simp] theorem zero_ndinter (s : multiset α) : ndinter 0 s = 0 := rfl @[simp] theorem cons_ndinter_of_mem {a : α} (s : multiset α) {t : multiset α} (h : a ∈ t) : ndinter (a::s) t = a :: (ndinter s t) := by simp [ndinter, h] @[simp] theorem ndinter_cons_of_not_mem {a : α} (s : multiset α) {t : multiset α} (h : a ∉ t) : ndinter (a::s) t = ndinter s t := by simp [ndinter, h] @[simp] theorem mem_ndinter {s t : multiset α} {a : α} : a ∈ ndinter s t ↔ a ∈ s ∧ a ∈ t := mem_filter theorem nodup_ndinter {s : multiset α} (t : multiset α) : nodup s → nodup (ndinter s t) := nodup_filter _ theorem le_ndinter {s t u : multiset α} : s ≤ ndinter t u ↔ s ≤ t ∧ s ⊆ u := by simp [ndinter, le_filter, subset_iff] theorem ndinter_le_left (s t : multiset α) : ndinter s t ≤ s := (le_ndinter.1 (le_refl _)).1 theorem ndinter_subset_right (s t : multiset α) : ndinter s t ⊆ t := (le_ndinter.1 (le_refl _)).2 theorem ndinter_le_right {s} (t : multiset α) (d : nodup s) : ndinter s t ≤ t := (le_iff_subset $ nodup_ndinter _ d).2 (ndinter_subset_right _ _) theorem inter_le_ndinter (s t : multiset α) : s ∩ t ≤ ndinter s t := le_ndinter.2 ⟨inter_le_left _ _, subset_of_le $ inter_le_right _ _⟩ @[simp] theorem ndinter_eq_inter {s t : multiset α} (d : nodup s) : ndinter s t = s ∩ t := le_antisymm (le_inter (ndinter_le_left _ _) (ndinter_le_right _ d)) (inter_le_ndinter _ _) theorem ndinter_eq_zero_iff_disjoint {s t : multiset α} : ndinter s t = 0 ↔ disjoint s t := by rw ← subset_zero; simp [subset_iff, disjoint] end /- fold -/ section fold variables (op : α → α → α) [hc : is_commutative α op] [ha : is_associative α op] local notation a * b := op a b include hc ha /-- `fold op b s` folds a commutative associative operation `op` over the multiset `s`. -/ def fold : α → multiset α → α := foldr op (left_comm _ hc.comm ha.assoc) theorem fold_eq_foldr (b : α) (s : multiset α) : fold op b s = foldr op (left_comm _ hc.comm ha.assoc) b s := rfl @[simp] theorem coe_fold_r (b : α) (l : list α) : fold op b l = l.foldr op b := rfl theorem coe_fold_l (b : α) (l : list α) : fold op b l = l.foldl op b := (coe_foldr_swap op _ b l).trans $ by simp [hc.comm] theorem fold_eq_foldl (b : α) (s : multiset α) : fold op b s = foldl op (right_comm _ hc.comm ha.assoc) b s := quot.induction_on s $ λ l, coe_fold_l _ _ _ @[simp] theorem fold_zero (b : α) : (0 : multiset α).fold op b = b := rfl @[simp] theorem fold_cons_left : ∀ (b a : α) (s : multiset α), (a :: s).fold op b = a * s.fold op b := foldr_cons _ _ theorem fold_cons_right (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op b * a := by simp [hc.comm] theorem fold_cons'_right (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op (b * a) := by rw [fold_eq_foldl, foldl_cons, ← fold_eq_foldl] theorem fold_cons'_left (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op (a * b) := by rw [fold_cons'_right, hc.comm] theorem fold_add (b₁ b₂ : α) (s₁ s₂ : multiset α) : (s₁ + s₂).fold op (b₁ * b₂) = s₁.fold op b₁ * s₂.fold op b₂ := multiset.induction_on s₂ (by rw [add_zero, fold_zero, ← fold_cons'_right, ← fold_cons_right op]) (by simp {contextual := tt}; cc) theorem fold_singleton (b a : α) : (a::0 : multiset α).fold op b = a * b := by simp theorem fold_distrib {f g : β → α} (u₁ u₂ : α) (s : multiset β) : (s.map (λx, f x * g x)).fold op (u₁ * u₂) = (s.map f).fold op u₁ * (s.map g).fold op u₂ := multiset.induction_on s (by simp) (by simp {contextual := tt}; cc) theorem fold_hom {op' : β → β → β} [is_commutative β op'] [is_associative β op'] {m : α → β} (hm : ∀x y, m (op x y) = op' (m x) (m y)) (b : α) (s : multiset α) : (s.map m).fold op' (m b) = m (s.fold op b) := multiset.induction_on s (by simp) (by simp [hm] {contextual := tt}) theorem fold_union_inter [decidable_eq α] (s₁ s₂ : multiset α) (b₁ b₂ : α) : (s₁ ∪ s₂).fold op b₁ * (s₁ ∩ s₂).fold op b₂ = s₁.fold op b₁ * s₂.fold op b₂ := by rw [← fold_add op, union_add_inter, fold_add op] @[simp] theorem fold_erase_dup_idem [decidable_eq α] [hi : is_idempotent α op] (s : multiset α) (b : α) : (erase_dup s).fold op b = s.fold op b := multiset.induction_on s (by simp) $ λ a s IH, begin by_cases a ∈ s; simp [IH, h], show fold op b s = op a (fold op b s), rw [← cons_erase h, fold_cons_left, ← ha.assoc, hi.idempotent], end end fold theorem le_smul_erase_dup [decidable_eq α] (s : multiset α) : ∃ n : ℕ, s ≤ n • erase_dup s := ⟨(s.map (λ a, count a s)).fold max 0, le_iff_count.2 $ λ a, begin rw count_smul, by_cases a ∈ s, { refine le_trans _ (mul_le_mul_left _ $ count_pos.2 $ mem_erase_dup.2 h), have : count a s ≤ fold max 0 (map (λ a, count a s) (a :: erase s a)); [simp [le_max_left], simpa [cons_erase h]] }, { simp [count_eq_zero.2 h, nat.zero_le] } end⟩ section sup variables [semilattice_sup_bot α] /-- Supremum of a multiset: `sup {a, b, c} = a ⊔ b ⊔ c` -/ def sup (s : multiset α) : α := s.fold (⊔) ⊥ @[simp] lemma sup_zero : (0 : multiset α).sup = ⊥ := fold_zero _ _ @[simp] lemma sup_cons (a : α) (s : multiset α) : (a :: s).sup = a ⊔ s.sup := fold_cons_left _ _ _ _ @[simp] lemma sup_singleton {a : α} : (a::0).sup = a := by simp @[simp] lemma sup_add (s₁ s₂ : multiset α) : (s₁ + s₂).sup = s₁.sup ⊔ s₂.sup := eq.trans (by simp [sup]) (fold_add _ _ _ _ _) variables [decidable_eq α] @[simp] lemma sup_erase_dup (s : multiset α) : (erase_dup s).sup = s.sup := fold_erase_dup_idem _ _ _ @[simp] lemma sup_ndunion (s₁ s₂ : multiset α) : (ndunion s₁ s₂).sup = s₁.sup ⊔ s₂.sup := by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_add]; simp @[simp] lemma sup_union (s₁ s₂ : multiset α) : (s₁ ∪ s₂).sup = s₁.sup ⊔ s₂.sup := by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_add]; simp @[simp] lemma sup_ndinsert (a : α) (s : multiset α) : (ndinsert a s).sup = a ⊔ s.sup := by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_cons]; simp lemma sup_le {s : multiset α} {a : α} : s.sup ≤ a ↔ (∀b ∈ s, b ≤ a) := multiset.induction_on s (by simp) (by simp [or_imp_distrib, forall_and_distrib] {contextual := tt}) lemma le_sup {s : multiset α} {a : α} (h : a ∈ s) : a ≤ s.sup := sup_le.1 (le_refl _) _ h lemma sup_mono {s₁ s₂ : multiset α} (h : s₁ ⊆ s₂) : s₁.sup ≤ s₂.sup := sup_le.2 $ assume b hb, le_sup (h hb) end sup section inf variables [semilattice_inf_top α] /-- Infimum of a multiset: `inf {a, b, c} = a ⊓ b ⊓ c` -/ def inf (s : multiset α) : α := s.fold (⊓) ⊤ @[simp] lemma inf_zero : (0 : multiset α).inf = ⊤ := fold_zero _ _ @[simp] lemma inf_cons (a : α) (s : multiset α) : (a :: s).inf = a ⊓ s.inf := fold_cons_left _ _ _ _ @[simp] lemma inf_singleton {a : α} : (a::0).inf = a := by simp @[simp] lemma inf_add (s₁ s₂ : multiset α) : (s₁ + s₂).inf = s₁.inf ⊓ s₂.inf := eq.trans (by simp [inf]) (fold_add _ _ _ _ _) variables [decidable_eq α] @[simp] lemma inf_erase_dup (s : multiset α) : (erase_dup s).inf = s.inf := fold_erase_dup_idem _ _ _ @[simp] lemma inf_ndunion (s₁ s₂ : multiset α) : (ndunion s₁ s₂).inf = s₁.inf ⊓ s₂.inf := by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_add]; simp @[simp] lemma inf_union (s₁ s₂ : multiset α) : (s₁ ∪ s₂).inf = s₁.inf ⊓ s₂.inf := by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_add]; simp @[simp] lemma inf_ndinsert (a : α) (s : multiset α) : (ndinsert a s).inf = a ⊓ s.inf := by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_cons]; simp lemma le_inf {s : multiset α} {a : α} : a ≤ s.inf ↔ (∀b ∈ s, a ≤ b) := multiset.induction_on s (by simp) (by simp [or_imp_distrib, forall_and_distrib] {contextual := tt}) lemma inf_le {s : multiset α} {a : α} (h : a ∈ s) : s.inf ≤ a := le_inf.1 (le_refl _) _ h lemma inf_mono {s₁ s₂ : multiset α} (h : s₁ ⊆ s₂) : s₂.inf ≤ s₁.inf := le_inf.2 $ assume b hb, inf_le (h hb) end inf section sort variables (r : α → α → Prop) [decidable_rel r] [is_trans α r] [is_antisymm α r] [is_total α r] /-- `sort s` constructs a sorted list from the multiset `s`. (Uses merge sort algorithm.) -/ def sort (s : multiset α) : list α := quot.lift_on s (merge_sort r) $ λ a b h, eq_of_sorted_of_perm ((perm_merge_sort _ _).trans $ h.trans (perm_merge_sort _ _).symm) (sorted_merge_sort r _) (sorted_merge_sort r _) @[simp] theorem coe_sort (l : list α) : sort r l = merge_sort r l := rfl @[simp] theorem sort_sorted (s : multiset α) : sorted r (sort r s) := quot.induction_on s $ λ l, sorted_merge_sort r _ @[simp] theorem sort_eq (s : multiset α) : ↑(sort r s) = s := quot.induction_on s $ λ l, quot.sound $ perm_merge_sort _ _ @[simp] theorem mem_sort {s : multiset α} {a : α} : a ∈ sort r s ↔ a ∈ s := by rw [← mem_coe, sort_eq] end sort instance [has_repr α] : has_repr (multiset α) := ⟨λ s, "{" ++ string.intercalate ", " ((s.map repr).sort (≤)) ++ "}"⟩ section sections def sections (s : multiset (multiset α)) : multiset (multiset α) := multiset.rec_on s {0} (λs _ c, s.bind $ λa, c.map ((::) a)) (assume a₀ a₁ s pi, by simp [map_bind, bind_bind a₀ a₁, cons_swap]) @[simp] lemma sections_zero : sections (0 : multiset (multiset α)) = 0::0 := rfl @[simp] lemma sections_cons (s : multiset (multiset α)) (m : multiset α) : sections (m :: s) = m.bind (λa, (sections s).map ((::) a)) := rec_on_cons m s lemma coe_sections : ∀(l : list (list α)), sections ((l.map (λl:list α, (l : multiset α))) : multiset (multiset α)) = ((l.sections.map (λl:list α, (l : multiset α))) : multiset (multiset α)) | [] := rfl | (a :: l) := begin simp, rw [← cons_coe, sections_cons, bind_map_comm, coe_sections l], simp [list.sections, (∘), list.bind] end @[simp] lemma sections_add (s t : multiset (multiset α)) : sections (s + t) = (sections s).bind (λm, (sections t).map ((+) m)) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, bind_assoc, map_bind, bind_map, -add_comm]) lemma mem_sections {s : multiset (multiset α)} : ∀{a}, a ∈ sections s ↔ s.rel (λs a, a ∈ s) a := multiset.induction_on s (by simp) (assume a s ih a', by simp [ih, rel_cons_left, -exists_and_distrib_left, exists_and_distrib_left.symm, eq_comm]) lemma card_sections {s : multiset (multiset α)} : card (sections s) = prod (s.map card) := multiset.induction_on s (by simp) (by simp {contextual := tt}) lemma prod_map_sum [comm_semiring α] {s : multiset (multiset α)} : prod (s.map sum) = sum ((sections s).map prod) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, map_bind, sum_map_mul_left, sum_map_mul_right]) end sections section pi variables [decidable_eq α] {δ : α → Type*} open function def pi.cons (m : multiset α) (a : α) (b : δ a) (f : Πa∈m, δ a) : Πa'∈a::m, δ a' := λa' ha', if h : a' = a then eq.rec b h.symm else f a' $ (mem_cons.1 ha').resolve_left h def pi.empty (δ : α → Type*) : (Πa∈(0:multiset α), δ a) . lemma pi.cons_same {m : multiset α} {a : α} {b : δ a} {f : Πa∈m, δ a} (h : a ∈ a :: m) : pi.cons m a b f a h = b := dif_pos rfl lemma pi.cons_ne {m : multiset α} {a a' : α} {b : δ a} {f : Πa∈m, δ a} (h' : a' ∈ a :: m) (h : a' ≠ a) : pi.cons m a b f a' h' = f a' ((mem_cons.1 h').resolve_left h) := dif_neg h lemma pi.cons_swap {a a' : α} {b : δ a} {b' : δ a'} {m : multiset α} {f : Πa∈m, δ a} (h : a ≠ a') : pi.cons (a' :: m) a b (pi.cons m a' b' f) == pi.cons (a :: m) a' b' (pi.cons m a b f) := begin apply hfunext, { refl }, intros a'' _ h, subst h, apply hfunext, { rw [cons_swap] }, intros ha₁ ha₂ h, by_cases h₁ : a'' = a; by_cases h₂ : a'' = a'; simp [*, pi.cons_same, pi.cons_ne] at *, { subst h₁, rw [pi.cons_same, pi.cons_same] }, { subst h₂, rw [pi.cons_same, pi.cons_same] } end /-- `pi m t` constructs the Cartesian product over `t` indexed by `m`. -/ def pi (m : multiset α) (t : Πa, multiset (δ a)) : multiset (Πa∈m, δ a) := m.rec_on {pi.empty δ} (λa m (p : multiset (Πa∈m, δ a)), (t a).bind $ λb, p.map $ pi.cons m a b) begin intros a a' m n, by_cases eq : a = a', { subst eq }, { simp [map_bind, bind_bind (t a') (t a)], apply bind_hcongr, { rw [cons_swap a a'] }, intros b hb, apply bind_hcongr, { rw [cons_swap a a'] }, intros b' hb', apply map_hcongr, { rw [cons_swap a a'] }, intros f hf, exact pi.cons_swap eq } end @[simp] lemma pi_zero (t : Πa, multiset (δ a)) : pi 0 t = pi.empty δ :: 0 := rfl @[simp] lemma pi_cons (m : multiset α) (t : Πa, multiset (δ a)) (a : α) : pi (a :: m) t = ((t a).bind $ λb, (pi m t).map $ pi.cons m a b) := rec_on_cons a m lemma injective_pi_cons {a : α} {b : δ a} {s : multiset α} (hs : a ∉ s) : function.injective (pi.cons s a b) := assume f₁ f₂ eq, funext $ assume a', funext $ assume h', have ne : a ≠ a', from assume h, hs $ h.symm ▸ h', have a' ∈ a :: s, from mem_cons_of_mem h', calc f₁ a' h' = pi.cons s a b f₁ a' this : by rw [pi.cons_ne this ne.symm] ... = pi.cons s a b f₂ a' this : by rw [eq] ... = f₂ a' h' : by rw [pi.cons_ne this ne.symm] lemma card_pi (m : multiset α) (t : Πa, multiset (δ a)) : card (pi m t) = prod (m.map $ λa, card (t a)) := multiset.induction_on m (by simp) (by simp [mul_comm] {contextual := tt}) lemma nodup_pi {s : multiset α} {t : Πa, multiset (δ a)} : nodup s → (∀a∈s, nodup (t a)) → nodup (pi s t) := multiset.induction_on s (assume _ _, nodup_singleton _) begin assume a s ih hs ht, have has : a ∉ s, by simp at hs; exact hs.1, have hs : nodup s, by simp at hs; exact hs.2, simp, split, { assume b hb, from nodup_map (injective_pi_cons has) (ih hs $ assume a' h', ht a' $ mem_cons_of_mem h') }, { apply pairwise_of_nodup _ (ht a $ mem_cons_self _ _), from assume b₁ hb₁ b₂ hb₂ neb, disjoint_map_map.2 (assume f hf g hg eq, have pi.cons s a b₁ f a (mem_cons_self _ _) = pi.cons s a b₂ g a (mem_cons_self _ _), by rw [eq], neb $ show b₁ = b₂, by rwa [pi.cons_same, pi.cons_same] at this) } end lemma mem_pi (m : multiset α) (t : Πa, multiset (δ a)) : ∀f:Πa∈m, δ a, (f ∈ pi m t) ↔ (∀a (h : a ∈ m), f a h ∈ t a) := begin refine multiset.induction_on m (λ f, _) (λ a m ih f, _), { simpa using show f = pi.empty δ, by funext a ha; exact ha.elim }, simp, split, { rintro ⟨b, hb, f', hf', rfl⟩ a' ha', rw [ih] at hf', by_cases a' = a, { subst h, rwa [pi.cons_same] }, { rw [pi.cons_ne _ h], apply hf' } }, { intro hf, refine ⟨_, hf a (mem_cons_self a _), λa ha, f a (mem_cons_of_mem ha), (ih _).2 (λ a' h', hf _ _), _⟩, funext a' h', by_cases a' = a, { subst h, rw [pi.cons_same] }, { rw [pi.cons_ne _ h] } } end end pi end multiset namespace multiset instance : functor multiset := { map := @map } instance : is_lawful_functor multiset := by refine { .. }; intros; simp open is_lawful_traversable is_comm_applicative variables {F : Type u_1 → Type u_1} [applicative F] [is_comm_applicative F] variables {α' β' : Type u_1} (f : α' → F β') def traverse : multiset α' → F (multiset β') := quotient.lift (functor.map coe ∘ traversable.traverse f) begin introv p, unfold function.comp, induction p, case perm.nil { refl }, case perm.skip { have : multiset.cons <$> f p_x <*> (coe <$> traverse f p_l₁) = multiset.cons <$> f p_x <*> (coe <$> traverse f p_l₂), { rw [p_ih] }, simpa with functor_norm }, case perm.swap { have : (λa b (l:list β'), (↑(a :: b :: l) : multiset β')) <$> f p_y <*> f p_x = (λa b l, ↑(a :: b :: l)) <$> f p_x <*> f p_y, { rw [is_comm_applicative.commutative_map], congr, funext a b l, simpa [flip] using perm.swap b a l }, simp [(∘), this] with functor_norm }, case perm.trans { simp [*] } end instance : monad multiset := { pure := λ α x, x::0, bind := @bind, .. multiset.functor } instance : is_lawful_monad multiset := { bind_pure_comp_eq_map := λ α β f s, multiset.induction_on s rfl $ λ a s ih, by rw [bind_cons, map_cons, bind_zero, add_zero], pure_bind := λ α β x f, by simp only [cons_bind, zero_bind, add_zero], bind_assoc := @bind_assoc } open functor open traversable is_lawful_traversable @[simp] lemma lift_beta {α β : Type*} (x : list α) (f : list α → β) (h : ∀ a b : list α, a ≈ b → f a = f b) : quotient.lift f h (x : multiset α) = f x := quotient.lift_beta _ _ _ @[simp] lemma map_comp_coe {α β} (h : α → β) : functor.map h ∘ coe = (coe ∘ functor.map h : list α → multiset β) := by funext; simp [functor.map] lemma id_traverse {α : Type*} (x : multiset α) : traverse id.mk x = x := quotient.induction_on x (by { intro, rw [traverse,quotient.lift_beta,function.comp], simp, congr }) lemma comp_traverse {G H : Type* → Type*} [applicative G] [applicative H] [is_comm_applicative G] [is_comm_applicative H] {α β γ : Type*} (g : α → G β) (h : β → H γ) (x : multiset α) : traverse (comp.mk ∘ functor.map h ∘ g) x = comp.mk (functor.map (traverse h) (traverse g x)) := quotient.induction_on x (by intro; simp [traverse,comp_traverse] with functor_norm; simp [(<$>),(∘)] with functor_norm) lemma map_traverse {G : Type* → Type*} [applicative G] [is_comm_applicative G] {α β γ : Type*} (g : α → G β) (h : β → γ) (x : multiset α) : functor.map (functor.map h) (traverse g x) = traverse (functor.map h ∘ g) x := quotient.induction_on x (by intro; simp [traverse] with functor_norm; rw [comp_map,map_traverse]) lemma traverse_map {G : Type* → Type*} [applicative G] [is_comm_applicative G] {α β γ : Type*} (g : α → β) (h : β → G γ) (x : multiset α) : traverse h (map g x) = traverse (h ∘ g) x := quotient.induction_on x (by intro; simp [traverse]; rw [← traversable.traverse_map h g]; [ refl, apply_instance ]) lemma naturality {G H : Type* → Type*} [applicative G] [applicative H] [is_comm_applicative G] [is_comm_applicative H] (eta : applicative_transformation G H) {α β : Type*} (f : α → G β) (x : multiset α) : eta (traverse f x) = traverse (@eta _ ∘ f) x := quotient.induction_on x (by intro; simp [traverse,is_lawful_traversable.naturality] with functor_norm) section choose variables (p : α → Prop) [decidable_pred p] (l : multiset α) def choose_x : Π hp : (∃! a, a ∈ l ∧ p a), { a // a ∈ l ∧ p a } := quotient.rec_on l (λ l' ex_unique, list.choose_x p l' (exists_of_exists_unique ex_unique)) begin intros, funext hp, suffices all_equal : ∀ x y : { t // t ∈ b ∧ p t }, x = y, { apply all_equal }, { rintros ⟨x, px⟩ ⟨y, py⟩, rcases hp with ⟨z, ⟨z_mem_l, pz⟩, z_unique⟩, congr, calc x = z : z_unique x px ... = y : (z_unique y py).symm } end def choose (hp : ∃! a, a ∈ l ∧ p a) : α := choose_x p l hp lemma choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) := (choose_x p l hp).property lemma choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1 lemma choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2 end choose /- Ico -/ /-- `Ico n m` is the multiset lifted from the list `Ico n m`, e.g. the set `{n, n+1, ..., m-1}`. -/ def Ico (n m : ℕ) : multiset ℕ := Ico n m namespace Ico theorem map_add (n m k : ℕ) : (Ico n m).map ((+) k) = Ico (n + k) (m + k) := congr_arg coe $ list.Ico.map_add _ _ _ theorem map_sub (n m k : ℕ) (h : k ≤ n) : (Ico n m).map (λ x, x - k) = Ico (n - k) (m - k) := congr_arg coe $ list.Ico.map_sub _ _ _ h theorem zero_bot (n : ℕ) : Ico 0 n = range n := congr_arg coe $ list.Ico.zero_bot _ @[simp] theorem card (n m : ℕ) : (Ico n m).card = m - n := list.Ico.length _ _ theorem nodup (n m : ℕ) : nodup (Ico n m) := Ico.nodup _ _ @[simp] theorem mem {n m l : ℕ} : l ∈ Ico n m ↔ n ≤ l ∧ l < m := list.Ico.mem theorem eq_zero_of_le {n m : ℕ} (h : m ≤ n) : Ico n m = 0 := congr_arg coe $ list.Ico.eq_nil_of_le h @[simp] theorem self_eq_zero {n : ℕ} : Ico n n = 0 := eq_zero_of_le $ le_refl n @[simp] theorem eq_zero_iff {n m : ℕ} : Ico n m = 0 ↔ m ≤ n := iff.trans (coe_eq_zero _) list.Ico.eq_empty_iff lemma add_consecutive {n m l : ℕ} (hnm : n ≤ m) (hml : m ≤ l) : Ico n m + Ico m l = Ico n l := congr_arg coe $ list.Ico.append_consecutive hnm hml @[simp] lemma inter_consecutive (n m l : ℕ) : Ico n m ∩ Ico m l = 0 := congr_arg coe $ list.Ico.bag_inter_consecutive n m l @[simp] theorem succ_singleton {n : ℕ} : Ico n (n+1) = {n} := congr_arg coe $ list.Ico.succ_singleton theorem succ_top {n m : ℕ} (h : n ≤ m) : Ico n (m + 1) = m :: Ico n m := by rw [Ico, list.Ico.succ_top h, ← coe_add, add_comm]; refl theorem eq_cons {n m : ℕ} (h : n < m) : Ico n m = n :: Ico (n + 1) m := congr_arg coe $ list.Ico.eq_cons h @[simp] theorem pred_singleton {m : ℕ} (h : m > 0) : Ico (m - 1) m = {m - 1} := congr_arg coe $ list.Ico.pred_singleton h @[simp] theorem not_mem_top {n m : ℕ} : m ∉ Ico n m := list.Ico.not_mem_top lemma filter_lt_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, x < l) = Ico n m := congr_arg coe $ list.Ico.filter_lt_of_top_le hml lemma filter_lt_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, x < l) = ∅ := congr_arg coe $ list.Ico.filter_lt_of_le_bot hln lemma filter_lt_of_ge {n m l : ℕ} (hlm : l ≤ m) : (Ico n m).filter (λ x, x < l) = Ico n l := congr_arg coe $ list.Ico.filter_lt_of_ge hlm @[simp] lemma filter_lt (n m l : ℕ) : (Ico n m).filter (λ x, x < l) = Ico n (min m l) := congr_arg coe $ list.Ico.filter_lt n m l lemma filter_ge_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, x ≥ l) = Ico n m := congr_arg coe $ list.Ico.filter_ge_of_le_bot hln lemma filter_ge_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, x ≥ l) = ∅ := congr_arg coe $ list.Ico.filter_ge_of_top_le hml lemma filter_ge_of_ge {n m l : ℕ} (hnl : n ≤ l) : (Ico n m).filter (λ x, x ≥ l) = Ico l m := congr_arg coe $ list.Ico.filter_ge_of_ge hnl @[simp] lemma filter_ge (n m l : ℕ) : (Ico n m).filter (λ x, x ≥ l) = Ico (max n l) m := congr_arg coe $ list.Ico.filter_ge n m l end Ico end multiset
5d733f293ae339523a6154189709d1afbc4bf1c7
b147e1312077cdcfea8e6756207b3fa538982e12
/data/stream/basic.lean
fb5ff2c6ddbde7b0448295f9fba5ef10ed29e24b
[ "Apache-2.0" ]
permissive
SzJS/mathlib
07836ee708ca27cd18347e1e11ce7dd5afb3e926
23a5591fca0d43ee5d49d89f6f0ee07a24a6ca29
refs/heads/master
1,584,980,332,064
1,532,063,841,000
1,532,063,841,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
66
lean
import tactic data.stream attribute [extensionality] stream.ext
ccad27bc4839c4bd1021db6cf30b6e02a2d55929
94e33a31faa76775069b071adea97e86e218a8ee
/src/logic/embedding.lean
2e6de95a72255cadf19cf47b35b060d23791353f
[ "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
18,087
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import data.fun_like.embedding import data.prod.pprod import data.set.basic import data.sigma.basic import logic.equiv.basic /-! # Injective functions -/ universes u v w x namespace function /-- `α ↪ β` is a bundled injective function. -/ @[nolint has_inhabited_instance] -- depending on cardinalities, an injective function may not exist structure embedding (α : Sort*) (β : Sort*) := (to_fun : α → β) (inj' : injective to_fun) infixr ` ↪ `:25 := embedding instance {α : Sort u} {β : Sort v} : has_coe_to_fun (α ↪ β) (λ _, α → β) := ⟨embedding.to_fun⟩ initialize_simps_projections embedding (to_fun → apply) instance {α : Sort u} {β : Sort v} : embedding_like (α ↪ β) α β := { coe := embedding.to_fun, injective' := embedding.inj', coe_injective' := λ f g h, by { cases f, cases g, congr' } } instance {α β : Sort*} : can_lift (α → β) (α ↪ β) := { coe := coe_fn, cond := injective, prf := λ f hf, ⟨⟨f, hf⟩, rfl⟩ } end function section equiv variables {α : Sort u} {β : Sort v} (f : α ≃ β) /-- Convert an `α ≃ β` to `α ↪ β`. This is also available as a coercion `equiv.coe_embedding`. The explicit `equiv.to_embedding` version is preferred though, since the coercion can have issues inferring the type of the resulting embedding. For example: ```lean -- Works: example (s : finset (fin 3)) (f : equiv.perm (fin 3)) : s.map f.to_embedding = s.map f := by simp -- Error, `f` has type `fin 3 ≃ fin 3` but is expected to have type `fin 3 ↪ ?m_1 : Type ?` example (s : finset (fin 3)) (f : equiv.perm (fin 3)) : s.map f = s.map f.to_embedding := by simp ``` -/ @[simps] protected def equiv.to_embedding : α ↪ β := ⟨f, f.injective⟩ instance equiv.coe_embedding : has_coe (α ≃ β) (α ↪ β) := ⟨equiv.to_embedding⟩ @[reducible] instance equiv.perm.coe_embedding : has_coe (equiv.perm α) (α ↪ α) := equiv.coe_embedding @[simp] lemma equiv.coe_eq_to_embedding : ↑f = f.to_embedding := rfl /-- Given an equivalence to a subtype, produce an embedding to the elements of the corresponding set. -/ @[simps] def equiv.as_embedding {p : β → Prop} (e : α ≃ subtype p) : α ↪ β := ⟨coe ∘ e, subtype.coe_injective.comp e.injective⟩ @[simp] lemma equiv.as_embedding_range {α β : Sort*} {p : β → Prop} (e : α ≃ subtype p) : set.range e.as_embedding = set_of p := set.ext $ λ x, ⟨λ ⟨y, h⟩, h ▸ subtype.coe_prop (e y), λ hs, ⟨e.symm ⟨x, hs⟩, by simp⟩⟩ end equiv namespace function namespace embedding lemma coe_injective {α β} : @function.injective (α ↪ β) (α → β) coe_fn := fun_like.coe_injective @[ext] lemma ext {α β} {f g : embedding α β} (h : ∀ x, f x = g x) : f = g := fun_like.ext f g h lemma ext_iff {α β} {f g : embedding α β} : (∀ x, f x = g x) ↔ f = g := fun_like.ext_iff.symm @[simp] theorem to_fun_eq_coe {α β} (f : α ↪ β) : to_fun f = f := rfl @[simp] theorem coe_fn_mk {α β} (f : α → β) (i) : (@mk _ _ f i : α → β) = f := rfl @[simp] lemma mk_coe {α β : Type*} (f : α ↪ β) (inj) : (⟨f, inj⟩ : α ↪ β) = f := by { ext, simp } protected theorem injective {α β} (f : α ↪ β) : injective f := embedding_like.injective f lemma apply_eq_iff_eq {α β} (f : α ↪ β) (x y : α) : f x = f y ↔ x = y := embedding_like.apply_eq_iff_eq f /-- The identity map as a `function.embedding`. -/ @[refl, simps {simp_rhs := tt}] protected def refl (α : Sort*) : α ↪ α := ⟨id, injective_id⟩ /-- Composition of `f : α ↪ β` and `g : β ↪ γ`. -/ @[trans, simps {simp_rhs := tt}] protected def trans {α β γ} (f : α ↪ β) (g : β ↪ γ) : α ↪ γ := ⟨g ∘ f, g.injective.comp f.injective⟩ @[simp] lemma equiv_to_embedding_trans_symm_to_embedding {α β : Sort*} (e : α ≃ β) : e.to_embedding.trans e.symm.to_embedding = embedding.refl _ := by { ext, simp, } @[simp] lemma equiv_symm_to_embedding_trans_to_embedding {α β : Sort*} (e : α ≃ β) : e.symm.to_embedding.trans e.to_embedding = embedding.refl _ := by { ext, simp, } /-- Transfer an embedding along a pair of equivalences. -/ @[simps { fully_applied := ff }] protected def congr {α : Sort u} {β : Sort v} {γ : Sort w} {δ : Sort x} (e₁ : α ≃ β) (e₂ : γ ≃ δ) (f : α ↪ γ) : (β ↪ δ) := (equiv.to_embedding e₁.symm).trans (f.trans e₂.to_embedding) /-- A right inverse `surj_inv` of a surjective function as an `embedding`. -/ protected noncomputable def of_surjective {α β} (f : β → α) (hf : surjective f) : α ↪ β := ⟨surj_inv hf, injective_surj_inv _⟩ /-- Convert a surjective `embedding` to an `equiv` -/ protected noncomputable def equiv_of_surjective {α β} (f : α ↪ β) (hf : surjective f) : α ≃ β := equiv.of_bijective f ⟨f.injective, hf⟩ /-- There is always an embedding from an empty type. --/ protected def of_is_empty {α β} [is_empty α] : α ↪ β := ⟨is_empty_elim, is_empty_elim⟩ /-- Change the value of an embedding `f` at one point. If the prescribed image is already occupied by some `f a'`, then swap the values at these two points. -/ def set_value {α β} (f : α ↪ β) (a : α) (b : β) [∀ a', decidable (a' = a)] [∀ a', decidable (f a' = b)] : α ↪ β := ⟨λ a', if a' = a then b else if f a' = b then f a else f a', begin intros x y h, dsimp at h, split_ifs at h; try { substI b }; try { simp only [f.injective.eq_iff] at * }; cc end⟩ theorem set_value_eq {α β} (f : α ↪ β) (a : α) (b : β) [∀ a', decidable (a' = a)] [∀ a', decidable (f a' = b)] : set_value f a b a = b := by simp [set_value] /-- Embedding into `option α` using `some`. -/ @[simps { fully_applied := ff }] protected def some {α} : α ↪ option α := ⟨some, option.some_injective α⟩ /-- Embedding into `option α` using `coe`. Usually the correct synctatical form for `simp`. -/ @[simps { fully_applied := ff }] def coe_option {α} : α ↪ option α := ⟨coe, option.some_injective α⟩ /-- Embedding into `with_top α`. -/ @[simps] def coe_with_top {α} : α ↪ with_top α := { to_fun := coe, ..embedding.some} /-- Given an embedding `f : α ↪ β` and a point outside of `set.range f`, construct an embedding `option α ↪ β`. -/ @[simps] def option_elim {α β} (f : α ↪ β) (x : β) (h : x ∉ set.range f) : option α ↪ β := ⟨option.elim x f, option.injective_iff.2 ⟨f.2, h⟩⟩ /-- Equivalence between embeddings of `option α` and a sigma type over the embeddings of `α`. -/ @[simps] def option_embedding_equiv (α β) : (option α ↪ β) ≃ Σ f : α ↪ β, ↥(set.range f)ᶜ := { to_fun := λ f, ⟨coe_option.trans f, f none, λ ⟨x, hx⟩, option.some_ne_none x $ f.injective hx⟩, inv_fun := λ f, f.1.option_elim f.2 f.2.2, left_inv := λ f, ext $ by { rintro (_|_); simp [option.coe_def] }, right_inv := λ ⟨f, y, hy⟩, by { ext; simp [option.coe_def] } } /-- A version of `option.map` for `function.embedding`s. -/ @[simps { fully_applied := ff }] def option_map {α β} (f : α ↪ β) : option α ↪ option β := ⟨option.map f, option.map_injective f.injective⟩ /-- Embedding of a `subtype`. -/ def subtype {α} (p : α → Prop) : subtype p ↪ α := ⟨coe, λ _ _, subtype.ext_val⟩ @[simp] lemma coe_subtype {α} (p : α → Prop) : ⇑(subtype p) = coe := rfl /-- Choosing an element `b : β` gives an embedding of `punit` into `β`. -/ def punit {β : Sort*} (b : β) : punit ↪ β := ⟨λ _, b, by { rintros ⟨⟩ ⟨⟩ _, refl, }⟩ /-- Fixing an element `b : β` gives an embedding `α ↪ α × β`. -/ @[simps] def sectl (α : Sort*) {β : Sort*} (b : β) : α ↪ α × β := ⟨λ a, (a, b), λ a a' h, congr_arg prod.fst h⟩ /-- Fixing an element `a : α` gives an embedding `β ↪ α × β`. -/ @[simps] def sectr {α : Sort*} (a : α) (β : Sort*): β ↪ α × β := ⟨λ b, (a, b), λ b b' h, congr_arg prod.snd h⟩ /-- Restrict the codomain of an embedding. -/ def cod_restrict {α β} (p : set β) (f : α ↪ β) (H : ∀ a, f a ∈ p) : α ↪ p := ⟨λ a, ⟨f a, H a⟩, λ a b h, f.injective (@congr_arg _ _ _ _ subtype.val h)⟩ @[simp] theorem cod_restrict_apply {α β} (p) (f : α ↪ β) (H a) : cod_restrict p f H a = ⟨f a, H a⟩ := rfl /-- If `e₁` and `e₂` are embeddings, then so is `prod.map e₁ e₂ : (a, b) ↦ (e₁ a, e₂ b)`. -/ def prod_map {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : α × γ ↪ β × δ := ⟨prod.map e₁ e₂, e₁.injective.prod_map e₂.injective⟩ @[simp] lemma coe_prod_map {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : ⇑(e₁.prod_map e₂) = prod.map e₁ e₂ := rfl /-- If `e₁` and `e₂` are embeddings, then so is `λ ⟨a, b⟩, ⟨e₁ a, e₂ b⟩ : pprod α γ → pprod β δ`. -/ def pprod_map {α β γ δ : Sort*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : pprod α γ ↪ pprod β δ := ⟨λ x, ⟨e₁ x.1, e₂ x.2⟩, e₁.injective.pprod_map e₂.injective⟩ section sum open sum /-- If `e₁` and `e₂` are embeddings, then so is `sum.map e₁ e₂`. -/ def sum_map {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : α ⊕ γ ↪ β ⊕ δ := ⟨sum.map e₁ e₂, assume s₁ s₂ h, match s₁, s₂, h with | inl a₁, inl a₂, h := congr_arg inl $ e₁.injective $ inl.inj h | inr b₁, inr b₂, h := congr_arg inr $ e₂.injective $ inr.inj h end⟩ @[simp] theorem coe_sum_map {α β γ δ} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : ⇑(sum_map e₁ e₂) = sum.map e₁ e₂ := rfl /-- The embedding of `α` into the sum `α ⊕ β`. -/ @[simps] def inl {α β : Type*} : α ↪ α ⊕ β := ⟨sum.inl, λ a b, sum.inl.inj⟩ /-- The embedding of `β` into the sum `α ⊕ β`. -/ @[simps] def inr {α β : Type*} : β ↪ α ⊕ β := ⟨sum.inr, λ a b, sum.inr.inj⟩ end sum section sigma variables {α α' : Type*} {β : α → Type*} {β' : α' → Type*} /-- `sigma.mk` as an `function.embedding`. -/ @[simps apply] def sigma_mk (a : α) : β a ↪ Σ x, β x := ⟨sigma.mk a, sigma_mk_injective⟩ /-- If `f : α ↪ α'` is an embedding and `g : Π a, β α ↪ β' (f α)` is a family of embeddings, then `sigma.map f g` is an embedding. -/ @[simps apply] def sigma_map (f : α ↪ α') (g : Π a, β a ↪ β' (f a)) : (Σ a, β a) ↪ Σ a', β' a' := ⟨sigma.map f (λ a, g a), f.injective.sigma_map (λ a, (g a).injective)⟩ end sigma /-- Define an embedding `(Π a : α, β a) ↪ (Π a : α, γ a)` from a family of embeddings `e : Π a, (β a ↪ γ a)`. This embedding sends `f` to `λ a, e a (f a)`. -/ @[simps] def Pi_congr_right {α : Sort*} {β γ : α → Sort*} (e : ∀ a, β a ↪ γ a) : (Π a, β a) ↪ (Π a, γ a) := ⟨λf a, e a (f a), λ f₁ f₂ h, funext $ λ a, (e a).injective (congr_fun h a)⟩ /-- An embedding `e : α ↪ β` defines an embedding `(γ → α) ↪ (γ → β)` that sends each `f` to `e ∘ f`. -/ def arrow_congr_right {α : Sort u} {β : Sort v} {γ : Sort w} (e : α ↪ β) : (γ → α) ↪ (γ → β) := Pi_congr_right (λ _, e) @[simp] lemma arrow_congr_right_apply {α : Sort u} {β : Sort v} {γ : Sort w} (e : α ↪ β) (f : γ ↪ α) : arrow_congr_right e f = e ∘ f := rfl /-- An embedding `e : α ↪ β` defines an embedding `(α → γ) ↪ (β → γ)` for any inhabited type `γ`. This embedding sends each `f : α → γ` to a function `g : β → γ` such that `g ∘ e = f` and `g y = default` whenever `y ∉ range e`. -/ noncomputable def arrow_congr_left {α : Sort u} {β : Sort v} {γ : Sort w} [inhabited γ] (e : α ↪ β) : (α → γ) ↪ (β → γ) := ⟨λ f, extend e f default, λ f₁ f₂ h, funext $ λ x, by simpa only [extend_apply e.injective] using congr_fun h (e x)⟩ /-- Restrict both domain and codomain of an embedding. -/ protected def subtype_map {α β} {p : α → Prop} {q : β → Prop} (f : α ↪ β) (h : ∀{{x}}, p x → q (f x)) : {x : α // p x} ↪ {y : β // q y} := ⟨subtype.map f h, subtype.map_injective h f.2⟩ open set /-- `set.image` as an embedding `set α ↪ set β`. -/ @[simps apply] protected def image {α β} (f : α ↪ β) : set α ↪ set β := ⟨image f, f.2.image_injective⟩ lemma swap_apply {α β : Type*} [decidable_eq α] [decidable_eq β] (f : α ↪ β) (x y z : α) : equiv.swap (f x) (f y) (f z) = f (equiv.swap x y z) := f.injective.swap_apply x y z lemma swap_comp {α β : Type*} [decidable_eq α] [decidable_eq β] (f : α ↪ β) (x y : α) : equiv.swap (f x) (f y) ∘ f = f ∘ equiv.swap x y := f.injective.swap_comp x y end embedding end function namespace equiv open function.embedding /-- The type of embeddings `α ↪ β` is equivalent to the subtype of all injective functions `α → β`. -/ def subtype_injective_equiv_embedding (α β : Sort*) : {f : α → β // function.injective f} ≃ (α ↪ β) := { to_fun := λ f, ⟨f.val, f.property⟩, inv_fun := λ f, ⟨f, f.injective⟩, left_inv := λ f, by simp, right_inv := λ f, by {ext, refl} } /-- If `α₁ ≃ α₂` and `β₁ ≃ β₂`, then the type of embeddings `α₁ ↪ β₁` is equivalent to the type of embeddings `α₂ ↪ β₂`. -/ @[congr, simps apply] def embedding_congr {α β γ δ : Sort*} (h : α ≃ β) (h' : γ ≃ δ) : (α ↪ γ) ≃ (β ↪ δ) := { to_fun := λ f, f.congr h h', inv_fun := λ f, f.congr h.symm h'.symm, left_inv := λ x, by {ext, simp}, right_inv := λ x, by {ext, simp} } @[simp] lemma embedding_congr_refl {α β : Sort*} : embedding_congr (equiv.refl α) (equiv.refl β) = equiv.refl (α ↪ β) := by {ext, refl} @[simp] lemma embedding_congr_trans {α₁ β₁ α₂ β₂ α₃ β₃ : Sort*} (e₁ : α₁ ≃ α₂) (e₁' : β₁ ≃ β₂) (e₂ : α₂ ≃ α₃) (e₂' : β₂ ≃ β₃) : embedding_congr (e₁.trans e₂) (e₁'.trans e₂') = (embedding_congr e₁ e₁').trans (embedding_congr e₂ e₂') := rfl @[simp] lemma embedding_congr_symm {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : (embedding_congr e₁ e₂).symm = embedding_congr e₁.symm e₂.symm := rfl lemma embedding_congr_apply_trans {α₁ β₁ γ₁ α₂ β₂ γ₂ : Sort*} (ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) (ec : γ₁ ≃ γ₂) (f : α₁ ↪ β₁) (g : β₁ ↪ γ₁) : equiv.embedding_congr ea ec (f.trans g) = (equiv.embedding_congr ea eb f).trans (equiv.embedding_congr eb ec g) := by {ext, simp} @[simp] lemma refl_to_embedding {α : Type*} : (equiv.refl α).to_embedding = function.embedding.refl α := rfl @[simp] lemma trans_to_embedding {α β γ : Type*} (e : α ≃ β) (f : β ≃ γ) : (e.trans f).to_embedding = e.to_embedding.trans f.to_embedding := rfl end equiv namespace set /-- The injection map is an embedding between subsets. -/ @[simps apply] def embedding_of_subset {α} (s t : set α) (h : s ⊆ t) : s ↪ t := ⟨λ x, ⟨x.1, h x.2⟩, λ ⟨x, hx⟩ ⟨y, hy⟩ h, by { congr, injection h }⟩ end set section subtype variable {α : Type*} /-- A subtype `{x // p x ∨ q x}` over a disjunction of `p q : α → Prop` can be injectively split into a sum of subtypes `{x // p x} ⊕ {x // q x}` such that `¬ p x` is sent to the right. -/ def subtype_or_left_embedding (p q : α → Prop) [decidable_pred p] : {x // p x ∨ q x} ↪ {x // p x} ⊕ {x // q x} := ⟨λ x, if h : p x then sum.inl ⟨x, h⟩ else sum.inr ⟨x, x.prop.resolve_left h⟩, begin intros x y, dsimp only, split_ifs; simp [subtype.ext_iff] end⟩ lemma subtype_or_left_embedding_apply_left {p q : α → Prop} [decidable_pred p] (x : {x // p x ∨ q x}) (hx : p x) : subtype_or_left_embedding p q x = sum.inl ⟨x, hx⟩ := dif_pos hx lemma subtype_or_left_embedding_apply_right {p q : α → Prop} [decidable_pred p] (x : {x // p x ∨ q x}) (hx : ¬ p x) : subtype_or_left_embedding p q x = sum.inr ⟨x, x.prop.resolve_left hx⟩ := dif_neg hx /-- A subtype `{x // p x}` can be injectively sent to into a subtype `{x // q x}`, if `p x → q x` for all `x : α`. -/ @[simps] def subtype.imp_embedding (p q : α → Prop) (h : p ≤ q) : {x // p x} ↪ {x // q x} := ⟨λ x, ⟨x, h x x.prop⟩, λ x y, by simp [subtype.ext_iff]⟩ /-- A subtype `{x // p x ∨ q x}` over a disjunction of `p q : α → Prop` is equivalent to a sum of subtypes `{x // p x} ⊕ {x // q x}` such that `¬ p x` is sent to the right, when `disjoint p q`. See also `equiv.sum_compl`, for when `is_compl p q`. -/ @[simps apply] def subtype_or_equiv (p q : α → Prop) [decidable_pred p] (h : disjoint p q) : {x // p x ∨ q x} ≃ {x // p x} ⊕ {x // q x} := { to_fun := subtype_or_left_embedding p q, inv_fun := sum.elim (subtype.imp_embedding _ _ (λ x hx, (or.inl hx : p x ∨ q x))) (subtype.imp_embedding _ _ (λ x hx, (or.inr hx : p x ∨ q x))), left_inv := λ x, begin by_cases hx : p x, { rw subtype_or_left_embedding_apply_left _ hx, simp [subtype.ext_iff] }, { rw subtype_or_left_embedding_apply_right _ hx, simp [subtype.ext_iff] }, end, right_inv := λ x, begin cases x, { simp only [sum.elim_inl], rw subtype_or_left_embedding_apply_left, { simp }, { simpa using x.prop } }, { simp only [sum.elim_inr], rw subtype_or_left_embedding_apply_right, { simp }, { suffices : ¬ p x, { simpa }, intro hp, simpa using h x ⟨hp, x.prop⟩ } } end } @[simp] lemma subtype_or_equiv_symm_inl (p q : α → Prop) [decidable_pred p] (h : disjoint p q) (x : {x // p x}) : (subtype_or_equiv p q h).symm (sum.inl x) = ⟨x, or.inl x.prop⟩ := rfl @[simp] lemma subtype_or_equiv_symm_inr (p q : α → Prop) [decidable_pred p] (h : disjoint p q) (x : {x // q x}) : (subtype_or_equiv p q h).symm (sum.inr x) = ⟨x, or.inr x.prop⟩ := rfl end subtype
9230cef1331f374d1301b88fec6e4180aaa0220b
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebraic_geometry/ringed_space.lean
ff9354559ca563a7b7218fe137c98e803c5d8afe
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
7,062
lean
/- Copyright (c) 2021 Justus Springer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Justus Springer, Andrew Yang -/ import algebra.category.Ring.filtered_colimits import algebraic_geometry.sheafed_space import topology.sheaves.stalks import algebra.category.Ring.colimits import algebra.category.Ring.limits /-! # Ringed spaces > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We introduce the category of ringed spaces, as an alias for `SheafedSpace CommRing`. The facts collected in this file are typically stated for locally ringed spaces, but never actually make use of the locality of stalks. See for instance <https://stacks.math.columbia.edu/tag/01HZ>. -/ universe v open category_theory open topological_space open opposite open Top open Top.presheaf namespace algebraic_geometry /-- The type of Ringed spaces, as an abbreviation for `SheafedSpace CommRing`. -/ abbreviation RingedSpace : Type* := SheafedSpace CommRing namespace RingedSpace open SheafedSpace variables (X : RingedSpace.{v}) /-- If the germ of a section `f` is a unit in the stalk at `x`, then `f` must be a unit on some small neighborhood around `x`. -/ lemma is_unit_res_of_is_unit_germ (U : opens X) (f : X.presheaf.obj (op U)) (x : U) (h : is_unit (X.presheaf.germ x f)) : ∃ (V : opens X) (i : V ⟶ U) (hxV : x.1 ∈ V), is_unit (X.presheaf.map i.op f) := begin obtain ⟨g', heq⟩ := h.exists_right_inv, obtain ⟨V, hxV, g, rfl⟩ := X.presheaf.germ_exist x.1 g', let W := U ⊓ V, have hxW : x.1 ∈ W := ⟨x.2, hxV⟩, erw [← X.presheaf.germ_res_apply (opens.inf_le_left U V) ⟨x.1, hxW⟩ f, ← X.presheaf.germ_res_apply (opens.inf_le_right U V) ⟨x.1, hxW⟩ g, ← ring_hom.map_mul, ← ring_hom.map_one (X.presheaf.germ (⟨x.1, hxW⟩ : W))] at heq, obtain ⟨W', hxW', i₁, i₂, heq'⟩ := X.presheaf.germ_eq x.1 hxW hxW _ _ heq, use [W', i₁ ≫ opens.inf_le_left U V, hxW'], rw [ring_hom.map_one, ring_hom.map_mul, ← comp_apply, ← X.presheaf.map_comp, ← op_comp] at heq', exact is_unit_of_mul_eq_one _ _ heq', end /-- If a section `f` is a unit in each stalk, `f` must be a unit. -/ lemma is_unit_of_is_unit_germ (U : opens X) (f : X.presheaf.obj (op U)) (h : ∀ x : U, is_unit (X.presheaf.germ x f)) : is_unit f := begin -- We pick a cover of `U` by open sets `V x`, such that `f` is a unit on each `V x`. choose V iVU m h_unit using λ x : U, X.is_unit_res_of_is_unit_germ U f x (h x), have hcover : U ≤ supr V, { intros x hxU, rw [opens.mem_supr], exact ⟨⟨x, hxU⟩, m ⟨x, hxU⟩⟩ }, -- Let `g x` denote the inverse of `f` in `U x`. choose g hg using λ x : U, is_unit.exists_right_inv (h_unit x), -- We claim that these local inverses glue together to a global inverse of `f`. obtain ⟨gl, gl_spec, -⟩ := X.sheaf.exists_unique_gluing' V U iVU hcover g _, swap, { intros x y, apply section_ext X.sheaf (V x ⊓ V y), rintro ⟨z, hzVx, hzVy⟩, rw [germ_res_apply, germ_res_apply], apply (is_unit.mul_right_inj (h ⟨z, (iVU x).le hzVx⟩)).mp, erw [← X.presheaf.germ_res_apply (iVU x) ⟨z, hzVx⟩ f, ← ring_hom.map_mul, congr_arg (X.presheaf.germ (⟨z, hzVx⟩ : V x)) (hg x), germ_res_apply, ← X.presheaf.germ_res_apply (iVU y) ⟨z, hzVy⟩ f, ← ring_hom.map_mul, congr_arg (X.presheaf.germ (⟨z, hzVy⟩ : V y)) (hg y), ring_hom.map_one, ring_hom.map_one] }, apply is_unit_of_mul_eq_one f gl, apply X.sheaf.eq_of_locally_eq' V U iVU hcover, intro i, rw [ring_hom.map_one, ring_hom.map_mul, gl_spec], exact hg i, end /-- The basic open of a section `f` is the set of all points `x`, such that the germ of `f` at `x` is a unit. -/ def basic_open {U : opens X} (f : X.presheaf.obj (op U)) : opens X := { carrier := coe '' { x : U | is_unit (X.presheaf.germ x f) }, is_open' := begin rw is_open_iff_forall_mem_open, rintros _ ⟨x, hx, rfl⟩, obtain ⟨V, i, hxV, hf⟩ := X.is_unit_res_of_is_unit_germ U f x hx, use V.1, refine ⟨_, V.2, hxV⟩, intros y hy, use (⟨y, i.le hy⟩ : U), rw set.mem_set_of_eq, split, { convert ring_hom.is_unit_map (X.presheaf.germ ⟨y, hy⟩) hf, exact (X.presheaf.germ_res_apply i ⟨y, hy⟩ f).symm }, { refl } end } @[simp] lemma mem_basic_open {U : opens X} (f : X.presheaf.obj (op U)) (x : U) : ↑x ∈ X.basic_open f ↔ is_unit (X.presheaf.germ x f) := begin split, { rintro ⟨x, hx, a⟩, cases subtype.eq a, exact hx }, { intro h, exact ⟨x, h, rfl⟩ }, end @[simp] lemma mem_top_basic_open (f : X.presheaf.obj (op ⊤)) (x : X) : x ∈ X.basic_open f ↔ is_unit (X.presheaf.germ ⟨x, show x ∈ (⊤ : opens X), by trivial⟩ f) := mem_basic_open X f ⟨x, _⟩ lemma basic_open_le {U : opens X} (f : X.presheaf.obj (op U)) : X.basic_open f ≤ U := by { rintros _ ⟨x, hx, rfl⟩, exact x.2 } /-- The restriction of a section `f` to the basic open of `f` is a unit. -/ lemma is_unit_res_basic_open {U : opens X} (f : X.presheaf.obj (op U)) : is_unit (X.presheaf.map (@hom_of_le (opens X) _ _ _ (X.basic_open_le f)).op f) := begin apply is_unit_of_is_unit_germ, rintro ⟨_, ⟨x, hx, rfl⟩⟩, convert hx, rw germ_res_apply, refl, end @[simp] lemma basic_open_res {U V : (opens X)ᵒᵖ} (i : U ⟶ V) (f : X.presheaf.obj U) : @basic_open X (unop V) (X.presheaf.map i f) = (unop V) ⊓ @basic_open X (unop U) f := begin induction U using opposite.rec, induction V using opposite.rec, let g := i.unop, have : i = g.op := rfl, clear_value g, subst this, ext, split, { rintro ⟨x, (hx : is_unit _), rfl⟩, rw germ_res_apply at hx, exact ⟨x.2, g x, hx, rfl⟩ }, { rintros ⟨hxV, x, hx, rfl⟩, refine ⟨⟨x, hxV⟩, (_ : is_unit _), rfl⟩, rwa germ_res_apply } end -- This should fire before `basic_open_res`. @[simp, priority 1100] lemma basic_open_res_eq {U V : (opens X)ᵒᵖ} (i : U ⟶ V) [is_iso i] (f : X.presheaf.obj U) : @basic_open X (unop V) (X.presheaf.map i f) = @RingedSpace.basic_open X (unop U) f := begin apply le_antisymm, { rw X.basic_open_res i f, exact inf_le_right }, { have := X.basic_open_res (inv i) (X.presheaf.map i f), rw [← comp_apply, ← X.presheaf.map_comp, is_iso.hom_inv_id, X.presheaf.map_id] at this, erw this, exact inf_le_right } end @[simp] lemma basic_open_mul {U : opens X} (f g : X.presheaf.obj (op U)) : X.basic_open (f * g) = X.basic_open f ⊓ X.basic_open g := begin ext1, dsimp [RingedSpace.basic_open], rw ←set.image_inter subtype.coe_injective, congr, ext, simp_rw map_mul, exact is_unit.mul_iff, end lemma basic_open_of_is_unit {U : opens X} {f : X.presheaf.obj (op U)} (hf : is_unit f) : X.basic_open f = U := begin apply le_antisymm, { exact X.basic_open_le f }, intros x hx, erw X.mem_basic_open f (⟨x, hx⟩ : U), exact ring_hom.is_unit_map _ hf end end RingedSpace end algebraic_geometry
0d089013df6fe59c5c116091acb464f3f6c48a6f
a46270e2f76a375564f3b3e9c1bf7b635edc1f2c
/4.6.7.lean
b8ab66bb5ac6d59441dd6f749ab3b01e253caa6a
[ "CC0-1.0" ]
permissive
wudcscheme/lean-exercise
88ea2506714eac343de2a294d1132ee8ee6d3a20
5b23b9be3d361fff5e981d5be3a0a1175504b9f6
refs/heads/master
1,678,958,930,293
1,583,197,205,000
1,583,197,205,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
167
lean
#check sub_self example (x : ℤ) : x * 0 = 0 := calc x * 0 = x * (x - x): by rw sub_self x ... = x*x - x*x: by rw mul_sub x ... = 0: by rw sub_self (x*x)
48af4f18b0ddda7cd3cde024e5c38aba18148402
97f752b44fd85ec3f635078a2dd125ddae7a82b6
/hott/cubical/square.hlean
7be7f296e4d91b2af321c93b37cbdba67aa93945
[ "Apache-2.0" ]
permissive
tectronics/lean
ab977ba6be0fcd46047ddbb3c8e16e7c26710701
f38af35e0616f89c6e9d7e3eb1d48e47ee666efe
refs/heads/master
1,532,358,526,384
1,456,276,623,000
1,456,276,623,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
27,634
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Jakob von Raumer Squares in a type -/ import types.eq open eq equiv is_equiv sigma namespace eq variables {A B : Type} {a a' a'' a₀₀ a₂₀ a₄₀ a₀₂ a₂₂ a₂₄ a₀₄ a₄₂ a₄₄ a₁ a₂ a₃ a₄ : A} /-a₀₀-/ {p₁₀ p₁₀' : a₀₀ = a₂₀} /-a₂₀-/ {p₃₀ : a₂₀ = a₄₀} /-a₄₀-/ {p₀₁ p₀₁' : a₀₀ = a₀₂} /-s₁₁-/ {p₂₁ p₂₁' : a₂₀ = a₂₂} /-s₃₁-/ {p₄₁ : a₄₀ = a₄₂} /-a₀₂-/ {p₁₂ p₁₂' : a₀₂ = a₂₂} /-a₂₂-/ {p₃₂ : a₂₂ = a₄₂} /-a₄₂-/ {p₀₃ : a₀₂ = a₀₄} /-s₁₃-/ {p₂₃ : a₂₂ = a₂₄} /-s₃₃-/ {p₄₃ : a₄₂ = a₄₄} /-a₀₄-/ {p₁₄ : a₀₄ = a₂₄} /-a₂₄-/ {p₃₄ : a₂₄ = a₄₄} /-a₄₄-/ inductive square {A : Type} {a₀₀ : A} : Π{a₂₀ a₀₂ a₂₂ : A}, a₀₀ = a₂₀ → a₀₂ = a₂₂ → a₀₀ = a₀₂ → a₂₀ = a₂₂ → Type := ids : square idp idp idp idp /- square top bottom left right -/ variables {s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁} {s₃₁ : square p₃₀ p₃₂ p₂₁ p₄₁} {s₁₃ : square p₁₂ p₁₄ p₀₃ p₂₃} {s₃₃ : square p₃₂ p₃₄ p₂₃ p₄₃} definition ids [reducible] [constructor] := @square.ids definition idsquare [reducible] [constructor] (a : A) := @square.ids A a definition hrefl [unfold 4] (p : a = a') : square idp idp p p := by induction p; exact ids definition vrefl [unfold 4] (p : a = a') : square p p idp idp := by induction p; exact ids definition hrfl [reducible] [unfold 4] {p : a = a'} : square idp idp p p := !hrefl definition vrfl [reducible] [unfold 4] {p : a = a'} : square p p idp idp := !vrefl definition hdeg_square [unfold 6] {p q : a = a'} (r : p = q) : square idp idp p q := by induction r;apply hrefl definition vdeg_square [unfold 6] {p q : a = a'} (r : p = q) : square p q idp idp := by induction r;apply vrefl definition hdeg_square_idp (p : a = a') : hdeg_square (refl p) = hrfl := by cases p; reflexivity definition vdeg_square_idp (p : a = a') : vdeg_square (refl p) = vrfl := by cases p; reflexivity definition hconcat [unfold 16] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (s₃₁ : square p₃₀ p₃₂ p₂₁ p₄₁) : square (p₁₀ ⬝ p₃₀) (p₁₂ ⬝ p₃₂) p₀₁ p₄₁ := by induction s₃₁; exact s₁₁ definition vconcat [unfold 16] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (s₁₃ : square p₁₂ p₁₄ p₀₃ p₂₃) : square p₁₀ p₁₄ (p₀₁ ⬝ p₀₃) (p₂₁ ⬝ p₂₃) := by induction s₁₃; exact s₁₁ definition hinverse [unfold 10] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀⁻¹ p₁₂⁻¹ p₂₁ p₀₁ := by induction s₁₁;exact ids definition vinverse [unfold 10] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₂ p₁₀ p₀₁⁻¹ p₂₁⁻¹ := by induction s₁₁;exact ids definition eq_vconcat [unfold 11] {p : a₀₀ = a₂₀} (r : p = p₁₀) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p p₁₂ p₀₁ p₂₁ := by induction r; exact s₁₁ definition vconcat_eq [unfold 12] {p : a₀₂ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₁₂ = p) : square p₁₀ p p₀₁ p₂₁ := by induction r; exact s₁₁ definition eq_hconcat [unfold 11] {p : a₀₀ = a₀₂} (r : p = p₀₁) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀ p₁₂ p p₂₁ := by induction r; exact s₁₁ definition hconcat_eq [unfold 12] {p : a₂₀ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₂₁ = p) : square p₁₀ p₁₂ p₀₁ p := by induction r; exact s₁₁ infix ` ⬝h `:75 := hconcat --type using \tr infix ` ⬝v `:75 := vconcat --type using \tr infix ` ⬝hp `:75 := hconcat_eq --type using \tr infix ` ⬝vp `:75 := vconcat_eq --type using \tr infix ` ⬝ph `:75 := eq_hconcat --type using \tr infix ` ⬝pv `:75 := eq_vconcat --type using \tr postfix `⁻¹ʰ`:(max+1) := hinverse --type using \-1h postfix `⁻¹ᵛ`:(max+1) := vinverse --type using \-1v definition transpose [unfold 10] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₀₁ p₂₁ p₁₀ p₁₂ := by induction s₁₁;exact ids definition aps [unfold 12] {B : Type} (f : A → B) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square (ap f p₁₀) (ap f p₁₂) (ap f p₀₁) (ap f p₂₁) := by induction s₁₁;exact ids definition natural_square [unfold 8] {f g : A → B} (p : f ~ g) (q : a = a') : square (ap f q) (ap g q) (p a) (p a') := eq.rec_on q hrfl definition natural_square_tr [unfold 8] {f g : A → B} (p : f ~ g) (q : a = a') : square (p a) (p a') (ap f q) (ap g q) := eq.rec_on q vrfl /- canceling, whiskering and moving thinks along the sides of the square -/ definition whisker_tl (p : a = a₀₀) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square (p ⬝ p₁₀) p₁₂ (p ⬝ p₀₁) p₂₁ := by induction s₁₁;induction p;constructor definition whisker_br (p : a₂₂ = a) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀ (p₁₂ ⬝ p) p₀₁ (p₂₁ ⬝ p) := by induction p;exact s₁₁ definition whisker_rt (p : a = a₂₀) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square (p₁₀ ⬝ p⁻¹) p₁₂ p₀₁ (p ⬝ p₂₁) := by induction s₁₁;induction p;constructor definition whisker_tr (p : a₂₀ = a) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square (p₁₀ ⬝ p) p₁₂ p₀₁ (p⁻¹ ⬝ p₂₁) := by induction s₁₁;induction p;constructor definition whisker_bl (p : a = a₀₂) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀ (p ⬝ p₁₂) (p₀₁ ⬝ p⁻¹) p₂₁ := by induction s₁₁;induction p;constructor definition whisker_lb (p : a₀₂ = a) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀ (p⁻¹ ⬝ p₁₂) (p₀₁ ⬝ p) p₂₁ := by induction s₁₁;induction p;constructor definition cancel_tl (p : a = a₀₀) (s₁₁ : square (p ⬝ p₁₀) p₁₂ (p ⬝ p₀₁) p₂₁) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p; rewrite +idp_con at s₁₁; exact s₁₁ definition cancel_br (p : a₂₂ = a) (s₁₁ : square p₁₀ (p₁₂ ⬝ p) p₀₁ (p₂₁ ⬝ p)) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p;exact s₁₁ definition cancel_rt (p : a = a₂₀) (s₁₁ : square (p₁₀ ⬝ p⁻¹) p₁₂ p₀₁ (p ⬝ p₂₁)) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p; rewrite idp_con at s₁₁; exact s₁₁ definition cancel_tr (p : a₂₀ = a) (s₁₁ : square (p₁₀ ⬝ p) p₁₂ p₀₁ (p⁻¹ ⬝ p₂₁)) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p; rewrite [▸* at s₁₁,idp_con at s₁₁]; exact s₁₁ definition cancel_bl (p : a = a₀₂) (s₁₁ : square p₁₀ (p ⬝ p₁₂) (p₀₁ ⬝ p⁻¹) p₂₁) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p; rewrite idp_con at s₁₁; exact s₁₁ definition cancel_lb (p : a₀₂ = a) (s₁₁ : square p₁₀ (p⁻¹ ⬝ p₁₂) (p₀₁ ⬝ p) p₂₁) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p; rewrite [▸* at s₁₁,idp_con at s₁₁]; exact s₁₁ definition move_top_of_left {p : a₀₀ = a} {q : a = a₀₂} (s : square p₁₀ p₁₂ (p ⬝ q) p₂₁) : square (p⁻¹ ⬝ p₁₀) p₁₂ q p₂₁ := by apply cancel_tl p; rewrite con_inv_cancel_left; exact s definition move_top_of_left' {p : a = a₀₀} {q : a = a₀₂} (s : square p₁₀ p₁₂ (p⁻¹ ⬝ q) p₂₁) : square (p ⬝ p₁₀) p₁₂ q p₂₁ := by apply cancel_tl p⁻¹; rewrite inv_con_cancel_left; exact s definition move_left_of_top {p : a₀₀ = a} {q : a = a₂₀} (s : square (p ⬝ q) p₁₂ p₀₁ p₂₁) : square q p₁₂ (p⁻¹ ⬝ p₀₁) p₂₁ := by apply cancel_tl p; rewrite con_inv_cancel_left; exact s definition move_left_of_top' {p : a = a₀₀} {q : a = a₂₀} (s : square (p⁻¹ ⬝ q) p₁₂ p₀₁ p₂₁) : square q p₁₂ (p ⬝ p₀₁) p₂₁ := by apply cancel_tl p⁻¹; rewrite inv_con_cancel_left; exact s definition move_bot_of_right {p : a₂₀ = a} {q : a = a₂₂} (s : square p₁₀ p₁₂ p₀₁ (p ⬝ q)) : square p₁₀ (p₁₂ ⬝ q⁻¹) p₀₁ p := by apply cancel_br q; rewrite inv_con_cancel_right; exact s definition move_bot_of_right' {p : a₂₀ = a} {q : a₂₂ = a} (s : square p₁₀ p₁₂ p₀₁ (p ⬝ q⁻¹)) : square p₁₀ (p₁₂ ⬝ q) p₀₁ p := by apply cancel_br q⁻¹; rewrite con_inv_cancel_right; exact s definition move_right_of_bot {p : a₀₂ = a} {q : a = a₂₂} (s : square p₁₀ (p ⬝ q) p₀₁ p₂₁) : square p₁₀ p p₀₁ (p₂₁ ⬝ q⁻¹) := by apply cancel_br q; rewrite inv_con_cancel_right; exact s definition move_right_of_bot' {p : a₀₂ = a} {q : a₂₂ = a} (s : square p₁₀ (p ⬝ q⁻¹) p₀₁ p₂₁) : square p₁₀ p p₀₁ (p₂₁ ⬝ q) := by apply cancel_br q⁻¹; rewrite con_inv_cancel_right; exact s definition move_top_of_right {p : a₂₀ = a} {q : a = a₂₂} (s : square p₁₀ p₁₂ p₀₁ (p ⬝ q)) : square (p₁₀ ⬝ p) p₁₂ p₀₁ q := by apply cancel_rt p; rewrite con_inv_cancel_right; exact s definition move_right_of_top {p : a₀₀ = a} {q : a = a₂₀} (s : square (p ⬝ q) p₁₂ p₀₁ p₂₁) : square p p₁₂ p₀₁ (q ⬝ p₂₁) := by apply cancel_tr q; rewrite inv_con_cancel_left; exact s definition move_bot_of_left {p : a₀₀ = a} {q : a = a₀₂} (s : square p₁₀ p₁₂ (p ⬝ q) p₂₁) : square p₁₀ (q ⬝ p₁₂) p p₂₁ := by apply cancel_lb q; rewrite inv_con_cancel_left; exact s definition move_left_of_bot {p : a₀₂ = a} {q : a = a₂₂} (s : square p₁₀ (p ⬝ q) p₀₁ p₂₁) : square p₁₀ q (p₀₁ ⬝ p) p₂₁ := by apply cancel_bl p; rewrite con_inv_cancel_right; exact s /- some higher ∞-groupoid operations -/ definition vconcat_vrfl (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : s₁₁ ⬝v vrefl p₁₂ = s₁₁ := by induction s₁₁; reflexivity definition hconcat_hrfl (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : s₁₁ ⬝h hrefl p₂₁ = s₁₁ := by induction s₁₁; reflexivity /- equivalences -/ definition eq_of_square [unfold 10] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : p₁₀ ⬝ p₂₁ = p₀₁ ⬝ p₁₂ := by induction s₁₁; apply idp definition square_of_eq (r : p₁₀ ⬝ p₂₁ = p₀₁ ⬝ p₁₂) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p₁₂; esimp at r; induction r; induction p₂₁; induction p₁₀; exact ids definition eq_top_of_square [unfold 10] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : p₁₀ = p₀₁ ⬝ p₁₂ ⬝ p₂₁⁻¹ := by induction s₁₁; apply idp definition square_of_eq_top (r : p₁₀ = p₀₁ ⬝ p₁₂ ⬝ p₂₁⁻¹) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p₂₁; induction p₁₂; esimp at r;induction r;induction p₁₀;exact ids definition eq_bot_of_square [unfold 10] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : p₁₂ = p₀₁⁻¹ ⬝ p₁₀ ⬝ p₂₁ := by induction s₁₁; apply idp definition square_of_eq_bot (r : p₀₁⁻¹ ⬝ p₁₀ ⬝ p₂₁ = p₁₂) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p₂₁; induction p₁₀; esimp at r; induction r; induction p₀₁; exact ids definition square_equiv_eq [constructor] (t : a₀₀ = a₀₂) (b : a₂₀ = a₂₂) (l : a₀₀ = a₂₀) (r : a₀₂ = a₂₂) : square t b l r ≃ t ⬝ r = l ⬝ b := begin fapply equiv.MK, { exact eq_of_square}, { exact square_of_eq}, { intro s, induction b, esimp [concat] at s, induction s, induction r, induction t, apply idp}, { intro s, induction s, apply idp}, end definition hdeg_square_equiv' [constructor] (p q : a = a') : square idp idp p q ≃ p = q := by transitivity _;apply square_equiv_eq;transitivity _;apply eq_equiv_eq_symm; apply equiv_eq_closed_right;apply idp_con definition vdeg_square_equiv' [constructor] (p q : a = a') : square p q idp idp ≃ p = q := by transitivity _;apply square_equiv_eq;apply equiv_eq_closed_right; apply idp_con definition eq_of_hdeg_square [reducible] {p q : a = a'} (s : square idp idp p q) : p = q := to_fun !hdeg_square_equiv' s definition eq_of_vdeg_square [reducible] {p q : a = a'} (s : square p q idp idp) : p = q := to_fun !vdeg_square_equiv' s definition top_deg_square (l : a₁ = a₂) (b : a₂ = a₃) (r : a₄ = a₃) : square (l ⬝ b ⬝ r⁻¹) b l r := by induction r;induction b;induction l;constructor definition bot_deg_square (l : a₁ = a₂) (t : a₁ = a₃) (r : a₃ = a₄) : square t (l⁻¹ ⬝ t ⬝ r) l r := by induction r;induction t;induction l;constructor /- the following two equivalences have as underlying inverse function the functions hdeg_square and vdeg_square, respectively. See example below the definition -/ definition hdeg_square_equiv [constructor] (p q : a = a') : square idp idp p q ≃ p = q := begin fapply equiv_change_fun, { fapply equiv_change_inv, apply hdeg_square_equiv', exact hdeg_square, intro s, induction s, induction p, reflexivity}, { exact eq_of_hdeg_square}, { reflexivity} end definition vdeg_square_equiv [constructor] (p q : a = a') : square p q idp idp ≃ p = q := begin fapply equiv_change_fun, { fapply equiv_change_inv, apply vdeg_square_equiv',exact vdeg_square, intro s, induction s, induction p, reflexivity}, { exact eq_of_vdeg_square}, { reflexivity} end example (p q : a = a') : to_inv (hdeg_square_equiv p q) = hdeg_square := idp /- characterization of pathovers in a equality type. The type B of the equality is fixed here. A version where B may also varies over the path p is given in the file squareover -/ definition eq_pathover [unfold 7] {f g : A → B} {p : a = a'} {q : f a = g a} {r : f a' = g a'} (s : square q r (ap f p) (ap g p)) : q =[p] r := by induction p;apply pathover_idp_of_eq;exact eq_of_vdeg_square s definition square_of_pathover [unfold 7] {f g : A → B} {p : a = a'} {q : f a = g a} {r : f a' = g a'} (s : q =[p] r) : square q r (ap f p) (ap g p) := by induction p;apply vdeg_square;exact eq_of_pathover_idp s /- interaction of equivalences with operations on squares -/ definition eq_pathover_equiv_square [constructor] {f g : A → B} (p : a = a') (q : f a = g a) (r : f a' = g a') : q =[p] r ≃ square q r (ap f p) (ap g p) := equiv.MK square_of_pathover eq_pathover begin intro s, induction p, esimp [square_of_pathover,eq_pathover], exact ap vdeg_square (to_right_inv !pathover_idp (eq_of_vdeg_square s)) ⬝ to_left_inv !vdeg_square_equiv s end begin intro s, induction p, esimp [square_of_pathover,eq_pathover], exact ap pathover_idp_of_eq (to_right_inv !vdeg_square_equiv (eq_of_pathover_idp s)) ⬝ to_left_inv !pathover_idp s end definition square_of_pathover_eq_concato {f g : A → B} {p : a = a'} {q q' : f a = g a} {r : f a' = g a'} (s' : q = q') (s : q' =[p] r) : square_of_pathover (s' ⬝po s) = s' ⬝pv square_of_pathover s := by induction s;induction s';reflexivity definition square_of_pathover_concato_eq {f g : A → B} {p : a = a'} {q : f a = g a} {r r' : f a' = g a'} (s' : r = r') (s : q =[p] r) : square_of_pathover (s ⬝op s') = square_of_pathover s ⬝vp s' := by induction s;induction s';reflexivity definition square_of_pathover_concato {f g : A → B} {p : a = a'} {p' : a' = a''} {q : f a = g a} {q' : f a' = g a'} {q'' : f a'' = g a''} (s : q =[p] q') (s' : q' =[p'] q'') : square_of_pathover (s ⬝o s') = ap_con f p p' ⬝ph (square_of_pathover s ⬝v square_of_pathover s') ⬝hp (ap_con g p p')⁻¹ := by induction s';induction s;esimp [ap_con,hconcat_eq];exact !vconcat_vrfl⁻¹ definition eq_of_square_hrfl [unfold 4] (p : a = a') : eq_of_square hrfl = idp_con p := by induction p;reflexivity definition eq_of_square_vrfl [unfold 4] (p : a = a') : eq_of_square vrfl = (idp_con p)⁻¹ := by induction p;reflexivity definition eq_of_square_hdeg_square {p q : a = a'} (r : p = q) : eq_of_square (hdeg_square r) = !idp_con ⬝ r⁻¹ := by induction r;induction p;reflexivity definition eq_of_square_vdeg_square {p q : a = a'} (r : p = q) : eq_of_square (vdeg_square r) = r ⬝ !idp_con⁻¹ := by induction r;induction p;reflexivity definition eq_of_square_eq_vconcat {p : a₀₀ = a₂₀} (r : p = p₁₀) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : eq_of_square (r ⬝pv s₁₁) = whisker_right r p₂₁ ⬝ eq_of_square s₁₁ := by induction s₁₁;cases r;reflexivity definition eq_of_square_eq_hconcat {p : a₀₀ = a₀₂} (r : p = p₀₁) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : eq_of_square (r ⬝ph s₁₁) = eq_of_square s₁₁ ⬝ (whisker_right r p₁₂)⁻¹ := by induction r;reflexivity definition eq_of_square_vconcat_eq {p : a₀₂ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₁₂ = p) : eq_of_square (s₁₁ ⬝vp r) = eq_of_square s₁₁ ⬝ whisker_left p₀₁ r := by induction r;reflexivity definition eq_of_square_hconcat_eq {p : a₂₀ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₂₁ = p) : eq_of_square (s₁₁ ⬝hp r) = (whisker_left p₁₀ r)⁻¹ ⬝ eq_of_square s₁₁ := by induction s₁₁; induction r;reflexivity -- definition vconcat_eq [unfold 11] {p : a₀₂ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₁₂ = p) : -- square p₁₀ p p₀₁ p₂₁ := -- by induction r; exact s₁₁ -- definition eq_hconcat [unfold 11] {p : a₀₀ = a₀₂} (r : p = p₀₁) -- (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀ p₁₂ p p₂₁ := -- by induction r; exact s₁₁ -- definition hconcat_eq [unfold 11] {p : a₂₀ = a₂₂} -- (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₂₁ = p) : square p₁₀ p₁₂ p₀₁ p := -- by induction r; exact s₁₁ -- the following definition is very slow, maybe it's interesting to see why? -- definition eq_pathover_equiv_square' {f g : A → B}(p : a = a') (q : f a = g a) (r : f a' = g a') -- : square q r (ap f p) (ap g p) ≃ q =[p] r := -- equiv.MK eq_pathover -- square_of_pathover -- (λs, begin -- induction p, rewrite [↑[square_of_pathover,eq_pathover], -- to_right_inv !vdeg_square_equiv (eq_of_pathover_idp s), -- to_left_inv !pathover_idp s] -- end) -- (λs, begin -- induction p, rewrite [↑[square_of_pathover,eq_pathover],▸*, -- to_right_inv !(@pathover_idp A) (eq_of_vdeg_square s), -- to_left_inv !vdeg_square_equiv s] -- end) /- recursors for squares where some sides are reflexivity -/ definition rec_on_b [recursor] {a₀₀ : A} {P : Π{a₂₀ a₁₂ : A} {t : a₀₀ = a₂₀} {l : a₀₀ = a₁₂} {r : a₂₀ = a₁₂}, square t idp l r → Type} {a₂₀ a₁₂ : A} {t : a₀₀ = a₂₀} {l : a₀₀ = a₁₂} {r : a₂₀ = a₁₂} (s : square t idp l r) (H : P ids) : P s := have H2 : P (square_of_eq (eq_of_square s)), from eq.rec_on (eq_of_square s : t ⬝ r = l) (by induction r; induction t; exact H), left_inv (to_fun !square_equiv_eq) s ▸ H2 definition rec_on_r [recursor] {a₀₀ : A} {P : Π{a₀₂ a₂₁ : A} {t : a₀₀ = a₂₁} {b : a₀₂ = a₂₁} {l : a₀₀ = a₀₂}, square t b l idp → Type} {a₀₂ a₂₁ : A} {t : a₀₀ = a₂₁} {b : a₀₂ = a₂₁} {l : a₀₀ = a₀₂} (s : square t b l idp) (H : P ids) : P s := let p : l ⬝ b = t := (eq_of_square s)⁻¹ in have H2 : P (square_of_eq (eq_of_square s)⁻¹⁻¹), from @eq.rec_on _ _ (λx p, P (square_of_eq p⁻¹)) _ p (by induction b; induction l; exact H), left_inv (to_fun !square_equiv_eq) s ▸ !inv_inv ▸ H2 definition rec_on_l [recursor] {a₀₁ : A} {P : Π {a₂₀ a₂₂ : A} {t : a₀₁ = a₂₀} {b : a₀₁ = a₂₂} {r : a₂₀ = a₂₂}, square t b idp r → Type} {a₂₀ a₂₂ : A} {t : a₀₁ = a₂₀} {b : a₀₁ = a₂₂} {r : a₂₀ = a₂₂} (s : square t b idp r) (H : P ids) : P s := let p : t ⬝ r = b := eq_of_square s ⬝ !idp_con in have H2 : P (square_of_eq (p ⬝ !idp_con⁻¹)), from eq.rec_on p (by induction r; induction t; exact H), left_inv (to_fun !square_equiv_eq) s ▸ !con_inv_cancel_right ▸ H2 definition rec_on_t [recursor] {a₁₀ : A} {P : Π {a₀₂ a₂₂ : A} {b : a₀₂ = a₂₂} {l : a₁₀ = a₀₂} {r : a₁₀ = a₂₂}, square idp b l r → Type} {a₀₂ a₂₂ : A} {b : a₀₂ = a₂₂} {l : a₁₀ = a₀₂} {r : a₁₀ = a₂₂} (s : square idp b l r) (H : P ids) : P s := let p : l ⬝ b = r := (eq_of_square s)⁻¹ ⬝ !idp_con in assert H2 : P (square_of_eq ((p ⬝ !idp_con⁻¹)⁻¹)), from eq.rec_on p (by induction b; induction l; exact H), assert H3 : P (square_of_eq ((eq_of_square s)⁻¹⁻¹)), from eq.rec_on !con_inv_cancel_right H2, assert H4 : P (square_of_eq (eq_of_square s)), from eq.rec_on !inv_inv H3, proof left_inv (to_fun !square_equiv_eq) s ▸ H4 qed definition rec_on_tb [recursor] {a : A} {P : Π{b : A} {l : a = b} {r : a = b}, square idp idp l r → Type} {b : A} {l : a = b} {r : a = b} (s : square idp idp l r) (H : P ids) : P s := have H2 : P (square_of_eq (eq_of_square s)), from eq.rec_on (eq_of_square s : idp ⬝ r = l) (by induction r; exact H), left_inv (to_fun !square_equiv_eq) s ▸ H2 definition rec_on_lr [recursor] {a : A} {P : Π{a' : A} {t : a = a'} {b : a = a'}, square t b idp idp → Type} {a' : A} {t : a = a'} {b : a = a'} (s : square t b idp idp) (H : P ids) : P s := let p : idp ⬝ b = t := (eq_of_square s)⁻¹ in assert H2 : P (square_of_eq (eq_of_square s)⁻¹⁻¹), from @eq.rec_on _ _ (λx q, P (square_of_eq q⁻¹)) _ p (by induction b; exact H), to_left_inv (!square_equiv_eq) s ▸ !inv_inv ▸ H2 --we can also do the other recursors (tl, tr, bl, br, tbl, tbr, tlr, blr), but let's postpone this until they are needed definition whisker_square [unfold 14 15 16 17] (r₁₀ : p₁₀ = p₁₀') (r₁₂ : p₁₂ = p₁₂') (r₀₁ : p₀₁ = p₀₁') (r₂₁ : p₂₁ = p₂₁') (s : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀' p₁₂' p₀₁' p₂₁' := by induction r₁₀; induction r₁₂; induction r₀₁; induction r₂₁; exact s /- squares commute with some operations on 2-paths -/ definition square_inv2 {p₁ p₂ p₃ p₄ : a = a'} {t : p₁ = p₂} {b : p₃ = p₄} {l : p₁ = p₃} {r : p₂ = p₄} (s : square t b l r) : square (inverse2 t) (inverse2 b) (inverse2 l) (inverse2 r) := by induction s;constructor definition square_con2 {p₁ p₂ p₃ p₄ : a₁ = a₂} {q₁ q₂ q₃ q₄ : a₂ = a₃} {t₁ : p₁ = p₂} {b₁ : p₃ = p₄} {l₁ : p₁ = p₃} {r₁ : p₂ = p₄} {t₂ : q₁ = q₂} {b₂ : q₃ = q₄} {l₂ : q₁ = q₃} {r₂ : q₂ = q₄} (s₁ : square t₁ b₁ l₁ r₁) (s₂ : square t₂ b₂ l₂ r₂) : square (t₁ ◾ t₂) (b₁ ◾ b₂) (l₁ ◾ l₂) (r₁ ◾ r₂) := by induction s₂;induction s₁;constructor open is_trunc definition is_set.elims [H : is_set A] : square p₁₀ p₁₂ p₀₁ p₂₁ := square_of_eq !is_set.elim -- definition square_of_con_inv_hsquare {p₁ p₂ p₃ p₄ : a₁ = a₂} -- {t : p₁ = p₂} {b : p₃ = p₄} {l : p₁ = p₃} {r : p₂ = p₄} -- (s : square (con_inv_eq_idp t) (con_inv_eq_idp b) (l ◾ r⁻²) idp) -- : square t b l r := -- sorry --by induction s /- Square fillers -/ -- TODO replace by "more algebraic" fillers? variables (p₁₀ p₁₂ p₀₁ p₂₁) definition square_fill_t : Σ (p : a₀₀ = a₂₀), square p p₁₂ p₀₁ p₂₁ := by induction p₀₁; induction p₂₁; exact ⟨_, !vrefl⟩ definition square_fill_b : Σ (p : a₀₂ = a₂₂), square p₁₀ p p₀₁ p₂₁ := by induction p₀₁; induction p₂₁; exact ⟨_, !vrefl⟩ definition square_fill_l : Σ (p : a₀₀ = a₀₂), square p₁₀ p₁₂ p p₂₁ := by induction p₁₀; induction p₁₂; exact ⟨_, !hrefl⟩ definition square_fill_r : Σ (p : a₂₀ = a₂₂) , square p₁₀ p₁₂ p₀₁ p := by induction p₁₀; induction p₁₂; exact ⟨_, !hrefl⟩ /- Squares having an 'ap' term on one face -/ --TODO find better names definition square_Flr_ap_idp {A B : Type} {c : B} {f : A → B} (p : Π a, f a = c) {a b : A} (q : a = b) : square (p a) (p b) (ap f q) idp := by induction q; apply vrfl definition square_Flr_idp_ap {A B : Type} {c : B} {f : A → B} (p : Π a, c = f a) {a b : A} (q : a = b) : square (p a) (p b) idp (ap f q) := by induction q; apply vrfl definition square_ap_idp_Flr {A B : Type} {b : B} {f : A → B} (p : Π a, f a = b) {a b : A} (q : a = b) : square (ap f q) idp (p a) (p b) := by induction q; apply hrfl /- Matching eq_hconcat with hconcat etc. -/ -- TODO maybe rename hconcat_eq and the like? variable (s₁₁) definition ph_eq_pv_h_vp {p : a₀₀ = a₀₂} (r : p = p₀₁) : r ⬝ph s₁₁ = !idp_con⁻¹ ⬝pv ((hdeg_square r) ⬝h s₁₁) ⬝vp !idp_con := by cases r; cases s₁₁; esimp definition hdeg_h_eq_pv_ph_vp {p : a₀₀ = a₀₂} (r : p = p₀₁) : hdeg_square r ⬝h s₁₁ = !idp_con ⬝pv (r ⬝ph s₁₁) ⬝vp !idp_con⁻¹ := by cases r; cases s₁₁; esimp definition hp_eq_h {p : a₂₀ = a₂₂} (r : p₂₁ = p) : s₁₁ ⬝hp r = s₁₁ ⬝h hdeg_square r := by cases r; cases s₁₁; esimp definition pv_eq_ph_vdeg_v_vh {p : a₀₀ = a₂₀} (r : p = p₁₀) : r ⬝pv s₁₁ = !idp_con⁻¹ ⬝ph ((vdeg_square r) ⬝v s₁₁) ⬝hp !idp_con := by cases r; cases s₁₁; esimp definition vdeg_v_eq_ph_pv_hp {p : a₀₀ = a₂₀} (r : p = p₁₀) : vdeg_square r ⬝v s₁₁ = !idp_con ⬝ph (r ⬝pv s₁₁) ⬝hp !idp_con⁻¹ := by cases r; cases s₁₁; esimp definition vp_eq_v {p : a₀₂ = a₂₂} (r : p₁₂ = p) : s₁₁ ⬝vp r = s₁₁ ⬝v vdeg_square r := by cases r; cases s₁₁; esimp end eq
b34adebed0fbce5e8691662fad332649046e86ab
88fb7558b0636ec6b181f2a548ac11ad3919f8a5
/tests/lean/run/resolve_name_bug.lean
2a7910d5a29056cf3aeecbd88a65ec4a03e409c1
[ "Apache-2.0" ]
permissive
moritayasuaki/lean
9f666c323cb6fa1f31ac597d777914aed41e3b7a
ae96ebf6ee953088c235ff7ae0e8c95066ba8001
refs/heads/master
1,611,135,440,814
1,493,852,869,000
1,493,852,869,000
90,269,903
0
0
null
1,493,906,291,000
1,493,906,291,000
null
UTF-8
Lean
false
false
468
lean
open tactic constant f : nat → nat meta def check_expr (p : pexpr) (t : expr) : tactic unit := do e ← to_expr p, guard (t = e) namespace foo axiom f_lemma1 : f 0 = 1 namespace bla axiom f_lemma2 : f 1 = 2 def g (a : nat) := a + 1 example : g 0 = 1 := begin unfold g, (target >>= check_expr `(0 + 1 = 1)), reflexivity end example : f (f 0) = 2 := by rewrite [f_lemma1, f_lemma2] lemma ex2 : f (f 0) = 2 := by simp [f_lemma1, f_lemma2] end bla end foo
e764f89e164200d04efcf2eb36c2c2562feaeea1
6b2a480f27775cba4f3ae191b1c1387a29de586e
/group_rep1/morphism/ni.lean
ceb2bc3f448f9a5c18443084bc1734f9c3e8f911
[]
no_license
Or7ando/group_representation
a681de2e19d1930a1e1be573d6735a2f0b8356cb
9b576984f17764ebf26c8caa2a542d248f1b50d2
refs/heads/master
1,662,413,107,324
1,590,302,389,000
1,590,302,389,000
258,130,829
0
1
null
null
null
null
UTF-8
Lean
false
false
6
lean
#eval
0128a13abd573690eaa1885d66f724c6025e1b2d
cbcb0199842f03e7606d4e43666573fc15dd07a5
/src/topology/uniform_space/completion.lean
8ad1605d04dcb52254283b7fbabe83f7c4dc3356
[ "Apache-2.0" ]
permissive
truonghoangle/mathlib
a6a7c14b3767ec71156239d8ea97f6921fe79627
673bae584febcd830c2c9256eb7e7a81e27ed303
refs/heads/master
1,590,347,998,944
1,559,728,860,000
1,559,728,860,000
187,431,971
0
0
null
1,558,238,525,000
1,558,238,525,000
null
UTF-8
Lean
false
false
25,207
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl Hausdorff completions of uniform spaces. The goal is to construct a left-adjoint to the inclusion of complete Hausdorff uniform spaces into all uniform spaces. Any uniform space `α` gets a completion `completion α` and a morphism (ie. uniformly continuous map) `completion : α → completion α` which solves the universal mapping problem of factorizing morphisms from `α` to any complete Hausdorff uniform space `β`. It means any uniformly continuous `f : α → β` gives rise to a unique morphism `completion.map f : completion α → β` such that `f = completion.extension f ∘ completion α`. Actually `completion.extension f` is defined for all maps from `α` to `β` but it has the desired properties only if `f` is uniformly continuous. Beware that `completion α` is not injective if `α` is not Hausdorff. But its image is always dense. The adjoint functor acting on morphisms is then constructed by the usual abstract nonsense. For every uniform spaces `α` and `β`, it turns `f : α → β` into a morphism `completion.map f : completion α → completion β` such that `coe ∘ f = (completion.map f) ∘ coe` provided `f` is uniformly continuous. This construction is compatible with composition. In this file we introduce the following concepts: * `Cauchy α` the uniform completion of the uniform space `α` (using Cauchy filters). These are not minimal filters. * `completion α := quotient (separation_setoid (Cauchy α))` the Hausdorff completion. This formalization is mostly based on N. Bourbaki: General Topology I. M. James: Topologies and Uniformities From a slightly different perspective in order to reuse material in topology.uniform_space.basic. -/ import data.set.basic import topology.uniform_space.uniform_embedding topology.uniform_space.separation noncomputable theory local attribute [instance] classical.prop_decidable open filter set universes u v w x local notation `𝓤` := uniformity /-- Space of Cauchy filters This is essentially the completion of a uniform space. The embeddings are the neighbourhood filters. This space is not minimal, the separated uniform space (i.e. quotiented on the intersection of all entourages) is necessary for this. -/ def Cauchy (α : Type u) [uniform_space α] : Type u := { f : filter α // cauchy f } namespace Cauchy section parameters {α : Type u} [uniform_space α] variables {β : Type v} {γ : Type w} variables [uniform_space β] [uniform_space γ] def gen (s : set (α × α)) : set (Cauchy α × Cauchy α) := {p | s ∈ filter.prod (p.1.val) (p.2.val) } lemma monotone_gen : monotone gen := monotone_set_of $ assume p, @monotone_mem_sets (α×α) (filter.prod (p.1.val) (p.2.val)) private lemma symm_gen : map prod.swap ((𝓤 α).lift' gen) ≤ (𝓤 α).lift' gen := calc map prod.swap ((𝓤 α).lift' gen) = (𝓤 α).lift' (λs:set (α×α), {p | s ∈ filter.prod (p.2.val) (p.1.val) }) : begin delta gen, simp [map_lift'_eq, monotone_set_of, monotone_mem_sets, function.comp, image_swap_eq_preimage_swap] end ... ≤ (𝓤 α).lift' gen : uniformity_lift_le_swap (monotone_comp (monotone_set_of $ assume p, @monotone_mem_sets (α×α) ((filter.prod ((p.2).val) ((p.1).val)))) monotone_principal) begin have h := λ(p:Cauchy α×Cauchy α), @filter.prod_comm _ _ (p.2.val) (p.1.val), simp [function.comp, h], exact le_refl _ end private lemma comp_rel_gen_gen_subset_gen_comp_rel {s t : set (α×α)} : comp_rel (gen s) (gen t) ⊆ (gen (comp_rel s t) : set (Cauchy α × Cauchy α)) := assume ⟨f, g⟩ ⟨h, h₁, h₂⟩, let ⟨t₁, (ht₁ : t₁ ∈ f.val), t₂, (ht₂ : t₂ ∈ h.val), (h₁ : set.prod t₁ t₂ ⊆ s)⟩ := mem_prod_iff.mp h₁ in let ⟨t₃, (ht₃ : t₃ ∈ h.val), t₄, (ht₄ : t₄ ∈ g.val), (h₂ : set.prod t₃ t₄ ⊆ t)⟩ := mem_prod_iff.mp h₂ in have t₂ ∩ t₃ ∈ h.val, from inter_mem_sets ht₂ ht₃, let ⟨x, xt₂, xt₃⟩ := inhabited_of_mem_sets (h.property.left) this in (filter.prod f.val g.val).sets_of_superset (prod_mem_prod ht₁ ht₄) (assume ⟨a, b⟩ ⟨(ha : a ∈ t₁), (hb : b ∈ t₄)⟩, ⟨x, h₁ (show (a, x) ∈ set.prod t₁ t₂, from ⟨ha, xt₂⟩), h₂ (show (x, b) ∈ set.prod t₃ t₄, from ⟨xt₃, hb⟩)⟩) private lemma comp_gen : ((𝓤 α).lift' gen).lift' (λs, comp_rel s s) ≤ (𝓤 α).lift' gen := calc ((𝓤 α).lift' gen).lift' (λs, comp_rel s s) = (𝓤 α).lift' (λs, comp_rel (gen s) (gen s)) : begin rw [lift'_lift'_assoc], exact monotone_gen, exact (monotone_comp_rel monotone_id monotone_id) end ... ≤ (𝓤 α).lift' (λs, gen $ comp_rel s s) : lift'_mono' $ assume s hs, comp_rel_gen_gen_subset_gen_comp_rel ... = ((𝓤 α).lift' $ λs:set(α×α), comp_rel s s).lift' gen : begin rw [lift'_lift'_assoc], exact (monotone_comp_rel monotone_id monotone_id), exact monotone_gen end ... ≤ (𝓤 α).lift' gen : lift'_mono comp_le_uniformity (le_refl _) instance : uniform_space (Cauchy α) := uniform_space.of_core { uniformity := (𝓤 α).lift' gen, refl := principal_le_lift' $ assume s hs ⟨a, b⟩ (a_eq_b : a = b), a_eq_b ▸ a.property.right hs, symm := symm_gen, comp := comp_gen } theorem mem_uniformity {s : set (Cauchy α × Cauchy α)} : s ∈ 𝓤 (Cauchy α) ↔ ∃ t ∈ 𝓤 α, gen t ⊆ s := mem_lift'_sets monotone_gen theorem mem_uniformity' {s : set (Cauchy α × Cauchy α)} : s ∈ 𝓤 (Cauchy α) ↔ ∃ t ∈ 𝓤 α, ∀ f g : Cauchy α, t ∈ filter.prod f.1 g.1 → (f, g) ∈ s := mem_uniformity.trans $ bex_congr $ λ t h, prod.forall /-- Embedding of `α` into its completion -/ def pure_cauchy (a : α) : Cauchy α := ⟨pure a, cauchy_pure⟩ lemma uniform_embedding_pure_cauchy : uniform_embedding (pure_cauchy : α → Cauchy α) := ⟨assume a₁ a₂ h, have (pure_cauchy a₁).val = (pure_cauchy a₂).val, from congr_arg _ h, have {a₁} = ({a₂} : set α), from principal_eq_iff_eq.mp this, by simp at this; assumption, have (preimage (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ∘ gen) = id, from funext $ assume s, set.ext $ assume ⟨a₁, a₂⟩, by simp [preimage, gen, pure_cauchy, prod_principal_principal], calc comap (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ((𝓤 α).lift' gen) = (𝓤 α).lift' (preimage (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ∘ gen) : comap_lift'_eq monotone_gen ... = 𝓤 α : by simp [this]⟩ lemma pure_cauchy_dense : ∀x, x ∈ closure (range pure_cauchy) := assume f, have h_ex : ∀ s ∈ 𝓤 (Cauchy α), ∃y:α, (f, pure_cauchy y) ∈ s, from assume s hs, let ⟨t'', ht''₁, (ht''₂ : gen t'' ⊆ s)⟩ := (mem_lift'_sets monotone_gen).mp hs in let ⟨t', ht'₁, ht'₂⟩ := comp_mem_uniformity_sets ht''₁ in have t' ∈ filter.prod (f.val) (f.val), from f.property.right ht'₁, let ⟨t, ht, (h : set.prod t t ⊆ t')⟩ := mem_prod_same_iff.mp this in let ⟨x, (hx : x ∈ t)⟩ := inhabited_of_mem_sets f.property.left ht in have t'' ∈ filter.prod f.val (pure x), from mem_prod_iff.mpr ⟨t, ht, {y:α | (x, y) ∈ t'}, assume y, begin simp, intro h, simp [h], exact refl_mem_uniformity ht'₁ end, assume ⟨a, b⟩ ⟨(h₁ : a ∈ t), (h₂ : (x, b) ∈ t')⟩, ht'₂ $ prod_mk_mem_comp_rel (@h (a, x) ⟨h₁, hx⟩) h₂⟩, ⟨x, ht''₂ $ by dsimp [gen]; exact this⟩, begin simp [closure_eq_nhds, nhds_eq_uniformity, lift'_inf_principal_eq, set.inter_comm], exact (lift'_neq_bot_iff $ monotone_inter monotone_const monotone_preimage).mpr (assume s hs, let ⟨y, hy⟩ := h_ex s hs in have pure_cauchy y ∈ range pure_cauchy ∩ {y : Cauchy α | (f, y) ∈ s}, from ⟨mem_range_self y, hy⟩, ne_empty_of_mem this) end lemma dense_embedding_pure_cauchy : dense_embedding pure_cauchy := uniform_embedding_pure_cauchy.dense_embedding pure_cauchy_dense lemma nonempty_Cauchy_iff : nonempty (Cauchy α) ↔ nonempty α := begin split ; rintro ⟨c⟩, { have := eq_univ_iff_forall.1 dense_embedding_pure_cauchy.closure_range c, have := mem_closure_iff.1 this _ is_open_univ trivial, rcases exists_mem_of_ne_empty this with ⟨_, ⟨_, a, _⟩⟩, exact ⟨a⟩ }, { exact ⟨pure_cauchy c⟩ } end section set_option eqn_compiler.zeta true instance : complete_space (Cauchy α) := complete_space_extension uniform_embedding_pure_cauchy pure_cauchy_dense $ assume f hf, let f' : Cauchy α := ⟨f, hf⟩ in have map pure_cauchy f ≤ (𝓤 $ Cauchy α).lift' (preimage (prod.mk f')), from le_lift' $ assume s hs, let ⟨t, ht₁, (ht₂ : gen t ⊆ s)⟩ := (mem_lift'_sets monotone_gen).mp hs in let ⟨t', ht', (h : set.prod t' t' ⊆ t)⟩ := mem_prod_same_iff.mp (hf.right ht₁) in have t' ⊆ { y : α | (f', pure_cauchy y) ∈ gen t }, from assume x hx, (filter.prod f (pure x)).sets_of_superset (prod_mem_prod ht' $ mem_pure hx) h, f.sets_of_superset ht' $ subset.trans this (preimage_mono ht₂), ⟨f', by simp [nhds_eq_uniformity]; assumption⟩ end instance [inhabited α] : inhabited (Cauchy α) := ⟨pure_cauchy $ default α⟩ instance [h : nonempty α] : nonempty (Cauchy α) := h.rec_on $ assume a, nonempty.intro $ Cauchy.pure_cauchy a section extend variables [_root_.complete_space β] [separated β] def extend (f : α → β) : (Cauchy α → β) := if uniform_continuous f then dense_embedding_pure_cauchy.extend f else λ x, f (classical.inhabited_of_nonempty $ nonempty_Cauchy_iff.1 ⟨x⟩).default lemma extend_pure_cauchy {f : α → β} (hf : uniform_continuous f) (a : α) : extend f (pure_cauchy a) = f a := begin rw [extend, if_pos hf], exact uniformly_extend_of_emb uniform_embedding_pure_cauchy pure_cauchy_dense _ end lemma uniform_continuous_extend {f : α → β} : uniform_continuous (extend f) := begin by_cases hf : uniform_continuous f, { rw [extend, if_pos hf], exact uniform_continuous_uniformly_extend uniform_embedding_pure_cauchy pure_cauchy_dense hf }, { rw [extend, if_neg hf], exact uniform_continuous_of_const (assume a b, by congr) } end end extend end theorem Cauchy_eq {α : Type*} [inhabited α] [uniform_space α] [complete_space α] [separated α] {f g : Cauchy α} : lim f.1 = lim g.1 ↔ (f, g) ∈ separation_rel (Cauchy α) := begin split, { intros e s hs, rcases Cauchy.mem_uniformity'.1 hs with ⟨t, tu, ts⟩, apply ts, rcases comp_mem_uniformity_sets tu with ⟨d, du, dt⟩, refine mem_prod_iff.2 ⟨_, le_nhds_lim_of_cauchy f.2 (mem_nhds_right (lim f.1) du), _, le_nhds_lim_of_cauchy g.2 (mem_nhds_left (lim g.1) du), λ x h, _⟩, cases x with a b, cases h with h₁ h₂, rw ← e at h₂, exact dt ⟨_, h₁, h₂⟩ }, { intros H, refine separated_def.1 (by apply_instance) _ _ (λ t tu, _), rcases mem_uniformity_is_closed tu with ⟨d, du, dc, dt⟩, refine H {p | (lim p.1.1, lim p.2.1) ∈ t} (Cauchy.mem_uniformity'.2 ⟨d, du, λ f g h, _⟩), rcases mem_prod_iff.1 h with ⟨x, xf, y, yg, h⟩, have limc : ∀ (f : Cauchy α) (x ∈ f.1), lim f.1 ∈ closure x, { intros f x xf, rw closure_eq_nhds, exact lattice.neq_bot_of_le_neq_bot f.2.1 (lattice.le_inf (le_nhds_lim_of_cauchy f.2) (le_principal_iff.2 xf)) }, have := (closure_subset_iff_subset_of_is_closed dc).2 h, rw closure_prod_eq at this, refine dt (this ⟨_, _⟩); dsimp; apply limc; assumption } end section local attribute [instance] uniform_space.separation_setoid lemma injective_separated_pure_cauchy {α : Type*} [uniform_space α] [s : separated α] : function.injective (λa:α, ⟦pure_cauchy a⟧) | a b h := separated_def.1 s _ _ $ assume s hs, let ⟨t, ht, hts⟩ := by rw [← (@uniform_embedding_pure_cauchy α _).right, filter.mem_comap_sets] at hs; exact hs in have (pure_cauchy a, pure_cauchy b) ∈ t, from quotient.exact h t ht, @hts (a, b) this end section prod variables {α : Type*} {β : Type*} [uniform_space α] [uniform_space β] def prod : Cauchy α × Cauchy β → Cauchy (α × β) := dense_embedding.extend (dense_embedding_pure_cauchy.prod dense_embedding_pure_cauchy) pure_cauchy lemma prod_pure_cauchy_pure_cauchy (a : α) (b :β) : prod (pure_cauchy a, pure_cauchy b) = pure_cauchy (a, b) := uniformly_extend_of_emb (uniform_embedding_pure_cauchy.prod uniform_embedding_pure_cauchy) (dense_embedding_pure_cauchy.prod dense_embedding_pure_cauchy).dense (a, b) lemma uniform_continuous_prod : uniform_continuous (@prod α β _ _) := uniform_continuous_uniformly_extend (uniform_embedding_pure_cauchy.prod uniform_embedding_pure_cauchy) (dense_embedding_pure_cauchy.prod dense_embedding_pure_cauchy).dense uniform_embedding_pure_cauchy.uniform_continuous end prod end Cauchy local attribute [instance] uniform_space.separation_setoid open Cauchy set namespace uniform_space variables (α : Type*) [uniform_space α] variables {β : Type*} [uniform_space β] variables {γ : Type*} [uniform_space γ] instance complete_space_separation [h : complete_space α] : complete_space (quotient (separation_setoid α)) := ⟨assume f, assume hf : cauchy f, have cauchy (f.comap (λx, ⟦x⟧)), from cauchy_comap comap_quotient_le_uniformity hf $ comap_neq_bot_of_surj hf.left $ assume b, quotient.exists_rep _, let ⟨x, (hx : f.comap (λx, ⟦x⟧) ≤ nhds x)⟩ := complete_space.complete this in ⟨⟦x⟧, calc f = map (λx, ⟦x⟧) (f.comap (λx, ⟦x⟧)) : (map_comap $ univ_mem_sets' $ assume b, quotient.exists_rep _).symm ... ≤ map (λx, ⟦x⟧) (nhds x) : map_mono hx ... ≤ _ : continuous_iff_continuous_at.mp uniform_continuous_quotient_mk.continuous _⟩⟩ /-- Hausdorff completion of `α` -/ def completion := quotient (separation_setoid $ Cauchy α) namespace completion @[priority 50] instance : uniform_space (completion α) := by dunfold completion ; apply_instance instance : complete_space (completion α) := by dunfold completion ; apply_instance instance : separated (completion α) := by dunfold completion ; apply_instance instance : t2_space (completion α) := separated_t2 instance : regular_space (completion α) := separated_regular /-- Automatic coercion from `α` to its completion. Not always injective. -/ instance : has_coe α (completion α) := ⟨quotient.mk ∘ pure_cauchy⟩ protected lemma coe_eq : (coe : α → completion α) = quotient.mk ∘ pure_cauchy := rfl lemma uniform_continuous_coe : uniform_continuous (coe : α → completion α) := uniform_continuous.comp uniform_embedding_pure_cauchy.uniform_continuous uniform_continuous_quotient_mk lemma continuous_coe : continuous (coe : α → completion α) := uniform_continuous.continuous (uniform_continuous_coe α) lemma comap_coe_eq_uniformity : (𝓤 _).comap (λ(p:α×α), ((p.1 : completion α), (p.2 : completion α))) = 𝓤 α := begin have : (λx:α×α, ((x.1 : completion α), (x.2 : completion α))) = (λx:(Cauchy α)×(Cauchy α), (⟦x.1⟧, ⟦x.2⟧)) ∘ (λx:α×α, (pure_cauchy x.1, pure_cauchy x.2)), { ext ⟨a, b⟩; simp; refl }, rw [this, ← filter.comap_comap_comp], change filter.comap _ (filter.comap _ (𝓤 $ quotient $ separation_setoid $ Cauchy α)) = 𝓤 α, rw [comap_quotient_eq_uniformity, uniform_embedding_pure_cauchy.2] end lemma uniform_embedding_coe [separated α] : uniform_embedding (coe : α → completion α) := ⟨injective_separated_pure_cauchy, comap_coe_eq_uniformity α⟩ variable {α} lemma dense : closure (range (coe : α → completion α)) = univ := by rw [completion.coe_eq, range_comp]; exact quotient_dense_of_dense pure_cauchy_dense lemma dense_embedding_coe [separated α]: dense_embedding (coe : α → completion α) := (uniform_embedding_coe α).dense_embedding (assume x, by rw [dense]; exact mem_univ _) lemma dense₂ : closure (range (λx:α × β, ((x.1 : completion α), (x.2 : completion β)))) = univ := by rw [← set.prod_range_range_eq, closure_prod_eq, dense, dense, univ_prod_univ] lemma dense₃ : closure (range (λx:α × (β × γ), ((x.1 : completion α), ((x.2.1 : completion β), (x.2.2 : completion γ))))) = univ := let a : α → completion α := coe, bc := λp:β × γ, ((p.1 : completion β), (p.2 : completion γ)) in show closure (range (λx:α × (β × γ), (a x.1, bc x.2))) = univ, begin rw [← set.prod_range_range_eq, @closure_prod_eq _ _ _ _ (range a) (range bc), ← univ_prod_univ], congr, exact dense, exact dense₂ end @[elab_as_eliminator] lemma induction_on {p : completion α → Prop} (a : completion α) (hp : is_closed {a | p a}) (ih : ∀a:α, p a) : p a := is_closed_property dense hp ih a @[elab_as_eliminator] lemma induction_on₂ {p : completion α → completion β → Prop} (a : completion α) (b : completion β) (hp : is_closed {x : completion α × completion β | p x.1 x.2}) (ih : ∀(a:α) (b:β), p a b) : p a b := have ∀x : completion α × completion β, p x.1 x.2, from is_closed_property dense₂ hp $ assume ⟨a, b⟩, ih a b, this (a, b) @[elab_as_eliminator] lemma induction_on₃ {p : completion α → completion β → completion γ → Prop} (a : completion α) (b : completion β) (c : completion γ) (hp : is_closed {x : completion α × completion β × completion γ | p x.1 x.2.1 x.2.2}) (ih : ∀(a:α) (b:β) (c:γ), p a b c) : p a b c := have ∀x : completion α × completion β × completion γ, p x.1 x.2.1 x.2.2, from is_closed_property dense₃ hp $ assume ⟨a, b, c⟩, ih a b c, this (a, b, c) @[elab_as_eliminator] lemma induction_on₄ {δ : Type*} [uniform_space δ] {p : completion α → completion β → completion γ → completion δ → Prop} (a : completion α) (b : completion β) (c : completion γ) (d : completion δ) (hp : is_closed {x : (completion α × completion β) × (completion γ × completion δ) | p x.1.1 x.1.2 x.2.1 x.2.2}) (ih : ∀(a:α) (b:β) (c:γ) (d : δ), p ↑a ↑b ↑c ↑d) : p a b c d := let ab := λp:α × β, ((p.1 : completion α), (p.2 : completion β)), cd := λp:γ × δ, ((p.1 : completion γ), (p.2 : completion δ)) in have dense₄ : closure (range (λx:(α × β) × (γ × δ), (ab x.1, cd x.2))) = univ, begin rw [← set.prod_range_range_eq, @closure_prod_eq _ _ _ _ (range ab) (range cd), ← univ_prod_univ], congr, exact dense₂, exact dense₂ end, have ∀x:(completion α × completion β) × (completion γ × completion δ), p x.1.1 x.1.2 x.2.1 x.2.2, from is_closed_property dense₄ hp (assume p:(α×β)×(γ×δ), ih p.1.1 p.1.2 p.2.1 p.2.2), this ((a, b), (c, d)) lemma ext [t2_space β] {f g : completion α → β} (hf : continuous f) (hg : continuous g) (h : ∀a:α, f a = g a) : f = g := funext $ assume a, completion.induction_on a (is_closed_eq hf hg) h section extension variables {f : α → β} variables [complete_space β] [separated β] /-- "Extension" to the completion. Based on `Cauchy.extend`, which is defined for any map `f` but returns an arbitrary constant value if `f` is not uniformly continuous -/ protected def extension (f : α → β) : completion α → β := quotient.lift (extend f) $ assume a b, eq_of_separated_of_uniform_continuous uniform_continuous_extend lemma uniform_continuous_extension : uniform_continuous (completion.extension f) := uniform_continuous_quotient_lift uniform_continuous_extend lemma continuous_extension : continuous (completion.extension f) := uniform_continuous_extension.continuous @[simp] lemma extension_coe (hf : uniform_continuous f) (a : α) : (completion.extension f) a = f a := extend_pure_cauchy hf a end extension section map variables {f : α → β} /-- Completion functor acting on morphisms -/ protected def map (f : α → β) : completion α → completion β := completion.extension (coe ∘ f) lemma uniform_continuous_map : uniform_continuous (completion.map f) := uniform_continuous_quotient_lift uniform_continuous_extend lemma continuous_map : continuous (completion.map f) := uniform_continuous_extension.continuous @[simp] lemma map_coe (hf : uniform_continuous f) (a : α) : (completion.map f) a = f a := by rw [completion.map, extension_coe]; from hf.comp (uniform_continuous_coe β) lemma map_unique {f : α → β} {g : completion α → completion β} (hg : uniform_continuous g) (h : ∀a:α, ↑(f a) = g a) : completion.map f = g := completion.ext continuous_map hg.continuous $ begin intro a, simp only [completion.map, (∘), h], rw [extension_coe ((uniform_continuous_coe α).comp hg)] end lemma map_id : completion.map (@id α) = id := map_unique uniform_continuous_id (assume a, rfl) lemma extension_map [complete_space γ] [separated γ] {f : β → γ} {g : α → β} (hf : uniform_continuous f) (hg : uniform_continuous g) : completion.extension f ∘ completion.map g = completion.extension (f ∘ g) := completion.ext (continuous_extension.comp continuous_map) continuous_extension $ by intro a; simp only [hg, hf, hg.comp hf, (∘), map_coe, extension_coe] lemma map_comp {g : β → γ} {f : α → β} (hg : uniform_continuous g) (hf : uniform_continuous f) : completion.map g ∘ completion.map f = completion.map (g ∘ f) := extension_map (hg.comp (uniform_continuous_coe _)) hf end map /- In this section we construct isomorphisms between the completion of a uniform space and the completion of its separation quotient -/ section separation_quotient_completion def completion_separation_quotient_equiv (α : Type u) [uniform_space α] : completion (separation_quotient α) ≃ completion α := begin refine ⟨completion.extension (separation_quotient.lift (coe : α → completion α)), completion.map quotient.mk, _, _⟩, { assume a, refine completion.induction_on a (is_closed_eq (continuous_map.comp continuous_extension) continuous_id) _, rintros ⟨a⟩, show completion.map quotient.mk (completion.extension (separation_quotient.lift coe) ↑⟦a⟧) = ↑⟦a⟧, rw [extension_coe (separation_quotient.uniform_continuous_lift _), separation_quotient.lift_mk (uniform_continuous_coe α), completion.map_coe uniform_continuous_quotient_mk] }, { assume a, refine completion.induction_on a (is_closed_eq (continuous_extension.comp continuous_map) continuous_id) _, assume a, rw [map_coe uniform_continuous_quotient_mk, extension_coe (separation_quotient.uniform_continuous_lift _), separation_quotient.lift_mk (uniform_continuous_coe α) _] } end lemma uniform_continuous_completion_separation_quotient_equiv : uniform_continuous ⇑(completion_separation_quotient_equiv α) := uniform_continuous_extension lemma uniform_continuous_completion_separation_quotient_equiv_symm : uniform_continuous ⇑(completion_separation_quotient_equiv α).symm := uniform_continuous_map end separation_quotient_completion section prod variables [uniform_space β] protected def prod {α β} [uniform_space α] [uniform_space β] (p : completion α × completion β) : completion (α × β) := quotient.lift_on₂ p.1 p.2 (λa b, ⟦Cauchy.prod (a, b)⟧) $ assume a b c d hab hcd, quotient.sound $ separated_of_uniform_continuous uniform_continuous_prod $ separation_prod.2 ⟨hab, hcd⟩ lemma uniform_continuous_prod : uniform_continuous (@completion.prod α β _ _) := uniform_continuous_quotient_lift₂ $ suffices uniform_continuous (quotient.mk ∘ Cauchy.prod), { convert this, ext ⟨a, b⟩, refl }, Cauchy.uniform_continuous_prod.comp uniform_continuous_quotient_mk lemma prod_coe_coe (a : α) (b : β) : completion.prod ((a : completion α), (b : completion β)) = (a, b) := congr_arg quotient.mk $ Cauchy.prod_pure_cauchy_pure_cauchy a b end prod section map₂ protected def map₂ (f : α → β → γ) (a : completion α) (b : completion β) : completion γ := completion.map (λp:α×β, f p.1 p.2) (completion.prod (a, b)) lemma uniform_continuous_map₂' (f : α → β → γ) : uniform_continuous (λp:completion α×completion β, completion.map₂ f p.1 p.2) := uniform_continuous.comp uniform_continuous_prod completion.uniform_continuous_map lemma continuous_map₂ {δ} [topological_space δ] {f : α → β → γ} {a : δ → completion α} {b : δ → completion β} (ha : continuous a) (hb : continuous b) : continuous (λd:δ, completion.map₂ f (a d) (b d)) := (uniform_continuous_map₂' f).continuous.comp (continuous.prod_mk ha hb) lemma map₂_coe_coe (a : α) (b : β) (f : α → β → γ) (hf : uniform_continuous (λp:α×β, f p.1 p.2)) : completion.map₂ f (a : completion α) (b : completion β) = f a b := by rw [completion.map₂, completion.prod_coe_coe, completion.map_coe hf] end map₂ end completion end uniform_space
0df917c401121470962835475a5f60e9951a5949
95dcf8dea2baf2b4b0a60d438f27c35ae3dd3990
/src/group_theory/abelianization.lean
d324a3ab28b9d5e7063d6709f0bf99bdb4b6e774
[ "Apache-2.0" ]
permissive
uniformity1/mathlib
829341bad9dfa6d6be9adaacb8086a8a492e85a4
dd0e9bd8f2e5ec267f68e72336f6973311909105
refs/heads/master
1,588,592,015,670
1,554,219,842,000
1,554,219,842,000
179,110,702
0
0
Apache-2.0
1,554,220,076,000
1,554,220,076,000
null
UTF-8
Lean
false
false
2,851
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau The functor Grp → Ab which is the left adjoint of the forgetful functor Ab → Grp. -/ import group_theory.quotient_group universes u v variables (α : Type u) [group α] def commutator : set α := { x | ∃ L : list α, (∀ z ∈ L, ∃ p q, p * q * p⁻¹ * q⁻¹ = z) ∧ L.prod = x } instance : normal_subgroup (commutator α) := { one_mem := ⟨[], by simp⟩, mul_mem := λ x y ⟨L1, HL1, HP1⟩ ⟨L2, HL2, HP2⟩, ⟨L1 ++ L2, list.forall_mem_append.2 ⟨HL1, HL2⟩, by simp*⟩, inv_mem := λ x ⟨L, HL, HP⟩, ⟨L.reverse.map has_inv.inv, λ x hx, let ⟨y, h3, h4⟩ := list.exists_of_mem_map hx in let ⟨p, q, h5⟩ := HL y (list.mem_reverse.1 h3) in ⟨q, p, by rw [← h4, ← h5]; simp [mul_assoc]⟩, by rw ← HP; from list.rec_on L (by simp) (λ hd tl ih, by rw [list.reverse_cons, list.map_append, list.prod_append, ih]; simp)⟩, normal := λ x ⟨L, HL, HP⟩ g, ⟨L.map $ λ z, g * z * g⁻¹, λ x hx, let ⟨y, h3, h4⟩ := list.exists_of_mem_map hx in let ⟨p, q, h5⟩ := HL y h3 in ⟨g * p * g⁻¹, g * q * g⁻¹, by rw [← h4, ← h5]; simp [mul_assoc]⟩, by rw ← HP; from list.rec_on L (by simp) (λ hd tl ih, by rw [list.map_cons, list.prod_cons, ih]; simp [mul_assoc])⟩, } def abelianization : Type u := quotient_group.quotient $ commutator α namespace abelianization local attribute [instance] quotient_group.left_rel normal_subgroup.to_is_subgroup instance : comm_group (abelianization α) := { mul_comm := λ x y, quotient.induction_on₂ x y $ λ m n, quotient.sound $ ⟨[n⁻¹*m⁻¹*n*m], by simp; refine ⟨n⁻¹, m⁻¹, _⟩; simp, by simp [mul_assoc]⟩, .. quotient_group.group _ } variable {α} def of (x : α) : abelianization α := quotient.mk x instance of.is_group_hom : is_group_hom (@of α _) := ⟨λ _ _, rfl⟩ section lift variables {β : Type v} [comm_group β] (f : α → β) [is_group_hom f] def lift : abelianization α → β := quotient_group.lift _ f $ λ x ⟨L, HL, hx⟩, hx ▸ list.rec_on L (λ _, is_group_hom.one f) (λ hd tl HL ih, by rw [list.forall_mem_cons] at ih; rcases ih with ⟨⟨p, q, hpq⟩, ih⟩; specialize HL ih; rw [list.prod_cons, is_group_hom.mul f, ← hpq, HL]; simp [is_group_hom.mul f, is_group_hom.inv f, mul_comm]) HL instance lift.is_group_hom : is_group_hom (lift f) := quotient_group.is_group_hom_quotient_lift _ _ _ @[simp] lemma lift.of (x : α) : lift f (of x) = f x := rfl theorem lift.unique (g : abelianization α → β) [is_group_hom g] (hg : ∀ x, g (of x) = f x) {x} : g x = lift f x := quotient.induction_on x $ λ m, hg m end lift end abelianization
ad887f25d3036facdbb24b02e3b5ac595541369e
5e42295de7f5bcdf224b94603a8ec29b17c2d367
/comp_val.lean
b4a9359aa054d1a31bf52d07943f329cfff82742
[]
no_license
pnmadelaine/lean_polya
9369e0d87dce773f91383bb58ac6fde0a00a1a40
1c62b0b3fa71044b0225ce28030627d251b08ebc
refs/heads/master
1,590,161,172,243
1,515,010,019,000
1,515,010,019,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,544
lean
/- Copyright (c) 2017 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Robert Y. Lewis The built-in comp_val tactic only applies to ℕ and certain other datatypes. This extends it to work on arbitrary algebraic structures. For efficiency reasons, this should be ported to C++ eventually. -/ #exit import data.rat open tactic expr universe u variables {α : Type u} {a b : α} section semirings variable [linear_ordered_semiring α] theorem bit0_ge_bit0 (h : a ≥ b) : bit0 a ≥ bit0 b := add_le_add h h theorem bit0_gt_bit0 (h : a > b) : bit0 a > bit0 b := add_lt_add h h theorem bit1_gt_bit0 (h : a ≥ b) : bit1 a > bit0 b := suffices a + a + 1 > b + b + 0, by rw add_zero at this; apply this, add_lt_add_of_le_of_lt (bit0_ge_bit0 h) zero_lt_one theorem bit0_gt_bit1 (h : a ≥ b + 1) : bit0 a > bit1 b := begin unfold bit0 bit1, apply lt_of_lt_of_le, rotate 1, apply add_le_add, repeat {apply h}, simp, apply add_lt_add_left, apply add_lt_add_left, apply lt_add_of_pos_left, apply zero_lt_one end theorem bit0_gt_bit1' {c : α} (h : a ≥ c) (h2 : b+1=c) : bit0 a > bit1 b := begin apply bit0_gt_bit1, rw h2, apply h end theorem bit1_gt_bit1 (h : a > b) : bit1 a > bit1 b := add_lt_add_right (bit0_gt_bit0 h) _ theorem bit0_gt_zero (h : a > 0) : bit0 a > 0 := add_pos h h theorem bit1_gt_zero (h : a ≥ 0) : bit1 a > 0 := add_pos_of_nonneg_of_pos (add_nonneg h h) zero_lt_one theorem bit0_gt_one (h : a ≥ 1) : bit0 a > 1 := begin unfold bit0, rw [←zero_add (1 : α)], apply add_lt_add_of_lt_of_le, apply lt_of_lt_of_le, apply zero_lt_one, repeat {assumption} end theorem bit1_gt_one (h : a > 0) : bit1 a > 1 := begin unfold bit1 bit0, apply lt_add_of_pos_left, apply add_pos, repeat {assumption} end end semirings section rings variable [linear_ordered_ring α] theorem gt_neg {c : α} (h : a + b = c) (h2 : c > 0) : a > -b := have h' : b + a = c, from add_comm a b ▸ h, calc a = -b + c : eq_neg_add_of_add_eq h' ... > -b : lt_add_of_pos_right _ h2 end rings set_option eqn_compiler.max_steps 20000 meta def mk_gt_prf (mk_ge_prf : expr → expr → tactic expr) : expr → expr → tactic expr | (`(bit0 %%t1)) (`(bit0 %%t2)) := do prf ← mk_gt_prf t1 t2, to_expr ``(bit0_gt_bit0 %%prf) | (`(bit1 %%t1)) (`(bit0 %%t2)) := do prf ← mk_ge_prf t1 t2, tactic.mk_app `bit1_gt_bit0 [prf] | (`(bit0 %%t1)) (`(@bit1 %%t %%_ %%_ %%t2)) := do (n, eqp) ← to_expr ``(%%t2 + 1 : %%t) >>= norm_num, prf ← mk_ge_prf t1 n, tactic.mk_app `bit0_gt_bit1' [prf, eqp] | (`(bit1 %%t1)) (`(bit1 %%t2)) := do prf ← mk_gt_prf t1 t2, tactic.mk_app `bit1_gt_bit1 [prf] | (`(bit0 %%t1)) (`(@has_zero.zero %%t %%_)) := do prf ← to_expr ``(0 : %%t) >>= mk_gt_prf t1, tactic.mk_app `bit0_gt_zero [prf] | (`(bit0 %%t1)) (`(@has_one.one %%t %%_)) := do prf ← to_expr ``(1 : %%t) >>= mk_ge_prf t1, to_expr ``(bit0_gt_one %%prf) --tactic.mk_mapp `bit0_gt_one [none, none, some t1, some prf] | (`(bit1 %%t1)) (`(@has_zero.zero %%t %%_)) := do prf ← to_expr ``(0 : %%t) >>= mk_ge_prf t1 , tactic.mk_app `bit1_gt_zero [prf] | (`(@bit1 %%_ %%_ %%_ %%t1)) (`(@has_one.one %%t %%_)) := do prf ← to_expr ``(0 : %%t) >>= mk_gt_prf t1, tactic.mk_app `bit1_gt_one [prf] | (`(@has_one.one %%tp %%_)) (`(@has_zero.zero %%_ %%_)) := trace "abc" >> to_expr ``(@zero_lt_one %%tp _) | (t1) `(@has_neg.neg %%tp %%_ %%t2) := do (n, eqp) ← to_expr ``(%%t1 + %%t2) >>= norm_num, prf ← to_expr ``(0 : %%tp) >>= mk_gt_prf n, tactic.mk_app `gt_neg [eqp, prf] | a b := tactic.fail "mk_gt_prf failed" meta def mk_ge_prf : expr → expr → tactic expr := λ e1 e2, (guard (e1 = e2) >> to_expr ``((le_refl _ : %%e1 ≥ %%e2))) <|> do gtprf ← mk_gt_prf mk_ge_prf e1 e2, mk_app `le_of_lt [gtprf] lemma rat_gt {a b c d : ℚ} (h : a*d > c*b) (hb : b > 0) (hd : d > 0) : a / b > c / d := begin apply lt_div_of_mul_lt, assumption, rw div_mul_eq_mul_div, apply div_lt_of_mul_lt_of_pos, repeat {assumption} end lemma rat_gt' {a b c : ℚ} (h : a > c*b) (hb : b > 0) : a / b > c := begin apply lt_div_of_mul_lt, repeat {assumption} end lemma rat_gt'' {a b c : ℚ} (h : a*c > b) (hb : c > 0) : a > b / c := begin apply div_lt_of_mul_lt_of_pos, repeat {assumption} end lemma eqs_gt_trans {a b c d : ℚ} (ha : a = b) (hc : c = d) (h : b > d) : a > c := by cc lemma eq_gt_trans {a b c : ℚ} (ha : a = b) (h : b > c) : a > c := by cc lemma eq_gt_trans' {a b c : ℚ} (ha : a = b) (h : c > b) : c > a := by cc meta def mk_rat_gt_pf (mk_rat_ge_prf : expr → expr → tactic expr) : expr → expr → tactic expr | `(%%a / %%b) `(%%c / %%d) := do (lhs, lprf) ← norm_num `(%%a * %%d : ℚ), (rhs, rprf) ← norm_num `(%%c * %%b : ℚ), gtpf ← mk_gt_prf mk_rat_ge_prf lhs rhs, gtpf' ← mk_app `eqs_gt_trans [lprf, rprf, gtpf], bs ← mk_gt_prf mk_rat_ge_prf b `(0 : ℚ), ds ← mk_gt_prf mk_rat_ge_prf d `(0 : ℚ), mk_app ``rat_gt [gtpf', bs, ds] | `(%%a / %%b) c := do (lhs, lprf) ← norm_num `(%%c * %%b : ℚ), gtpf ← mk_gt_prf mk_rat_ge_prf a lhs, gtpf' ← mk_app `eq_gt_trans' [lprf, gtpf], bs ← mk_gt_prf mk_rat_ge_prf b `(0 : ℚ), mk_app ``rat_gt' [gtpf', bs] | a `(%%b / %%c) := do (lhs, lprf) ← norm_num `(%%a * %%c : ℚ), gtpf ← mk_rat_gt_pf lhs b, trace "a1", gtpf' ← mk_app `eq_gt_trans [lprf, gtpf], trace "a2", bs ← mk_gt_prf mk_rat_ge_prf c `(0 : ℚ), trace ("a3", a, b, c), infer_type gtpf' >>= trace, infer_type bs >>= trace, mk_app ``rat_gt'' [gtpf', bs] | a b := trace "!!!!" >> trace a >> trace b >> mk_gt_prf mk_rat_ge_prf a b--fail "mk_rat_gt_pf failed" meta def mk_rat_ge_prf : expr → expr → tactic expr := λ e1 e2, (guard (e1 = e2) >> to_expr ``((le_refl _ : %%e1 ≥ %%e2))) <|> do gtprf ← mk_rat_gt_pf mk_rat_ge_prf e1 e2, trace "mk_rat_ge_prf:", infer_type gtprf >>= trace, l ← mk_app `le_of_lt [gtprf], infer_type l >>= trace, return l meta def mk_gt_prf' (lhs rhs : expr) : tactic expr := do tp ← infer_type lhs, if tp = `(ℚ) then mk_rat_gt_pf mk_rat_ge_prf lhs rhs else mk_gt_prf @mk_ge_prf lhs rhs meta def mk_ge_prf' (lhs rhs : expr) : tactic expr := do tp ← infer_type lhs, if tp = `(ℚ) then mk_rat_ge_prf lhs rhs else mk_ge_prf lhs rhs -- assumes ≥ or > and already normalized meta def gen_comp_val_prf : expr → tactic expr | `(@has_le.le %%_ %%_ %%lhs %%rhs) := to_expr ``(%%rhs ≥ %%lhs) >>= gen_comp_val_prf | `(@has_lt.lt %%_ %%_ %%lhs %%rhs) := to_expr ``(%%rhs > %%lhs) >>= gen_comp_val_prf | `(@ge %%_ %%_ %%lhs %%rhs) := mk_ge_prf' lhs rhs | `(@gt %%_ %%_ %%lhs %%rhs) := mk_gt_prf' /-mk_ge_prf-/ lhs rhs | _ := tactic.fail "comp_val' didn't match" meta def is_num : expr → bool | `(@bit0 %%_ %%_ %%t) := is_num t | `(@bit1 %%_ %%_ %%_ %%t) := is_num t | `(@has_zero.zero %%_ %%_) := tt | `(@has_one.one %%_ %%_) := tt | _ := ff meta def is_signed_num : expr → bool | `(-%%a) := is_num a | a := is_num a #check @rewrite_core meta def gen_comp_val : tactic unit := do t ← target, [_, _, lhs, rhs] ← return $ get_app_args t, if is_num lhs then if is_num rhs then gen_comp_val_prf t >>= apply else do (rhs', prf) ← norm_num rhs, rewrite_target prf, target >>= gen_comp_val_prf >>= apply else do (lhs', prfl) ← norm_num lhs, rewrite_target prfl, if is_num rhs then do trace "here", trace_state, t ← target, t ← gen_comp_val_prf t, trace "now here", infer_type t >>= trace, failed-- exact t else do (rhs', prf) ← norm_num rhs, rewrite_target prf, t ← target >>= gen_comp_val_prf, apply t meta def make_expr_into_num : expr → tactic expr := λ e, do t ← infer_type e, (do onet ← to_expr ``(1 : %%t), unify e onet, return onet) <|> (do zerot ← to_expr ``(0 : %%t), unify e zerot, return zerot) <|> (do m ← mk_meta_var t, b0m ← to_expr ``(bit0 %%m), unify e b0m, m' ← make_expr_into_num m, to_expr ``(bit0 %%m')) <|> (do m ← mk_meta_var t, b1m ← to_expr ``(bit1 %%m), unify e b1m, m' ← make_expr_into_num m, to_expr ``(bit1 %%m')) <|> (do m ← mk_meta_var t, negm ← to_expr ``(- %%m), unify e negm, rv ← make_expr_into_num m, to_expr ``(- %%rv)) meta def make_expr_into_rat (e : expr) : tactic expr := make_expr_into_num e <|> do t ← infer_type e, num ← mk_meta_var t, den ← mk_meta_var t, to_expr ``(%%num / %%den) >>= unify e, num' ← make_expr_into_num num, den' ← make_expr_into_num den, to_expr ``(%%num' / %%den') meta def make_expr_into_mul (e : expr) : tactic expr := do t ← infer_type e, m1 ← mk_meta_var t, m2 ← mk_meta_var t, to_expr ``(%%m1 * %%m2) >>= unify e, lhs ← make_expr_into_rat m1, rhs ← make_expr_into_rat m2, to_expr ``(%%lhs * %%rhs) meta def make_expr_into_sum : expr → tactic expr := λ e, (do t ← infer_type e, m1 ← mk_meta_var t, m2 ← mk_meta_var t, to_expr ``(%%m1 + %%m2) >>= unify e, lhs ← make_expr_into_sum m1, rhs ← make_expr_into_sum m2, to_expr ``(%%lhs + %%rhs)) <|> (make_expr_into_mul e) meta def make_expr_into_eq_zero (e : expr) : tactic expr := do m0 ← mk_mvar, m1 ← mk_mvar, m2 ← mk_mvar, to_expr ``(@eq %%m1 %%m0 (@has_zero.zero %%m1 %%m2))>>= unify e, return m0 set_option profiler true example : (198 : ℚ) / 100 ≤ 2 := by gen_comp_val--btrivial
ddfa8087269daa15a71f42dd0b5131e4d16cba60
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/data/rbtree/min_max.lean
56bb829e6dfa6889c54e15f8bb0d2568c45d115e
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,721
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import data.rbtree.basic universe u namespace rbnode variables {α : Type u} {lt : α → α → Prop} lemma mem_of_min_eq (lt : α → α → Prop) [is_irrefl α lt] {a : α} {t : rbnode α} : t.min = some a → mem lt a t := begin induction t, { intros, contradiction }, all_goals { cases t_lchild; simp [rbnode.min]; intro h, { subst t_val, simp [mem, irrefl_of lt a] }, all_goals { rw [mem], simp [t_ih_lchild h] } } end lemma mem_of_max_eq (lt : α → α → Prop) [is_irrefl α lt] {a : α} {t : rbnode α} : t.max = some a → mem lt a t := begin induction t, { intros, contradiction }, all_goals { cases t_rchild; simp [rbnode.max]; intro h, { subst t_val, simp [mem, irrefl_of lt a] }, all_goals { rw [mem], simp [t_ih_rchild h] } } end variables [is_strict_weak_order α lt] lemma eq_leaf_of_min_eq_none {t : rbnode α} : t.min = none → t = leaf := begin induction t, { intros, refl }, all_goals { cases t_lchild; simp [rbnode.min, false_implies_iff]; intro h, all_goals { have := t_ih_lchild h, contradiction } } end lemma eq_leaf_of_max_eq_none {t : rbnode α} : t.max = none → t = leaf := begin induction t, { intros, refl }, all_goals { cases t_rchild; simp [rbnode.max, false_implies_iff]; intro h, all_goals { have := t_ih_rchild h, contradiction } } end lemma min_is_minimal {a : α} {t : rbnode α} : ∀ {lo hi}, is_searchable lt t lo hi → t.min = some a → ∀ {b}, mem lt b t → a ≈[lt] b ∨ lt a b := begin classical, induction t, { simp [strict_weak_order.equiv], intros _ _ hs hmin b, contradiction }, all_goals { cases t_lchild; intros lo hi hs hmin b hmem, { simp [rbnode.min] at hmin, subst t_val, simp [mem] at hmem, cases hmem with heqv hmem, { left, exact heqv.swap }, { have := lt_of_mem_right hs (by constructor) hmem, right, assumption } }, all_goals { have hs' := hs, cases hs, simp [rbnode.min] at hmin, rw [mem] at hmem, blast_disjs, { exact t_ih_lchild hs_hs₁ hmin hmem }, { have hmm := mem_of_min_eq lt hmin, have a_lt_val := lt_of_mem_left hs' (by constructor) hmm, have a_lt_b := lt_of_lt_of_incomp a_lt_val hmem.swap, right, assumption }, { have hmm := mem_of_min_eq lt hmin, have a_lt_b := lt_of_mem_left_right hs' (by constructor) hmm hmem, right, assumption } } } end lemma max_is_maximal {a : α} {t : rbnode α} : ∀ {lo hi}, is_searchable lt t lo hi → t.max = some a → ∀ {b}, mem lt b t → a ≈[lt] b ∨ lt b a := begin classical, induction t, { simp [strict_weak_order.equiv], intros _ _ hs hmax b, contradiction }, all_goals { cases t_rchild; intros lo hi hs hmax b hmem, { simp [rbnode.max] at hmax, subst t_val, simp [mem] at hmem, cases hmem with hmem heqv, { have := lt_of_mem_left hs (by constructor) hmem, right, assumption }, { left, exact heqv.swap } }, all_goals { have hs' := hs, cases hs, simp [rbnode.max] at hmax, rw [mem] at hmem, blast_disjs, { have hmm := mem_of_max_eq lt hmax, have a_lt_b := lt_of_mem_left_right hs' (by constructor) hmem hmm, right, assumption }, { have hmm := mem_of_max_eq lt hmax, have val_lt_a := lt_of_mem_right hs' (by constructor) hmm, have a_lt_b := lt_of_incomp_of_lt hmem val_lt_a, right, assumption }, { exact t_ih_rchild hs_hs₂ hmax hmem } } } end end rbnode
bf025dcf2a86265a65f4b37e927fe8a79785fd7b
79cc757e5e5b09c7a522f717a6c490d321d36469
/src/mywork/sep_29.lean
d6cb42df3d355ff83024ed69891372867aa66bde
[]
no_license
LukeMathe/cs2120f21
534c3b8868dcfdea98a9d22513180c8a062794c6
d51940b174569a8782e62ae027b108b5f099a9aa
refs/heads/main
1,693,418,664,935
1,634,585,653,000
1,634,585,653,000
403,762,076
0
0
null
1,630,963,485,000
1,630,963,485,000
null
UTF-8
Lean
false
false
3,815
lean
/- UPDATE: Test distributed after class on Monday. Monday will be a review day. The test is due back Wednesday before class. In class Wednesday we will have at least a short quiz to sanity check what you will have submitted for the test. We reserve the right to do follow-on in-person testing if the results indicate a possible problem. -/ /- REVIEW: Last time we focused on the question, how do we construct a proof of ∃ x, P x. To do so, you apply the introduction rule for exists. It's called exists.intro in Lean. You apply it to two arguments: a specific value, w, in place of x, and a proof that that particular w satisfies the predicate, P, i.e., that there is a proof of the proposition, P w. In other words, you can think of a proof of ∃ x, P x, as a pair, ⟨w, pf ⟩, where w is a witness and pf is a proof of P w. -/ /- Today we'll delve deeper into the mysteries of exists elimination, or how you can *use* a proof of ∃ x, P x. Here's the idea: If you have a proof, ex, of of ∃ (x : X), P x, you can apply exists.elim to ex, and (after a few more simple maneuvers) have yourself a specific value, (w : X), and a proof that w satisfies P, i.e., (pf : P w). The idea is that you can then uses the values in your subsequent proof steps. Why does this rule make sense? Consider a very simple example. If I tell you there exists some green ball, you can say, "well, call it b," and give that we know it's green, we also know that it satisfies the isGreen _ predicate, so we can also assume we have a proof of (isGreen b). In this example, b is a witness to the fact that some object satisfies the predicate. The proof then shows for sure that that is so. -/ example : ∃ (b : bool), b && tt = ff := begin apply exists.intro ff, exact eq.refl ff, end example : (exists (b : bool), b && tt = ff) → (∃ (b : bool), true) := begin assume h, cases h with w pf, apply exists.intro w, trivial, end /- Let's set up some assumptions so that we can explore their consequences when it comes to existentially quantified propositions. -/ /- Beachballs! What could be more fun -/ axioms (Ball : Type) -- There are balls (Green : Ball → Prop) -- a Ball can be Green (Red : Ball → Prop) -- a Ball can be Red (b1 b2 : Ball) -- b1 and b2 are balls (b1r : Red b1) -- b1 is red (b1g : Green b1) -- b1 is green (b2r : Red b2) -- b2 is red example : (∃ (b : Ball), Red b ∧ Green b) → (∃ (b : Ball), Red b) := begin assume h, cases h with b rg, apply exists.intro b, apply and.elim_left rg, end example : (∃ (b : Ball), Red b ∨ Green b) → (∃ (b : Ball), Green b ∨ Red b) := begin assume h, cases h with b rg, apply exists.intro b, cases rg, apply or.intro_right, apply rg, apply or.intro_left, apply rg, end example : (∃ (b : Ball), Red b ∨ Green b) → (∃ (b : Ball), Red b) := begin end example : (∃ (b : Ball), Red b) → (∃ (b : Ball), Red b ∨ Green b) := begin end /- Social Networks -/ axioms (Person : Type) (Nice : Person → Prop) (Likes : Person → Person → Prop) example : (∃ (p1 : Person), ∀ (p2 : Person), Likes p2 p1) → (∀ (e : Person), ∃ (s : Person), Likes e s) := begin assume h, assume e, cases h with p pf, apply exists.intro p, apply pf e, end /- Write formal expressions for each of the following English language sentences. -/ -- Everyone likes him or herself -- Someone doesn't like him or herself -- There is someone likes someone else -- No one likes anyone who dislikes them -- Everyone likes anyone who is nice -- No one likes anyone who is not nice /- If everyone who's nice likes someone, then there is someone whom everyone who is nice likes. -/
c734595a53f3b6173a850971cb3189112a089362
1fd908b06e3f9c1252cb2285ada1102623a67f72
/types/bool.lean
96a4a547d6212aa644907b798bdd6388cfb916a6
[ "Apache-2.0" ]
permissive
avigad/hott3
609a002849182721e7c7ae536d9f1e2956d6d4d3
f64750cd2de7a81e87d4828246d1369d59f16f43
refs/heads/master
1,629,027,243,322
1,510,946,717,000
1,510,946,717,000
103,570,461
0
0
null
1,505,415,620,000
1,505,415,620,000
null
UTF-8
Lean
false
false
4,716
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura, Floris van Doorn Partially ported from the standard library -/ import ..init universes u v w hott_theory namespace hott open decidable namespace bool -- local attribute bor [reducible] -- local attribute band [reducible] @[hott] def dichotomy : ∀ b, b = ff ⊎ b = tt | ff := sum.inl rfl | tt := sum.inr rfl @[hott, hsimp] def cond_ff {A : Type _} (t e : A) : cond ff t e = e := idp @[hott, hsimp] def cond_tt {A : Type _} (t e : A) : cond tt t e = t := idp @[hott] def eq_tt_of_ne_ff : Π {a : bool}, a ≠ ff → a = tt | tt H := rfl | ff H := absurd rfl H @[hott] def eq_ff_of_ne_tt : Π {a : bool}, a ≠ tt → a = ff | tt H := absurd rfl H | ff H := rfl @[hott] def absurd_of_eq_ff_of_eq_tt {B : Type _} {a : bool} (H₁ : a = ff) (H₂ : a = tt) : B := absurd (H₁⁻¹ ⬝ H₂) ff_ne_tt @[hott, hsimp] def tt_bor (a : bool) : tt || a = tt := idp @[hott, hsimp] def bor_tt (a : bool) : a || tt = tt := by cases a; refl @[hott, hsimp] def ff_bor (a : bool) : ff || a = a := by cases a; refl @[hott, hsimp] def bor_ff (a : bool) : a || ff = a := by cases a; refl @[hott, hsimp] def bor_self (a : bool) : a || a = a := by cases a; refl @[hott, hsimp] def bor.comm (a b : bool) : a || b = b || a := by cases a; repeat { cases b <|> reflexivity } @[hott, hsimp] def bor.assoc (a b c) : (a || b) || c = a || (b || c) := by cases a; hsimp @[hott] def or_of_bor_eq : Π {a b}, a || b = tt → a = tt ⊎ b = tt | ff b H := sum.inr (by hsimp at H; assumption) | tt b H := sum.inl idp @[hott] def bor_inl {a b : bool} (H : a = tt) : a || b = tt := by rwr H @[hott] def bor_inr {a b : bool} (H : b = tt) : a || b = tt := by cases a; rwr H @[hott, hsimp] def ff_band (a : bool) : ff && a = ff := rfl @[hott, hsimp] def tt_band (a : bool) : tt && a = a := by cases a; refl @[hott, hsimp] def band_ff (a : bool) : a && ff = ff := by cases a; refl @[hott, hsimp] def band_tt (a : bool) : a && tt = a := by cases a; refl @[hott, hsimp] def band_self (a : bool) : a && a = a := by cases a; refl @[hott, hsimp] def band.comm (a b : bool) : a && b = b && a := by cases a; cases b; refl @[hott, hsimp] def band.assoc (a b c : bool) : (a && b) && c = a && (b && c) := by cases a; hsimp @[hott] def band_elim_left {a b : bool} (H : a && b = tt) : a = tt := by cases a; hsimp at H; assumption @[hott] def band_intro {a b : bool} (H₁ : a = tt) (H₂ : b = tt) : a && b = tt := by hsimp * @[hott] def band_elim_right {a b : bool} (H : a && b = tt) : b = tt := by apply band_elim_left; rwra band.comm @[hott, hsimp] def bnot_bnot (a : bool) : bnot (bnot a) = a := bool.cases_on a rfl rfl @[hott, hsimp] def bnot_empty : bnot ff = tt := rfl @[hott, hsimp] def bnot_unit : bnot tt = ff := rfl @[hott] def eq_tt_of_bnot_eq_ff {a : bool} : bnot a = ff → a = tt := bool.cases_on a (by dsimp; intro; hsimp*) (λ h, rfl) @[hott] def eq_ff_of_bnot_eq_tt {a : bool} : bnot a = tt → a = ff := bool.cases_on a (λ h, rfl) (by dsimp; intro; hsimp*) /- HoTT-related stuff -/ open is_equiv equiv function is_trunc option unit decidable @[hott, instance] def is_equiv_bnot : is_equiv bnot := by fapply is_equiv.mk bnot bnot; intro a; cases a; refl @[hott] def bnot_ne : Π(b : bool), bnot b ≠ b | tt := ff_ne_tt | ff := ne.symm ff_ne_tt @[hott] def equiv_bnot : bool ≃ bool := equiv.mk bnot (by apply_instance) @[hott] def eq_bnot : bool = bool := ua equiv_bnot @[hott] def eq_bnot_ne_idp : eq_bnot ≠ idp := assume H : eq_bnot = idp, have H2 : bnot = id, from (cast_ua_fn equiv_bnot).inverse ⬝ ap cast H, absurd (ap10 H2 tt) ff_ne_tt @[hott] def is_set_bool : is_set bool := by apply_instance @[hott] def not_is_prop_bool_eq_bool : ¬ is_prop (bool = bool) := λ H, eq_bnot_ne_idp (by apply is_prop.elim) @[hott] def bool_equiv_option_unit : bool ≃ option unit := begin fapply equiv.MK, { intro b, cases b, exact none, exact some star}, { intro u, cases u, exact ff, exact tt}, { intro u, cases u with u, reflexivity, cases u, reflexivity}, { intro b, cases b, reflexivity, reflexivity}, end /- pointed and truncated bool -/ open pointed @[hott, instance] def pointed_bool : pointed bool := pointed.mk ff @[hott] def ptbool : Set* := pSet.mk' bool @[hott] def pbool : Type* := ptbool.to_pType @[hott] def tbool : Set := trunctype.mk bool (by apply_instance) notation `bool*` := pbool end bool end hott
346608cbd79dfdef473428940fb548f37d5b455d
e9078bde91465351e1b354b353c9f9d8b8a9c8c2
/colimit/seq_colim.hlean
222a46f7ab228fe5a5858b471706287afd1e8497
[ "Apache-2.0" ]
permissive
EgbertRijke/leansnippets
09fb7a9813477471532fbdd50c99be8d8fe3e6c4
1d9a7059784c92c0281fcc7ce66ac7b3619c8661
refs/heads/master
1,610,743,957,626
1,442,532,603,000
1,442,532,603,000
41,563,379
0
0
null
1,440,787,514,000
1,440,787,514,000
null
UTF-8
Lean
false
false
19,973
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Egbert Rijke -/ import hit.quotient .sequence cubical.squareover types.arrow .move_to_lib types.equiv open eq nat sigma sigma.ops quotient equiv equiv.ops pi is_trunc is_equiv fiber namespace seq_colim section parameters (A : ℕ → Type) [f : seq_diagram A] variables {n : ℕ} (a : A n) include f local abbreviation B := Σ(n : ℕ), A n inductive seq_rel : B → B → Type := | Rmk : Π{n : ℕ} (a : A n), seq_rel ⟨succ n, f a⟩ ⟨n, a⟩ open seq_rel local abbreviation R := seq_rel definition seq_colim : Type := quotient seq_rel parameters {A f} variable (n) -- do we want to make n explicit for ι? 'ι a' is ambiguous for a : A n. It can be 'ι n a' or 'ι 0 a' in a shifted sequence definition inclusion [constructor] : seq_colim := class_of R ⟨n, a⟩ abbreviation ι' [constructor] := @inclusion variable {n} abbreviation ι [constructor] [parsing-only] := @inclusion n definition glue : ι (f a) = ι a := eq_of_rel seq_rel (Rmk a) protected definition rec {P : seq_colim → Type} (Pincl : Π⦃n : ℕ⦄ (a : A n), P (ι a)) (Pglue : Π(n : ℕ) (a : A n), Pincl (f a) =[glue a] Pincl a) (aa : seq_colim) : P aa := begin fapply (quotient.rec_on aa), { intro a, cases a, apply Pincl}, { intro a a' H, cases H, apply Pglue} end protected definition rec_on [reducible] {P : seq_colim → Type} (aa : seq_colim) (Pincl : Π⦃n : ℕ⦄ (a : A n), P (ι a)) (Pglue : Π⦃n : ℕ⦄ (a : A n), Pincl (f a) =[glue a] Pincl a) : P aa := rec Pincl Pglue aa theorem rec_glue {P : seq_colim → Type} (Pincl : Π⦃n : ℕ⦄ (a : A n), P (ι a)) (Pglue : Π⦃n : ℕ⦄ (a : A n), Pincl (f a) =[glue a] Pincl a) {n : ℕ} (a : A n) : apdo (rec Pincl Pglue) (glue a) = Pglue a := !rec_eq_of_rel protected definition elim {P : Type} (Pincl : Π⦃n : ℕ⦄ (a : A n), P) (Pglue : Π⦃n : ℕ⦄ (a : A n), Pincl (f a) = Pincl a) : seq_colim → P := rec Pincl (λn a, pathover_of_eq (Pglue a)) protected definition elim_on [reducible] {P : Type} (aa : seq_colim) (Pincl : Π⦃n : ℕ⦄ (a : A n), P) (Pglue : Π⦃n : ℕ⦄ (a : A n), Pincl (f a) = Pincl a) : P := elim Pincl Pglue aa theorem elim_glue {P : Type} (Pincl : Π⦃n : ℕ⦄ (a : A n), P) (Pglue : Π⦃n : ℕ⦄ (a : A n), Pincl (f a) = Pincl a) {n : ℕ} (a : A n) : ap (elim Pincl Pglue) (glue a) = Pglue a := begin apply eq_of_fn_eq_fn_inv !(pathover_constant (glue a)), rewrite [▸*,-apdo_eq_pathover_of_eq_ap,↑elim,rec_glue], end protected definition elim_type (Pincl : Π⦃n : ℕ⦄ (a : A n), Type) (Pglue : Π⦃n : ℕ⦄ (a : A n), Pincl (f a) ≃ Pincl a) : seq_colim → Type := elim Pincl (λn a, ua (Pglue a)) protected definition elim_type_on [reducible] (aa : seq_colim) (Pincl : Π⦃n : ℕ⦄ (a : A n), Type) (Pglue : Π⦃n : ℕ⦄ (a : A n), Pincl (f a) ≃ Pincl a) : Type := elim_type Pincl Pglue aa theorem elim_type_glue (Pincl : Π⦃n : ℕ⦄ (a : A n), Type) (Pglue : Π⦃n : ℕ⦄ (a : A n), Pincl (f a) ≃ Pincl a) {n : ℕ} (a : A n) : transport (elim_type Pincl Pglue) (glue a) = Pglue a := by rewrite [tr_eq_cast_ap_fn,↑elim_type,elim_glue];apply cast_ua_fn end end seq_colim attribute seq_colim.inclusion seq_colim.ι [constructor] attribute seq_colim.rec seq_colim.elim [unfold 6] [recursor 6] attribute seq_colim.elim_type [unfold 5] attribute seq_colim.rec_on seq_colim.elim_on [unfold 4] attribute seq_colim.elim_type_on [unfold 3] namespace seq_colim variables {A : ℕ → Type} [f : seq_diagram A] variables {n : ℕ} (a : A n) include f definition ess_constant_seq_back (H : is_equiseq f) : seq_colim A → A 0 := begin intro x, induction x with n a, induction n with n g, exact a, end definition ess_constant_seq (H : is_equiseq f) : is_equiv (@inclusion 0) := begin exact sorry end definition rep_glue (k : ℕ) : @ι _ _ _ (rep k a) = ι a := begin induction k with k IH, { reflexivity}, { exact glue (rep k a) ⬝ IH} end definition shift_up [unfold 3] (a : seq_colim A) : seq_colim (λk, A (succ k)) := begin induction a, { exact ι (f a)}, { exact glue (f a)} end definition shift_down [unfold 3] (a : seq_colim (λn, A (succ n))) : seq_colim A := begin induction a, { exact ι a}, { exact glue a} end -- definition kshift_up (k : ℕ) (a : seq_colim A) : @seq_colim (λn, A (k + n)) (kshift_diag A k) := -- begin -- induction a, -- { apply ι' n, refine my.add.comm n k ▸ rep k a}, -- { exact sorry} -- end -- definition kshift_down (k : ℕ) (a : @seq_colim (λn, A (k + n)) (kshift_diag A k)) : seq_colim A := -- begin -- induction a, -- { exact ι a}, -- { exact glue a} -- end definition kshift_up' (k : ℕ) (a : seq_colim A) : @seq_colim (λn, A (n + k)) (kshift_diag' A k) := begin induction a, { apply ι' n, exact rep k a}, { exact sorry} end definition kshift_down' (k : ℕ) (a : @seq_colim (λn, A (n + k)) (kshift_diag' A k)) : seq_colim A := begin induction a, { exact ι a}, { esimp, exact sorry} end variable (A) definition shift_equiv [constructor] : seq_colim A ≃ seq_colim (λn, A (succ n)) := equiv.MK shift_up shift_down abstract begin intro a, induction a, { esimp, exact glue a}, { apply eq_pathover, rewrite [▸*, ap_id, ap_compose shift_up shift_down, ↑shift_down, @elim_glue (λk, A (succ k)) _, ↑shift_up], apply square_of_eq, apply whisker_right, exact !elim_glue⁻¹} end end abstract begin intro a, induction a, { exact glue a}, { apply eq_pathover, rewrite [▸*, ap_id, ap_compose shift_down shift_up, ↑shift_up, @elim_glue A _, ↑shift_down], apply square_of_eq, apply whisker_right, exact !elim_glue⁻¹} end end -- definition kshift_equiv [constructor] (k : ℕ) -- : seq_colim A ≃ @seq_colim (λn, A (k + n)) (kshift_diag A k) := -- equiv.MK (kshift_up k) -- (kshift_down k) -- abstract begin -- intro a, exact sorry, -- -- induction a, -- -- { esimp, exact glue a}, -- -- { apply eq_pathover, -- -- rewrite [▸*, ap_id, ap_compose shift_up shift_down, ↑shift_down, -- -- @elim_glue (λk, A (succ k)) _, ↑shift_up], -- -- apply square_of_eq, apply whisker_right, exact !elim_glue⁻¹} -- end end -- abstract begin -- intro a, exact sorry -- -- induction a, -- -- { exact glue a}, -- -- { apply eq_pathover, -- -- rewrite [▸*, ap_id, ap_compose shift_down shift_up, ↑shift_up, -- -- @elim_glue A _, ↑shift_down], -- -- apply square_of_eq, apply whisker_right, exact !elim_glue⁻¹} -- end end definition kshift_equiv' [constructor] (k : ℕ) : seq_colim A ≃ @seq_colim (λn, A (n + k)) (kshift_diag' A k) := equiv.MK (kshift_up' k) (kshift_down' k) abstract begin intro a, exact sorry, -- induction a, -- { esimp, exact glue a}, -- { apply eq_pathover, -- rewrite [▸*, ap_id, ap_compose shift_up shift_down, ↑shift_down, -- @elim_glue (λk, A (succ k)) _, ↑shift_up], -- apply square_of_eq, apply whisker_right, exact !elim_glue⁻¹} end end abstract begin intro a, exact sorry -- induction a, -- { exact glue a}, -- { apply eq_pathover, -- rewrite [▸*, ap_id, ap_compose shift_down shift_up, ↑shift_up, -- @elim_glue A _, ↑shift_down], -- apply square_of_eq, apply whisker_right, exact !elim_glue⁻¹} end end variable {A} /- functorial action and equivalences -/ section functor variables {A' : ℕ → Type} [f' : seq_diagram A'] variables (g : Π{n}, A n → A' n) (p : Π⦃n⦄ (a : A n), g (f a) = f' (g a)) include p definition seq_colim_functor [unfold 7] : seq_colim A → seq_colim A' := seq_colim.elim (λn a, ι (g a)) (λn a, ap ι (p a) ⬝ glue (g a)) theorem seq_colim_functor_glue {n : ℕ} (a : A n) : ap (seq_colim_functor @g p) (glue a) = ap ι (p a) ⬝ glue (g a) := !elim_glue omit p f theorem inv_commute'_fn {A : Type} {B C : A → Type} (f : Π{a}, B a → C a) [H : Πa, is_equiv (@f a)] {g : A → A} (h : Π{a}, B a → B (g a)) (h' : Π{a}, C a → C (g a)) (p : Π⦃a : A⦄ (b : B a), f (h b) = h' (f b)) {a : A} (b : B a) : inv_commute' @f @h @h' p (f b) = (ap f⁻¹ (p b))⁻¹ ⬝ left_inv f (h b) ⬝ (ap h (left_inv f b))⁻¹ := begin rewrite [↑[inv_commute',eq_of_fn_eq_fn'],+ap_con,-adj_inv f,+con.assoc,inv_con_cancel_left, adj f,+ap_inv,-+ap_compose, eq_bot_of_square (natural_square (λb, (left_inv f (h b))⁻¹ ⬝ ap f⁻¹ (p b)) (left_inv f b))⁻¹ʰ, con_inv,inv_inv,+con.assoc], do 3 apply whisker_left, rewrite [con_inv_cancel_left,con.left_inv] end include f p --set_option pp.notation false definition is_equiv_seq_colim_functor [constructor] [H : Πn, is_equiv (g : A n → A' n)] : is_equiv (seq_colim_functor @g p) := adjointify _ (seq_colim_functor (λn, g⁻¹) (λn a, inv_commute' @g @f @f' p a)) abstract begin intro x, induction x, { esimp, exact ap ι (right_inv g a)}, { apply eq_pathover, rewrite [ap_id,ap_compose (seq_colim_functor @g p) (seq_colim_functor _ _), seq_colim_functor_glue _ _ a,ap_con,▸*,seq_colim_functor_glue _ _ (g⁻¹ a), -ap_compose,↑[function.compose],ap_compose ι g,ap_inv_commute',+ap_con,con.assoc, +ap_inv,inv_con_cancel_left,con.assoc,-ap_compose], apply whisker_tl, apply move_left_of_top, esimp, apply transpose, apply square_of_pathover, apply apdo} end end abstract begin intro x, induction x, { esimp, exact ap ι (left_inv g a)}, { apply eq_pathover, rewrite [ap_id,ap_compose (seq_colim_functor _ _) (seq_colim_functor _ _), seq_colim_functor_glue _ _ a,ap_con,▸*,seq_colim_functor_glue _ _ (g a), -ap_compose,↑[function.compose],ap_compose ι g⁻¹,inv_commute'_fn,+ap_con, con.assoc,con.assoc,+ap_inv,con_inv_cancel_left,-ap_compose], apply whisker_tl, apply move_left_of_top, esimp, apply transpose, apply square_of_pathover, apply apdo} end end omit p variables {f f'} definition seq_colim_equiv [constructor] (g : Π{n}, A n ≃ A' n) (p : Π⦃n⦄ (a : A n), g (f a) = f' (g a)) : seq_colim A ≃ seq_colim A' := equiv.mk _ (is_equiv_seq_colim_functor @g p) definition seq_colim_rec_unc [unfold 4] {P : seq_colim A → Type} (v : Σ(Pincl : Π ⦃n : ℕ⦄ (a : A n), P (ι a)), Π ⦃n : ℕ⦄ (a : A n), Pincl (f a) =[ glue a ] Pincl a) : Π(x : seq_colim A), P x := by induction v with Pincl Pglue ;exact seq_colim.rec Pincl Pglue omit f definition eq_pathover_dep {A : Type} {B : A → Type} {a a' : A} {f g : Πa, B a} {p : a = a'} {q : f a = g a} {r : f a' = g a'} (s : squareover B !hrfl (pathover_idp_of_eq q) (pathover_idp_of_eq r) (apdo f p) (apdo g p)) : q =[p] r := begin induction p, apply pathover_idp_of_eq, let H := pathover_of_vdeg_squareover s, let H' := eq_of_pathover_idp H, exact eq_of_fn_eq_fn !pathover_idp⁻¹ᵉ H', end include f definition is_equiv_seq_colim_rec (P : seq_colim A → Type) : is_equiv (seq_colim_rec_unc : (Σ(Pincl : Π ⦃n : ℕ⦄ (a : A n), P (ι a)), Π ⦃n : ℕ⦄ (a : A n), Pincl (f a) =[ glue a ] Pincl a) → (Π (aa : seq_colim A), P aa)) := begin fapply adjointify, { intro f, exact ⟨λn a, f (ι a), λn a, apdo f (glue a)⟩}, { intro f, apply eq_of_homotopy, intro x, induction x, { reflexivity}, { apply eq_pathover_dep, esimp, apply hdeg_squareover, apply rec_glue}}, { intro v, induction v with Pincl Pglue, fapply ap (sigma.mk _), apply eq_of_homotopy2, intros n a, apply rec_glue}, end definition equiv_seq_colim_rec (P : seq_colim A → Type) : (Σ(Pincl : Π ⦃n : ℕ⦄ (a : A n), P (ι a)), Π ⦃n : ℕ⦄ (a : A n), Pincl (f a) =[ glue a ] Pincl a) ≃ (Π (aa : seq_colim A), P aa) := equiv.mk _ !is_equiv_seq_colim_rec end functor /- colimits of dependent sequences, sigma's commute with colimits -/ section over universe variable v variables (P : Π⦃n⦄, A n → Type.{v}) [g : seq_diagram_over P] include g definition f_rep_equiv_rep_f : @seq_colim (λk, P (rep (succ k) a)) _ ≃ @seq_colim (λk, P (rep k (f a))) (seq_diagram_of_over P (f a)) := seq_colim_equiv (rep_f_equiv a P) abstract (λk p, begin esimp, rewrite [+my.cast_apo011], refine _ ⬝ (my.fn_tro_eq_tro_fn (rep_f k a)⁻¹ᵒ g p)⁻¹, rewrite [↑rep_f,↓rep_f k a], refine !my.pathover_ap_invo_tro ⬝ _, rewrite [my.apo_invo,my.apo_tro] end) end set_option class.trace_instances true definition rep_equiv_rep_rep (l : ℕ) : @seq_colim (λk, P (rep (k + l) a)) (kshift_diag' _ _) ≃ @seq_colim (λk, P (rep k (rep l a))) (seq_diagram_of_over P (rep l a)) := seq_colim_equiv (λk, rep_rep_equiv a P k l) abstract (λk p, begin exact sorry -- esimp, -- rewrite [+my.cast_apo011], -- refine _ ⬝ (my.fn_tro_eq_tro_fn (rep_f k a)⁻¹ᵒ g p)⁻¹, -- rewrite [↑rep_f,↓rep_f k a], -- refine !my.pathover_ap_invo_tro ⬝ _, -- rewrite [my.apo_invo,my.apo_tro] end) end definition seq_colim_over [unfold 5] (x : seq_colim A) : Type.{v} := begin fapply seq_colim.elim_type_on x, { intro n a, exact seq_colim (λk, P (rep k a))}, { intro n a, symmetry, refine !shift_equiv ⬝e !f_rep_equiv_rep_f} end variable {P} -- theorem seq_colim_over_glue (x : seq_colim_over P (ι (f a))) -- : transport (seq_colim_over P) (glue a) x = shift_down ((to_fun (f_rep_equiv_rep_f a P))⁻¹ x) := -- ap10 (elim_type_glue _ _ a) x -- REPORT: the following gives error: by exact ap10 (elim_type_glue _ _ a) x -- changing ap10 to ap10.{v v} resolves the error definition seq_colim_over_glue (x : seq_colim_over P (ι (f a))) : pathover (seq_colim_over P) x (glue a) (shift_down (to_inv (f_rep_equiv_rep_f a P) x)) := -- pathover_of_tr_eq (ap10 (elim_type_glue _ _ a) x) begin esimp [f_rep_equiv_rep_f], end set_option pp.universes true check @elim_type_glue check @seq_colim check @seq_diagram set_option formatter.hide_full_terms false definition seq_colim_over_glue' (k : ℕ) (p : P (rep k (f a))) : pathover (seq_colim_over P) (ι' k p) (glue a) (ι' (succ k) (cast ((apo011 P (succ_add n k) (rep_f k a))) p)) := -- concato_eq (pathover_of_tr_eq (ap10 (elim_type_glue.{_ _} (λ ⦃n : ℕ⦄ (a : A n), seq_colim.{v} (λ (k : ℕ), P (rep.{l_1} k a))) _ a) (ι' k p))) sorry begin refine concato_eq (pathover_of_tr_eq (ap10 (elim_type_glue.{_ _} (λ ⦃n : ℕ⦄ (a : A n), seq_colim.{v} (λ (k : ℕ), P (rep.{l_1} k a))) _ a) (ι' k p))) sorry, -- esimp [equiv.trans,equiv.symm,f_rep_equiv_rep_f], -- apply ap ι, unfold cast, -- rewrite [-my.apo011_inv], -- exact sorry end -- definition seq_colim_over_glue' {k : ℕ} (p : P (rep k (f a))) -- : pathover (seq_colim_over P) (ι' k p) (glue a) (shift_down ((to_fun (f_rep_equiv_rep_f a P))⁻¹ (ι' k p))) := -- begin -- esimp [f_rep_equiv_rep_f] -- end definition glue_over (p : P a) : pathover (seq_colim_over P) (@ι _ (seq_diagram_of_over P (f a)) 0 (g p)) (glue a) (@ι _ _ 1 (g p)) := !seq_colim_over_glue -- set_option class.trace_instances true -- set_option pp.all true -- attribute rep [reducible] -- definition glue_over'' {k : ℕ} (p : P (@rep A f n k a)) : pathover (seq_colim_over P) -- (@ι _ (seq_diagram_of_over P (rep k a)) 0 p) _ _ := -- begin -- esimp [seq_diagram_of_over], -- apply pathover_of_tr_eq, -- apply seq_colim_over_glue -- end -- definition glue_over' {k : ℕ} (p : P (rep k a)) : pathover (seq_colim_over P) -- (@ι _ (seq_diagram_of_over P (f a)) 0 p) (glue (rep k a)) (@ι _ _ 1 (g p)) := -- begin -- esimp [seq_diagram_of_over], -- apply pathover_of_tr_eq, -- apply seq_colim_over_glue -- end -- set_option pp.notation false -- set_option pp.implicit true definition glue_over_rep (k : ℕ) (p : P (rep k a)) : pathover (seq_colim_over P) (@ι _ (seq_diagram_of_over P (rep k a)) 0 p) (rep_glue a k) (@ι _ _ k p) := begin revert a p, induction k with k IH, all_goals intro a p, { constructor}, { rewrite [↑seq_diagram_of_over,↑rep_glue,↓rep_glue a k], --refine _ ⬝o _, unfold ι, refine !pathover_tr ⬝o _, -- refine eq_concato !glue⁻¹ _, esimp, -- refine !glue_over⁻¹ᵒ ⬝o _, } end -- variables {k l : ℕ} (p : P (rep k a)) -- check (glue p : ι (g p) = ι p) definition sigma_colim_of_colim_sigma (a : seq_colim (λn, Σ(x : A n), P x)) : Σ(x : seq_colim A), seq_colim_over P x := begin induction a with n v n v, { induction v with a p, exact ⟨ι a, @ι _ _ 0 p⟩}, { induction v with a p, esimp [seq_diagram_sigma], fapply sigma_eq, apply glue, esimp, exact concato_eq !glue_over (glue p)} end theorem is_equiv_sigma_colim_of_colim_sigma : is_equiv (sigma_colim_of_colim_sigma : seq_colim (λn, Σ(x : A n), P x) → Σ(x : seq_colim A), seq_colim_over P x) := begin apply is_equiv_of_is_contr_fun, intro v, induction v with aa pp, induction aa, rotate 1, apply is_hprop.elimo, induction pp with k p, rotate 1, apply is_hprop.elimo, fapply is_contr.mk, { fapply fiber.mk, { exact ι ⟨rep k a, p⟩}, { esimp [sigma_colim_of_colim_sigma], fapply sigma_eq, { esimp, apply rep_glue}, { esimp, rexact glue_over_rep a k p}}}, { intro v, induction v with v q, induction v with l v l v, { induction v with a' p', esimp [sigma_colim_of_colim_sigma] at q, fapply fiber_eq, { esimp, exact sorry}, { esimp, exact sorry}}, { induction v with a' p', esimp, exact sorry}} end variable {P} definition colim_sigma_of_sigma_colim (v : Σ(x : seq_colim A), seq_colim_over P x) : seq_colim (λn, Σ(x : A n), P x) := begin induction v with a p, induction a, { esimp at p, induction p with k p, { exact ι ⟨rep k a, p⟩}, { apply glue}}, { esimp, apply arrow_pathover_left, intro x, esimp at x, induction x with k p k p, { esimp, apply pathover_of_tr_eq, exact sorry}, { exact sorry}} end variable (P) definition seq_colim_over_equiv [constructor] : (Σ(x : seq_colim A), seq_colim_over P x) ≃ seq_colim (λn, Σ(x : A n), P x) := equiv.MK colim_sigma_of_sigma_colim sigma_colim_of_colim_sigma sorry sorry end over end seq_colim
a20cf34da3c31751f725f64f18cc56ad02b4801d
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/set_theory/cofinality.lean
0b7f4180ceb58be35de3a10ced5c63e5bf9b4335
[ "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
25,449
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Floris van Doorn -/ import set_theory.cardinal_ordinal /-! # Cofinality This file contains the definition of cofinality of a ordinal number and regular cardinals ## Main Definitions * `ordinal.cof o` is the cofinality of the ordinal `o`. If `o` is the order type of the relation `<` on `α`, then `o.cof` is the smallest cardinality of a subset `s` of α that is *cofinal* in `α`, i.e. `∀ x : α, ∃ y ∈ s, ¬ y < x`. * `cardinal.is_limit c` means that `c` is a (weak) limit cardinal: `c ≠ 0 ∧ ∀ x < c, succ x < c`. * `cardinal.is_strong_limit c` means that `c` is a strong limit cardinal: `c ≠ 0 ∧ ∀ x < c, 2 ^ x < c`. * `cardinal.is_regular c` means that `c` is a regular cardinal: `ω ≤ c ∧ c.ord.cof = c`. * `cardinal.is_inaccessible c` means that `c` is strongly inaccessible: `ω < c ∧ is_regular c ∧ is_strong_limit c`. ## Main Statements * `ordinal.infinite_pigeonhole_card`: the infinite pigeonhole principle * `cardinal.lt_power_cof`: A consequence of König's theorem stating that `c < c ^ c.ord.cof` for `c ≥ ω` * `cardinal.univ_inaccessible`: The type of ordinals in `Type u` form an inaccessible cardinal (in `Type v` with `v > u`). This shows (externally) that in `Type u` there are at least `u` inaccessible cardinals. ## Implementation Notes * The cofinality is defined for ordinals. If `c` is a cardinal number, its cofinality is `c.ord.cof`. ## Tags cofinality, regular cardinals, limits cardinals, inaccessible cardinals, infinite pigeonhole principle -/ noncomputable theory open function cardinal set open_locale classical cardinal universes u v w variables {α : Type*} {r : α → α → Prop} namespace order /-- Cofinality of a reflexive order `≼`. This is the smallest cardinality of a subset `S : set α` such that `∀ a, ∃ b ∈ S, a ≼ b`. -/ def cof (r : α → α → Prop) [is_refl α r] : cardinal := @cardinal.min {S : set α // ∀ a, ∃ b ∈ S, r a b} ⟨⟨set.univ, λ a, ⟨a, ⟨⟩, refl _⟩⟩⟩ (λ S, #S) lemma cof_le (r : α → α → Prop) [is_refl α r] {S : set α} (h : ∀a, ∃(b ∈ S), r a b) : order.cof r ≤ #S := le_trans (cardinal.min_le _ ⟨S, h⟩) (le_refl _) lemma le_cof {r : α → α → Prop} [is_refl α r] (c : cardinal) : c ≤ order.cof r ↔ ∀ {S : set α} (h : ∀a, ∃(b ∈ S), r a b) , c ≤ #S := by { rw [order.cof, cardinal.le_min], exact ⟨λ H S h, H ⟨S, h⟩, λ H ⟨S, h⟩, H h ⟩ } end order theorem rel_iso.cof.aux {α : Type u} {β : Type v} {r s} [is_refl α r] [is_refl β s] (f : r ≃r s) : cardinal.lift.{(max u v)} (order.cof r) ≤ cardinal.lift.{(max u v)} (order.cof s) := begin rw [order.cof, order.cof, lift_min, lift_min, cardinal.le_min], intro S, cases S with S H, simp only [comp, coe_sort_coe_base, subtype.coe_mk], refine le_trans (min_le _ _) _, { exact ⟨f ⁻¹' S, λ a, let ⟨b, bS, h⟩ := H (f a) in ⟨f.symm b, by simp [bS, ← f.map_rel_iff, h, -coe_fn_coe_base, -coe_fn_coe_trans, principal_seg.coe_coe_fn', initial_seg.coe_coe_fn]⟩⟩ }, { exact lift_mk_le.{u v (max u v)}.2 ⟨⟨λ ⟨x, h⟩, ⟨f x, h⟩, λ ⟨x, h₁⟩ ⟨y, h₂⟩ h₃, by congr; injection h₃ with h'; exact f.to_equiv.injective h'⟩⟩ } end theorem rel_iso.cof {α : Type u} {β : Type v} {r s} [is_refl α r] [is_refl β s] (f : r ≃r s) : cardinal.lift.{(max u v)} (order.cof r) = cardinal.lift.{(max u v)} (order.cof s) := le_antisymm (rel_iso.cof.aux f) (rel_iso.cof.aux f.symm) def strict_order.cof (r : α → α → Prop) [h : is_irrefl α r] : cardinal := @order.cof α (λ x y, ¬ r y x) ⟨h.1⟩ namespace ordinal /-- Cofinality of an ordinal. This is the smallest cardinal of a subset `S` of the ordinal which is unbounded, in the sense `∀ a, ∃ b ∈ S, ¬(b > a)`. It is defined for all ordinals, but `cof 0 = 0` and `cof (succ o) = 1`, so it is only really interesting on limit ordinals (when it is an infinite cardinal). -/ def cof (o : ordinal.{u}) : cardinal.{u} := quot.lift_on o (λ ⟨α, r, _⟩, by exactI strict_order.cof r) begin rintros ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨⟨f, hf⟩⟩, rw ← cardinal.lift_inj, apply rel_iso.cof ⟨f, _⟩, simp [hf] end lemma cof_type (r : α → α → Prop) [is_well_order α r] : (type r).cof = strict_order.cof r := rfl theorem le_cof_type [is_well_order α r] {c} : c ≤ cof (type r) ↔ ∀ S : set α, (∀ a, ∃ b ∈ S, ¬ r b a) → c ≤ #S := by dsimp [cof, strict_order.cof, order.cof, type, quotient.mk, quot.lift_on]; rw [cardinal.le_min, subtype.forall]; refl theorem cof_type_le [is_well_order α r] (S : set α) (h : ∀ a, ∃ b ∈ S, ¬ r b a) : cof (type r) ≤ #S := le_cof_type.1 (le_refl _) S h theorem lt_cof_type [is_well_order α r] (S : set α) (hl : #S < cof (type r)) : ∃ a, ∀ b ∈ S, r b a := not_forall_not.1 $ λ h, not_le_of_lt hl $ cof_type_le S (λ a, not_ball.1 (h a)) theorem cof_eq (r : α → α → Prop) [is_well_order α r] : ∃ S : set α, (∀ a, ∃ b ∈ S, ¬ r b a) ∧ #S = cof (type r) := begin have : ∃ i, cof (type r) = _, { dsimp [cof, order.cof, type, quotient.mk, quot.lift_on], apply cardinal.min_eq }, exact let ⟨⟨S, hl⟩, e⟩ := this in ⟨S, hl, e.symm⟩, end theorem ord_cof_eq (r : α → α → Prop) [is_well_order α r] : ∃ S : set α, (∀ a, ∃ b ∈ S, ¬ r b a) ∧ type (subrel r S) = (cof (type r)).ord := let ⟨S, hS, e⟩ := cof_eq r, ⟨s, _, e'⟩ := cardinal.ord_eq S, T : set α := {a | ∃ aS : a ∈ S, ∀ b : S, s b ⟨_, aS⟩ → r b a} in begin resetI, suffices, { refine ⟨T, this, le_antisymm _ (cardinal.ord_le.2 $ cof_type_le T this)⟩, rw [← e, e'], refine type_le'.2 ⟨rel_embedding.of_monotone (λ a, ⟨a, let ⟨aS, _⟩ := a.2 in aS⟩) (λ a b h, _)⟩, rcases a with ⟨a, aS, ha⟩, rcases b with ⟨b, bS, hb⟩, change s ⟨a, _⟩ ⟨b, _⟩, refine ((trichotomous_of s _ _).resolve_left (λ hn, _)).resolve_left _, { exact asymm h (ha _ hn) }, { intro e, injection e with e, subst b, exact irrefl _ h } }, { intro a, have : {b : S | ¬ r b a}.nonempty := let ⟨b, bS, ba⟩ := hS a in ⟨⟨b, bS⟩, ba⟩, let b := (is_well_order.wf).min _ this, have ba : ¬r b a := (is_well_order.wf).min_mem _ this, refine ⟨b, ⟨b.2, λ c, not_imp_not.1 $ λ h, _⟩, ba⟩, rw [show ∀b:S, (⟨b, b.2⟩:S) = b, by intro b; cases b; refl], exact (is_well_order.wf).not_lt_min _ this (is_order_connected.neg_trans h ba) } end theorem lift_cof (o) : (cof o).lift = cof o.lift := induction_on o $ begin introsI α r _, cases lift_type r with _ e, rw e, apply le_antisymm, { unfreezingI { refine le_cof_type.2 (λ S H, _) }, have : (#(ulift.up ⁻¹' S)).lift ≤ #S := ⟨⟨λ ⟨⟨x, h⟩⟩, ⟨⟨x⟩, h⟩, λ ⟨⟨x, h₁⟩⟩ ⟨⟨y, h₂⟩⟩ e, by simp at e; congr; injection e⟩⟩, refine le_trans (cardinal.lift_le.2 $ cof_type_le _ _) this, exact λ a, let ⟨⟨b⟩, bs, br⟩ := H ⟨a⟩ in ⟨b, bs, br⟩ }, { rcases cof_eq r with ⟨S, H, e'⟩, have : #(ulift.down ⁻¹' S) ≤ (#S).lift := ⟨⟨λ ⟨⟨x⟩, h⟩, ⟨⟨x, h⟩⟩, λ ⟨⟨x⟩, h₁⟩ ⟨⟨y⟩, h₂⟩ e, by simp at e; congr; injections⟩⟩, rw e' at this, unfreezingI { refine le_trans (cof_type_le _ _) this }, exact λ ⟨a⟩, let ⟨b, bs, br⟩ := H a in ⟨⟨b⟩, bs, br⟩ } end theorem cof_le_card (o) : cof o ≤ card o := induction_on o $ λ α r _, begin resetI, have : #(@set.univ α) = card (type r) := quotient.sound ⟨equiv.set.univ _⟩, rw ← this, exact cof_type_le set.univ (λ a, ⟨a, ⟨⟩, irrefl a⟩) end theorem cof_ord_le (c : cardinal) : cof c.ord ≤ c := by simpa using cof_le_card c.ord @[simp] theorem cof_zero : cof 0 = 0 := le_antisymm (by simpa using cof_le_card 0) (cardinal.zero_le _) @[simp] theorem cof_eq_zero {o} : cof o = 0 ↔ o = 0 := ⟨induction_on o $ λ α r _ z, by exactI let ⟨S, hl, e⟩ := cof_eq r in type_eq_zero_iff_is_empty.2 $ ⟨λ a, let ⟨b, h, _⟩ := hl a in (mk_eq_zero_iff.1 (e.trans z)).elim' ⟨_, h⟩⟩, λ e, by simp [e]⟩ @[simp] theorem cof_succ (o) : cof (succ o) = 1 := begin apply le_antisymm, { refine induction_on o (λ α r _, _), change cof (type _) ≤ _, rw [← (_ : #_ = 1)], apply cof_type_le, { refine λ a, ⟨sum.inr punit.star, set.mem_singleton _, _⟩, rcases a with a|⟨⟨⟨⟩⟩⟩; simp [empty_relation] }, { rw [cardinal.fintype_card, set.card_singleton], simp } }, { rw [← cardinal.succ_zero, cardinal.succ_le], simpa [lt_iff_le_and_ne, cardinal.zero_le] using λ h, succ_ne_zero o (cof_eq_zero.1 (eq.symm h)) } end @[simp] theorem cof_eq_one_iff_is_succ {o} : cof.{u} o = 1 ↔ ∃ a, o = succ a := ⟨induction_on o $ λ α r _ z, begin resetI, rcases cof_eq r with ⟨S, hl, e⟩, rw z at e, cases mk_ne_zero_iff.1 (by rw e; exact one_ne_zero) with a, refine ⟨typein r a, eq.symm $ quotient.sound ⟨rel_iso.of_surjective (rel_embedding.of_monotone _ (λ x y, _)) (λ x, _)⟩⟩, { apply sum.rec; [exact subtype.val, exact λ _, a] }, { rcases x with x|⟨⟨⟨⟩⟩⟩; rcases y with y|⟨⟨⟨⟩⟩⟩; simp [subrel, order.preimage, empty_relation], exact x.2 }, { suffices : r x a ∨ ∃ (b : punit), ↑a = x, {simpa}, rcases trichotomous_of r x a with h|h|h, { exact or.inl h }, { exact or.inr ⟨punit.star, h.symm⟩ }, { rcases hl x with ⟨a', aS, hn⟩, rw (_ : ↑a = a') at h, {exact absurd h hn}, refine congr_arg subtype.val (_ : a = ⟨a', aS⟩), haveI := le_one_iff_subsingleton.1 (le_of_eq e), apply subsingleton.elim } } end, λ ⟨a, e⟩, by simp [e]⟩ @[simp] theorem cof_add (a b : ordinal) : b ≠ 0 → cof (a + b) = cof b := induction_on a $ λ α r _, induction_on b $ λ β s _ b0, begin resetI, change cof (type _) = _, refine eq_of_forall_le_iff (λ c, _), rw [le_cof_type, le_cof_type], split; intros H S hS, { refine le_trans (H {a | sum.rec_on a (∅:set α) S} (λ a, _)) ⟨⟨_, _⟩⟩, { cases a with a b, { cases type_ne_zero_iff_nonempty.1 b0 with b, rcases hS b with ⟨b', bs, _⟩, exact ⟨sum.inr b', bs, by simp⟩ }, { rcases hS b with ⟨b', bs, h⟩, exact ⟨sum.inr b', bs, by simp [h]⟩ } }, { exact λ a, match a with ⟨sum.inr b, h⟩ := ⟨b, h⟩ end }, { exact λ a b, match a, b with ⟨sum.inr a, h₁⟩, ⟨sum.inr b, h₂⟩, h := by congr; injection h end } }, { refine le_trans (H (sum.inr ⁻¹' S) (λ a, _)) ⟨⟨_, _⟩⟩, { rcases hS (sum.inr a) with ⟨a'|b', bs, h⟩; simp at h, { cases h }, { exact ⟨b', bs, h⟩ } }, { exact λ ⟨a, h⟩, ⟨_, h⟩ }, { exact λ ⟨a, h₁⟩ ⟨b, h₂⟩ h, by injection h with h; congr; injection h } } end @[simp] theorem cof_cof (o : ordinal) : cof (cof o).ord= cof o := le_antisymm (le_trans (cof_le_card _) (by simp)) $ induction_on o $ λ α r _, by exactI let ⟨S, hS, e₁⟩ := ord_cof_eq r, ⟨T, hT, e₂⟩ := cof_eq (subrel r S) in begin rw e₁ at e₂, rw ← e₂, refine le_trans (cof_type_le {a | ∃ h, (subtype.mk a h : S) ∈ T} (λ a, _)) ⟨⟨_, _⟩⟩, { rcases hS a with ⟨b, bS, br⟩, rcases hT ⟨b, bS⟩ with ⟨⟨c, cS⟩, cT, cs⟩, exact ⟨c, ⟨cS, cT⟩, is_order_connected.neg_trans cs br⟩ }, { exact λ ⟨a, h⟩, ⟨⟨a, h.fst⟩, h.snd⟩ }, { exact λ ⟨a, ha⟩ ⟨b, hb⟩ h, by injection h with h; congr; injection h }, end theorem omega_le_cof {o} : ω ≤ cof o ↔ is_limit o := begin rcases zero_or_succ_or_limit o with rfl|⟨o,rfl⟩|l, { simp [not_zero_is_limit, cardinal.omega_ne_zero] }, { simp [not_succ_is_limit, cardinal.one_lt_omega] }, { simp [l], refine le_of_not_lt (λ h, _), cases cardinal.lt_omega.1 h with n e, have := cof_cof o, rw [e, ord_nat] at this, cases n, { simp at e, simpa [e, not_zero_is_limit] using l }, { rw [← nat_cast_succ, cof_succ] at this, rw [← this, cof_eq_one_iff_is_succ] at e, rcases e with ⟨a, rfl⟩, exact not_succ_is_limit _ l } } end @[simp] theorem cof_omega : cof omega = ω := le_antisymm (by rw ← card_omega; apply cof_le_card) (omega_le_cof.2 omega_is_limit) theorem cof_eq' (r : α → α → Prop) [is_well_order α r] (h : is_limit (type r)) : ∃ S : set α, (∀ a, ∃ b ∈ S, r a b) ∧ #S = cof (type r) := let ⟨S, H, e⟩ := cof_eq r in ⟨S, λ a, let a' := enum r _ (h.2 _ (typein_lt_type r a)) in let ⟨b, h, ab⟩ := H a' in ⟨b, h, (is_order_connected.conn a b a' $ (typein_lt_typein r).1 (by rw typein_enum; apply ordinal.lt_succ_self)).resolve_right ab⟩, e⟩ theorem cof_sup_le_lift {ι} (f : ι → ordinal) (H : ∀ i, f i < sup f) : cof (sup f) ≤ (#ι).lift := begin generalize e : sup f = o, refine ordinal.induction_on o _ e, introsI α r _ e', rw e' at H, refine le_trans (cof_type_le (set.range (λ i, enum r _ (H i))) _) ⟨embedding.of_surjective _ _⟩, { intro a, by_contra h, apply not_le_of_lt (typein_lt_type r a), rw [← e', sup_le], intro i, have h : ∀ (x : ι), r (enum r (f x) _) a, { simpa using h }, simpa only [typein_enum] using le_of_lt ((typein_lt_typein r).2 (h i)) }, { exact λ i, ⟨_, set.mem_range_self i.1⟩ }, { intro a, rcases a with ⟨_, i, rfl⟩, exact ⟨⟨i⟩, by simp⟩ } end theorem cof_sup_le {ι} (f : ι → ordinal) (H : ∀ i, f i < sup.{u u} f) : cof (sup.{u u} f) ≤ #ι := by simpa using cof_sup_le_lift.{u u} f H theorem cof_bsup_le_lift {o : ordinal} : ∀ (f : Π a < o, ordinal), (∀ i h, f i h < bsup o f) → cof (bsup o f) ≤ o.card.lift := induction_on o $ λ α r _ f H, by rw bsup_type; refine cof_sup_le_lift _ _; rw ← bsup_type; intro a; apply H theorem cof_bsup_le {o : ordinal} : ∀ (f : Π a < o, ordinal), (∀ i h, f i h < bsup.{u u} o f) → cof (bsup.{u u} o f) ≤ o.card := induction_on o $ λ α r _ f H, by simpa using cof_bsup_le_lift.{u u} f H @[simp] theorem cof_univ : cof univ.{u v} = cardinal.univ := le_antisymm (cof_le_card _) begin refine le_of_forall_lt (λ c h, _), rcases lt_univ'.1 h with ⟨c, rfl⟩, rcases @cof_eq ordinal.{u} (<) _ with ⟨S, H, Se⟩, rw [univ, ← lift_cof, ← cardinal.lift_lift, cardinal.lift_lt, ← Se], refine lt_of_not_ge (λ h, _), cases cardinal.lift_down h with a e, refine quotient.induction_on a (λ α e, _) e, cases quotient.exact e with f, have f := equiv.ulift.symm.trans f, let g := λ a, (f a).1, let o := succ (sup.{u u} g), rcases H o with ⟨b, h, l⟩, refine l (lt_succ.2 _), rw ← show g (f.symm ⟨b, h⟩) = b, by dsimp [g]; simp, apply le_sup end theorem sup_lt_ord {ι} (f : ι → ordinal) {c : ordinal} (H1 : #ι < c.cof) (H2 : ∀ i, f i < c) : sup.{u u} f < c := begin apply lt_of_le_of_ne, { rw [sup_le], exact λ i, le_of_lt (H2 i) }, rintro h, apply not_le_of_lt H1, simpa [sup_ord, H2, h] using cof_sup_le.{u} f end theorem sup_lt {ι} (f : ι → cardinal) {c : cardinal} (H1 : #ι < c.ord.cof) (H2 : ∀ i, f i < c) : cardinal.sup.{u u} f < c := by { rw [←ord_lt_ord, ←sup_ord], apply sup_lt_ord _ H1, intro i, rw ord_lt_ord, apply H2 } /-- If the union of s is unbounded and s is smaller than the cofinality, then s has an unbounded member -/ theorem unbounded_of_unbounded_sUnion (r : α → α → Prop) [wo : is_well_order α r] {s : set (set α)} (h₁ : unbounded r $ ⋃₀ s) (h₂ : #s < strict_order.cof r) : ∃(x ∈ s), unbounded r x := begin by_contra h, simp only [not_exists, exists_prop, not_and, not_unbounded_iff] at h, apply not_le_of_lt h₂, let f : s → α := λ x : s, wo.wf.sup x (h x.1 x.2), let t : set α := range f, have : #t ≤ #s, exact mk_range_le, refine le_trans _ this, have : unbounded r t, { intro x, rcases h₁ x with ⟨y, ⟨c, hc, hy⟩, hxy⟩, refine ⟨f ⟨c, hc⟩, mem_range_self _, _⟩, intro hxz, apply hxy, refine trans (wo.wf.lt_sup _ hy) hxz }, exact cardinal.min_le _ (subtype.mk t this) end /-- If the union of s is unbounded and s is smaller than the cofinality, then s has an unbounded member -/ theorem unbounded_of_unbounded_Union {α β : Type u} (r : α → α → Prop) [wo : is_well_order α r] (s : β → set α) (h₁ : unbounded r $ ⋃x, s x) (h₂ : #β < strict_order.cof r) : ∃x : β, unbounded r (s x) := begin rw [← sUnion_range] at h₁, have : #(range (λ (i : β), s i)) < strict_order.cof r := lt_of_le_of_lt mk_range_le h₂, rcases unbounded_of_unbounded_sUnion r h₁ this with ⟨_, ⟨x, rfl⟩, u⟩, exact ⟨x, u⟩ end /-- The infinite pigeonhole principle -/ theorem infinite_pigeonhole {β α : Type u} (f : β → α) (h₁ : ω ≤ #β) (h₂ : #α < (#β).ord.cof) : ∃a : α, #(f ⁻¹' {a}) = #β := begin have : ¬∀a, #(f ⁻¹' {a}) < #β, { intro h, apply not_lt_of_ge (ge_of_eq $ mk_univ), rw [←@preimage_univ _ _ f, ←Union_of_singleton, preimage_Union], apply lt_of_le_of_lt mk_Union_le_sum_mk, apply lt_of_le_of_lt (sum_le_sup _), apply mul_lt_of_lt h₁ (lt_of_lt_of_le h₂ $ cof_ord_le _), exact sup_lt _ h₂ h }, rw [not_forall] at this, cases this with x h, use x, apply le_antisymm _ (le_of_not_gt h), rw [le_mk_iff_exists_set], exact ⟨_, rfl⟩ end /-- pigeonhole principle for a cardinality below the cardinality of the domain -/ theorem infinite_pigeonhole_card {β α : Type u} (f : β → α) (θ : cardinal) (hθ : θ ≤ #β) (h₁ : ω ≤ θ) (h₂ : #α < θ.ord.cof) : ∃a : α, θ ≤ #(f ⁻¹' {a}) := begin rcases le_mk_iff_exists_set.1 hθ with ⟨s, rfl⟩, cases infinite_pigeonhole (f ∘ subtype.val : s → α) h₁ h₂ with a ha, use a, rw [←ha, @preimage_comp _ _ _ subtype.val f], apply mk_preimage_of_injective _ _ subtype.val_injective end theorem infinite_pigeonhole_set {β α : Type u} {s : set β} (f : s → α) (θ : cardinal) (hθ : θ ≤ #s) (h₁ : ω ≤ θ) (h₂ : #α < θ.ord.cof) : ∃(a : α) (t : set β) (h : t ⊆ s), θ ≤ #t ∧ ∀{{x}} (hx : x ∈ t), f ⟨x, h hx⟩ = a := begin cases infinite_pigeonhole_card f θ hθ h₁ h₂ with a ha, refine ⟨a, {x | ∃(h : x ∈ s), f ⟨x, h⟩ = a}, _, _, _⟩, { rintro x ⟨hx, hx'⟩, exact hx }, { refine le_trans ha _, apply ge_of_eq, apply quotient.sound, constructor, refine equiv.trans _ (equiv.subtype_subtype_equiv_subtype_exists _ _).symm, simp only [set_coe_eq_subtype, mem_singleton_iff, mem_preimage, mem_set_of_eq] }, rintro x ⟨hx, hx'⟩, exact hx' end end ordinal namespace cardinal open ordinal local infixr ^ := @pow cardinal.{u} cardinal cardinal.has_pow /-- A cardinal is a limit if it is not zero or a successor cardinal. Note that `ω` is a limit cardinal by this definition. -/ def is_limit (c : cardinal) : Prop := c ≠ 0 ∧ ∀ x < c, succ x < c /-- A cardinal is a strong limit if it is not zero and it is closed under powersets. Note that `ω` is a strong limit by this definition. -/ def is_strong_limit (c : cardinal) : Prop := c ≠ 0 ∧ ∀ x < c, 2 ^ x < c theorem is_strong_limit.is_limit {c} (H : is_strong_limit c) : is_limit c := ⟨H.1, λ x h, lt_of_le_of_lt (succ_le.2 $ cantor _) (H.2 _ h)⟩ /-- A cardinal is regular if it is infinite and it equals its own cofinality. -/ def is_regular (c : cardinal) : Prop := ω ≤ c ∧ c.ord.cof = c lemma is_regular.pos {c : cardinal} (H : c.is_regular) : 0 < c := omega_pos.trans_le H.left lemma is_regular.ord_pos {c : cardinal} (H : c.is_regular) : 0 < c.ord := by { rw cardinal.lt_ord, exact H.pos } theorem cof_is_regular {o : ordinal} (h : o.is_limit) : is_regular o.cof := ⟨omega_le_cof.2 h, cof_cof _⟩ theorem omega_is_regular : is_regular ω := ⟨le_refl _, by simp⟩ theorem succ_is_regular {c : cardinal.{u}} (h : ω ≤ c) : is_regular (succ c) := ⟨le_trans h (le_of_lt $ lt_succ_self _), begin refine le_antisymm (cof_ord_le _) (succ_le.2 _), cases quotient.exists_rep (succ c) with α αe, simp at αe, rcases ord_eq α with ⟨r, wo, re⟩, resetI, have := ord_is_limit (le_trans h $ le_of_lt $ lt_succ_self _), rw [← αe, re] at this ⊢, rcases cof_eq' r this with ⟨S, H, Se⟩, rw [← Se], apply lt_imp_lt_of_le_imp_le (λ (h : #S ≤ c), mul_le_mul_right' h c), rw [mul_eq_self h, ← succ_le, ← αe, ← sum_const], refine le_trans _ (sum_le_sum (λ x:S, card (typein r x)) _ _), { simp [typein, sum_mk (λ x:S, {a//r a x})], refine ⟨embedding.of_surjective _ _⟩, { exact λ x, x.2.1 }, { exact λ a, let ⟨b, h, ab⟩ := H a in ⟨⟨⟨_, h⟩, _, ab⟩, rfl⟩ } }, { intro i, rw [← lt_succ, ← lt_ord, ← αe, re], apply typein_lt_type } end⟩ /-- A function whose codomain's cardinality is infinite but strictly smaller than its domain's has a fiber with cardinality strictly great than the codomain. -/ theorem infinite_pigeonhole_card_lt {β α : Type u} (f : β → α) (w : #α < #β) (w' : ω ≤ #α) : ∃ a : α, #α < #(f ⁻¹' {a}) := begin simp_rw [← succ_le], exact ordinal.infinite_pigeonhole_card f (#α).succ (succ_le.mpr w) (w'.trans (lt_succ_self _).le) ((lt_succ_self _).trans_le (succ_is_regular w').2.ge), end /-- A function whose codomain's cardinality is infinite but strictly smaller than its domain's has an infinite fiber. -/ theorem exists_infinite_fiber {β α : Type*} (f : β → α) (w : #α < #β) (w' : _root_.infinite α) : ∃ a : α, _root_.infinite (f ⁻¹' {a}) := begin simp_rw [cardinal.infinite_iff] at ⊢ w', cases infinite_pigeonhole_card_lt f w w' with a ha, exact ⟨a, w'.trans ha.le⟩, end /-- If an infinite type `β` can be expressed as a union of finite sets, then the cardinality of the collection of those finite sets must be at least the cardinality of `β`. -/ lemma le_range_of_union_finset_eq_top {α β : Type*} [infinite β] (f : α → finset β) (w : (⋃ a, (f a : set β)) = ⊤) : #β ≤ #(range f) := begin have k : _root_.infinite (range f), { rw infinite_coe_iff, apply mt (union_finset_finite_of_range_finite f), rw w, exact infinite_univ, }, by_contradiction h, simp only [not_le] at h, let u : Π b, ∃ a, b ∈ f a := λ b, by simpa using (w.ge : _) (set.mem_univ b), let u' : β → range f := λ b, ⟨f (u b).some, by simp⟩, have v' : ∀ a, u' ⁻¹' {⟨f a, by simp⟩} ≤ f a, begin rintros a p m, simp at m, rw ←m, apply (λ b, (u b).some_spec), end, obtain ⟨⟨-, ⟨a, rfl⟩⟩, p⟩ := exists_infinite_fiber u' h k, exact (@infinite.of_injective _ _ p (inclusion (v' a)) (inclusion_injective _)).false, end theorem sup_lt_ord_of_is_regular {ι} (f : ι → ordinal) {c} (hc : is_regular c) (H1 : #ι < c) (H2 : ∀ i, f i < c.ord) : ordinal.sup.{u u} f < c.ord := by { apply sup_lt_ord _ _ H2, rw [hc.2], exact H1 } theorem sup_lt_of_is_regular {ι} (f : ι → cardinal) {c} (hc : is_regular c) (H1 : #ι < c) (H2 : ∀ i, f i < c) : sup.{u u} f < c := by { apply sup_lt _ _ H2, rwa [hc.2] } theorem sum_lt_of_is_regular {ι} (f : ι → cardinal) {c} (hc : is_regular c) (H1 : #ι < c) (H2 : ∀ i, f i < c) : sum.{u u} f < c := lt_of_le_of_lt (sum_le_sup _) $ mul_lt_of_lt hc.1 H1 $ sup_lt_of_is_regular f hc H1 H2 /-- A cardinal is inaccessible if it is an uncountable regular strong limit cardinal. -/ def is_inaccessible (c : cardinal) := ω < c ∧ is_regular c ∧ is_strong_limit c theorem is_inaccessible.mk {c} (h₁ : ω < c) (h₂ : c ≤ c.ord.cof) (h₃ : ∀ x < c, 2 ^ x < c) : is_inaccessible c := ⟨h₁, ⟨le_of_lt h₁, le_antisymm (cof_ord_le _) h₂⟩, ne_of_gt (lt_trans omega_pos h₁), h₃⟩ /- Lean's foundations prove the existence of ω many inaccessible cardinals -/ theorem univ_inaccessible : is_inaccessible (univ.{u v}) := is_inaccessible.mk (by simpa using lift_lt_univ' ω) (by simp) (λ c h, begin rcases lt_univ'.1 h with ⟨c, rfl⟩, rw ← lift_two_power.{u (max (u+1) v)}, apply lift_lt_univ' end) theorem lt_power_cof {c : cardinal.{u}} : ω ≤ c → c < c ^ cof c.ord := quotient.induction_on c $ λ α h, begin rcases ord_eq α with ⟨r, wo, re⟩, resetI, have := ord_is_limit h, rw [mk_def, re] at this ⊢, rcases cof_eq' r this with ⟨S, H, Se⟩, have := sum_lt_prod (λ a:S, #{x // r x a}) (λ _, #α) (λ i, _), { simp [Se.symm] at this ⊢, refine lt_of_le_of_lt _ this, refine ⟨embedding.of_surjective _ _⟩, { exact λ x, x.2.1 }, { exact λ a, let ⟨b, h, ab⟩ := H a in ⟨⟨⟨_, h⟩, _, ab⟩, rfl⟩ } }, { have := typein_lt_type r i, rwa [← re, lt_ord] at this } end theorem lt_cof_power {a b : cardinal} (ha : ω ≤ a) (b1 : 1 < b) : a < cof (b ^ a).ord := begin have b0 : b ≠ 0 := ne_of_gt (lt_trans zero_lt_one b1), apply lt_imp_lt_of_le_imp_le (power_le_power_left $ power_ne_zero a b0), rw [← power_mul, mul_eq_self ha], exact lt_power_cof (le_trans ha $ le_of_lt $ cantor' _ b1), end end cardinal
07a76bd984eeb45424172579cd255e6b0b7a6977
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/limits/preserves/shapes/equalizers_auto.lean
640bf975e43092cb24d1124a39b5ad63afc05184
[]
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
11,104
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.limits.shapes.split_coequalizer import Mathlib.category_theory.limits.preserves.basic import Mathlib.PostPort universes u₁ u₂ v namespace Mathlib /-! # Preserving (co)equalizers Constructions to relate the notions of preserving (co)equalizers and reflecting (co)equalizers to concrete (co)forks. In particular, we show that `equalizer_comparison G f` is an isomorphism iff `G` preserves the limit of `f` as well as the dual. -/ namespace category_theory.limits /-- The map of a fork is a limit iff the fork consisting of the mapped morphisms is a limit. This essentially lets us commute `fork.of_ι` with `functor.map_cone`. -/ def is_limit_map_cone_fork_equiv {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) {X : C} {Y : C} {Z : C} {f : X ⟶ Y} {g : X ⟶ Y} {h : Z ⟶ X} (w : h ≫ f = h ≫ g) : is_limit (functor.map_cone G (fork.of_ι h w)) ≃ is_limit (fork.of_ι (functor.map G h) (is_limit_map_cone_fork_equiv._proof_1 G w)) := equiv.trans (equiv.symm (is_limit.postcompose_hom_equiv (diagram_iso_parallel_pair (parallel_pair f g ⋙ G)) (functor.map_cone G (fork.of_ι h w)))) (is_limit.equiv_iso_limit (fork.ext (iso.refl (cone.X (functor.obj (cones.postcompose (iso.hom (diagram_iso_parallel_pair (parallel_pair f g ⋙ G)))) (functor.map_cone G (fork.of_ι h w))))) sorry)) /-- The property of preserving equalizers expressed in terms of forks. -/ def is_limit_fork_map_of_is_limit {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) {X : C} {Y : C} {Z : C} {f : X ⟶ Y} {g : X ⟶ Y} {h : Z ⟶ X} (w : h ≫ f = h ≫ g) [preserves_limit (parallel_pair f g) G] (l : is_limit (fork.of_ι h w)) : is_limit (fork.of_ι (functor.map G h) (is_limit_map_cone_fork_equiv._proof_1 G w)) := coe_fn (is_limit_map_cone_fork_equiv G w) (preserves_limit.preserves l) /-- The property of reflecting equalizers expressed in terms of forks. -/ def is_limit_of_is_limit_fork_map {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) {X : C} {Y : C} {Z : C} {f : X ⟶ Y} {g : X ⟶ Y} {h : Z ⟶ X} (w : h ≫ f = h ≫ g) [reflects_limit (parallel_pair f g) G] (l : is_limit (fork.of_ι (functor.map G h) (is_limit_of_is_limit_fork_map._proof_1 G w))) : is_limit (fork.of_ι h w) := reflects_limit.reflects (coe_fn (equiv.symm (is_limit_map_cone_fork_equiv G w)) l) /-- If `G` preserves equalizers and `C` has them, then the fork constructed of the mapped morphisms of a fork is a limit. -/ def is_limit_of_has_equalizer_of_preserves_limit {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) [has_equalizer f g] [preserves_limit (parallel_pair f g) G] : is_limit (fork.of_ι (functor.map G (equalizer.ι f g)) (is_limit_of_has_equalizer_of_preserves_limit._proof_1 G f g)) := is_limit_fork_map_of_is_limit G (equalizer.condition f g) (equalizer_is_equalizer f g) /-- If the equalizer comparison map for `G` at `(f,g)` is an isomorphism, then `G` preserves the equalizer of `(f,g)`. -/ def preserves_equalizer.of_iso_comparison {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) [has_equalizer f g] [has_equalizer (functor.map G f) (functor.map G g)] [i : is_iso (equalizer_comparison f g G)] : preserves_limit (parallel_pair f g) G := preserves_limit_of_preserves_limit_cone (equalizer_is_equalizer f g) (coe_fn (equiv.symm (is_limit_map_cone_fork_equiv G (equalizer.condition f g))) (is_limit.of_point_iso (limit.is_limit (parallel_pair (functor.map G f) (functor.map G g))))) /-- If `G` preserves the equalizer of `(f,g)`, then the equalizer comparison map for `G` at `(f,g)` is an isomorphism. -/ def preserves_equalizer.iso {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) [has_equalizer f g] [has_equalizer (functor.map G f) (functor.map G g)] [preserves_limit (parallel_pair f g) G] : functor.obj G (equalizer f g) ≅ equalizer (functor.map G f) (functor.map G g) := is_limit.cone_point_unique_up_to_iso (is_limit_of_has_equalizer_of_preserves_limit G f g) (limit.is_limit (parallel_pair (functor.map G f) (functor.map G g))) @[simp] theorem preserves_equalizer.iso_hom {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) [has_equalizer f g] [has_equalizer (functor.map G f) (functor.map G g)] [preserves_limit (parallel_pair f g) G] : iso.hom (preserves_equalizer.iso G f g) = equalizer_comparison f g G := rfl protected instance equalizer_comparison.category_theory.is_iso {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) [has_equalizer f g] [has_equalizer (functor.map G f) (functor.map G g)] [preserves_limit (parallel_pair f g) G] : is_iso (equalizer_comparison f g G) := eq.mpr sorry (is_iso.of_iso (preserves_equalizer.iso G f g)) /-- The map of a cofork is a colimit iff the cofork consisting of the mapped morphisms is a colimit. This essentially lets us commute `cofork.of_π` with `functor.map_cocone`. -/ def is_colimit_map_cocone_cofork_equiv {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) {X : C} {Y : C} {Z : C} {f : X ⟶ Y} {g : X ⟶ Y} {h : Y ⟶ Z} (w : f ≫ h = g ≫ h) : is_colimit (functor.map_cocone G (cofork.of_π h w)) ≃ is_colimit (cofork.of_π (functor.map G h) (is_colimit_map_cocone_cofork_equiv._proof_1 G w)) := equiv.trans (equiv.symm (is_colimit.precompose_inv_equiv (diagram_iso_parallel_pair (parallel_pair f g ⋙ G)) (functor.map_cocone G (cofork.of_π h w)))) (is_colimit.equiv_iso_colimit (cofork.ext (iso.refl (cocone.X (functor.obj (cocones.precompose (iso.inv (diagram_iso_parallel_pair (parallel_pair f g ⋙ G)))) (functor.map_cocone G (cofork.of_π h w))))) sorry)) /-- The property of preserving coequalizers expressed in terms of coforks. -/ def is_colimit_cofork_map_of_is_colimit {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) {X : C} {Y : C} {Z : C} {f : X ⟶ Y} {g : X ⟶ Y} {h : Y ⟶ Z} (w : f ≫ h = g ≫ h) [preserves_colimit (parallel_pair f g) G] (l : is_colimit (cofork.of_π h w)) : is_colimit (cofork.of_π (functor.map G h) (is_colimit_map_cocone_cofork_equiv._proof_1 G w)) := coe_fn (is_colimit_map_cocone_cofork_equiv G w) (preserves_colimit.preserves l) /-- The property of reflecting coequalizers expressed in terms of coforks. -/ def is_colimit_of_is_colimit_cofork_map {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) {X : C} {Y : C} {Z : C} {f : X ⟶ Y} {g : X ⟶ Y} {h : Y ⟶ Z} (w : f ≫ h = g ≫ h) [reflects_colimit (parallel_pair f g) G] (l : is_colimit (cofork.of_π (functor.map G h) (is_colimit_of_is_colimit_cofork_map._proof_1 G w))) : is_colimit (cofork.of_π h w) := reflects_colimit.reflects (coe_fn (equiv.symm (is_colimit_map_cocone_cofork_equiv G w)) l) /-- If `G` preserves coequalizers and `C` has them, then the cofork constructed of the mapped morphisms of a cofork is a colimit. -/ def is_colimit_of_has_coequalizer_of_preserves_colimit {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) [has_coequalizer f g] [preserves_colimit (parallel_pair f g) G] : is_colimit (cofork.of_π (functor.map G (coequalizer.π f g)) (is_colimit_of_has_coequalizer_of_preserves_colimit._proof_1 G f g)) := is_colimit_cofork_map_of_is_colimit G (coequalizer.condition f g) (coequalizer_is_coequalizer f g) /-- If the coequalizer comparison map for `G` at `(f,g)` is an isomorphism, then `G` preserves the coequalizer of `(f,g)`. -/ def of_iso_comparison {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) [has_coequalizer f g] [has_coequalizer (functor.map G f) (functor.map G g)] [i : is_iso (coequalizer_comparison f g G)] : preserves_colimit (parallel_pair f g) G := preserves_colimit_of_preserves_colimit_cocone (coequalizer_is_coequalizer f g) (coe_fn (equiv.symm (is_colimit_map_cocone_cofork_equiv G (coequalizer.condition f g))) (is_colimit.of_point_iso (colimit.is_colimit (parallel_pair (functor.map G f) (functor.map G g))))) /-- If `G` preserves the coequalizer of `(f,g)`, then the coequalizer comparison map for `G` at `(f,g)` is an isomorphism. -/ def preserves_coequalizer.iso {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) [has_coequalizer f g] [has_coequalizer (functor.map G f) (functor.map G g)] [preserves_colimit (parallel_pair f g) G] : coequalizer (functor.map G f) (functor.map G g) ≅ functor.obj G (coequalizer f g) := is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit (parallel_pair (functor.map G f) (functor.map G g))) (is_colimit_of_has_coequalizer_of_preserves_colimit G f g) @[simp] theorem preserves_coequalizer.iso_hom {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) [has_coequalizer f g] [has_coequalizer (functor.map G f) (functor.map G g)] [preserves_colimit (parallel_pair f g) G] : iso.hom (preserves_coequalizer.iso G f g) = coequalizer_comparison f g G := rfl protected instance coequalizer_comparison.category_theory.is_iso {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) [has_coequalizer f g] [has_coequalizer (functor.map G f) (functor.map G g)] [preserves_colimit (parallel_pair f g) G] : is_iso (coequalizer_comparison f g G) := eq.mpr sorry (is_iso.of_iso (preserves_coequalizer.iso G f g)) /-- Any functor preserves coequalizers of split pairs. -/ protected instance preserves_split_coequalizers {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) [has_split_coequalizer f g] : preserves_colimit (parallel_pair f g) G := preserves_colimit_of_preserves_colimit_cocone (is_split_coequalizer.is_coequalizer (has_split_coequalizer.is_split_coequalizer f g)) (coe_fn (equiv.symm (is_colimit_map_cocone_cofork_equiv G sorry)) (is_split_coequalizer.is_coequalizer (is_split_coequalizer.map (has_split_coequalizer.is_split_coequalizer f g) G))) end Mathlib
2c763f72f35c58562bc05b0a8f1f4429cf39c945
c3f2fcd060adfa2ca29f924839d2d925e8f2c685
/library/algebra/category/basic.lean
f8dee3ef68f598ea05cbb685374de2afffa4eb69
[ "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
2,097
lean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: algebra.category.basic Author: Floris van Doorn -/ import logic.axioms.funext open eq eq.ops structure category [class] (ob : Type) : Type := (hom : ob → ob → Type) (comp : Π⦃a b c : ob⦄, hom b c → hom a b → hom a c) (ID : Π (a : ob), hom a a) (assoc : Π ⦃a b c d : ob⦄ (h : hom c d) (g : hom b c) (f : hom a b), comp h (comp g f) = comp (comp h g) f) (id_left : Π ⦃a b : ob⦄ (f : hom a b), comp !ID f = f) (id_right : Π ⦃a b : ob⦄ (f : hom a b), comp f !ID = f) attribute category [multiple-instances] namespace category variables {ob : Type} [C : category ob] variables {a b c d : ob} include C definition compose := comp definition id [reducible] {a : ob} : hom a a := ID a infixr `∘` := comp infixl `⟶`:25 := hom -- input ⟶ using \--> (this is a different arrow than \-> (→)) variables {h : hom c d} {g : hom b c} {f : hom a b} {i : hom a a} --the following is the only theorem for which "include C" is necessary if C is a variable (why?) theorem id_compose (a : ob) : (ID a) ∘ id = id := !id_left theorem left_id_unique (H : Π{b} {f : hom b a}, i ∘ f = f) : i = id := calc i = i ∘ id : id_right ... = id : H theorem right_id_unique (H : Π{b} {f : hom a b}, f ∘ i = f) : i = id := calc i = id ∘ i : id_left ... = id : H end category inductive Category : Type := mk : Π (ob : Type), category ob → Category namespace category definition Mk {ob} (C) : Category := Category.mk ob C definition MK (a b c d e f g) : Category := Category.mk a (category.mk b c d e f g) definition objects [coercion] [reducible] (C : Category) : Type := Category.rec (fun c s, c) C definition category_instance [instance] [coercion] [reducible] (C : Category) : category (objects C) := Category.rec (fun c s, s) C end category open category theorem Category.equal (C : Category) : Category.mk C C = C := Category.rec (λ ob c, rfl) C
e1626394c9299305c40cd8c6a271ad41eeeab19d
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/finsupp/pointwise_auto.lean
b0b0c2f4688906d0777dc93eb82d137ce6031c87
[]
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
1,636
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.finsupp.basic import Mathlib.PostPort universes u₂ u₁ namespace Mathlib /-! # The pointwise product on `finsupp`. TODO per issue #1864: We intend to remove the convolution product on finsupp, and define it only on a type synonym `add_monoid_algebra`. After we've done this, it would be good to make this the default product on `finsupp`. -/ namespace finsupp /-! ### Declarations about the pointwise product on `finsupp`s -/ /-- The product of `f g : α →₀ β` is the finitely supported function whose value at `a` is `f a * g a`. -/ protected instance has_mul {α : Type u₁} {β : Type u₂} [mul_zero_class β] : Mul (α →₀ β) := { mul := zip_with Mul.mul sorry } @[simp] theorem mul_apply {α : Type u₁} {β : Type u₂} [mul_zero_class β] {g₁ : α →₀ β} {g₂ : α →₀ β} {a : α} : coe_fn (g₁ * g₂) a = coe_fn g₁ a * coe_fn g₂ a := rfl theorem support_mul {α : Type u₁} {β : Type u₂} [mul_zero_class β] {g₁ : α →₀ β} {g₂ : α →₀ β} : support (g₁ * g₂) ⊆ support g₁ ∩ support g₂ := sorry protected instance semigroup {α : Type u₁} {β : Type u₂} [semiring β] : semigroup (α →₀ β) := semigroup.mk Mul.mul sorry protected instance distrib {α : Type u₁} {β : Type u₂} [semiring β] : distrib (α →₀ β) := distrib.mk semigroup.mul add_comm_monoid.add sorry sorry end Mathlib
7cc91a0cb0f55dbf47086a6b6ab9035cf7b54571
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/update.lean
ae13b2e6c8cf01de4e87850d59d9b354fa5d3cf0
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,137
lean
import Lean.Expr open Lean def main : IO Unit := do let f := mkConst `f []; let x := mkConst `x []; let y := mkConst `y []; let t1 := mkApp f x; let t2 := t1.updateApp! f y; let t3 := t1.updateApp! f x; let t4 := mkProj `Prod 1 x; let t5 := t4.updateProj! y; let t6 := t4.updateProj! x; let x₁ := x.updateConst! [levelOne]; let x₂ := x.updateConst! []; let s := mkSort levelOne; let s₁ := s.updateSort! levelOne; let s₂ := s.updateSort! levelZero; let a := mkForall `x BinderInfo.default s s; let a₁ := a.updateForall! BinderInfo.default s s; let a₂ := a.updateForall! BinderInfo.default s₂ s; let nat := mkConst `Nat []; let id := mkLambda `x BinderInfo.default nat (mkBVar 0); let id₁ := id.updateLambda! BinderInfo.default s (mkBVar 0); let id₂ := id.updateLambda! BinderInfo.default nat (mkBVar 0); let l := mkLet `z nat x t1; let l₁ := l.updateLet! nat x t2; let l₂ := l.updateLet! nat x t1; IO.println [t1, t2, t3, t5, t6, x₁, x₂, s₁, s₂, a₁, a₂, id₁, id₂, l₁, l₂]; pure () #eval main
04537e23dd6f472556428cda27ab502e4b993860
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/library/data/list/comb.lean
c891f9f7e5df33866df3cfbc0844199524ea6e86
[ "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
24,619
lean
/- Copyright (c) 2015 Leonardo de Moura. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Haitao Zhang, Floris van Doorn List combinators. -/ import data.list.basic data.equiv open nat prod decidable function helper_tactics namespace list variables {A B C : Type} section replicate -- 'replicate i n' returns the list contain i copies of n. definition replicate : ℕ → A → list A | 0 a := [] | (succ n) a := a :: replicate n a theorem length_replicate : ∀ (i : ℕ) (a : A), length (replicate i a) = i | 0 a := rfl | (succ i) a := calc length (replicate (succ i) a) = length (replicate i a) + 1 : rfl ... = i + 1 : length_replicate end replicate /- map -/ definition map (f : A → B) : list A → list B | [] := [] | (a :: l) := f a :: map l theorem map_nil (f : A → B) : map f [] = [] theorem map_cons (f : A → B) (a : A) (l : list A) : map f (a :: l) = f a :: map f l lemma map_concat (f : A → B) (a : A) : Πl, map f (concat a l) = concat (f a) (map f l) | nil := rfl | (b::l) := begin rewrite [concat_cons, +map_cons, concat_cons, map_concat] end lemma map_append (f : A → B) : ∀ l₁ l₂, map f (l₁++l₂) = (map f l₁)++(map f l₂) | nil := take l, rfl | (a::l) := take l', begin rewrite [append_cons, *map_cons, append_cons, map_append] end lemma map_reverse (f : A → B) : Πl, map f (reverse l) = reverse (map f l) | nil := rfl | (b::l) := begin rewrite [reverse_cons, +map_cons, reverse_cons, map_concat, map_reverse] end lemma map_singleton (f : A → B) (a : A) : map f [a] = [f a] := rfl theorem map_id [simp] : ∀ l : list A, map id l = l | [] := rfl | (x::xs) := begin rewrite [map_cons, map_id] end theorem map_id' {f : A → A} (H : ∀x, f x = x) : ∀ l : list A, map f l = l | [] := rfl | (x::xs) := begin rewrite [map_cons, H, map_id'] end theorem map_map [simp] (g : B → C) (f : A → B) : ∀ l, map g (map f l) = map (g ∘ f) l | [] := rfl | (a :: l) := show (g ∘ f) a :: map g (map f l) = map (g ∘ f) (a :: l), by rewrite (map_map l) theorem length_map [simp] (f : A → B) : ∀ l : list A, length (map f l) = length l | [] := by esimp | (a :: l) := show length (map f l) + 1 = length l + 1, by rewrite (length_map l) theorem map_ne_nil_of_ne_nil (f : A → B) {l : list A} (H : l ≠ nil) : map f l ≠ nil := suppose map f l = nil, have length (map f l) = length l, from !length_map, have 0 = length l, from calc 0 = length nil : length_nil ... = length (map f l) : {eq.symm `map f l = nil`} ... = length l : this, have l = nil, from eq_nil_of_length_eq_zero (eq.symm this), H this theorem mem_map {A B : Type} (f : A → B) : ∀ {a l}, a ∈ l → f a ∈ map f l | a [] i := absurd i !not_mem_nil | a (x::xs) i := or.elim (eq_or_mem_of_mem_cons i) (suppose a = x, by rewrite [this, map_cons]; apply mem_cons) (suppose a ∈ xs, or.inr (mem_map this)) theorem exists_of_mem_map {A B : Type} {f : A → B} {b : B} : ∀{l}, b ∈ map f l → ∃a, a ∈ l ∧ f a = b | [] H := false.elim H | (c::l) H := or.elim (iff.mp !mem_cons_iff H) (suppose b = f c, exists.intro c (and.intro !mem_cons (eq.symm this))) (suppose b ∈ map f l, obtain a (Hl : a ∈ l) (Hr : f a = b), from exists_of_mem_map this, exists.intro a (and.intro (mem_cons_of_mem _ Hl) Hr)) theorem eq_of_map_const {A B : Type} {b₁ b₂ : B} : ∀ {l : list A}, b₁ ∈ map (const A b₂) l → b₁ = b₂ | [] h := absurd h !not_mem_nil | (a::l) h := or.elim (eq_or_mem_of_mem_cons h) (suppose b₁ = b₂, this) (suppose b₁ ∈ map (const A b₂) l, eq_of_map_const this) definition map₂ (f : A → B → C) : list A → list B → list C | [] _ := [] | _ [] := [] | (x::xs) (y::ys) := f x y :: map₂ xs ys theorem map₂_nil1 (f : A → B → C) : ∀ (l : list B), map₂ f [] l = [] | [] := rfl | (a::y) := rfl theorem map₂_nil2 (f : A → B → C) : ∀ (l : list A), map₂ f l [] = [] | [] := rfl | (a::y) := rfl theorem length_map₂ : ∀(f : A → B → C) x y, length (map₂ f x y) = min (length x) (length y) | f [] [] := rfl | f (xh::xr) [] := rfl | f [] (yh::yr) := rfl | f (xh::xr) (yh::yr) := calc length (map₂ f (xh::xr) (yh::yr)) = length (map₂ f xr yr) + 1 : rfl ... = min (length xr) (length yr) + 1 : length_map₂ ... = min (length (xh::xr)) (length (yh::yr)) : min_succ_succ /- filter -/ definition filter (p : A → Prop) [h : decidable_pred p] : list A → list A | [] := [] | (a::l) := if p a then a :: filter l else filter l theorem filter_nil [simp] (p : A → Prop) [h : decidable_pred p] : filter p [] = [] theorem filter_cons_of_pos [simp] {p : A → Prop} [h : decidable_pred p] {a : A} : ∀ l, p a → filter p (a::l) = a :: filter p l := λ l pa, if_pos pa theorem filter_cons_of_neg [simp] {p : A → Prop} [h : decidable_pred p] {a : A} : ∀ l, ¬ p a → filter p (a::l) = filter p l := λ l pa, if_neg pa theorem of_mem_filter {p : A → Prop} [h : decidable_pred p] {a : A} : ∀ {l}, a ∈ filter p l → p a | [] ain := absurd ain !not_mem_nil | (b::l) ain := by_cases (assume pb : p b, have a ∈ b :: filter p l, by rewrite [filter_cons_of_pos _ pb at ain]; exact ain, or.elim (eq_or_mem_of_mem_cons this) (suppose a = b, by rewrite [-this at pb]; exact pb) (suppose a ∈ filter p l, of_mem_filter this)) (suppose ¬ p b, by rewrite [filter_cons_of_neg _ this at ain]; exact (of_mem_filter ain)) theorem mem_of_mem_filter {p : A → Prop} [h : decidable_pred p] {a : A} : ∀ {l}, a ∈ filter p l → a ∈ l | [] ain := absurd ain !not_mem_nil | (b::l) ain := by_cases (λ pb : p b, have a ∈ b :: filter p l, by rewrite [filter_cons_of_pos _ pb at ain]; exact ain, or.elim (eq_or_mem_of_mem_cons this) (suppose a = b, by rewrite this; exact !mem_cons) (suppose a ∈ filter p l, mem_cons_of_mem _ (mem_of_mem_filter this))) (suppose ¬ p b, by rewrite [filter_cons_of_neg _ this at ain]; exact (mem_cons_of_mem _ (mem_of_mem_filter ain))) theorem mem_filter_of_mem {p : A → Prop} [h : decidable_pred p] {a : A} : ∀ {l}, a ∈ l → p a → a ∈ filter p l | [] ain pa := absurd ain !not_mem_nil | (b::l) ain pa := by_cases (λ pb : p b, or.elim (eq_or_mem_of_mem_cons ain) (λ aeqb : a = b, by rewrite [filter_cons_of_pos _ pb, aeqb]; exact !mem_cons) (λ ainl : a ∈ l, by rewrite [filter_cons_of_pos _ pb]; exact (mem_cons_of_mem _ (mem_filter_of_mem ainl pa)))) (λ npb : ¬ p b, or.elim (eq_or_mem_of_mem_cons ain) (λ aeqb : a = b, absurd (eq.rec_on aeqb pa) npb) (λ ainl : a ∈ l, by rewrite [filter_cons_of_neg _ npb]; exact (mem_filter_of_mem ainl pa))) theorem filter_sub [simp] {p : A → Prop} [h : decidable_pred p] (l : list A) : filter p l ⊆ l := λ a ain, mem_of_mem_filter ain theorem filter_append {p : A → Prop} [h : decidable_pred p] : ∀ (l₁ l₂ : list A), filter p (l₁++l₂) = filter p l₁ ++ filter p l₂ | [] l₂ := rfl | (a::l₁) l₂ := by_cases (suppose p a, by rewrite [append_cons, *filter_cons_of_pos _ this, filter_append]) (suppose ¬ p a, by rewrite [append_cons, *filter_cons_of_neg _ this, filter_append]) /- foldl & foldr -/ definition foldl (f : A → B → A) : A → list B → A | a [] := a | a (b :: l) := foldl (f a b) l theorem foldl_nil [simp] (f : A → B → A) (a : A) : foldl f a [] = a theorem foldl_cons [simp] (f : A → B → A) (a : A) (b : B) (l : list B) : foldl f a (b::l) = foldl f (f a b) l definition foldr (f : A → B → B) : B → list A → B | b [] := b | b (a :: l) := f a (foldr b l) theorem foldr_nil [simp] (f : A → B → B) (b : B) : foldr f b [] = b theorem foldr_cons [simp] (f : A → B → B) (b : B) (a : A) (l : list A) : foldr f b (a::l) = f a (foldr f b l) section foldl_eq_foldr -- foldl and foldr coincide when f is commutative and associative parameters {α : Type} {f : α → α → α} hypothesis (Hcomm : ∀ a b, f a b = f b a) hypothesis (Hassoc : ∀ a b c, f (f a b) c = f a (f b c)) include Hcomm Hassoc theorem foldl_eq_of_comm_of_assoc : ∀ a b l, foldl f a (b::l) = f b (foldl f a l) | a b nil := Hcomm a b | a b (c::l) := begin change foldl f (f (f a b) c) l = f b (foldl f (f a c) l), rewrite -foldl_eq_of_comm_of_assoc, change foldl f (f (f a b) c) l = foldl f (f (f a c) b) l, have H₁ : f (f a b) c = f (f a c) b, by rewrite [Hassoc, Hassoc, Hcomm b c], rewrite H₁ end theorem foldl_eq_foldr : ∀ a l, foldl f a l = foldr f a l | a nil := rfl | a (b :: l) := begin rewrite foldl_eq_of_comm_of_assoc, esimp, change f b (foldl f a l) = f b (foldr f a l), rewrite foldl_eq_foldr end end foldl_eq_foldr theorem foldl_append [simp] (f : B → A → B) : ∀ (b : B) (l₁ l₂ : list A), foldl f b (l₁++l₂) = foldl f (foldl f b l₁) l₂ | b [] l₂ := rfl | b (a::l₁) l₂ := by rewrite [append_cons, *foldl_cons, foldl_append] theorem foldr_append [simp] (f : A → B → B) : ∀ (b : B) (l₁ l₂ : list A), foldr f b (l₁++l₂) = foldr f (foldr f b l₂) l₁ | b [] l₂ := rfl | b (a::l₁) l₂ := by rewrite [append_cons, *foldr_cons, foldr_append] /- all & any -/ definition all (l : list A) (p : A → Prop) : Prop := foldr (λ a r, p a ∧ r) true l definition any (l : list A) (p : A → Prop) : Prop := foldr (λ a r, p a ∨ r) false l theorem all_nil_eq [simp] (p : A → Prop) : all [] p = true theorem all_nil (p : A → Prop) : all [] p := trivial theorem all_cons_eq (p : A → Prop) (a : A) (l : list A) : all (a::l) p = (p a ∧ all l p) theorem all_cons {p : A → Prop} {a : A} {l : list A} (H1 : p a) (H2 : all l p) : all (a::l) p := and.intro H1 H2 theorem all_of_all_cons {p : A → Prop} {a : A} {l : list A} : all (a::l) p → all l p := assume h, by rewrite [all_cons_eq at h]; exact (and.elim_right h) theorem of_all_cons {p : A → Prop} {a : A} {l : list A} : all (a::l) p → p a := assume h, by rewrite [all_cons_eq at h]; exact (and.elim_left h) theorem all_cons_of_all {p : A → Prop} {a : A} {l : list A} : p a → all l p → all (a::l) p := assume pa alllp, and.intro pa alllp theorem all_implies {p q : A → Prop} : ∀ {l}, all l p → (∀ x, p x → q x) → all l q | [] h₁ h₂ := trivial | (a::l) h₁ h₂ := have all l q, from all_implies (all_of_all_cons h₁) h₂, have q a, from h₂ a (of_all_cons h₁), all_cons_of_all this `all l q` theorem of_mem_of_all {p : A → Prop} {a : A} : ∀ {l}, a ∈ l → all l p → p a | [] h₁ h₂ := absurd h₁ !not_mem_nil | (b::l) h₁ h₂ := or.elim (eq_or_mem_of_mem_cons h₁) (suppose a = b, by rewrite [all_cons_eq at h₂, -this at h₂]; exact (and.elim_left h₂)) (suppose a ∈ l, have all l p, by rewrite [all_cons_eq at h₂]; exact (and.elim_right h₂), of_mem_of_all `a ∈ l` this) theorem all_of_forall {p : A → Prop} : ∀ {l}, (∀a, a ∈ l → p a) → all l p | [] H := !all_nil | (a::l) H := all_cons (H a !mem_cons) (all_of_forall (λ a' H', H a' (mem_cons_of_mem _ H'))) theorem any_nil [simp] (p : A → Prop) : any [] p = false theorem any_cons [simp] (p : A → Prop) (a : A) (l : list A) : any (a::l) p = (p a ∨ any l p) theorem any_of_mem {p : A → Prop} {a : A} : ∀ {l}, a ∈ l → p a → any l p | [] i h := absurd i !not_mem_nil | (b::l) i h := or.elim (eq_or_mem_of_mem_cons i) (suppose a = b, by rewrite [-this]; exact (or.inl h)) (suppose a ∈ l, have any l p, from any_of_mem this h, or.inr this) theorem exists_of_any {p : A → Prop} : ∀{l : list A}, any l p → ∃a, a ∈ l ∧ p a | [] H := false.elim H | (b::l) H := or.elim H (assume H1 : p b, exists.intro b (and.intro !mem_cons H1)) (assume H1 : any l p, obtain a (H2l : a ∈ l) (H2r : p a), from exists_of_any H1, exists.intro a (and.intro (mem_cons_of_mem b H2l) H2r)) definition decidable_all (p : A → Prop) [H : decidable_pred p] : ∀ l, decidable (all l p) | [] := decidable_true | (a :: l) := match H a with | inl Hp₁ := match decidable_all l with | inl Hp₂ := inl (and.intro Hp₁ Hp₂) | inr Hn₂ := inr (not_and_of_not_right (p a) Hn₂) end | inr Hn := inr (not_and_of_not_left (all l p) Hn) end definition decidable_any (p : A → Prop) [H : decidable_pred p] : ∀ l, decidable (any l p) | [] := decidable_false | (a :: l) := match H a with | inl Hp := inl (or.inl Hp) | inr Hn₁ := match decidable_any l with | inl Hp₂ := inl (or.inr Hp₂) | inr Hn₂ := inr (not_or Hn₁ Hn₂) end end /- zip & unzip -/ definition zip (l₁ : list A) (l₂ : list B) : list (A × B) := map₂ (λ a b, (a, b)) l₁ l₂ definition unzip : list (A × B) → list A × list B | [] := ([], []) | ((a, b) :: l) := match unzip l with | (la, lb) := (a :: la, b :: lb) end theorem unzip_nil [simp] : unzip (@nil (A × B)) = ([], []) theorem unzip_cons [simp] (a : A) (b : B) (l : list (A × B)) : unzip ((a, b) :: l) = match unzip l with (la, lb) := (a :: la, b :: lb) end := rfl theorem zip_unzip : ∀ (l : list (A × B)), zip (pr₁ (unzip l)) (pr₂ (unzip l)) = l | [] := rfl | ((a, b) :: l) := begin rewrite unzip_cons, have r : zip (pr₁ (unzip l)) (pr₂ (unzip l)) = l, from zip_unzip l, revert r, eapply prod.cases_on (unzip l), intro la lb r, rewrite -r end section mapAccumR variable {S : Type} -- This runs a function over a list returning the intermediate results and a -- a final result. definition mapAccumR : (A → S → S × B) → list A → S → (S × list B) | f [] c := (c, []) | f (y::yr) c := let r := mapAccumR f yr c in let z := f y (pr₁ r) in (pr₁ z, pr₂ z :: pr₂ r) theorem length_mapAccumR : ∀ (f : A → S → S × B) (x : list A) (s : S), length (pr₂ (mapAccumR f x s)) = length x | f (a::x) s := calc length (pr₂ (mapAccumR f (a::x) s)) = length x + 1 : { length_mapAccumR f x s } ... = length (a::x) : rfl | f [] s := calc length (pr₂ (mapAccumR f [] s)) = 0 : rfl end mapAccumR section mapAccumR₂ variable {S : Type} -- This runs a function over two lists returning the intermediate results and a -- a final result. definition mapAccumR₂ : (A → B → S → S × C) → list A → list B → S → S × list C | f [] _ c := (c,[]) | f _ [] c := (c,[]) | f (x::xr) (y::yr) c := let r := mapAccumR₂ f xr yr c in let q := f x y (pr₁ r) in (pr₁ q, pr₂ q :: (pr₂ r)) theorem length_mapAccumR₂ : ∀ (f : A → B → S → S × C) (x : list A) (y : list B) (c : S), length (pr₂ (mapAccumR₂ f x y c)) = min (length x) (length y) | f (a::x) (b::y) c := calc length (pr₂ (mapAccumR₂ f (a::x) (b::y) c)) = length (pr₂ (mapAccumR₂ f x y c)) + 1 : rfl ... = min (length x) (length y) + 1 : length_mapAccumR₂ f x y c ... = min (length (a::x)) (length (b::y)) : min_succ_succ | f (a::x) [] c := rfl | f [] (b::y) c := rfl | f [] [] c := rfl end mapAccumR₂ /- flat -/ definition flat (l : list (list A)) : list A := foldl append nil l /- product -/ section product definition product : list A → list B → list (A × B) | [] l₂ := [] | (a::l₁) l₂ := map (λ b, (a, b)) l₂ ++ product l₁ l₂ theorem nil_product (l : list B) : product (@nil A) l = [] theorem product_cons (a : A) (l₁ : list A) (l₂ : list B) : product (a::l₁) l₂ = map (λ b, (a, b)) l₂ ++ product l₁ l₂ theorem product_nil : ∀ (l : list A), product l (@nil B) = [] | [] := rfl | (a::l) := by rewrite [product_cons, map_nil, product_nil] theorem eq_of_mem_map_pair₁ {a₁ a : A} {b₁ : B} {l : list B} : (a₁, b₁) ∈ map (λ b, (a, b)) l → a₁ = a := assume ain, assert pr1 (a₁, b₁) ∈ map pr1 (map (λ b, (a, b)) l), from mem_map pr1 ain, assert a₁ ∈ map (λb, a) l, by revert this; rewrite [map_map, ↑pr1]; intro this; assumption, eq_of_map_const this theorem mem_of_mem_map_pair₁ {a₁ a : A} {b₁ : B} {l : list B} : (a₁, b₁) ∈ map (λ b, (a, b)) l → b₁ ∈ l := assume ain, assert pr2 (a₁, b₁) ∈ map pr2 (map (λ b, (a, b)) l), from mem_map pr2 ain, assert b₁ ∈ map (λx, x) l, by rewrite [map_map at this, ↑pr2 at this]; exact this, by rewrite [map_id at this]; exact this theorem mem_product {a : A} {b : B} : ∀ {l₁ l₂}, a ∈ l₁ → b ∈ l₂ → (a, b) ∈ product l₁ l₂ | [] l₂ h₁ h₂ := absurd h₁ !not_mem_nil | (x::l₁) l₂ h₁ h₂ := or.elim (eq_or_mem_of_mem_cons h₁) (assume aeqx : a = x, assert (a, b) ∈ map (λ b, (a, b)) l₂, from mem_map _ h₂, begin rewrite [-aeqx, product_cons], exact mem_append_left _ this end) (assume ainl₁ : a ∈ l₁, assert (a, b) ∈ product l₁ l₂, from mem_product ainl₁ h₂, begin rewrite [product_cons], exact mem_append_right _ this end) theorem mem_of_mem_product_left {a : A} {b : B} : ∀ {l₁ l₂}, (a, b) ∈ product l₁ l₂ → a ∈ l₁ | [] l₂ h := absurd h !not_mem_nil | (x::l₁) l₂ h := or.elim (mem_or_mem_of_mem_append h) (suppose (a, b) ∈ map (λ b, (x, b)) l₂, assert a = x, from eq_of_mem_map_pair₁ this, by rewrite this; exact !mem_cons) (suppose (a, b) ∈ product l₁ l₂, have a ∈ l₁, from mem_of_mem_product_left this, mem_cons_of_mem _ this) theorem mem_of_mem_product_right {a : A} {b : B} : ∀ {l₁ l₂}, (a, b) ∈ product l₁ l₂ → b ∈ l₂ | [] l₂ h := absurd h !not_mem_nil | (x::l₁) l₂ h := or.elim (mem_or_mem_of_mem_append h) (suppose (a, b) ∈ map (λ b, (x, b)) l₂, mem_of_mem_map_pair₁ this) (suppose (a, b) ∈ product l₁ l₂, mem_of_mem_product_right this) theorem length_product : ∀ (l₁ : list A) (l₂ : list B), length (product l₁ l₂) = length l₁ * length l₂ | [] l₂ := by rewrite [length_nil, zero_mul] | (x::l₁) l₂ := assert length (product l₁ l₂) = length l₁ * length l₂, from length_product l₁ l₂, by rewrite [product_cons, length_append, length_cons, length_map, this, right_distrib, one_mul, add.comm] end product -- new for list/comb dependent map theory definition dinj₁ (p : A → Prop) (f : Π a, p a → B) := ∀ ⦃a1 a2⦄ (h1 : p a1) (h2 : p a2), a1 ≠ a2 → (f a1 h1) ≠ (f a2 h2) definition dinj (p : A → Prop) (f : Π a, p a → B) := ∀ ⦃a1 a2⦄ (h1 : p a1) (h2 : p a2), (f a1 h1) = (f a2 h2) → a1 = a2 definition dmap (p : A → Prop) [h : decidable_pred p] (f : Π a, p a → B) : list A → list B | [] := [] | (a::l) := if P : (p a) then cons (f a P) (dmap l) else (dmap l) -- properties of dmap section dmap variable {p : A → Prop} variable [h : decidable_pred p] include h variable {f : Π a, p a → B} lemma dmap_nil : dmap p f [] = [] := rfl lemma dmap_cons_of_pos {a : A} (P : p a) : ∀ l, dmap p f (a::l) = (f a P) :: dmap p f l := λ l, dif_pos P lemma dmap_cons_of_neg {a : A} (P : ¬ p a) : ∀ l, dmap p f (a::l) = dmap p f l := λ l, dif_neg P lemma mem_dmap : ∀ {l : list A} {a} (Pa : p a), a ∈ l → (f a Pa) ∈ dmap p f l | [] := take a Pa Pinnil, by contradiction | (a::l) := take b Pb Pbin, or.elim (eq_or_mem_of_mem_cons Pbin) (assume Pbeqa, begin rewrite [eq.symm Pbeqa, dmap_cons_of_pos Pb], exact !mem_cons end) (assume Pbinl, decidable.rec_on (h a) (assume Pa, begin rewrite [dmap_cons_of_pos Pa], apply mem_cons_of_mem, exact mem_dmap Pb Pbinl end) (assume nPa, begin rewrite [dmap_cons_of_neg nPa], exact mem_dmap Pb Pbinl end)) lemma exists_of_mem_dmap : ∀ {l : list A} {b : B}, b ∈ dmap p f l → ∃ a P, a ∈ l ∧ b = f a P | [] := take b, by rewrite dmap_nil; contradiction | (a::l) := take b, decidable.rec_on (h a) (assume Pa, begin rewrite [dmap_cons_of_pos Pa, mem_cons_iff], intro Pb, cases Pb with Peq Pin, exact exists.intro a (exists.intro Pa (and.intro !mem_cons Peq)), assert Pex : ∃ (a : A) (P : p a), a ∈ l ∧ b = f a P, exact exists_of_mem_dmap Pin, cases Pex with a' Pex', cases Pex' with Pa' P', exact exists.intro a' (exists.intro Pa' (and.intro (mem_cons_of_mem a (and.left P')) (and.right P'))) end) (assume nPa, begin rewrite [dmap_cons_of_neg nPa], intro Pin, assert Pex : ∃ (a : A) (P : p a), a ∈ l ∧ b = f a P, exact exists_of_mem_dmap Pin, cases Pex with a' Pex', cases Pex' with Pa' P', exact exists.intro a' (exists.intro Pa' (and.intro (mem_cons_of_mem a (and.left P')) (and.right P'))) end) lemma map_dmap_of_inv_of_pos {g : B → A} (Pinv : ∀ a (Pa : p a), g (f a Pa) = a) : ∀ {l : list A}, (∀ ⦃a⦄, a ∈ l → p a) → map g (dmap p f l) = l | [] := assume Pl, by rewrite [dmap_nil, map_nil] | (a::l) := assume Pal, assert Pa : p a, from Pal a !mem_cons, assert Pl : ∀ a, a ∈ l → p a, from take x Pxin, Pal x (mem_cons_of_mem a Pxin), by rewrite [dmap_cons_of_pos Pa, map_cons, Pinv, map_dmap_of_inv_of_pos Pl] lemma mem_of_dinj_of_mem_dmap (Pdi : dinj p f) : ∀ {l : list A} {a} (Pa : p a), (f a Pa) ∈ dmap p f l → a ∈ l | [] := take a Pa Pinnil, by contradiction | (b::l) := take a Pa Pmap, decidable.rec_on (h b) (λ Pb, begin rewrite (dmap_cons_of_pos Pb) at Pmap, rewrite mem_cons_iff at Pmap, rewrite mem_cons_iff, apply (or_of_or_of_imp_of_imp Pmap), apply Pdi, apply mem_of_dinj_of_mem_dmap Pa end) (λ nPb, begin rewrite (dmap_cons_of_neg nPb) at Pmap, apply mem_cons_of_mem, exact mem_of_dinj_of_mem_dmap Pa Pmap end) lemma not_mem_dmap_of_dinj_of_not_mem (Pdi : dinj p f) {l : list A} {a} (Pa : p a) : a ∉ l → (f a Pa) ∉ dmap p f l := not.mto (mem_of_dinj_of_mem_dmap Pdi Pa) end dmap section open equiv definition list_equiv_of_equiv {A B : Type} : A ≃ B → list A ≃ list B | (mk f g l r) := mk (map f) (map g) begin intros, rewrite [map_map, id_of_left_inverse l, map_id], try reflexivity end begin intros, rewrite [map_map, id_of_right_inverse r, map_id], try reflexivity end private definition to_nat : list nat → nat | [] := 0 | (x::xs) := succ (mkpair (to_nat xs) x) open prod.ops private definition of_nat.F : Π (n : nat), (Π m, m < n → list nat) → list nat | 0 f := [] | (succ n) f := (unpair n).2 :: f (unpair n).1 (unpair_lt n) private definition of_nat : nat → list nat := well_founded.fix of_nat.F private lemma of_nat_zero : of_nat 0 = [] := well_founded.fix_eq of_nat.F 0 private lemma of_nat_succ (n : nat) : of_nat (succ n) = (unpair n).2 :: of_nat (unpair n).1 := well_founded.fix_eq of_nat.F (succ n) private lemma to_nat_of_nat (n : nat) : to_nat (of_nat n) = n := nat.case_strong_induction_on n _ (λ n ih, begin rewrite of_nat_succ, unfold to_nat, have to_nat (of_nat (unpair n).1) = (unpair n).1, from ih _ (le_of_lt_succ (unpair_lt n)), rewrite this, rewrite mkpair_unpair end) private lemma of_nat_to_nat : ∀ (l : list nat), of_nat (to_nat l) = l | [] := rfl | (x::xs) := begin unfold to_nat, rewrite of_nat_succ, rewrite *unpair_mkpair, esimp, congruence, apply of_nat_to_nat end definition list_nat_equiv_nat : list nat ≃ nat := mk to_nat of_nat of_nat_to_nat to_nat_of_nat definition list_equiv_self_of_equiv_nat {A : Type} : A ≃ nat → list A ≃ A := suppose A ≃ nat, calc list A ≃ list nat : list_equiv_of_equiv this ... ≃ nat : list_nat_equiv_nat ... ≃ A : this end end list attribute list.decidable_any [instance] attribute list.decidable_all [instance]
ebf66847f39e957de77d4a327885d994b21e62ff
680b0d1592ce164979dab866b232f6fa743f2cc8
/library/algebra/ordered_ring.lean
ff3875e0bee7448daa9b293185b45be55c2a1400
[ "Apache-2.0" ]
permissive
syohex/lean
657428ab520f8277fc18cf04bea2ad200dbae782
081ad1212b686780f3ff8a6d0e5f8a1d29a7d8bc
refs/heads/master
1,611,274,838,635
1,452,668,188,000
1,452,668,188,000
49,562,028
0
0
null
1,452,675,604,000
1,452,675,602,000
null
UTF-8
Lean
false
false
27,803
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 end structure linear_ordered_semiring [class] (A : Type) extends ordered_semiring A, linear_strong_order_pair A := (zero_lt_one : lt zero one) section variable [s : linear_ordered_semiring A] variables {a b c : A} include s theorem zero_lt_one : 0 < (1:A) := linear_ordered_semiring.zero_lt_one A theorem lt_of_mul_lt_mul_left (H : c * a < c * b) (Hc : c ≥ 0) : a < b := lt_of_not_ge (assume H1 : b ≤ a, have H2 : c * b ≤ c * a, from mul_le_mul_of_nonneg_left H1 Hc, not_lt_of_ge H2 H) theorem lt_of_mul_lt_mul_right (H : a * c < b * c) (Hc : c ≥ 0) : a < b := lt_of_not_ge (assume H1 : b ≤ a, have H2 : b * c ≤ a * c, from mul_le_mul_of_nonneg_right H1 Hc, not_lt_of_ge H2 H) theorem le_of_mul_le_mul_left (H : c * a ≤ c * b) (Hc : c > 0) : a ≤ b := le_of_not_gt (assume H1 : b < a, have H2 : c * b < c * a, from mul_lt_mul_of_pos_left H1 Hc, not_le_of_gt H2 H) theorem le_of_mul_le_mul_right (H : a * c ≤ b * c) (Hc : c > 0) : a ≤ b := le_of_not_gt (assume H1 : b < a, have H2 : b * c < a * c, from mul_lt_mul_of_pos_right H1 Hc, not_le_of_gt H2 H) theorem le_iff_mul_le_mul_left (a b : A) {c : A} (H : c > 0) : a ≤ b ↔ c * a ≤ c * b := iff.intro (assume H', mul_le_mul_of_nonneg_left H' (le_of_lt H)) (assume H', le_of_mul_le_mul_left H' H) theorem le_iff_mul_le_mul_right (a b : A) {c : A} (H : c > 0) : a ≤ b ↔ a * c ≤ b * c := iff.intro (assume H', mul_le_mul_of_nonneg_right H' (le_of_lt H)) (assume H', le_of_mul_le_mul_right H' H) theorem pos_of_mul_pos_left (H : 0 < a * b) (H1 : 0 ≤ a) : 0 < b := lt_of_not_ge (assume H2 : b ≤ 0, have H3 : a * b ≤ 0, from mul_nonpos_of_nonneg_of_nonpos H1 H2, not_lt_of_ge H3 H) theorem pos_of_mul_pos_right (H : 0 < a * b) (H1 : 0 ≤ b) : 0 < a := lt_of_not_ge (assume H2 : a ≤ 0, have H3 : a * b ≤ 0, from mul_nonpos_of_nonpos_of_nonneg H2 H1, not_lt_of_ge H3 H) theorem nonneg_of_mul_nonneg_left (H : 0 ≤ a * b) (H1 : 0 < a) : 0 ≤ b := le_of_not_gt (assume H2 : b < 0, not_le_of_gt (mul_neg_of_pos_of_neg H1 H2) H) theorem nonneg_of_mul_nonneg_right (H : 0 ≤ a * b) (H1 : 0 < b) : 0 ≤ a := le_of_not_gt (assume H2 : a < 0, not_le_of_gt (mul_neg_of_neg_of_pos H2 H1) H) theorem neg_of_mul_neg_left (H : a * b < 0) (H1 : 0 ≤ a) : b < 0 := lt_of_not_ge (assume H2 : b ≥ 0, not_lt_of_ge (mul_nonneg H1 H2) H) theorem neg_of_mul_neg_right (H : a * b < 0) (H1 : 0 ≤ b) : a < 0 := lt_of_not_ge (assume H2 : a ≥ 0, not_lt_of_ge (mul_nonneg H2 H1) H) theorem nonpos_of_mul_nonpos_left (H : a * b ≤ 0) (H1 : 0 < a) : b ≤ 0 := le_of_not_gt (assume H2 : b > 0, not_le_of_gt (mul_pos H1 H2) H) theorem nonpos_of_mul_nonpos_right (H : a * b ≤ 0) (H1 : 0 < b) : a ≤ 0 := le_of_not_gt (assume H2 : a > 0, not_le_of_gt (mul_pos H2 H1) H) end structure decidable_linear_ordered_semiring [class] (A : Type) extends linear_ordered_semiring A, decidable_linear_order A /- ring structures -/ structure ordered_ring [class] (A : Type) extends ring A, ordered_comm_group A, zero_ne_one_class A := (mul_nonneg : ∀a b, le zero a → le zero b → le zero (mul a b)) (mul_pos : ∀a b, lt zero a → lt zero b → lt zero (mul a b)) theorem ordered_ring.mul_le_mul_of_nonneg_left [s : ordered_ring A] {a b c : A} (Hab : a ≤ b) (Hc : 0 ≤ c) : c * a ≤ c * b := have H1 : 0 ≤ b - a, from iff.elim_right !sub_nonneg_iff_le Hab, assert H2 : 0 ≤ c * (b - a), from ordered_ring.mul_nonneg _ _ Hc H1, begin rewrite mul_sub_left_distrib at H2, exact (iff.mp !sub_nonneg_iff_le H2) end theorem ordered_ring.mul_le_mul_of_nonneg_right [s : ordered_ring A] {a b c : A} (Hab : a ≤ b) (Hc : 0 ≤ c) : a * c ≤ b * c := have H1 : 0 ≤ b - a, from iff.elim_right !sub_nonneg_iff_le Hab, assert H2 : 0 ≤ (b - a) * c, from ordered_ring.mul_nonneg _ _ H1 Hc, begin rewrite mul_sub_right_distrib at H2, exact (iff.mp !sub_nonneg_iff_le H2) end theorem ordered_ring.mul_lt_mul_of_pos_left [s : ordered_ring A] {a b c : A} (Hab : a < b) (Hc : 0 < c) : c * a < c * b := have H1 : 0 < b - a, from iff.elim_right !sub_pos_iff_lt Hab, assert H2 : 0 < c * (b - a), from ordered_ring.mul_pos _ _ Hc H1, begin rewrite mul_sub_left_distrib at H2, exact (iff.mp !sub_pos_iff_lt H2) end theorem ordered_ring.mul_lt_mul_of_pos_right [s : ordered_ring A] {a b c : A} (Hab : a < b) (Hc : 0 < c) : a * c < b * c := have H1 : 0 < b - a, from iff.elim_right !sub_pos_iff_lt Hab, assert H2 : 0 < (b - a) * c, from ordered_ring.mul_pos _ _ H1 Hc, begin rewrite mul_sub_right_distrib at H2, exact (iff.mp !sub_pos_iff_lt H2) end definition ordered_ring.to_ordered_semiring [trans_instance] [reducible] [s : ordered_ring A] : ordered_semiring A := ⦃ ordered_semiring, s, mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add.left_cancel A _, add_right_cancel := @add.right_cancel A _, le_of_add_le_add_left := @le_of_add_le_add_left A _, mul_le_mul_of_nonneg_left := @ordered_ring.mul_le_mul_of_nonneg_left A _, mul_le_mul_of_nonneg_right := @ordered_ring.mul_le_mul_of_nonneg_right A _, mul_lt_mul_of_pos_left := @ordered_ring.mul_lt_mul_of_pos_left A _, mul_lt_mul_of_pos_right := @ordered_ring.mul_lt_mul_of_pos_right A _, lt_of_add_lt_add_left := @lt_of_add_lt_add_left A _⦄ section variable [s : ordered_ring A] variables {a b c : A} include s theorem mul_le_mul_of_nonpos_left (H : b ≤ a) (Hc : c ≤ 0) : c * a ≤ c * b := have Hc' : -c ≥ 0, from iff.mpr !neg_nonneg_iff_nonpos Hc, assert H1 : -c * b ≤ -c * a, from mul_le_mul_of_nonneg_left H Hc', have H2 : -(c * b) ≤ -(c * a), begin rewrite [-*neg_mul_eq_neg_mul at H1], exact H1 end, iff.mp !neg_le_neg_iff_le H2 theorem mul_le_mul_of_nonpos_right (H : b ≤ a) (Hc : c ≤ 0) : a * c ≤ b * c := have Hc' : -c ≥ 0, from iff.mpr !neg_nonneg_iff_nonpos Hc, assert H1 : b * -c ≤ a * -c, from mul_le_mul_of_nonneg_right H Hc', have H2 : -(b * c) ≤ -(a * c), begin rewrite [-*neg_mul_eq_mul_neg at H1], exact H1 end, iff.mp !neg_le_neg_iff_le H2 theorem mul_nonneg_of_nonpos_of_nonpos (Ha : a ≤ 0) (Hb : b ≤ 0) : 0 ≤ a * b := begin have H : 0 * b ≤ a * b, from mul_le_mul_of_nonpos_right Ha Hb, rewrite zero_mul at H, exact H end theorem mul_lt_mul_of_neg_left (H : b < a) (Hc : c < 0) : c * a < c * b := have Hc' : -c > 0, from iff.mpr !neg_pos_iff_neg Hc, assert H1 : -c * b < -c * a, from mul_lt_mul_of_pos_left H Hc', have H2 : -(c * b) < -(c * a), begin rewrite [-*neg_mul_eq_neg_mul at H1], exact H1 end, iff.mp !neg_lt_neg_iff_lt H2 theorem mul_lt_mul_of_neg_right (H : b < a) (Hc : c < 0) : a * c < b * c := have Hc' : -c > 0, from iff.mpr !neg_pos_iff_neg Hc, assert H1 : b * -c < a * -c, from mul_lt_mul_of_pos_right H Hc', have H2 : -(b * c) < -(a * c), begin rewrite [-*neg_mul_eq_mul_neg at H1], exact H1 end, iff.mp !neg_lt_neg_iff_lt H2 theorem mul_pos_of_neg_of_neg (Ha : a < 0) (Hb : b < 0) : 0 < a * b := begin have H : 0 * b < a * b, from mul_lt_mul_of_neg_right Ha Hb, rewrite zero_mul at H, exact H end end -- TODO: we can eliminate mul_pos_of_pos, but now it is not worth the effort to redeclare the -- class instance structure linear_ordered_ring [class] (A : Type) extends ordered_ring A, linear_strong_order_pair A := (zero_lt_one : lt zero one) definition linear_ordered_ring.to_linear_ordered_semiring [trans_instance] [reducible] [s : linear_ordered_ring A] : linear_ordered_semiring A := ⦃ linear_ordered_semiring, s, mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add.left_cancel A _, add_right_cancel := @add.right_cancel A _, le_of_add_le_add_left := @le_of_add_le_add_left A _, mul_le_mul_of_nonneg_left := @mul_le_mul_of_nonneg_left A _, mul_le_mul_of_nonneg_right := @mul_le_mul_of_nonneg_right A _, mul_lt_mul_of_pos_left := @mul_lt_mul_of_pos_left A _, mul_lt_mul_of_pos_right := @mul_lt_mul_of_pos_right A _, le_total := linear_ordered_ring.le_total, lt_of_add_lt_add_left := @lt_of_add_lt_add_left A _ ⦄ structure linear_ordered_comm_ring [class] (A : Type) extends linear_ordered_ring A, comm_monoid A theorem linear_ordered_comm_ring.eq_zero_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] [reducible] [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 zero_le_one : 0 ≤ (1:A) := one_mul 1 ▸ mul_self_nonneg 1 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 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 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
0fb13e22cc734abc721b5a7b66ebc78f1b81035f
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/data/setoid.lean
f536025b895944e0a38a437e20986e6bc67e92a6
[ "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
856
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 -/ prelude import init.logic universes u class setoid (α : Sort u) := (r : α → α → Prop) (iseqv : equivalence r) @[priority 100] instance setoid_has_equiv {α : Sort u} [setoid α] : has_equiv α := ⟨setoid.r⟩ namespace setoid variables {α : Sort u} [setoid α] @[refl] lemma refl (a : α) : a ≈ a := match setoid.iseqv with | ⟨h_refl, h_symm, h_trans⟩ := h_refl a end @[symm] lemma symm {a b : α} (hab : a ≈ b) : b ≈ a := match setoid.iseqv with | ⟨h_refl, h_symm, h_trans⟩ := h_symm hab end @[trans] lemma trans {a b c : α} (hab : a ≈ b) (hbc : b ≈ c) : a ≈ c := match setoid.iseqv with | ⟨h_refl, h_symm, h_trans⟩ := h_trans hab hbc end end setoid
1888175a9806caaad743e59e5383f2793aebd49e
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/smartUnfoldingMatch.lean
d52f2bb3ffe04f07d82e9552fd5cdad64adc1c1d
[ "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
268
lean
import Lean open Lean Meta Elab Term in elab "whnf%" t:term : term <= expectedType => do let r ← whnf (← elabTerm t expectedType) trace[Meta.debug] "r: {r}" return r constant x : Option Nat := some 42 set_option trace.Meta.debug true #eval whnf% x.getD 0
a087551c2073a983db2dc3d7ae8f1cba048de8e7
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/types_auto.lean
32a112f2d4d2e3189c2e29ee1ebe385473f28547
[]
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,930
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stephen Morgan, Scott Morrison, Johannes Hölzl -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.fully_faithful import Mathlib.data.equiv.basic import Mathlib.PostPort universes u v w u' u_1 u_2 namespace Mathlib /-! # The category `Type`. In this section we set up the theory so that Lean's types and functions between them can be viewed as a `large_category` in our framework. Lean can not transparently view a function as a morphism in this category, and needs a hint in order to be able to type check. We provide the abbreviation `as_hom f` to guide type checking, as well as a corresponding notation `↾ f`. (Entered as `\upr `.) We provide various simplification lemmas for functors and natural transformations valued in `Type`. We define `ulift_functor`, from `Type u` to `Type (max u v)`, and show that it is fully faithful (but not, of course, essentially surjective). We prove some basic facts about the category `Type`: * epimorphisms are surjections and monomorphisms are injections, * `iso` is both `iso` and `equiv` to `equiv` (at least within a fixed universe), * every type level `is_lawful_functor` gives a categorical functor `Type ⥤ Type` (the corresponding fact about monads is in `src/category_theory/monad/types.lean`). -/ namespace category_theory protected instance types : large_category (Type u) := category.mk theorem types_hom {α : Type u} {β : Type u} : (α ⟶ β) = (α → β) := rfl theorem types_id (X : Type u) : 𝟙 = id := rfl theorem types_comp {X : Type u} {Y : Type u} {Z : Type u} (f : X ⟶ Y) (g : Y ⟶ Z) : f ≫ g = g ∘ f := rfl @[simp] theorem types_id_apply (X : Type u) (x : X) : 𝟙 = x := rfl @[simp] theorem types_comp_apply {X : Type u} {Y : Type u} {Z : Type u} (f : X ⟶ Y) (g : Y ⟶ Z) (x : X) : category_struct.comp f g x = g (f x) := rfl @[simp] theorem hom_inv_id_apply {X : Type u} {Y : Type u} (f : X ≅ Y) (x : X) : iso.inv f (iso.hom f x) = x := congr_fun (iso.hom_inv_id f) x @[simp] theorem inv_hom_id_apply {X : Type u} {Y : Type u} (f : X ≅ Y) (y : Y) : iso.hom f (iso.inv f y) = y := congr_fun (iso.inv_hom_id f) y /-- `as_hom f` helps Lean type check a function as a morphism in the category `Type`. -/ -- Unfortunately without this wrapper we can't use `category_theory` idioms, such as `is_iso f`. -- If you don't mind some notation you can use fewer keystrokes: def as_hom {α : Type u} {β : Type u} (f : α → β) : α ⟶ β := f prefix:200 "↾" => Mathlib.category_theory.as_hom namespace functor /-- The sections of a functor `J ⥤ Type` are the choices of a point `u j : F.obj j` for each `j`, such that `F.map f (u j) = u j` for every morphism `f : j ⟶ j'`. We later use these to define limits in `Type` and in many concrete categories. -/ def sections {J : Type u} [category J] (F : J ⥤ Type w) : set ((j : J) → obj F j) := set_of fun (u : (j : J) → obj F j) => ∀ {j j' : J} (f : j ⟶ j'), map F f (u j) = u j' end functor namespace functor_to_types @[simp] theorem map_comp_apply {C : Type u} [category C] (F : C ⥤ Type w) {X : C} {Y : C} {Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) (a : functor.obj F X) : functor.map F (f ≫ g) a = functor.map F g (functor.map F f a) := sorry @[simp] theorem map_id_apply {C : Type u} [category C] (F : C ⥤ Type w) {X : C} (a : functor.obj F X) : functor.map F 𝟙 a = a := sorry theorem naturality {C : Type u} [category C] (F : C ⥤ Type w) (G : C ⥤ Type w) {X : C} {Y : C} (σ : F ⟶ G) (f : X ⟶ Y) (x : functor.obj F X) : nat_trans.app σ Y (functor.map F f x) = functor.map G f (nat_trans.app σ X x) := congr_fun (nat_trans.naturality σ f) x @[simp] theorem comp {C : Type u} [category C] (F : C ⥤ Type w) (G : C ⥤ Type w) (H : C ⥤ Type w) {X : C} (σ : F ⟶ G) (τ : G ⟶ H) (x : functor.obj F X) : nat_trans.app (σ ≫ τ) X x = nat_trans.app τ X (nat_trans.app σ X x) := rfl @[simp] theorem hcomp {C : Type u} [category C] (F : C ⥤ Type w) (G : C ⥤ Type w) (σ : F ⟶ G) {D : Type u'} [𝒟 : category D] (I : D ⥤ C) (J : D ⥤ C) (ρ : I ⟶ J) {W : D} (x : functor.obj (I ⋙ F) W) : nat_trans.app (ρ ◫ σ) W x = functor.map G (nat_trans.app ρ W) (nat_trans.app σ (functor.obj I W) x) := rfl @[simp] theorem map_inv_map_hom_apply {C : Type u} [category C] (F : C ⥤ Type w) {X : C} {Y : C} (f : X ≅ Y) (x : functor.obj F X) : functor.map F (iso.inv f) (functor.map F (iso.hom f) x) = x := congr_fun (iso.hom_inv_id (functor.map_iso F f)) x @[simp] theorem map_hom_map_inv_apply {C : Type u} [category C] (F : C ⥤ Type w) {X : C} {Y : C} (f : X ≅ Y) (y : functor.obj F Y) : functor.map F (iso.hom f) (functor.map F (iso.inv f) y) = y := congr_fun (iso.inv_hom_id (functor.map_iso F f)) y @[simp] theorem hom_inv_id_app_apply {C : Type u} [category C] (F : C ⥤ Type w) (G : C ⥤ Type w) (α : F ≅ G) (X : C) (x : functor.obj F X) : nat_trans.app (iso.inv α) X (nat_trans.app (iso.hom α) X x) = x := congr_fun (iso.hom_inv_id_app α X) x @[simp] theorem inv_hom_id_app_apply {C : Type u} [category C] (F : C ⥤ Type w) (G : C ⥤ Type w) (α : F ≅ G) (X : C) (x : functor.obj G X) : nat_trans.app (iso.hom α) X (nat_trans.app (iso.inv α) X x) = x := congr_fun (iso.inv_hom_id_app α X) x end functor_to_types /-- The isomorphism between a `Type` which has been `ulift`ed to the same universe, and the original type. -/ def ulift_trivial (V : Type u) : ulift V ≅ V := iso.mk (id fun (ᾰ : ulift V) => ulift.cases_on ᾰ fun (ᾰ : V) => ᾰ) ulift.up /-- The functor embedding `Type u` into `Type (max u v)`. Write this as `ulift_functor.{5 2}` to get `Type 2 ⥤ Type 5`. -/ def ulift_functor : Type u ⥤ Type (max u v) := functor.mk (fun (X : Type u) => ulift X) fun (X Y : Type u) (f : X ⟶ Y) (x : ulift X) => ulift.up (f (ulift.down x)) @[simp] theorem ulift_functor_map {X : Type u} {Y : Type u} (f : X ⟶ Y) (x : ulift X) : functor.map ulift_functor f x = ulift.up (f (ulift.down x)) := rfl protected instance ulift_functor_full : full ulift_functor := full.mk fun (X Y : Type u) (f : functor.obj ulift_functor X ⟶ functor.obj ulift_functor Y) (x : X) => ulift.down (f (ulift.up x)) protected instance ulift_functor_faithful : faithful ulift_functor := faithful.mk /-- Any term `x` of a type `X` corresponds to a morphism `punit ⟶ X`. -/ -- TODO We should connect this to a general story about concrete categories -- whose forgetful functor is representable. def hom_of_element {X : Type u} (x : X) : PUnit ⟶ X := fun (_x : PUnit) => x theorem hom_of_element_eq_iff {X : Type u} (x : X) (y : X) : hom_of_element x = hom_of_element y ↔ x = y := sorry /-- A morphism in `Type` is a monomorphism if and only if it is injective. See https://stacks.math.columbia.edu/tag/003C. -/ theorem mono_iff_injective {X : Type u} {Y : Type u} (f : X ⟶ Y) : mono f ↔ function.injective f := sorry /-- A morphism in `Type` is an epimorphism if and only if it is surjective. See https://stacks.math.columbia.edu/tag/003C. -/ theorem epi_iff_surjective {X : Type u} {Y : Type u} (f : X ⟶ Y) : epi f ↔ function.surjective f := sorry /-- `of_type_functor m` converts from Lean's `Type`-based `category` to `category_theory`. This allows us to use these functors in category theory. -/ def of_type_functor (m : Type u → Type v) [Functor m] [is_lawful_functor m] : Type u ⥤ Type v := functor.mk m fun (α β : Type u) => Functor.map @[simp] theorem of_type_functor_obj (m : Type u → Type v) [Functor m] [is_lawful_functor m] : functor.obj (of_type_functor m) = m := rfl @[simp] theorem of_type_functor_map (m : Type u → Type v) [Functor m] [is_lawful_functor m] {α : Type u} {β : Type u} (f : α → β) : functor.map (of_type_functor m) f = Functor.map f := rfl end category_theory -- Isomorphisms in Type and equivalences. namespace equiv /-- Any equivalence between types in the same universe gives a categorical isomorphism between those types. -/ def to_iso {X : Type u} {Y : Type u} (e : X ≃ Y) : X ≅ Y := category_theory.iso.mk (to_fun e) (inv_fun e) @[simp] theorem to_iso_hom {X : Type u} {Y : Type u} {e : X ≃ Y} : category_theory.iso.hom (to_iso e) = ⇑e := rfl @[simp] theorem to_iso_inv {X : Type u} {Y : Type u} {e : X ≃ Y} : category_theory.iso.inv (to_iso e) = ⇑(equiv.symm e) := rfl end equiv namespace category_theory.iso /-- Any isomorphism between types gives an equivalence. -/ def to_equiv {X : Type u} {Y : Type u} (i : X ≅ Y) : X ≃ Y := equiv.mk (hom i) (inv i) sorry sorry @[simp] theorem to_equiv_fun {X : Type u} {Y : Type u} (i : X ≅ Y) : ⇑(to_equiv i) = hom i := rfl @[simp] theorem to_equiv_symm_fun {X : Type u} {Y : Type u} (i : X ≅ Y) : ⇑(equiv.symm (to_equiv i)) = inv i := rfl @[simp] theorem to_equiv_id (X : Type u) : to_equiv (refl X) = equiv.refl X := rfl @[simp] theorem to_equiv_comp {X : Type u} {Y : Type u} {Z : Type u} (f : X ≅ Y) (g : Y ≅ Z) : to_equiv (f ≪≫ g) = equiv.trans (to_equiv f) (to_equiv g) := rfl end category_theory.iso namespace category_theory /-- A morphism in `Type u` is an isomorphism if and only if it is bijective. -/ def is_iso_equiv_bijective {X : Type u} {Y : Type u} (f : X ⟶ Y) : is_iso f ≃ function.bijective f := equiv_of_subsingleton_of_subsingleton sorry fun (b : function.bijective f) => is_iso.mk (iso.inv (equiv.to_iso (equiv.of_bijective f b))) end category_theory -- We prove `equiv_iso_iso` and then use that to sneakily construct `equiv_equiv_iso`. -- (In this order the proofs are handled by `obviously`.) /-- Equivalences (between types in the same universe) are the same as (isomorphic to) isomorphisms of types. -/ @[simp] theorem equiv_iso_iso_hom {X : Type u} {Y : Type u} (e : X ≃ Y) : category_theory.iso.hom equiv_iso_iso e = equiv.to_iso e := Eq.refl (category_theory.iso.hom equiv_iso_iso e) /-- Equivalences (between types in the same universe) are the same as (equivalent to) isomorphisms of types. -/ -- We leave `X` and `Y` as explicit arguments here, because the coercions from `equiv` to a function -- won't fire without them. -- TODO: is it still true? def equiv_equiv_iso (X : Type u) (Y : Type u) : X ≃ Y ≃ (X ≅ Y) := category_theory.iso.to_equiv equiv_iso_iso @[simp] theorem equiv_equiv_iso_hom {X : Type u} {Y : Type u} (e : X ≃ Y) : coe_fn (equiv_equiv_iso X Y) e = equiv.to_iso e := rfl @[simp] theorem equiv_equiv_iso_inv {X : Type u} {Y : Type u} (e : X ≅ Y) : coe_fn (equiv.symm (equiv_equiv_iso X Y)) e = category_theory.iso.to_equiv e := rfl end Mathlib
bd18c20a86390ce937f6a970d13e36bdcb5a8439
7cef822f3b952965621309e88eadf618da0c8ae9
/src/topology/instances/nnreal.lean
17c1487885f7d93645c978d1ddb94ee6cd991e1f
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
4,715
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin Nonnegative real numbers. -/ import data.real.nnreal topology.instances.real topology.algebra.infinite_sum noncomputable theory open set topological_space metric open_locale topological_space namespace nnreal open_locale nnreal instance : topological_space ℝ≥0 := infer_instance -- short-circuit type class inference instance : topological_semiring ℝ≥0 := { continuous_mul := continuous_subtype_mk _ $ (continuous_subtype_val.comp continuous_fst).mul (continuous_subtype_val.comp continuous_snd), continuous_add := continuous_subtype_mk _ $ (continuous_subtype_val.comp continuous_fst).add (continuous_subtype_val.comp continuous_snd) } instance : second_countable_topology nnreal := topological_space.subtype.second_countable_topology _ _ instance : orderable_topology ℝ≥0 := ⟨ le_antisymm (le_generate_from $ assume s hs, match s, hs with | _, ⟨⟨a, ha⟩, or.inl rfl⟩ := ⟨{b : ℝ | a < b}, is_open_lt' a, rfl⟩ | _, ⟨⟨a, ha⟩, or.inr rfl⟩ := ⟨{b : ℝ | b < a}, is_open_gt' a, set.ext $ assume b, iff.rfl⟩ end) begin apply coinduced_le_iff_le_induced.1, rw [orderable_topology.topology_eq_generate_intervals ℝ], apply le_generate_from, assume s hs, rcases hs with ⟨a, rfl | rfl⟩, { show topological_space.generate_open _ {b : ℝ≥0 | a < b }, by_cases ha : 0 ≤ a, { exact topological_space.generate_open.basic _ ⟨⟨a, ha⟩, or.inl rfl⟩ }, { have : a < 0, from lt_of_not_ge ha, have : {b : ℝ≥0 | a < b } = set.univ, from (set.eq_univ_iff_forall.2 $ assume b, lt_of_lt_of_le this b.2), rw [this], exact topological_space.generate_open.univ _ } }, { show (topological_space.generate_from _).is_open {b : ℝ≥0 | a > b }, by_cases ha : 0 ≤ a, { exact topological_space.generate_open.basic _ ⟨⟨a, ha⟩, or.inr rfl⟩ }, { have : {b : ℝ≥0 | a > b } = ∅, from (set.eq_empty_iff_forall_not_mem.2 $ assume b hb, ha $ show 0 ≤ a, from le_trans b.2 (le_of_lt hb)), rw [this], apply @is_open_empty } }, end⟩ section coe variable {α : Type*} open filter lemma continuous_of_real : continuous nnreal.of_real := continuous_subtype_mk _ $ continuous_id.max continuous_const lemma continuous_coe : continuous (coe : nnreal → ℝ) := continuous_subtype_val lemma tendsto_coe {f : filter α} {m : α → nnreal} : ∀{x : nnreal}, tendsto (λa, (m a : ℝ)) f (𝓝 (x : ℝ)) ↔ tendsto m f (𝓝 x) | ⟨r, hr⟩ := by rw [nhds_subtype_eq_comap, tendsto_comap_iff]; refl lemma tendsto_of_real {f : filter α} {m : α → ℝ} {x : ℝ} (h : tendsto m f (𝓝 x)) : tendsto (λa, nnreal.of_real (m a)) f (𝓝 (nnreal.of_real x)) := tendsto.comp (continuous_iff_continuous_at.1 continuous_of_real _) h lemma tendsto.sub {f : filter α} {m n : α → nnreal} {r p : nnreal} (hm : tendsto m f (𝓝 r)) (hn : tendsto n f (𝓝 p)) : tendsto (λa, m a - n a) f (𝓝 (r - p)) := tendsto_of_real $ (tendsto_coe.2 hm).sub (tendsto_coe.2 hn) lemma continuous_sub : continuous (λp:nnreal×nnreal, p.1 - p.2) := continuous_subtype_mk _ $ ((continuous.comp continuous_coe continuous_fst).sub (continuous.comp continuous_coe continuous_snd)).max continuous_const lemma continuous.sub [topological_space α] {f g : α → nnreal} (hf : continuous f) (hg : continuous g) : continuous (λ a, f a - g a) := continuous_sub.comp (hf.prod_mk hg) @[elim_cast] lemma has_sum_coe {f : α → nnreal} {r : nnreal} : has_sum (λa, (f a : ℝ)) (r : ℝ) ↔ has_sum f r := by simp [has_sum, sum_coe.symm, tendsto_coe] @[elim_cast] lemma summable_coe {f : α → nnreal} : summable (λa, (f a : ℝ)) ↔ summable f := begin simp [summable], split, exact assume ⟨a, ha⟩, ⟨⟨a, has_sum_le (λa, (f a).2) has_sum_zero ha⟩, has_sum_coe.1 ha⟩, exact assume ⟨a, ha⟩, ⟨a.1, has_sum_coe.2 ha⟩ end open_locale classical @[move_cast] lemma coe_tsum {f : α → nnreal} : ↑(∑a, f a) = (∑a, (f a : ℝ)) := if hf : summable f then (eq.symm $ tsum_eq_has_sum $ has_sum_coe.2 $ has_sum_tsum $ hf) else by simp [tsum, hf, mt summable_coe.1 hf] lemma summable_comp_injective {β : Type*} {f : α → nnreal} (hf : summable f) {i : β → α} (hi : function.injective i) : summable (f ∘ i) := nnreal.summable_coe.1 $ show summable ((coe ∘ f) ∘ i), from summable_comp_of_summable_of_injective _ (nnreal.summable_coe.2 hf) hi end coe end nnreal
036eb61e425a5148557b8da6a0876e726f2de630
7571914d3f4d9677288f35ab1a53a2ad70a62bd7
/tests/lean/run/cc4.lean
1507178840d416e0626130e26ce3eb65a2c53541
[ "Apache-2.0" ]
permissive
picrin/lean-1
a395fed5287995f09a15a190bb24609919a0727f
b50597228b42a7eaa01bf8cb7a4fb1a98e7a8aab
refs/heads/master
1,610,757,735,162
1,502,008,413,000
1,502,008,413,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
722
lean
open tactic universe variables u axiom app : Π {α : Type u} {n m : nat}, vector α m → vector α n → vector α (m+n) example (n1 n2 n3 : nat) (v1 w1 : vector nat n1) (w1' : vector nat n3) (v2 w2 : vector nat n2) : n1 = n3 → v1 = w1 → w1 == w1' → v2 = w2 → app v1 v2 == app w1' w2 := by cc example (n1 n2 n3 : nat) (v1 w1 : vector nat n1) (w1' : vector nat n3) (v2 w2 : vector nat n2) : n1 == n3 → v1 = w1 → w1 == w1' → v2 == w2 → app v1 v2 == app w1' w2 := by cc example (n1 n2 n3 : nat) (v1 w1 v : vector nat n1) (w1' : vector nat n3) (v2 w2 w : vector nat n2) : n1 == n3 → v1 = w1 → w1 == w1' → v2 == w2 → app w1' w2 == app v w → app v1 v2 = app v w := by cc
43199d5c380ea87b024a3209a255b97a5910cff9
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/complex/basic.lean
fa7527bc84e7d461da94e717162d33c1e6557362
[]
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
21,627
lean
/- Copyright (c) 2017 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.real.sqrt import Mathlib.PostPort universes l u_1 namespace Mathlib /-! # The complex numbers The complex numbers are modelled as ℝ^2 in the obvious way. -/ /-! ### Definition and basic arithmmetic -/ /-- Complex numbers consist of two `real`s: a real part `re` and an imaginary part `im`. -/ structure complex where re : ℝ im : ℝ notation:1024 "ℂ" => Mathlib.complex namespace complex protected instance decidable_eq : DecidableEq ℂ := classical.dec_eq ℂ /-- The equivalence between the complex numbers and `ℝ × ℝ`. -/ def equiv_real_prod : ℂ ≃ ℝ × ℝ := equiv.mk (fun (z : ℂ) => (re z, im z)) (fun (p : ℝ × ℝ) => mk (prod.fst p) (prod.snd p)) sorry sorry @[simp] theorem equiv_real_prod_apply (z : ℂ) : coe_fn equiv_real_prod z = (re z, im z) := rfl theorem equiv_real_prod_symm_re (x : ℝ) (y : ℝ) : re (coe_fn (equiv.symm equiv_real_prod) (x, y)) = x := rfl theorem equiv_real_prod_symm_im (x : ℝ) (y : ℝ) : im (coe_fn (equiv.symm equiv_real_prod) (x, y)) = y := rfl @[simp] theorem eta (z : ℂ) : mk (re z) (im z) = z := cases_on z fun (z_re z_im : ℝ) => idRhs (mk (re (mk z_re z_im)) (im (mk z_re z_im)) = mk (re (mk z_re z_im)) (im (mk z_re z_im))) rfl theorem ext {z : ℂ} {w : ℂ} : re z = re w → im z = im w → z = w := sorry theorem ext_iff {z : ℂ} {w : ℂ} : z = w ↔ re z = re w ∧ im z = im w := sorry protected instance has_coe : has_coe ℝ ℂ := has_coe.mk fun (r : ℝ) => mk r 0 @[simp] theorem of_real_re (r : ℝ) : re ↑r = r := rfl @[simp] theorem of_real_im (r : ℝ) : im ↑r = 0 := rfl @[simp] theorem of_real_inj {z : ℝ} {w : ℝ} : ↑z = ↑w ↔ z = w := { mp := congr_arg re, mpr := congr_arg fun {z : ℝ} => ↑z } protected instance has_zero : HasZero ℂ := { zero := ↑0 } protected instance inhabited : Inhabited ℂ := { default := 0 } @[simp] theorem zero_re : re 0 = 0 := rfl @[simp] theorem zero_im : im 0 = 0 := rfl @[simp] theorem of_real_zero : ↑0 = 0 := rfl @[simp] theorem of_real_eq_zero {z : ℝ} : ↑z = 0 ↔ z = 0 := of_real_inj theorem of_real_ne_zero {z : ℝ} : ↑z ≠ 0 ↔ z ≠ 0 := not_congr of_real_eq_zero protected instance has_one : HasOne ℂ := { one := ↑1 } @[simp] theorem one_re : re 1 = 1 := rfl @[simp] theorem one_im : im 1 = 0 := rfl @[simp] theorem of_real_one : ↑1 = 1 := rfl protected instance has_add : Add ℂ := { add := fun (z w : ℂ) => mk (re z + re w) (im z + im w) } @[simp] theorem add_re (z : ℂ) (w : ℂ) : re (z + w) = re z + re w := rfl @[simp] theorem add_im (z : ℂ) (w : ℂ) : im (z + w) = im z + im w := rfl @[simp] theorem bit0_re (z : ℂ) : re (bit0 z) = bit0 (re z) := rfl @[simp] theorem bit1_re (z : ℂ) : re (bit1 z) = bit1 (re z) := rfl @[simp] theorem bit0_im (z : ℂ) : im (bit0 z) = bit0 (im z) := Eq.refl (im (bit0 z)) @[simp] theorem bit1_im (z : ℂ) : im (bit1 z) = bit0 (im z) := add_zero (im (bit0 z)) @[simp] theorem of_real_add (r : ℝ) (s : ℝ) : ↑(r + s) = ↑r + ↑s := sorry @[simp] theorem of_real_bit0 (r : ℝ) : ↑(bit0 r) = bit0 ↑r := sorry @[simp] theorem of_real_bit1 (r : ℝ) : ↑(bit1 r) = bit1 ↑r := sorry protected instance has_neg : Neg ℂ := { neg := fun (z : ℂ) => mk (-re z) (-im z) } @[simp] theorem neg_re (z : ℂ) : re (-z) = -re z := rfl @[simp] theorem neg_im (z : ℂ) : im (-z) = -im z := rfl @[simp] theorem of_real_neg (r : ℝ) : ↑(-r) = -↑r := sorry protected instance has_sub : Sub ℂ := { sub := fun (z w : ℂ) => mk (re z - re w) (im z - im w) } protected instance has_mul : Mul ℂ := { mul := fun (z w : ℂ) => mk (re z * re w - im z * im w) (re z * im w + im z * re w) } @[simp] theorem mul_re (z : ℂ) (w : ℂ) : re (z * w) = re z * re w - im z * im w := rfl @[simp] theorem mul_im (z : ℂ) (w : ℂ) : im (z * w) = re z * im w + im z * re w := rfl @[simp] theorem of_real_mul (r : ℝ) (s : ℝ) : ↑(r * s) = ↑r * ↑s := sorry theorem smul_re (r : ℝ) (z : ℂ) : re (↑r * z) = r * re z := sorry theorem smul_im (r : ℝ) (z : ℂ) : im (↑r * z) = r * im z := sorry theorem of_real_smul (r : ℝ) (z : ℂ) : ↑r * z = mk (r * re z) (r * im z) := ext (smul_re r z) (smul_im r z) /-! ### The imaginary unit, `I` -/ /-- The imaginary unit. -/ def I : ℂ := mk 0 1 @[simp] theorem I_re : re I = 0 := rfl @[simp] theorem I_im : im I = 1 := rfl @[simp] theorem I_mul_I : I * I = -1 := sorry theorem I_mul (z : ℂ) : I * z = mk (-im z) (re z) := sorry theorem I_ne_zero : I ≠ 0 := mt (congr_arg im) (ne.symm zero_ne_one) theorem mk_eq_add_mul_I (a : ℝ) (b : ℝ) : mk a b = ↑a + ↑b * I := sorry @[simp] theorem re_add_im (z : ℂ) : ↑(re z) + ↑(im z) * I = z := sorry /-! ### Commutative ring instance and lemmas -/ protected instance comm_ring : comm_ring ℂ := comm_ring.mk Add.add sorry 0 sorry sorry Neg.neg Sub.sub sorry sorry Mul.mul sorry 1 sorry sorry sorry sorry sorry protected instance re.is_add_group_hom : is_add_group_hom re := is_add_group_hom.mk protected instance im.is_add_group_hom : is_add_group_hom im := is_add_group_hom.mk @[simp] theorem I_pow_bit0 (n : ℕ) : I ^ bit0 n = (-1) ^ n := eq.mpr (id (Eq._oldrec (Eq.refl (I ^ bit0 n = (-1) ^ n)) (pow_bit0' I n))) (eq.mpr (id (Eq._oldrec (Eq.refl ((I * I) ^ n = (-1) ^ n)) I_mul_I)) (Eq.refl ((-1) ^ n))) @[simp] theorem I_pow_bit1 (n : ℕ) : I ^ bit1 n = (-1) ^ n * I := eq.mpr (id (Eq._oldrec (Eq.refl (I ^ bit1 n = (-1) ^ n * I)) (pow_bit1' I n))) (eq.mpr (id (Eq._oldrec (Eq.refl ((I * I) ^ n * I = (-1) ^ n * I)) I_mul_I)) (Eq.refl ((-1) ^ n * I))) /-! ### Complex conjugation -/ /-- The complex conjugate. -/ def conj : ℂ →+* ℂ := ring_hom.mk (fun (z : ℂ) => mk (re z) (-im z)) sorry sorry sorry sorry @[simp] theorem conj_re (z : ℂ) : re (coe_fn conj z) = re z := rfl @[simp] theorem conj_im (z : ℂ) : im (coe_fn conj z) = -im z := rfl @[simp] theorem conj_of_real (r : ℝ) : coe_fn conj ↑r = ↑r := sorry @[simp] theorem conj_I : coe_fn conj I = -I := sorry @[simp] theorem conj_bit0 (z : ℂ) : coe_fn conj (bit0 z) = bit0 (coe_fn conj z) := sorry @[simp] theorem conj_bit1 (z : ℂ) : coe_fn conj (bit1 z) = bit1 (coe_fn conj z) := sorry @[simp] theorem conj_neg_I : coe_fn conj (-I) = I := sorry @[simp] theorem conj_conj (z : ℂ) : coe_fn conj (coe_fn conj z) = z := sorry theorem conj_involutive : function.involutive ⇑conj := conj_conj theorem conj_bijective : function.bijective ⇑conj := function.involutive.bijective conj_involutive theorem conj_inj {z : ℂ} {w : ℂ} : coe_fn conj z = coe_fn conj w ↔ z = w := function.injective.eq_iff (and.left conj_bijective) @[simp] theorem conj_eq_zero {z : ℂ} : coe_fn conj z = 0 ↔ z = 0 := sorry theorem eq_conj_iff_real {z : ℂ} : coe_fn conj z = z ↔ ∃ (r : ℝ), z = ↑r := sorry theorem eq_conj_iff_re {z : ℂ} : coe_fn conj z = z ↔ ↑(re z) = z := sorry protected instance star_ring : star_ring ℂ := star_ring.mk sorry /-! ### Norm squared -/ /-- The norm squared function. -/ def norm_sq : monoid_with_zero_hom ℂ ℝ := monoid_with_zero_hom.mk (fun (z : ℂ) => re z * re z + im z * im z) sorry sorry sorry theorem norm_sq_apply (z : ℂ) : coe_fn norm_sq z = re z * re z + im z * im z := rfl @[simp] theorem norm_sq_of_real (r : ℝ) : coe_fn norm_sq ↑r = r * r := sorry theorem norm_sq_zero : coe_fn norm_sq 0 = 0 := monoid_with_zero_hom.map_zero norm_sq theorem norm_sq_one : coe_fn norm_sq 1 = 1 := monoid_with_zero_hom.map_one norm_sq @[simp] theorem norm_sq_I : coe_fn norm_sq I = 1 := sorry theorem norm_sq_nonneg (z : ℂ) : 0 ≤ coe_fn norm_sq z := add_nonneg (mul_self_nonneg (re z)) (mul_self_nonneg (im z)) theorem norm_sq_eq_zero {z : ℂ} : coe_fn norm_sq z = 0 ↔ z = 0 := sorry @[simp] theorem norm_sq_pos {z : ℂ} : 0 < coe_fn norm_sq z ↔ z ≠ 0 := iff.trans (has_le.le.lt_iff_ne (norm_sq_nonneg z)) (not_congr (iff.trans eq_comm norm_sq_eq_zero)) @[simp] theorem norm_sq_neg (z : ℂ) : coe_fn norm_sq (-z) = coe_fn norm_sq z := sorry @[simp] theorem norm_sq_conj (z : ℂ) : coe_fn norm_sq (coe_fn conj z) = coe_fn norm_sq z := sorry theorem norm_sq_mul (z : ℂ) (w : ℂ) : coe_fn norm_sq (z * w) = coe_fn norm_sq z * coe_fn norm_sq w := monoid_with_zero_hom.map_mul norm_sq z w theorem norm_sq_add (z : ℂ) (w : ℂ) : coe_fn norm_sq (z + w) = coe_fn norm_sq z + coe_fn norm_sq w + bit0 1 * re (z * coe_fn conj w) := sorry theorem re_sq_le_norm_sq (z : ℂ) : re z * re z ≤ coe_fn norm_sq z := le_add_of_nonneg_right (mul_self_nonneg (im z)) theorem im_sq_le_norm_sq (z : ℂ) : im z * im z ≤ coe_fn norm_sq z := le_add_of_nonneg_left (mul_self_nonneg (re z)) theorem mul_conj (z : ℂ) : z * coe_fn conj z = ↑(coe_fn norm_sq z) := sorry theorem add_conj (z : ℂ) : z + coe_fn conj z = ↑(bit0 1 * re z) := sorry /-- The coercion `ℝ → ℂ` as a `ring_hom`. -/ def of_real : ℝ →+* ℂ := ring_hom.mk coe of_real_one of_real_mul of_real_zero of_real_add @[simp] theorem of_real_eq_coe (r : ℝ) : coe_fn of_real r = ↑r := rfl @[simp] theorem I_sq : I ^ bit0 1 = -1 := eq.mpr (id (Eq._oldrec (Eq.refl (I ^ bit0 1 = -1)) (pow_two I))) (eq.mpr (id (Eq._oldrec (Eq.refl (I * I = -1)) I_mul_I)) (Eq.refl (-1))) @[simp] theorem sub_re (z : ℂ) (w : ℂ) : re (z - w) = re z - re w := rfl @[simp] theorem sub_im (z : ℂ) (w : ℂ) : im (z - w) = im z - im w := rfl @[simp] theorem of_real_sub (r : ℝ) (s : ℝ) : ↑(r - s) = ↑r - ↑s := sorry @[simp] theorem of_real_pow (r : ℝ) (n : ℕ) : ↑(r ^ n) = ↑r ^ n := sorry theorem sub_conj (z : ℂ) : z - coe_fn conj z = ↑(bit0 1 * im z) * I := sorry theorem norm_sq_sub (z : ℂ) (w : ℂ) : coe_fn norm_sq (z - w) = coe_fn norm_sq z + coe_fn norm_sq w - bit0 1 * re (z * coe_fn conj w) := sorry /-! ### Inversion -/ protected instance has_inv : has_inv ℂ := has_inv.mk fun (z : ℂ) => coe_fn conj z * ↑(coe_fn norm_sq z⁻¹) theorem inv_def (z : ℂ) : z⁻¹ = coe_fn conj z * ↑(coe_fn norm_sq z⁻¹) := rfl @[simp] theorem inv_re (z : ℂ) : re (z⁻¹) = re z / coe_fn norm_sq z := sorry @[simp] theorem inv_im (z : ℂ) : im (z⁻¹) = -im z / coe_fn norm_sq z := sorry @[simp] theorem of_real_inv (r : ℝ) : ↑(r⁻¹) = (↑r⁻¹) := sorry protected theorem inv_zero : 0⁻¹ = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (0⁻¹ = 0)) (Eq.symm of_real_zero))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑0⁻¹ = ↑0)) (Eq.symm (of_real_inv 0)))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑(0⁻¹) = ↑0)) inv_zero)) (Eq.refl ↑0))) protected theorem mul_inv_cancel {z : ℂ} (h : z ≠ 0) : z * (z⁻¹) = 1 := sorry /-! ### Field instance and lemmas -/ protected instance field : field ℂ := field.mk comm_ring.add comm_ring.add_assoc comm_ring.zero comm_ring.zero_add comm_ring.add_zero comm_ring.neg comm_ring.sub comm_ring.add_left_neg comm_ring.add_comm comm_ring.mul comm_ring.mul_assoc comm_ring.one comm_ring.one_mul comm_ring.mul_one comm_ring.left_distrib comm_ring.right_distrib comm_ring.mul_comm has_inv.inv sorry complex.mul_inv_cancel complex.inv_zero @[simp] theorem I_fpow_bit0 (n : ℤ) : I ^ bit0 n = (-1) ^ n := eq.mpr (id (Eq._oldrec (Eq.refl (I ^ bit0 n = (-1) ^ n)) (fpow_bit0' I n))) (eq.mpr (id (Eq._oldrec (Eq.refl ((I * I) ^ n = (-1) ^ n)) I_mul_I)) (Eq.refl ((-1) ^ n))) @[simp] theorem I_fpow_bit1 (n : ℤ) : I ^ bit1 n = (-1) ^ n * I := eq.mpr (id (Eq._oldrec (Eq.refl (I ^ bit1 n = (-1) ^ n * I)) (fpow_bit1' I n))) (eq.mpr (id (Eq._oldrec (Eq.refl ((I * I) ^ n * I = (-1) ^ n * I)) I_mul_I)) (Eq.refl ((-1) ^ n * I))) theorem div_re (z : ℂ) (w : ℂ) : re (z / w) = re z * re w / coe_fn norm_sq w + im z * im w / coe_fn norm_sq w := sorry theorem div_im (z : ℂ) (w : ℂ) : im (z / w) = im z * re w / coe_fn norm_sq w - re z * im w / coe_fn norm_sq w := sorry @[simp] theorem of_real_div (r : ℝ) (s : ℝ) : ↑(r / s) = ↑r / ↑s := ring_hom.map_div of_real r s @[simp] theorem of_real_fpow (r : ℝ) (n : ℤ) : ↑(r ^ n) = ↑r ^ n := ring_hom.map_fpow of_real r n @[simp] theorem div_I (z : ℂ) : z / I = -(z * I) := sorry @[simp] theorem inv_I : I⁻¹ = -I := sorry @[simp] theorem norm_sq_inv (z : ℂ) : coe_fn norm_sq (z⁻¹) = (coe_fn norm_sq z⁻¹) := monoid_with_zero_hom.map_inv' norm_sq z @[simp] theorem norm_sq_div (z : ℂ) (w : ℂ) : coe_fn norm_sq (z / w) = coe_fn norm_sq z / coe_fn norm_sq w := monoid_with_zero_hom.map_div norm_sq z w /-! ### Cast lemmas -/ @[simp] theorem of_real_nat_cast (n : ℕ) : ↑↑n = ↑n := ring_hom.map_nat_cast of_real n @[simp] theorem nat_cast_re (n : ℕ) : re ↑n = ↑n := eq.mpr (id (Eq._oldrec (Eq.refl (re ↑n = ↑n)) (Eq.symm (of_real_nat_cast n)))) (eq.mpr (id (Eq._oldrec (Eq.refl (re ↑↑n = ↑n)) (of_real_re ↑n))) (Eq.refl ↑n)) @[simp] theorem nat_cast_im (n : ℕ) : im ↑n = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (im ↑n = 0)) (Eq.symm (of_real_nat_cast n)))) (eq.mpr (id (Eq._oldrec (Eq.refl (im ↑↑n = 0)) (of_real_im ↑n))) (Eq.refl 0)) @[simp] theorem of_real_int_cast (n : ℤ) : ↑↑n = ↑n := ring_hom.map_int_cast of_real n @[simp] theorem int_cast_re (n : ℤ) : re ↑n = ↑n := eq.mpr (id (Eq._oldrec (Eq.refl (re ↑n = ↑n)) (Eq.symm (of_real_int_cast n)))) (eq.mpr (id (Eq._oldrec (Eq.refl (re ↑↑n = ↑n)) (of_real_re ↑n))) (Eq.refl ↑n)) @[simp] theorem int_cast_im (n : ℤ) : im ↑n = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (im ↑n = 0)) (Eq.symm (of_real_int_cast n)))) (eq.mpr (id (Eq._oldrec (Eq.refl (im ↑↑n = 0)) (of_real_im ↑n))) (Eq.refl 0)) @[simp] theorem of_real_rat_cast (n : ℚ) : ↑↑n = ↑n := ring_hom.map_rat_cast of_real n @[simp] theorem rat_cast_re (q : ℚ) : re ↑q = ↑q := eq.mpr (id (Eq._oldrec (Eq.refl (re ↑q = ↑q)) (Eq.symm (of_real_rat_cast q)))) (eq.mpr (id (Eq._oldrec (Eq.refl (re ↑↑q = ↑q)) (of_real_re ↑q))) (Eq.refl ↑q)) @[simp] theorem rat_cast_im (q : ℚ) : im ↑q = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (im ↑q = 0)) (Eq.symm (of_real_rat_cast q)))) (eq.mpr (id (Eq._oldrec (Eq.refl (im ↑↑q = 0)) (of_real_im ↑q))) (Eq.refl 0)) /-! ### Characteristic zero -/ protected instance char_zero_complex : char_zero ℂ := char_zero_of_inj_zero fun (n : ℕ) (h : ↑n = 0) => eq.mp (Eq._oldrec (Eq.refl (↑n = 0)) (propext nat.cast_eq_zero)) (eq.mp (Eq._oldrec (Eq.refl (↑↑n = 0)) (propext of_real_eq_zero)) (eq.mp (Eq._oldrec (Eq.refl (↑n = 0)) (Eq.symm (of_real_nat_cast n))) h)) /-- A complex number `z` plus its conjugate `conj z` is `2` times its real part. -/ theorem re_eq_add_conj (z : ℂ) : ↑(re z) = (z + coe_fn conj z) / bit0 1 := sorry /-- A complex number `z` minus its conjugate `conj z` is `2i` times its imaginary part. -/ theorem im_eq_sub_conj (z : ℂ) : ↑(im z) = (z - coe_fn conj z) / (bit0 1 * I) := sorry /-! ### Absolute value -/ /-- The complex absolute value function, defined as the square root of the norm squared. -/ def abs (z : ℂ) : ℝ := real.sqrt (coe_fn norm_sq z) @[simp] theorem abs_of_real (r : ℝ) : abs ↑r = abs r := sorry theorem abs_of_nonneg {r : ℝ} (h : 0 ≤ r) : abs ↑r = r := Eq.trans (abs_of_real r) (abs_of_nonneg h) theorem abs_of_nat (n : ℕ) : abs ↑n = ↑n := Eq.trans (eq.mpr (id (Eq._oldrec (Eq.refl (abs ↑n = abs ↑↑n)) (of_real_nat_cast n))) (Eq.refl (abs ↑n))) (abs_of_nonneg (nat.cast_nonneg n)) theorem mul_self_abs (z : ℂ) : abs z * abs z = coe_fn norm_sq z := real.mul_self_sqrt (norm_sq_nonneg z) @[simp] theorem abs_zero : abs 0 = 0 := sorry @[simp] theorem abs_one : abs 1 = 1 := sorry @[simp] theorem abs_I : abs I = 1 := sorry @[simp] theorem abs_two : abs (bit0 1) = bit0 1 := sorry theorem abs_nonneg (z : ℂ) : 0 ≤ abs z := real.sqrt_nonneg (coe_fn norm_sq z) @[simp] theorem abs_eq_zero {z : ℂ} : abs z = 0 ↔ z = 0 := iff.trans (real.sqrt_eq_zero (norm_sq_nonneg z)) norm_sq_eq_zero theorem abs_ne_zero {z : ℂ} : abs z ≠ 0 ↔ z ≠ 0 := not_congr abs_eq_zero @[simp] theorem abs_conj (z : ℂ) : abs (coe_fn conj z) = abs z := sorry @[simp] theorem abs_mul (z : ℂ) (w : ℂ) : abs (z * w) = abs z * abs w := sorry theorem abs_re_le_abs (z : ℂ) : abs (re z) ≤ abs z := sorry theorem abs_im_le_abs (z : ℂ) : abs (im z) ≤ abs z := sorry theorem re_le_abs (z : ℂ) : re z ≤ abs z := and.right (iff.mp abs_le (abs_re_le_abs z)) theorem im_le_abs (z : ℂ) : im z ≤ abs z := and.right (iff.mp abs_le (abs_im_le_abs z)) theorem abs_add (z : ℂ) (w : ℂ) : abs (z + w) ≤ abs z + abs w := sorry protected instance abs.is_absolute_value : is_absolute_value abs := is_absolute_value.mk abs_nonneg (fun (_x : ℂ) => abs_eq_zero) abs_add abs_mul @[simp] theorem abs_abs (z : ℂ) : abs (abs z) = abs z := abs_of_nonneg (abs_nonneg z) @[simp] theorem abs_pos {z : ℂ} : 0 < abs z ↔ z ≠ 0 := is_absolute_value.abv_pos abs @[simp] theorem abs_neg (z : ℂ) : abs (-z) = abs z := is_absolute_value.abv_neg abs theorem abs_sub (z : ℂ) (w : ℂ) : abs (z - w) = abs (w - z) := is_absolute_value.abv_sub abs theorem abs_sub_le (a : ℂ) (b : ℂ) (c : ℂ) : abs (a - c) ≤ abs (a - b) + abs (b - c) := is_absolute_value.abv_sub_le abs @[simp] theorem abs_inv (z : ℂ) : abs (z⁻¹) = (abs z⁻¹) := is_absolute_value.abv_inv abs @[simp] theorem abs_div (z : ℂ) (w : ℂ) : abs (z / w) = abs z / abs w := is_absolute_value.abv_div abs theorem abs_abs_sub_le_abs_sub (z : ℂ) (w : ℂ) : abs (abs z - abs w) ≤ abs (z - w) := is_absolute_value.abs_abv_sub_le_abv_sub abs theorem abs_le_abs_re_add_abs_im (z : ℂ) : abs z ≤ abs (re z) + abs (im z) := sorry theorem abs_re_div_abs_le_one (z : ℂ) : abs (re z / abs z) ≤ 1 := sorry theorem abs_im_div_abs_le_one (z : ℂ) : abs (im z / abs z) ≤ 1 := sorry @[simp] theorem abs_cast_nat (n : ℕ) : abs ↑n = ↑n := eq.mpr (id (Eq._oldrec (Eq.refl (abs ↑n = ↑n)) (Eq.symm (of_real_nat_cast n)))) (eq.mpr (id (Eq._oldrec (Eq.refl (abs ↑↑n = ↑n)) (abs_of_nonneg (nat.cast_nonneg n)))) (Eq.refl ↑n)) @[simp] theorem int_cast_abs (n : ℤ) : ↑(abs n) = abs ↑n := eq.mpr (id (Eq._oldrec (Eq.refl (↑(abs n) = abs ↑n)) (Eq.symm (of_real_int_cast n)))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑(abs n) = abs ↑↑n)) (abs_of_real ↑n))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑(abs n) = abs ↑n)) int.cast_abs)) (Eq.refl (abs ↑n)))) theorem norm_sq_eq_abs (x : ℂ) : coe_fn norm_sq x = abs x ^ bit0 1 := sorry /-! ### Cauchy sequences -/ theorem is_cau_seq_re (f : cau_seq ℂ abs) : is_cau_seq abs fun (n : ℕ) => re (coe_fn f n) := sorry theorem is_cau_seq_im (f : cau_seq ℂ abs) : is_cau_seq abs fun (n : ℕ) => im (coe_fn f n) := sorry /-- The real part of a complex Cauchy sequence, as a real Cauchy sequence. -/ def cau_seq_re (f : cau_seq ℂ abs) : cau_seq ℝ abs := { val := fun (n : ℕ) => re (coe_fn f n), property := is_cau_seq_re f } /-- The imaginary part of a complex Cauchy sequence, as a real Cauchy sequence. -/ def cau_seq_im (f : cau_seq ℂ abs) : cau_seq ℝ abs := { val := fun (n : ℕ) => im (coe_fn f n), property := is_cau_seq_im f } theorem is_cau_seq_abs {f : ℕ → ℂ} (hf : is_cau_seq abs f) : is_cau_seq abs (abs ∘ f) := sorry /-- The limit of a Cauchy sequence of complex numbers. -/ def lim_aux (f : cau_seq ℂ abs) : ℂ := mk (cau_seq.lim (cau_seq_re f)) (cau_seq.lim (cau_seq_im f)) theorem equiv_lim_aux (f : cau_seq ℂ abs) : f ≈ cau_seq.const abs (lim_aux f) := sorry protected instance abs.cau_seq.is_complete : cau_seq.is_complete ℂ abs := cau_seq.is_complete.mk sorry theorem lim_eq_lim_im_add_lim_re (f : cau_seq ℂ abs) : cau_seq.lim f = ↑(cau_seq.lim (cau_seq_re f)) + ↑(cau_seq.lim (cau_seq_im f)) * I := sorry theorem lim_re (f : cau_seq ℂ abs) : cau_seq.lim (cau_seq_re f) = re (cau_seq.lim f) := sorry theorem lim_im (f : cau_seq ℂ abs) : cau_seq.lim (cau_seq_im f) = im (cau_seq.lim f) := sorry theorem is_cau_seq_conj (f : cau_seq ℂ abs) : is_cau_seq abs fun (n : ℕ) => coe_fn conj (coe_fn f n) := sorry /-- The complex conjugate of a complex Cauchy sequence, as a complex Cauchy sequence. -/ def cau_seq_conj (f : cau_seq ℂ abs) : cau_seq ℂ abs := { val := fun (n : ℕ) => coe_fn conj (coe_fn f n), property := is_cau_seq_conj f } theorem lim_conj (f : cau_seq ℂ abs) : cau_seq.lim (cau_seq_conj f) = coe_fn conj (cau_seq.lim f) := sorry /-- The absolute value of a complex Cauchy sequence, as a real Cauchy sequence. -/ def cau_seq_abs (f : cau_seq ℂ abs) : cau_seq ℝ abs := { val := abs ∘ subtype.val f, property := sorry } theorem lim_abs (f : cau_seq ℂ abs) : cau_seq.lim (cau_seq_abs f) = abs (cau_seq.lim f) := sorry @[simp] theorem of_real_prod {α : Type u_1} (s : finset α) (f : α → ℝ) : ↑(finset.prod s fun (i : α) => f i) = finset.prod s fun (i : α) => ↑(f i) := ring_hom.map_prod of_real (fun (x : α) => f x) s @[simp] theorem of_real_sum {α : Type u_1} (s : finset α) (f : α → ℝ) : ↑(finset.sum s fun (i : α) => f i) = finset.sum s fun (i : α) => ↑(f i) := ring_hom.map_sum of_real (fun (x : α) => f x) s
b97bdad464c510832f97a12bf9a6602b6cd59e75
626e312b5c1cb2d88fca108f5933076012633192
/src/algebra/pointwise.lean
e19543b048d53c89f5dbae4ea8733adebe9d910f
[ "Apache-2.0" ]
permissive
Bioye97/mathlib
9db2f9ee54418d29dd06996279ba9dc874fd6beb
782a20a27ee83b523f801ff34efb1a9557085019
refs/heads/master
1,690,305,956,488
1,631,067,774,000
1,631,067,774,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
31,610
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Floris van Doorn -/ import algebra.module.basic import data.set.finite import group_theory.submonoid.basic /-! # Pointwise addition, multiplication, and scalar multiplication of sets. This file defines pointwise algebraic operations on sets. * For a type `α` with multiplication, multiplication is defined on `set α` by taking `s * t` to be the set of all `x * y` where `x ∈ s` and `y ∈ t`. Similarly for addition. * For `α` a semigroup, `set α` is a semigroup. * If `α` is a (commutative) monoid, we define an alias `set_semiring α` for `set α`, which then becomes a (commutative) semiring with union as addition and pointwise multiplication as multiplication. * For a type `β` with scalar multiplication by another type `α`, this file defines a scalar multiplication of `set β` by `set α` and a separate scalar multiplication of `set β` by `α`. * We also define pointwise multiplication on `finset`. Appropriate definitions and results are also transported to the additive theory via `to_additive`. ## Implementation notes * The following expressions are considered in simp-normal form in a group: `(λ h, h * g) ⁻¹' s`, `(λ h, g * h) ⁻¹' s`, `(λ h, h * g⁻¹) ⁻¹' s`, `(λ h, g⁻¹ * h) ⁻¹' s`, `s * t`, `s⁻¹`, `(1 : set _)` (and similarly for additive variants). Expressions equal to one of these will be simplified. * We put all instances in the locale `pointwise`, so that these instances are not available by default. Note that we do not mark them as reducible (as argued by note [reducible non-instances]) since we expect the locale to be open whenever the instances are actually used (and making the instances reducible changes the behavior of `simp`). ## Tags set multiplication, set addition, pointwise addition, pointwise multiplication -/ namespace set open function variables {α : Type*} {β : Type*} {s s₁ s₂ t t₁ t₂ u : set α} {a b : α} {x y : β} /-! ### Properties about 1 -/ /-- The set `(1 : set α)` is defined as `{1}` in locale `pointwise`. -/ @[to_additive /-"The set `(0 : set α)` is defined as `{0}` in locale `pointwise`. "-/] protected def has_one [has_one α] : has_one (set α) := ⟨{1}⟩ localized "attribute [instance] set.has_one set.has_zero" in pointwise @[to_additive] lemma singleton_one [has_one α] : ({1} : set α) = 1 := rfl @[simp, to_additive] lemma mem_one [has_one α] : a ∈ (1 : set α) ↔ a = 1 := iff.rfl @[to_additive] lemma one_mem_one [has_one α] : (1 : α) ∈ (1 : set α) := eq.refl _ @[simp, to_additive] theorem one_subset [has_one α] : 1 ⊆ s ↔ (1 : α) ∈ s := singleton_subset_iff @[to_additive] theorem one_nonempty [has_one α] : (1 : set α).nonempty := ⟨1, rfl⟩ @[simp, to_additive] theorem image_one [has_one α] {f : α → β} : f '' 1 = {f 1} := image_singleton /-! ### Properties about multiplication -/ /-- The set `(s * t : set α)` is defined as `{x * y | x ∈ s, y ∈ t}` in locale `pointwise`. -/ @[to_additive /-" The set `(s + t : set α)` is defined as `{x + y | x ∈ s, y ∈ t}` in locale `pointwise`."-/] protected def has_mul [has_mul α] : has_mul (set α) := ⟨image2 has_mul.mul⟩ localized "attribute [instance] set.has_mul set.has_add" in pointwise @[simp, to_additive] lemma image2_mul [has_mul α] : image2 has_mul.mul s t = s * t := rfl @[to_additive] lemma mem_mul [has_mul α] : a ∈ s * t ↔ ∃ x y, x ∈ s ∧ y ∈ t ∧ x * y = a := iff.rfl @[to_additive] lemma mul_mem_mul [has_mul α] (ha : a ∈ s) (hb : b ∈ t) : a * b ∈ s * t := mem_image2_of_mem ha hb @[to_additive add_image_prod] lemma image_mul_prod [has_mul α] : (λ x : α × α, x.fst * x.snd) '' s.prod t = s * t := image_prod _ @[simp, to_additive] lemma image_mul_left [group α] : (λ b, a * b) '' t = (λ b, a⁻¹ * b) ⁻¹' t := by { rw image_eq_preimage_of_inverse; intro c; simp } @[simp, to_additive] lemma image_mul_right [group α] : (λ a, a * b) '' t = (λ a, a * b⁻¹) ⁻¹' t := by { rw image_eq_preimage_of_inverse; intro c; simp } @[to_additive] lemma image_mul_left' [group α] : (λ b, a⁻¹ * b) '' t = (λ b, a * b) ⁻¹' t := by simp @[to_additive] lemma image_mul_right' [group α] : (λ a, a * b⁻¹) '' t = (λ a, a * b) ⁻¹' t := by simp @[simp, to_additive] lemma preimage_mul_left_singleton [group α] : ((*) a) ⁻¹' {b} = {a⁻¹ * b} := by rw [← image_mul_left', image_singleton] @[simp, to_additive] lemma preimage_mul_right_singleton [group α] : (* a) ⁻¹' {b} = {b * a⁻¹} := by rw [← image_mul_right', image_singleton] @[simp, to_additive] lemma preimage_mul_left_one [group α] : (λ b, a * b) ⁻¹' 1 = {a⁻¹} := by rw [← image_mul_left', image_one, mul_one] @[simp, to_additive] lemma preimage_mul_right_one [group α] : (λ a, a * b) ⁻¹' 1 = {b⁻¹} := by rw [← image_mul_right', image_one, one_mul] @[to_additive] lemma preimage_mul_left_one' [group α] : (λ b, a⁻¹ * b) ⁻¹' 1 = {a} := by simp @[to_additive] lemma preimage_mul_right_one' [group α] : (λ a, a * b⁻¹) ⁻¹' 1 = {b} := by simp @[simp, to_additive] lemma mul_singleton [has_mul α] : s * {b} = (λ a, a * b) '' s := image2_singleton_right @[simp, to_additive] lemma singleton_mul [has_mul α] : {a} * t = (λ b, a * b) '' t := image2_singleton_left @[simp, to_additive] lemma singleton_mul_singleton [has_mul α] : ({a} : set α) * {b} = {a * b} := image2_singleton @[to_additive] protected lemma mul_comm [comm_semigroup α] : s * t = t * s := by simp only [← image2_mul, image2_swap _ s, mul_comm] /-- `set α` is a `mul_one_class` under pointwise operations if `α` is. -/ @[to_additive /-"`set α` is an `add_zero_class` under pointwise operations if `α` is."-/] protected def mul_one_class [mul_one_class α] : mul_one_class (set α) := { mul_one := λ s, by { simp only [← singleton_one, mul_singleton, mul_one, image_id'] }, one_mul := λ s, by { simp only [← singleton_one, singleton_mul, one_mul, image_id'] }, ..set.has_one, ..set.has_mul } /-- `set α` is a `semigroup` under pointwise operations if `α` is. -/ @[to_additive /-"`set α` is an `add_semigroup` under pointwise operations if `α` is. "-/] protected def semigroup [semigroup α] : semigroup (set α) := { mul_assoc := λ _ _ _, image2_assoc mul_assoc, ..set.has_mul } /-- `set α` is a `monoid` under pointwise operations if `α` is. -/ @[to_additive /-"`set α` is an `add_monoid` under pointwise operations if `α` is. "-/] protected def monoid [monoid α] : monoid (set α) := { ..set.semigroup, ..set.mul_one_class } /-- `set α` is a `comm_monoid` under pointwise operations if `α` is. -/ @[to_additive /-"`set α` is an `add_comm_monoid` under pointwise operations if `α` is. "-/] protected def comm_monoid [comm_monoid α] : comm_monoid (set α) := { mul_comm := λ _ _, set.mul_comm, ..set.monoid } localized "attribute [instance] set.mul_one_class set.add_zero_class set.semigroup set.add_semigroup set.monoid set.add_monoid set.comm_monoid set.add_comm_monoid" in pointwise lemma pow_mem_pow [monoid α] (ha : a ∈ s) (n : ℕ) : a ^ n ∈ s ^ n := begin induction n with n ih, { rw pow_zero, exact set.mem_singleton 1 }, { rw pow_succ, exact set.mul_mem_mul ha ih }, end /-- Under `[has_mul M]`, the `singleton` map from `M` to `set M` as a `mul_hom`, that is, a map which preserves multiplication. -/ @[to_additive "Under `[has_add A]`, the `singleton` map from `A` to `set A` as an `add_hom`, that is, a map which preserves addition.", simps] def singleton_mul_hom [has_mul α] : mul_hom α (set α) := { to_fun := singleton, map_mul' := λ a b, singleton_mul_singleton.symm } @[simp, to_additive] lemma empty_mul [has_mul α] : ∅ * s = ∅ := image2_empty_left @[simp, to_additive] lemma mul_empty [has_mul α] : s * ∅ = ∅ := image2_empty_right lemma empty_pow [monoid α] (n : ℕ) (hn : n ≠ 0) : (∅ : set α) ^ n = ∅ := by rw [←nat.sub_add_cancel (nat.pos_of_ne_zero hn), pow_succ, empty_mul] instance decidable_mem_mul [monoid α] [fintype α] [decidable_eq α] [decidable_pred (∈ s)] [decidable_pred (∈ t)] : decidable_pred (∈ s * t) := λ _, decidable_of_iff _ mem_mul.symm instance decidable_mem_pow [monoid α] [fintype α] [decidable_eq α] [decidable_pred (∈ s)] (n : ℕ) : decidable_pred (∈ (s ^ n)) := begin induction n with n ih, { simp_rw [pow_zero, mem_one], apply_instance }, { letI := ih, rw pow_succ, apply_instance } end @[to_additive] lemma mul_subset_mul [has_mul α] (h₁ : s₁ ⊆ t₁) (h₂ : s₂ ⊆ t₂) : s₁ * s₂ ⊆ t₁ * t₂ := image2_subset h₁ h₂ lemma pow_subset_pow [monoid α] (hst : s ⊆ t) (n : ℕ) : s ^ n ⊆ t ^ n := begin induction n with n ih, { rw pow_zero, exact subset.rfl }, { rw [pow_succ, pow_succ], exact mul_subset_mul hst ih }, end @[to_additive] lemma union_mul [has_mul α] : (s ∪ t) * u = (s * u) ∪ (t * u) := image2_union_left @[to_additive] lemma mul_union [has_mul α] : s * (t ∪ u) = (s * t) ∪ (s * u) := image2_union_right @[to_additive] lemma Union_mul_left_image [has_mul α] : (⋃ a ∈ s, (λ x, a * x) '' t) = s * t := Union_image_left _ @[to_additive] lemma Union_mul_right_image [has_mul α] : (⋃ a ∈ t, (λ x, x * a) '' s) = s * t := Union_image_right _ @[to_additive] lemma Union_mul {ι : Sort*} [has_mul α] (s : ι → set α) (t : set α) : (⋃ i, s i) * t = ⋃ i, (s i * t) := image2_Union_left _ _ _ @[to_additive] lemma mul_Union {ι : Sort*} [has_mul α] (t : set α) (s : ι → set α) : t * (⋃ i, s i) = ⋃ i, (t * s i) := image2_Union_right _ _ _ @[simp, to_additive] lemma univ_mul_univ [monoid α] : (univ : set α) * univ = univ := begin have : ∀x, ∃a b : α, a * b = x := λx, ⟨x, ⟨1, mul_one x⟩⟩, simpa only [mem_mul, eq_univ_iff_forall, mem_univ, true_and] end /-- `singleton` is a monoid hom. -/ @[to_additive singleton_add_hom "singleton is an add monoid hom"] def singleton_hom [monoid α] : α →* set α := { to_fun := singleton, map_one' := rfl, map_mul' := λ a b, singleton_mul_singleton.symm } @[to_additive] lemma nonempty.mul [has_mul α] : s.nonempty → t.nonempty → (s * t).nonempty := nonempty.image2 @[to_additive] lemma finite.mul [has_mul α] (hs : finite s) (ht : finite t) : finite (s * t) := hs.image2 _ ht /-- multiplication preserves finiteness -/ @[to_additive "addition preserves finiteness"] def fintype_mul [has_mul α] [decidable_eq α] (s t : set α) [hs : fintype s] [ht : fintype t] : fintype (s * t : set α) := set.fintype_image2 _ s t @[to_additive] lemma bdd_above_mul [ordered_comm_monoid α] {A B : set α} : bdd_above A → bdd_above B → bdd_above (A * B) := begin rintros ⟨bA, hbA⟩ ⟨bB, hbB⟩, use bA * bB, rintros x ⟨xa, xb, hxa, hxb, rfl⟩, exact mul_le_mul' (hbA hxa) (hbB hxb), end section big_operators open_locale big_operators variables {ι : Type*} [comm_monoid α] /-- The n-ary version of `set.mem_mul`. -/ @[to_additive /-" The n-ary version of `set.mem_add`. "-/] lemma mem_finset_prod (t : finset ι) (f : ι → set α) (a : α) : a ∈ ∏ i in t, f i ↔ ∃ (g : ι → α) (hg : ∀ {i}, i ∈ t → g i ∈ f i), ∏ i in t, g i = a := begin classical, induction t using finset.induction_on with i is hi ih generalizing a, { simp_rw [finset.prod_empty, set.mem_one], exact ⟨λ h, ⟨λ i, a, λ i, false.elim, h.symm⟩, λ ⟨f, _, hf⟩, hf.symm⟩ }, rw [finset.prod_insert hi, set.mem_mul], simp_rw [finset.prod_insert hi], simp_rw ih, split, { rintros ⟨x, y, hx, ⟨g, hg, rfl⟩, rfl⟩, refine ⟨function.update g i x, λ j hj, _, _⟩, obtain rfl | hj := finset.mem_insert.mp hj, { rw function.update_same, exact hx }, { rw update_noteq (ne_of_mem_of_not_mem hj hi), exact hg hj, }, rw [finset.prod_update_of_not_mem hi, function.update_same], }, { rintros ⟨g, hg, rfl⟩, exact ⟨g i, is.prod g, hg (is.mem_insert_self _), ⟨g, λ i hi, hg (finset.mem_insert_of_mem hi), rfl⟩, rfl⟩ }, end /-- A version of `set.mem_finset_prod` with a simpler RHS for products over a fintype. -/ @[to_additive /-" A version of `set.mem_finset_sum` with a simpler RHS for sums over a fintype. "-/] lemma mem_fintype_prod [fintype ι] (f : ι → set α) (a : α) : a ∈ ∏ i, f i ↔ ∃ (g : ι → α) (hg : ∀ i, g i ∈ f i), ∏ i, g i = a := by { rw mem_finset_prod, simp } /-- The n-ary version of `set.mul_mem_mul`. -/ @[to_additive /-" The n-ary version of `set.add_mem_add`. "-/] lemma finset_prod_mem_finset_prod (t : finset ι) (f : ι → set α) (g : ι → α) (hg : ∀ i ∈ t, g i ∈ f i) : ∏ i in t, g i ∈ ∏ i in t, f i := by { rw mem_finset_prod, exact ⟨g, hg, rfl⟩ } /-- The n-ary version of `set.mul_subset_mul`. -/ @[to_additive /-" The n-ary version of `set.add_subset_add`. "-/] lemma finset_prod_subset_finset_prod (t : finset ι) (f₁ f₂ : ι → set α) (hf : ∀ {i}, i ∈ t → f₁ i ⊆ f₂ i) : ∏ i in t, f₁ i ⊆ ∏ i in t, f₂ i := begin intro a, rw [mem_finset_prod, mem_finset_prod], rintro ⟨g, hg, rfl⟩, exact ⟨g, λ i hi, hf hi $ hg hi, rfl⟩ end /-! TODO: define `decidable_mem_finset_prod` and `decidable_mem_finset_sum`. -/ end big_operators /-! ### Properties about inversion -/ /-- The set `(s⁻¹ : set α)` is defined as `{x | x⁻¹ ∈ s}` in locale `pointwise`. It is equal to `{x⁻¹ | x ∈ s}`, see `set.image_inv`. -/ @[to_additive /-" The set `(-s : set α)` is defined as `{x | -x ∈ s}` in locale `pointwise`. It is equal to `{-x | x ∈ s}`, see `set.image_neg`. "-/] protected def has_inv [has_inv α] : has_inv (set α) := ⟨preimage has_inv.inv⟩ localized "attribute [instance] set.has_inv set.has_neg" in pointwise @[simp, to_additive] lemma inv_empty [has_inv α] : (∅ : set α)⁻¹ = ∅ := rfl @[simp, to_additive] lemma inv_univ [has_inv α] : (univ : set α)⁻¹ = univ := rfl @[simp, to_additive] lemma nonempty_inv [group α] {s : set α} : s⁻¹.nonempty ↔ s.nonempty := inv_involutive.surjective.nonempty_preimage @[to_additive] lemma nonempty.inv [group α] {s : set α} (h : s.nonempty) : s⁻¹.nonempty := nonempty_inv.2 h @[simp, to_additive] lemma mem_inv [has_inv α] : a ∈ s⁻¹ ↔ a⁻¹ ∈ s := iff.rfl @[to_additive] lemma inv_mem_inv [group α] : a⁻¹ ∈ s⁻¹ ↔ a ∈ s := by simp only [mem_inv, inv_inv] @[simp, to_additive] lemma inv_preimage [has_inv α] : has_inv.inv ⁻¹' s = s⁻¹ := rfl @[simp, to_additive] lemma image_inv [group α] : has_inv.inv '' s = s⁻¹ := by { simp only [← inv_preimage], rw [image_eq_preimage_of_inverse]; intro; simp only [inv_inv] } @[simp, to_additive] lemma inter_inv [has_inv α] : (s ∩ t)⁻¹ = s⁻¹ ∩ t⁻¹ := preimage_inter @[simp, to_additive] lemma union_inv [has_inv α] : (s ∪ t)⁻¹ = s⁻¹ ∪ t⁻¹ := preimage_union @[simp, to_additive] lemma compl_inv [has_inv α] : (sᶜ)⁻¹ = (s⁻¹)ᶜ := preimage_compl @[simp, to_additive] protected lemma inv_inv [group α] : s⁻¹⁻¹ = s := by { simp only [← inv_preimage, preimage_preimage, inv_inv, preimage_id'] } @[simp, to_additive] protected lemma univ_inv [group α] : (univ : set α)⁻¹ = univ := preimage_univ @[simp, to_additive] lemma inv_subset_inv [group α] {s t : set α} : s⁻¹ ⊆ t⁻¹ ↔ s ⊆ t := (equiv.inv α).surjective.preimage_subset_preimage_iff @[to_additive] lemma inv_subset [group α] {s t : set α} : s⁻¹ ⊆ t ↔ s ⊆ t⁻¹ := by { rw [← inv_subset_inv, set.inv_inv] } @[to_additive] lemma finite.inv [group α] {s : set α} (hs : finite s) : finite s⁻¹ := hs.preimage $ inv_injective.inj_on _ /-! ### Properties about scalar multiplication -/ /-- The scaling of a set `(x • s : set β)` by a scalar `x ∶ α` is defined as `{x • y | y ∈ s}` in locale `pointwise`. -/ @[to_additive has_vadd_set "The translation of a set `(x +ᵥ s : set β)` by a scalar `x ∶ α` is defined as `{x +ᵥ y | y ∈ s}` in locale `pointwise`."] protected def has_scalar_set [has_scalar α β] : has_scalar α (set β) := ⟨λ a, image (has_scalar.smul a)⟩ /-- The pointwise scalar multiplication `(s • t : set β)` by a set of scalars `s ∶ set α` is defined as `{x • y | x ∈ s, y ∈ t}` in locale `pointwise`. -/ @[to_additive has_vadd "The pointwise translation `(s +ᵥ t : set β)` by a set of constants `s ∶ set α` is defined as `{x +ᵥ y | x ∈ s, y ∈ t}` in locale `pointwise`."] protected def has_scalar [has_scalar α β] : has_scalar (set α) (set β) := ⟨image2 has_scalar.smul⟩ localized "attribute [instance] set.has_scalar_set set.has_scalar" in pointwise localized "attribute [instance] set.has_vadd_set set.has_vadd" in pointwise @[simp, to_additive] lemma image_smul [has_scalar α β] {t : set β} : (λ x, a • x) '' t = a • t := rfl @[to_additive] lemma mem_smul_set [has_scalar α β] {t : set β} : x ∈ a • t ↔ ∃ y, y ∈ t ∧ a • y = x := iff.rfl @[to_additive] lemma smul_mem_smul_set [has_scalar α β] {t : set β} (hy : y ∈ t) : a • y ∈ a • t := ⟨y, hy, rfl⟩ @[to_additive] lemma smul_set_union [has_scalar α β] {s t : set β} : a • (s ∪ t) = a • s ∪ a • t := by simp only [← image_smul, image_union] @[simp, to_additive] lemma smul_set_empty [has_scalar α β] (a : α) : a • (∅ : set β) = ∅ := by rw [← image_smul, image_empty] @[to_additive] lemma smul_set_mono [has_scalar α β] {s t : set β} (h : s ⊆ t) : a • s ⊆ a • t := by { simp only [← image_smul, image_subset, h] } @[simp, to_additive] lemma image2_smul [has_scalar α β] {t : set β} : image2 has_scalar.smul s t = s • t := rfl @[to_additive] lemma mem_smul [has_scalar α β] {t : set β} : x ∈ s • t ↔ ∃ a y, a ∈ s ∧ y ∈ t ∧ a • y = x := iff.rfl @[to_additive] lemma image_smul_prod [has_scalar α β] {t : set β} : (λ x : α × β, x.fst • x.snd) '' s.prod t = s • t := image_prod _ @[to_additive] theorem range_smul_range [has_scalar α β] {ι κ : Type*} (b : ι → α) (c : κ → β) : range b • range c = range (λ p : ι × κ, b p.1 • c p.2) := ext $ λ x, ⟨λ hx, let ⟨p, q, ⟨i, hi⟩, ⟨j, hj⟩, hpq⟩ := set.mem_smul.1 hx in ⟨(i, j), hpq ▸ hi ▸ hj ▸ rfl⟩, λ ⟨⟨i, j⟩, h⟩, set.mem_smul.2 ⟨b i, c j, ⟨i, rfl⟩, ⟨j, rfl⟩, h⟩⟩ @[simp, to_additive] lemma singleton_smul [has_scalar α β] {t : set β} : ({a} : set α) • t = a • t := image2_singleton_left @[to_additive] instance smul_comm_class_set {γ : Type*} [has_scalar α γ] [has_scalar β γ] [smul_comm_class α β γ] : smul_comm_class α (set β) (set γ) := { smul_comm := λ a T T', by simp only [←image2_smul, ←image_smul, image2_image_right, image_image2, smul_comm] } @[to_additive] instance smul_comm_class_set' {γ : Type*} [has_scalar α γ] [has_scalar β γ] [smul_comm_class α β γ] : smul_comm_class (set α) β (set γ) := by haveI := smul_comm_class.symm α β γ; exact smul_comm_class.symm _ _ _ @[to_additive] instance smul_comm_class {γ : Type*} [has_scalar α γ] [has_scalar β γ] [smul_comm_class α β γ] : smul_comm_class (set α) (set β) (set γ) := { smul_comm := λ T T' T'', begin simp only [←image2_smul, image2_swap _ T], exact image2_assoc (λ b c a, smul_comm a b c), end } instance is_scalar_tower {γ : Type*} [has_scalar α β] [has_scalar α γ] [has_scalar β γ] [is_scalar_tower α β γ] : is_scalar_tower α β (set γ) := { smul_assoc := λ a b T, by simp only [←image_smul, image_image, smul_assoc] } instance is_scalar_tower' {γ : Type*} [has_scalar α β] [has_scalar α γ] [has_scalar β γ] [is_scalar_tower α β γ] : is_scalar_tower α (set β) (set γ) := { smul_assoc := λ a T T', by simp only [←image_smul, ←image2_smul, image_image2, image2_image_left, smul_assoc] } instance is_scalar_tower'' {γ : Type*} [has_scalar α β] [has_scalar α γ] [has_scalar β γ] [is_scalar_tower α β γ] : is_scalar_tower (set α) (set β) (set γ) := { smul_assoc := λ T T' T'', image2_assoc smul_assoc } section monoid /-! ### `set α` as a `(∪,*)`-semiring -/ /-- An alias for `set α`, which has a semiring structure given by `∪` as "addition" and pointwise multiplication `*` as "multiplication". -/ @[derive inhabited] def set_semiring (α : Type*) : Type* := set α /-- The identitiy function `set α → set_semiring α`. -/ protected def up (s : set α) : set_semiring α := s /-- The identitiy function `set_semiring α → set α`. -/ protected def set_semiring.down (s : set_semiring α) : set α := s @[simp] protected lemma down_up {s : set α} : s.up.down = s := rfl @[simp] protected lemma up_down {s : set_semiring α} : s.down.up = s := rfl instance set_semiring.add_comm_monoid : add_comm_monoid (set_semiring α) := { add := λ s t, (s ∪ t : set α), zero := (∅ : set α), add_assoc := union_assoc, zero_add := empty_union, add_zero := union_empty, add_comm := union_comm, } instance set_semiring.non_unital_non_assoc_semiring [has_mul α] : non_unital_non_assoc_semiring (set_semiring α) := { zero_mul := λ s, empty_mul, mul_zero := λ s, mul_empty, left_distrib := λ _ _ _, mul_union, right_distrib := λ _ _ _, union_mul, ..set.has_mul, ..set_semiring.add_comm_monoid } instance set_semiring.non_assoc_semiring [mul_one_class α] : non_assoc_semiring (set_semiring α) := { ..set_semiring.non_unital_non_assoc_semiring, ..set.mul_one_class } instance set_semiring.non_unital_semiring [semigroup α] : non_unital_semiring (set_semiring α) := { ..set_semiring.non_unital_non_assoc_semiring, ..set.semigroup } instance set_semiring.semiring [monoid α] : semiring (set_semiring α) := { ..set_semiring.non_assoc_semiring, ..set_semiring.non_unital_semiring } instance set_semiring.comm_semiring [comm_monoid α] : comm_semiring (set_semiring α) := { ..set.comm_monoid, ..set_semiring.semiring } /-- A multiplicative action of a monoid on a type β gives also a multiplicative action on the subsets of β. -/ @[to_additive "An additive action of an additive monoid on a type β gives also an additive action on the subsets of β."] protected def mul_action_set [monoid α] [mul_action α β] : mul_action α (set β) := { mul_smul := by { intros, simp only [← image_smul, image_image, ← mul_smul] }, one_smul := by { intros, simp only [← image_smul, image_eta, one_smul, image_id'] }, ..set.has_scalar_set } localized "attribute [instance] set.mul_action_set set.add_action_set" in pointwise section mul_hom variables [has_mul α] [has_mul β] (m : mul_hom α β) @[to_additive] lemma image_mul : m '' (s * t) = m '' s * m '' t := by { simp only [← image2_mul, image_image2, image2_image_left, image2_image_right, m.map_mul] } @[to_additive] lemma preimage_mul_preimage_subset {s t : set β} : m ⁻¹' s * m ⁻¹' t ⊆ m ⁻¹' (s * t) := by { rintros _ ⟨_, _, _, _, rfl⟩, exact ⟨_, _, ‹_›, ‹_›, (m.map_mul _ _).symm ⟩ } end mul_hom /-- The image of a set under function is a ring homomorphism with respect to the pointwise operations on sets. -/ def image_hom [monoid α] [monoid β] (f : α →* β) : set_semiring α →+* set_semiring β := { to_fun := image f, map_zero' := image_empty _, map_one' := by simp only [← singleton_one, image_singleton, f.map_one], map_add' := image_union _, map_mul' := λ _ _, image_mul f.to_mul_hom } end monoid end set open set open_locale pointwise section variables {α : Type*} {β : Type*} /-- A nonempty set in a module is scaled by zero to the singleton containing 0 in the module. -/ lemma zero_smul_set [semiring α] [add_comm_monoid β] [module α β] {s : set β} (h : s.nonempty) : (0 : α) • s = (0 : set β) := by simp only [← image_smul, image_eta, zero_smul, h.image_const, singleton_zero] lemma mem_inv_smul_set_iff [group_with_zero α] [mul_action α β] {a : α} (ha : a ≠ 0) (A : set β) (x : β) : x ∈ a⁻¹ • A ↔ a • x ∈ A := by simp only [← image_smul, mem_image, inv_smul_eq_iff' ha, exists_eq_right] lemma mem_smul_set_iff_inv_smul_mem [group_with_zero α] [mul_action α β] {a : α} (ha : a ≠ 0) (A : set β) (x : β) : x ∈ a • A ↔ a⁻¹ • x ∈ A := by rw [← mem_inv_smul_set_iff $ inv_ne_zero ha, inv_inv'] lemma preimage_smul [group α] [mul_action α β] (a : α) (t : set β) : (λ x, a • x) ⁻¹' t = a⁻¹ • t := ((mul_action.to_perm a).symm.image_eq_preimage _).symm lemma preimage_smul' [group_with_zero α] [mul_action α β] {a : α} (ha : a ≠ 0) (t : set β) : (λ x, a • x) ⁻¹' t = a⁻¹ • t := preimage_smul (units.mk0 a ha) t end namespace finset variables {α : Type*} [decidable_eq α] /-- The pointwise product of two finite sets `s` and `t`: `st = s ⬝ t = s * t = { x * y | x ∈ s, y ∈ t }`. -/ @[to_additive /-"The pointwise sum of two finite sets `s` and `t`: `s + t = { x + y | x ∈ s, y ∈ t }`. "-/] protected def has_mul [has_mul α] : has_mul (finset α) := ⟨λ s t, (s.product t).image (λ p : α × α, p.1 * p.2)⟩ localized "attribute [instance] finset.has_mul finset.has_add" in pointwise @[to_additive] lemma mul_def [has_mul α] {s t : finset α} : s * t = (s.product t).image (λ p : α × α, p.1 * p.2) := rfl @[to_additive] lemma mem_mul [has_mul α] {s t : finset α} {x : α} : x ∈ s * t ↔ ∃ y z, y ∈ s ∧ z ∈ t ∧ y * z = x := by { simp only [finset.mul_def, and.assoc, mem_image, exists_prop, prod.exists, mem_product] } @[simp, norm_cast, to_additive] lemma coe_mul [has_mul α] {s t : finset α} : (↑(s * t) : set α) = ↑s * ↑t := by { ext, simp only [mem_mul, set.mem_mul, mem_coe] } @[to_additive] lemma mul_mem_mul [has_mul α] {s t : finset α} {x y : α} (hx : x ∈ s) (hy : y ∈ t) : x * y ∈ s * t := by { simp only [finset.mem_mul], exact ⟨x, y, hx, hy, rfl⟩ } @[to_additive] lemma mul_card_le [has_mul α] {s t : finset α} : (s * t).card ≤ s.card * t.card := by { convert finset.card_image_le, rw [finset.card_product, mul_comm] } open_locale classical /-- A finite set `U` contained in the product of two sets `S * S'` is also contained in the product of two finite sets `T * T' ⊆ S * S'`. -/ @[to_additive] lemma subset_mul {M : Type*} [monoid M] {S : set M} {S' : set M} {U : finset M} (f : ↑U ⊆ S * S') : ∃ (T T' : finset M), ↑T ⊆ S ∧ ↑T' ⊆ S' ∧ U ⊆ T * T' := begin apply finset.induction_on' U, { use [∅, ∅], simp only [finset.empty_subset, finset.coe_empty, set.empty_subset, and_self], }, rintros a s haU hs has ⟨T, T', hS, hS', h⟩, obtain ⟨x, y, hx, hy, ha⟩ := set.mem_mul.1 (f haU), use [insert x T, insert y T'], simp only [finset.coe_insert], repeat { rw [set.insert_subset], }, use [hx, hS, hy, hS'], refine finset.insert_subset.mpr ⟨_, _⟩, { rw finset.mem_mul, use [x,y], simpa only [true_and, true_or, eq_self_iff_true, finset.mem_insert], }, { suffices g : (s : set M) ⊆ insert x T * insert y T', { norm_cast at g, assumption, }, transitivity ↑(T * T'), apply h, rw finset.coe_mul, apply set.mul_subset_mul (set.subset_insert x T) (set.subset_insert y T'), }, end end finset /-! Some lemmas about pointwise multiplication and submonoids. Ideally we put these in `group_theory.submonoid.basic`, but currently we cannot because that file is imported by this. -/ namespace submonoid variables {M : Type*} [monoid M] @[to_additive] lemma mul_subset {s t : set M} {S : submonoid M} (hs : s ⊆ S) (ht : t ⊆ S) : s * t ⊆ S := by { rintro _ ⟨p, q, hp, hq, rfl⟩, exact submonoid.mul_mem _ (hs hp) (ht hq) } @[to_additive] lemma mul_subset_closure {s t u : set M} (hs : s ⊆ u) (ht : t ⊆ u) : s * t ⊆ submonoid.closure u := mul_subset (subset.trans hs submonoid.subset_closure) (subset.trans ht submonoid.subset_closure) @[to_additive] lemma coe_mul_self_eq (s : submonoid M) : (s : set M) * s = s := begin ext x, refine ⟨_, λ h, ⟨x, 1, h, s.one_mem, mul_one x⟩⟩, rintros ⟨a, b, ha, hb, rfl⟩, exact s.mul_mem ha hb end @[to_additive] lemma closure_mul_le (S T : set M) : closure (S * T) ≤ closure S ⊔ closure T := Inf_le $ λ x ⟨s, t, hs, ht, hx⟩, hx ▸ (closure S ⊔ closure T).mul_mem (set_like.le_def.mp le_sup_left $ subset_closure hs) (set_like.le_def.mp le_sup_right $ subset_closure ht) @[to_additive] lemma sup_eq_closure (H K : submonoid M) : H ⊔ K = closure (H * K) := le_antisymm (sup_le (λ h hh, subset_closure ⟨h, 1, hh, K.one_mem, mul_one h⟩) (λ k hk, subset_closure ⟨1, k, H.one_mem, hk, one_mul k⟩)) (by conv_rhs { rw [← closure_eq H, ← closure_eq K] }; apply closure_mul_le) end submonoid namespace group lemma card_pow_eq_card_pow_card_univ_aux {f : ℕ → ℕ} (h1 : monotone f) {B : ℕ} (h2 : ∀ n, f n ≤ B) (h3 : ∀ n, f n = f (n + 1) → f (n + 1) = f (n + 2)) : ∀ k, B ≤ k → f k = f B := begin have key : ∃ n : ℕ, n ≤ B ∧ f n = f (n + 1), { contrapose! h2, suffices : ∀ n : ℕ, n ≤ B + 1 → n ≤ f n, { exact ⟨B + 1, this (B + 1) (le_refl (B + 1))⟩ }, exact λ n, nat.rec (λ h, nat.zero_le (f 0)) (λ n ih h, lt_of_le_of_lt (ih (n.le_succ.trans h)) (lt_of_le_of_ne (h1 n.le_succ) (h2 n (nat.succ_le_succ_iff.mp h)))) n }, { obtain ⟨n, hn1, hn2⟩ := key, replace key : ∀ k : ℕ, f (n + k) = f (n + k + 1) ∧ f (n + k) = f n := λ k, nat.rec ⟨hn2, rfl⟩ (λ k ih, ⟨h3 _ ih.1, ih.1.symm.trans ih.2⟩) k, replace key : ∀ k : ℕ, n ≤ k → f k = f n := λ k hk, (congr_arg f (nat.add_sub_cancel' hk)).symm.trans (key (k - n)).2, exact λ k hk, (key k (hn1.trans hk)).trans (key B hn1).symm }, end variables {G : Type*} [group G] [fintype G] (S : set G) lemma card_pow_eq_card_pow_card_univ [∀ (k : ℕ), decidable_pred (∈ (S ^ k))] : ∀ k, fintype.card G ≤ k → fintype.card ↥(S ^ k) = fintype.card ↥(S ^ (fintype.card G)) := begin have hG : 0 < fintype.card G := fintype.card_pos_iff.mpr ⟨1⟩, by_cases hS : S = ∅, { intros k hk, congr' 2, rw [hS, empty_pow _ (ne_of_gt (lt_of_lt_of_le hG hk)), empty_pow _ (ne_of_gt hG)] }, obtain ⟨a, ha⟩ := set.ne_empty_iff_nonempty.mp hS, classical, have key : ∀ a (s t : set G), (∀ b : G, b ∈ s → a * b ∈ t) → fintype.card s ≤ fintype.card t, { refine λ a s t h, fintype.card_le_of_injective (λ ⟨b, hb⟩, ⟨a * b, h b hb⟩) _, rintros ⟨b, hb⟩ ⟨c, hc⟩ hbc, exact subtype.ext (mul_left_cancel (subtype.ext_iff.mp hbc)) }, have mono : monotone (λ n, fintype.card ↥(S ^ n) : ℕ → ℕ) := monotone_nat_of_le_succ (λ n, key a _ _ (λ b hb, set.mul_mem_mul ha hb)), convert card_pow_eq_card_pow_card_univ_aux mono (λ n, set_fintype_card_le_univ (S ^ n)) (λ n h, le_antisymm (mono (n + 1).le_succ) (key a⁻¹ _ _ _)), { simp only [finset.filter_congr_decidable, fintype.card_of_finset] }, replace h : {a} * S ^ n = S ^ (n + 1), { refine set.eq_of_subset_of_card_le _ (le_trans (ge_of_eq h) _), { exact mul_subset_mul (set.singleton_subset_iff.mpr ha) set.subset.rfl }, { convert key a (S ^ n) ({a} * S ^ n) (λ b hb, set.mul_mem_mul (set.mem_singleton a) hb) } }, rw [pow_succ', ←h, mul_assoc, ←pow_succ', h], rintros _ ⟨b, c, hb, hc, rfl⟩, rwa [set.mem_singleton_iff.mp hb, inv_mul_cancel_left], end end group
bab010a5df3a5302e8fd5a2d530117816f63f840
367134ba5a65885e863bdc4507601606690974c1
/src/linear_algebra/basic.lean
92bcae115421504b18b540f7631404ee889ecc6b
[ "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
99,722
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Kevin Buzzard, Yury Kudryashov -/ import algebra.big_operators.pi import algebra.module.pi import algebra.module.prod import algebra.module.submodule import algebra.group.prod import data.finsupp.basic import data.dfinsupp import algebra.pointwise import order.compactly_generated /-! # Linear algebra This file defines the basics of linear algebra. It sets up the "categorical/lattice structure" of modules over a ring, submodules, and linear maps. If `p` and `q` are submodules of a module, `p ≤ q` means that `p ⊆ q`. Many of the relevant definitions, including `module`, `submodule`, and `linear_map`, are found in `src/algebra/module`. ## Main definitions * Many constructors for linear maps * `submodule.span s` is defined to be the smallest submodule containing the set `s`. * If `p` is a submodule of `M`, `submodule.quotient p` is the quotient of `M` with respect to `p`: that is, elements of `M` are identified if their difference is in `p`. This is itself a module. * The kernel `ker` and range `range` of a linear map are submodules of the domain and codomain respectively. * The general linear group is defined to be the group of invertible linear maps from `M` to itself. ## Main statements * The first and second isomorphism laws for modules are proved as `quot_ker_equiv_range` and `quotient_inf_equiv_sup_quotient`. ## Notations * We continue to use the notation `M →ₗ[R] M₂` for the type of linear maps from `M` to `M₂` over the ring `R`. * We introduce the notations `M ≃ₗ M₂` and `M ≃ₗ[R] M₂` for `linear_equiv M M₂`. In the first, the ring `R` is implicit. * We introduce the notation `R ∙ v` for the span of a singleton, `submodule.span R {v}`. This is `\.`, not the same as the scalar multiplication `•`/`\bub`. ## Implementation notes We note that, when constructing linear maps, it is convenient to use operations defined on bundled maps (`linear_map.prod`, `linear_map.coprod`, arithmetic operations like `+`) instead of defining a function and proving it is linear. ## Tags linear algebra, vector space, module -/ open function open_locale big_operators universes u v w x y z u' v' w' y' variables {R : Type u} {K : Type u'} {M : Type v} {V : Type v'} {M₂ : Type w} {V₂ : Type w'} variables {M₃ : Type y} {V₃ : Type y'} {M₄ : Type z} {ι : Type x} namespace finsupp lemma smul_sum {α : Type u} {β : Type v} {R : Type w} {M : Type y} [has_zero β] [semiring R] [add_comm_monoid M] [semimodule R M] {v : α →₀ β} {c : R} {h : α → β → M} : c • (v.sum h) = v.sum (λa b, c • h a b) := finset.smul_sum @[simp] lemma sum_smul_index_linear_map' {α : Type u} {R : Type v} {M : Type w} {M₂ : Type x} [semiring R] [add_comm_monoid M] [semimodule R M] [add_comm_monoid M₂] [semimodule R M₂] {v : α →₀ M} {c : R} {h : α → M →ₗ[R] M₂} : (c • v).sum (λ a, h a) = c • (v.sum (λ a, h a)) := begin rw [finsupp.sum_smul_index', finsupp.smul_sum], { simp only [linear_map.map_smul], }, { intro i, exact (h i).map_zero }, end end finsupp section open_locale classical /-- decomposing `x : ι → R` as a sum along the canonical basis -/ lemma pi_eq_sum_univ {ι : Type u} [fintype ι] {R : Type v} [semiring R] (x : ι → R) : x = ∑ i, x i • (λj, if i = j then 1 else 0) := by { ext, simp } end /-! ### Properties of linear maps -/ namespace linear_map section add_comm_monoid variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] [semimodule R M₄] variables (f g : M →ₗ[R] M₂) include R @[simp] theorem comp_id : f.comp id = f := linear_map.ext $ λ x, rfl @[simp] theorem id_comp : id.comp f = f := linear_map.ext $ λ x, rfl theorem comp_assoc (g : M₂ →ₗ[R] M₃) (h : M₃ →ₗ[R] M₄) : (h.comp g).comp f = h.comp (g.comp f) := rfl /-- The restriction of a linear map `f : M → M₂` to a submodule `p ⊆ M` gives a linear map `p → M₂`. -/ def dom_restrict (f : M →ₗ[R] M₂) (p : submodule R M) : p →ₗ[R] M₂ := f.comp p.subtype @[simp] lemma dom_restrict_apply (f : M →ₗ[R] M₂) (p : submodule R M) (x : p) : f.dom_restrict p x = f x := rfl /-- A linear map `f : M₂ → M` whose values lie in a submodule `p ⊆ M` can be restricted to a linear map M₂ → p. -/ def cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (h : ∀c, f c ∈ p) : M₂ →ₗ[R] p := by refine {to_fun := λc, ⟨f c, h c⟩, ..}; intros; apply set_coe.ext; simp @[simp] theorem cod_restrict_apply (p : submodule R M) (f : M₂ →ₗ[R] M) {h} (x : M₂) : (cod_restrict p f h x : M) = f x := rfl @[simp] lemma comp_cod_restrict (p : submodule R M₂) (h : ∀b, f b ∈ p) (g : M₃ →ₗ[R] M) : (cod_restrict p f h).comp g = cod_restrict p (f.comp g) (assume b, h _) := ext $ assume b, rfl @[simp] lemma subtype_comp_cod_restrict (p : submodule R M₂) (h : ∀b, f b ∈ p) : p.subtype.comp (cod_restrict p f h) = f := ext $ assume b, rfl /-- Restrict domain and codomain of an endomorphism. -/ def restrict (f : M →ₗ[R] M) {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) : p →ₗ[R] p := (f.dom_restrict p).cod_restrict p $ submodule.forall.2 hf lemma restrict_apply {f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) (x : p) : f.restrict hf x = ⟨f x, hf x.1 x.2⟩ := rfl lemma subtype_comp_restrict {f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) : p.subtype.comp (f.restrict hf) = f.dom_restrict p := rfl lemma restrict_eq_cod_restrict_dom_restrict {f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) : f.restrict hf = (f.dom_restrict p).cod_restrict p (λ x, hf x.1 x.2) := rfl lemma restrict_eq_dom_restrict_cod_restrict {f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x, f x ∈ p) : f.restrict (λ x _, hf x) = (f.cod_restrict p hf).dom_restrict p := rfl /-- The constant 0 map is linear. -/ instance : has_zero (M →ₗ[R] M₂) := ⟨⟨λ _, 0, by simp, by simp⟩⟩ instance : inhabited (M →ₗ[R] M₂) := ⟨0⟩ @[simp] lemma zero_apply (x : M) : (0 : M →ₗ[R] M₂) x = 0 := rfl @[simp] lemma default_def : default (M →ₗ[R] M₂) = 0 := rfl instance unique_of_left [subsingleton M] : unique (M →ₗ[R] M₂) := { uniq := λ f, ext $ λ x, by rw [subsingleton.elim x 0, map_zero, map_zero], .. linear_map.inhabited } instance unique_of_right [subsingleton M₂] : unique (M →ₗ[R] M₂) := coe_injective.unique /-- The sum of two linear maps is linear. -/ instance : has_add (M →ₗ[R] M₂) := ⟨λ f g, ⟨λ b, f b + g b, by simp [add_comm, add_left_comm], by simp [smul_add]⟩⟩ @[simp] lemma add_apply (x : M) : (f + g) x = f x + g x := rfl /-- The type of linear maps is an additive monoid. -/ instance : add_comm_monoid (M →ₗ[R] M₂) := by refine {zero := 0, add := (+), ..}; intros; ext; simp [add_comm, add_left_comm] instance linear_map_apply_is_add_monoid_hom (a : M) : is_add_monoid_hom (λ f : M →ₗ[R] M₂, f a) := { map_add := λ f g, linear_map.add_apply f g a, map_zero := rfl } lemma add_comp (g : M₂ →ₗ[R] M₃) (h : M₂ →ₗ[R] M₃) : (h + g).comp f = h.comp f + g.comp f := rfl lemma comp_add (g : M →ₗ[R] M₂) (h : M₂ →ₗ[R] M₃) : h.comp (f + g) = h.comp f + h.comp g := by { ext, simp } lemma sum_apply (t : finset ι) (f : ι → M →ₗ[R] M₂) (b : M) : (∑ d in t, f d) b = ∑ d in t, f d b := (t.sum_hom (λ g : M →ₗ[R] M₂, g b)).symm section smul_right variables {S : Type*} [semiring S] [semimodule R S] [semimodule S M] [is_scalar_tower R S M] /-- When `f` is an `R`-linear map taking values in `S`, then `λb, f b • x` is an `R`-linear map. -/ def smul_right (f : M₂ →ₗ[R] S) (x : M) : M₂ →ₗ[R] M := { to_fun := λb, f b • x, map_add' := λ x y, by rw [f.map_add, add_smul], map_smul' := λ b y, by rw [f.map_smul, smul_assoc] } @[simp] theorem smul_right_apply (f : M₂ →ₗ[R] S) (x : M) (c : M₂) : smul_right f x c = f c • x := rfl end smul_right instance : has_one (M →ₗ[R] M) := ⟨linear_map.id⟩ instance : has_mul (M →ₗ[R] M) := ⟨linear_map.comp⟩ lemma mul_eq_comp (f g : M →ₗ[R] M) : f * g = f.comp g := rfl @[simp] lemma one_apply (x : M) : (1 : M →ₗ[R] M) x = x := rfl @[simp] lemma mul_apply (f g : M →ₗ[R] M) (x : M) : (f * g) x = f (g x) := rfl lemma coe_one : ⇑(1 : M →ₗ[R] M) = _root_.id := rfl lemma coe_mul (f g : M →ₗ[R] M) : ⇑(f * g) = f ∘ g := rfl @[simp] theorem comp_zero : f.comp (0 : M₃ →ₗ[R] M) = 0 := ext $ assume c, by rw [comp_apply, zero_apply, zero_apply, f.map_zero] @[simp] theorem zero_comp : (0 : M₂ →ₗ[R] M₃).comp f = 0 := rfl @[simp, norm_cast] lemma coe_fn_sum {ι : Type*} (t : finset ι) (f : ι → M →ₗ[R] M₂) : ⇑(∑ i in t, f i) = ∑ i in t, (f i : M → M₂) := add_monoid_hom.map_sum ⟨@to_fun R M M₂ _ _ _ _ _, rfl, λ x y, rfl⟩ _ _ instance : monoid (M →ₗ[R] M) := by refine {mul := (*), one := 1, ..}; { intros, apply linear_map.ext, simp {proj := ff} } @[simp] lemma pow_apply (f : M →ₗ[R] M) (n : ℕ) (m : M) : (f^n) m = (f^[n] m) := begin induction n with n ih, { refl, }, { simp only [function.comp_app, function.iterate_succ, linear_map.mul_apply, pow_succ, ih], exact (function.commute.iterate_self _ _ m).symm, }, end lemma coe_pow (f : M →ₗ[R] M) (n : ℕ) : ⇑(f^n) = (f^[n]) := by { ext m, apply pow_apply, } section open_locale classical /-- A linear map `f` applied to `x : ι → R` can be computed using the image under `f` of elements of the canonical basis. -/ lemma pi_apply_eq_sum_univ [fintype ι] (f : (ι → R) →ₗ[R] M) (x : ι → R) : f x = ∑ i, x i • (f (λj, if i = j then 1 else 0)) := begin conv_lhs { rw [pi_eq_sum_univ x, f.map_sum] }, apply finset.sum_congr rfl (λl hl, _), rw f.map_smul end end end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_monoid M] [add_comm_group M₂] [add_comm_group M₃] [add_comm_group M₄] [semimodule R M] [semimodule R M₂] [semimodule R M₃] [semimodule R M₄] (f g : M →ₗ[R] M₂) /-- The negation of a linear map is linear. -/ instance : has_neg (M →ₗ[R] M₂) := ⟨λ f, ⟨λ b, - f b, by simp [add_comm], by simp⟩⟩ @[simp] lemma neg_apply (x : M) : (- f) x = - f x := rfl @[simp] lemma comp_neg (g : M₂ →ₗ[R] M₃) : g.comp (- f) = - g.comp f := by { ext, simp } /-- The negation of a linear map is linear. -/ instance : has_sub (M →ₗ[R] M₂) := ⟨λ f g, ⟨λ b, f b - g b, by { simp only [map_add, sub_eq_add_neg, neg_add], cc }, by { intros, simp only [map_smul, smul_sub] }⟩⟩ @[simp] lemma sub_apply (x : M) : (f - g) x = f x - g x := rfl lemma sub_comp (g : M₂ →ₗ[R] M₃) (h : M₂ →ₗ[R] M₃) : (g - h).comp f = g.comp f - h.comp f := rfl lemma comp_sub (g : M →ₗ[R] M₂) (h : M₂ →ₗ[R] M₃) : h.comp (g - f) = h.comp g - h.comp f := by { ext, simp } /-- The type of linear maps is an additive group. -/ instance : add_comm_group (M →ₗ[R] M₂) := by refine {zero := 0, add := (+), neg := has_neg.neg, sub := has_sub.sub, sub_eq_add_neg := _, ..}; intros; ext; simp [add_comm, add_left_comm, sub_eq_add_neg] instance linear_map_apply_is_add_group_hom (a : M) : is_add_group_hom (λ f : M →ₗ[R] M₂, f a) := { map_add := λ f g, linear_map.add_apply f g a } end add_comm_group section has_scalar variables {S : Type*} [semiring R] [monoid S] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [semimodule R M] [semimodule R M₂] [semimodule R M₃] [distrib_mul_action S M₂] [smul_comm_class R S M₂] (f : M →ₗ[R] M₂) instance : has_scalar S (M →ₗ[R] M₂) := ⟨λ a f, ⟨λ b, a • f b, λ x y, by rw [f.map_add, smul_add], λ c x, by simp only [f.map_smul, smul_comm c]⟩⟩ @[simp] lemma smul_apply (a : S) (x : M) : (a • f) x = a • f x := rfl instance {T : Type*} [monoid T] [distrib_mul_action T M₂] [smul_comm_class R T M₂] [smul_comm_class S T M₂] : smul_comm_class S T (M →ₗ[R] M₂) := ⟨λ a b f, ext $ λ x, smul_comm _ _ _⟩ -- example application of this instance: if S -> T -> R are homomorphisms of commutative rings and -- M and M₂ are R-modules then the S-module and T-module structures on Hom_R(M,M₂) are compatible. instance {T : Type*} [monoid T] [has_scalar S T] [distrib_mul_action T M₂] [smul_comm_class R T M₂] [is_scalar_tower S T M₂] : is_scalar_tower S T (M →ₗ[R] M₂) := { smul_assoc := λ _ _ _, ext $ λ _, smul_assoc _ _ _ } instance : distrib_mul_action S (M →ₗ[R] M₂) := { one_smul := λ f, ext $ λ _, one_smul _ _, mul_smul := λ c c' f, ext $ λ _, mul_smul _ _ _, smul_add := λ c f g, ext $ λ x, smul_add _ _ _, smul_zero := λ c, ext $ λ x, smul_zero _ } theorem smul_comp (a : S) (g : M₃ →ₗ[R] M₂) (f : M →ₗ[R] M₃) : (a • g).comp f = a • (g.comp f) := rfl end has_scalar section semimodule variables {S : Type*} [semiring R] [semiring S] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [semimodule R M] [semimodule R M₂] [semimodule R M₃] [semimodule S M₂] [semimodule S M₃] [smul_comm_class R S M₂] [smul_comm_class R S M₃] (f : M →ₗ[R] M₂) instance : semimodule S (M →ₗ[R] M₂) := { add_smul := λ a b f, ext $ λ x, add_smul _ _ _, zero_smul := λ f, ext $ λ x, zero_smul _ _ } variable (S) /-- Applying a linear map at `v : M`, seen as `S`-linear map from `M →ₗ[R] M₂` to `M₂`. See `linear_map.applyₗ` for a version where `S = R`. -/ @[simps] def applyₗ' : M →+ (M →ₗ[R] M₂) →ₗ[S] M₂ := { to_fun := λ v, { to_fun := λ f, f v, map_add' := λ f g, f.add_apply g v, map_smul' := λ x f, f.smul_apply x v }, map_zero' := linear_map.ext $ λ f, f.map_zero, map_add' := λ x y, linear_map.ext $ λ f, f.map_add _ _ } section variables (R M) /-- The equivalence between R-linear maps from `R` to `M`, and points of `M` itself. This says that the forgetful functor from `R`-modules to types is representable, by `R`. This as an `S`-linear equivalence, under the assumption that `S` acts on `M` commuting with `R`. When `R` is commutative, we can take this to be the usual action with `S = R`. Otherwise, `S = ℕ` shows that the equivalence is additive. See note [bundled maps over different rings]. -/ @[simps] def ring_lmap_equiv_self [semimodule S M] [smul_comm_class R S M] : (R →ₗ[R] M) ≃ₗ[S] M := { to_fun := λ f, f 1, inv_fun := smul_right (1 : R →ₗ[R] R), left_inv := λ f, by { ext, simp }, right_inv := λ x, by simp, .. applyₗ' S (1 : R) } end end semimodule section comm_semiring variables [comm_semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] variables (f g : M →ₗ[R] M₂) include R theorem comp_smul (g : M₂ →ₗ[R] M₃) (a : R) : g.comp (a • f) = a • (g.comp f) := ext $ assume b, by rw [comp_apply, smul_apply, g.map_smul]; refl /-- Composition by `f : M₂ → M₃` is a linear map from the space of linear maps `M → M₂` to the space of linear maps `M₂ → M₃`. -/ def comp_right (f : M₂ →ₗ[R] M₃) : (M →ₗ[R] M₂) →ₗ[R] (M →ₗ[R] M₃) := ⟨f.comp, λ _ _, linear_map.ext $ λ _, f.2 _ _, λ _ _, linear_map.ext $ λ _, f.3 _ _⟩ /-- Applying a linear map at `v : M`, seen as a linear map from `M →ₗ[R] M₂` to `M₂`. See also `linear_map.applyₗ'` for a version that works with two different semirings. This is the `linear_map` version of `add_monoid_hom.eval`. -/ @[simps] def applyₗ : M →ₗ[R] (M →ₗ[R] M₂) →ₗ[R] M₂ := { to_fun := λ v, { to_fun := λ f, f v, ..applyₗ' R v }, map_smul' := λ x y, linear_map.ext $ λ f, f.map_smul _ _, ..applyₗ' R } /-- Alternative version of `dom_restrict` as a linear map. -/ def dom_restrict' (p : submodule R M) : (M →ₗ[R] M₂) →ₗ[R] (p →ₗ[R] M₂) := { to_fun := λ φ, φ.dom_restrict p, map_add' := by simp [linear_map.ext_iff], map_smul' := by simp [linear_map.ext_iff] } @[simp] lemma dom_restrict'_apply (f : M →ₗ[R] M₂) (p : submodule R M) (x : p) : dom_restrict' p f x = f x := rfl end comm_semiring section semiring variables [semiring R] [add_comm_monoid M] [semimodule R M] instance endomorphism_semiring : semiring (M →ₗ[R] M) := by refine {mul := (*), one := 1, ..linear_map.add_comm_monoid, ..}; { intros, apply linear_map.ext, simp {proj := ff} } end semiring section ring variables [ring R] [add_comm_group M] [semimodule R M] instance endomorphism_ring : ring (M →ₗ[R] M) := { ..linear_map.endomorphism_semiring, ..linear_map.add_comm_group } end ring section comm_ring variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] /-- The family of linear maps `M₂ → M` parameterised by `f ∈ M₂ → R`, `x ∈ M`, is linear in `f`, `x`. -/ def smul_rightₗ : (M₂ →ₗ[R] R) →ₗ[R] M →ₗ[R] M₂ →ₗ[R] M := { to_fun := λ f, { to_fun := linear_map.smul_right f, map_add' := λ m m', by { ext, apply smul_add, }, map_smul' := λ c m, by { ext, apply smul_comm, } }, map_add' := λ f f', by { ext, apply add_smul, }, map_smul' := λ c f, by { ext, apply mul_smul, } } @[simp] lemma smul_rightₗ_apply (f : M₂ →ₗ[R] R) (x : M) (c : M₂) : (smul_rightₗ : (M₂ →ₗ R) →ₗ M →ₗ M₂ →ₗ M) f x c = (f c) • x := rfl end comm_ring end linear_map /-! ### Properties of submodules -/ namespace submodule section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] variables (p p' : submodule R M) (q q' : submodule R M₂) variables {r : R} {x y : M} open set instance : partial_order (submodule R M) := { le := λ p p', ∀ ⦃x⦄, x ∈ p → x ∈ p', ..partial_order.lift (coe : submodule R M → set M) coe_injective } variables {p p'} lemma le_def : p ≤ p' ↔ (p : set M) ⊆ p' := iff.rfl @[simp, norm_cast] lemma coe_subset_coe : (p : set M) ⊆ p' ↔ p ≤ p' := iff.rfl lemma le_def' : p ≤ p' ↔ ∀ x ∈ p, x ∈ p' := iff.rfl lemma lt_def : p < p' ↔ (p : set M) ⊂ p' := iff.rfl lemma not_le_iff_exists : ¬ (p ≤ p') ↔ ∃ x ∈ p, x ∉ p' := not_subset lemma exists_of_lt {p p' : submodule R M} : p < p' → ∃ x ∈ p', x ∉ p := exists_of_ssubset lemma lt_iff_le_and_exists : p < p' ↔ p ≤ p' ∧ ∃ x ∈ p', x ∉ p := by rw [lt_iff_le_not_le, not_le_iff_exists] /-- If two submodules `p` and `p'` satisfy `p ⊆ p'`, then `of_le p p'` is the linear map version of this inclusion. -/ def of_le (h : p ≤ p') : p →ₗ[R] p' := p.subtype.cod_restrict p' $ λ ⟨x, hx⟩, h hx @[simp] theorem coe_of_le (h : p ≤ p') (x : p) : (of_le h x : M) = x := rfl theorem of_le_apply (h : p ≤ p') (x : p) : of_le h x = ⟨x, h x.2⟩ := rfl variables (p p') lemma subtype_comp_of_le (p q : submodule R M) (h : p ≤ q) : q.subtype.comp (of_le h) = p.subtype := by { ext ⟨b, hb⟩, refl } /-- The set `{0}` is the bottom element of the lattice of submodules. -/ instance : has_bot (submodule R M) := ⟨{ carrier := {0}, smul_mem' := by simp { contextual := tt }, .. (⊥ : add_submonoid M)}⟩ instance inhabited' : inhabited (submodule R M) := ⟨⊥⟩ @[simp] lemma bot_coe : ((⊥ : submodule R M) : set M) = {0} := rfl section variables (R) @[simp] lemma mem_bot : x ∈ (⊥ : submodule R M) ↔ x = 0 := mem_singleton_iff end instance unique_bot : unique (⊥ : submodule R M) := ⟨infer_instance, λ x, subtype.ext $ (mem_bot R).1 x.mem⟩ lemma nonzero_mem_of_bot_lt {I : submodule R M} (bot_lt : ⊥ < I) : ∃ a : I, a ≠ 0 := begin have h := (submodule.lt_iff_le_and_exists.1 bot_lt).2, tidy, end instance : order_bot (submodule R M) := { bot := ⊥, bot_le := λ p x, by simp {contextual := tt}, ..submodule.partial_order } protected lemma eq_bot_iff (p : submodule R M) : p = ⊥ ↔ ∀ x ∈ p, x = (0 : M) := ⟨ λ h, h.symm ▸ λ x hx, (mem_bot R).mp hx, λ h, eq_bot_iff.mpr (λ x hx, (mem_bot R).mpr (h x hx)) ⟩ protected lemma ne_bot_iff (p : submodule R M) : p ≠ ⊥ ↔ ∃ x ∈ p, x ≠ (0 : M) := by { haveI := classical.prop_decidable, simp_rw [ne.def, p.eq_bot_iff, not_forall] } /-- The universal set is the top element of the lattice of submodules. -/ instance : has_top (submodule R M) := ⟨{ carrier := univ, smul_mem' := λ _ _ _, trivial, .. (⊤ : add_submonoid M)}⟩ @[simp] lemma top_coe : ((⊤ : submodule R M) : set M) = univ := rfl @[simp] lemma mem_top : x ∈ (⊤ : submodule R M) := trivial instance : order_top (submodule R M) := { top := ⊤, le_top := λ p x _, trivial, ..submodule.partial_order } instance : has_Inf (submodule R M) := ⟨λ S, { carrier := ⋂ s ∈ S, (s : set M), zero_mem' := by simp, add_mem' := by simp [add_mem] {contextual := tt}, smul_mem' := by simp [smul_mem] {contextual := tt} }⟩ private lemma Inf_le' {S : set (submodule R M)} {p} : p ∈ S → Inf S ≤ p := bInter_subset_of_mem private lemma le_Inf' {S : set (submodule R M)} {p} : (∀p' ∈ S, p ≤ p') → p ≤ Inf S := subset_bInter instance : has_inf (submodule R M) := ⟨λ p p', { carrier := p ∩ p', zero_mem' := by simp, add_mem' := by simp [add_mem] {contextual := tt}, smul_mem' := by simp [smul_mem] {contextual := tt} }⟩ instance : complete_lattice (submodule R M) := { sup := λ a b, Inf {x | a ≤ x ∧ b ≤ x}, le_sup_left := λ a b, le_Inf' $ λ x ⟨ha, hb⟩, ha, le_sup_right := λ a b, le_Inf' $ λ x ⟨ha, hb⟩, hb, sup_le := λ a b c h₁ h₂, Inf_le' ⟨h₁, h₂⟩, inf := (⊓), le_inf := λ a b c, subset_inter, inf_le_left := λ a b, inter_subset_left _ _, inf_le_right := λ a b, inter_subset_right _ _, Sup := λtt, Inf {t | ∀t'∈tt, t' ≤ t}, le_Sup := λ s p hs, le_Inf' $ λ p' hp', hp' _ hs, Sup_le := λ s p hs, Inf_le' hs, Inf := Inf, le_Inf := λ s a, le_Inf', Inf_le := λ s a, Inf_le', ..submodule.order_top, ..submodule.order_bot } instance add_comm_monoid_submodule : add_comm_monoid (submodule R M) := { add := (⊔), add_assoc := λ _ _ _, sup_assoc, zero := ⊥, zero_add := λ _, bot_sup_eq, add_zero := λ _, sup_bot_eq, add_comm := λ _ _, sup_comm } @[simp] lemma add_eq_sup (p q : submodule R M) : p + q = p ⊔ q := rfl @[simp] lemma zero_eq_bot : (0 : submodule R M) = ⊥ := rfl lemma eq_top_iff' {p : submodule R M} : p = ⊤ ↔ ∀ x, x ∈ p := eq_top_iff.trans ⟨λ h x, @h x trivial, λ h x _, h x⟩ variables (R) @[simp] lemma bot_to_add_submonoid : (⊥ : submodule R M).to_add_submonoid = ⊥ := rfl @[simp] lemma top_to_add_submonoid : (⊤ : submodule R M).to_add_submonoid = ⊤ := rfl lemma subsingleton_iff : subsingleton M ↔ subsingleton (submodule R M) := add_submonoid.subsingleton_iff.trans $ begin rw [←subsingleton_iff_bot_eq_top, ←subsingleton_iff_bot_eq_top], convert to_add_submonoid_eq; refl end lemma nontrivial_iff : nontrivial M ↔ nontrivial (submodule R M) := not_iff_not.mp ( (not_nontrivial_iff_subsingleton.trans $ subsingleton_iff R).trans not_nontrivial_iff_subsingleton.symm) variables {R} instance [subsingleton M] : unique (submodule R M) := ⟨⟨⊥⟩, λ a, @subsingleton.elim _ ((subsingleton_iff R).mp ‹_›) a _⟩ instance unique' [subsingleton R] : unique (submodule R M) := by haveI := semimodule.subsingleton R M; apply_instance instance [nontrivial M] : nontrivial (submodule R M) := (nontrivial_iff R).mp ‹_› @[simp] theorem inf_coe : (p ⊓ p' : set M) = p ∩ p' := rfl @[simp] theorem mem_inf {p p' : submodule R M} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl @[simp] theorem Inf_coe (P : set (submodule R M)) : (↑(Inf P) : set M) = ⋂ p ∈ P, ↑p := rfl @[simp] theorem infi_coe {ι} (p : ι → submodule R M) : (↑⨅ i, p i : set M) = ⋂ i, ↑(p i) := by rw [infi, Inf_coe]; ext a; simp; exact ⟨λ h i, h _ i rfl, λ h i x e, e ▸ h _⟩ @[simp] lemma mem_Inf {S : set (submodule R M)} {x : M} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_bInter_iff @[simp] theorem mem_infi {ι} (p : ι → submodule R M) : x ∈ (⨅ i, p i) ↔ ∀ i, x ∈ p i := by rw [← mem_coe, infi_coe, mem_Inter]; refl theorem disjoint_def {p p' : submodule R M} : disjoint p p' ↔ ∀ x ∈ p, x ∈ p' → x = (0:M) := show (∀ x, x ∈ p ∧ x ∈ p' → x ∈ ({0} : set M)) ↔ _, by simp theorem disjoint_def' {p p' : submodule R M} : disjoint p p' ↔ ∀ (x ∈ p) (y ∈ p'), x = y → x = (0:M) := disjoint_def.trans ⟨λ h x hx y hy hxy, h x hx $ hxy.symm ▸ hy, λ h x hx hx', h _ hx x hx' rfl⟩ theorem mem_right_iff_eq_zero_of_disjoint {p p' : submodule R M} (h : disjoint p p') {x : p} : (x:M) ∈ p' ↔ x = 0 := ⟨λ hx, coe_eq_zero.1 $ disjoint_def.1 h x x.2 hx, λ h, h.symm ▸ p'.zero_mem⟩ theorem mem_left_iff_eq_zero_of_disjoint {p p' : submodule R M} (h : disjoint p p') {x : p'} : (x:M) ∈ p ↔ x = 0 := ⟨λ hx, coe_eq_zero.1 $ disjoint_def.1 h x hx x.2, λ h, h.symm ▸ p.zero_mem⟩ /-- The pushforward of a submodule `p ⊆ M` by `f : M → M₂` -/ def map (f : M →ₗ[R] M₂) (p : submodule R M) : submodule R M₂ := { carrier := f '' p, smul_mem' := by rintro a _ ⟨b, hb, rfl⟩; exact ⟨_, p.smul_mem _ hb, f.map_smul _ _⟩, .. p.to_add_submonoid.map f.to_add_monoid_hom } @[simp] lemma map_coe (f : M →ₗ[R] M₂) (p : submodule R M) : (map f p : set M₂) = f '' p := rfl @[simp] lemma mem_map {f : M →ₗ[R] M₂} {p : submodule R M} {x : M₂} : x ∈ map f p ↔ ∃ y, y ∈ p ∧ f y = x := iff.rfl theorem mem_map_of_mem {f : M →ₗ[R] M₂} {p : submodule R M} {r} (h : r ∈ p) : f r ∈ map f p := set.mem_image_of_mem _ h @[simp] lemma map_id : map linear_map.id p = p := submodule.ext $ λ a, by simp lemma map_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) (p : submodule R M) : map (g.comp f) p = map g (map f p) := submodule.coe_injective $ by simp [map_coe]; rw ← image_comp lemma map_mono {f : M →ₗ[R] M₂} {p p' : submodule R M} : p ≤ p' → map f p ≤ map f p' := image_subset _ @[simp] lemma map_zero : map (0 : M →ₗ[R] M₂) p = ⊥ := have ∃ (x : M), x ∈ p := ⟨0, p.zero_mem⟩, ext $ by simp [this, eq_comm] lemma range_map_nonempty (N : submodule R M) : (set.range (λ ϕ, submodule.map ϕ N : (M →ₗ[R] M₂) → submodule R M₂)).nonempty := ⟨_, set.mem_range.mpr ⟨0, rfl⟩⟩ /-- The pullback of a submodule `p ⊆ M₂` along `f : M → M₂` -/ def comap (f : M →ₗ[R] M₂) (p : submodule R M₂) : submodule R M := { carrier := f ⁻¹' p, smul_mem' := λ a x h, by simp [p.smul_mem _ h], .. p.to_add_submonoid.comap f.to_add_monoid_hom } @[simp] lemma comap_coe (f : M →ₗ[R] M₂) (p : submodule R M₂) : (comap f p : set M) = f ⁻¹' p := rfl @[simp] lemma mem_comap {f : M →ₗ[R] M₂} {p : submodule R M₂} : x ∈ comap f p ↔ f x ∈ p := iff.rfl lemma comap_id : comap linear_map.id p = p := submodule.coe_injective rfl lemma comap_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) (p : submodule R M₃) : comap (g.comp f) p = comap f (comap g p) := rfl lemma comap_mono {f : M →ₗ[R] M₂} {q q' : submodule R M₂} : q ≤ q' → comap f q ≤ comap f q' := preimage_mono lemma map_le_iff_le_comap {f : M →ₗ[R] M₂} {p : submodule R M} {q : submodule R M₂} : map f p ≤ q ↔ p ≤ comap f q := image_subset_iff lemma gc_map_comap (f : M →ₗ[R] M₂) : galois_connection (map f) (comap f) | p q := map_le_iff_le_comap @[simp] lemma map_bot (f : M →ₗ[R] M₂) : map f ⊥ = ⊥ := (gc_map_comap f).l_bot @[simp] lemma map_sup (f : M →ₗ[R] M₂) : map f (p ⊔ p') = map f p ⊔ map f p' := (gc_map_comap f).l_sup @[simp] lemma map_supr {ι : Sort*} (f : M →ₗ[R] M₂) (p : ι → submodule R M) : map f (⨆i, p i) = (⨆i, map f (p i)) := (gc_map_comap f).l_supr @[simp] lemma comap_top (f : M →ₗ[R] M₂) : comap f ⊤ = ⊤ := rfl @[simp] lemma comap_inf (f : M →ₗ[R] M₂) : comap f (q ⊓ q') = comap f q ⊓ comap f q' := rfl @[simp] lemma comap_infi {ι : Sort*} (f : M →ₗ[R] M₂) (p : ι → submodule R M₂) : comap f (⨅i, p i) = (⨅i, comap f (p i)) := (gc_map_comap f).u_infi @[simp] lemma comap_zero : comap (0 : M →ₗ[R] M₂) q = ⊤ := ext $ by simp lemma map_comap_le (f : M →ₗ[R] M₂) (q : submodule R M₂) : map f (comap f q) ≤ q := (gc_map_comap f).l_u_le _ lemma le_comap_map (f : M →ₗ[R] M₂) (p : submodule R M) : p ≤ comap f (map f p) := (gc_map_comap f).le_u_l _ --TODO(Mario): is there a way to prove this from order properties? lemma map_inf_eq_map_inf_comap {f : M →ₗ[R] M₂} {p : submodule R M} {p' : submodule R M₂} : map f p ⊓ p' = map f (p ⊓ comap f p') := le_antisymm (by rintro _ ⟨⟨x, h₁, rfl⟩, h₂⟩; exact ⟨_, ⟨h₁, h₂⟩, rfl⟩) (le_inf (map_mono inf_le_left) (map_le_iff_le_comap.2 inf_le_right)) lemma map_comap_subtype : map p.subtype (comap p.subtype p') = p ⊓ p' := ext $ λ x, ⟨by rintro ⟨⟨_, h₁⟩, h₂, rfl⟩; exact ⟨h₁, h₂⟩, λ ⟨h₁, h₂⟩, ⟨⟨_, h₁⟩, h₂, rfl⟩⟩ lemma eq_zero_of_bot_submodule : ∀(b : (⊥ : submodule R M)), b = 0 | ⟨b', hb⟩ := subtype.eq $ show b' = 0, from (mem_bot R).1 hb section variables (R) /-- The span of a set `s ⊆ M` is the smallest submodule of M that contains `s`. -/ def span (s : set M) : submodule R M := Inf {p | s ⊆ p} end variables {s t : set M} lemma mem_span : x ∈ span R s ↔ ∀ p : submodule R M, s ⊆ p → x ∈ p := mem_bInter_iff lemma subset_span : s ⊆ span R s := λ x h, mem_span.2 $ λ p hp, hp h lemma span_le {p} : span R s ≤ p ↔ s ⊆ p := ⟨subset.trans subset_span, λ ss x h, mem_span.1 h _ ss⟩ lemma span_mono (h : s ⊆ t) : span R s ≤ span R t := span_le.2 $ subset.trans h subset_span lemma span_eq_of_le (h₁ : s ⊆ p) (h₂ : p ≤ span R s) : span R s = p := le_antisymm (span_le.2 h₁) h₂ @[simp] lemma span_eq : span R (p : set M) = p := span_eq_of_le _ (subset.refl _) subset_span lemma map_span (f : M →ₗ[R] M₂) (s : set M) : (span R s).map f = span R (f '' s) := eq.symm $ span_eq_of_le _ (set.image_subset f subset_span) $ map_le_iff_le_comap.2 $ span_le.2 $ λ x hx, subset_span ⟨x, hx, rfl⟩ /- See also `span_preimage_eq` below. -/ lemma span_preimage_le (f : M →ₗ[R] M₂) (s : set M₂) : span R (f ⁻¹' s) ≤ (span R s).comap f := by { rw [span_le, comap_coe], exact preimage_mono (subset_span), } /-- An induction principle for span membership. If `p` holds for 0 and all elements of `s`, and is preserved under addition and scalar multiplication, then `p` holds for all elements of the span of `s`. -/ @[elab_as_eliminator] lemma span_induction {p : M → Prop} (h : x ∈ span R s) (Hs : ∀ x ∈ s, p x) (H0 : p 0) (H1 : ∀ x y, p x → p y → p (x + y)) (H2 : ∀ (a:R) x, p x → p (a • x)) : p x := (@span_le _ _ _ _ _ _ ⟨p, H0, H1, H2⟩).2 Hs h section variables (R M) /-- `span` forms a Galois insertion with the coercion from submodule to set. -/ protected def gi : galois_insertion (@span R M _ _ _) coe := { choice := λ s _, span R s, gc := λ s t, span_le, le_l_u := λ s, subset_span, choice_eq := λ s h, rfl } end @[simp] lemma span_empty : span R (∅ : set M) = ⊥ := (submodule.gi R M).gc.l_bot @[simp] lemma span_univ : span R (univ : set M) = ⊤ := eq_top_iff.2 $ le_def.2 $ subset_span lemma span_union (s t : set M) : span R (s ∪ t) = span R s ⊔ span R t := (submodule.gi R M).gc.l_sup lemma span_Union {ι} (s : ι → set M) : span R (⋃ i, s i) = ⨆ i, span R (s i) := (submodule.gi R M).gc.l_supr lemma span_eq_supr_of_singleton_spans (s : set M) : span R s = ⨆ x ∈ s, span R {x} := by simp only [←span_Union, set.bUnion_of_singleton s] @[simp] theorem coe_supr_of_directed {ι} [hι : nonempty ι] (S : ι → submodule R M) (H : directed (≤) S) : ((supr S : submodule R M) : set M) = ⋃ i, S i := begin refine subset.antisymm _ (Union_subset $ le_supr S), suffices : (span R (⋃ i, (S i : set M)) : set M) ⊆ ⋃ (i : ι), ↑(S i), by simpa only [span_Union, span_eq] using this, refine (λ x hx, span_induction hx (λ _, id) _ _ _); simp only [mem_Union, exists_imp_distrib], { exact hι.elim (λ i, ⟨i, (S i).zero_mem⟩) }, { intros x y i hi j hj, rcases H i j with ⟨k, ik, jk⟩, exact ⟨k, add_mem _ (ik hi) (jk hj)⟩ }, { exact λ a x i hi, ⟨i, smul_mem _ a hi⟩ }, end lemma mem_sup_left {S T : submodule R M} : ∀ {x : M}, x ∈ S → x ∈ S ⊔ T := show S ≤ S ⊔ T, from le_sup_left lemma mem_sup_right {S T : submodule R M} : ∀ {x : M}, x ∈ T → x ∈ S ⊔ T := show T ≤ S ⊔ T, from le_sup_right lemma mem_supr_of_mem {ι : Sort*} {b : M} {p : ι → submodule R M} (i : ι) (h : b ∈ p i) : b ∈ (⨆i, p i) := have p i ≤ (⨆i, p i) := le_supr p i, @this b h lemma sum_mem_bsupr {ι : Type*} {s : finset ι} {f : ι → M} {p : ι → submodule R M} (h : ∀ i ∈ s, f i ∈ p i) : ∑ i in s, f i ∈ ⨆ i ∈ s, p i := sum_mem _ $ λ i hi, mem_supr_of_mem i $ mem_supr_of_mem hi (h i hi) lemma sum_mem_supr {ι : Type*} [fintype ι] {f : ι → M} {p : ι → submodule R M} (h : ∀ i, f i ∈ p i) : ∑ i, f i ∈ ⨆ i, p i := sum_mem _ $ λ i hi, mem_supr_of_mem i (h i) lemma mem_Sup_of_mem {S : set (submodule R M)} {s : submodule R M} (hs : s ∈ S) : ∀ {x : M}, x ∈ s → x ∈ Sup S := show s ≤ Sup S, from le_Sup hs @[simp] theorem mem_supr_of_directed {ι} [nonempty ι] (S : ι → submodule R M) (H : directed (≤) S) {x} : x ∈ supr S ↔ ∃ i, x ∈ S i := by { rw [← mem_coe, coe_supr_of_directed S H, mem_Union], refl } theorem mem_Sup_of_directed {s : set (submodule R M)} {z} (hs : s.nonempty) (hdir : directed_on (≤) s) : z ∈ Sup s ↔ ∃ y ∈ s, z ∈ y := begin haveI : nonempty s := hs.to_subtype, simp only [Sup_eq_supr', mem_supr_of_directed _ hdir.directed_coe, set_coe.exists, subtype.coe_mk] end section variables {p p'} lemma mem_sup : x ∈ p ⊔ p' ↔ ∃ (y ∈ p) (z ∈ p'), y + z = x := ⟨λ h, begin rw [← span_eq p, ← span_eq p', ← span_union] at h, apply span_induction h, { rintro y (h | h), { exact ⟨y, h, 0, by simp, by simp⟩ }, { exact ⟨0, by simp, y, h, by simp⟩ } }, { exact ⟨0, by simp, 0, by simp⟩ }, { rintro _ _ ⟨y₁, hy₁, z₁, hz₁, rfl⟩ ⟨y₂, hy₂, z₂, hz₂, rfl⟩, exact ⟨_, add_mem _ hy₁ hy₂, _, add_mem _ hz₁ hz₂, by simp [add_assoc]; cc⟩ }, { rintro a _ ⟨y, hy, z, hz, rfl⟩, exact ⟨_, smul_mem _ a hy, _, smul_mem _ a hz, by simp [smul_add]⟩ } end, by rintro ⟨y, hy, z, hz, rfl⟩; exact add_mem _ ((le_sup_left : p ≤ p ⊔ p') hy) ((le_sup_right : p' ≤ p ⊔ p') hz)⟩ lemma mem_sup' : x ∈ p ⊔ p' ↔ ∃ (y : p) (z : p'), (y:M) + z = x := mem_sup.trans $ by simp only [submodule.exists, coe_mk] end notation R`∙`:1000 x := span R (@singleton _ _ set.has_singleton x) lemma mem_span_singleton_self (x : M) : x ∈ R ∙ x := subset_span rfl lemma nontrivial_span_singleton {x : M} (h : x ≠ 0) : nontrivial (R ∙ x) := ⟨begin use [0, x, submodule.mem_span_singleton_self x], intros H, rw [eq_comm, submodule.mk_eq_zero] at H, exact h H end⟩ lemma mem_span_singleton {y : M} : x ∈ (R ∙ y) ↔ ∃ a:R, a • y = x := ⟨λ h, begin apply span_induction h, { rintro y (rfl|⟨⟨⟩⟩), exact ⟨1, by simp⟩ }, { exact ⟨0, by simp⟩ }, { rintro _ _ ⟨a, rfl⟩ ⟨b, rfl⟩, exact ⟨a + b, by simp [add_smul]⟩ }, { rintro a _ ⟨b, rfl⟩, exact ⟨a * b, by simp [smul_smul]⟩ } end, by rintro ⟨a, y, rfl⟩; exact smul_mem _ _ (subset_span $ by simp)⟩ lemma le_span_singleton_iff {s : submodule R M} {v₀ : M} : s ≤ (R ∙ v₀) ↔ ∀ v ∈ s, ∃ r : R, r • v₀ = v := by simp_rw [le_def', mem_span_singleton] @[simp] lemma span_zero_singleton : (R ∙ (0:M)) = ⊥ := by { ext, simp [mem_span_singleton, eq_comm] } lemma span_singleton_eq_range (y : M) : ↑(R ∙ y) = range ((• y) : R → M) := set.ext $ λ x, mem_span_singleton lemma span_singleton_smul_le (r : R) (x : M) : (R ∙ (r • x)) ≤ R ∙ x := begin rw [span_le, set.singleton_subset_iff, mem_coe], exact smul_mem _ _ (mem_span_singleton_self _) end lemma span_singleton_smul_eq {K E : Type*} [division_ring K] [add_comm_group E] [module K E] {r : K} (x : E) (hr : r ≠ 0) : (K ∙ (r • x)) = K ∙ x := begin refine le_antisymm (span_singleton_smul_le r x) _, convert span_singleton_smul_le r⁻¹ (r • x), exact (inv_smul_smul' hr _).symm end lemma disjoint_span_singleton {K E : Type*} [division_ring K] [add_comm_group E] [module K E] {s : submodule K E} {x : E} : disjoint s (K ∙ x) ↔ (x ∈ s → x = 0) := begin refine disjoint_def.trans ⟨λ H hx, H x hx $ subset_span $ mem_singleton x, _⟩, assume H y hy hyx, obtain ⟨c, hc⟩ := mem_span_singleton.1 hyx, subst y, classical, by_cases hc : c = 0, by simp only [hc, zero_smul], rw [s.smul_mem_iff hc] at hy, rw [H hy, smul_zero] end lemma disjoint_span_singleton' {K E : Type*} [division_ring K] [add_comm_group E] [module K E] {p : submodule K E} {x : E} (x0 : x ≠ 0) : disjoint p (K ∙ x) ↔ x ∉ p := disjoint_span_singleton.trans ⟨λ h₁ h₂, x0 (h₁ h₂), λ h₁ h₂, (h₁ h₂).elim⟩ lemma mem_span_insert {y} : x ∈ span R (insert y s) ↔ ∃ (a:R) (z ∈ span R s), x = a • y + z := begin simp only [← union_singleton, span_union, mem_sup, mem_span_singleton, exists_prop, exists_exists_eq_and], rw [exists_comm], simp only [eq_comm, add_comm, exists_and_distrib_left] end lemma span_insert_eq_span (h : x ∈ span R s) : span R (insert x s) = span R s := span_eq_of_le _ (set.insert_subset.mpr ⟨h, subset_span⟩) (span_mono $ subset_insert _ _) lemma span_span : span R (span R s : set M) = span R s := span_eq _ lemma span_eq_bot : span R (s : set M) = ⊥ ↔ ∀ x ∈ s, (x:M) = 0 := eq_bot_iff.trans ⟨ λ H x h, (mem_bot R).1 $ H $ subset_span h, λ H, span_le.2 (λ x h, (mem_bot R).2 $ H x h)⟩ @[simp] lemma span_singleton_eq_bot : (R ∙ x) = ⊥ ↔ x = 0 := span_eq_bot.trans $ by simp @[simp] lemma span_zero : span R (0 : set M) = ⊥ := by rw [←singleton_zero, span_singleton_eq_bot] @[simp] lemma span_image (f : M →ₗ[R] M₂) : span R (f '' s) = map f (span R s) := span_eq_of_le _ (image_subset _ subset_span) $ map_le_iff_le_comap.2 $ span_le.2 $ image_subset_iff.1 subset_span lemma apply_mem_span_image_of_mem_span (f : M →ₗ[R] M₂) {x : M} {s : set M} (h : x ∈ submodule.span R s) : f x ∈ submodule.span R (f '' s) := begin rw submodule.span_image, exact submodule.mem_map_of_mem h end /-- `f` is an explicit argument so we can `apply` this theorem and obtain `h` as a new goal. -/ lemma not_mem_span_of_apply_not_mem_span_image (f : M →ₗ[R] M₂) {x : M} {s : set M} (h : f x ∉ submodule.span R (f '' s)) : x ∉ submodule.span R s := not.imp h (apply_mem_span_image_of_mem_span f) lemma supr_eq_span {ι : Sort w} (p : ι → submodule R M) : (⨆ (i : ι), p i) = submodule.span R (⋃ (i : ι), ↑(p i)) := le_antisymm (supr_le $ assume i, subset.trans (assume m hm, set.mem_Union.mpr ⟨i, hm⟩) subset_span) (span_le.mpr $ Union_subset_iff.mpr $ assume i m hm, mem_supr_of_mem i hm) lemma span_singleton_le_iff_mem (m : M) (p : submodule R M) : (R ∙ m) ≤ p ↔ m ∈ p := by rw [span_le, singleton_subset_iff, mem_coe] lemma singleton_span_is_compact_element (x : M) : complete_lattice.is_compact_element (span R {x} : submodule R M) := begin rw complete_lattice.is_compact_element_iff_le_of_directed_Sup_le, intros d hemp hdir hsup, have : x ∈ Sup d, from (le_def.mp hsup) (mem_span_singleton_self x), obtain ⟨y, ⟨hyd, hxy⟩⟩ := (mem_Sup_of_directed hemp hdir).mp this, exact ⟨y, ⟨hyd, by simpa only [span_le, singleton_subset_iff]⟩⟩, end instance : is_compactly_generated (submodule R M) := ⟨λ s, ⟨(λ x, span R {x}) '' s, ⟨λ t ht, begin rcases (set.mem_image _ _ _).1 ht with ⟨x, hx, rfl⟩, apply singleton_span_is_compact_element, end, by rw [Sup_eq_supr, supr_image, ←span_eq_supr_of_singleton_spans, span_eq]⟩⟩⟩ lemma lt_add_iff_not_mem {I : submodule R M} {a : M} : I < I + (R ∙ a) ↔ a ∉ I := begin split, { intro h, by_contra akey, have h1 : I + (R ∙ a) ≤ I, { simp only [add_eq_sup, sup_le_iff], split, { exact le_refl I, }, { exact (span_singleton_le_iff_mem a I).mpr akey, } }, have h2 := gt_of_ge_of_gt h1 h, exact lt_irrefl I h2, }, { intro h, apply lt_iff_le_and_exists.mpr, split, simp only [add_eq_sup, le_sup_left], use a, split, swap, { assumption, }, { have : (R ∙ a) ≤ I + (R ∙ a) := le_sup_right, exact this (mem_span_singleton_self a), } }, end lemma mem_supr {ι : Sort w} (p : ι → submodule R M) {m : M} : (m ∈ ⨆ i, p i) ↔ (∀ N, (∀ i, p i ≤ N) → m ∈ N) := begin rw [← span_singleton_le_iff_mem, le_supr_iff], simp only [span_singleton_le_iff_mem], end section open_locale classical /-- For every element in the span of a set, there exists a finite subset of the set such that the element is contained in the span of the subset. -/ lemma mem_span_finite_of_mem_span {S : set M} {x : M} (hx : x ∈ span R S) : ∃ T : finset M, ↑T ⊆ S ∧ x ∈ span R (T : set M) := begin refine span_induction hx (λ x hx, _) _ _ _, { refine ⟨{x}, _, _⟩, { rwa [finset.coe_singleton, set.singleton_subset_iff] }, { rw finset.coe_singleton, exact submodule.mem_span_singleton_self x } }, { use ∅, simp }, { rintros x y ⟨X, hX, hxX⟩ ⟨Y, hY, hyY⟩, refine ⟨X ∪ Y, _, _⟩, { rw finset.coe_union, exact set.union_subset hX hY }, rw [finset.coe_union, span_union, mem_sup], exact ⟨x, hxX, y, hyY, rfl⟩, }, { rintros a x ⟨T, hT, h2⟩, exact ⟨T, hT, smul_mem _ _ h2⟩ } end end /-- The product of two submodules is a submodule. -/ def prod : submodule R (M × M₂) := { carrier := set.prod p q, smul_mem' := by rintro a ⟨x, y⟩ ⟨hx, hy⟩; exact ⟨smul_mem _ a hx, smul_mem _ a hy⟩, .. p.to_add_submonoid.prod q.to_add_submonoid } @[simp] lemma prod_coe : (prod p q : set (M × M₂)) = set.prod p q := rfl @[simp] lemma mem_prod {p : submodule R M} {q : submodule R M₂} {x : M × M₂} : x ∈ prod p q ↔ x.1 ∈ p ∧ x.2 ∈ q := set.mem_prod lemma span_prod_le (s : set M) (t : set M₂) : span R (set.prod s t) ≤ prod (span R s) (span R t) := span_le.2 $ set.prod_mono subset_span subset_span @[simp] lemma prod_top : (prod ⊤ ⊤ : submodule R (M × M₂)) = ⊤ := by ext; simp @[simp] lemma prod_bot : (prod ⊥ ⊥ : submodule R (M × M₂)) = ⊥ := by ext ⟨x, y⟩; simp [prod.zero_eq_mk] lemma prod_mono {p p' : submodule R M} {q q' : submodule R M₂} : p ≤ p' → q ≤ q' → prod p q ≤ prod p' q' := prod_mono @[simp] lemma prod_inf_prod : prod p q ⊓ prod p' q' = prod (p ⊓ p') (q ⊓ q') := coe_injective set.prod_inter_prod @[simp] lemma prod_sup_prod : prod p q ⊔ prod p' q' = prod (p ⊔ p') (q ⊔ q') := begin refine le_antisymm (sup_le (prod_mono le_sup_left le_sup_left) (prod_mono le_sup_right le_sup_right)) _, simp [le_def'], intros xx yy hxx hyy, rcases mem_sup.1 hxx with ⟨x, hx, x', hx', rfl⟩, rcases mem_sup.1 hyy with ⟨y, hy, y', hy', rfl⟩, refine mem_sup.2 ⟨(x, y), ⟨hx, hy⟩, (x', y'), ⟨hx', hy'⟩, rfl⟩ end end add_comm_monoid variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] variables (p p' : submodule R M) (q q' : submodule R M₂) variables {r : R} {x y : M} open set @[simp] lemma neg_coe : -(p : set M) = p := set.ext $ λ x, p.neg_mem_iff @[simp] protected lemma map_neg (f : M →ₗ[R] M₂) : map (-f) p = map f p := ext $ λ y, ⟨λ ⟨x, hx, hy⟩, hy ▸ ⟨-x, neg_mem _ hx, f.map_neg x⟩, λ ⟨x, hx, hy⟩, hy ▸ ⟨-x, neg_mem _ hx, ((-f).map_neg _).trans (neg_neg (f x))⟩⟩ @[simp] lemma span_neg (s : set M) : span R (-s) = span R s := calc span R (-s) = span R ((-linear_map.id : M →ₗ[R] M) '' s) : by simp ... = map (-linear_map.id) (span R s) : (map_span _ _).symm ... = span R s : by simp lemma mem_span_insert' {y} {s : set M} : x ∈ span R (insert y s) ↔ ∃(a:R), x + a • y ∈ span R s := begin rw mem_span_insert, split, { rintro ⟨a, z, hz, rfl⟩, exact ⟨-a, by simp [hz, add_assoc]⟩ }, { rintro ⟨a, h⟩, exact ⟨-a, _, h, by simp [add_comm, add_left_comm]⟩ } end -- TODO(Mario): Factor through add_subgroup /-- The equivalence relation associated to a submodule `p`, defined by `x ≈ y` iff `y - x ∈ p`. -/ def quotient_rel : setoid M := ⟨λ x y, x - y ∈ p, λ x, by simp, λ x y h, by simpa using neg_mem _ h, λ x y z h₁ h₂, by simpa [sub_eq_add_neg, add_left_comm, add_assoc] using add_mem _ h₁ h₂⟩ /-- The quotient of a module `M` by a submodule `p ⊆ M`. -/ def quotient : Type* := quotient (quotient_rel p) namespace quotient /-- Map associating to an element of `M` the corresponding element of `M/p`, when `p` is a submodule of `M`. -/ def mk {p : submodule R M} : M → quotient p := quotient.mk' @[simp] theorem mk_eq_mk {p : submodule R M} (x : M) : (quotient.mk x : quotient p) = mk x := rfl @[simp] theorem mk'_eq_mk {p : submodule R M} (x : M) : (quotient.mk' x : quotient p) = mk x := rfl @[simp] theorem quot_mk_eq_mk {p : submodule R M} (x : M) : (quot.mk _ x : quotient p) = mk x := rfl protected theorem eq {x y : M} : (mk x : quotient p) = mk y ↔ x - y ∈ p := quotient.eq' instance : has_zero (quotient p) := ⟨mk 0⟩ instance : inhabited (quotient p) := ⟨0⟩ @[simp] theorem mk_zero : mk 0 = (0 : quotient p) := rfl @[simp] theorem mk_eq_zero : (mk x : quotient p) = 0 ↔ x ∈ p := by simpa using (quotient.eq p : mk x = 0 ↔ _) instance : has_add (quotient p) := ⟨λ a b, quotient.lift_on₂' a b (λ a b, mk (a + b)) $ λ a₁ a₂ b₁ b₂ h₁ h₂, (quotient.eq p).2 $ by simpa [sub_eq_add_neg, add_left_comm, add_comm] using add_mem p h₁ h₂⟩ @[simp] theorem mk_add : (mk (x + y) : quotient p) = mk x + mk y := rfl instance : has_neg (quotient p) := ⟨λ a, quotient.lift_on' a (λ a, mk (-a)) $ λ a b h, (quotient.eq p).2 $ by simpa using neg_mem p h⟩ @[simp] theorem mk_neg : (mk (-x) : quotient p) = -mk x := rfl instance : has_sub (quotient p) := ⟨λ a b, quotient.lift_on₂' a b (λ a b, mk (a - b)) $ λ a₁ a₂ b₁ b₂ h₁ h₂, (quotient.eq p).2 $ by simpa [sub_eq_add_neg, add_left_comm, add_comm] using add_mem p h₁ (neg_mem p h₂)⟩ @[simp] theorem mk_sub : (mk (x - y) : quotient p) = mk x - mk y := rfl instance : add_comm_group (quotient p) := by refine {zero := 0, add := (+), neg := has_neg.neg, sub := has_sub.sub, sub_eq_add_neg := _, ..}; repeat {rintro ⟨⟩}; simp [-mk_zero, ← mk_zero p, -mk_add, ← mk_add p, -mk_neg, ← mk_neg p, -mk_sub, ← mk_sub p, sub_eq_add_neg]; cc instance : has_scalar R (quotient p) := ⟨λ a x, quotient.lift_on' x (λ x, mk (a • x)) $ λ x y h, (quotient.eq p).2 $ by simpa [smul_sub] using smul_mem p a h⟩ @[simp] theorem mk_smul : (mk (r • x) : quotient p) = r • mk x := rfl instance : semimodule R (quotient p) := semimodule.of_core $ by refine {smul := (•), ..}; repeat {rintro ⟨⟩ <|> intro}; simp [smul_add, add_smul, smul_smul, -mk_add, (mk_add p).symm, -mk_smul, (mk_smul p).symm] lemma mk_surjective : function.surjective (@mk _ _ _ _ _ p) := by { rintros ⟨x⟩, exact ⟨x, rfl⟩ } lemma nontrivial_of_lt_top (h : p < ⊤) : nontrivial (p.quotient) := begin obtain ⟨x, _, not_mem_s⟩ := exists_of_lt h, refine ⟨⟨mk x, 0, _⟩⟩, simpa using not_mem_s end end quotient lemma quot_hom_ext ⦃f g : quotient p →ₗ[R] M₂⦄ (h : ∀ x, f (quotient.mk x) = g (quotient.mk x)) : f = g := linear_map.ext $ λ x, quotient.induction_on' x h end submodule namespace submodule variables [field K] variables [add_comm_group V] [vector_space K V] variables [add_comm_group V₂] [vector_space K V₂] lemma comap_smul (f : V →ₗ[K] V₂) (p : submodule K V₂) (a : K) (h : a ≠ 0) : p.comap (a • f) = p.comap f := by ext b; simp only [submodule.mem_comap, p.smul_mem_iff h, linear_map.smul_apply] lemma map_smul (f : V →ₗ[K] V₂) (p : submodule K V) (a : K) (h : a ≠ 0) : p.map (a • f) = p.map f := le_antisymm begin rw [map_le_iff_le_comap, comap_smul f _ a h, ← map_le_iff_le_comap], exact le_refl _ end begin rw [map_le_iff_le_comap, ← comap_smul f _ a h, ← map_le_iff_le_comap], exact le_refl _ end lemma comap_smul' (f : V →ₗ[K] V₂) (p : submodule K V₂) (a : K) : p.comap (a • f) = (⨅ h : a ≠ 0, p.comap f) := by classical; by_cases a = 0; simp [h, comap_smul] lemma map_smul' (f : V →ₗ[K] V₂) (p : submodule K V) (a : K) : p.map (a • f) = (⨆ h : a ≠ 0, p.map f) := by classical; by_cases a = 0; simp [h, map_smul] end submodule /-! ### Properties of linear maps -/ namespace linear_map section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] include R open submodule /-- If two linear maps are equal on a set `s`, then they are equal on `submodule.span s`. See also `linear_map.eq_on_span'` for a version using `set.eq_on`. -/ lemma eq_on_span {s : set M} {f g : M →ₗ[R] M₂} (H : set.eq_on f g s) ⦃x⦄ (h : x ∈ span R s) : f x = g x := by apply span_induction h H; simp {contextual := tt} /-- If two linear maps are equal on a set `s`, then they are equal on `submodule.span s`. This version uses `set.eq_on`, and the hidden argument will expand to `h : x ∈ (span R s : set M)`. See `linear_map.eq_on_span` for a version that takes `h : x ∈ span R s` as an argument. -/ lemma eq_on_span' {s : set M} {f g : M →ₗ[R] M₂} (H : set.eq_on f g s) : set.eq_on f g (span R s : set M) := eq_on_span H /-- If `s` generates the whole semimodule and linear maps `f`, `g` are equal on `s`, then they are equal. -/ lemma ext_on {s : set M} {f g : M →ₗ[R] M₂} (hv : span R s = ⊤) (h : set.eq_on f g s) : f = g := linear_map.ext (λ x, eq_on_span h (eq_top_iff'.1 hv _)) /-- If the range of `v : ι → M` generates the whole semimodule and linear maps `f`, `g` are equal at each `v i`, then they are equal. -/ lemma ext_on_range {v : ι → M} {f g : M →ₗ[R] M₂} (hv : span R (set.range v) = ⊤) (h : ∀i, f (v i) = g (v i)) : f = g := ext_on hv (set.forall_range_iff.2 h) section finsupp variables {γ : Type*} [has_zero γ] @[simp] lemma map_finsupp_sum (f : M →ₗ[R] M₂) {t : ι →₀ γ} {g : ι → γ → M} : f (t.sum g) = t.sum (λ i d, f (g i d)) := f.map_sum lemma coe_finsupp_sum (t : ι →₀ γ) (g : ι → γ → M →ₗ[R] M₂) : ⇑(t.sum g) = t.sum (λ i d, g i d) := coe_fn_sum _ _ @[simp] lemma finsupp_sum_apply (t : ι →₀ γ) (g : ι → γ → M →ₗ[R] M₂) (b : M) : (t.sum g) b = t.sum (λ i d, g i d b) := sum_apply _ _ _ end finsupp section dfinsupp variables {γ : ι → Type*} [decidable_eq ι] [Π i, has_zero (γ i)] [Π i (x : γ i), decidable (x ≠ 0)] @[simp] lemma map_dfinsupp_sum (f : M →ₗ[R] M₂) {t : Π₀ i, γ i} {g : Π i, γ i → M} : f (t.sum g) = t.sum (λ i d, f (g i d)) := f.map_sum lemma coe_dfinsupp_sum (t : Π₀ i, γ i) (g : Π i, γ i → M →ₗ[R] M₂) : ⇑(t.sum g) = t.sum (λ i d, g i d) := coe_fn_sum _ _ @[simp] lemma dfinsupp_sum_apply (t : Π₀ i, γ i) (g : Π i, γ i → M →ₗ[R] M₂) (b : M) : (t.sum g) b = t.sum (λ i d, g i d b) := sum_apply _ _ _ end dfinsupp theorem map_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (h p') : submodule.map (cod_restrict p f h) p' = comap p.subtype (p'.map f) := submodule.ext $ λ ⟨x, hx⟩, by simp [subtype.ext_iff_val] theorem comap_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf p') : submodule.comap (cod_restrict p f hf) p' = submodule.comap f (map p.subtype p') := submodule.ext $ λ x, ⟨λ h, ⟨⟨_, hf x⟩, h, rfl⟩, by rintro ⟨⟨_, _⟩, h, ⟨⟩⟩; exact h⟩ /-- The range of a linear map `f : M → M₂` is a submodule of `M₂`. -/ def range (f : M →ₗ[R] M₂) : submodule R M₂ := map f ⊤ theorem range_coe (f : M →ₗ[R] M₂) : (range f : set M₂) = set.range f := set.image_univ @[simp] theorem mem_range {f : M →ₗ[R] M₂} : ∀ {x}, x ∈ range f ↔ ∃ y, f y = x := set.ext_iff.1 (range_coe f) theorem mem_range_self (f : M →ₗ[R] M₂) (x : M) : f x ∈ f.range := mem_range.2 ⟨x, rfl⟩ @[simp] theorem range_id : range (linear_map.id : M →ₗ[R] M) = ⊤ := map_id _ theorem range_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : range (g.comp f) = map g (range f) := map_comp _ _ _ theorem range_comp_le_range (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : range (g.comp f) ≤ range g := by rw range_comp; exact map_mono le_top theorem range_eq_top {f : M →ₗ[R] M₂} : range f = ⊤ ↔ surjective f := by rw [submodule.ext'_iff, range_coe, top_coe, set.range_iff_surjective] lemma range_le_iff_comap {f : M →ₗ[R] M₂} {p : submodule R M₂} : range f ≤ p ↔ comap f p = ⊤ := by rw [range, map_le_iff_le_comap, eq_top_iff] lemma map_le_range {f : M →ₗ[R] M₂} {p : submodule R M} : map f p ≤ range f := map_mono le_top /-- Restrict the codomain of a linear map `f` to `f.range`. This is the bundled version of `set.range_factorization`. -/ @[reducible] def range_restrict (f : M →ₗ[R] M₂) : M →ₗ[R] f.range := f.cod_restrict f.range f.mem_range_self section variables (R) (M) /-- Given an element `x` of a module `M` over `R`, the natural map from `R` to scalar multiples of `x`.-/ def to_span_singleton (x : M) : R →ₗ[R] M := linear_map.id.smul_right x /-- The range of `to_span_singleton x` is the span of `x`.-/ lemma span_singleton_eq_range (x : M) : (R ∙ x) = (to_span_singleton R M x).range := submodule.ext $ λ y, by {refine iff.trans _ mem_range.symm, exact mem_span_singleton } lemma to_span_singleton_one (x : M) : to_span_singleton R M x 1 = x := one_smul _ _ end /-- The kernel of a linear map `f : M → M₂` is defined to be `comap f ⊥`. This is equivalent to the set of `x : M` such that `f x = 0`. The kernel is a submodule of `M`. -/ def ker (f : M →ₗ[R] M₂) : submodule R M := comap f ⊥ @[simp] theorem mem_ker {f : M →ₗ[R] M₂} {y} : y ∈ ker f ↔ f y = 0 := mem_bot R @[simp] theorem ker_id : ker (linear_map.id : M →ₗ[R] M) = ⊥ := rfl @[simp] theorem map_coe_ker (f : M →ₗ[R] M₂) (x : ker f) : f x = 0 := mem_ker.1 x.2 lemma comp_ker_subtype (f : M →ₗ[R] M₂) : f.comp f.ker.subtype = 0 := linear_map.ext $ λ x, suffices f x = 0, by simp [this], mem_ker.1 x.2 theorem ker_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : ker (g.comp f) = comap f (ker g) := rfl theorem ker_le_ker_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : ker f ≤ ker (g.comp f) := by rw ker_comp; exact comap_mono bot_le theorem disjoint_ker {f : M →ₗ[R] M₂} {p : submodule R M} : disjoint p (ker f) ↔ ∀ x ∈ p, f x = 0 → x = 0 := by simp [disjoint_def] theorem ker_eq_bot' {f : M →ₗ[R] M₂} : ker f = ⊥ ↔ (∀ m, f m = 0 → m = 0) := by simpa [disjoint] using @disjoint_ker _ _ _ _ _ _ _ _ f ⊤ theorem ker_eq_bot_of_inverse {f : M →ₗ[R] M₂} {g : M₂ →ₗ[R] M} (h : g.comp f = id) : ker f = ⊥ := ker_eq_bot'.2 $ λ m hm, by rw [← id_apply m, ← h, comp_apply, hm, g.map_zero] lemma le_ker_iff_map {f : M →ₗ[R] M₂} {p : submodule R M} : p ≤ ker f ↔ map f p = ⊥ := by rw [ker, eq_bot_iff, map_le_iff_le_comap] lemma ker_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf) : ker (cod_restrict p f hf) = ker f := by rw [ker, comap_cod_restrict, map_bot]; refl lemma range_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf) : range (cod_restrict p f hf) = comap p.subtype f.range := map_cod_restrict _ _ _ _ lemma ker_restrict {p : submodule R M} {f : M →ₗ[R] M} (hf : ∀ x : M, x ∈ p → f x ∈ p) : ker (f.restrict hf) = (f.dom_restrict p).ker := by rw [restrict_eq_cod_restrict_dom_restrict, ker_cod_restrict] lemma map_comap_eq (f : M →ₗ[R] M₂) (q : submodule R M₂) : map f (comap f q) = range f ⊓ q := le_antisymm (le_inf (map_mono le_top) (map_comap_le _ _)) $ by rintro _ ⟨⟨x, _, rfl⟩, hx⟩; exact ⟨x, hx, rfl⟩ lemma map_comap_eq_self {f : M →ₗ[R] M₂} {q : submodule R M₂} (h : q ≤ range f) : map f (comap f q) = q := by rwa [map_comap_eq, inf_eq_right] @[simp] theorem ker_zero : ker (0 : M →ₗ[R] M₂) = ⊤ := eq_top_iff'.2 $ λ x, by simp @[simp] theorem range_zero : range (0 : M →ₗ[R] M₂) = ⊥ := submodule.map_zero _ theorem ker_eq_top {f : M →ₗ[R] M₂} : ker f = ⊤ ↔ f = 0 := ⟨λ h, ext $ λ x, mem_ker.1 $ h.symm ▸ trivial, λ h, h.symm ▸ ker_zero⟩ lemma range_le_bot_iff (f : M →ₗ[R] M₂) : range f ≤ ⊥ ↔ f = 0 := by rw [range_le_iff_comap]; exact ker_eq_top theorem range_eq_bot {f : M →ₗ[R] M₂} : range f = ⊥ ↔ f = 0 := by rw [← range_le_bot_iff, le_bot_iff] lemma range_le_ker_iff {f : M →ₗ[R] M₂} {g : M₂ →ₗ[R] M₃} : range f ≤ ker g ↔ g.comp f = 0 := ⟨λ h, ker_eq_top.1 $ eq_top_iff'.2 $ λ x, h $ mem_map_of_mem trivial, λ h x hx, mem_ker.2 $ exists.elim hx $ λ y ⟨_, hy⟩, by rw [←hy, ←comp_apply, h, zero_apply]⟩ theorem comap_le_comap_iff {f : M →ₗ[R] M₂} (hf : range f = ⊤) {p p'} : comap f p ≤ comap f p' ↔ p ≤ p' := ⟨λ H x hx, by rcases range_eq_top.1 hf x with ⟨y, hy, rfl⟩; exact H hx, comap_mono⟩ theorem comap_injective {f : M →ₗ[R] M₂} (hf : range f = ⊤) : injective (comap f) := λ p p' h, le_antisymm ((comap_le_comap_iff hf).1 (le_of_eq h)) ((comap_le_comap_iff hf).1 (ge_of_eq h)) theorem ker_eq_bot_of_injective {f : M →ₗ[R] M₂} (hf : injective f) : ker f = ⊥ := begin have : disjoint ⊤ f.ker, by { rw [disjoint_ker, ← map_zero f], exact λ x hx H, hf H }, simpa [disjoint] end end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] include R open submodule lemma comap_map_eq (f : M →ₗ[R] M₂) (p : submodule R M) : comap f (map f p) = p ⊔ ker f := begin refine le_antisymm _ (sup_le (le_comap_map _ _) (comap_mono bot_le)), rintro x ⟨y, hy, e⟩, exact mem_sup.2 ⟨y, hy, x - y, by simpa using sub_eq_zero.2 e.symm, by simp⟩ end lemma comap_map_eq_self {f : M →ₗ[R] M₂} {p : submodule R M} (h : ker f ≤ p) : comap f (map f p) = p := by rw [comap_map_eq, sup_of_le_left h] theorem map_le_map_iff (f : M →ₗ[R] M₂) {p p'} : map f p ≤ map f p' ↔ p ≤ p' ⊔ ker f := by rw [map_le_iff_le_comap, comap_map_eq] theorem map_le_map_iff' {f : M →ₗ[R] M₂} (hf : ker f = ⊥) {p p'} : map f p ≤ map f p' ↔ p ≤ p' := by rw [map_le_map_iff, hf, sup_bot_eq] theorem map_injective {f : M →ₗ[R] M₂} (hf : ker f = ⊥) : injective (map f) := λ p p' h, le_antisymm ((map_le_map_iff' hf).1 (le_of_eq h)) ((map_le_map_iff' hf).1 (ge_of_eq h)) theorem map_eq_top_iff {f : M →ₗ[R] M₂} (hf : range f = ⊤) {p : submodule R M} : p.map f = ⊤ ↔ p ⊔ f.ker = ⊤ := by simp_rw [← top_le_iff, ← hf, range, map_le_map_iff] end add_comm_group section ring variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] variables {f : M →ₗ[R] M₂} include R open submodule theorem sub_mem_ker_iff {x y} : x - y ∈ f.ker ↔ f x = f y := by rw [mem_ker, map_sub, sub_eq_zero] theorem disjoint_ker' {p : submodule R M} : disjoint p (ker f) ↔ ∀ x y ∈ p, f x = f y → x = y := disjoint_ker.trans ⟨λ H x y hx hy h, eq_of_sub_eq_zero $ H _ (sub_mem _ hx hy) (by simp [h]), λ H x h₁ h₂, H x 0 h₁ (zero_mem _) (by simpa using h₂)⟩ theorem inj_of_disjoint_ker {p : submodule R M} {s : set M} (h : s ⊆ p) (hd : disjoint p (ker f)) : ∀ x y ∈ s, f x = f y → x = y := λ x y hx hy, disjoint_ker'.1 hd _ _ (h hx) (h hy) theorem ker_eq_bot : ker f = ⊥ ↔ injective f := by simpa [disjoint] using @disjoint_ker' _ _ _ _ _ _ _ _ f ⊤ lemma ker_le_iff {p : submodule R M} : ker f ≤ p ↔ ∃ (y ∈ range f), f ⁻¹' {y} ⊆ p := begin split, { intros h, use 0, rw [← mem_coe, f.range_coe], exact ⟨⟨0, map_zero f⟩, h⟩, }, { rintros ⟨y, h₁, h₂⟩, rw le_def, intros z hz, simp only [mem_ker, mem_coe] at hz, rw [← mem_coe, f.range_coe, set.mem_range] at h₁, obtain ⟨x, hx⟩ := h₁, have hx' : x ∈ p, { exact h₂ hx, }, have hxz : z + x ∈ p, { apply h₂, simp [hx, hz], }, suffices : z + x - x ∈ p, { simpa only [this, add_sub_cancel], }, exact p.sub_mem hxz hx', }, end end ring section field variables [field K] variables [add_comm_group V] [vector_space K V] variables [add_comm_group V₂] [vector_space K V₂] lemma ker_smul (f : V →ₗ[K] V₂) (a : K) (h : a ≠ 0) : ker (a • f) = ker f := submodule.comap_smul f _ a h lemma ker_smul' (f : V →ₗ[K] V₂) (a : K) : ker (a • f) = ⨅(h : a ≠ 0), ker f := submodule.comap_smul' f _ a lemma range_smul (f : V →ₗ[K] V₂) (a : K) (h : a ≠ 0) : range (a • f) = range f := submodule.map_smul f _ a h lemma range_smul' (f : V →ₗ[K] V₂) (a : K) : range (a • f) = ⨆(h : a ≠ 0), range f := submodule.map_smul' f _ a lemma span_singleton_sup_ker_eq_top (f : V →ₗ[K] K) {x : V} (hx : f x ≠ 0) : (K ∙ x) ⊔ f.ker = ⊤ := eq_top_iff.2 (λ y hy, submodule.mem_sup.2 ⟨(f y * (f x)⁻¹) • x, submodule.mem_span_singleton.2 ⟨f y * (f x)⁻¹, rfl⟩, ⟨y - (f y * (f x)⁻¹) • x, by rw [linear_map.mem_ker, f.map_sub, f.map_smul, smul_eq_mul, mul_assoc, inv_mul_cancel hx, mul_one, sub_self], by simp only [add_sub_cancel'_right]⟩⟩) end field end linear_map namespace is_linear_map lemma is_linear_map_add [semiring R] [add_comm_monoid M] [semimodule R M] : is_linear_map R (λ (x : M × M), x.1 + x.2) := begin apply is_linear_map.mk, { intros x y, simp, cc }, { intros x y, simp [smul_add] } end lemma is_linear_map_sub {R M : Type*} [semiring R] [add_comm_group M] [semimodule R M]: is_linear_map R (λ (x : M × M), x.1 - x.2) := begin apply is_linear_map.mk, { intros x y, simp [add_comm, add_left_comm, sub_eq_add_neg] }, { intros x y, simp [smul_sub] } end end is_linear_map namespace submodule section add_comm_monoid variables {T : semiring R} [add_comm_monoid M] [add_comm_monoid M₂] variables [semimodule R M] [semimodule R M₂] variables (p p' : submodule R M) (q : submodule R M₂) include T open linear_map @[simp] theorem map_top (f : M →ₗ[R] M₂) : map f ⊤ = range f := rfl @[simp] theorem comap_bot (f : M →ₗ[R] M₂) : comap f ⊥ = ker f := rfl @[simp] theorem ker_subtype : p.subtype.ker = ⊥ := ker_eq_bot_of_injective $ λ x y, subtype.ext_val @[simp] theorem range_subtype : p.subtype.range = p := by simpa using map_comap_subtype p ⊤ lemma map_subtype_le (p' : submodule R p) : map p.subtype p' ≤ p := by simpa using (map_mono le_top : map p.subtype p' ≤ p.subtype.range) /-- Under the canonical linear map from a submodule `p` to the ambient space `M`, the image of the maximal submodule of `p` is just `p `. -/ @[simp] lemma map_subtype_top : map p.subtype (⊤ : submodule R p) = p := by simp @[simp] lemma comap_subtype_eq_top {p p' : submodule R M} : comap p.subtype p' = ⊤ ↔ p ≤ p' := eq_top_iff.trans $ map_le_iff_le_comap.symm.trans $ by rw [map_subtype_top] @[simp] lemma comap_subtype_self : comap p.subtype p = ⊤ := comap_subtype_eq_top.2 (le_refl _) @[simp] theorem ker_of_le (p p' : submodule R M) (h : p ≤ p') : (of_le h).ker = ⊥ := by rw [of_le, ker_cod_restrict, ker_subtype] lemma range_of_le (p q : submodule R M) (h : p ≤ q) : (of_le h).range = comap q.subtype p := by rw [← map_top, of_le, linear_map.map_cod_restrict, map_top, range_subtype] end add_comm_monoid section ring variables {T : ring R} [add_comm_group M] [add_comm_group M₂] [semimodule R M] [semimodule R M₂] variables (p p' : submodule R M) (q : submodule R M₂) include T open linear_map lemma disjoint_iff_comap_eq_bot {p q : submodule R M} : disjoint p q ↔ comap p.subtype q = ⊥ := by rw [eq_bot_iff, ← map_le_map_iff' p.ker_subtype, map_bot, map_comap_subtype, disjoint] /-- If `N ⊆ M` then submodules of `N` are the same as submodules of `M` contained in `N` -/ def map_subtype.rel_iso : submodule R p ≃o {p' : submodule R M // p' ≤ p} := { to_fun := λ p', ⟨map p.subtype p', map_subtype_le p _⟩, inv_fun := λ q, comap p.subtype q, left_inv := λ p', comap_map_eq_self $ by simp, right_inv := λ ⟨q, hq⟩, subtype.ext_val $ by simp [map_comap_subtype p, inf_of_le_right hq], map_rel_iff' := λ p₁ p₂, map_le_map_iff' (ker_subtype p) } /-- If `p ⊆ M` is a submodule, the ordering of submodules of `p` is embedded in the ordering of submodules of `M`. -/ def map_subtype.order_embedding : submodule R p ↪o submodule R M := (rel_iso.to_rel_embedding $ map_subtype.rel_iso p).trans (subtype.rel_embedding _ _) @[simp] lemma map_subtype_embedding_eq (p' : submodule R p) : map_subtype.order_embedding p p' = map p.subtype p' := rfl /-- The map from a module `M` to the quotient of `M` by a submodule `p` as a linear map. -/ def mkq : M →ₗ[R] p.quotient := ⟨quotient.mk, by simp, by simp⟩ @[simp] theorem mkq_apply (x : M) : p.mkq x = quotient.mk x := rfl /-- The map from the quotient of `M` by a submodule `p` to `M₂` induced by a linear map `f : M → M₂` vanishing on `p`, as a linear map. -/ def liftq (f : M →ₗ[R] M₂) (h : p ≤ f.ker) : p.quotient →ₗ[R] M₂ := ⟨λ x, _root_.quotient.lift_on' x f $ λ a b (ab : a - b ∈ p), eq_of_sub_eq_zero $ by simpa using h ab, by rintro ⟨x⟩ ⟨y⟩; exact f.map_add x y, by rintro a ⟨x⟩; exact f.map_smul a x⟩ @[simp] theorem liftq_apply (f : M →ₗ[R] M₂) {h} (x : M) : p.liftq f h (quotient.mk x) = f x := rfl @[simp] theorem liftq_mkq (f : M →ₗ[R] M₂) (h) : (p.liftq f h).comp p.mkq = f := by ext; refl @[simp] theorem range_mkq : p.mkq.range = ⊤ := eq_top_iff'.2 $ by rintro ⟨x⟩; exact ⟨x, trivial, rfl⟩ @[simp] theorem ker_mkq : p.mkq.ker = p := by ext; simp lemma le_comap_mkq (p' : submodule R p.quotient) : p ≤ comap p.mkq p' := by simpa using (comap_mono bot_le : p.mkq.ker ≤ comap p.mkq p') @[simp] theorem mkq_map_self : map p.mkq p = ⊥ := by rw [eq_bot_iff, map_le_iff_le_comap, comap_bot, ker_mkq]; exact le_refl _ @[simp] theorem comap_map_mkq : comap p.mkq (map p.mkq p') = p ⊔ p' := by simp [comap_map_eq, sup_comm] @[simp] theorem map_mkq_eq_top : map p.mkq p' = ⊤ ↔ p ⊔ p' = ⊤ := by simp only [map_eq_top_iff p.range_mkq, sup_comm, ker_mkq] /-- The map from the quotient of `M` by submodule `p` to the quotient of `M₂` by submodule `q` along `f : M → M₂` is linear. -/ def mapq (f : M →ₗ[R] M₂) (h : p ≤ comap f q) : p.quotient →ₗ[R] q.quotient := p.liftq (q.mkq.comp f) $ by simpa [ker_comp] using h @[simp] theorem mapq_apply (f : M →ₗ[R] M₂) {h} (x : M) : mapq p q f h (quotient.mk x) = quotient.mk (f x) := rfl theorem mapq_mkq (f : M →ₗ[R] M₂) {h} : (mapq p q f h).comp p.mkq = q.mkq.comp f := by ext x; refl theorem comap_liftq (f : M →ₗ[R] M₂) (h) : q.comap (p.liftq f h) = (q.comap f).map (mkq p) := le_antisymm (by rintro ⟨x⟩ hx; exact ⟨_, hx, rfl⟩) (by rw [map_le_iff_le_comap, ← comap_comp, liftq_mkq]; exact le_refl _) theorem map_liftq (f : M →ₗ[R] M₂) (h) (q : submodule R (quotient p)) : q.map (p.liftq f h) = (q.comap p.mkq).map f := le_antisymm (by rintro _ ⟨⟨x⟩, hxq, rfl⟩; exact ⟨x, hxq, rfl⟩) (by rintro _ ⟨x, hxq, rfl⟩; exact ⟨quotient.mk x, hxq, rfl⟩) theorem ker_liftq (f : M →ₗ[R] M₂) (h) : ker (p.liftq f h) = (ker f).map (mkq p) := comap_liftq _ _ _ _ theorem range_liftq (f : M →ₗ[R] M₂) (h) : range (p.liftq f h) = range f := map_liftq _ _ _ _ theorem ker_liftq_eq_bot (f : M →ₗ[R] M₂) (h) (h' : ker f ≤ p) : ker (p.liftq f h) = ⊥ := by rw [ker_liftq, le_antisymm h h', mkq_map_self] /-- The correspondence theorem for modules: there is an order isomorphism between submodules of the quotient of `M` by `p`, and submodules of `M` larger than `p`. -/ def comap_mkq.rel_iso : submodule R p.quotient ≃o {p' : submodule R M // p ≤ p'} := { to_fun := λ p', ⟨comap p.mkq p', le_comap_mkq p _⟩, inv_fun := λ q, map p.mkq q, left_inv := λ p', map_comap_eq_self $ by simp, right_inv := λ ⟨q, hq⟩, subtype.ext_val $ by simpa [comap_map_mkq p], map_rel_iff' := λ p₁ p₂, comap_le_comap_iff $ range_mkq _ } /-- The ordering on submodules of the quotient of `M` by `p` embeds into the ordering on submodules of `M`. -/ def comap_mkq.order_embedding : submodule R p.quotient ↪o submodule R M := (rel_iso.to_rel_embedding $ comap_mkq.rel_iso p).trans (subtype.rel_embedding _ _) @[simp] lemma comap_mkq_embedding_eq (p' : submodule R p.quotient) : comap_mkq.order_embedding p p' = comap p.mkq p' := rfl lemma span_preimage_eq {f : M →ₗ[R] M₂} {s : set M₂} (h₀ : s.nonempty) (h₁ : s ⊆ range f) : span R (f ⁻¹' s) = (span R s).comap f := begin suffices : (span R s).comap f ≤ span R (f ⁻¹' s), { exact le_antisymm (span_preimage_le f s) this, }, have hk : ker f ≤ span R (f ⁻¹' s), { let y := classical.some h₀, have hy : y ∈ s, { exact classical.some_spec h₀, }, rw ker_le_iff, use [y, h₁ hy], rw ← set.singleton_subset_iff at hy, exact set.subset.trans subset_span (span_mono (set.preimage_mono hy)), }, rw ← left_eq_sup at hk, rw f.range_coe at h₁, rw [hk, ← map_le_map_iff, map_span, map_comap_eq, set.image_preimage_eq_of_subset h₁], exact inf_le_right, end end ring end submodule namespace linear_map variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] lemma range_mkq_comp (f : M →ₗ[R] M₂) : f.range.mkq.comp f = 0 := linear_map.ext $ λ x, by simp lemma ker_le_range_iff {f : M →ₗ[R] M₂} {g : M₂ →ₗ[R] M₃} : g.ker ≤ f.range ↔ f.range.mkq.comp g.ker.subtype = 0 := by rw [←range_le_ker_iff, submodule.ker_mkq, submodule.range_subtype] /-- A monomorphism is injective. -/ lemma ker_eq_bot_of_cancel {f : M →ₗ[R] M₂} (h : ∀ (u v : f.ker →ₗ[R] M), f.comp u = f.comp v → u = v) : f.ker = ⊥ := begin have h₁ : f.comp (0 : f.ker →ₗ[R] M) = 0 := comp_zero _, rw [←submodule.range_subtype f.ker, ←h 0 f.ker.subtype (eq.trans h₁ (comp_ker_subtype f).symm)], exact range_zero end /-- An epimorphism is surjective. -/ lemma range_eq_top_of_cancel {f : M →ₗ[R] M₂} (h : ∀ (u v : M₂ →ₗ[R] f.range.quotient), u.comp f = v.comp f → u = v) : f.range = ⊤ := begin have h₁ : (0 : M₂ →ₗ[R] f.range.quotient).comp f = 0 := zero_comp _, rw [←submodule.ker_mkq f.range, ←h 0 f.range.mkq (eq.trans h₁ (range_mkq_comp _).symm)], exact ker_zero end end linear_map @[simp] lemma linear_map.range_range_restrict [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] (f : M →ₗ[R] M₂) : f.range_restrict.range = ⊤ := by simp [f.range_cod_restrict _] /-! ### Linear equivalences -/ namespace linear_equiv section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] section variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} variables (e e' : M ≃ₗ[R] M₂) lemma map_eq_comap {p : submodule R M} : (p.map e : submodule R M₂) = p.comap e.symm := submodule.coe_injective $ by simp [e.image_eq_preimage] /-- A linear equivalence of two modules restricts to a linear equivalence from any submodule of the domain onto the image of the submodule. -/ def of_submodule (p : submodule R M) : p ≃ₗ[R] ↥(p.map ↑e : submodule R M₂) := { inv_fun := λ y, ⟨e.symm y, by { rcases y with ⟨y', hy⟩, rw submodule.mem_map at hy, rcases hy with ⟨x, hx, hxy⟩, subst hxy, simp only [symm_apply_apply, submodule.coe_mk, coe_coe, hx], }⟩, left_inv := λ x, by simp, right_inv := λ y, by { apply set_coe.ext, simp, }, ..((e : M →ₗ[R] M₂).dom_restrict p).cod_restrict (p.map ↑e) (λ x, ⟨x, by simp⟩) } @[simp] lemma of_submodule_apply (p : submodule R M) (x : p) : ↑(e.of_submodule p x) = e x := rfl @[simp] lemma of_submodule_symm_apply (p : submodule R M) (x : (p.map ↑e : submodule R M₂)) : ↑((e.of_submodule p).symm x) = e.symm x := rfl end section uncurry variables (V V₂ R) /-- Linear equivalence between a curried and uncurried function. Differs from `tensor_product.curry`. -/ protected def uncurry : (V → V₂ → R) ≃ₗ[R] (V × V₂ → R) := { map_add' := λ _ _, by { ext ⟨⟩, refl }, map_smul' := λ _ _, by { ext ⟨⟩, refl }, .. equiv.arrow_arrow_equiv_prod_arrow _ _ _} @[simp] lemma coe_uncurry : ⇑(linear_equiv.uncurry R V V₂) = uncurry := rfl @[simp] lemma coe_uncurry_symm : ⇑(linear_equiv.uncurry R V V₂).symm = curry := rfl end uncurry section variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} variables (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M) (e : M ≃ₗ[R] M₂) variables (p q : submodule R M) /-- Linear equivalence between two equal submodules. -/ def of_eq (h : p = q) : p ≃ₗ[R] q := { map_smul' := λ _ _, rfl, map_add' := λ _ _, rfl, .. equiv.set.of_eq (congr_arg _ h) } variables {p q} @[simp] lemma coe_of_eq_apply (h : p = q) (x : p) : (of_eq p q h x : M) = x := rfl @[simp] lemma of_eq_symm (h : p = q) : (of_eq p q h).symm = of_eq q p h.symm := rfl /-- A linear equivalence which maps a submodule of one module onto another, restricts to a linear equivalence of the two submodules. -/ def of_submodules (p : submodule R M) (q : submodule R M₂) (h : p.map ↑e = q) : p ≃ₗ[R] q := (e.of_submodule p).trans (linear_equiv.of_eq _ _ h) @[simp] lemma of_submodules_apply {p : submodule R M} {q : submodule R M₂} (h : p.map ↑e = q) (x : p) : ↑(e.of_submodules p q h x) = e x := rfl @[simp] lemma of_submodules_symm_apply {p : submodule R M} {q : submodule R M₂} (h : p.map ↑e = q) (x : q) : ↑((e.of_submodules p q h).symm x) = e.symm x := rfl variable (p) /-- The top submodule of `M` is linearly equivalent to `M`. -/ def of_top (h : p = ⊤) : p ≃ₗ[R] M := { inv_fun := λ x, ⟨x, h.symm ▸ trivial⟩, left_inv := λ ⟨x, h⟩, rfl, right_inv := λ x, rfl, .. p.subtype } @[simp] theorem of_top_apply {h} (x : p) : of_top p h x = x := rfl @[simp] theorem coe_of_top_symm_apply {h} (x : M) : ((of_top p h).symm x : M) = x := rfl theorem of_top_symm_apply {h} (x : M) : (of_top p h).symm x = ⟨x, h.symm ▸ trivial⟩ := rfl /-- If a linear map has an inverse, it is a linear equivalence. -/ def of_linear (h₁ : f.comp g = linear_map.id) (h₂ : g.comp f = linear_map.id) : M ≃ₗ[R] M₂ := { inv_fun := g, left_inv := linear_map.ext_iff.1 h₂, right_inv := linear_map.ext_iff.1 h₁, ..f } @[simp] theorem of_linear_apply {h₁ h₂} (x : M) : of_linear f g h₁ h₂ x = f x := rfl @[simp] theorem of_linear_symm_apply {h₁ h₂} (x : M₂) : (of_linear f g h₁ h₂).symm x = g x := rfl @[simp] protected theorem range : (e : M →ₗ[R] M₂).range = ⊤ := linear_map.range_eq_top.2 e.to_equiv.surjective lemma eq_bot_of_equiv [semimodule R M₂] (e : p ≃ₗ[R] (⊥ : submodule R M₂)) : p = ⊥ := begin refine bot_unique (submodule.le_def'.2 $ assume b hb, (submodule.mem_bot R).2 _), rw [← p.mk_eq_zero hb, ← e.map_eq_zero_iff], apply submodule.eq_zero_of_bot_submodule end @[simp] protected theorem ker : (e : M →ₗ[R] M₂).ker = ⊥ := linear_map.ker_eq_bot_of_injective e.to_equiv.injective variables {f g} /-- An linear map `f : M →ₗ[R] M₂` with a left-inverse `g : M₂ →ₗ[R] M` defines a linear equivalence between `M` and `f.range`. This is a computable alternative to `linear_equiv.of_injective`, and a bidirectional version of `linear_map.range_restrict`. -/ def of_left_inverse {g : M₂ → M} (h : function.left_inverse g f) : M ≃ₗ[R] f.range := { to_fun := f.range_restrict, inv_fun := g ∘ f.range.subtype, left_inv := h, right_inv := λ x, subtype.ext $ let ⟨x', hx'⟩ := linear_map.mem_range.mp x.prop in show f (g x) = x, by rw [←hx', h x'], .. f.range_restrict } @[simp] lemma of_left_inverse_apply (h : function.left_inverse g f) (x : M) : ↑(of_left_inverse h x) = f x := rfl @[simp] lemma of_left_inverse_symm_apply (h : function.left_inverse g f) (x : f.range) : (of_left_inverse h).symm x = g x := rfl end end add_comm_monoid section add_comm_group variables [semiring R] variables [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] [add_comm_group M₄] variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} variables {semimodule_M₃ : semimodule R M₃} {semimodule_M₄ : semimodule R M₄} variables (e e₁ : M ≃ₗ[R] M₂) (e₂ : M₃ ≃ₗ[R] M₄) @[simp] theorem map_neg (a : M) : e (-a) = -e a := e.to_linear_map.map_neg a @[simp] theorem map_sub (a b : M) : e (a - b) = e a - e b := e.to_linear_map.map_sub a b end add_comm_group section neg variables (R) [semiring R] [add_comm_group M] [semimodule R M] /-- `x ↦ -x` as a `linear_equiv` -/ def neg : M ≃ₗ[R] M := { .. equiv.neg M, .. (-linear_map.id : M →ₗ[R] M) } variable {R} @[simp] lemma coe_neg : ⇑(neg R : M ≃ₗ[R] M) = -id := rfl lemma neg_apply (x : M) : neg R x = -x := by simp @[simp] lemma symm_neg : (neg R : M ≃ₗ[R] M).symm = neg R := rfl end neg section ring variables [ring R] [add_comm_group M] [add_comm_group M₂] variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} variables (f : M →ₗ[R] M₂) (e : M ≃ₗ[R] M₂) /-- An `injective` linear map `f : M →ₗ[R] M₂` defines a linear equivalence between `M` and `f.range`. See also `linear_map.of_left_inverse`. -/ noncomputable def of_injective (h : f.ker = ⊥) : M ≃ₗ[R] f.range := of_left_inverse $ classical.some_spec (linear_map.ker_eq_bot.1 h).has_left_inverse @[simp] theorem of_injective_apply {h : f.ker = ⊥} (x : M) : ↑(of_injective f h x) = f x := rfl /-- A bijective linear map is a linear equivalence. Here, bijectivity is described by saying that the kernel of `f` is `{0}` and the range is the universal set. -/ noncomputable def of_bijective (hf₁ : f.ker = ⊥) (hf₂ : f.range = ⊤) : M ≃ₗ[R] M₂ := (of_injective f hf₁).trans (of_top _ hf₂) @[simp] theorem of_bijective_apply {hf₁ hf₂} (x : M) : of_bijective f hf₁ hf₂ x = f x := rfl end ring section comm_ring variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] open linear_map /-- Multiplying by a unit `a` of the ring `R` is a linear equivalence. -/ def smul_of_unit (a : units R) : M ≃ₗ[R] M := of_linear ((a:R) • 1 : M →ₗ M) (((a⁻¹ : units R) : R) • 1 : M →ₗ M) (by rw [smul_comp, comp_smul, smul_smul, units.mul_inv, one_smul]; refl) (by rw [smul_comp, comp_smul, smul_smul, units.inv_mul, one_smul]; refl) /-- A linear isomorphism between the domains and codomains of two spaces of linear maps gives a linear isomorphism between the two function spaces. -/ def arrow_congr {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_ring R] [add_comm_group M₁] [add_comm_group M₂] [add_comm_group M₂₁] [add_comm_group M₂₂] [module R M₁] [module R M₂] [module R M₂₁] [module R M₂₂] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) : (M₁ →ₗ[R] M₂₁) ≃ₗ[R] (M₂ →ₗ[R] M₂₂) := { to_fun := λ f, (e₂ : M₂₁ →ₗ[R] M₂₂).comp $ f.comp e₁.symm, inv_fun := λ f, (e₂.symm : M₂₂ →ₗ[R] M₂₁).comp $ f.comp e₁, left_inv := λ f, by { ext x, simp }, right_inv := λ f, by { ext x, simp }, map_add' := λ f g, by { ext x, simp }, map_smul' := λ c f, by { ext x, simp } } @[simp] lemma arrow_congr_apply {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_ring R] [add_comm_group M₁] [add_comm_group M₂] [add_comm_group M₂₁] [add_comm_group M₂₂] [module R M₁] [module R M₂] [module R M₂₁] [module R M₂₂] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) (f : M₁ →ₗ[R] M₂₁) (x : M₂) : arrow_congr e₁ e₂ f x = e₂ (f (e₁.symm x)) := rfl @[simp] lemma arrow_congr_symm_apply {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_ring R] [add_comm_group M₁] [add_comm_group M₂] [add_comm_group M₂₁] [add_comm_group M₂₂] [module R M₁] [module R M₂] [module R M₂₁] [module R M₂₂] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) (f : M₂ →ₗ[R] M₂₂) (x : M₁) : (arrow_congr e₁ e₂).symm f x = e₂.symm (f (e₁ x)) := rfl lemma arrow_congr_comp {N N₂ N₃ : Sort*} [add_comm_group N] [add_comm_group N₂] [add_comm_group N₃] [module R N] [module R N₂] [module R N₃] (e₁ : M ≃ₗ[R] N) (e₂ : M₂ ≃ₗ[R] N₂) (e₃ : M₃ ≃ₗ[R] N₃) (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : arrow_congr e₁ e₃ (g.comp f) = (arrow_congr e₂ e₃ g).comp (arrow_congr e₁ e₂ f) := by { ext, simp only [symm_apply_apply, arrow_congr_apply, linear_map.comp_apply], } lemma arrow_congr_trans {M₁ M₂ M₃ N₁ N₂ N₃ : Sort*} [add_comm_group M₁] [module R M₁] [add_comm_group M₂] [module R M₂] [add_comm_group M₃] [module R M₃] [add_comm_group N₁] [module R N₁] [add_comm_group N₂] [module R N₂] [add_comm_group N₃] [module R N₃] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : N₁ ≃ₗ[R] N₂) (e₃ : M₂ ≃ₗ[R] M₃) (e₄ : N₂ ≃ₗ[R] N₃) : (arrow_congr e₁ e₂).trans (arrow_congr e₃ e₄) = arrow_congr (e₁.trans e₃) (e₂.trans e₄) := rfl /-- If `M₂` and `M₃` are linearly isomorphic then the two spaces of linear maps from `M` into `M₂` and `M` into `M₃` are linearly isomorphic. -/ def congr_right (f : M₂ ≃ₗ[R] M₃) : (M →ₗ[R] M₂) ≃ₗ (M →ₗ M₃) := arrow_congr (linear_equiv.refl R M) f /-- If `M` and `M₂` are linearly isomorphic then the two spaces of linear maps from `M` and `M₂` to themselves are linearly isomorphic. -/ def conj (e : M ≃ₗ[R] M₂) : (module.End R M) ≃ₗ[R] (module.End R M₂) := arrow_congr e e lemma conj_apply (e : M ≃ₗ[R] M₂) (f : module.End R M) : e.conj f = ((↑e : M →ₗ[R] M₂).comp f).comp e.symm := rfl lemma symm_conj_apply (e : M ≃ₗ[R] M₂) (f : module.End R M₂) : e.symm.conj f = ((↑e.symm : M₂ →ₗ[R] M).comp f).comp e := rfl lemma conj_comp (e : M ≃ₗ[R] M₂) (f g : module.End R M) : e.conj (g.comp f) = (e.conj g).comp (e.conj f) := arrow_congr_comp e e e f g lemma conj_trans (e₁ : M ≃ₗ[R] M₂) (e₂ : M₂ ≃ₗ[R] M₃) : e₁.conj.trans e₂.conj = (e₁.trans e₂).conj := by { ext f x, refl, } @[simp] lemma conj_id (e : M ≃ₗ[R] M₂) : e.conj linear_map.id = linear_map.id := by { ext, simp [conj_apply], } end comm_ring section field variables [field K] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module K M] [module K M₂] [module K M₃] variables (K) (M) open linear_map /-- Multiplying by a nonzero element `a` of the field `K` is a linear equivalence. -/ def smul_of_ne_zero (a : K) (ha : a ≠ 0) : M ≃ₗ[K] M := smul_of_unit $ units.mk0 a ha section noncomputable theory open_locale classical lemma ker_to_span_singleton {x : M} (h : x ≠ 0) : (to_span_singleton K M x).ker = ⊥ := begin ext c, split, { intros hc, rw submodule.mem_bot, rw mem_ker at hc, by_contra hc', have : x = 0, calc x = c⁻¹ • (c • x) : by rw [← mul_smul, inv_mul_cancel hc', one_smul] ... = c⁻¹ • ((to_span_singleton K M x) c) : rfl ... = 0 : by rw [hc, smul_zero], tauto }, { rw [mem_ker, submodule.mem_bot], intros h, rw h, simp } end /-- Given a nonzero element `x` of a vector space `M` over a field `K`, the natural map from `K` to the span of `x`, with invertibility check to consider it as an isomorphism.-/ def to_span_nonzero_singleton (x : M) (h : x ≠ 0) : K ≃ₗ[K] (K ∙ x) := linear_equiv.trans (linear_equiv.of_injective (to_span_singleton K M x) (ker_to_span_singleton K M h)) (of_eq (to_span_singleton K M x).range (K ∙ x) (span_singleton_eq_range K M x).symm) lemma to_span_nonzero_singleton_one (x : M) (h : x ≠ 0) : to_span_nonzero_singleton K M x h 1 = (⟨x, submodule.mem_span_singleton_self x⟩ : K ∙ x) := begin apply submodule.coe_eq_coe.mp, have : ↑(to_span_nonzero_singleton K M x h 1) = to_span_singleton K M x 1 := rfl, rw [this, to_span_singleton_one, submodule.coe_mk], end /-- Given a nonzero element `x` of a vector space `M` over a field `K`, the natural map from the span of `x` to `K`.-/ abbreviation coord (x : M) (h : x ≠ 0) : (K ∙ x) ≃ₗ[K] K := (to_span_nonzero_singleton K M x h).symm lemma coord_self (x : M) (h : x ≠ 0) : (coord K M x h) (⟨x, submodule.mem_span_singleton_self x⟩ : K ∙ x) = 1 := by rw [← to_span_nonzero_singleton_one K M x h, symm_apply_apply] end end field end linear_equiv namespace submodule section semimodule variables [semiring R] [add_comm_monoid M] [semimodule R M] /-- If `s ≤ t`, then we can view `s` as a submodule of `t` by taking the comap of `t.subtype`. -/ def comap_subtype_equiv_of_le {p q : submodule R M} (hpq : p ≤ q) : comap q.subtype p ≃ₗ[R] p := { to_fun := λ x, ⟨x, x.2⟩, inv_fun := λ x, ⟨⟨x, hpq x.2⟩, x.2⟩, left_inv := λ x, by simp only [coe_mk, submodule.eta, coe_coe], right_inv := λ x, by simp only [subtype.coe_mk, submodule.eta, coe_coe], map_add' := λ x y, rfl, map_smul' := λ c x, rfl } end semimodule variables [ring R] [add_comm_group M] [module R M] variables (p : submodule R M) open linear_map /-- If `p = ⊥`, then `M / p ≃ₗ[R] M`. -/ def quot_equiv_of_eq_bot (hp : p = ⊥) : p.quotient ≃ₗ[R] M := linear_equiv.of_linear (p.liftq id $ hp.symm ▸ bot_le) p.mkq (liftq_mkq _ _ _) $ p.quot_hom_ext $ λ x, rfl @[simp] lemma quot_equiv_of_eq_bot_apply_mk (hp : p = ⊥) (x : M) : p.quot_equiv_of_eq_bot hp (quotient.mk x) = x := rfl @[simp] lemma quot_equiv_of_eq_bot_symm_apply (hp : p = ⊥) (x : M) : (p.quot_equiv_of_eq_bot hp).symm x = quotient.mk x := rfl @[simp] lemma coe_quot_equiv_of_eq_bot_symm (hp : p = ⊥) : ((p.quot_equiv_of_eq_bot hp).symm : M →ₗ[R] p.quotient) = p.mkq := rfl variables (q : submodule R M) /-- Quotienting by equal submodules gives linearly equivalent quotients. -/ def quot_equiv_of_eq (h : p = q) : p.quotient ≃ₗ[R] q.quotient := { map_add' := by { rintros ⟨x⟩ ⟨y⟩, refl }, map_smul' := by { rintros x ⟨y⟩, refl }, ..@quotient.congr _ _ (quotient_rel p) (quotient_rel q) (equiv.refl _) $ λ a b, by { subst h, refl } } end submodule namespace submodule variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [module R M] [module R M₂] variables (p : submodule R M) (q : submodule R M₂) @[simp] lemma mem_map_equiv {e : M ≃ₗ[R] M₂} {x : M₂} : x ∈ p.map (e : M →ₗ[R] M₂) ↔ e.symm x ∈ p := begin rw submodule.mem_map, split, { rintros ⟨y, hy, hx⟩, simp [←hx, hy], }, { intros hx, refine ⟨e.symm x, hx, by simp⟩, }, end lemma comap_le_comap_smul (f : M →ₗ[R] M₂) (c : R) : comap f q ≤ comap (c • f) q := begin rw le_def', intros m h, change c • (f m) ∈ q, change f m ∈ q at h, apply q.smul_mem _ h, end lemma inf_comap_le_comap_add (f₁ f₂ : M →ₗ[R] M₂) : comap f₁ q ⊓ comap f₂ q ≤ comap (f₁ + f₂) q := begin rw le_def', intros m h, change f₁ m + f₂ m ∈ q, change f₁ m ∈ q ∧ f₂ m ∈ q at h, apply q.add_mem h.1 h.2, end /-- Given modules `M`, `M₂` over a commutative ring, together with submodules `p ⊆ M`, `q ⊆ M₂`, the set of maps $\{f ∈ Hom(M, M₂) | f(p) ⊆ q \}$ is a submodule of `Hom(M, M₂)`. -/ def compatible_maps : submodule R (M →ₗ[R] M₂) := { carrier := {f | p ≤ comap f q}, zero_mem' := by { change p ≤ comap 0 q, rw comap_zero, refine le_top, }, add_mem' := λ f₁ f₂ h₁ h₂, by { apply le_trans _ (inf_comap_le_comap_add q f₁ f₂), rw le_inf_iff, exact ⟨h₁, h₂⟩, }, smul_mem' := λ c f h, le_trans h (comap_le_comap_smul q f c), } /-- Given modules `M`, `M₂` over a commutative ring, together with submodules `p ⊆ M`, `q ⊆ M₂`, the natural map $\{f ∈ Hom(M, M₂) | f(p) ⊆ q \} \to Hom(M/p, M₂/q)$ is linear. -/ def mapq_linear : compatible_maps p q →ₗ[R] p.quotient →ₗ[R] q.quotient := { to_fun := λ f, mapq _ _ f.val f.property, map_add' := λ x y, by { ext m', apply quotient.induction_on' m', intros m, refl, }, map_smul' := λ c f, by { ext m', apply quotient.induction_on' m', intros m, refl, } } end submodule namespace equiv variables [semiring R] [add_comm_monoid M] [semimodule R M] [add_comm_monoid M₂] [semimodule R M₂] /-- An equivalence whose underlying function is linear is a linear equivalence. -/ def to_linear_equiv (e : M ≃ M₂) (h : is_linear_map R (e : M → M₂)) : M ≃ₗ[R] M₂ := { .. e, .. h.mk' e} end equiv namespace add_equiv variables [semiring R] [add_comm_monoid M] [semimodule R M] [add_comm_monoid M₂] [semimodule R M₂] /-- An additive equivalence whose underlying function preserves `smul` is a linear equivalence. -/ def to_linear_equiv (e : M ≃+ M₂) (h : ∀ (c : R) x, e (c • x) = c • e x) : M ≃ₗ[R] M₂ := { map_smul' := h, .. e, } @[simp] lemma coe_to_linear_equiv (e : M ≃+ M₂) (h : ∀ (c : R) x, e (c • x) = c • e x) : ⇑(e.to_linear_equiv h) = e := rfl @[simp] lemma coe_to_linear_equiv_symm (e : M ≃+ M₂) (h : ∀ (c : R) x, e (c • x) = c • e x) : ⇑(e.to_linear_equiv h).symm = e.symm := rfl end add_equiv namespace linear_map open submodule section isomorphism_laws variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] variables (f : M →ₗ[R] M₂) /-- The first isomorphism law for modules. The quotient of `M` by the kernel of `f` is linearly equivalent to the range of `f`. -/ noncomputable def quot_ker_equiv_range : f.ker.quotient ≃ₗ[R] f.range := (linear_equiv.of_injective (f.ker.liftq f $ le_refl _) $ submodule.ker_liftq_eq_bot _ _ _ (le_refl f.ker)).trans (linear_equiv.of_eq _ _ $ submodule.range_liftq _ _ _) /-- The first isomorphism theorem for surjective linear maps. -/ noncomputable def quot_ker_equiv_of_surjective (f : M →ₗ[R] M₂) (hf : function.surjective f) : f.ker.quotient ≃ₗ[R] M₂ := f.quot_ker_equiv_range.trans (linear_equiv.of_top f.range (linear_map.range_eq_top.2 hf)) @[simp] lemma quot_ker_equiv_range_apply_mk (x : M) : (f.quot_ker_equiv_range (submodule.quotient.mk x) : M₂) = f x := rfl @[simp] lemma quot_ker_equiv_range_symm_apply_image (x : M) (h : f x ∈ f.range) : f.quot_ker_equiv_range.symm ⟨f x, h⟩ = f.ker.mkq x := f.quot_ker_equiv_range.symm_apply_apply (f.ker.mkq x) /-- Canonical linear map from the quotient `p/(p ∩ p')` to `(p+p')/p'`, mapping `x + (p ∩ p')` to `x + p'`, where `p` and `p'` are submodules of an ambient module. -/ def quotient_inf_to_sup_quotient (p p' : submodule R M) : (comap p.subtype (p ⊓ p')).quotient →ₗ[R] (comap (p ⊔ p').subtype p').quotient := (comap p.subtype (p ⊓ p')).liftq ((comap (p ⊔ p').subtype p').mkq.comp (of_le le_sup_left)) begin rw [ker_comp, of_le, comap_cod_restrict, ker_mkq, map_comap_subtype], exact comap_mono (inf_le_inf_right _ le_sup_left) end /-- Second Isomorphism Law : the canonical map from `p/(p ∩ p')` to `(p+p')/p'` as a linear isomorphism. -/ noncomputable def quotient_inf_equiv_sup_quotient (p p' : submodule R M) : (comap p.subtype (p ⊓ p')).quotient ≃ₗ[R] (comap (p ⊔ p').subtype p').quotient := linear_equiv.of_bijective (quotient_inf_to_sup_quotient p p') begin rw [quotient_inf_to_sup_quotient, ker_liftq_eq_bot], rw [ker_comp, ker_mkq], exact λ ⟨x, hx1⟩ hx2, ⟨hx1, hx2⟩ end begin rw [quotient_inf_to_sup_quotient, range_liftq, eq_top_iff'], rintros ⟨x, hx⟩, rcases mem_sup.1 hx with ⟨y, hy, z, hz, rfl⟩, use [⟨y, hy⟩, trivial], apply (submodule.quotient.eq _).2, change y - (y + z) ∈ p', rwa [sub_add_eq_sub_sub, sub_self, zero_sub, neg_mem_iff] end @[simp] lemma coe_quotient_inf_to_sup_quotient (p p' : submodule R M) : ⇑(quotient_inf_to_sup_quotient p p') = quotient_inf_equiv_sup_quotient p p' := rfl @[simp] lemma quotient_inf_equiv_sup_quotient_apply_mk (p p' : submodule R M) (x : p) : quotient_inf_equiv_sup_quotient p p' (submodule.quotient.mk x) = submodule.quotient.mk (of_le (le_sup_left : p ≤ p ⊔ p') x) := rfl lemma quotient_inf_equiv_sup_quotient_symm_apply_left (p p' : submodule R M) (x : p ⊔ p') (hx : (x:M) ∈ p) : (quotient_inf_equiv_sup_quotient p p').symm (submodule.quotient.mk x) = submodule.quotient.mk ⟨x, hx⟩ := (linear_equiv.symm_apply_eq _).2 $ by simp [of_le_apply] @[simp] lemma quotient_inf_equiv_sup_quotient_symm_apply_eq_zero_iff {p p' : submodule R M} {x : p ⊔ p'} : (quotient_inf_equiv_sup_quotient p p').symm (submodule.quotient.mk x) = 0 ↔ (x:M) ∈ p' := (linear_equiv.symm_apply_eq _).trans $ by simp [of_le_apply] lemma quotient_inf_equiv_sup_quotient_symm_apply_right (p p' : submodule R M) {x : p ⊔ p'} (hx : (x:M) ∈ p') : (quotient_inf_equiv_sup_quotient p p').symm (submodule.quotient.mk x) = 0 := quotient_inf_equiv_sup_quotient_symm_apply_eq_zero_iff.2 hx end isomorphism_laws section fun_left variables (R M) [semiring R] [add_comm_monoid M] [semimodule R M] variables {m n p : Type*} /-- Given an `R`-module `M` and a function `m → n` between arbitrary types, construct a linear map `(n → M) →ₗ[R] (m → M)` -/ def fun_left (f : m → n) : (n → M) →ₗ[R] (m → M) := mk (∘f) (λ _ _, rfl) (λ _ _, rfl) @[simp] theorem fun_left_apply (f : m → n) (g : n → M) (i : m) : fun_left R M f g i = g (f i) := rfl @[simp] theorem fun_left_id (g : n → M) : fun_left R M _root_.id g = g := rfl theorem fun_left_comp (f₁ : n → p) (f₂ : m → n) : fun_left R M (f₁ ∘ f₂) = (fun_left R M f₂).comp (fun_left R M f₁) := rfl /-- Given an `R`-module `M` and an equivalence `m ≃ n` between arbitrary types, construct a linear equivalence `(n → M) ≃ₗ[R] (m → M)` -/ def fun_congr_left (e : m ≃ n) : (n → M) ≃ₗ[R] (m → M) := linear_equiv.of_linear (fun_left R M e) (fun_left R M e.symm) (ext $ λ x, funext $ λ i, by rw [id_apply, ← fun_left_comp, equiv.symm_comp_self, fun_left_id]) (ext $ λ x, funext $ λ i, by rw [id_apply, ← fun_left_comp, equiv.self_comp_symm, fun_left_id]) @[simp] theorem fun_congr_left_apply (e : m ≃ n) (x : n → M) : fun_congr_left R M e x = fun_left R M e x := rfl @[simp] theorem fun_congr_left_id : fun_congr_left R M (equiv.refl n) = linear_equiv.refl R (n → M) := rfl @[simp] theorem fun_congr_left_comp (e₁ : m ≃ n) (e₂ : n ≃ p) : fun_congr_left R M (equiv.trans e₁ e₂) = linear_equiv.trans (fun_congr_left R M e₂) (fun_congr_left R M e₁) := rfl @[simp] lemma fun_congr_left_symm (e : m ≃ n) : (fun_congr_left R M e).symm = fun_congr_left R M e.symm := rfl end fun_left universe i variables [semiring R] [add_comm_monoid M] [semimodule R M] variables (R M) instance automorphism_group : group (M ≃ₗ[R] M) := { mul := λ f g, g.trans f, one := linear_equiv.refl R M, inv := λ f, f.symm, mul_assoc := λ f g h, by {ext, refl}, mul_one := λ f, by {ext, refl}, one_mul := λ f, by {ext, refl}, mul_left_inv := λ f, by {ext, exact f.left_inv x} } instance automorphism_group.to_linear_map_is_monoid_hom : is_monoid_hom (linear_equiv.to_linear_map : (M ≃ₗ[R] M) → (M →ₗ[R] M)) := { map_one := rfl, map_mul := λ f g, rfl } /-- The group of invertible linear maps from `M` to itself -/ @[reducible] def general_linear_group := units (M →ₗ[R] M) namespace general_linear_group variables {R M} instance : has_coe_to_fun (general_linear_group R M) := by apply_instance /-- An invertible linear map `f` determines an equivalence from `M` to itself. -/ def to_linear_equiv (f : general_linear_group R M) : (M ≃ₗ[R] M) := { inv_fun := f.inv.to_fun, left_inv := λ m, show (f.inv * f.val) m = m, by erw f.inv_val; simp, right_inv := λ m, show (f.val * f.inv) m = m, by erw f.val_inv; simp, ..f.val } /-- An equivalence from `M` to itself determines an invertible linear map. -/ def of_linear_equiv (f : (M ≃ₗ[R] M)) : general_linear_group R M := { val := f, inv := f.symm, val_inv := linear_map.ext $ λ _, f.apply_symm_apply _, inv_val := linear_map.ext $ λ _, f.symm_apply_apply _ } variables (R M) /-- The general linear group on `R` and `M` is multiplicatively equivalent to the type of linear equivalences between `M` and itself. -/ def general_linear_equiv : general_linear_group R M ≃* (M ≃ₗ[R] M) := { to_fun := to_linear_equiv, inv_fun := of_linear_equiv, left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext, refl }, map_mul' := λ x y, by {ext, refl} } @[simp] lemma general_linear_equiv_to_linear_map (f : general_linear_group R M) : (general_linear_equiv R M f : M →ₗ[R] M) = f := by {ext, refl} end general_linear_group end linear_map namespace submodule variables [ring R] [add_comm_group M] [module R M] instance : is_modular_lattice (submodule R M) := ⟨λ x y z xz a ha, begin rw [mem_inf, mem_sup] at ha, rcases ha with ⟨⟨b, hb, c, hc, rfl⟩, haz⟩, rw mem_sup, refine ⟨b, hb, c, mem_inf.2 ⟨hc, _⟩, rfl⟩, rw [← add_sub_cancel c b, add_comm], apply z.sub_mem haz (xz hb), end⟩ end submodule
83b25b08e9b0d658e606c93f22ebcb0b475c6328
56af0912bd25910f5caae91d6dd0603b0c032989
/kb_solutions/I.lean
ff0d22ebd94263d95195fe66c60d1361795428d4
[ "Apache-2.0" ]
permissive
isabella232/complex-number-game
ae36e0b1df9761d9df07049ca29c91ae44dbdc2d
3d767f14041f9002e435bed3a3527fdd297c166d
refs/heads/master
1,679,305,953,116
1,606,397,567,000
1,606,397,567,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,546
lean
/- Copyright (c) 2020 The Xena project. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Kevin Buzzard Thanks: Imperial College London, leanprover-community The complex numbers, modelled as R^2 in the obvious way. -/ import complex.basic -- tutorial level /-! # Level 1: I I find it unbelievable that we have written quite a lot of code about the complex numbers and we've still never defined i, or j, or I, or $$\sqrt{-1}$$, or whatever it's called. Why don't you supply the definition, and make the basic API? All the proofs below are sorried. You can try them in tactic mode by replacing `sorry` with `begin end` and then starting to write tactics in the `begin end` block. -/ namespace complex /-- complex.I is the square root of -1 above the imaginary axis -/ def I : ℂ := ⟨0, 1⟩ /- Easy lemmas, tagged with `simp` so Lean can prove things about `I` by equating real and imaginary parts. -/ /-- re(I) = 0 -/ @[simp] lemma I_re : re(I) = 0 := begin refl end /-- im(I) = 1 -/ @[simp] lemma I_im : im(I) = 1 := begin refl end /-- I*I = -1 -/ @[simp] lemma I_mul_I : I * I = -1 := begin -- suffices to check real and imaginary parts ext; -- do them both at once simp, end -- Boss level. Hint: don't forget ext_iff /-- I is non-zero -/ lemma I_ne_zero : (I : ℂ) ≠ 0 := begin -- by contradiction intro h, -- what does it mean for two complex numbers to be equal rw ext_iff at h, -- this is now just a logic puzzle simp * at *, end end complex
1cbb80fa4fb02834c73b11cc4181fe67c2804291
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/data/option/basic.lean
5792a6d44999d8e989a76eb8270adddd4720aaa2
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
7,209
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 logic.basic data.bool data.option.defs tactic.basic namespace option variables {α : Type*} {β : Type*} {γ : Type*} lemma some_ne_none (x : α) : some x ≠ none := λ h, option.no_confusion h @[simp] theorem get_mem : ∀ {o : option α} (h : is_some o), option.get h ∈ o | (some a) _ := rfl theorem get_of_mem {a : α} : ∀ {o : option α} (h : is_some o), a ∈ o → option.get h = a | _ _ rfl := rfl @[simp] lemma not_mem_none (a : α) : a ∉ (none : option α) := λ h, option.no_confusion h @[simp] lemma some_get : ∀ {x : option α} (h : is_some x), some (option.get h) = x | (some x) hx := rfl @[simp] lemma get_some (x : α) (h : is_some (some x)) : option.get h = x := rfl theorem mem_unique {o : option α} {a b : α} (ha : a ∈ o) (hb : b ∈ o) : a = b := option.some.inj $ ha.symm.trans hb theorem injective_some (α : Type*) : function.injective (@some α) := λ _ _, some_inj.mp /-- `option.map f` is injective if `f` is injective. -/ theorem injective_map {f : α → β} (Hf : function.injective f) : function.injective (option.map f) | none none H := rfl | (some a₁) (some a₂) H := by rw Hf (option.some.inj H) @[ext] theorem ext : ∀ {o₁ o₂ : option α}, (∀ a, a ∈ o₁ ↔ a ∈ o₂) → o₁ = o₂ | none none H := rfl | (some a) o H := ((H _).1 rfl).symm | o (some b) H := (H _).2 rfl theorem eq_none_iff_forall_not_mem {o : option α} : o = none ↔ (∀ a, a ∉ o) := ⟨λ e a h, by rw e at h; cases h, λ h, ext $ by simpa⟩ @[simp] theorem none_bind {α β} (f : α → option β) : none >>= f = none := rfl @[simp] theorem some_bind {α β} (a : α) (f : α → option β) : some a >>= f = f a := rfl @[simp] theorem none_bind' (f : α → option β) : none.bind f = none := rfl @[simp] theorem some_bind' (a : α) (f : α → option β) : (some a).bind f = f a := rfl @[simp] theorem bind_some : ∀ x : option α, x >>= some = x := @bind_pure α option _ _ @[simp] theorem bind_eq_some {α β} {x : option α} {f : α → option β} {b : β} : x >>= f = some b ↔ ∃ a, x = some a ∧ f a = some b := by cases x; simp @[simp] theorem bind_eq_some' {x : option α} {f : α → option β} {b : β} : x.bind f = some b ↔ ∃ a, x = some a ∧ f a = some b := by cases x; simp @[simp] theorem bind_eq_none' {o : option α} {f : α → option β} : o.bind f = none ↔ (∀ b a, a ∈ o → b ∉ f a) := by simp only [eq_none_iff_forall_not_mem, not_exists, not_and, mem_def, bind_eq_some'] @[simp] theorem bind_eq_none {α β} {o : option α} {f : α → option β} : o >>= f = none ↔ (∀ b a, a ∈ o → b ∉ f a) := bind_eq_none' lemma bind_comm {α β γ} {f : α → β → option γ} (a : option α) (b : option β) : a.bind (λx, b.bind (f x)) = b.bind (λy, a.bind (λx, f x y)) := by cases a; cases b; refl lemma bind_assoc (x : option α) (f : α → option β) (g : β → option γ) : (x.bind f).bind g = x.bind (λ y, (f y).bind g) := by cases x; refl @[simp] theorem map_none {α β} {f : α → β} : f <$> none = none := rfl @[simp] theorem map_some {α β} {a : α} {f : α → β} : f <$> some a = some (f a) := rfl @[simp] theorem map_none' {f : α → β} : option.map f none = none := rfl @[simp] theorem map_some' {a : α} {f : α → β} : option.map f (some a) = some (f a) := rfl @[simp] theorem map_eq_some {α β} {x : option α} {f : α → β} {b : β} : f <$> x = some b ↔ ∃ a, x = some a ∧ f a = b := by cases x; simp @[simp] theorem map_eq_some' {x : option α} {f : α → β} {b : β} : x.map f = some b ↔ ∃ a, x = some a ∧ f a = b := by cases x; simp @[simp] theorem map_id' : option.map (@id α) = id := map_id @[simp] theorem seq_some {α β} {a : α} {f : α → β} : some f <*> some a = some (f a) := rfl @[simp] theorem some_orelse' (a : α) (x : option α) : (some a).orelse x = some a := rfl @[simp] theorem some_orelse (a : α) (x : option α) : (some a <|> x) = some a := rfl @[simp] theorem none_orelse' (x : option α) : none.orelse x = x := by cases x; refl @[simp] theorem none_orelse (x : option α) : (none <|> x) = x := none_orelse' x @[simp] theorem orelse_none' (x : option α) : x.orelse none = x := by cases x; refl @[simp] theorem orelse_none (x : option α) : (x <|> none) = x := orelse_none' x @[simp] theorem is_some_none : @is_some α none = ff := rfl @[simp] theorem is_some_some {a : α} : is_some (some a) = tt := rfl theorem is_some_iff_exists {x : option α} : is_some x ↔ ∃ a, x = some a := by cases x; simp [is_some]; exact ⟨_, rfl⟩ @[simp] theorem is_none_none : @is_none α none = tt := rfl @[simp] theorem is_none_some {a : α} : is_none (some a) = ff := rfl @[simp] theorem not_is_some {a : option α} : is_some a = ff ↔ a.is_none = tt := by cases a; simp lemma eq_some_iff_get_eq {o : option α} {a : α} : o = some a ↔ ∃ h : o.is_some, option.get h = a := by cases o; simp lemma not_is_some_iff_eq_none {o : option α} : ¬o.is_some ↔ o = none := by cases o; simp lemma ne_none_iff_is_some {o : option α} : o ≠ none ↔ o.is_some := by cases o; simp lemma bex_ne_none {p : option α → Prop} : (∃ x ≠ none, p x) ↔ ∃ x, p (some x) := ⟨λ ⟨x, hx, hp⟩, ⟨get $ ne_none_iff_is_some.1 hx, by rwa [some_get]⟩, λ ⟨x, hx⟩, ⟨some x, some_ne_none x, hx⟩⟩ lemma ball_ne_none {p : option α → Prop} : (∀ x ≠ none, p x) ↔ ∀ x, p (some x) := ⟨λ h x, h (some x) (some_ne_none x), λ h x hx, by simpa only [some_get] using h (get $ ne_none_iff_is_some.1 hx)⟩ theorem iget_mem [inhabited α] : ∀ {o : option α}, is_some o → o.iget ∈ o | (some a) _ := rfl theorem iget_of_mem [inhabited α] {a : α} : ∀ {o : option α}, a ∈ o → o.iget = a | _ rfl := rfl @[simp] theorem guard_eq_some {p : α → Prop} [decidable_pred p] {a b : α} : guard p a = some b ↔ a = b ∧ p a := by by_cases p a; simp [option.guard, h]; intro; contradiction @[simp] theorem guard_eq_some' {p : Prop} [decidable p] : ∀ u, _root_.guard p = some u ↔ p | () := by by_cases p; simp [guard, h, pure]; intro; contradiction theorem lift_or_get_choice {f : α → α → α} (h : ∀ a b, f a b = a ∨ f a b = b) : ∀ o₁ o₂, lift_or_get f o₁ o₂ = o₁ ∨ lift_or_get f o₁ o₂ = o₂ | none none := or.inl rfl | (some a) none := or.inl rfl | none (some b) := or.inr rfl | (some a) (some b) := by simpa [lift_or_get] using h a b @[simp] lemma lift_or_get_none_left {f} {b : option α} : lift_or_get f none b = b := by cases b; refl @[simp] lemma lift_or_get_none_right {f} {a : option α} : lift_or_get f a none = a := by cases a; refl @[simp] lemma lift_or_get_some_some {f} {a b : α} : lift_or_get f (some a) (some b) = f a b := rfl /-- given an element of `a : option α`, a default element `b : β` and a function `α → β`, apply this function to `a` if it comes from `α`, and return `b` otherwise. -/ def cases_on' : option α → β → (α → β) → β | none n s := n | (some a) n s := s a end option
af96c4437100d418ba1f69fbe81c848cae1f497c
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/module/opposites.lean
55f6fc11aaf071d3a9ce198b74650974da0fbaca
[ "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,445
lean
/- Copyright (c) 2020 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import algebra.module.linear_map import algebra.opposites /-! # Module operations on `Mᵒᵖ` This file contains definitions that could not be placed into `algebra.opposites` due to import cycles. -/ namespace opposite universes u v variables (R : Type u) {M : Type v} /-- Like `mul_zero_class.to_smul_with_zero`, but multiplies on the right. -/ instance mul_zero_class.to_opposite_smul_with_zero [mul_zero_class R] : smul_with_zero (opposite R) R := { smul := λ c x, x * c.unop, smul_zero := λ x, zero_mul _, zero_smul := mul_zero } /-- Like `monoid_with_zero.to_mul_action_with_zero`, but multiplies on the right. -/ instance monoid_with_zero.to_opposite_mul_action_with_zero [monoid_with_zero R] : mul_action_with_zero (opposite R) R := { ..mul_zero_class.to_opposite_smul_with_zero R, ..monoid.to_opposite_mul_action R } /-- Like `semiring.to_module`, but multiplies on the right. -/ instance semiring.to_opposite_module [semiring R] : module (opposite R) R := { smul_add := λ r x y, add_mul _ _ _, add_smul := λ r s x, mul_add _ _ _, ..mul_zero_class.to_opposite_smul_with_zero R } variables [semiring R] [add_comm_monoid M] [module R M] /-- `opposite.distrib_mul_action` extends to a `module` -/ instance : module R (opposite M) := { add_smul := λ r₁ r₂ x, unop_injective $ add_smul r₁ r₂ (unop x), zero_smul := λ x, unop_injective $ zero_smul _ (unop x), ..opposite.distrib_mul_action M R } /-- The function `op` is a linear equivalence. -/ def op_linear_equiv : M ≃ₗ[R] Mᵒᵖ := { map_smul' := opposite.op_smul, .. op_add_equiv } @[simp] lemma coe_op_linear_equiv : (op_linear_equiv R : M → Mᵒᵖ) = op := rfl @[simp] lemma coe_op_linear_equiv_symm : ((op_linear_equiv R).symm : Mᵒᵖ → M) = unop := rfl @[simp] lemma coe_op_linear_equiv_to_linear_map : ((op_linear_equiv R).to_linear_map : M → Mᵒᵖ) = op := rfl @[simp] lemma coe_op_linear_equiv_symm_to_linear_map : ((op_linear_equiv R).symm.to_linear_map : Mᵒᵖ → M) = unop := rfl @[simp] lemma op_linear_equiv_to_add_equiv : (op_linear_equiv R : M ≃ₗ[R] Mᵒᵖ).to_add_equiv = op_add_equiv := rfl @[simp] lemma op_linear_equiv_symm_to_add_equiv : (op_linear_equiv R : M ≃ₗ[R] Mᵒᵖ).symm.to_add_equiv = op_add_equiv.symm := rfl end opposite
d5eabaf2c5a19d40a56a32f33713493f1d1b681d
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/complex/removable_singularity.lean
ce0694306c384c8331436950bf7c407e352876a7
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
7,330
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.calculus.fderiv_analytic import analysis.asymptotics.specific_asymptotics import analysis.complex.cauchy_integral /-! # Removable singularity theorem In this file we prove Riemann's removable singularity theorem: if `f : ℂ → E` is complex differentiable in a punctured neighborhood of a point `c` and is bounded in a punctured neighborhood of `c` (or, more generally, $f(z) - f(c)=o((z-c)^{-1})$), then it has a limit at `c` and the function `function.update f c (lim (𝓝[≠] c) f)` is complex differentiable in a neighborhood of `c`. -/ open topological_space metric set filter asymptotics function open_locale topological_space filter nnreal universe u variables {E : Type u} [normed_add_comm_group E] [normed_space ℂ E] [complete_space E] namespace complex /-- **Removable singularity** theorem, weak version. If `f : ℂ → E` is differentiable in a punctured neighborhood of a point and is continuous at this point, then it is analytic at this point. -/ lemma analytic_at_of_differentiable_on_punctured_nhds_of_continuous_at {f : ℂ → E} {c : ℂ} (hd : ∀ᶠ z in 𝓝[≠] c, differentiable_at ℂ f z) (hc : continuous_at f c) : analytic_at ℂ f c := begin rcases (nhds_within_has_basis nhds_basis_closed_ball _).mem_iff.1 hd with ⟨R, hR0, hRs⟩, lift R to ℝ≥0 using hR0.le, replace hc : continuous_on f (closed_ball c R), { refine λ z hz, continuous_at.continuous_within_at _, rcases eq_or_ne z c with rfl | hne, exacts [hc, (hRs ⟨hz, hne⟩).continuous_at] }, exact (has_fpower_series_on_ball_of_differentiable_off_countable (countable_singleton c) hc (λ z hz, hRs (diff_subset_diff_left ball_subset_closed_ball hz)) hR0).analytic_at end lemma differentiable_on_compl_singleton_and_continuous_at_iff {f : ℂ → E} {s : set ℂ} {c : ℂ} (hs : s ∈ 𝓝 c) : differentiable_on ℂ f (s \ {c}) ∧ continuous_at f c ↔ differentiable_on ℂ f s := begin refine ⟨_, λ hd, ⟨hd.mono (diff_subset _ _), (hd.differentiable_at hs).continuous_at⟩⟩, rintro ⟨hd, hc⟩ x hx, rcases eq_or_ne x c with rfl | hne, { refine (analytic_at_of_differentiable_on_punctured_nhds_of_continuous_at _ hc) .differentiable_at.differentiable_within_at, refine eventually_nhds_within_iff.2 ((eventually_mem_nhds.2 hs).mono $ λ z hz hzx, _), exact hd.differentiable_at (inter_mem hz (is_open_ne.mem_nhds hzx)) }, { simpa only [differentiable_within_at, has_fderiv_within_at, hne.nhds_within_diff_singleton] using hd x ⟨hx, hne⟩ } end lemma differentiable_on_dslope {f : ℂ → E} {s : set ℂ} {c : ℂ} (hc : s ∈ 𝓝 c) : differentiable_on ℂ (dslope f c) s ↔ differentiable_on ℂ f s := ⟨λ h, h.of_dslope, λ h, (differentiable_on_compl_singleton_and_continuous_at_iff hc).mp $ ⟨iff.mpr (differentiable_on_dslope_of_nmem $ λ h, h.2 rfl) (h.mono $ diff_subset _ _), continuous_at_dslope_same.2 $ h.differentiable_at hc⟩⟩ /-- **Removable singularity** theorem: if `s` is a neighborhood of `c : ℂ`, a function `f : ℂ → E` is complex differentiable on `s \ {c}`, and $f(z) - f(c)=o((z-c)^{-1})$, then `f` redefined to be equal to `lim (𝓝[≠] c) f` at `c` is complex differentiable on `s`. -/ lemma differentiable_on_update_lim_of_is_o {f : ℂ → E} {s : set ℂ} {c : ℂ} (hc : s ∈ 𝓝 c) (hd : differentiable_on ℂ f (s \ {c})) (ho : (λ z, f z - f c) =o[𝓝[≠] c] (λ z, (z - c)⁻¹)) : differentiable_on ℂ (update f c (lim (𝓝[≠] c) f)) s := begin set F : ℂ → E := λ z, (z - c) • f z with hF, suffices : differentiable_on ℂ F (s \ {c}) ∧ continuous_at F c, { rw [differentiable_on_compl_singleton_and_continuous_at_iff hc, ← differentiable_on_dslope hc, dslope_sub_smul] at this; try { apply_instance }, have hc : tendsto f (𝓝[≠] c) (𝓝 (deriv F c)), from continuous_at_update_same.mp (this.continuous_on.continuous_at hc), rwa hc.lim_eq }, refine ⟨(differentiable_on_id.sub_const _).smul hd, _⟩, rw ← continuous_within_at_compl_self, have H := ho.tendsto_inv_smul_nhds_zero, have H' : tendsto (λ z, (z - c) • f c) (𝓝[≠] c) (𝓝 (F c)), from (continuous_within_at_id.tendsto.sub tendsto_const_nhds).smul tendsto_const_nhds, simpa [← smul_add, continuous_within_at] using H.add H' end /-- **Removable singularity** theorem: if `s` is a punctured neighborhood of `c : ℂ`, a function `f : ℂ → E` is complex differentiable on `s`, and $f(z) - f(c)=o((z-c)^{-1})$, then `f` redefined to be equal to `lim (𝓝[≠] c) f` at `c` is complex differentiable on `{c} ∪ s`. -/ lemma differentiable_on_update_lim_insert_of_is_o {f : ℂ → E} {s : set ℂ} {c : ℂ} (hc : s ∈ 𝓝[≠] c) (hd : differentiable_on ℂ f s) (ho : (λ z, f z - f c) =o[𝓝[≠] c] (λ z, (z - c)⁻¹)) : differentiable_on ℂ (update f c (lim (𝓝[≠] c) f)) (insert c s) := differentiable_on_update_lim_of_is_o (insert_mem_nhds_iff.2 hc) (hd.mono $ λ z hz, hz.1.resolve_left hz.2) ho /-- **Removable singularity** theorem: if `s` is a neighborhood of `c : ℂ`, a function `f : ℂ → E` is complex differentiable and is bounded on `s \ {c}`, then `f` redefined to be equal to `lim (𝓝[≠] c) f` at `c` is complex differentiable on `s`. -/ lemma differentiable_on_update_lim_of_bdd_above {f : ℂ → E} {s : set ℂ} {c : ℂ} (hc : s ∈ 𝓝 c) (hd : differentiable_on ℂ f (s \ {c})) (hb : bdd_above (norm ∘ f '' (s \ {c}))) : differentiable_on ℂ (update f c (lim (𝓝[≠] c) f)) s := differentiable_on_update_lim_of_is_o hc hd $ is_bounded_under.is_o_sub_self_inv $ let ⟨C, hC⟩ := hb in ⟨C + ‖f c‖, eventually_map.2 $ mem_nhds_within_iff_exists_mem_nhds_inter.2 ⟨s, hc, λ z hz, norm_sub_le_of_le (hC $ mem_image_of_mem _ hz) le_rfl⟩⟩ /-- **Removable singularity** theorem: if a function `f : ℂ → E` is complex differentiable on a punctured neighborhood of `c` and $f(z) - f(c)=o((z-c)^{-1})$, then `f` has a limit at `c`. -/ lemma tendsto_lim_of_differentiable_on_punctured_nhds_of_is_o {f : ℂ → E} {c : ℂ} (hd : ∀ᶠ z in 𝓝[≠] c, differentiable_at ℂ f z) (ho : (λ z, f z - f c) =o[𝓝[≠] c] (λ z, (z - c)⁻¹)) : tendsto f (𝓝[≠] c) (𝓝 $ lim (𝓝[≠] c) f) := begin rw eventually_nhds_within_iff at hd, have : differentiable_on ℂ f ({z | z ≠ c → differentiable_at ℂ f z} \ {c}), from λ z hz, (hz.1 hz.2).differentiable_within_at, have H := differentiable_on_update_lim_of_is_o hd this ho, exact continuous_at_update_same.1 (H.differentiable_at hd).continuous_at end /-- **Removable singularity** theorem: if a function `f : ℂ → E` is complex differentiable and bounded on a punctured neighborhood of `c`, then `f` has a limit at `c`. -/ lemma tendsto_lim_of_differentiable_on_punctured_nhds_of_bounded_under {f : ℂ → E} {c : ℂ} (hd : ∀ᶠ z in 𝓝[≠] c, differentiable_at ℂ f z) (hb : is_bounded_under (≤) (𝓝[≠] c) (λ z, ‖f z - f c‖)) : tendsto f (𝓝[≠] c) (𝓝 $ lim (𝓝[≠] c) f) := tendsto_lim_of_differentiable_on_punctured_nhds_of_is_o hd hb.is_o_sub_self_inv end complex
d6bc6fdb052d0ce7461ed71ee5ddf8e94300cc1d
e030b0259b777fedcdf73dd966f3f1556d392178
/tests/lean/run/monad_univ_lift.lean
a9c23de9172f3c363e9b8122de55234d0bec5f50
[ "Apache-2.0" ]
permissive
fgdorais/lean
17b46a095b70b21fa0790ce74876658dc5faca06
c3b7c54d7cca7aaa25328f0a5660b6b75fe26055
refs/heads/master
1,611,523,590,686
1,484,412,902,000
1,484,412,902,000
38,489,734
0
0
null
1,435,923,380,000
1,435,923,379,000
null
UTF-8
Lean
false
false
436
lean
universe variables u v def M : Type u → Type v := sorry instance : monad M := sorry def act1 : M unit := return () def act2 : M (Σ (A : Type), A) := return ⟨nat, 0⟩ def {t s} up {A : Type s} (a : M A) : M (ulift.{t} A) := sorry def {t s} down {A : Type s} (a : M (ulift.{t} A)) : M A := sorry prefix `↑`:10 := up.{2} prefix `↓`:10 := down.{2} def ex : M unit := ↓do ↑act1, act2, ↑act1, act2, ↑act1
675a0e3c84d7b6ddbba4e2560b9f4874eeb02efb
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Meta/KAbstract.lean
aed457f85348529f424c4cee45d87065f6e5117d
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
2,026
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ import Lean.Data.Occurrences import Lean.HeadIndex import Lean.Meta.Basic namespace Lean.Meta /-- Abstract occurrences of `p` in `e`. We detect subterms equivalent to `p` using key-matching. That is, only perform `isDefEq` tests when the head symbol of substerm is equivalent to head symbol of `p`. By default, all occurrences are abstracted, but this behavior can be controlled using the `occs` parameter. -/ def kabstract (e : Expr) (p : Expr) (occs : Occurrences := .all) : MetaM Expr := do let e ← instantiateMVars e if p.isFVar && occs == Occurrences.all then return e.abstract #[p] -- Easy case else let pHeadIdx := p.toHeadIndex let pNumArgs := p.headNumArgs let rec visit (e : Expr) (offset : Nat) : StateRefT Nat MetaM Expr := do let visitChildren : Unit → StateRefT Nat MetaM Expr := fun _ => do match e with | .app f a => return e.updateApp! (← visit f offset) (← visit a offset) | .mdata _ b => return e.updateMData! (← visit b offset) | .proj _ _ b => return e.updateProj! (← visit b offset) | .letE _ t v b _ => return e.updateLet! (← visit t offset) (← visit v offset) (← visit b (offset+1)) | .lam _ d b _ => return e.updateLambdaE! (← visit d offset) (← visit b (offset+1)) | .forallE _ d b _ => return e.updateForallE! (← visit d offset) (← visit b (offset+1)) | e => return e if e.hasLooseBVars then visitChildren () else if e.toHeadIndex != pHeadIdx || e.headNumArgs != pNumArgs then visitChildren () else if (← isDefEq e p) then let i ← get set (i+1) if occs.contains i then return mkBVar offset else visitChildren () else visitChildren () visit e 0 |>.run' 1 end Lean.Meta
c08d14520789be5a51480939011895cb776a7e3a
0003047346476c031128723dfd16fe273c6bc605
/src/algebra/module.lean
cabf1bcdc2d2e65e224cfc1df8c3ac7ced08ae3f
[ "Apache-2.0" ]
permissive
ChandanKSingh/mathlib
d2bf4724ccc670bf24915c12c475748281d3fb73
d60d1616958787ccb9842dc943534f90ea0bab64
refs/heads/master
1,588,238,823,679
1,552,867,469,000
1,552,867,469,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,440
lean
/- Copyright (c) 2015 Nathaniel Thomas. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro Modules over a ring. -/ import algebra.ring algebra.big_operators group_theory.subgroup open function universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} /-- Typeclass for types with a scalar multiplication operation, denoted `•` (`\bu`) -/ class has_scalar (α : Type u) (γ : Type v) := (smul : α → γ → γ) infixr ` • `:73 := has_scalar.smul /-- A semimodule is a generalization of vector spaces to a scalar semiring. It consists of a scalar semiring `α` and an additive monoid of "vectors" `β`, connected by a "scalar multiplication" operation `r • x : β` (where `r : α` and `x : β`) with some natural associativity and distributivity axioms similar to those on a ring. -/ class semimodule (α : Type u) (β : Type v) [semiring α] [add_comm_monoid β] extends has_scalar α β := (smul_add : ∀(r : α) (x y : β), r • (x + y) = r • x + r • y) (add_smul : ∀(r s : α) (x : β), (r + s) • x = r • x + s • x) (mul_smul : ∀(r s : α) (x : β), (r * s) • x = r • s • x) (one_smul : ∀x : β, (1 : α) • x = x) (zero_smul : ∀x : β, (0 : α) • x = 0) (smul_zero {} : ∀(r : α), r • (0 : β) = 0) section semimodule variables [R:semiring α] [add_comm_monoid β] [semimodule α β] (r s : α) (x y : β) include R theorem smul_add : r • (x + y) = r • x + r • y := semimodule.smul_add r x y theorem add_smul : (r + s) • x = r • x + s • x := semimodule.add_smul r s x theorem mul_smul : (r * s) • x = r • s • x := semimodule.mul_smul r s x @[simp] theorem smul_zero : r • (0 : β) = 0 := semimodule.smul_zero r variables (α) @[simp] theorem one_smul : (1 : α) • x = x := semimodule.one_smul α x @[simp] theorem zero_smul : (0 : α) • x = 0 := semimodule.zero_smul α x lemma smul_smul : r • s • x = (r * s) • x := (mul_smul _ _ _).symm instance smul.is_add_monoid_hom {r : α} : is_add_monoid_hom (λ x : β, r • x) := by refine_struct {..}; simp [smul_add] end semimodule /-- A module is a generalization of vector spaces to a scalar ring. It consists of a scalar ring `α` and an additive group of "vectors" `β`, connected by a "scalar multiplication" operation `r • x : β` (where `r : α` and `x : β`) with some natural associativity and distributivity axioms similar to those on a ring. -/ class module (α : Type u) (β : Type v) [ring α] [add_comm_group β] extends semimodule α β structure module.core (α β) [ring α] [add_comm_group β] extends has_scalar α β := (smul_add : ∀(r : α) (x y : β), r • (x + y) = r • x + r • y) (add_smul : ∀(r s : α) (x : β), (r + s) • x = r • x + s • x) (mul_smul : ∀(r s : α) (x : β), (r * s) • x = r • s • x) (one_smul : ∀x : β, (1 : α) • x = x) def module.of_core {α β} [ring α] [add_comm_group β] (M : module.core α β) : module α β := by letI := M.to_has_scalar; exact { zero_smul := λ x, have (0 : α) • x + (0 : α) • x = (0 : α) • x + 0, by rw ← M.add_smul; simp, add_left_cancel this, smul_zero := λ r, have r • (0:β) + r • 0 = r • 0 + 0, by rw ← M.smul_add; simp, add_left_cancel this, ..M } section module variables [ring α] [add_comm_group β] [module α β] (r s : α) (x y : β) @[simp] theorem neg_smul : -r • x = - (r • x) := eq_neg_of_add_eq_zero (by rw [← add_smul, add_left_neg, zero_smul]) variables (α) theorem neg_one_smul (x : β) : (-1 : α) • x = -x := by simp variables {α} @[simp] theorem smul_neg : r • (-x) = -(r • x) := by rw [← neg_one_smul α, ← mul_smul, mul_neg_one, neg_smul] theorem smul_sub (r : α) (x y : β) : r • (x - y) = r • x - r • y := by simp [smul_add]; rw smul_neg theorem sub_smul (r s : α) (y : β) : (r - s) • y = r • y - s • y := by simp [add_smul] end module instance semiring.to_semimodule [r : semiring α] : semimodule α α := { smul := (*), smul_add := mul_add, add_smul := add_mul, mul_smul := mul_assoc, one_smul := one_mul, zero_smul := zero_mul, smul_zero := mul_zero, ..r } @[simp] lemma smul_eq_mul [semiring α] {a a' : α} : a • a' = a * a' := rfl instance ring.to_module [r : ring α] : module α α := { ..semiring.to_semimodule } class is_linear_map (α : Type u) {β : Type v} {γ : Type w} [ring α] [add_comm_group β] [add_comm_group γ] [module α β] [module α γ] (f : β → γ) : Prop := (add : ∀x y, f (x + y) = f x + f y) (smul : ∀(c : α) x, f (c • x) = c • f x) structure linear_map (α : Type u) (β : Type v) (γ : Type w) [ring α] [add_comm_group β] [add_comm_group γ] [module α β] [module α γ] := (to_fun : β → γ) (add : ∀x y, to_fun (x + y) = to_fun x + to_fun y) (smul : ∀(c : α) x, to_fun (c • x) = c • to_fun x) infixr ` →ₗ `:25 := linear_map _ notation β ` →ₗ[`:25 α `] ` γ := linear_map α β γ namespace linear_map variables [ring α] [add_comm_group β] [add_comm_group γ] [add_comm_group δ] variables [module α β] [module α γ] [module α δ] variables (f g : β →ₗ[α] γ) include α instance : has_coe_to_fun (β →ₗ[α] γ) := ⟨_, to_fun⟩ theorem is_linear : is_linear_map α f := {..f} @[extensionality] theorem ext {f g : β →ₗ[α] γ} (H : ∀ x, f x = g x) : f = g := by cases f; cases g; congr'; exact funext H theorem ext_iff {f g : β →ₗ[α] γ} : f = g ↔ ∀ x, f x = g x := ⟨by rintro rfl; simp, ext⟩ @[simp] lemma map_add (x y : β) : f (x + y) = f x + f y := f.add x y @[simp] lemma map_smul (c : α) (x : β) : f (c • x) = c • f x := f.smul c x @[simp] lemma map_zero : f 0 = 0 := by rw [← zero_smul α, map_smul f 0 0, zero_smul] instance : is_add_group_hom f := ⟨map_add f⟩ @[simp] lemma map_neg (x : β) : f (- x) = - f x := by rw [← neg_one_smul α, map_smul, neg_one_smul] @[simp] lemma map_sub (x y : β) : f (x - y) = f x - f y := by simp [map_neg, map_add] @[simp] lemma map_sum {ι} {t : finset ι} {g : ι → β} : f (t.sum g) = t.sum (λi, f (g i)) := (finset.sum_hom f).symm def comp (f : γ →ₗ[α] δ) (g : β →ₗ[α] γ) : β →ₗ[α] δ := ⟨f ∘ g, by simp, by simp⟩ @[simp] lemma comp_apply (f : γ →ₗ[α] δ) (g : β →ₗ[α] γ) (x : β) : f.comp g x = f (g x) := rfl def id : β →ₗ[α] β := ⟨id, by simp, by simp⟩ @[simp] lemma id_apply (x : β) : @id α β _ _ _ x = x := rfl end linear_map namespace is_linear_map variables [ring α] [add_comm_group β] [add_comm_group γ] variables [module α β] [module α γ] include α def mk' (f : β → γ) (H : is_linear_map α f) : β →ₗ γ := {to_fun := f, ..H} @[simp] theorem mk'_apply {f : β → γ} (H : is_linear_map α f) (x : β) : mk' f H x = f x := rfl end is_linear_map /-- A submodule of a module is one which is closed under vector operations. This is a sufficient condition for the subset of vectors in the submodule to themselves form a module. -/ structure submodule (α : Type u) (β : Type v) [ring α] [add_comm_group β] [module α β] : Type v := (carrier : set β) (zero : (0:β) ∈ carrier) (add : ∀ {x y}, x ∈ carrier → y ∈ carrier → x + y ∈ carrier) (smul : ∀ (c:α) {x}, x ∈ carrier → c • x ∈ carrier) namespace submodule variables [ring α] [add_comm_group β] [add_comm_group γ] variables [module α β] [module α γ] variables (p p' : submodule α β) variables {r : α} {x y : β} instance : has_coe (submodule α β) (set β) := ⟨submodule.carrier⟩ instance : has_mem β (submodule α β) := ⟨λ x p, x ∈ (p : set β)⟩ @[simp] theorem mem_coe : x ∈ (p : set β) ↔ x ∈ p := iff.rfl theorem ext' {s t : submodule α β} (h : (s : set β) = t) : s = t := by cases s; cases t; congr' protected theorem ext'_iff {s t : submodule α β} : (s : set β) = t ↔ s = t := ⟨ext', λ h, h ▸ rfl⟩ @[extensionality] theorem ext {s t : submodule α β} (h : ∀ x, x ∈ s ↔ x ∈ t) : s = t := ext' $ set.ext h @[simp] lemma zero_mem : (0 : β) ∈ p := p.zero lemma add_mem (h₁ : x ∈ p) (h₂ : y ∈ p) : x + y ∈ p := p.add h₁ h₂ lemma smul_mem (r : α) (h : x ∈ p) : r • x ∈ p := p.smul r h lemma neg_mem (hx : x ∈ p) : -x ∈ p := by rw ← neg_one_smul α; exact p.smul_mem _ hx lemma sub_mem (hx : x ∈ p) (hy : y ∈ p) : x - y ∈ p := p.add_mem hx (p.neg_mem hy) lemma neg_mem_iff : -x ∈ p ↔ x ∈ p := ⟨λ h, by simpa using neg_mem p h, neg_mem p⟩ lemma add_mem_iff_left (h₁ : y ∈ p) : x + y ∈ p ↔ x ∈ p := ⟨λ h₂, by simpa using sub_mem _ h₂ h₁, λ h₂, add_mem _ h₂ h₁⟩ lemma add_mem_iff_right (h₁ : x ∈ p) : x + y ∈ p ↔ y ∈ p := ⟨λ h₂, by simpa using sub_mem _ h₂ h₁, add_mem _ h₁⟩ lemma sum_mem {ι : Type w} [decidable_eq ι] {t : finset ι} {f : ι → β} : (∀c∈t, f c ∈ p) → t.sum f ∈ p := finset.induction_on t (by simp [p.zero_mem]) (by simp [p.add_mem] {contextual := tt}) instance : has_add p := ⟨λx y, ⟨x.1 + y.1, add_mem _ x.2 y.2⟩⟩ instance : has_zero p := ⟨⟨0, zero_mem _⟩⟩ instance : has_neg p := ⟨λx, ⟨-x.1, neg_mem _ x.2⟩⟩ instance : has_scalar α p := ⟨λ c x, ⟨c • x.1, smul_mem _ c x.2⟩⟩ @[simp] lemma coe_add (x y : p) : (↑(x + y) : β) = ↑x + ↑y := rfl @[simp] lemma coe_zero : ((0 : p) : β) = 0 := rfl @[simp] lemma coe_neg (x : p) : ((-x : p) : β) = -x := rfl @[simp] lemma coe_smul (r : α) (x : p) : ((r • x : p) : β) = r • ↑x := rfl instance : add_comm_group p := by refine {add := (+), zero := 0, neg := has_neg.neg, ..}; { intros, apply set_coe.ext, simp } instance submodule_is_add_subgroup : is_add_subgroup (p : set β) := { zero_mem := p.zero, add_mem := p.add, neg_mem := λ _, p.neg_mem } lemma coe_sub (x y : p) : (↑(x - y) : β) = ↑x - ↑y := by simp instance : module α p := by refine {smul := (•), ..}; { intros, apply set_coe.ext, simp [smul_add, add_smul, mul_smul] } protected def subtype : p →ₗ[α] β := by refine {to_fun := coe, ..}; simp [coe_smul] @[simp] theorem subtype_apply (x : p) : p.subtype x = x := rfl end submodule @[reducible] def ideal (α : Type u) [comm_ring α] := submodule α α namespace ideal variables [comm_ring α] (I : ideal α) {a b : α} protected lemma zero_mem : (0 : α) ∈ I := I.zero_mem protected lemma add_mem : a ∈ I → b ∈ I → a + b ∈ I := I.add_mem lemma neg_mem_iff : -a ∈ I ↔ a ∈ I := I.neg_mem_iff lemma add_mem_iff_left : b ∈ I → (a + b ∈ I ↔ a ∈ I) := I.add_mem_iff_left lemma add_mem_iff_right : a ∈ I → (a + b ∈ I ↔ b ∈ I) := I.add_mem_iff_right protected lemma sub_mem : a ∈ I → b ∈ I → a - b ∈ I := I.sub_mem lemma mul_mem_left : b ∈ I → a * b ∈ I := I.smul_mem _ lemma mul_mem_right (h : a ∈ I) : a * b ∈ I := mul_comm b a ▸ I.mul_mem_left h end ideal /-- A vector space is the same as a module, except the scalar ring is actually a field. (This adds commutativity of the multiplication and existence of inverses.) This is the traditional generalization of spaces like `ℝ^n`, which have a natural addition operation and a way to multiply them by real numbers, but no multiplication operation between vectors. -/ class vector_space (α : Type u) (β : Type v) [discrete_field α] [add_comm_group β] extends module α β instance discrete_field.to_vector_space {α : Type*} [discrete_field α] : vector_space α α := { .. ring.to_module } /-- Subspace of a vector space. Defined to equal `submodule`. -/ @[reducible] def subspace (α : Type u) (β : Type v) [discrete_field α] [add_comm_group β] [vector_space α β] : Type v := submodule α β instance subspace.vector_space {α β} {f : discrete_field α} [add_comm_group β] [vector_space α β] (p : subspace α β) : vector_space α p := {..submodule.module p} namespace submodule variables {R:discrete_field α} [add_comm_group β] [add_comm_group γ] variables [vector_space α β] [vector_space α γ] variables (p p' : submodule α β) variables {r : α} {x y : β} include R theorem smul_mem_iff (r0 : r ≠ 0) : r • x ∈ p ↔ x ∈ p := ⟨λ h, by simpa [smul_smul, inv_mul_cancel r0] using p.smul_mem (r⁻¹) h, p.smul_mem r⟩ end submodule
1115951085199414f64da998094ac01a9d0ce345
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/ring.lean
f0d15a8954313dc4ac25bf164d4cd1930456f348
[ "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,833
lean
import tactic.ring import data.real.basic import algebra.parity example (x y : ℕ) : x + y = y + x := by ring example (x y : ℕ) : x + y + y = 2 * y + x := by ring example (x y : ℕ) : x + id y = y + id x := by ring! example {α} [comm_ring α] (x y : α) : x + y + y - x = 2 * y := by ring example (x y : ℚ) : x / 2 + x / 2 = x := by ring example (x y : ℚ) : (x + y) ^ 3 = x ^ 3 + y ^ 3 + 3 * (x * y ^ 2 + x ^ 2 * y) := by ring example (x y : ℝ) : (x + y) ^ 3 = x ^ 3 + y ^ 3 + 3 * (x * y ^ 2 + x ^ 2 * y) := by ring example {α} [comm_semiring α] (x : α) : (x + 1) ^ 6 = (1 + x) ^ 6 := by try_for 15000 {ring} example (n : ℕ) : (n / 2) + (n / 2) = 2 * (n / 2) := by ring example {α} [field α] [char_zero α] (a : α) : a / 2 = a / 2 := by ring example {α} [linear_ordered_field α] (a b c : α) : a * (-c / b) * (-c / b) + -c + c = a * (c / b * (c / b)) := by ring example {α} [linear_ordered_field α] (a b c : α) : b ^ 2 - 4 * c * a = -(4 * c * a) + b ^ 2 := by ring example (x : ℚ) : x ^ (2 + 2) = x^4 := by ring_nf -- TODO: ring should work? example {α} [comm_ring α] (x : α) : x ^ 2 = x * x := by ring example {α} [linear_ordered_field α] (a b c : α) : b ^ 2 - 4 * c * a = -(4 * c * a) + b ^ 2 := by ring example {α} [linear_ordered_field α] (a b c : α) : b ^ 2 - 4 * a * c = 4 * a * 0 + b * b - 4 * a * c := by ring example {α} [comm_semiring α] (x y z : α) (n : ℕ) : (x + y) * (z * (y * y) + (x * x ^ n + (1 + ↑n) * x ^ n * y)) = x * (x * x ^ n) + ((2 + ↑n) * (x * x ^ n) * y + (x * z + (z * y + (1 + ↑n) * x ^ n)) * (y * y)) := by ring example {α} [comm_ring α] (a b c d e : α) : (-(a * b) + c + d) * e = (c + (d + -a * b)) * e := by ring example (a n s: ℕ) : a * (n - s) = (n - s) * a := by ring example (x y z : ℚ) (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) : x / (y / z) + y ⁻¹ + 1 / (y * -x) = -1/ (x * y) + (x * z + 1) / y := begin field_simp, ring end example {A : ℤ} (f : ℤ → ℤ) : f 0 = f (A - A) := by ring_nf example {A : ℤ} (f : ℤ → ℤ) : f 0 = f (A + -A) := by ring_nf example {a b c : ℝ} (h : 0 < a ^ 4 + b ^ 4 + c ^ 4) : a ^ 4 / (a ^ 4 + b ^ 4 + c ^ 4) + b ^ 4 / (b ^ 4 + c ^ 4 + a ^ 4) + c ^ 4 / (c ^ 4 + a ^ 4 + b ^ 4) = 1 := begin ring_nf at ⊢ h, field_simp [h.ne'], end example (a b c d x y : ℚ) (hx : x ≠ 0) (hy : y ≠ 0) : a + b / x - c / x^2 + d / x^3 = a + x⁻¹ * (y * b / y + (d / x - c) / x) := begin field_simp, ring end example : (876544 : ℤ) * -1 + (1000000 - 123456) = 0 := by ring example (x y : ℝ) (hx : x ≠ 0) (hy : y ≠ 0) : 2 * x ^ 3 * 2 / (24 * x) = x ^ 2 / 6 := begin field_simp, ring end -- this proof style is not recommended practice example (A B : ℕ) (H : B * A = 2) : A * B = 2 := by {ring_nf, exact H} example (a : ℤ) : odd ((2 * a + 1) ^ 2) := begin use 2 * a ^ 2 + 2 * a, ring_nf, end example {x y : ℝ} (hxy : -y ^ 2 + x ^ 2 = -(5 * y) + 5 * x) : x ^ 2 - y ^ 2 = 5 * x - 5 * y := begin ring_nf at hxy ⊢, exact hxy end example {α} [field α] {x y : α} (h : 0 = (1 - x) ^ 2 * (x * (2 ^ 2 * y ^ 2 + 4 * (1 - x) ^ 2))) : 0 = x * ((2 ^ 2 * y ^ 2 + 4 * (1 - x) ^ 2) * (1 - x) ^ 2) := by transitivity; [exact h, ring] -- `ring_nf` should descend into the subexpressions `x * -a` and `-a * x`: example {a x : ℚ} : x * -a = - a * x := by ring_nf example (f : ℤ → ℤ) (a b : ℤ) : f (2 * a + b) + b = b + f (b + a + a) := begin success_if_fail {{ ring_nf {recursive := ff} }}, ring_nf end -- instances do not have to syntactically be `monoid.has_pow` example {R} [comm_semiring R] (x : ℕ → R) : x ^ 2 = x * x := by ring -- even if there's an instance we don't recognize, we treat it as an atom example {R} [field R] (x : ℕ → R) : (x ^ (2 : ℤ)) ^ 2 = (x ^ (2 : ℤ)) * (x ^ (2 : ℤ)) := by ring
4584c21f188a355aac78db5d90037e018161550f
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/omega_complete_partial_order.lean
395258fa713007e1afa04f6389856720cae29eb4
[ "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
4,820
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import topology.basic import order.omega_complete_partial_order /-! # Scott Topological Spaces A type of topological spaces whose notion of continuity is equivalent to continuity in ωCPOs. ## Reference * https://ncatlab.org/nlab/show/Scott+topology -/ open omega_complete_partial_order open_locale classical universes u namespace Scott /-- `x` is an `ω`-Sup of a chain `c` if it is the least upper bound of the range of `c`. -/ def is_ωSup {α : Type u} [preorder α] (c : chain α) (x : α) : Prop := (∀ i, c i ≤ x) ∧ (∀ y, (∀ i, c i ≤ y) → x ≤ y) lemma is_ωSup_iff_is_lub {α : Type u} [preorder α] {c : chain α} {x : α} : is_ωSup c x ↔ is_lub (set.range c) x := by simp [is_ωSup, is_lub, is_least, upper_bounds, lower_bounds] variables (α : Type u) [omega_complete_partial_order α] local attribute [irreducible] set /-- The characteristic function of open sets is monotone and preserves the limits of chains. -/ def is_open (s : set α) : Prop := continuous' (λ x, x ∈ s) theorem is_open_univ : is_open α set.univ := ⟨λ x y h, by simp only [set.mem_univ]; refl', by convert @complete_lattice.top_continuous α Prop _ _; ext; simp ⟩ theorem is_open.inter (s t : set α) : is_open α s → is_open α t → is_open α (s ∩ t) := complete_lattice.inf_continuous' theorem is_open_sUnion (s : set (set α)) (hs : ∀t∈s, is_open α t) : is_open α (⋃₀ s) := begin simp only [is_open] at hs ⊢, convert complete_lattice.Sup_continuous' (set_of ⁻¹' s) _, { ext1 x, simp only [Sup_apply, set.set_of_bijective.surjective.exists, exists_prop, set.mem_preimage, set_coe.exists, supr_Prop_eq, set.mem_set_of_eq, subtype.coe_mk] }, { intros p hp, convert hs (set_of p) (set.mem_preimage.1 hp), simp only [set.mem_set_of_eq] }, end end Scott /-- A Scott topological space is defined on preorders such that their open sets, seen as a function `α → Prop`, preserves the joins of ω-chains -/ @[reducible] def Scott (α : Type u) := α instance Scott.topological_space (α : Type u) [omega_complete_partial_order α] : topological_space (Scott α) := { is_open := Scott.is_open α, is_open_univ := Scott.is_open_univ α, is_open_inter := Scott.is_open.inter α, is_open_sUnion := Scott.is_open_sUnion α } section not_below variables {α : Type*} [omega_complete_partial_order α] (y : Scott α) /-- `not_below` is an open set in `Scott α` used to prove the monotonicity of continuous functions -/ def not_below := { x | ¬ x ≤ y } lemma not_below_is_open : is_open (not_below y) := begin have h : monotone (not_below y), { intros x y' h, simp only [not_below, set_of, le_Prop_eq], intros h₀ h₁, apply h₀ (le_trans h h₁) }, existsi h, rintros c, apply eq_of_forall_ge_iff, intro z, rw ωSup_le_iff, simp only [ωSup_le_iff, not_below, set.mem_set_of_eq, le_Prop_eq, order_hom.coe_fun_mk, chain.map_coe, function.comp_app, exists_imp_distrib, not_forall], end end not_below open Scott (hiding is_open) open omega_complete_partial_order lemma is_ωSup_ωSup {α} [omega_complete_partial_order α] (c : chain α) : is_ωSup c (ωSup c) := begin split, { apply le_ωSup, }, { apply ωSup_le, }, end lemma Scott_continuous_of_continuous {α β} [omega_complete_partial_order α] [omega_complete_partial_order β] (f : Scott α → Scott β) (hf : continuous f) : omega_complete_partial_order.continuous' f := begin simp only [continuous_def, (⁻¹')] at hf, have h : monotone f, { intros x y h, cases (hf {x | ¬ x ≤ f y} (not_below_is_open _)) with hf hf', clear hf', specialize hf h, simp only [set.preimage, set_of, (∈), set.mem, le_Prop_eq] at hf, by_contradiction H, apply hf H (le_refl (f y)) }, existsi h, intro c, apply eq_of_forall_ge_iff, intro z, specialize (hf _ (not_below_is_open z)), cases hf, specialize hf_h c, simp only [not_below, order_hom.coe_fun_mk, eq_iff_iff, set.mem_set_of_eq] at hf_h, rw [← not_iff_not], simp only [ωSup_le_iff, hf_h, ωSup, supr, Sup, complete_lattice.Sup, complete_semilattice_Sup.Sup, exists_prop, set.mem_range, order_hom.coe_fun_mk, chain.map_coe, function.comp_app, eq_iff_iff, not_forall], tauto, end lemma continuous_of_Scott_continuous {α β} [omega_complete_partial_order α] [omega_complete_partial_order β] (f : Scott α → Scott β) (hf : omega_complete_partial_order.continuous' f) : continuous f := begin rw continuous_def, intros s hs, change continuous' (s ∘ f), cases hs with hs hs', cases hf with hf hf', apply continuous.of_bundled, apply continuous_comp _ _ hf' hs', end