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
5f466182fb283d211713bdfa62f984c2f99afc5d
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/data/equiv/denumerable.lean
0cf55c33ae1c8cc81f68013a323247a474c777bd
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
8,831
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Denumerable (countably infinite) types, as a typeclass extending encodable. This is used to provide explicit encode/decode functions from nat, where the functions are known inverses of each other. -/ import data.equiv.encodable data.sigma data.fintype data.list.min_max open nat /-- A denumerable type is one which is (constructively) bijective with ℕ. Although we already have a name for this property, namely `α ≃ ℕ`, we are here interested in using it as a typeclass. -/ class denumerable (α : Type*) extends encodable α := (decode_inv : ∀ n, ∃ a ∈ decode n, encode a = n) namespace denumerable section variables {α : Type*} {β : Type*} [denumerable α] [denumerable β] open encodable @[simp] theorem decode_is_some (α) [denumerable α] (n : ℕ) : (decode α n).is_some := option.is_some_iff_exists.2 $ (decode_inv α n).imp $ λ a, Exists.fst def of_nat (α) [f : denumerable α] (n : ℕ) : α := option.get (decode_is_some α n) @[simp] theorem decode_eq_of_nat (α) [denumerable α] (n : ℕ) : decode α n = some (of_nat α n) := option.eq_some_of_is_some _ @[simp] theorem of_nat_of_decode {n b} (h : decode α n = some b) : of_nat α n = b := option.some.inj $ (decode_eq_of_nat _ _).symm.trans h @[simp] theorem encode_of_nat (n) : encode (of_nat α n) = n := let ⟨a, h, e⟩ := decode_inv α n in by rwa [of_nat_of_decode h] @[simp] theorem of_nat_encode (a) : of_nat α (encode a) = a := of_nat_of_decode (encodek _) def eqv (α) [denumerable α] : α ≃ ℕ := ⟨encode, of_nat α, of_nat_encode, encode_of_nat⟩ def mk' {α} (e : α ≃ ℕ) : denumerable α := { encode := e, decode := some ∘ e.symm, encodek := λ a, congr_arg some (e.symm_apply_apply _), decode_inv := λ n, ⟨_, rfl, e.apply_symm_apply _⟩ } def of_equiv (α) {β} [denumerable α] (e : β ≃ α) : denumerable β := { decode_inv := λ n, by simp, ..encodable.of_equiv _ e } @[simp] theorem of_equiv_of_nat (α) {β} [denumerable α] (e : β ≃ α) (n) : @of_nat β (of_equiv _ e) n = e.symm (of_nat α n) := by apply of_nat_of_decode; show option.map _ _ = _; simp def equiv₂ (α β) [denumerable α] [denumerable β] : α ≃ β := (eqv α).trans (eqv β).symm instance nat : denumerable nat := ⟨λ n, ⟨_, rfl, rfl⟩⟩ @[simp] theorem of_nat_nat (n) : of_nat ℕ n = n := rfl instance option : denumerable (option α) := ⟨λ n, by cases n; simp⟩ instance sum : denumerable (α ⊕ β) := ⟨λ n, begin suffices : ∃ a ∈ @decode_sum α β _ _ n, encode_sum a = bit (bodd n) (div2 n), {simpa [bit_decomp]}, simp [decode_sum]; cases bodd n; simp [decode_sum, bit, encode_sum] end⟩ section sigma variables {γ : α → Type*} [∀ a, denumerable (γ a)] instance sigma : denumerable (sigma γ) := ⟨λ n, by simp [decode_sigma]; exact ⟨_, _, ⟨rfl, heq.rfl⟩, by simp⟩⟩ @[simp] theorem sigma_of_nat_val (n : ℕ) : of_nat (sigma γ) n = ⟨of_nat α (unpair n).1, of_nat (γ _) (unpair n).2⟩ := option.some.inj $ by rw [← decode_eq_of_nat, decode_sigma_val]; simp; refl end sigma instance prod : denumerable (α × β) := of_equiv _ (equiv.sigma_equiv_prod α β).symm @[simp] theorem prod_of_nat_val (n : ℕ) : of_nat (α × β) n = (of_nat α (unpair n).1, of_nat β (unpair n).2) := by simp; refl @[simp] theorem prod_nat_of_nat : of_nat (ℕ × ℕ) = unpair := by funext; simp instance int : denumerable ℤ := denumerable.mk' equiv.int_equiv_nat instance pnat : denumerable ℕ+ := denumerable.mk' equiv.pnat_equiv_nat instance ulift : denumerable (ulift α) := of_equiv _ equiv.ulift instance plift : denumerable (plift α) := of_equiv _ equiv.plift def pair : α × α ≃ α := equiv₂ _ _ end end denumerable namespace nat.subtype open function encodable lattice variables {s : set ℕ} [decidable_pred s] [infinite s] lemma exists_succ (x : s) : ∃ n, x.1 + n + 1 ∈ s := classical.by_contradiction $ λ h, have ∀ (a : ℕ) (ha : a ∈ s), a < x.val.succ, from λ a ha, lt_of_not_ge (λ hax, h ⟨a - (x.1 + 1), by rwa [add_right_comm, nat.add_sub_cancel' hax]⟩), infinite.not_fintype ⟨(((multiset.range x.1.succ).filter (∈ s)).pmap (λ (y : ℕ) (hy : y ∈ s), subtype.mk y hy) (by simp [-multiset.range_succ])).to_finset, by simpa [subtype.ext, multiset.mem_filter, -multiset.range_succ]⟩ def succ (x : s) : s := have h : ∃ m, x.1 + m + 1 ∈ s, from exists_succ x, ⟨x.1 + nat.find h + 1, nat.find_spec h⟩ lemma succ_le_of_lt {x y : s} (h : y < x) : succ y ≤ x := have hx : ∃ m, y.1 + m + 1 ∈ s, from exists_succ _, let ⟨k, hk⟩ := nat.exists_eq_add_of_lt h in have nat.find hx ≤ k, from nat.find_min' _ (hk ▸ x.2), show y.1 + nat.find hx + 1 ≤ x.1, by rw hk; exact add_le_add_right (add_le_add_left this _) _ lemma le_succ_of_forall_lt_le {x y : s} (h : ∀ z < x, z ≤ y) : x ≤ succ y := have hx : ∃ m, y.1 + m + 1 ∈ s, from exists_succ _, show x.1 ≤ y.1 + nat.find hx + 1, from le_of_not_gt $ λ hxy, have y.1 + nat.find hx + 1 ≤ y.1 := h ⟨_, nat.find_spec hx⟩ hxy, not_lt_of_le this $ calc y.1 ≤ y.1 + nat.find hx : le_add_of_nonneg_right (nat.zero_le _) ... < y.1 + nat.find hx + 1 : nat.lt_succ_self _ lemma lt_succ_self (x : s) : x < succ x := calc x.1 ≤ x.1 + _ : le_add_right (le_refl _) ... < succ x : nat.lt_succ_self (x.1 + _) lemma lt_succ_iff_le {x y : s} : x < succ y ↔ x ≤ y := ⟨λ h, le_of_not_gt (λ h', not_le_of_gt h (succ_le_of_lt h')), λ h, lt_of_le_of_lt h (lt_succ_self _)⟩ def of_nat (s : set ℕ) [decidable_pred s] [infinite s] : ℕ → s | 0 := ⊥ | (n+1) := succ (of_nat n) lemma of_nat_surjective_aux : ∀ {x : ℕ} (hx : x ∈ s), ∃ n, of_nat s n = ⟨x, hx⟩ | x := λ hx, let t : list s := ((list.range x).filter (λ y, y ∈ s)).pmap (λ (y : ℕ) (hy : y ∈ s), ⟨y, hy⟩) (by simp) in have hmt : ∀ {y : s}, y ∈ t ↔ y < ⟨x, hx⟩, by simp [list.mem_filter, subtype.ext, t]; intros; refl, if ht : t = [] then ⟨0, le_antisymm (@bot_le s _ _) (le_of_not_gt (λ h, list.not_mem_nil ⊥ $ by rw [← ht, hmt]; exact h))⟩ else by letI : inhabited s := ⟨⊥⟩; exact have wf : (list.maximum t).1 < x, by simpa [hmt] using list.maximum_mem ht, let ⟨a, ha⟩ := of_nat_surjective_aux (list.maximum t).2 in ⟨a + 1, le_antisymm (by rw of_nat; exact succ_le_of_lt (by rw ha; exact wf)) $ by rw of_nat; exact le_succ_of_forall_lt_le (λ z hz, by rw ha; exact list.le_maximum_of_mem (hmt.2 hz))⟩ lemma of_nat_surjective : surjective (of_nat s) := λ ⟨x, hx⟩, of_nat_surjective_aux hx private def to_fun_aux (x : s) : ℕ := (list.range x).countp s private lemma to_fun_aux_eq (x : s) : to_fun_aux x = ((finset.range x).filter s).card := by rw [to_fun_aux, list.countp_eq_length_filter]; refl open finset private lemma right_inverse_aux : ∀ n, to_fun_aux (of_nat s n) = n | 0 := begin rw [to_fun_aux_eq, card_eq_zero, eq_empty_iff_forall_not_mem], assume n, rw [mem_filter, of_nat, mem_range], assume h, exact not_lt_of_le bot_le (show (⟨n, h.2⟩ : s) < ⊥, from h.1) end | (n+1) := have ih : to_fun_aux (of_nat s n) = n, from right_inverse_aux n, have h₁ : (of_nat s n : ℕ) ∉ (range (of_nat s n)).filter s, by simp, have h₂ : (range (succ (of_nat s n))).filter s = insert (of_nat s n) ((range (of_nat s n)).filter s), begin simp only [finset.ext, mem_insert, mem_range, mem_filter], assume m, exact ⟨λ h, by simp only [h.2, and_true]; exact or.symm (lt_or_eq_of_le ((@lt_succ_iff_le _ _ _ ⟨m, h.2⟩ _).1 h.1)), λ h, h.elim (λ h, h.symm ▸ ⟨lt_succ_self _, subtype.property _⟩) (λ h, ⟨lt_of_le_of_lt (le_of_lt h.1) (lt_succ_self _), h.2⟩)⟩ end, begin clear_aux_decl, simp only [to_fun_aux_eq, of_nat, range_succ] at *, conv {to_rhs, rw [← ih, ← card_insert_of_not_mem h₁, ← h₂] }, end def denumerable (s : set ℕ) [decidable_pred s] [infinite s] : denumerable s := denumerable.of_equiv ℕ { to_fun := to_fun_aux, inv_fun := of_nat s, left_inv := left_inverse_of_surjective_of_right_inverse of_nat_surjective right_inverse_aux, right_inv := right_inverse_aux } end nat.subtype namespace denumerable open encodable def of_encodable_of_infinite (α : Type*) [encodable α] [infinite α] : denumerable α := begin letI := @decidable_range_encode α _; letI : infinite (set.range (@encode α _)) := infinite.of_injective _ (equiv.set.range _ encode_injective).injective, letI := nat.subtype.denumerable (set.range (@encode α _)), exact denumerable.of_equiv (set.range (@encode α _)) (equiv_range_encode α) end end denumerable
bfbafa88cbd114fbcfd9e4da2c83cb7aaf0e6679
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/src/Lean/Meta/Tactic/FVarSubst.lean
ebc51dac71467fff4a488edf2072c565f8779659
[ "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
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
2,309
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Data.AssocList import Lean.Expr import Lean.LocalContext import Lean.Util.ReplaceExpr namespace Lean.Meta /-- Some tactics substitute hypotheses with expressions. We track these substitutions using `FVarSubst`. It is just a mapping from the original FVarId (internal) name to an expression. The free variables occurring in the expression must be defined in the new goal. -/ structure FVarSubst where map : AssocList FVarId Expr := {} deriving Inhabited namespace FVarSubst def empty : FVarSubst := {} def isEmpty (s : FVarSubst) : Bool := s.map.isEmpty def contains (s : FVarSubst) (fvarId : FVarId) : Bool := s.map.contains fvarId /-- Add entry `fvarId |-> v` to `s` if `s` does not contain an entry for `fvarId`. -/ def insert (s : FVarSubst) (fvarId : FVarId) (v : Expr) : FVarSubst := if s.contains fvarId then s else let map := s.map.mapVal fun e => e.replaceFVarId fvarId v; { map := map.insert fvarId v } def erase (s : FVarSubst) (fvarId : FVarId) : FVarSubst := { map := s.map.erase fvarId } def find? (s : FVarSubst) (fvarId : FVarId) : Option Expr := s.map.find? fvarId def get (s : FVarSubst) (fvarId : FVarId) : Expr := match s.map.find? fvarId with | none => mkFVar fvarId -- it has not been replaced | some v => v /-- Given `e`, for each `(x => v)` in `s` replace `x` with `v` in `e` -/ def apply (s : FVarSubst) (e : Expr) : Expr := if s.map.isEmpty then e else if !e.hasFVar then e else e.replace fun e => match e with | Expr.fvar fvarId => match s.map.find? fvarId with | none => e | some v => v | _ => none def domain (s : FVarSubst) : List FVarId := s.map.foldl (init := []) fun r k _ => k :: r def any (p : FVarId → Expr → Bool) (s : FVarSubst) : Bool := s.map.any p end FVarSubst end Meta def LocalDecl.applyFVarSubst (s : Meta.FVarSubst) : LocalDecl → LocalDecl | LocalDecl.cdecl i id n t bi => LocalDecl.cdecl i id n (s.apply t) bi | LocalDecl.ldecl i id n t v nd => LocalDecl.ldecl i id n (s.apply t) (s.apply v) nd abbrev Expr.applyFVarSubst (s : Meta.FVarSubst) (e : Expr) : Expr := s.apply e end Lean
ee52c75208c14f8f6be352572dcf81c3daeb46d6
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/meta/tactic.lean
720cd26bcecb1d3b3d06e574008f54743347c53a
[]
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
20,155
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.function import Mathlib.Lean3Lib.init.data.option.basic import Mathlib.Lean3Lib.init.util import Mathlib.Lean3Lib.init.control.combinators import Mathlib.Lean3Lib.init.control.monad import Mathlib.Lean3Lib.init.control.alternative import Mathlib.Lean3Lib.init.control.monad_fail import Mathlib.Lean3Lib.init.data.nat.div import Mathlib.Lean3Lib.init.meta.exceptional import Mathlib.Lean3Lib.init.meta.format import Mathlib.Lean3Lib.init.meta.environment import Mathlib.Lean3Lib.init.meta.pexpr import Mathlib.Lean3Lib.init.data.repr import Mathlib.Lean3Lib.init.data.string.basic import Mathlib.Lean3Lib.init.meta.interaction_monad import Mathlib.Lean3Lib.init.classical universes l namespace Mathlib infixl:2 " >>=[tactic] " => Mathlib.interaction_monad_bind infixl:2 " >>[tactic] " => Mathlib.interaction_monad_seq namespace tactic_state /-- Format the given tactic state. If `target_lhs_only` is true and the target is of the form `lhs ~ rhs`, where `~` is a simplification relation, then only the `lhs` is displayed. Remark: the parameter `target_lhs_only` is a temporary hack used to implement the `conv` monad. It will be removed in the future. -/ /-- 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. -/ end tactic_state /-- `tactic` is the monad for building tactics. You use this to: - View and modify the local goals and hypotheses in the prover's state. - Invoke type checking and elaboration of terms. - View and modify the environment. - Build new tactics out of existing ones such as `simp` and `rewrite`. -/ namespace tactic end tactic namespace tactic_result end tactic_result namespace interactive /-- Typeclass for custom interaction monads, which provides the information required to convert an interactive-mode construction to a `tactic` which can actually be executed. Given a `[monad m]`, `execute_with` explains how to turn a `begin ... end` block, or a `by ...` statement into a `tactic α` which can actually be executed. The `inhabited` first argument facilitates the passing of an optional configuration parameter `config`, using the syntax: ``` begin [custom_monad] with config, ... end ``` -/ /-- Default `executor` instance for `tactic`s themselves -/ end interactive namespace tactic /-- Does nothing. -/ /-- `try_core t` acts like `t`, but succeeds even if `t` fails. It returns the result of `t` if `t` succeeded and `none` otherwise. -/ /-- `try t` acts like `t`, but succeeds even if `t` fails. -/ /-- `fail_if_success t` acts like `t`, but succeeds if `t` fails and fails if `t` succeeds. Changes made by `t` to the `tactic_state` are preserved only if `t` succeeds. -/ /-- `success_if_fail t` acts like `t`, but succeeds if `t` fails and fails if `t` succeeds. Changes made by `t` to the `tactic_state` are preserved only if `t` succeeds. -/ /-- `iterate_at_most n t` iterates `t` `n` times or until `t` fails, returning the result of each successful iteration. -/ /-- `iterate_at_most' n t` repeats `t` `n` times or until `t` fails. -/ /-- `iterate_exactly n t` iterates `t` `n` times, returning the result of each iteration. If any iteration fails, the whole tactic fails. -/ /-- `iterate_exactly' n t` executes `t` `n` times. If any iteration fails, the whole tactic fails. -/ /-- `iterate t` repeats `t` 100.000 times or until `t` fails, returning the result of each iteration. -/ /-- `iterate' t` repeats `t` 100.000 times or until `t` fails. -/ /-- Decorate t's exceptions with msg. -/ /-- Set the tactic_state. -/ /-- Get the tactic_state. -/ /-- `capture t` acts like `t`, but succeeds with a result containing either the returned value or the exception. Changes made by `t` to the `tactic_state` are preserved in both cases. The result can be used to inspect the error message, or passed to `unwrap` to rethrow the failure later. -/ /-- `unwrap r` unwraps a result previously obtained using `capture`. If the previous result was a success, this produces its wrapped value. If the previous result was an exception, this "rethrows" the exception as if it came from where it originated. `do r ← capture t, unwrap r` is identical to `t`, but allows for intermediate tactics to be inserted. -/ /-- `resume r` continues execution from a result previously obtained using `capture`. This is like `unwrap`, but the `tactic_state` is rolled back to point of capture even upon success. -/ end tactic namespace tactic /-- A parameter representing how aggressively definitions should be unfolded when trying to decide if two terms match, unify or are definitionally equal. By default, theorem declarations are never unfolded. - `all` will unfold everything, including macros and theorems. Except projection macros. - `semireducible` will unfold everything except theorems and definitions tagged as irreducible. - `instances` will unfold all class instance definitions and definitions tagged with reducible. - `reducible` will only unfold definitions tagged with the `reducible` attribute. - `none` will never unfold anything. [NOTE] You are not allowed to tag a definition with more than one of `reducible`, `irreducible`, `semireducible` attributes. [NOTE] there is a config flag `m_unfold_lemmas`that will make it unfold theorems. -/ inductive transparency where | all : transparency | semireducible : transparency | instances : transparency | reducible : transparency | none : transparency /-- (eval_expr α e) evaluates 'e' IF 'e' has type 'α'. -/ /-- 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. -/ /-- 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. -/ /-- Return target type of the main goal. Fail if tactic_state does not have any goal left. -/ /-- Clear the given local constant. The tactic fails if the given expression is not a local constant. -/ /-- `revert_lst : list expr → tactic nat` is the reverse of `intron`. It takes a local constant `c` and puts it back as bound by a `pi` or `elet` of the main target. If there are other local constants that depend on `c`, these are also reverted. Because of this, the `nat` that is returned is the actual number of reverted local constants. Example: with `x : ℕ, h : P(x) ⊢ T(x)`, `revert_lst [x]` returns `2` and produces the state ` ⊢ Π x, P(x) → T(x)`. -/ /-- Return `e` in weak head normal form with respect to the given transparency setting. If `unfold_ginductive` is `tt`, then nested and/or mutually recursive inductive datatype constructors and types are unfolded. Recall that nested and mutually recursive inductive datatype declarations are compiled into primitive datatypes accepted by the Kernel. -/ /-- (head) eta expand the given expression. `f : α → β` head-eta-expands to `λ a, f a`. If `f` isn't a function then it just returns `f`. -/ /-- (head) beta reduction. `(λ x, B) c` reduces to `B[x/c]`. -/ /-- (head) zeta reduction. Reduction of let bindings at the head of the expression. `let x : a := b in c` reduces to `c[x/b]`. -/ /-- Zeta reduction. Reduction of let bindings. `let x : a := b in c` reduces to `c[x/b]`. -/ /-- (head) eta reduction. `(λ x, f x)` reduces to `f`. -/ /-- Succeeds if `t` and `s` can be unified using the given transparency setting. -/ /-- Similar to `unify`, but it treats metavariables as constants. -/ /-- Infer the type of the given expression. Remark: transparency does not affect type inference -/ /-- Get the `local_const` expr for the given `name`. -/ /-- Resolve a name using the current local context, environment, aliases, etc. -/ /-- Return the hypothesis in the main goal. Fail if tactic_state does not have any goal left. -/ /-- Get a fresh name that is guaranteed to not be in use in the local context. If `n` is provided and `n` is not in use, then `n` is returned. Otherwise a number `i` is appended to give `"n_i"`. -/ /-- Helper tactic for creating simple applications where some arguments are inferred using type inference. Example, given ``` rel.{l_1 l_2} : Pi (α : Type.{l_1}) (β : α -> Type.{l_2}), (Pi x : α, β x) -> (Pi x : α, β x) -> , Prop nat : Type real : Type vec.{l} : Pi (α : Type l) (n : nat), Type.{l1} f g : Pi (n : nat), vec real n ``` then ``` mk_app_core semireducible "rel" [f, g] ``` returns the application ``` rel.{1 2} nat (fun n : nat, vec real n) f g ``` The unification constraints due to type inference are solved using the transparency `md`. -/ /-- Similar to `mk_app`, but allows to specify which arguments are explicit/implicit. Example, given `(a b : nat)` then ``` mk_mapp "ite" [some (a > b), none, none, some a, some b] ``` returns the application ``` @ite.{1} (a > b) (nat.decidable_gt a b) nat a b ``` -/ /-- (mk_congr_arg h₁ h₂) is a more efficient version of (mk_app `congr_arg [h₁, h₂]) -/ /-- (mk_congr_fun h₁ h₂) is a more efficient version of (mk_app `congr_fun [h₁, h₂]) -/ /-- (mk_congr h₁ h₂) is a more efficient version of (mk_app `congr [h₁, h₂]) -/ /-- (mk_eq_refl h) is a more efficient version of (mk_app `eq.refl [h]) -/ /-- (mk_eq_symm h) is a more efficient version of (mk_app `eq.symm [h]) -/ /-- (mk_eq_trans h₁ h₂) is a more efficient version of (mk_app `eq.trans [h₁, h₂]) -/ /-- (mk_eq_mp h₁ h₂) is a more efficient version of (mk_app `eq.mp [h₁, h₂]) -/ /-- (mk_eq_mpr h₁ h₂) is a more efficient version of (mk_app `eq.mpr [h₁, h₂]) -/ /- Given a local constant t, if t has type (lhs = rhs) apply substitution. 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. -/ /-- Close the current goal using `e`. Fail if the type of `e` is not definitionally equal to the target type. -/ /-- Elaborate the given quoted expression with respect to the current main goal. Note that this means that any implicit arguments for the given `pexpr` will be applied with fresh metavariables. If `allow_mvars` is tt, then metavariables are tolerated and become new goals if `subgoals` is tt. -/ /-- Return true if the given expression is a type class. -/ /-- Try to create an instance of the given type class. -/ /-- Change the target of the main goal. The input expression must be definitionally equal to the current target. If `check` is `ff`, then the tactic does not check whether `e` is definitionally equal to the current target. If it is not, then the error will only be detected by the kernel type checker. -/ /-- `assert_core H T`, adds a new goal for T, and change target to `T -> target`. -/ /-- `assertv_core H T P`, change target to (T -> target) if P has type T. -/ /-- `define_core H T`, adds a new goal for T, and change target to `let H : T := ?M in target` in the current goal. -/ /-- `definev_core H T P`, change target to `let H : T := P in target` if P has type T. -/ /-- Rotate goals to the left. That is, `rotate_left 1` takes the main goal and puts it to the back of the subgoal list. -/ /-- Gets a list of metavariables, one for each goal. -/ /-- Replace the current list of goals with the given one. Each expr in the list should be a metavariable. Any assigned metavariables will be ignored.-/ /-- How to order the new goals made from an `apply` tactic. Supposing we were applying `e : ∀ (a:α) (p : P(a)), Q` - `non_dep_first` would produce goals `⊢ P(?m)`, `⊢ α`. It puts the P goal at the front because none of the arguments after `p` in `e` depend on `p`. It doesn't matter what the result `Q` depends on. - `non_dep_only` would produce goal `⊢ P(?m)`. - `all` would produce goals `⊢ α`, `⊢ P(?m)`. -/ inductive new_goals where | non_dep_first : new_goals | non_dep_only : new_goals | all : new_goals /-- Configuration options for the `apply` tactic. - `md` sets how aggressively definitions are unfolded. - `new_goals` is the strategy for ordering new goals. - `instances` if `tt`, then `apply` tries to synthesize unresolved `[...]` arguments using type class resolution. - `auto_param` if `tt`, then `apply` tries to synthesize unresolved `(h : p . tac_id)` arguments using tactic `tac_id`. - `opt_param` if `tt`, then `apply` tries to synthesize unresolved `(a : t := v)` arguments by setting them to `v`. - `unify` if `tt`, then `apply` is free to assign existing metavariables in the goal when solving unification constraints. For example, in the goal `|- ?x < succ 0`, the tactic `apply succ_lt_succ` succeeds with the default configuration, but `apply_with succ_lt_succ {unify := ff}` doesn't since it would require Lean to assign `?x` to `succ ?y` where `?y` is a fresh metavariable. -/ structure apply_cfg where md : transparency approx : Bool new_goals : new_goals instances : Bool auto_param : Bool opt_param : Bool unify : Bool /-- Apply the expression `e` to the main goal, the unification is performed using the transparency mode in `cfg`. Supposing `e : Π (a₁:α₁) ... (aₙ:αₙ), P(a₁,...,aₙ)` and the target is `Q`, `apply` will attempt to unify `Q` with `P(?a₁,...?aₙ)`. All of the metavariables that are not assigned are added as new metavariables. If `cfg.approx` is `tt`, then fallback to first-order unification, and approximate context during unification. `cfg.new_goals` specifies which unassigned metavariables become new goals, and their order. If `cfg.instances` is `tt`, then use type class resolution to instantiate unassigned meta-variables. The fields `cfg.auto_param` and `cfg.opt_param` are ignored by this tactic (See `tactic.apply`). It returns a list of all introduced meta variables and the parameter name associated with them, even the assigned ones. -/ /- Create a fresh meta universe variable. -/ /- Create a fresh meta-variable with the given type. The scope of the new meta-variable is the local context of the main goal. -/ /-- 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. -/ /-- Return the value assigned to the given meta-variable. Fail if argument is not a meta-variable or if it is not assigned. -/ /-- Return true if the given meta-variable is assigned. Fail if argument is not a meta-variable. -/ /-- Make a name that is guaranteed to be unique. Eg `_fresh.1001.4667`. These will be different for each run of the tactic. -/ /-- Induction on `h` using recursor `rec`, names for the new hypotheses are retrieved from `ns`. If `ns` does not have sufficient names, then use the internal binder names in the recursor. It returns for each new goal the name of the constructor (if `rec_name` is a builtin recursor), a list of new hypotheses, and a list of substitutions for hypotheses depending on `h`. The substitutions map internal names to their replacement terms. If the replacement is again a hypothesis the user name stays the same. The internal names are only valid in the original goal, not in the type context of the new goal. Remark: if `rec_name` is not a builtin recursor, we use parameter names of `rec_name` instead of constructor names. If `rec` is none, then the type of `h` is inferred, if it is of the form `C ...`, tactic uses `C.rec` -/ /-- Apply `cases_on` recursor, names for the new hypotheses are retrieved from `ns`. `h` must be a local constant. It returns for each new goal the name of the constructor, a list of new hypotheses, and a list of substitutions for hypotheses depending on `h`. The number of new goals may be smaller than the number of constructors. Some goals may be discarded when the indices to not match. See `induction` for information on the list of substitutions. The `cases` tactic is implemented using this one, and it relaxes the restriction of `h`. Note: There is one "new hypothesis" for every constructor argument. These are usually local constants, but due to dependent pattern matching, they can also be arbitrary terms. -/ /-- Similar to cases tactic, but does not revert/intro/clear hypotheses. -/ /-- Generalizes the target with respect to `e`. -/ /-- instantiate assigned metavariables in the given expression -/ /-- Add the given declaration to the environment -/ /-- Changes the environment to the `new_env`. The new environment does not need to be a descendant of the old one. Use with care. -/ /-- Changes the environment to the `new_env`. `new_env` needs to be a descendant from the current environment. -/ /-- `doc_string env d k` returns the doc string for `d` (if available) -/ /-- Set the docstring for the given declaration. -/ /-- Create an auxiliary definition with name `c` where `type` and `value` may contain local constants and meta-variables. This function collects all dependencies (universe parameters, universe metavariables, local constants (aka hypotheses) and metavariables). It updates the environment in the tactic_state, and returns an expression of the form (c.{l_1 ... l_n} a_1 ... a_m) where l_i's and a_j's are the collected dependencies. -/ /-- Returns a list of all top-level (`/-! ... -/`) docstrings in the active module and imported ones. The returned object is a list of modules, indexed by `(some filename)` for imported modules and `none` for the active one, where each module in the list is paired with a list of `(position_in_file, docstring)` pairs. -/ /-- Returns a list of docstrings in the active module. An entry in the list can be either: - a top-level (`/-! ... -/`) docstring, represented as `(none, docstring)` - a declaration-specific (`/-- ... -/`) docstring, represented as `(some decl_name, docstring)` -/ /-- Set attribute `attr_name` for constant `c_name` with the given priority. If the priority is none, then use default -/ /-- `unset_attribute attr_name c_name` -/ /-- `has_attribute attr_name c_name` succeeds if the declaration `decl_name` has the attribute `attr_name`. The result is the priority and whether or not the attribute is persistent. -/ /-- `copy_attribute attr_name c_name p d_name` copy attribute `attr_name` from `src` to `tgt` if it is defined for `src`; make it persistent if `p` is `tt`; if `p` is `none`, the copied attribute is made persistent iff it is persistent on `src` -/ /-- Name of the declaration currently being elaborated. -/ /-- `save_type_info e ref` save (typeof e) at position associated with ref -/ /-- Return list of currently open namespaces -/ /-- Return tt iff `t` "occurs" in `e`. The occurrence checking is performed using keyed matching with the given transparency setting. We say `t` occurs in `e` by keyed matching iff there is a subterm `s` s.t. `t` and `s` have the same head, and `is_def_eq t s md` The main idea is to minimize the number of `is_def_eq` checks performed. -/ /-- Abstracts all occurrences of the term `t` in `e` using keyed matching. If `unify` is `ff`, then matching is used instead of unification. That is, metavariables occurring in `e` are not assigned. -/ /-- Blocks the execution of the current thread for at least `msecs` milliseconds. This tactic is used mainly for debugging purposes. -/ /-- Type check `e` with respect to the current goal. Fails if `e` is not type correct. -/ /-- A `tag` is a list of `names`. These are attached to goals to help tactics track them.-/ def tag := List name
269d3d0a12f6aa2af6d9ca2d3299d9bfaed067c9
6fbf10071e62af7238f2de8f9aa83d55d8763907
/hw/hw5-exam1-practice.lean
2ba87d4edab6ef81efc0e591c5b42c0c2eca4bb5
[]
no_license
HasanMukati/uva-cs-dm-s19
ee5aad4568a3ca330c2738ed579c30e1308b03b0
3e7177682acdb56a2d16914e0344c10335583dcf
refs/heads/master
1,596,946,213,130
1,568,221,949,000
1,568,221,949,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,100
lean
/- Here is the practice exam. It provides you with a set of problems illustrative of the material to be tested. This is a homework assignment due this coming Thursday. We will review the questions in class. Copy this file your "work" directory. Work on it there. Upload to Collab when done. Note: An incorrect answer above or below a correct answer can cause Lean to be unable to process the correct answer. If you are not able to complete a problem successfully please comment out your incomplete answer so that we can see your work but so that your incomplete work does not cause problems for surrounding problems and answers. -/ /- PART I: Functions. Functions are an essential element of the language of predicate logic. In this section, you show that you understand how to define, use, and reason about functions in Lean. -/ /- 1. Study each of the following definitions, then answer the associated question about the types involved in these definitions. -/ -- Consider this function def f (n : ℕ) (s : string) := s /- a. What is it's return type? Answer: -/ /- b. What is the type of (f 5)? Answer: -/ /- c. What is the value of (f 0 "yay") -/ /- d. What is the type of this function? -/ /- 2. Define three functions called square, square', and square'', each of type ℕ → ℕ. Each function must return the square of the value to which it is applied. Write the first function in "C" style, the second using a tactic script, and the third using a lambda abstraction. Declare all argument and return types explicitly. Answer below. -/ def square (n : ℕ) : ℕ := n^2 def square' (n : ℕ) : ℕ := begin exact n^2 end def square'' : ℕ → ℕ := λ n, n^2 /- 3. Construct three proofs to test your function definitions. The first must use "lemma" to define a proof, called square_3_9, of the proposition that (square 3) equals 9. The second must use "theorem" to define a proof, called square'_4_16, of the proposition that square' applied to 4 reduces to 16. The third must prove that square'' 5 is equal to 25. This third proof must not use the equals sign, =, but must use "eq" instead to state the proposition to be proved. Hint on #3, sometimes you need to use parentheses to express how you want terms to be grouped. Answer below. -/ lemma square_3_9 : eq (square 3) 9 := rfl /- 4. Define a function called last_first. It must take two string values, called "first" and "last" (without quotes), and return a string consisting of "last" followed by a comma and a space followed by "first". For example (last_first "Orson" "Welles") must return the string, "Welles, Orson". Write a test case for your function to prove that (last_first "Orson" "Welles") is "Welles, Orson". Use "example", to check the proof. Hint: The ++ operator implements the string append function. Answer below. -/ def lastFirst (s1 s2 : string) : string := s2 ++ ", " ++ s1 example : lastFirst "Orson" "Welles" = "Welles, Orson" := rfl /- 5. Complete the following definition of a function, called apply3. It takes, as an argument, a function, you might call it f, of type ℕ → ℕ. It must return a function, also of type ℕ to ℕ, that, when applied to a value, n, returns the result of applying the given function, f, to the given value, n, three times. The function returned must compute f(f(f(n))) when it is applied to an argument, n. -/ def apply3 : (ℕ → ℕ) → (ℕ → ℕ) := λ f : ℕ → ℕ, λ n, f(f(f(n))) #reduce apply3 (λ n : ℕ, n^2) 2 /- 6. The Lean libraries define a function, string.length, that takes a string and returns its length as a natural number. Define a function, len2, that takes two strings and returns the sum of their lengths. You may use the ++ operator but not the + operator in your answer. Follow your function definition with a test case in the form of a proof using "example" showing that len2 applied to "Orson" and "Welles" is 11. Remember: you might need parenthesis in some cases to group terms correctly into larger terms. -/ def len2 (s1 s2 : string) : ℕ := string.length (s1 ++ s2) /- 7. Use "example" to prove that there is a function of the following type: ((ℕ → ℕ) → (ℕ → ℕ)) → ((ℕ → ℕ) → ℕ) → ((ℕ → ℕ) → ℕ) -/ example : ((ℕ → ℕ) → (ℕ → ℕ)) → ((ℕ → ℕ) → ℕ) → ((ℕ → ℕ) → ℕ) := λ f, λ g, g /- PART II: Functions, revisited. In mathematics, functions play a central role. A function, f, in the mathematical sense is a triple, f = { D, P, C }, where D, a set, is the domain of definition of f, C is the co-domain of f, and P is a set of ordered pairs, each with a first element from D and a second element from C,. In addition, P has one additional essential property, the subject of one of the following questions. -/ /- 8. What one additional property is essential to the definition of what it means for a triple, { D, P, C } to be a function? Name the property. Answer: Now explain precisely what it means: "That there are no two pairs, (x, y) and (x', y') such that..." Fill in the blank, and use a logical ∧ in answering. You might also want to use = or ≠. Answer: -/ /- 9. Give names to the following concepts: The set of all values appearing as the first element of any pair in P. Answer: The set of all values appearing as the second element of any pair in P. Answer: The property that the set of all values appearing as the first element of P is the same as the entire set, D. Answer: The property that the set of all values appearing as the second element of P is the same as the entire set, C. Answer: The property of being one-to-one and onto. Answer: -/ /- 10. What does it mean for a function, f, to be injective? Give you answer by completing the following sentences with logical expressions. "A function, f, is said to be injective if it has no two pairs, (x, y) and (x', y'), such that ..." Answer: In other words, "If (x, y) and (x', y') are related by f and x ≠ x' then ..." Answer: -/ /- 11. Suppose that S and T are types and that f is defined to be a function, *in Lean*, of type S → T. Which of the following properties, if any, does f necessarily have? - injective - surjective - bijective - one-to-many - one-to-one - onto - single-valued - partial - total Answer: -/ /- PART III: Logic and Proof. -/ /- 12a. Use axiom and/or axioms in Lean to express, in formal logic, the following assumptions: - T is a type - t1 and t2 are values of type T - t1 = t2 Answer immediately after this comment block. If you need to introduce a name, use eqt1t2. -/ axiom T : Type axioms t1 t2 : T axiom t1eqt2 :t1 = t2 /- 12b. Use axiom or axioms to represent the additional assumptions that - P is a predicate expressing a property of objects of type T - t1 has property P If you need to use a name, use Pt1 -/ axiom P : T → Prop axiom pf : P t1 example : P t2 := eq.subst t1eqt2 pf /- 12 c. Now use "example" to assert, and then prove, that t2 also has property P. -/ /- 13 a. Define eq_1_0 to be the proposition, 1 = 0. -/ /- 13 b. Define pf_eq_0_0 to be a proof of the proposition that 0 = 0. Use the lemma keyword. -/ /- 13 c. Write a function, w, that takes three values, a, b, and c of type ℕ, and that also takes proofs, cb : c = b, and ba : b = a, and that returns a proof that a = c. -/ /- 13d. What is the type of this function? Answer: What is the form of this proposition? Answer: What's the form the proposition after the comma? Answer: What is the premise of the proposition after the comma? Answer: -/ /- 14. Complete the following proofs. Give each one in the form indicated by a comment preceding the statement of the conjecture to be proved. When using tactic scripts, remember to write begin/end pairs right away, so Lean knowns you want to use a tactic script. -/ -- lambda expression example : ∀ (s : string), s = s := _ -- lambda expresion example : ∀ (n : ℕ), ∀ (m : ℕ), true := _ -- tactic script example : ∀ (T : Type), ∀ (t : T), eq t t := _ -- tactic script example : ∀ (T : Type), ∀ (P : T → Prop), ∀ t1 t2 : T, ∀ Pt1 : P t1, ∀ t2t1 : t2 = t1, P t2 := _ /- The following problems involve implications. For example, false → P in an implication. To prove an implication, just show that there is (give) a function of the specified type. -/ -- lambda expression example : ∀ (P : Prop), false → P := _ -- tactic script example : ∀ (P : Prop), false → P := _ -- lambda expression example : ∀ (P Q : Prop), P ∧ Q → Q ∧ P := _ -- tactic script example : ∀ (P Q : Prop), P ∧ Q → Q ∧ P := _ -- tactic script example : ∀ T : Type, ∀ (t1 t2 t3 : T), t1 = t2 ∧ t2 = t3 → t1 = t3 := _ /- 15. Use Lean to model a world in which there are Dogs, all Dogs are friendly, and Fido is a Dog, with a proof that in this world, Fido must be friendly, too. -/ /- Another Prove: ∀(A B C: Prop), A ∧ (B ∧ C) → (A ∧ B) ∧ C -/
c97155f4e0ace6a365223d526d7a16ff3b855ddd
1a61aba1b67cddccce19532a9596efe44be4285f
/hott/hit/cylinder.hlean
917e8be638a72ab37e11f35828e3d9b8132b3204
[ "Apache-2.0" ]
permissive
eigengrau/lean
07986a0f2548688c13ba36231f6cdbee82abf4c6
f8a773be1112015e2d232661ce616d23f12874d0
refs/heads/master
1,610,939,198,566
1,441,352,386,000
1,441,352,494,000
41,903,576
0
0
null
1,441,352,210,000
1,441,352,210,000
null
UTF-8
Lean
false
false
3,187
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 Declaration of mapping cylinders -/ import .quotient open quotient eq sum equiv equiv.ops namespace cylinder section universe u parameters {A B : Type.{u}} (f : A → B) local abbreviation C := B + A inductive cylinder_rel : C → C → Type := | Rmk : Π(a : A), cylinder_rel (inl (f a)) (inr a) open cylinder_rel local abbreviation R := cylinder_rel definition cylinder := quotient cylinder_rel -- TODO: define this in root namespace definition base (b : B) : cylinder := class_of R (inl b) definition top (a : A) : cylinder := class_of R (inr a) definition seg (a : A) : base (f a) = top a := eq_of_rel cylinder_rel (Rmk f a) protected definition rec {P : cylinder → Type} (Pbase : Π(b : B), P (base b)) (Ptop : Π(a : A), P (top a)) (Pseg : Π(a : A), Pbase (f a) =[seg a] Ptop a) (x : cylinder) : P x := begin induction x, { cases a, apply Pbase, apply Ptop}, { cases H, apply Pseg} end protected definition rec_on [reducible] {P : cylinder → Type} (x : cylinder) (Pbase : Π(b : B), P (base b)) (Ptop : Π(a : A), P (top a)) (Pseg : Π(a : A), Pbase (f a) =[seg a] Ptop a) : P x := rec Pbase Ptop Pseg x theorem rec_seg {P : cylinder → Type} (Pbase : Π(b : B), P (base b)) (Ptop : Π(a : A), P (top a)) (Pseg : Π(a : A), Pbase (f a) =[seg a] Ptop a) (a : A) : apdo (rec Pbase Ptop Pseg) (seg a) = Pseg a := !rec_eq_of_rel protected definition elim {P : Type} (Pbase : B → P) (Ptop : A → P) (Pseg : Π(a : A), Pbase (f a) = Ptop a) (x : cylinder) : P := rec Pbase Ptop (λa, pathover_of_eq (Pseg a)) x protected definition elim_on [reducible] {P : Type} (x : cylinder) (Pbase : B → P) (Ptop : A → P) (Pseg : Π(a : A), Pbase (f a) = Ptop a) : P := elim Pbase Ptop Pseg x theorem elim_seg {P : Type} (Pbase : B → P) (Ptop : A → P) (Pseg : Π(a : A), Pbase (f a) = Ptop a) (a : A) : ap (elim Pbase Ptop Pseg) (seg a) = Pseg a := begin apply eq_of_fn_eq_fn_inv !(pathover_constant (seg a)), rewrite [▸*,-apdo_eq_pathover_of_eq_ap,↑elim,rec_seg], end protected definition elim_type (Pbase : B → Type) (Ptop : A → Type) (Pseg : Π(a : A), Pbase (f a) ≃ Ptop a) (x : cylinder) : Type := elim Pbase Ptop (λa, ua (Pseg a)) x protected definition elim_type_on [reducible] (x : cylinder) (Pbase : B → Type) (Ptop : A → Type) (Pseg : Π(a : A), Pbase (f a) ≃ Ptop a) : Type := elim_type Pbase Ptop Pseg x theorem elim_type_seg (Pbase : B → Type) (Ptop : A → Type) (Pseg : Π(a : A), Pbase (f a) ≃ Ptop a) (a : A) : transport (elim_type Pbase Ptop Pseg) (seg a) = Pseg a := by rewrite [tr_eq_cast_ap_fn,↑elim_type,elim_seg];apply cast_ua_fn end end cylinder attribute cylinder.base cylinder.top [constructor] attribute cylinder.rec cylinder.elim [unfold 8] [recursor 8] attribute cylinder.elim_type [unfold 7] attribute cylinder.rec_on cylinder.elim_on [unfold 5] attribute cylinder.elim_type_on [unfold 4]
22aa0bad23ef52caff86d253275d63eedcab1543
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/interactive/term_goal_info.lean
21cff6d73f1d334e2937c5f565b3d764e3cabf7e
[ "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
1,049
lean
example (p q r : Prop) : p → (p ∧ q → r) → q → r := λ hp hpqr hq, hpqr (and.intro (id hp) hq) --^ "command":"info" example (p q r : Prop) : p → (p ∧ q → r) → q → r := λ hp hpqr, by intro hq; exact hpqr (and.intro hp hq) --^ "command":"info" example (p q r : Prop) : p → (p ∧ q → r) → q → r := λ hp hpqr, by intro hq; exact hpqr (and.intro hp hq) --^ "command":"info" example (p q r : Prop) : p → (p ∧ q → r) → q → r := λ hp hpqr, by intro hq; exact hpqr (and.intro hp hq) --^ "command":"info" example (p q : Prop) : (p → p → q) → p → q := λ hppq, by intro hp; apply hppq hp; assumption --^ "command":"info" example (p : Prop) : p → p := λ h, h --^ "command": "info" example (p q : Prop) : p → q → true ∧ p ∧ q := by intros; refine (and.intro true.intro (and.intro _ _) : _); assumption --^ "command": "info"
99fdafe1bba7362cae28ea273e22d78b869c1f61
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/ring_theory/int/basic.lean
d3cae070796eeee9598659ce5f8bfdc1c6f59e5e
[ "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
13,403
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jens Wagemaker, Aaron Anderson -/ import data.int.basic import data.int.gcd import ring_theory.multiplicity import ring_theory.principal_ideal_domain /-! # Divisibility over ℕ and ℤ This file collects results for the integers and natural numbers that use abstract algebra in their proofs or cases of ℕ and ℤ being examples of structures in abstract algebra. ## Main statements * `nat.prime_iff`: `nat.prime` coincides with the general definition of `prime` * `nat.irreducible_iff_prime`: a non-unit natural number is only divisible by `1` iff it is prime * `nat.factors_eq`: the multiset of elements of `nat.factors` is equal to the factors given by the `unique_factorization_monoid` instance * ℤ is a `normalization_monoid` * ℤ is a `gcd_monoid` ## Tags prime, irreducible, natural numbers, integers, normalization monoid, gcd monoid, greatest common divisor, prime factorization, prime factors, unique factorization, unique factors -/ theorem nat.prime_iff {p : ℕ} : p.prime ↔ prime p := begin split; intro h, { refine ⟨h.ne_zero, ⟨_, λ a b, _⟩⟩, { rw nat.is_unit_iff, apply h.ne_one }, { apply h.dvd_mul.1 } }, { refine ⟨_, λ m hm, _⟩, { cases p, { exfalso, apply h.ne_zero rfl }, cases p, { exfalso, apply h.ne_one rfl }, exact (add_le_add_right (zero_le p) 2 : _ ) }, { cases hm with n hn, cases h.2.2 m n (hn ▸ dvd_refl _) with hpm hpn, { right, apply nat.dvd_antisymm (dvd.intro _ hn.symm) hpm }, { left, cases n, { exfalso, rw [hn, mul_zero] at h, apply h.ne_zero rfl }, apply nat.eq_of_mul_eq_mul_right (nat.succ_pos _), rw [← hn, one_mul], apply nat.dvd_antisymm hpn (dvd.intro m _), rw [mul_comm, hn], }, } } end theorem nat.irreducible_iff_prime {p : ℕ} : irreducible p ↔ prime p := begin refine ⟨λ h, _, irreducible_of_prime⟩, rw ← nat.prime_iff, refine ⟨_, λ m hm, _⟩, { cases p, { exfalso, apply h.ne_zero rfl }, cases p, { exfalso, apply h.not_unit is_unit_one, }, exact (add_le_add_right (zero_le p) 2 : _ ) }, { cases hm with n hn, cases h.is_unit_or_is_unit hn with um un, { left, rw nat.is_unit_iff.1 um, }, { right, rw [hn, nat.is_unit_iff.1 un, mul_one], } } end namespace nat instance : wf_dvd_monoid ℕ := ⟨begin apply rel_hom.well_founded _ (with_top.well_founded_lt nat.lt_wf), refine ⟨λ x, if x = 0 then ⊤ else x, _⟩, intros a b h, cases a, { exfalso, revert h, simp [dvd_not_unit] }, cases b, {simp [succ_ne_zero, with_top.coe_lt_top]}, cases dvd_and_not_dvd_iff.2 h with h1 h2, simp only [succ_ne_zero, with_top.coe_lt_coe, if_false], apply lt_of_le_of_ne (nat.le_of_dvd (nat.succ_pos _) h1) (λ con, h2 _), rw con, end⟩ instance : unique_factorization_monoid ℕ := ⟨λ _, nat.irreducible_iff_prime⟩ end nat namespace int section normalization_monoid instance : normalization_monoid ℤ := { norm_unit := λa:ℤ, if 0 ≤ a then 1 else -1, norm_unit_zero := if_pos (le_refl _), norm_unit_mul := assume a b hna hnb, begin cases hna.lt_or_lt with ha ha; cases hnb.lt_or_lt with hb hb; simp [mul_nonneg_iff, ha.le, ha.not_le, hb.le, hb.not_le] end, norm_unit_coe_units := assume u, (units_eq_one_or u).elim (assume eq, eq.symm ▸ if_pos zero_le_one) (assume eq, eq.symm ▸ if_neg (not_le_of_gt $ show (-1:ℤ) < 0, by dec_trivial)), } lemma normalize_of_nonneg {z : ℤ} (h : 0 ≤ z) : normalize z = z := show z * ↑(ite _ _ _) = z, by rw [if_pos h, units.coe_one, mul_one] lemma normalize_of_neg {z : ℤ} (h : z < 0) : normalize z = -z := show z * ↑(ite _ _ _) = -z, by rw [if_neg (not_le_of_gt h), units.coe_neg, units.coe_one, mul_neg_one] lemma normalize_coe_nat (n : ℕ) : normalize (n : ℤ) = n := normalize_of_nonneg (coe_nat_le_coe_nat_of_le $ nat.zero_le n) theorem coe_nat_abs_eq_normalize (z : ℤ) : (z.nat_abs : ℤ) = normalize z := begin by_cases 0 ≤ z, { simp [nat_abs_of_nonneg h, normalize_of_nonneg h] }, { simp [of_nat_nat_abs_of_nonpos (le_of_not_ge h), normalize_of_neg (lt_of_not_ge h)] } end end normalization_monoid section gcd_monoid instance : gcd_monoid ℤ := { gcd := λa b, int.gcd a b, lcm := λa b, int.lcm a b, gcd_dvd_left := assume a b, int.gcd_dvd_left _ _, gcd_dvd_right := assume a b, int.gcd_dvd_right _ _, dvd_gcd := assume a b c, dvd_gcd, normalize_gcd := assume a b, normalize_coe_nat _, gcd_mul_lcm := by intros; rw [← int.coe_nat_mul, gcd_mul_lcm, coe_nat_abs_eq_normalize], lcm_zero_left := assume a, coe_nat_eq_zero.2 $ nat.lcm_zero_left _, lcm_zero_right := assume a, coe_nat_eq_zero.2 $ nat.lcm_zero_right _, .. int.normalization_monoid } lemma coe_gcd (i j : ℤ) : ↑(int.gcd i j) = gcd_monoid.gcd i j := rfl lemma coe_lcm (i j : ℤ) : ↑(int.lcm i j) = gcd_monoid.lcm i j := rfl lemma nat_abs_gcd (i j : ℤ) : nat_abs (gcd_monoid.gcd i j) = int.gcd i j := rfl lemma nat_abs_lcm (i j : ℤ) : nat_abs (gcd_monoid.lcm i j) = int.lcm i j := rfl end gcd_monoid lemma exists_unit_of_abs (a : ℤ) : ∃ (u : ℤ) (h : is_unit u), (int.nat_abs a : ℤ) = u * a := begin cases (nat_abs_eq a) with h, { use [1, is_unit_one], rw [← h, one_mul], }, { use [-1, is_unit_one.neg], rw [ ← neg_eq_iff_neg_eq.mp (eq.symm h)], simp only [neg_mul_eq_neg_mul_symm, one_mul] } end lemma gcd_eq_nat_abs {a b : ℤ} : int.gcd a b = nat.gcd a.nat_abs b.nat_abs := rfl lemma gcd_eq_one_iff_coprime {a b : ℤ} : int.gcd a b = 1 ↔ is_coprime a b := begin split, { intro hg, obtain ⟨ua, hua, ha⟩ := exists_unit_of_abs a, obtain ⟨ub, hub, hb⟩ := exists_unit_of_abs b, use [(nat.gcd_a (int.nat_abs a) (int.nat_abs b)) * ua, (nat.gcd_b (int.nat_abs a) (int.nat_abs b)) * ub], rw [mul_assoc, ← ha, mul_assoc, ← hb, mul_comm, mul_comm _ (int.nat_abs b : ℤ), ← nat.gcd_eq_gcd_ab, ←gcd_eq_nat_abs, hg, int.coe_nat_one] }, { rintro ⟨r, s, h⟩, by_contradiction hg, obtain ⟨p, ⟨hp, ha, hb⟩⟩ := nat.prime.not_coprime_iff_dvd.mp hg, apply nat.prime.not_dvd_one hp, rw [←coe_nat_dvd, int.coe_nat_one, ← h], exact dvd_add (dvd_mul_of_dvd_right (coe_nat_dvd_left.mpr ha) _) (dvd_mul_of_dvd_right (coe_nat_dvd_left.mpr hb) _) } end lemma coprime_iff_nat_coprime {a b : ℤ} : is_coprime a b ↔ nat.coprime a.nat_abs b.nat_abs := by rw [←gcd_eq_one_iff_coprime, nat.coprime_iff_gcd_eq_one, gcd_eq_nat_abs] lemma sq_of_gcd_eq_one {a b c : ℤ} (h : int.gcd a b = 1) (heq : a * b = c ^ 2) : ∃ (a0 : ℤ), a = a0 ^ 2 ∨ a = - (a0 ^ 2) := begin have h' : gcd_monoid.gcd a b = 1, { rw [← coe_gcd, h], dec_trivial }, obtain ⟨d, ⟨u, hu⟩⟩ := exists_associated_pow_of_mul_eq_pow h' heq, use d, rw ← hu, cases int.units_eq_one_or u with hu' hu'; { rw hu', simp } end lemma sq_of_coprime {a b c : ℤ} (h : is_coprime a b) (heq : a * b = c ^ 2) : ∃ (a0 : ℤ), a = a0 ^ 2 ∨ a = - (a0 ^ 2) := sq_of_gcd_eq_one (gcd_eq_one_iff_coprime.mpr h) heq lemma nat_abs_euclidean_domain_gcd (a b : ℤ) : int.nat_abs (euclidean_domain.gcd a b) = int.gcd a b := begin apply nat.dvd_antisymm; rw ← int.coe_nat_dvd, { rw int.nat_abs_dvd, exact int.dvd_gcd (euclidean_domain.gcd_dvd_left _ _) (euclidean_domain.gcd_dvd_right _ _) }, { rw int.dvd_nat_abs, exact euclidean_domain.dvd_gcd (int.gcd_dvd_left _ _) (int.gcd_dvd_right _ _) } end end int theorem irreducible_iff_nat_prime : ∀(a : ℕ), irreducible a ↔ nat.prime a | 0 := by simp [nat.not_prime_zero] | 1 := by simp [nat.prime, one_lt_two] | (n + 2) := have h₁ : ¬n + 2 = 1, from dec_trivial, begin simp [h₁, nat.prime, irreducible_iff, (≥), nat.le_add_left 2 n, (∣)], refine forall_congr (assume a, forall_congr $ assume b, forall_congr $ assume hab, _), by_cases a = 1; simp [h], split, { assume hb, simpa [hb] using hab.symm }, { assume ha, subst ha, have : n + 2 > 0, from dec_trivial, refine nat.eq_of_mul_eq_mul_left this _, rw [← hab, mul_one] } end lemma nat.prime_iff_prime_int {p : ℕ} : p.prime ↔ _root_.prime (p : ℤ) := ⟨λ hp, ⟨int.coe_nat_ne_zero_iff_pos.2 hp.pos, mt int.is_unit_iff_nat_abs_eq.1 hp.ne_one, λ a b h, by rw [← int.dvd_nat_abs, int.coe_nat_dvd, int.nat_abs_mul, hp.dvd_mul] at h; rwa [← int.dvd_nat_abs, int.coe_nat_dvd, ← int.dvd_nat_abs, int.coe_nat_dvd]⟩, λ hp, nat.prime_iff.2 ⟨int.coe_nat_ne_zero.1 hp.1, mt nat.is_unit_iff.1 $ λ h, by simpa [h, not_prime_one] using hp, λ a b, by simpa only [int.coe_nat_dvd, (int.coe_nat_mul _ _).symm] using hp.2.2 a b⟩⟩ /-- Maps an associate class of integers consisting of `-n, n` to `n : ℕ` -/ def associates_int_equiv_nat : associates ℤ ≃ ℕ := begin refine ⟨λz, z.out.nat_abs, λn, associates.mk n, _, _⟩, { refine (assume a, quotient.induction_on' a $ assume a, associates.mk_eq_mk_iff_associated.2 $ associated.symm $ ⟨norm_unit a, _⟩), show normalize a = int.nat_abs (normalize a), rw [int.coe_nat_abs_eq_normalize, normalize_idem] }, { intro n, dsimp, rw [associates.out_mk ↑n, ← int.coe_nat_abs_eq_normalize, int.nat_abs_of_nat, int.nat_abs_of_nat] } end lemma int.prime.dvd_mul {m n : ℤ} {p : ℕ} (hp : nat.prime p) (h : (p : ℤ) ∣ m * n) : p ∣ m.nat_abs ∨ p ∣ n.nat_abs := begin apply (nat.prime.dvd_mul hp).mp, rw ← int.nat_abs_mul, exact int.coe_nat_dvd_left.mp h end lemma int.prime.dvd_mul' {m n : ℤ} {p : ℕ} (hp : nat.prime p) (h : (p : ℤ) ∣ m * n) : (p : ℤ) ∣ m ∨ (p : ℤ) ∣ n := begin rw [int.coe_nat_dvd_left, int.coe_nat_dvd_left], exact int.prime.dvd_mul hp h end lemma int.prime.dvd_pow {n : ℤ} {k p : ℕ} (hp : nat.prime p) (h : (p : ℤ) ∣ n ^ k) : p ∣ n.nat_abs := begin apply @nat.prime.dvd_of_dvd_pow _ _ k hp, rw ← int.nat_abs_pow, exact int.coe_nat_dvd_left.mp h end lemma int.prime.dvd_pow' {n : ℤ} {k p : ℕ} (hp : nat.prime p) (h : (p : ℤ) ∣ n ^ k) : (p : ℤ) ∣ n := begin rw int.coe_nat_dvd_left, exact int.prime.dvd_pow hp h end lemma prime_two_or_dvd_of_dvd_two_mul_pow_self_two {m : ℤ} {p : ℕ} (hp : nat.prime p) (h : (p : ℤ) ∣ 2 * m ^ 2) : p = 2 ∨ p ∣ int.nat_abs m := begin cases int.prime.dvd_mul hp h with hp2 hpp, { apply or.intro_left, exact le_antisymm (nat.le_of_dvd zero_lt_two hp2) (nat.prime.two_le hp) }, { apply or.intro_right, rw [sq, int.nat_abs_mul] at hpp, exact (or_self _).mp ((nat.prime.dvd_mul hp).mp hpp)} end open unique_factorization_monoid theorem nat.factors_eq {n : ℕ} : factors n = n.factors := begin cases n, { simp }, rw [← multiset.rel_eq, ← associated_eq_eq], apply factors_unique (irreducible_of_factor) _, { rw [multiset.coe_prod, nat.prod_factors (nat.succ_pos _)], apply factors_prod (nat.succ_ne_zero _) }, { apply_instance }, { intros x hx, rw [nat.irreducible_iff_prime, ← nat.prime_iff], exact nat.prime_of_mem_factors hx } end lemma nat.factors_multiset_prod_of_irreducible {s : multiset ℕ} (h : ∀ (x : ℕ), x ∈ s → irreducible x) : unique_factorization_monoid.factors (s.prod) = s := begin rw [← multiset.rel_eq, ← associated_eq_eq], apply (unique_factorization_monoid.factors_unique irreducible_of_factor h (factors_prod _)), rw [ne.def, multiset.prod_eq_zero_iff], intro con, exact not_irreducible_zero (h 0 con), end namespace multiplicity lemma finite_int_iff_nat_abs_finite {a b : ℤ} : finite a b ↔ finite a.nat_abs b.nat_abs := by simp only [finite_def, ← int.nat_abs_dvd_abs_iff, int.nat_abs_pow] lemma finite_int_iff {a b : ℤ} : finite a b ↔ (a.nat_abs ≠ 1 ∧ b ≠ 0) := by rw [finite_int_iff_nat_abs_finite, finite_nat_iff, pos_iff_ne_zero, int.nat_abs_ne_zero] instance decidable_nat : decidable_rel (λ a b : ℕ, (multiplicity a b).dom) := λ a b, decidable_of_iff _ finite_nat_iff.symm instance decidable_int : decidable_rel (λ a b : ℤ, (multiplicity a b).dom) := λ a b, decidable_of_iff _ finite_int_iff.symm end multiplicity lemma induction_on_primes {P : ℕ → Prop} (h₀ : P 0) (h₁ : P 1) (h : ∀ p a : ℕ, p.prime → P a → P (p * a)) (n : ℕ) : P n := begin apply unique_factorization_monoid.induction_on_prime, exact h₀, { intros n h, rw nat.is_unit_iff.1 h, exact h₁, }, { intros a p _ hp ha, exact h p a (nat.prime_iff.2 hp) ha, }, end lemma int.associated_nat_abs (k : ℤ) : associated k k.nat_abs := associated_of_dvd_dvd (int.coe_nat_dvd_right.mpr (dvd_refl _)) (int.nat_abs_dvd.mpr (dvd_refl _)) lemma int.prime_iff_nat_abs_prime {k : ℤ} : prime k ↔ nat.prime k.nat_abs := begin rw nat.prime_iff_prime_int, rw prime_iff_of_associated (int.associated_nat_abs k), end theorem int.associated_iff_nat_abs {a b : ℤ} : associated a b ↔ a.nat_abs = b.nat_abs := begin rw [←dvd_dvd_iff_associated, ←int.nat_abs_dvd_abs_iff, ←int.nat_abs_dvd_abs_iff, dvd_dvd_iff_associated], exact associated_iff_eq, end lemma int.associated_iff {a b : ℤ} : associated a b ↔ (a = b ∨ a = -b) := begin rw int.associated_iff_nat_abs, exact int.nat_abs_eq_nat_abs_iff, end
381d7cfd350dc50febe3fd42ccd508ace28b1ea3
bb31430994044506fa42fd667e2d556327e18dfe
/src/number_theory/zsqrtd/basic.lean
4e29530bb4f3799e2547d35cd0dd55d4ce1dd604
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
33,365
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 algebra.associated import ring_theory.int.basic import tactic.ring /-! # ℤ[√d] The ring of integers adjoined with a square root of `d : ℤ`. After defining the norm, we show that it is a linearly ordered commutative ring, as well as an integral domain. We provide the universal property, that ring homomorphisms `ℤ√d →+* R` correspond to choices of square roots of `d` in `R`. -/ /-- The ring of integers adjoined with a square root of `d`. These have the form `a + b √d` where `a b : ℤ`. The components are called `re` and `im` by analogy to the negative `d` case. -/ structure zsqrtd (d : ℤ) := (re : ℤ) (im : ℤ) prefix `ℤ√`:100 := zsqrtd namespace zsqrtd section parameters {d : ℤ} instance : decidable_eq ℤ√d := by tactic.mk_dec_eq_instance theorem ext : ∀ {z w : ℤ√d}, z = w ↔ z.re = w.re ∧ z.im = w.im | ⟨x, y⟩ ⟨x', y'⟩ := ⟨λ h, by injection h; split; assumption, λ ⟨h₁, h₂⟩, by congr; assumption⟩ /-- Convert an integer to a `ℤ√d` -/ def of_int (n : ℤ) : ℤ√d := ⟨n, 0⟩ theorem of_int_re (n : ℤ) : (of_int n).re = n := rfl theorem of_int_im (n : ℤ) : (of_int n).im = 0 := rfl /-- The zero of the ring -/ instance : has_zero ℤ√d := ⟨of_int 0⟩ @[simp] theorem zero_re : (0 : ℤ√d).re = 0 := rfl @[simp] theorem zero_im : (0 : ℤ√d).im = 0 := rfl instance : inhabited ℤ√d := ⟨0⟩ /-- The one of the ring -/ instance : has_one ℤ√d := ⟨of_int 1⟩ @[simp] theorem one_re : (1 : ℤ√d).re = 1 := rfl @[simp] theorem one_im : (1 : ℤ√d).im = 0 := rfl /-- The representative of `√d` in the ring -/ def sqrtd : ℤ√d := ⟨0, 1⟩ @[simp] theorem sqrtd_re : (sqrtd : ℤ√d).re = 0 := rfl @[simp] theorem sqrtd_im : (sqrtd : ℤ√d).im = 1 := rfl /-- Addition of elements of `ℤ√d` -/ instance : has_add ℤ√d := ⟨λ z w, ⟨z.1 + w.1, z.2 + w.2⟩⟩ @[simp] lemma add_def (x y x' y' : ℤ) : (⟨x, y⟩ + ⟨x', y'⟩ : ℤ√d) = ⟨x + x', y + y'⟩ := rfl @[simp] lemma add_re (z w : ℤ√d) : (z + w).re = z.re + w.re := rfl @[simp] lemma add_im (z w : ℤ√d) : (z + w).im = z.im + w.im := rfl @[simp] lemma bit0_re (z) : (bit0 z : ℤ√d).re = bit0 z.re := rfl @[simp] lemma bit0_im (z) : (bit0 z : ℤ√d).im = bit0 z.im := rfl @[simp] theorem bit1_re (z) : (bit1 z : ℤ√d).re = bit1 z.re := rfl @[simp] theorem bit1_im (z) : (bit1 z : ℤ√d).im = bit0 z.im := by simp [bit1] /-- Negation in `ℤ√d` -/ instance : has_neg ℤ√d := ⟨λ z, ⟨-z.1, -z.2⟩⟩ @[simp] lemma neg_re (z : ℤ√d) : (-z).re = -z.re := rfl @[simp] lemma neg_im (z : ℤ√d) : (-z).im = -z.im := rfl /-- Multiplication in `ℤ√d` -/ instance : has_mul ℤ√d := ⟨λ z w, ⟨z.1 * w.1 + d * z.2 * w.2, z.1 * w.2 + z.2 * w.1⟩⟩ @[simp] lemma mul_re (z w : ℤ√d) : (z * w).re = z.re * w.re + d * z.im * w.im := rfl @[simp] lemma mul_im (z w : ℤ√d) : (z * w).im = z.re * w.im + z.im * w.re := rfl instance : add_comm_group ℤ√d := by refine_struct { add := (+), zero := (0 : ℤ√d), sub := λ a b, a + -b, neg := has_neg.neg, zsmul := @zsmul_rec (ℤ√d) ⟨0⟩ ⟨(+)⟩ ⟨has_neg.neg⟩, nsmul := @nsmul_rec (ℤ√d) ⟨0⟩ ⟨(+)⟩ }; intros; try { refl }; simp [ext, add_comm, add_left_comm] instance : add_group_with_one ℤ√d := { nat_cast := λ n, of_int n, int_cast := of_int, one := 1, .. zsqrtd.add_comm_group } instance : comm_ring ℤ√d := by refine_struct { add := (+), zero := (0 : ℤ√d), mul := (*), one := 1, npow := @npow_rec (ℤ√d) ⟨1⟩ ⟨(*)⟩, .. zsqrtd.add_group_with_one }; intros; try { refl }; simp [ext, add_mul, mul_add, add_comm, add_left_comm, mul_comm, mul_left_comm] instance : add_monoid ℤ√d := by apply_instance instance : monoid ℤ√d := by apply_instance instance : comm_monoid ℤ√d := by apply_instance instance : comm_semigroup ℤ√d := by apply_instance instance : semigroup ℤ√d := by apply_instance instance : add_comm_semigroup ℤ√d := by apply_instance instance : add_semigroup ℤ√d := by apply_instance instance : comm_semiring ℤ√d := by apply_instance instance : semiring ℤ√d := by apply_instance instance : ring ℤ√d := by apply_instance instance : distrib ℤ√d := by apply_instance /-- Conjugation in `ℤ√d`. The conjugate of `a + b √d` is `a - b √d`. -/ def conj (z : ℤ√d) : ℤ√d := ⟨z.1, -z.2⟩ @[simp] lemma conj_re (z : ℤ√d) : (conj z).re = z.re := rfl @[simp] lemma conj_im (z : ℤ√d) : (conj z).im = -z.im := rfl /-- `conj` as an `add_monoid_hom`. -/ def conj_hom : ℤ√d →+ ℤ√d := { to_fun := conj, map_add' := λ ⟨a, ai⟩ ⟨b, bi⟩, ext.mpr ⟨rfl, neg_add _ _⟩, map_zero' := ext.mpr ⟨rfl, neg_zero⟩ } @[simp] lemma conj_zero : conj (0 : ℤ√d) = 0 := conj_hom.map_zero @[simp] lemma conj_one : conj (1 : ℤ√d) = 1 := by simp only [zsqrtd.ext, zsqrtd.conj_re, zsqrtd.conj_im, zsqrtd.one_im, neg_zero, eq_self_iff_true, and_self] @[simp] lemma conj_neg (x : ℤ√d) : (-x).conj = -x.conj := rfl @[simp] lemma conj_add (x y : ℤ√d) : (x + y).conj = x.conj + y.conj := conj_hom.map_add x y @[simp] lemma conj_sub (x y : ℤ√d) : (x - y).conj = x.conj - y.conj := conj_hom.map_sub x y @[simp] lemma conj_conj {d : ℤ} (x : ℤ√d) : x.conj.conj = x := by simp only [ext, true_and, conj_re, eq_self_iff_true, neg_neg, conj_im] instance : nontrivial ℤ√d := ⟨⟨0, 1, dec_trivial⟩⟩ @[simp] theorem coe_nat_re (n : ℕ) : (n : ℤ√d).re = n := rfl @[simp] theorem coe_nat_im (n : ℕ) : (n : ℤ√d).im = 0 := rfl theorem coe_nat_val (n : ℕ) : (n : ℤ√d) = ⟨n, 0⟩ := rfl @[simp] theorem coe_int_re (n : ℤ) : (n : ℤ√d).re = n := by cases n; refl @[simp] theorem coe_int_im (n : ℤ) : (n : ℤ√d).im = 0 := by cases n; refl theorem coe_int_val (n : ℤ) : (n : ℤ√d) = ⟨n, 0⟩ := by simp [ext] instance : char_zero ℤ√d := { cast_injective := λ m n, by simp [ext] } @[simp] theorem of_int_eq_coe (n : ℤ) : (of_int n : ℤ√d) = n := by simp [ext, of_int_re, of_int_im] @[simp] theorem smul_val (n x y : ℤ) : (n : ℤ√d) * ⟨x, y⟩ = ⟨n * x, n * y⟩ := by simp [ext] theorem smul_re (a : ℤ) (b : ℤ√d) : (↑a * b).re = a * b.re := by simp theorem smul_im (a : ℤ) (b : ℤ√d) : (↑a * b).im = a * b.im := by simp @[simp] theorem muld_val (x y : ℤ) : sqrtd * ⟨x, y⟩ = ⟨d * y, x⟩ := by simp [ext] @[simp] theorem dmuld : sqrtd * sqrtd = d := by simp [ext] @[simp] theorem smuld_val (n x y : ℤ) : sqrtd * (n : ℤ√d) * ⟨x, y⟩ = ⟨d * n * y, n * x⟩ := by simp [ext] theorem decompose {x y : ℤ} : (⟨x, y⟩ : ℤ√d) = x + sqrtd * y := by simp [ext] theorem mul_conj {x y : ℤ} : (⟨x, y⟩ * conj ⟨x, y⟩ : ℤ√d) = x * x - d * y * y := by simp [ext, sub_eq_add_neg, mul_comm] theorem conj_mul {a b : ℤ√d} : conj (a * b) = conj a * conj b := by { simp [ext], ring } protected lemma coe_int_add (m n : ℤ) : (↑(m + n) : ℤ√d) = ↑m + ↑n := (int.cast_ring_hom _).map_add _ _ protected lemma coe_int_sub (m n : ℤ) : (↑(m - n) : ℤ√d) = ↑m - ↑n := (int.cast_ring_hom _).map_sub _ _ protected lemma coe_int_mul (m n : ℤ) : (↑(m * n) : ℤ√d) = ↑m * ↑n := (int.cast_ring_hom _).map_mul _ _ protected lemma coe_int_inj {m n : ℤ} (h : (↑m : ℤ√d) = ↑n) : m = n := by simpa using congr_arg re h lemma coe_int_dvd_iff (z : ℤ) (a : ℤ√d) : ↑z ∣ a ↔ z ∣ a.re ∧ z ∣ a.im := begin split, { rintro ⟨x, rfl⟩, simp only [add_zero, coe_int_re, zero_mul, mul_im, dvd_mul_right, and_self, mul_re, mul_zero, coe_int_im] }, { rintro ⟨⟨r, hr⟩, ⟨i, hi⟩⟩, use ⟨r, i⟩, rw [smul_val, ext], exact ⟨hr, hi⟩ }, end @[simp, norm_cast] lemma coe_int_dvd_coe_int (a b : ℤ) : (a : ℤ√d) ∣ b ↔ a ∣ b := begin rw coe_int_dvd_iff, split, { rintro ⟨hre, -⟩, rwa [coe_int_re] at hre }, { rw [coe_int_re, coe_int_im], exact λ hc, ⟨hc, dvd_zero a⟩ }, end protected lemma eq_of_smul_eq_smul_left {a : ℤ} {b c : ℤ√d} (ha : a ≠ 0) (h : ↑a * b = a * c) : b = c := begin rw ext at h ⊢, apply and.imp _ _ h; { simpa only [smul_re, smul_im] using mul_left_cancel₀ ha }, end section gcd lemma gcd_eq_zero_iff (a : ℤ√d) : int.gcd a.re a.im = 0 ↔ a = 0 := by simp only [int.gcd_eq_zero_iff, ext, eq_self_iff_true, zero_im, zero_re] lemma gcd_pos_iff (a : ℤ√d) : 0 < int.gcd a.re a.im ↔ a ≠ 0 := pos_iff_ne_zero.trans $ not_congr a.gcd_eq_zero_iff lemma coprime_of_dvd_coprime {a b : ℤ√d} (hcoprime : is_coprime a.re a.im) (hdvd : b ∣ a) : is_coprime b.re b.im := begin apply is_coprime_of_dvd, { rintro ⟨hre, him⟩, obtain rfl : b = 0, { simp only [ext, hre, eq_self_iff_true, zero_im, him, and_self, zero_re] }, rw zero_dvd_iff at hdvd, simpa only [hdvd, zero_im, zero_re, not_coprime_zero_zero] using hcoprime }, { intros z hz hznezero hzdvdu hzdvdv, apply hz, obtain ⟨ha, hb⟩ : z ∣ a.re ∧ z ∣ a.im, { rw ←coe_int_dvd_iff, apply dvd_trans _ hdvd, rw coe_int_dvd_iff, exact ⟨hzdvdu, hzdvdv⟩ }, exact hcoprime.is_unit_of_dvd' ha hb }, end lemma exists_coprime_of_gcd_pos {a : ℤ√d} (hgcd : 0 < int.gcd a.re a.im) : ∃ b : ℤ√d, a = ((int.gcd a.re a.im : ℤ) : ℤ√d) * b ∧ is_coprime b.re b.im := begin obtain ⟨re, im, H1, Hre, Him⟩ := int.exists_gcd_one hgcd, rw [mul_comm] at Hre Him, refine ⟨⟨re, im⟩, _, _⟩, { rw [smul_val, ext, ←Hre, ←Him], split; refl }, { rw [←int.gcd_eq_one_iff_coprime, H1] } end end gcd /-- Read `sq_le a c b d` as `a √c ≤ b √d` -/ def sq_le (a c b d : ℕ) : Prop := c*a*a ≤ d*b*b theorem sq_le_of_le {c d x y z w : ℕ} (xz : z ≤ x) (yw : y ≤ w) (xy : sq_le x c y d) : sq_le z c w d := le_trans (mul_le_mul (nat.mul_le_mul_left _ xz) xz (nat.zero_le _) (nat.zero_le _)) $ le_trans xy (mul_le_mul (nat.mul_le_mul_left _ yw) yw (nat.zero_le _) (nat.zero_le _)) theorem sq_le_add_mixed {c d x y z w : ℕ} (xy : sq_le x c y d) (zw : sq_le z c w d) : c * (x * z) ≤ d * (y * w) := nat.mul_self_le_mul_self_iff.2 $ by simpa [mul_comm, mul_left_comm] using mul_le_mul xy zw (nat.zero_le _) (nat.zero_le _) theorem sq_le_add {c d x y z w : ℕ} (xy : sq_le x c y d) (zw : sq_le z c w d) : sq_le (x + z) c (y + w) d := begin have xz := sq_le_add_mixed xy zw, simp [sq_le, mul_assoc] at xy zw, simp [sq_le, mul_add, mul_comm, mul_left_comm, add_le_add, *] end theorem sq_le_cancel {c d x y z w : ℕ} (zw : sq_le y d x c) (h : sq_le (x + z) c (y + w) d) : sq_le z c w d := begin apply le_of_not_gt, intro l, refine not_le_of_gt _ h, simp [sq_le, mul_add, mul_comm, mul_left_comm, add_assoc], have hm := sq_le_add_mixed zw (le_of_lt l), simp [sq_le, mul_assoc] at l zw, exact lt_of_le_of_lt (add_le_add_right zw _) (add_lt_add_left (add_lt_add_of_le_of_lt hm (add_lt_add_of_le_of_lt hm l)) _) end theorem sq_le_smul {c d x y : ℕ} (n : ℕ) (xy : sq_le x c y d) : sq_le (n * x) c (n * y) d := by simpa [sq_le, mul_left_comm, mul_assoc] using nat.mul_le_mul_left (n * n) xy theorem sq_le_mul {d x y z w : ℕ} : (sq_le x 1 y d → sq_le z 1 w d → sq_le (x * w + y * z) d (x * z + d * y * w) 1) ∧ (sq_le x 1 y d → sq_le w d z 1 → sq_le (x * z + d * y * w) 1 (x * w + y * z) d) ∧ (sq_le y d x 1 → sq_le z 1 w d → sq_le (x * z + d * y * w) 1 (x * w + y * z) d) ∧ (sq_le y d x 1 → sq_le w d z 1 → sq_le (x * w + y * z) d (x * z + d * y * w) 1) := by refine ⟨_, _, _, _⟩; { intros xy zw, have := int.mul_nonneg (sub_nonneg_of_le (int.coe_nat_le_coe_nat_of_le xy)) (sub_nonneg_of_le (int.coe_nat_le_coe_nat_of_le zw)), refine int.le_of_coe_nat_le_coe_nat (le_of_sub_nonneg _), convert this, simp only [one_mul, int.coe_nat_add, int.coe_nat_mul], ring } /-- "Generalized" `nonneg`. `nonnegg c d x y` means `a √c + b √d ≥ 0`; we are interested in the case `c = 1` but this is more symmetric -/ def nonnegg (c d : ℕ) : ℤ → ℤ → Prop | (a : ℕ) (b : ℕ) := true | (a : ℕ) -[1+ b] := sq_le (b+1) c a d | -[1+ a] (b : ℕ) := sq_le (a+1) d b c | -[1+ a] -[1+ b] := false theorem nonnegg_comm {c d : ℕ} {x y : ℤ} : nonnegg c d x y = nonnegg d c y x := by induction x; induction y; refl theorem nonnegg_neg_pos {c d} : Π {a b : ℕ}, nonnegg c d (-a) b ↔ sq_le a d b c | 0 b := ⟨by simp [sq_le, nat.zero_le], λa, trivial⟩ | (a+1) b := by rw ← int.neg_succ_of_nat_coe; refl theorem nonnegg_pos_neg {c d} {a b : ℕ} : nonnegg c d a (-b) ↔ sq_le b c a d := by rw nonnegg_comm; exact nonnegg_neg_pos theorem nonnegg_cases_right {c d} {a : ℕ} : Π {b : ℤ}, (Π x : ℕ, b = -x → sq_le x c a d) → nonnegg c d a b | (b:nat) h := trivial | -[1+ b] h := h (b+1) rfl theorem nonnegg_cases_left {c d} {b : ℕ} {a : ℤ} (h : Π x : ℕ, a = -x → sq_le x d b c) : nonnegg c d a b := cast nonnegg_comm (nonnegg_cases_right h) section norm /-- The norm of an element of `ℤ[√d]`. -/ def norm (n : ℤ√d) : ℤ := n.re * n.re - d * n.im * n.im lemma norm_def (n : ℤ√d) : n.norm = n.re * n.re - d * n.im * n.im := rfl @[simp] lemma norm_zero : norm 0 = 0 := by simp [norm] @[simp] lemma norm_one : norm 1 = 1 := by simp [norm] @[simp] lemma norm_int_cast (n : ℤ) : norm n = n * n := by simp [norm] @[simp] lemma norm_nat_cast (n : ℕ) : norm n = n * n := norm_int_cast n @[simp] lemma norm_mul (n m : ℤ√d) : norm (n * m) = norm n * norm m := by { simp only [norm, mul_im, mul_re], ring } /-- `norm` as a `monoid_hom`. -/ def norm_monoid_hom : ℤ√d →* ℤ := { to_fun := norm, map_mul' := norm_mul, map_one' := norm_one } lemma norm_eq_mul_conj (n : ℤ√d) : (norm n : ℤ√d) = n * n.conj := by cases n; simp [norm, conj, zsqrtd.ext, mul_comm, sub_eq_add_neg] @[simp] lemma norm_neg (x : ℤ√d) : (-x).norm = x.norm := coe_int_inj $ by simp only [norm_eq_mul_conj, conj_neg, neg_mul, mul_neg, neg_neg] @[simp] lemma norm_conj (x : ℤ√d) : x.conj.norm = x.norm := coe_int_inj $ by simp only [norm_eq_mul_conj, conj_conj, mul_comm] lemma norm_nonneg (hd : d ≤ 0) (n : ℤ√d) : 0 ≤ n.norm := add_nonneg (mul_self_nonneg _) (by rw [mul_assoc, neg_mul_eq_neg_mul]; exact (mul_nonneg (neg_nonneg.2 hd) (mul_self_nonneg _))) lemma norm_eq_one_iff {x : ℤ√d} : x.norm.nat_abs = 1 ↔ is_unit x := ⟨λ h, is_unit_iff_dvd_one.2 $ (le_total 0 (norm x)).cases_on (λ hx, show x ∣ 1, from ⟨x.conj, by rwa [← int.coe_nat_inj', int.nat_abs_of_nonneg hx, ← @int.cast_inj (ℤ√d) _ _, norm_eq_mul_conj, eq_comm] at h⟩) (λ hx, show x ∣ 1, from ⟨- x.conj, by rwa [← int.coe_nat_inj', int.of_nat_nat_abs_of_nonpos hx, ← @int.cast_inj (ℤ√d) _ _, int.cast_neg, norm_eq_mul_conj, neg_mul_eq_mul_neg, eq_comm] at h⟩), λ h, let ⟨y, hy⟩ := is_unit_iff_dvd_one.1 h in begin have := congr_arg (int.nat_abs ∘ norm) hy, rw [function.comp_app, function.comp_app, norm_mul, int.nat_abs_mul, norm_one, int.nat_abs_one, eq_comm, nat.mul_eq_one_iff] at this, exact this.1 end⟩ lemma is_unit_iff_norm_is_unit {d : ℤ} (z : ℤ√d) : is_unit z ↔ is_unit z.norm := by rw [int.is_unit_iff_nat_abs_eq, norm_eq_one_iff] lemma norm_eq_one_iff' {d : ℤ} (hd : d ≤ 0) (z : ℤ√d) : z.norm = 1 ↔ is_unit z := by rw [←norm_eq_one_iff, ←int.coe_nat_inj', int.nat_abs_of_nonneg (norm_nonneg hd z), int.coe_nat_one] lemma norm_eq_zero_iff {d : ℤ} (hd : d < 0) (z : ℤ√d) : z.norm = 0 ↔ z = 0 := begin split, { intro h, rw [ext, zero_re, zero_im], rw [norm_def, sub_eq_add_neg, mul_assoc] at h, have left := mul_self_nonneg z.re, have right := neg_nonneg.mpr (mul_nonpos_of_nonpos_of_nonneg hd.le (mul_self_nonneg z.im)), obtain ⟨ha, hb⟩ := (add_eq_zero_iff' left right).mp h, split; apply eq_zero_of_mul_self_eq_zero, { exact ha }, { rw [neg_eq_zero, mul_eq_zero] at hb, exact hb.resolve_left hd.ne } }, { rintro rfl, exact norm_zero } end lemma norm_eq_of_associated {d : ℤ} (hd : d ≤ 0) {x y : ℤ√d} (h : associated x y) : x.norm = y.norm := begin obtain ⟨u, rfl⟩ := h, rw [norm_mul, (norm_eq_one_iff' hd _).mpr u.is_unit, mul_one], end end norm end section parameter {d : ℕ} /-- Nonnegativity of an element of `ℤ√d`. -/ def nonneg : ℤ√d → Prop | ⟨a, b⟩ := nonnegg d 1 a b instance : has_le ℤ√d := ⟨λ a b, nonneg (b - a)⟩ instance : has_lt ℤ√d := ⟨λ a b, ¬ b ≤ a⟩ instance decidable_nonnegg (c d a b) : decidable (nonnegg c d a b) := by cases a; cases b; repeat {rw int.of_nat_eq_coe}; unfold nonnegg sq_le; apply_instance instance decidable_nonneg : Π (a : ℤ√d), decidable (nonneg a) | ⟨a, b⟩ := zsqrtd.decidable_nonnegg _ _ _ _ instance decidable_le : @decidable_rel (ℤ√d) (≤) := λ _ _, decidable_nonneg _ theorem nonneg_cases : Π {a : ℤ√d}, nonneg a → ∃ x y : ℕ, a = ⟨x, y⟩ ∨ a = ⟨x, -y⟩ ∨ a = ⟨-x, y⟩ | ⟨(x : ℕ), (y : ℕ)⟩ h := ⟨x, y, or.inl rfl⟩ | ⟨(x : ℕ), -[1+ y]⟩ h := ⟨x, y+1, or.inr $ or.inl rfl⟩ | ⟨-[1+ x], (y : ℕ)⟩ h := ⟨x+1, y, or.inr $ or.inr rfl⟩ | ⟨-[1+ x], -[1+ y]⟩ h := false.elim h lemma nonneg_add_lem {x y z w : ℕ} (xy : nonneg ⟨x, -y⟩) (zw : nonneg ⟨-z, w⟩) : nonneg (⟨x, -y⟩ + ⟨-z, w⟩) := have nonneg ⟨int.sub_nat_nat x z, int.sub_nat_nat w y⟩, from int.sub_nat_nat_elim x z (λm n i, sq_le y d m 1 → sq_le n 1 w d → nonneg ⟨i, int.sub_nat_nat w y⟩) (λj k, int.sub_nat_nat_elim w y (λm n i, sq_le n d (k + j) 1 → sq_le k 1 m d → nonneg ⟨int.of_nat j, i⟩) (λm n xy zw, trivial) (λm n xy zw, sq_le_cancel zw xy)) (λj k, int.sub_nat_nat_elim w y (λm n i, sq_le n d k 1 → sq_le (k + j + 1) 1 m d → nonneg ⟨-[1+ j], i⟩) (λm n xy zw, sq_le_cancel xy zw) (λm n xy zw, let t := nat.le_trans zw (sq_le_of_le (nat.le_add_right n (m+1)) le_rfl xy) in have k + j + 1 ≤ k, from nat.mul_self_le_mul_self_iff.2 (by repeat{rw one_mul at t}; exact t), absurd this (not_le_of_gt $ nat.succ_le_succ $ nat.le_add_right _ _))) (nonnegg_pos_neg.1 xy) (nonnegg_neg_pos.1 zw), show nonneg ⟨_, _⟩, by rw [neg_add_eq_sub]; rwa [int.sub_nat_nat_eq_coe,int.sub_nat_nat_eq_coe] at this lemma nonneg.add {a b : ℤ√d} (ha : nonneg a) (hb : nonneg b) : nonneg (a + b) := begin rcases nonneg_cases ha with ⟨x, y, rfl|rfl|rfl⟩; rcases nonneg_cases hb with ⟨z, w, rfl|rfl|rfl⟩, { trivial }, { refine nonnegg_cases_right (λi h, sq_le_of_le _ _ (nonnegg_pos_neg.1 hb)), { exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ y (by simp [add_comm, *]))) }, { apply nat.le_add_left } }, { refine nonnegg_cases_left (λi h, sq_le_of_le _ _ (nonnegg_neg_pos.1 hb)), { exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ x (by simp [add_comm, *]))) }, { apply nat.le_add_left } }, { refine nonnegg_cases_right (λi h, sq_le_of_le _ _ (nonnegg_pos_neg.1 ha)), { exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ w (by simp *))) }, { apply nat.le_add_right } }, { simpa [add_comm] using nonnegg_pos_neg.2 (sq_le_add (nonnegg_pos_neg.1 ha) (nonnegg_pos_neg.1 hb)) }, { exact nonneg_add_lem ha hb }, { refine nonnegg_cases_left (λi h, sq_le_of_le _ _ (nonnegg_neg_pos.1 ha)), { exact int.coe_nat_le.1 (le_of_neg_le_neg (int.le.intro h)) }, { apply nat.le_add_right } }, { dsimp, rw [add_comm, add_comm ↑y], exact nonneg_add_lem hb ha }, { simpa [add_comm] using nonnegg_neg_pos.2 (sq_le_add (nonnegg_neg_pos.1 ha) (nonnegg_neg_pos.1 hb)) }, end theorem nonneg_iff_zero_le {a : ℤ√d} : nonneg a ↔ 0 ≤ a := show _ ↔ nonneg _, by simp theorem le_of_le_le {x y z w : ℤ} (xz : x ≤ z) (yw : y ≤ w) : (⟨x, y⟩ : ℤ√d) ≤ ⟨z, w⟩ := show nonneg ⟨z - x, w - y⟩, from match z - x, w - y, int.le.dest_sub xz, int.le.dest_sub yw with ._, ._, ⟨a, rfl⟩, ⟨b, rfl⟩ := trivial end protected theorem nonneg_total : Π (a : ℤ√d), nonneg a ∨ nonneg (-a) | ⟨(x : ℕ), (y : ℕ)⟩ := or.inl trivial | ⟨-[1+ x], -[1+ y]⟩ := or.inr trivial | ⟨0, -[1+ y]⟩ := or.inr trivial | ⟨-[1+ x], 0⟩ := or.inr trivial | ⟨(x+1:ℕ), -[1+ y]⟩ := nat.le_total | ⟨-[1+ x], (y+1:ℕ)⟩ := nat.le_total protected theorem le_total (a b : ℤ√d) : a ≤ b ∨ b ≤ a := begin have t := (b - a).nonneg_total, rwa neg_sub at t, end instance : preorder ℤ√d := { le := (≤), le_refl := λ a, show nonneg (a - a), by simp only [sub_self], le_trans := λ a b c hab hbc, by simpa [sub_add_sub_cancel'] using hab.add hbc, lt := (<), lt_iff_le_not_le := λ a b, (and_iff_right_of_imp (zsqrtd.le_total _ _).resolve_left).symm } theorem le_arch (a : ℤ√d) : ∃n : ℕ, a ≤ n := let ⟨x, y, (h : a ≤ ⟨x, y⟩)⟩ := show ∃x y : ℕ, nonneg (⟨x, y⟩ + -a), from match -a with | ⟨int.of_nat x, int.of_nat y⟩ := ⟨0, 0, trivial⟩ | ⟨int.of_nat x, -[1+ y]⟩ := ⟨0, y+1, by simp [int.neg_succ_of_nat_coe, add_assoc]⟩ | ⟨-[1+ x], int.of_nat y⟩ := ⟨x+1, 0, by simp [int.neg_succ_of_nat_coe, add_assoc]⟩ | ⟨-[1+ x], -[1+ y]⟩ := ⟨x+1, y+1, by simp [int.neg_succ_of_nat_coe, add_assoc]⟩ end in begin refine ⟨x + d*y, h.trans _⟩, change nonneg ⟨(↑x + d*y) - ↑x, 0-↑y⟩, cases y with y, { simp }, have h : ∀y, sq_le y d (d * y) 1 := λ y, by simpa [sq_le, mul_comm, mul_left_comm] using nat.mul_le_mul_right (y * y) (nat.le_mul_self d), rw [show (x:ℤ) + d * nat.succ y - x = d * nat.succ y, by simp], exact h (y+1) end protected theorem add_le_add_left (a b : ℤ√d) (ab : a ≤ b) (c : ℤ√d) : c + a ≤ c + b := show nonneg _, by rw add_sub_add_left_eq_sub; exact ab protected theorem le_of_add_le_add_left (a b c : ℤ√d) (h : c + a ≤ c + b) : a ≤ b := by simpa using zsqrtd.add_le_add_left _ _ h (-c) protected theorem add_lt_add_left (a b : ℤ√d) (h : a < b) (c) : c + a < c + b := λ h', h (zsqrtd.le_of_add_le_add_left _ _ _ h') theorem nonneg_smul {a : ℤ√d} {n : ℕ} (ha : nonneg a) : nonneg (n * a) := by simp only [← int.cast_coe_nat] {single_pass := tt}; exact match a, nonneg_cases ha, ha with | ._, ⟨x, y, or.inl rfl⟩, ha := by rw smul_val; trivial | ._, ⟨x, y, or.inr $ or.inl rfl⟩, ha := by rw smul_val; simpa using nonnegg_pos_neg.2 (sq_le_smul n $ nonnegg_pos_neg.1 ha) | ._, ⟨x, y, or.inr $ or.inr rfl⟩, ha := by rw smul_val; simpa using nonnegg_neg_pos.2 (sq_le_smul n $ nonnegg_neg_pos.1 ha) end theorem nonneg_muld {a : ℤ√d} (ha : nonneg a) : nonneg (sqrtd * a) := by refine match a, nonneg_cases ha, ha with | ._, ⟨x, y, or.inl rfl⟩, ha := trivial | ._, ⟨x, y, or.inr $ or.inl rfl⟩, ha := by simp; apply nonnegg_neg_pos.2; simpa [sq_le, mul_comm, mul_left_comm] using nat.mul_le_mul_left d (nonnegg_pos_neg.1 ha) | ._, ⟨x, y, or.inr $ or.inr rfl⟩, ha := by simp; apply nonnegg_pos_neg.2; simpa [sq_le, mul_comm, mul_left_comm] using nat.mul_le_mul_left d (nonnegg_neg_pos.1 ha) end theorem nonneg_mul_lem {x y : ℕ} {a : ℤ√d} (ha : nonneg a) : nonneg (⟨x, y⟩ * a) := have (⟨x, y⟩ * a : ℤ√d) = x * a + sqrtd * (y * a), by rw [decompose, right_distrib, mul_assoc]; refl, by rw this; exact (nonneg_smul ha).add (nonneg_muld $ nonneg_smul ha) theorem nonneg_mul {a b : ℤ√d} (ha : nonneg a) (hb : nonneg b) : nonneg (a * b) := match a, b, nonneg_cases ha, nonneg_cases hb, ha, hb with | ._, ._, ⟨x, y, or.inl rfl⟩, ⟨z, w, or.inl rfl⟩, ha, hb := trivial | ._, ._, ⟨x, y, or.inl rfl⟩, ⟨z, w, or.inr $ or.inr rfl⟩, ha, hb := nonneg_mul_lem hb | ._, ._, ⟨x, y, or.inl rfl⟩, ⟨z, w, or.inr $ or.inl rfl⟩, ha, hb := nonneg_mul_lem hb | ._, ._, ⟨x, y, or.inr $ or.inr rfl⟩, ⟨z, w, or.inl rfl⟩, ha, hb := by rw mul_comm; exact nonneg_mul_lem ha | ._, ._, ⟨x, y, or.inr $ or.inl rfl⟩, ⟨z, w, or.inl rfl⟩, ha, hb := by rw mul_comm; exact nonneg_mul_lem ha | ._, ._, ⟨x, y, or.inr $ or.inr rfl⟩, ⟨z, w, or.inr $ or.inr rfl⟩, ha, hb := by rw [calc (⟨-x, y⟩ * ⟨-z, w⟩ : ℤ√d) = ⟨_, _⟩ : rfl ... = ⟨x * z + d * y * w, -(x * w + y * z)⟩ : by simp [add_comm]]; exact nonnegg_pos_neg.2 (sq_le_mul.left (nonnegg_neg_pos.1 ha) (nonnegg_neg_pos.1 hb)) | ._, ._, ⟨x, y, or.inr $ or.inr rfl⟩, ⟨z, w, or.inr $ or.inl rfl⟩, ha, hb := by rw [calc (⟨-x, y⟩ * ⟨z, -w⟩ : ℤ√d) = ⟨_, _⟩ : rfl ... = ⟨-(x * z + d * y * w), x * w + y * z⟩ : by simp [add_comm]]; exact nonnegg_neg_pos.2 (sq_le_mul.right.left (nonnegg_neg_pos.1 ha) (nonnegg_pos_neg.1 hb)) | ._, ._, ⟨x, y, or.inr $ or.inl rfl⟩, ⟨z, w, or.inr $ or.inr rfl⟩, ha, hb := by rw [calc (⟨x, -y⟩ * ⟨-z, w⟩ : ℤ√d) = ⟨_, _⟩ : rfl ... = ⟨-(x * z + d * y * w), x * w + y * z⟩ : by simp [add_comm]]; exact nonnegg_neg_pos.2 (sq_le_mul.right.right.left (nonnegg_pos_neg.1 ha) (nonnegg_neg_pos.1 hb)) | ._, ._, ⟨x, y, or.inr $ or.inl rfl⟩, ⟨z, w, or.inr $ or.inl rfl⟩, ha, hb := by rw [calc (⟨x, -y⟩ * ⟨z, -w⟩ : ℤ√d) = ⟨_, _⟩ : rfl ... = ⟨x * z + d * y * w, -(x * w + y * z)⟩ : by simp [add_comm]]; exact nonnegg_pos_neg.2 (sq_le_mul.right.right.right (nonnegg_pos_neg.1 ha) (nonnegg_pos_neg.1 hb)) end protected theorem mul_nonneg (a b : ℤ√d) : 0 ≤ a → 0 ≤ b → 0 ≤ a * b := by repeat {rw ← nonneg_iff_zero_le}; exact nonneg_mul theorem not_sq_le_succ (c d y) (h : 0 < c) : ¬sq_le (y + 1) c 0 d := not_le_of_gt $ mul_pos (mul_pos h $ nat.succ_pos _) $ nat.succ_pos _ /-- A nonsquare is a natural number that is not equal to the square of an integer. This is implemented as a typeclass because it's a necessary condition for much of the Pell equation theory. -/ class nonsquare (x : ℕ) : Prop := (ns [] : ∀n : ℕ, x ≠ n*n) parameter [dnsq : nonsquare d] include dnsq theorem d_pos : 0 < d := lt_of_le_of_ne (nat.zero_le _) $ ne.symm $ (nonsquare.ns d 0) theorem divides_sq_eq_zero {x y} (h : x * x = d * y * y) : x = 0 ∧ y = 0 := let g := x.gcd y in or.elim g.eq_zero_or_pos (λH, ⟨nat.eq_zero_of_gcd_eq_zero_left H, nat.eq_zero_of_gcd_eq_zero_right H⟩) (λgpos, false.elim $ let ⟨m, n, co, (hx : x = m * g), (hy : y = n * g)⟩ := nat.exists_coprime gpos in begin rw [hx, hy] at h, have : m * m = d * (n * n) := mul_left_cancel₀ (mul_pos gpos gpos).ne' (by simpa [mul_comm, mul_left_comm] using h), have co2 := let co1 := co.mul_right co in co1.mul co1, exact nonsquare.ns d m (nat.dvd_antisymm (by rw this; apply dvd_mul_right) $ co2.dvd_of_dvd_mul_right $ by simp [this]) end) theorem divides_sq_eq_zero_z {x y : ℤ} (h : x * x = d * y * y) : x = 0 ∧ y = 0 := by rw [mul_assoc, ← int.nat_abs_mul_self, ← int.nat_abs_mul_self, ← int.coe_nat_mul, ← mul_assoc] at h; exact let ⟨h1, h2⟩ := divides_sq_eq_zero (int.coe_nat_inj h) in ⟨int.eq_zero_of_nat_abs_eq_zero h1, int.eq_zero_of_nat_abs_eq_zero h2⟩ theorem not_divides_sq (x y) : (x + 1) * (x + 1) ≠ d * (y + 1) * (y + 1) := λe, by have t := (divides_sq_eq_zero e).left; contradiction theorem nonneg_antisymm : Π {a : ℤ√d}, nonneg a → nonneg (-a) → a = 0 | ⟨0, 0⟩ xy yx := rfl | ⟨-[1+ x], -[1+ y]⟩ xy yx := false.elim xy | ⟨(x+1:nat), (y+1:nat)⟩ xy yx := false.elim yx | ⟨-[1+ x], 0⟩ xy yx := absurd xy (not_sq_le_succ _ _ _ dec_trivial) | ⟨(x+1:nat), 0⟩ xy yx := absurd yx (not_sq_le_succ _ _ _ dec_trivial) | ⟨0, -[1+ y]⟩ xy yx := absurd xy (not_sq_le_succ _ _ _ d_pos) | ⟨0, (y+1:nat)⟩ _ yx := absurd yx (not_sq_le_succ _ _ _ d_pos) | ⟨(x+1:nat), -[1+ y]⟩ (xy : sq_le _ _ _ _) (yx : sq_le _ _ _ _) := let t := le_antisymm yx xy in by rw[one_mul] at t; exact absurd t (not_divides_sq _ _) | ⟨-[1+ x], (y+1:nat)⟩ (xy : sq_le _ _ _ _) (yx : sq_le _ _ _ _) := let t := le_antisymm xy yx in by rw[one_mul] at t; exact absurd t (not_divides_sq _ _) theorem le_antisymm {a b : ℤ√d} (ab : a ≤ b) (ba : b ≤ a) : a = b := eq_of_sub_eq_zero $ nonneg_antisymm ba (by rw neg_sub; exact ab) instance : linear_order ℤ√d := { le_antisymm := @zsqrtd.le_antisymm, le_total := zsqrtd.le_total, decidable_le := zsqrtd.decidable_le, ..zsqrtd.preorder } protected theorem eq_zero_or_eq_zero_of_mul_eq_zero : Π {a b : ℤ√d}, a * b = 0 → a = 0 ∨ b = 0 | ⟨x, y⟩ ⟨z, w⟩ h := by injection h with h1 h2; exact have h1 : x*z = -(d*y*w), from eq_neg_of_add_eq_zero_left h1, have h2 : x*w = -(y*z), from eq_neg_of_add_eq_zero_left h2, have fin : x*x = d*y*y → (⟨x, y⟩:ℤ√d) = 0, from λe, match x, y, divides_sq_eq_zero_z e with ._, ._, ⟨rfl, rfl⟩ := rfl end, if z0 : z = 0 then if w0 : w = 0 then or.inr (match z, w, z0, w0 with ._, ._, rfl, rfl := rfl end) else or.inl $ fin $ mul_right_cancel₀ w0 $ calc x * x * w = -y * (x * z) : by simp [h2, mul_assoc, mul_left_comm] ... = d * y * y * w : by simp [h1, mul_assoc, mul_left_comm] else or.inl $ fin $ mul_right_cancel₀ z0 $ calc x * x * z = d * -y * (x * w) : by simp [h1, mul_assoc, mul_left_comm] ... = d * y * y * z : by simp [h2, mul_assoc, mul_left_comm] instance : no_zero_divisors ℤ√d := { eq_zero_or_eq_zero_of_mul_eq_zero := @zsqrtd.eq_zero_or_eq_zero_of_mul_eq_zero } instance : is_domain ℤ√d := by exact no_zero_divisors.to_is_domain _ protected theorem mul_pos (a b : ℤ√d) (a0 : 0 < a) (b0 : 0 < b) : 0 < a * b := λab, or.elim (eq_zero_or_eq_zero_of_mul_eq_zero (le_antisymm ab (mul_nonneg _ _ (le_of_lt a0) (le_of_lt b0)))) (λe, ne_of_gt a0 e) (λe, ne_of_gt b0 e) instance : linear_ordered_comm_ring ℤ√d := { add_le_add_left := @zsqrtd.add_le_add_left, mul_pos := @zsqrtd.mul_pos, zero_le_one := dec_trivial, .. zsqrtd.comm_ring, .. zsqrtd.linear_order, .. zsqrtd.nontrivial } instance : linear_ordered_ring ℤ√d := by apply_instance instance : ordered_ring ℤ√d := by apply_instance end lemma norm_eq_zero {d : ℤ} (h_nonsquare : ∀ n : ℤ, d ≠ n*n) (a : ℤ√d) : norm a = 0 ↔ a = 0 := begin refine ⟨λ ha, ext.mpr _, λ h, by rw [h, norm_zero]⟩, delta norm at ha, rw sub_eq_zero at ha, by_cases h : 0 ≤ d, { obtain ⟨d', rfl⟩ := int.eq_coe_of_zero_le h, haveI : nonsquare d' := ⟨λ n h, h_nonsquare n $ by exact_mod_cast h⟩, exact divides_sq_eq_zero_z ha, }, { push_neg at h, suffices : a.re * a.re = 0, { rw eq_zero_of_mul_self_eq_zero this at ha ⊢, simpa only [true_and, or_self_right, zero_re, zero_im, eq_self_iff_true, zero_eq_mul, mul_zero, mul_eq_zero, h.ne, false_or, or_self] using ha }, apply _root_.le_antisymm _ (mul_self_nonneg _), rw [ha, mul_assoc], exact mul_nonpos_of_nonpos_of_nonneg h.le (mul_self_nonneg _) } end variables {R : Type} @[ext] lemma hom_ext [ring R] {d : ℤ} (f g : ℤ√d →+* R) (h : f sqrtd = g sqrtd) : f = g := begin ext ⟨x_re, x_im⟩, simp [decompose, h], end variables [comm_ring R] /-- The unique `ring_hom` from `ℤ√d` to a ring `R`, constructed by replacing `√d` with the provided root. Conversely, this associates to every mapping `ℤ√d →+* R` a value of `√d` in `R`. -/ @[simps] def lift {d : ℤ} : {r : R // r * r = ↑d} ≃ (ℤ√d →+* R) := { to_fun := λ r, { to_fun := λ a, a.1 + a.2*(r : R), map_zero' := by simp, map_add' := λ a b, by { simp, ring, }, map_one' := by simp, map_mul' := λ a b, by { have : (a.re + a.im * r : R) * (b.re + b.im * r) = a.re * b.re + (a.re * b.im + a.im * b.re) * r + a.im * b.im * (r * r) := by ring, simp [this, r.prop], ring, } }, inv_fun := λ f, ⟨f sqrtd, by rw [←f.map_mul, dmuld, map_int_cast]⟩, left_inv := λ r, by { ext, simp }, right_inv := λ f, by { ext, simp } } /-- `lift r` is injective if `d` is non-square, and R has characteristic zero (that is, the map from `ℤ` into `R` is injective). -/ lemma lift_injective [char_zero R] {d : ℤ} (r : {r : R // r * r = ↑d}) (hd : ∀ n : ℤ, d ≠ n*n) : function.injective (lift r) := (injective_iff_map_eq_zero (lift r)).mpr $ λ a ha, begin have h_inj : function.injective (coe : ℤ → R) := int.cast_injective, suffices : lift r a.norm = 0, { simp only [coe_int_re, add_zero, lift_apply_apply, coe_int_im, int.cast_zero, zero_mul] at this, rwa [← int.cast_zero, h_inj.eq_iff, norm_eq_zero hd] at this }, rw [norm_eq_mul_conj, ring_hom.map_mul, ha, zero_mul] end end zsqrtd
572c7c3b8c14370ea9baead35ab9b520af63a576
7cef822f3b952965621309e88eadf618da0c8ae9
/src/field_theory/minimal_polynomial.lean
1ff4d258ddc29df25e7184e6990bd3a92649e0e8
[ "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
8,597
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johan Commelin -/ import ring_theory.integral_closure /-! # Minimal polynomials This file defines the minimal polynomial of an element x of an A-algebra B, under the assumption that x is integral over A. After stating the defining property we specialize to the setting of field extensions and derive some well-known properties, amongst which the fact that minimal polynomials are irreducible, and uniquely determined by their defining property. -/ universes u v w open_locale classical open polynomial set function variables {α : Type u} {β : Type v} section min_poly_def variables [comm_ring α] [comm_ring β] [algebra α β] /-- Let B be an A-algebra, and x an element of B that is integral over A. The minimal polynomial of x is a monic polynomial of smallest degree that has x as its root. -/ noncomputable def minimal_polynomial {x : β} (hx : is_integral α x) : polynomial α := well_founded.min polynomial.degree_lt_wf _ hx end min_poly_def namespace minimal_polynomial section ring variables [comm_ring α] [comm_ring β] [algebra α β] variables {x : β} (hx : is_integral α x) /--A minimal polynomial is monic.-/ lemma monic : monic (minimal_polynomial hx) := (well_founded.min_mem degree_lt_wf _ hx).1 /--An element is a root of its minimal polynomial.-/ @[simp] lemma aeval : aeval α β x (minimal_polynomial hx) = 0 := (well_founded.min_mem degree_lt_wf _ hx).2 /--The defining property of the minimal polynomial of an element x: it is the monic polynomial with smallest degree that has x as its root.-/ lemma min {p : polynomial α} (pmonic : p.monic) (hp : polynomial.aeval α β x p = 0) : degree (minimal_polynomial hx) ≤ degree p := le_of_not_lt $ well_founded.not_lt_min degree_lt_wf _ hx ⟨pmonic, hp⟩ end ring section field variables [discrete_field α] [discrete_field β] [algebra α β] variables {x : β} (hx : is_integral α x) /--A minimal polynomial is nonzero.-/ lemma ne_zero : (minimal_polynomial hx) ≠ 0 := ne_zero_of_monic (monic hx) /--If an element x is a root of a nonzero polynomial p, then the degree of p is at least the degree of the minimal polynomial of x.-/ lemma degree_le_of_ne_zero {p : polynomial α} (pnz : p ≠ 0) (hp : polynomial.aeval α β x p = 0) : degree (minimal_polynomial hx) ≤ degree p := calc degree (minimal_polynomial hx) ≤ degree (p * C (leading_coeff p)⁻¹) : min _ (monic_mul_leading_coeff_inv pnz) (by simp [hp]) ... = degree p : degree_mul_leading_coeff_inv p pnz /--The minimal polynomial of an element x is uniquely characterized by its defining property: if there is another monic polynomial of minimal degree that has x as a root, then this polynomial is equal to the minimal polynomial of x.-/ lemma unique {p : polynomial α} (pmonic : p.monic) (hp : polynomial.aeval α β x p = 0) (pmin : ∀ q : polynomial α, q.monic → polynomial.aeval α β x q = 0 → degree p ≤ degree q) : p = minimal_polynomial hx := begin symmetry, apply eq_of_sub_eq_zero, by_contra hnz, have := degree_le_of_ne_zero hx hnz (by simp [hp]), contrapose! this, apply degree_sub_lt _ (ne_zero hx), { rw [(monic hx).leading_coeff, pmonic.leading_coeff] }, { exact le_antisymm (min hx pmonic hp) (pmin (minimal_polynomial hx) (monic hx) (aeval hx)) }, end /--If an element x is a root of a polynomial p, then the minimal polynomial of x divides p.-/ lemma dvd {p : polynomial α} (hp : polynomial.aeval α β x p = 0) : minimal_polynomial hx ∣ p := begin rw ← dvd_iff_mod_by_monic_eq_zero (monic hx), by_contra hnz, have := degree_le_of_ne_zero hx hnz _, { contrapose! this, exact degree_mod_by_monic_lt _ (monic hx) (ne_zero hx) }, { rw ← mod_by_monic_add_div p (monic hx) at hp, simpa using hp } end /--The degree of a minimal polynomial is nonzero.-/ lemma degree_ne_zero : degree (minimal_polynomial hx) ≠ 0 := begin assume deg_eq_zero, have ndeg_eq_zero : nat_degree (minimal_polynomial hx) = 0, { simpa using congr_arg nat_degree (eq_C_of_degree_eq_zero deg_eq_zero) }, have eq_one : minimal_polynomial hx = 1, { rw eq_C_of_degree_eq_zero deg_eq_zero, congr, simpa [ndeg_eq_zero.symm] using (monic hx).leading_coeff }, simpa [eq_one, aeval_def] using aeval hx end /--A minimal polynomial is not a unit.-/ lemma not_is_unit : ¬ is_unit (minimal_polynomial hx) := assume H, degree_ne_zero hx $ degree_eq_zero_of_is_unit H /--The degree of a minimal polynomial is positive.-/ lemma degree_pos : 0 < degree (minimal_polynomial hx) := degree_pos_of_ne_zero_of_nonunit (ne_zero hx) (not_is_unit hx) /--A minimal polynomial is prime.-/ lemma prime : prime (minimal_polynomial hx) := begin refine ⟨ne_zero hx, not_is_unit hx, _⟩, rintros p q ⟨d, h⟩, have : polynomial.aeval α β x (p*q) = 0 := by simp [h, aeval hx], replace : polynomial.aeval α β x p = 0 ∨ polynomial.aeval α β x q = 0 := by simpa, cases this; [left, right]; apply dvd; assumption end /--A minimal polynomial is irreducible.-/ lemma irreducible : irreducible (minimal_polynomial hx) := irreducible_of_prime (prime hx) /--If L/K is a field extension, and x is an element of L in the image of K, then the minimal polynomial of x is X - C x.-/ @[simp] protected lemma algebra_map (a : α) (ha : is_integral α (algebra_map β a)) : minimal_polynomial ha = X - C a := begin refine (unique ha (monic_X_sub_C a) (by simp [aeval_def]) _).symm, intros q hq H, rw degree_X_sub_C, suffices : 0 < degree q, { -- This part is annoying and shouldn't be there. have q_ne_zero : q ≠ 0, { apply polynomial.ne_zero_of_degree_gt this }, rw degree_eq_nat_degree q_ne_zero at this ⊢, rw [← with_bot.coe_zero, with_bot.coe_lt_coe] at this, rwa [← with_bot.coe_one, with_bot.coe_le_coe], }, apply degree_pos_of_root (ne_zero_of_monic hq), show is_root q a, apply is_ring_hom.injective (algebra_map β : α → β), rw [is_ring_hom.map_zero (algebra_map β : α → β), ← H], convert polynomial.hom_eval₂ _ _ _ _, { exact is_semiring_hom.id }, { apply_instance } end variable (β) /--If L/K is a field extension, and x is an element of L in the image of K, then the minimal polynomial of x is X - C x.-/ lemma algebra_map' (a : α) : minimal_polynomial (@is_integral_algebra_map α β _ _ _ a) = X - C a := minimal_polynomial.algebra_map _ _ variable {β} /--The minimal polynomial of 0 is X.-/ @[simp] lemma zero {h₀ : is_integral α (0:β)} : minimal_polynomial h₀ = X := by simpa only [add_zero, polynomial.C_0, sub_eq_add_neg, neg_zero, algebra.map_zero] using algebra_map' β (0:α) /--The minimal polynomial of 1 is X - 1.-/ @[simp] lemma one {h₁ : is_integral α (1:β)} : minimal_polynomial h₁ = X - 1 := by simpa only [algebra.map_one, polynomial.C_1, sub_eq_add_neg] using algebra_map' β (1:α) /--If L/K is a field extension and an element y of K is a root of the minimal polynomial of an element x ∈ L, then y maps to x under the field embedding.-/ lemma root {x : β} (hx : is_integral α x) {y : α} (h : is_root (minimal_polynomial hx) y) : algebra_map β y = x := begin have ndeg_one : nat_degree (minimal_polynomial hx) = 1, { rw ← polynomial.degree_eq_iff_nat_degree_eq_of_pos (nat.zero_lt_one), exact degree_eq_one_of_irreducible_of_root (irreducible hx) h }, have coeff_one : (minimal_polynomial hx).coeff 1 = 1, { simpa [ndeg_one, leading_coeff] using (monic hx).leading_coeff }, have hy : y = - coeff (minimal_polynomial hx) 0, { rw (minimal_polynomial hx).as_sum at h, apply eq_neg_of_add_eq_zero, simpa [ndeg_one, finset.sum_range_succ, coeff_one] using h }, subst y, rw [algebra.map_neg, neg_eq_iff_add_eq_zero], have H := aeval hx, rw (minimal_polynomial hx).as_sum at H, simpa [ndeg_one, finset.sum_range_succ, coeff_one, aeval_def] using H end /--The constant coefficient of the minimal polynomial of x is 0 if and only if x = 0.-/ @[simp] lemma coeff_zero_eq_zero : coeff (minimal_polynomial hx) 0 = 0 ↔ x = 0 := begin split, { intro h, have zero_root := polynomial.zero_is_root_of_coeff_zero_eq_zero h, rw ← root hx zero_root, exact is_ring_hom.map_zero _ }, { rintro rfl, simp } end /--The minimal polynomial of a nonzero element has nonzero constant coefficient.-/ lemma coeff_zero_ne_zero (h : x ≠ 0) : coeff (minimal_polynomial hx) 0 ≠ 0 := by { contrapose! h, simpa using h } end field end minimal_polynomial
028cc73aa547648b58bfe91adcc84d7e8ee96795
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/tactic/monotonicity/basic.lean
1662abb704955b2d0bba92e8e9e49014399c172f
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
5,734
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon -/ import algebra.order_functions namespace tactic.interactive open tactic list open lean lean.parser interactive open interactive.types @[derive inhabited] structure mono_cfg := (unify := ff) @[derive [decidable_eq, has_reflect, inhabited]] inductive mono_selection : Type | left : mono_selection | right : mono_selection | both : mono_selection declare_trace mono.relation section compare parameter opt : mono_cfg meta def compare (e₀ e₁ : expr) : tactic unit := do if opt.unify then do guard (¬ e₀.is_mvar ∧ ¬ e₁.is_mvar), unify e₀ e₁ else is_def_eq e₀ e₁ meta def find_one_difference : list expr → list expr → tactic (list expr × expr × expr × list expr) | (x :: xs) (y :: ys) := do c ← try_core (compare x y), if c.is_some then prod.map (cons x) id <$> find_one_difference xs ys else do guard (xs.length = ys.length), mzip_with' compare xs ys, return ([],x,y,xs) | xs ys := fail format!"find_one_difference: {xs}, {ys}" end compare def last_two {α : Type*} (l : list α) : option (α × α) := match l.reverse with | (x₁ :: x₀ :: _) := some (x₀, x₁) | _ := none end meta def match_imp : expr → tactic (expr × expr) | `(%%e₀ → %%e₁) := do guard (¬ e₁.has_var), return (e₀,e₁) | _ := failed open expr meta def same_operator : expr → expr → bool | (app e₀ _) (app e₁ _) := let fn₀ := e₀.get_app_fn, fn₁ := e₁.get_app_fn in fn₀.is_constant ∧ fn₀.const_name = fn₁.const_name | (pi _ _ _ _) (pi _ _ _ _) := tt | _ _ := ff meta def get_operator (e : expr) : option name := guard (¬ e.is_pi) >> pure e.get_app_fn.const_name meta def monotonicity.check_rel (l r : expr) : tactic (option name) := do guard (same_operator l r) <|> do { fail format!"{l} and {r} should be the f x and f y for some f" }, if l.is_pi then pure none else pure r.get_app_fn.const_name @[reducible] def mono_key := (with_bot name × with_bot name) open nat meta def mono_head_candidates : ℕ → list expr → expr → tactic mono_key | 0 _ h := fail!"Cannot find relation in {h}" | (succ n) xs h := do { (rel,l,r) ← if h.is_arrow then pure (none,h.binding_domain,h.binding_body) else guard h.get_app_fn.is_constant >> prod.mk (some h.get_app_fn.const_name) <$> last_two h.get_app_args, prod.mk <$> monotonicity.check_rel l r <*> pure rel } <|> match xs with | [] := fail format!"oh? {h}" | (x::xs) := mono_head_candidates n xs (h.pis [x]) end meta def monotonicity.check (lm_n : name) : tactic mono_key := do lm ← mk_const lm_n, lm_t ← infer_type lm >>= instantiate_mvars, when_tracing `mono.relation trace!"[mono] Looking for relation in {lm_t}", s ← simp_lemmas.mk.add_simp ``monotone, lm_t ← s.dsimplify [] lm_t { fail_if_unchanged := ff }, when_tracing `mono.relation trace!"[mono] Looking for relation in {lm_t} (after unfolding)", (xs,h) ← open_pis lm_t, mono_head_candidates 3 xs.reverse h meta instance : has_to_format mono_selection := ⟨ λ x, match x with | mono_selection.left := "left" | mono_selection.right := "right" | mono_selection.both := "both" end ⟩ meta def side : lean.parser mono_selection := with_desc "expecting 'left', 'right' or 'both' (default)" $ do some n ← optional ident | pure mono_selection.both, if n = `left then pure $ mono_selection.left else if n = `right then pure $ mono_selection.right else if n = `both then pure $ mono_selection.both else fail format!"invalid argument: {n}, expecting 'left', 'right' or 'both' (default)" open function @[user_attribute] meta def monotonicity.attr : user_attribute (native.rb_lmap mono_key (name)) (option mono_key × mono_selection) := { name := `mono , descr := "monotonicity of function `f` wrt relations `R₀` and `R₁`: R₀ x y → R₁ (f x) (f y)" , cache_cfg := { dependencies := [], mk_cache := λ ls, do ps ← ls.mmap monotonicity.attr.get_param, let ps := ps.filter_map prod.fst, pure $ (ps.zip ls).foldl (flip $ uncurry (λ k n m, m.insert k n)) (native.rb_lmap.mk mono_key _) } , after_set := some $ λ n prio p, do { (none,v) ← monotonicity.attr.get_param n | pure (), k ← monotonicity.check n, monotonicity.attr.set n (some k,v) p } , parser := prod.mk none <$> side } meta def filter_instances (e : mono_selection) (ns : list name) : tactic (list name) := ns.mfilter $ λ n, do d ← user_attribute.get_param_untyped monotonicity.attr n, (_,d) ← to_expr ``(id %%d) >>= eval_expr (option mono_key × mono_selection), return (e = d : bool) meta def get_monotonicity_lemmas (k : expr) (e : mono_selection) : tactic (list name) := do ns ← monotonicity.attr.get_cache, k' ← if k.is_pi then pure (get_operator k.binding_domain,none) else do { (x₀,x₁) ← last_two k.get_app_args, pure (get_operator x₀,some k.get_app_fn.const_name) }, let ns := ns.find_def [] k', ns' ← filter_instances e ns, if e ≠ mono_selection.both then (++) ns' <$> filter_instances mono_selection.both ns else pure ns' end tactic.interactive attribute [mono] add_le_add mul_le_mul neg_le_neg mul_lt_mul_of_pos_left mul_lt_mul_of_pos_right imp_imp_imp le_implies_le_of_le_of_le sub_le_sub abs_le_abs sup_le_sup inf_le_inf attribute [mono left] add_lt_add_of_le_of_lt mul_lt_mul' attribute [mono right] add_lt_add_of_lt_of_le mul_lt_mul
dc2bd45141e18271d46a6988d9cd0408ac836189
fe84e287c662151bb313504482b218a503b972f3
/src/algebra/cdga.lean
2f4ef7e4e265284b5b954fe0cb8837177a8e7ce8
[]
no_license
NeilStrickland/lean_lib
91e163f514b829c42fe75636407138b5c75cba83
6a9563de93748ace509d9db4302db6cd77d8f92c
refs/heads/master
1,653,408,198,261
1,652,996,419,000
1,652,996,419,000
181,006,067
4
1
null
null
null
null
UTF-8
Lean
false
false
2,117
lean
import algebra.ring group_theory.subgroup.basic tactic.ring data.finsupp variables (A : ℤ → Type*) [∀ n, add_comm_group (A n)] def tp {n m : ℤ} (h : n = m) : A n →+ A m := { to_fun := (congr_arg A h).mp, map_zero' := by { cases h, refl }, map_add' := by { cases h, intros, refl } } class dga := (one : A 0) (mul : ∀ {i j : ℤ}, (A i) → (A j) → A (i + j)) (diff : ∀ {i : ℤ}, A i →+ A (i - 1)) (mul_one : ∀ {i : ℤ} (a : A i), mul a one = tp A (add_zero i).symm a) (one_mul : ∀ {i : ℤ} (a : A i), mul one a = tp A (zero_add i).symm a) (mul_assoc : ∀ {i j k : ℤ} (a : A i) (b : A j) (c : A k), mul (mul a b) c = tp A (add_assoc i j k).symm (mul a (mul b c))) (mul_zero : ∀ {i j : ℤ} (a : A i), mul a (0 : (A j)) = 0) (zero_mul : ∀ {i j : ℤ} (b : A j), mul (0 : (A i)) b = 0) (mul_add : ∀ {i j : ℤ} (a : A i) (b c : A j), mul a (b + c) = (mul a b) + (mul a c)) (add_mul : ∀ {i j : ℤ} (a b : A i) (c : A j), mul (a + b) c = (mul a c) + (mul b c)) (diff_mul : ∀ {i j : ℤ} (a : A i) (b : A j), diff (mul a b) = tp A (by ring) (mul (diff a) b) + tp A (by ring) (mul a (diff b))) (diff_diff : ∀ {i : ℤ} (a : A i), diff (diff a) = 0) variable [dga A] variable {A} def dga.diff' {n : ℤ} : A (n + 1) →+ A n := (tp A (by ring_nf)).comp (@dga.diff A _ _ (n + 1)) variable (A) def cycles (n : ℤ) := (dga.diff : A n →+ A (n - 1)).ker def boundaries (n : ℤ) := (dga.diff' : A (n + 1) →+ A n).range def diff_as_cycle {n : ℤ} (a : A n) : cycles A (n - 1) := ⟨dga.diff a,dga.diff.mem_ker.mpr (dga.diff_diff a)⟩ -- def boundaries (n : ℤ) := { a : A n | ∃ } class grading (B : Type*) [add_comm_group B] := (parts : B → finsupp ℤ B) (parts_parts : ∀ (b : B) (i j : ℤ), i ≠ j → parts (parts b i) j = 0) (sum_parts : ∀ (b : B), (parts b).sum (λ n x, x) = b) def tot := Σ (n : ℤ), A n variable {A} def deg : tot A → ℤ := λ x, x.1 variable (A) class dga' := (mul : tot A → tot A → tot A) (deg_mul : ∀ a b, deg (mul a b) = deg a + deg b) (mul_comm : ∀ a b, mul a b = mul b a)
b4b0e9e8e4504ce27743db55a6362d1656bb92fb
7cef822f3b952965621309e88eadf618da0c8ae9
/src/group_theory/congruence.lean
07ee5f7f3bdeace7ab86b3f7067157a92f79724f
[ "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
43,364
lean
/- Copyright (c) 2019 Amelia Livingston. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Amelia Livingston -/ import group_theory.submonoid import data.setoid import algebra.pi_instances /-! # Congruence relations This file defines congruence relations: equivalence relations that preserve a binary operation, which in this case is multiplication or addition. The principal definition is a `structure` extending a `setoid` (an equivalence relation), and the inductive definition of the smallest congruence relation containing a binary relation is also given (see `con_gen`). The file also proves basic properties of the quotient of a type by a congruence relation, and the complete lattice of congruence relations on a type. We then establish an order-preserving bijection between the set of congruence relations containing a congruence relation `c` and the set of congruence relations on the quotient by `c`. The second half of the file concerns congruence relations on monoids, in which case the quotient by the congruence relation is also a monoid. There are results about the universal property of quotients of monoids, and the isomorphism theorems for monoids. ## Implementation notes The inductive definition of a congruence relation could be a nested inductive type, defined using the equivalence closure of a binary relation `eqv_gen`, but the recursor generated does not work. A nested inductive definition could conceivably shorten proofs, because they would allow invocation of the corresponding lemmas about `eqv_gen`. The lemmas `refl`, `symm` and `trans` are not tagged with `@[refl]`, `@[symm]`, and `@[trans]` respectively as these tags do not work on a structure coerced to a binary relation. There is a coercion from elements of a type to the element's equivalence class under a congruence relation. A congruence relation on a monoid `M` can be thought of as a submonoid of `M × M` for which membership is an equivalence relation, but whilst this fact is established in the file, it is not used, since this perspective adds more layers of definitional unfolding. ## Tags congruence, congruence relation, quotient, quotient by congruence relation, monoid, quotient monoid, isomorphism theorems -/ variables (M : Type*) {N : Type*} {P : Type*} set_option old_structure_cmd true open function setoid lattice /-- A congruence relation on a type with an addition is an equivalence relation which preserves addition. -/ structure add_con [has_add M] extends setoid M := (add' : ∀ {w x y z}, r w x → r y z → r (w + y) (x + z)) /-- A congruence relation on a type with a multiplication is an equivalence relation which preserves multiplication. -/ @[to_additive add_con] structure con [has_mul M] extends setoid M := (mul' : ∀ {w x y z}, r w x → r y z → r (w * y) (x * z)) variables {M} /-- The inductively defined smallest additive congruence relation containing a given binary relation. -/ inductive add_con_gen.rel [has_add M] (r : M → M → Prop) : M → M → Prop | of {} : Π x y, r x y → add_con_gen.rel x y | refl {} : Π x, add_con_gen.rel x x | symm {} : Π x y, add_con_gen.rel x y → add_con_gen.rel y x | trans {} : Π x y z, add_con_gen.rel x y → add_con_gen.rel y z → add_con_gen.rel x z | add {} : Π w x y z, add_con_gen.rel w x → add_con_gen.rel y z → add_con_gen.rel (w + y) (x + z) /-- The inductively defined smallest multiplicative congruence relation containing a given binary relation. -/ @[to_additive add_con_gen.rel] inductive con_gen.rel [has_mul M] (r : M → M → Prop) : M → M → Prop | of {} : Π x y, r x y → con_gen.rel x y | refl {} : Π x, con_gen.rel x x | symm {} : Π x y, con_gen.rel x y → con_gen.rel y x | trans {} : Π x y z, con_gen.rel x y → con_gen.rel y z → con_gen.rel x z | mul {} : Π w x y z, con_gen.rel w x → con_gen.rel y z → con_gen.rel (w * y) (x * z) /-- The inductively defined smallest multiplicative congruence relation containing a given binary relation. -/ @[to_additive add_con_gen "The inductively defined smallest additive congruence relation containing a given binary relation."] def con_gen [has_mul M] (r : M → M → Prop) : con M := ⟨con_gen.rel r, ⟨con_gen.rel.refl, con_gen.rel.symm, con_gen.rel.trans⟩, con_gen.rel.mul⟩ namespace con section variables [has_mul M] [has_mul N] [has_mul P] (c : con M) /-- A coercion from a congruence relation to its underlying binary relation. -/ @[to_additive "A coercion from an additive congruence relation to its underlying binary relation."] instance : has_coe_to_fun (con M) := ⟨_, λ c, λ x y, c.r x y⟩ /-- Congruence relations are reflexive. -/ @[to_additive "Additive congruence relations are reflexive."] protected lemma refl (x) : c x x := c.2.1 x /-- Congruence relations are symmetric. -/ @[to_additive "Additive congruence relations are symmetric."] protected lemma symm : ∀ {x y}, c x y → c y x := λ _ _ h, c.2.2.1 h /-- Congruence relations are transitive. -/ @[to_additive "Additive congruence relations are transitive."] protected lemma trans : ∀ {x y z}, c x y → c y z → c x z := λ _ _ _ h, c.2.2.2 h /-- Multiplicative congruence relations preserve multiplication. -/ @[to_additive "Additive congruence relations preserve addition."] protected lemma mul : ∀ {w x y z}, c w x → c y z → c (w * y) (x * z) := λ _ _ _ _ h1 h2, c.3 h1 h2 /-- Given a type `M` with a multiplication, a congruence relation `c` on `M`, and elements of `M` `x, y`, `(x, y) ∈ M × M` iff `x` is related to `y` by `c`. -/ @[to_additive "Given a type `M` with an addition, `x, y ∈ M`, and an additive congruence relation `c` on `M`, `(x, y) ∈ M × M` iff `x` is related to `y` by `c`."] instance : has_mem (M × M) (con M) := ⟨λ x c, c x.1 x.2⟩ variables {c} /-- The map sending a congruence relation to its underlying binary relation is injective. -/ @[to_additive "The map sending an additive congruence relation to its underlying binary relation is injective."] lemma ext' {c d : con M} (H : c.r = d.r) : c = d := by cases c; cases d; simpa using H /-- Extensionality rule for congruence relations. -/ @[ext, to_additive "Extensionality rule for additive congruence relations."] lemma ext {c d : con M} (H : ∀ x y, c x y ↔ d x y) : c = d := ext' $ by ext; apply H attribute [ext] add_con.ext /-- The map sending a congruence relation to its underlying equivalence relation is injective. -/ @[to_additive "The map sending an additive congruence relation to its underlying equivalence relation is injective."] lemma to_setoid_inj {c d : con M} (H : c.to_setoid = d.to_setoid) : c = d := ext $ ext_iff.1 H /-- Iff version of extensionality rule for congruence relations. -/ @[to_additive "Iff version of extensionality rule for additive congruence relations."] lemma ext_iff {c d : con M} : (∀ x y, c x y ↔ d x y) ↔ c = d := ⟨ext, λ h _ _, h ▸ iff.rfl⟩ /-- Two congruence relations are equal iff their underlying binary relations are equal. -/ @[to_additive "Two additive congruence relations are equal iff their underlying binary relations are equal."] lemma ext'_iff {c d : con M} : c.r = d.r ↔ c = d := ⟨ext', λ h, h ▸ rfl⟩ /-- The kernel of a multiplication-preserving function as a congruence relation. -/ @[to_additive "The kernel of an addition-preserving function as an additive congruence relation."] def mul_ker (f : M → P) (h : ∀ x y, f (x * y) = f x * f y) : con M := { r := λ x y, f x = f y, iseqv := ⟨λ _, rfl, λ _ _, eq.symm, λ _ _ _, eq.trans⟩, mul' := λ _ _ _ _ h1 h2, by rw [h, h1, h2, h] } /-- Given types with multiplications `M, N`, the product of two congruence relations `c` on `M` and `d` on `N`: `(x₁, x₂), (y₁, y₂) ∈ M × N` are related by `c.prod d` iff `x₁` is related to `y₁` by `c` and `x₂` is related to `y₂` by `d`. -/ @[to_additive prod "Given types with additions `M, N`, the product of two congruence relations `c` on `M` and `d` on `N`: `(x₁, x₂), (y₁, y₂) ∈ M × N` are related by `c.prod d` iff `x₁` is related to `y₁` by `c` and `x₂` is related to `y₂` by `d`."] protected def prod (c : con M) (d : con N) : con (M × N) := { mul' := λ _ _ _ _ h1 h2, ⟨c.mul h1.1 h2.1, d.mul h1.2 h2.2⟩, ..c.to_setoid.prod d.to_setoid } /-- The product of an indexed collection of congruence relations. -/ @[to_additive "The product of an indexed collection of additive congruence relations."] def pi {ι : Type*} {f : ι → Type*} [Π i, has_mul (f i)] (C : Π i, con (f i)) : con (Π i, f i) := { mul' := λ _ _ _ _ h1 h2 i, (C i).mul (h1 i) (h2 i), ..@pi_setoid _ _ $ λ i, (C i).to_setoid } variables (c) @[simp, to_additive] lemma coe_eq : c.to_setoid.r = c := rfl -- Quotients /-- Defining the quotient by a congruence relation of a type with a multiplication. -/ @[to_additive "Defining the quotient by an additive congruence relation of a type with an addition."] protected def quotient := quotient $ c.to_setoid /-- Coercion from a type with a multiplication to its quotient by a congruence relation. -/ @[to_additive "Coercion from a type with an addition to its quotient by an additive congruence relation", priority 0] instance : has_coe M c.quotient := ⟨@quotient.mk _ c.to_setoid⟩ /-- The quotient of a type with decidable equality by a congruence relation also has decidable equality. -/ @[to_additive "The quotient of a type with decidable equality by an additive congruence relation also has decidable equality."] instance [d : ∀ a b, decidable (c a b)] : decidable_eq c.quotient := @quotient.decidable_eq M c.to_setoid d /-- The function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes. -/ @[elab_as_eliminator, to_additive "The function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes."] protected def lift_on {β} {c : con M} (q : c.quotient) (f : M → β) (h : ∀ a b, c a b → f a = f b) : β := quotient.lift_on' q f h variables {c} /-- The inductive principle used to prove propositions about the elements of a quotient by a congruence relation. -/ @[elab_as_eliminator, to_additive "The inductive principle used to prove propositions about the elements of a quotient by an additive congruence relation."] protected lemma induction_on {C : c.quotient → Prop} (q : c.quotient) (H : ∀ x : M, C x) : C q := quotient.induction_on' q H /-- A version of `con.induction_on` for predicates which take two arguments. -/ @[elab_as_eliminator, to_additive "A version of `add_con.induction_on` for predicates which take two arguments."] protected lemma induction_on₂ {d : con N} {C : c.quotient → d.quotient → Prop} (p : c.quotient) (q : d.quotient) (H : ∀ (x : M) (y : N), C x y) : C p q := quotient.induction_on₂' p q H variables (c) /-- Two elements are related by a congruence relation `c` iff they are represented by the same element of the quotient by `c`. -/ @[simp, to_additive "Two elements are related by an additive congruence relation `c` iff they are represented by the same element of the quotient by `c`."] protected lemma eq {a b : M} : (a : c.quotient) = b ↔ c a b := quotient.eq' /-- The multiplication induced on the quotient by a congruence relation on a type with a multiplication. -/ @[to_additive "The addition induced on the quotient by an additive congruence relation on a type with a addition."] instance has_mul : has_mul c.quotient := ⟨λ x y, quotient.lift_on₂' x y (λ w z, ((w * z : M) : c.quotient)) $ λ _ _ _ _ h1 h2, c.eq.2 $ c.mul h1 h2⟩ /-- The kernel of the quotient map induced by a congruence relation `c` equals `c`. -/ @[simp, to_additive "The kernel of the quotient map induced by an additive congruence relation `c` equals `c`."] lemma mul_ker_mk_eq : mul_ker (coe : M → c.quotient) (λ x y, rfl) = c := ext $ λ x y, quotient.eq' variables {c} /-- The coercion to the quotient of a congruence relation commutes with multiplication (by definition). -/ @[simp, to_additive "The coercion to the quotient of an additive congruence relation commutes with addition (by definition)."] lemma coe_mul (x y : M) : (↑(x * y) : c.quotient) = ↑x * ↑y := rfl /-- Definition of the function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes. -/ @[simp, to_additive "Definition of the function on the quotient by an additive congruence relation `c` induced by a function that is constant on `c`'s equivalence classes."] protected lemma lift_on_beta {β} (c : con M) (f : M → β) (h : ∀ a b, c a b → f a = f b) (x : M) : con.lift_on (x : c.quotient) f h = f x := rfl /-- Makes an isomorphism of quotients by two congruence relations, given that the relations are equal. -/ @[to_additive "Makes an additive isomorphism of quotients by two additive congruence relations, given that the relations are equal."] protected def congr {c d : con M} (h : c = d) : c.quotient ≃* d.quotient := { map_mul' := λ x y, by rcases x; rcases y; refl, ..quotient.congr (equiv.refl M) $ by apply ext_iff.2 h } -- The complete lattice of congruence relations on a type /-- For congruence relations `c, d` on a type `M` with a multiplication, `c ≤ d` iff `∀ x y ∈ M`, `x` is related to `y` by `d` if `x` is related to `y` by `c`. -/ @[to_additive "For additive congruence relations `c, d` on a type `M` with an addition, `c ≤ d` iff `∀ x y ∈ M`, `x` is related to `y` by `d` if `x` is related to `y` by `c`."] instance : has_le (con M) := ⟨λ c d, c.to_setoid ≤ d.to_setoid⟩ /-- Definition of `≤` for congruence relations. -/ @[to_additive "Definition of `≤` for additive congruence relations."] theorem le_def {c d : con M} : c ≤ d ↔ ∀ {x y}, c x y → d x y := iff.rfl /-- The infimum of a set of congruence relations on a given type with a multiplication. -/ @[to_additive "The infimum of a set of additive congruence relations on a given type with an addition."] instance : has_Inf (con M) := ⟨λ S, ⟨λ x y, ∀ c : con M, c ∈ S → c x y, ⟨λ x c hc, c.refl x, λ _ _ h c hc, c.symm $ h c hc, λ _ _ _ h1 h2 c hc, c.trans (h1 c hc) $ h2 c hc⟩, λ _ _ _ _ h1 h2 c hc, c.mul (h1 c hc) $ h2 c hc⟩⟩ /-- The infimum of a set of congruence relations is the same as the infimum of the set's image under the map to the underlying equivalence relation. -/ @[to_additive "The infimum of a set of additive congruence relations is the same as the infimum of the set's image under the map to the underlying equivalence relation."] lemma Inf_to_setoid (S : set (con M)) : (Inf S).to_setoid = Inf (to_setoid '' S) := setoid.ext' $ λ x y, ⟨λ h r ⟨c, hS, hr⟩, by rw ←hr; exact h c hS, λ h c hS, h c.to_setoid ⟨c, hS, rfl⟩⟩ /-- The infimum of a set of congruence relations is the same as the infimum of the set's image under the map to the underlying binary relation. -/ @[to_additive "The infimum of a set of additive congruence relations is the same as the infimum of the set's image under the map to the underlying binary relation."] lemma Inf_def (S : set (con M)) : (Inf S).r = Inf (r '' S) := by { ext, simp only [Inf_image, infi_apply, infi_Prop_eq], refl } /-- If a congruence relation `c` is contained in every element of a set `s` of congruence relations on the same type, `c` is contained in the infimum of `s`. -/ @[to_additive "If an additive congruence relation `c` is contained in every element of a set `s` of additive congruence relations on the same type, `c` is contained in the infimum of `s`."] lemma le_Inf (s : set (con M)) (c) : (∀d ∈ s, c ≤ d) → c ≤ Inf s := λ h _ _ hc r hr, h r hr _ _ hc /-- The infimum of a set of congruence relations on a given type is contained in every element of the set. -/ @[to_additive "The infimum of a set of additive congruence relations on a given type is contained in every element of the set."] lemma Inf_le (s : set (con M)) (c) : c ∈ s → Inf s ≤ c := λ hc _ _ h, h c hc /-- The complete lattice of congruence relations on a given type with a multiplication. -/ @[to_additive "The complete lattice of additive congruence relations on a given type with an addition."] instance : complete_lattice (con M) := { sup := λ c d, Inf { x | c ≤ x ∧ d ≤ x}, le := (≤), lt := λ c d, c ≤ d ∧ ¬d ≤ c, le_refl := λ c _ _, id, le_trans := λ c1 c2 c3 h1 h2 x y h, h2 x y $ h1 x y h, lt_iff_le_not_le := λ _ _, iff.rfl, le_antisymm := λ c d hc hd, ext $ λ x y, ⟨hc x y, hd x y⟩, le_sup_left := λ _ _ _ _ h r hr, hr.1 _ _ h, le_sup_right := λ _ _ _ _ h r hr, hr.2 _ _ h, sup_le := λ _ _ c h1 h2, Inf_le _ c ⟨h1, h2⟩, inf := λ c d, ⟨(c.to_setoid ⊓ d.to_setoid).1, (c.to_setoid ⊓ d.to_setoid).2, λ _ _ _ _ h1 h2, ⟨c.mul h1.1 h2.1, d.mul h1.2 h2.2⟩⟩, inf_le_left := λ _ _ _ _ h, h.1, inf_le_right := λ _ _ _ _ h, h.2, le_inf := λ _ _ _ hb hc _ _ h, ⟨hb _ _ h, hc _ _ h⟩, top := { mul' := by tauto, ..setoid.complete_lattice.top}, le_top := λ _ _ _ h, trivial, bot := { mul' := λ _ _ _ _ h1 h2, h1 ▸ h2 ▸ rfl, ..setoid.complete_lattice.bot}, bot_le := λ c x y h, h ▸ c.refl x, Sup := λ tt, Inf {t | ∀t'∈tt, t' ≤ t}, Inf := has_Inf.Inf, le_Sup := λ _ _ hs, le_Inf _ _ $ λ c' hc', hc' _ hs, Sup_le := λ _ _ hs, Inf_le _ _ hs, Inf_le := λ _ _, Inf_le _ _, le_Inf := λ _ _, le_Inf _ _ } /-- The infimum of two congruence relations equals the infimum of the underlying binary operations. -/ @[to_additive "The infimum of two additive congruence relations equals the infimum of the underlying binary operations."] lemma inf_def {c d : con M} : (c ⊓ d).r = c.r ⊓ d.r := rfl /-- Definition of the infimum of two congruence relations. -/ @[to_additive "Definition of the infimum of two additive congruence relations."] theorem inf_iff_and {c d : con M} {x y} : (c ⊓ d) x y ↔ c x y ∧ d x y := iff.rfl /-- The inductively defined smallest congruence relation containing a binary relation `r` equals the infimum of the set of congruence relations containing `r`. -/ @[to_additive add_con_gen_eq "The inductively defined smallest additive congruence relation containing a binary relation `r` equals the infimum of the set of additive congruence relations containing `r`."] theorem con_gen_eq (r : M → M → Prop) : con_gen r = Inf {s : con M | ∀ x y, r x y → s.r x y} := ext $ λ x y, ⟨λ H, con_gen.rel.rec_on H (λ _ _ h _ hs, hs _ _ h) (con.refl _) (λ _ _ _, con.symm _) (λ _ _ _ _ _, con.trans _) $ λ w x y z _ _ h1 h2 c hc, c.mul (h1 c hc) $ h2 c hc, Inf_le _ _ (λ _ _, con_gen.rel.of _ _) _ _⟩ /-- The smallest congruence relation containing a binary relation `r` is contained in any congruence relation containing `r`. -/ @[to_additive add_con_gen_le "The smallest additive congruence relation containing a binary relation `r` is contained in any additive congruence relation containing `r`."] theorem con_gen_le {r : M → M → Prop} {c : con M} (h : ∀ x y, r x y → c.r x y) : con_gen r ≤ c := by rw con_gen_eq; exact Inf_le _ _ h /-- Given binary relations `r, s` with `r` contained in `s`, the smallest congruence relation containing `s` contains the smallest congruence relation containing `r`. -/ @[to_additive add_con_gen_mono "Given binary relations `r, s` with `r` contained in `s`, the smallest additive congruence relation containing `s` contains the smallest additive congruence relation containing `r`."] theorem con_gen_mono {r s : M → M → Prop} (h : ∀ x y, r x y → s x y) : con_gen r ≤ con_gen s := con_gen_le $ λ x y hr, con_gen.rel.of _ _ $ h x y hr /-- Congruence relations equal the smallest congruence relation in which they are contained. -/ @[simp, to_additive add_con_gen_of_add_con "Additive congruence relations equal the smallest additive congruence relation in which they are contained."] lemma con_gen_of_con (c : con M) : con_gen c.r = c := le_antisymm (by rw con_gen_eq; exact Inf_le _ c (λ _ _, id)) con_gen.rel.of /-- The map sending a binary relation to the smallest congruence relation in which it is contained is idempotent. -/ @[simp, to_additive add_con_gen_idem "The map sending a binary relation to the smallest additive congruence relation in which it is contained is idempotent."] lemma con_gen_idem (r : M → M → Prop) : con_gen (con_gen r).r = con_gen r := con_gen_of_con _ /-- The supremum of congruence relations `c, d` equals the smallest congruence relation containing the binary relation '`x` is related to `y` by `c` or `d`'. -/ @[to_additive sup_eq_add_con_gen "The supremum of additive congruence relations `c, d` equals the smallest additive congruence relation containing the binary relation '`x` is related to `y` by `c` or `d`'."] lemma sup_eq_con_gen (c d : con M) : c ⊔ d = con_gen (λ x y, c x y ∨ d x y) := begin rw con_gen_eq, apply congr_arg Inf, ext, exact ⟨λ h _ _ H, or.elim H (h.1 _ _) (h.2 _ _), λ H, ⟨λ _ _ h, H _ _ $ or.inl h, λ _ _ h, H _ _ $ or.inr h⟩⟩, end /-- The supremum of two congruence relations equals the smallest congruence relation containing the supremum of the underlying binary operations. -/ @[to_additive "The supremum of two additive congruence relations equals the smallest additive congruence relation containing the supremum of the underlying binary operations."] lemma sup_def {c d : con M} : c ⊔ d = con_gen (c.r ⊔ d.r) := by rw sup_eq_con_gen; refl /-- The supremum of a set of congruence relations `S` equals the smallest congruence relation containing the binary relation 'there exists `c ∈ S` such that `x` is related to `y` by `c`'. -/ @[to_additive Sup_eq_add_con_gen "The supremum of a set of additive congruence relations S equals the smallest additive congruence relation containing the binary relation 'there exists `c ∈ S` such that `x` is related to `y` by `c`'."] lemma Sup_eq_con_gen (S : set (con M)) : Sup S = con_gen (λ x y, ∃ c : con M, c ∈ S ∧ c x y) := begin rw con_gen_eq, apply congr_arg Inf, ext, exact ⟨λ h _ _ ⟨r, hr⟩, h r hr.1 _ _ hr.2, λ h r hS _ _ hr, h _ _ ⟨r, hS, hr⟩⟩, end /-- The supremum of a set of congruence relations is the same as the smallest congruence relation containing the supremum of the set's image under the map to the underlying binary relation. -/ @[to_additive "The supremum of a set of additive congruence relations is the same as the smallest additive congruence relation containing the supremum of the set's image under the map to the underlying binary relation."] lemma Sup_def {S : set (con M)} : Sup S = con_gen (Sup (r '' S)) := begin rw Sup_eq_con_gen, congr, ext x y, erw [Sup_image, supr_apply, supr_apply, supr_Prop_eq], simp only [Sup_image, supr_Prop_eq, supr_apply, supr_Prop_eq, exists_prop], refl, end variables (M) /-- There is a Galois insertion of congruence relations on a type with a multiplication `M` into binary relations on `M`. -/ @[to_additive "There is a Galois insertion of additive congruence relations on a type with an addition `M` into binary relations on `M`."] protected def gi : @galois_insertion (M → M → Prop) (con M) _ _ con_gen r := { choice := λ r h, con_gen r, gc := λ r c, ⟨λ H _ _ h, H _ _ $ con_gen.rel.of _ _ h, λ H, con_gen_of_con c ▸ con_gen_mono H⟩, le_l_u := λ x, (con_gen_of_con x).symm ▸ le_refl x, choice_eq := λ _ _, rfl } variables {M} (c) /-- Given a function `f`, the smallest congruence relation containing the binary relation on `f`'s image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by a congruence relation `c`.' -/ @[to_additive "Given a function `f`, the smallest additive congruence relation containing the binary relation on `f`'s image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by an additive congruence relation `c`.'"] def map_gen (f : M → N) : con N := con_gen $ λ x y, ∃ a b, f a = x ∧ f b = y ∧ c a b /-- Given a surjective multiplicative-preserving function `f` whose kernel is contained in a congruence relation `c`, the congruence relation on `f`'s codomain defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by `c`.' -/ @[to_additive "Given a surjective addition-preserving function `f` whose kernel is contained in an additive congruence relation `c`, the additive congruence relation on `f`'s codomain defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by `c`.'"] def map_of_surjective (f : M → N) (H : ∀ x y, f (x * y) = f x * f y) (h : mul_ker f H ≤ c) (hf : surjective f) : con N := { mul' := λ w x y z ⟨a, b, hw, hx, h1⟩ ⟨p, q, hy, hz, h2⟩, ⟨a * p, b * q, by rw [H, hw, hy], by rw [H, hx, hz], c.mul h1 h2⟩, ..c.to_setoid.map_of_surjective f h hf } /-- A specialization of 'the smallest congruence relation containing a congruence relation `c` equals `c`'. -/ @[to_additive "A specialization of 'the smallest additive congruence relation containing an additive congruence relation `c` equals `c`'."] lemma map_of_surjective_eq_map_gen {c : con M} {f : M → N} (H : ∀ x y, f (x * y) = f x * f y) (h : mul_ker f H ≤ c) (hf : surjective f) : c.map_gen f = c.map_of_surjective f H h hf := by rw ←con_gen_of_con (c.map_of_surjective f H h hf); refl /-- Given types with multiplications `M, N` and a congruence relation `c` on `N`, a multiplication-preserving map `f : M → N` induces a congruence relation on `f`'s domain defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `c`.' -/ @[to_additive "Given types with additions `M, N` and an additive congruence relation `c` on `N`, an addition-preserving map `f : M → N` induces an additive congruence relation on `f`'s domain defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `c`.' "] def comap (f : M → N) (H : ∀ x y, f (x * y) = f x * f y) (c : con N) : con M := { mul' := λ w x y z h1 h2, show c (f (w * y)) (f (x * z)), by rw [H, H]; exact c.mul h1 h2, ..c.to_setoid.comap f } section open quotient /-- Given a congruence relation `c` on a type `M` with a multiplication, the order-preserving bijection between the set of congruence relations containing `c` and the congruence relations on the quotient of `M` by `c`. -/ @[to_additive "Given an additive congruence relation `c` on a type `M` with an addition, the order-preserving bijection between the set of additive congruence relations containing `c` and the additive congruence relations on the quotient of `M` by `c`."] def correspondence : ((≤) : {d // c ≤ d} → {d // c ≤ d} → Prop) ≃o ((≤) : con c.quotient → con c.quotient → Prop) := { to_fun := λ d, d.1.map_of_surjective coe _ (by rw mul_ker_mk_eq; exact d.2) $ @exists_rep _ c.to_setoid, inv_fun := λ d, ⟨comap (coe : M → c.quotient) (λ x y, rfl) d, λ _ _ h, show d _ _, by rw c.eq.2 h; exact d.refl _ ⟩, left_inv := λ d, subtype.ext.2 $ ext $ λ _ _, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in d.1.trans (d.1.symm $ d.2 a _ $ c.eq.1 hx) $ d.1.trans H $ d.2 b _ $ c.eq.1 hy, λ h, ⟨_, _, rfl, rfl, h⟩⟩, right_inv := λ d, let Hm : mul_ker (coe : M → c.quotient) (λ x y, rfl) ≤ comap (coe : M → c.quotient) (λ x y, rfl) d := λ x y h, show d _ _, by rw mul_ker_mk_eq at h; exact c.eq.2 h ▸ d.refl _ in ext $ λ x y, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in hx ▸ hy ▸ H, con.induction_on₂ x y $ λ w z h, ⟨w, z, rfl, rfl, h⟩⟩, ord := λ s t, ⟨λ h _ _ hs, let ⟨a, b, hx, hy, Hs⟩ := hs in ⟨a, b, hx, hy, h _ _ Hs⟩, λ h _ _ hs, let ⟨a, b, hx, hy, ht⟩ := h _ _ ⟨_, _, rfl, rfl, hs⟩ in t.1.trans (t.1.symm $ t.2 a _ $ eq_rel.1 hx) $ t.1.trans ht $ t.2 b _ $ eq_rel.1 hy⟩ } end end -- Monoids variables {M} [monoid M] [monoid N] [monoid P] (c : con M) /-- The quotient of a monoid by a congruence relation is a monoid. -/ @[to_additive add_monoid "The quotient of an `add_monoid` by an additive congruence relation is an `add_monoid`."] instance monoid : monoid c.quotient := { one := ((1 : M) : c.quotient), mul := (*), mul_assoc := λ x y z, quotient.induction_on₃' x y z $ λ _ _ _, congr_arg coe $ mul_assoc _ _ _, mul_one := λ x, quotient.induction_on' x $ λ _, congr_arg coe $ mul_one _, one_mul := λ x, quotient.induction_on' x $ λ _, congr_arg coe $ one_mul _ } /-- The quotient of a `comm_monoid` by a congruence relation is a `comm_monoid`. -/ @[to_additive add_comm_monoid "The quotient of an `add_comm_monoid` by an additive congruence relation is an `add_comm_monoid`."] instance comm_monoid {α : Type*} [comm_monoid α] (c : con α) : comm_monoid c.quotient := { mul_comm := λ x y, con.induction_on₂ x y $ λ w z, by rw [←coe_mul, ←coe_mul, mul_comm], ..c.monoid} variables {c} /-- The 1 of the quotient of a monoid by a congruence relation is the equivalence class of the monoid's 1. -/ @[simp, to_additive "The 0 of the quotient of an `add_monoid` by an additive congruence relation is the equivalence class of the `add_monoid`'s 0."] lemma coe_one : ((1 : M) : c.quotient) = 1 := rfl variables (M c) /-- The submonoid of `M × M` defined by a congruence relation on a monoid `M`. -/ @[to_additive add_submonoid "The `add_submonoid` of `M × M` defined by an additive congruence relation on an `add_monoid` `M`."] protected def submonoid : submonoid (M × M) := { carrier := { x | c x.1 x.2 }, one_mem' := c.iseqv.1 1, mul_mem' := λ _ _, c.mul } variables {M c} /-- The congruence relation on a monoid `M` from a submonoid of `M × M` for which membership is an equivalence relation. -/ @[to_additive of_add_submonoid "The additive congruence relation on an `add_monoid` `M` from an `add_submonoid` of `M × M` for which membership is an equivalence relation."] def of_submonoid (N : submonoid (M × M)) (H : equivalence (λ x y, (x, y) ∈ N)) : con M := { r := λ x y, (x, y) ∈ N, iseqv := H, mul' := λ _ _ _ _, N.mul_mem } /-- Coercion from a congruence relation `c` on a monoid `M` to the submonoid of `M × M` whose elements are `(x, y)` such that `x` is related to `y` by `c`. -/ @[to_additive to_add_submonoid "Coercion from a congruence relation `c` on an `add_monoid` `M` to the `add_submonoid` of `M × M` whose elements are `(x, y)` such that `x` is related to `y` by `c`."] instance to_submonoid : has_coe (con M) (submonoid (M × M)) := ⟨λ c, c.submonoid M⟩ @[to_additive] lemma mem_coe {c : con M} {x y} : (x, y) ∈ (↑c : submonoid (M × M)) ↔ (x, y) ∈ c := iff.rfl @[to_additive to_add_submonoid_inj] theorem to_submonoid_inj (c d : con M) (H : (c : submonoid (M × M)) = d) : c = d := ext $ λ x y, show (x, y) ∈ (c : submonoid (M × M)) ↔ (x, y) ∈ ↑d, by rw H @[to_additive] lemma le_iff {c d : con M} : c ≤ d ↔ (c : submonoid (M × M)) ≤ d := ⟨λ h x, h x.1 x.2, λ h x y hc, h $ show (x, y) ∈ c, from hc⟩ /-- The kernel of a monoid homomorphism as a congruence relation. -/ @[to_additive "The kernel of an `add_monoid` homomorphism as an additive congruence relation."] def ker (f : M →* P) : con M := mul_ker f f.3 /-- The definition of the congruence relation defined by a monoid homomorphism's kernel. -/ @[to_additive "The definition of the additive congruence relation defined by an `add_monoid` homomorphism's kernel."] lemma ker_rel (f : M →* P) {x y} : ker f x y ↔ f x = f y := iff.rfl /-- There exists an element of the quotient of a monoid by a congruence relation (namely 1). -/ @[to_additive "There exists an element of the quotient of an `add_monoid` by a congruence relation (namely 0)."] instance : inhabited c.quotient := ⟨((1 : M) : c.quotient)⟩ variables (c) /-- The natural homomorphism from a monoid to its quotient by a congruence relation. -/ @[to_additive "The natural homomorphism from an `add_monoid` to its quotient by an additive congruence relation."] def mk' : M →* c.quotient := ⟨coe, rfl, λ _ _, rfl⟩ variables (x y : M) /-- The kernel of the natural homomorphism from a monoid to its quotient by a congruence relation `c` equals `c`. -/ @[simp, to_additive "The kernel of the natural homomorphism from an `add_monoid` to its quotient by an additive congruence relation `c` equals `c`."] lemma mk'_ker : ker c.mk' = c := ext $ λ _ _, c.eq variables {c} /-- The natural homomorphism from a monoid to its quotient by a congruence relation is surjective. -/ @[to_additive "The natural homomorphism from an `add_monoid` to its quotient by a congruence relation is surjective."] lemma mk'_surjective : surjective c.mk' := λ x, by rcases x; exact ⟨x, rfl⟩ @[simp, to_additive] lemma comp_mk'_apply (g : c.quotient →* P) {x} : g.comp c.mk' x = g x := rfl /-- The elements related to `x ∈ M`, `M` a monoid, by the kernel of a monoid homomorphism are those in the preimage of `f(x)` under `f`. -/ @[to_additive "The elements related to `x ∈ M`, `M` an `add_monoid`, by the kernel of an `add_monoid` homomorphism are those in the preimage of `f(x)` under `f`. "] lemma ker_apply_eq_preimage {f : M →* P} (x) : (ker f) x = f ⁻¹' {f x} := set.ext $ λ x, ⟨λ h, set.mem_preimage.2 $ set.mem_singleton_iff.2 h.symm, λ h, (set.mem_singleton_iff.1 $ set.mem_preimage.1 h).symm⟩ /-- Given a monoid homomorphism `f : N → M` and a congruence relation `c` on `M`, the congruence relation induced on `N` by `f` equals the kernel of `c`'s quotient homomorphism composed with `f`. -/ @[to_additive "Given an `add_monoid` homomorphism `f : N → M` and an additive congruence relation `c` on `M`, the additive congruence relation induced on `N` by `f` equals the kernel of `c`'s quotient homomorphism composed with `f`."] lemma comap_eq {f : N →* M} : comap f f.map_mul c = ker (c.mk'.comp f) := ext $ λ x y, show c _ _ ↔ c.mk' _ = c.mk' _, by rw ←c.eq; refl variables (c) (f : M →* P) /-- The homomorphism on the quotient of a monoid by a congruence relation `c` induced by a homomorphism constant on `c`'s equivalence classes. -/ @[to_additive "The homomorphism on the quotient of an `add_monoid` by an additive congruence relation `c` induced by a homomorphism constant on `c`'s equivalence classes."] def lift (H : c ≤ ker f) : c.quotient →* P := { to_fun := λ x, con.lift_on x f $ λ _ _, H _ _, map_one' := by rw ←f.map_one; refl, map_mul' := λ x y, con.induction_on₂ x y $ λ m n, f.map_mul m n ▸ rfl } variables {c f} /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] lemma lift_mk' (H : c ≤ ker f) (x) : c.lift f H (c.mk' x) = f x := rfl /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] lemma lift_coe (H : c ≤ ker f) (x : M) : c.lift f H x = f x := rfl /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] theorem lift_comp_mk' (H : c ≤ ker f) : (c.lift f H).comp c.mk' = f := by ext; refl /-- Given a homomorphism `f` from the quotient of a monoid by a congruence relation, `f` equals the homomorphism on the quotient induced by `f` composed with the natural map from the monoid to the quotient. -/ @[simp, to_additive "Given a homomorphism `f` from the quotient of an `add_monoid` by an additive congruence relation, `f` equals the homomorphism on the quotient induced by `f` composed with the natural map from the `add_monoid` to the quotient."] lemma lift_apply_mk' (f : c.quotient →* P) : c.lift (f.comp c.mk') (λ x y h, show f ↑x = f ↑y, by rw c.eq.2 h) = f := by ext; rcases x; refl /-- Homomorphisms on the quotient of a monoid by a congruence relation are equal if they are equal on elements that are coercions from the monoid. -/ @[to_additive "Homomorphisms on the quotient of an `add_monoid` by an additive congruence relation are equal if they are equal on elements that are coercions from the `add_monoid`."] lemma lift_funext (f g : c.quotient →* P) (h : ∀ a : M, f a = g a) : f = g := begin rw [←lift_apply_mk' f, ←lift_apply_mk' g], congr' 1, exact monoid_hom.ext_iff.2 h, end /-- The uniqueness part of the universal property for quotients of monoids. -/ @[to_additive "The uniqueness part of the universal property for quotients of `add_monoid`s."] theorem lift_unique (H : c ≤ ker f) (g : c.quotient →* P) (Hg : g.comp c.mk' = f) : g = c.lift f H := lift_funext g (c.lift f H) $ λ x, by rw [lift_coe H, ←comp_mk'_apply, Hg] /-- Given a congruence relation `c` on a monoid and a homomorphism `f` constant on `c`'s equivalence classes, `f` has the same image as the homomorphism that `f` induces on the quotient. -/ @[to_additive "Given an additive congruence relation `c` on an `add_monoid` and a homomorphism `f` constant on `c`'s equivalence classes, `f` has the same image as the homomorphism that `f` induces on the quotient."] theorem lift_range (H : c ≤ ker f) : (c.lift f H).range = f.range := submonoid.ext $ λ x, ⟨λ ⟨y, hy⟩, by revert hy; rcases y; exact λ hy, ⟨y, hy.1, by rw [hy.2.symm, ←lift_coe H]; refl⟩, λ ⟨y, hy⟩, ⟨↑y, hy.1, by rw ←hy.2; refl⟩⟩ /-- Surjective monoid homomorphisms constant on a congruence relation `c`'s equivalence classes induce a surjective homomorphism on `c`'s quotient. -/ @[to_additive "Surjective `add_monoid` homomorphisms constant on an additive congruence relation `c`'s equivalence classes induce a surjective homomorphism on `c`'s quotient."] lemma lift_surjective_of_surjective (h : c ≤ ker f) (hf : surjective f) : surjective (c.lift f h) := λ y, exists.elim (hf y) $ λ w hw, ⟨w, (lift_mk' h w).symm ▸ hw⟩ variables (c f) /-- Given a monoid homomorphism `f` from `M` to `P`, the kernel of `f` is the unique congruence relation on `M` whose induced map from the quotient of `M` to `P` is injective. -/ @[to_additive "Given an `add_monoid` homomorphism `f` from `M` to `P`, the kernel of `f` is the unique additive congruence relation on `M` whose induced map from the quotient of `M` to `P` is injective."] lemma ker_eq_lift_of_injective (H : c ≤ ker f) (h : injective (c.lift f H)) : ker f = c := to_setoid_inj $ ker_eq_lift_of_injective f H h variables {c} /-- The homomorphism induced on the quotient of a monoid by the kernel of a monoid homomorphism. -/ @[to_additive "The homomorphism induced on the quotient of an `add_monoid` by the kernel of an `add_monoid` homomorphism."] def ker_lift : (ker f).quotient →* P := (ker f).lift f $ λ _ _, id variables {f} /-- The diagram described by the universal property for quotients of monoids, when the congruence relation is the kernel of the homomorphism, commutes. -/ @[simp, to_additive "The diagram described by the universal property for quotients of `add_monoid`s, when the additive congruence relation is the kernel of the homomorphism, commutes."] lemma ker_lift_mk (x : M) : ker_lift f x = f x := rfl /-- Given a monoid homomorphism `f`, the induced homomorphism on the quotient by `f`'s kernel has the same image as `f`. -/ @[simp, to_additive "Given an `add_monoid` homomorphism `f`, the induced homomorphism on the quotient by `f`'s kernel has the same image as `f`."] lemma ker_lift_range_eq : (ker_lift f).range = f.range := lift_range $ λ _ _, id /-- A monoid homomorphism `f` induces an injective homomorphism on the quotient by `f`'s kernel. -/ @[to_additive "An `add_monoid` homomorphism `f` induces an injective homomorphism on the quotient by `f`'s kernel."] lemma injective_ker_lift (f : M →* P) : injective (ker_lift f) := λ x y, quotient.induction_on₂' x y $ λ _ _, (ker f).eq.2 /-- Given congruence relations `c, d` on a monoid such that `d` contains `c`, `d`'s quotient map induces a homomorphism from the quotient by `c` to the quotient by `d`. -/ @[to_additive "Given additive congruence relations `c, d` on an `add_monoid` such that `d` contains `c`, `d`'s quotient map induces a homomorphism from the quotient by `c` to the quotient by `d`."] def map (c d : con M) (h : c ≤ d) : c.quotient →* d.quotient := c.lift d.mk' $ λ x y hc, show (ker d.mk') x y, from (mk'_ker d).symm ▸ h x y hc /-- Given congruence relations `c, d` on a monoid such that `d` contains `c`, the definition of the homomorphism from the quotient by `c` to the quotient by `d` induced by `d`'s quotient map. -/ @[to_additive "Given additive congruence relations `c, d` on an `add_monoid` such that `d` contains `c`, the definition of the homomorphism from the quotient by `c` to the quotient by `d` induced by `d`'s quotient map."] lemma map_apply {c d : con M} (h : c ≤ d) (x) : c.map d h x = c.lift d.mk' (λ x y hc, d.eq.2 $ h x y hc) x := rfl variables (c) /-- The first isomorphism theorem for monoids. -/ @[to_additive "The first isomorphism theorem for `add_monoid`s."] noncomputable def quotient_ker_equiv_range (f : M →* P) : (ker f).quotient ≃* f.range := { map_mul' := monoid_hom.map_mul _, ..@equiv.of_bijective _ _ ((@mul_equiv.to_monoid_hom (ker_lift f).range _ _ _ $ mul_equiv.submonoid_congr ker_lift_range_eq).comp (ker_lift f).range_mk) $ bijective_comp (equiv.bijective _) ⟨λ x y h, injective_ker_lift f $ by rcases x; rcases y; injections, λ ⟨w, z, hzm, hz⟩, ⟨z, by rcases hz; rcases _x; refl⟩⟩ } /-- The first isomorphism theorem for monoids in the case of a surjective homomorphism. -/ @[to_additive "The first isomorphism theorem for `add_monoid`s in the case of a surjective homomorphism."] noncomputable def quotient_ker_equiv_of_surjective (f : M →* P) (hf : surjective f) : (ker f).quotient ≃* P := { map_mul' := monoid_hom.map_mul _, ..@equiv.of_bijective _ _ (ker_lift f) ⟨injective_ker_lift f, lift_surjective_of_surjective (le_refl _) hf⟩ } /-- The second isomorphism theorem for monoids. -/ @[to_additive "The second isomorphism theorem for `add_monoid`s."] noncomputable def comap_quotient_equiv (f : N →* M) : (comap f f.map_mul c).quotient ≃* (c.mk'.comp f).range := (con.congr comap_eq).trans $ quotient_ker_equiv_range $ c.mk'.comp f /-- The third isomorphism theorem for monoids. -/ @[to_additive "The third isomorphism theorem for `add_monoid`s."] def quotient_quotient_equiv_quotient (c d : con M) (h : c ≤ d) : (ker (c.map d h)).quotient ≃* d.quotient := { map_mul' := λ x y, con.induction_on₂ x y $ λ w z, con.induction_on₂ w z $ λ a b, show _ = d.mk' a * d.mk' b, by rw ←d.mk'.map_mul; refl, ..quotient_quotient_equiv_quotient _ _ h } end con
7fa410175153f85c670b42ae52cc4f9b381fcd31
9dc8cecdf3c4634764a18254e94d43da07142918
/src/measure_theory/measure/ae_measurable.lean
99b01758f417e082b525db9ca592df49e89c8d6d
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
15,104
lean
/- Copyright (c) 2021 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import measure_theory.measure.measure_space /-! # Almost everywhere measurable functions A function is almost everywhere measurable if it coincides almost everywhere with a measurable function. This property, called `ae_measurable f μ`, is defined in the file `measure_space_def`. We discuss several of its properties that are analogous to properties of measurable functions. -/ open measure_theory measure_theory.measure filter set function open_locale measure_theory filter classical ennreal interval variables {ι α β γ δ R : Type*} {m0 : measurable_space α} [measurable_space β] [measurable_space γ] [measurable_space δ] {f g : α → β} {μ ν : measure α} include m0 section @[nontriviality, measurability] lemma subsingleton.ae_measurable [subsingleton α] : ae_measurable f μ := subsingleton.measurable.ae_measurable @[nontriviality, measurability] lemma ae_measurable_of_subsingleton_codomain [subsingleton β] : ae_measurable f μ := (measurable_of_subsingleton_codomain f).ae_measurable @[simp, measurability] lemma ae_measurable_zero_measure : ae_measurable f (0 : measure α) := begin nontriviality α, inhabit α, exact ⟨λ x, f default, measurable_const, rfl⟩ end namespace ae_measurable lemma mono_measure (h : ae_measurable f μ) (h' : ν ≤ μ) : ae_measurable f ν := ⟨h.mk f, h.measurable_mk, eventually.filter_mono (ae_mono h') h.ae_eq_mk⟩ lemma mono_set {s t} (h : s ⊆ t) (ht : ae_measurable f (μ.restrict t)) : ae_measurable f (μ.restrict s) := ht.mono_measure (restrict_mono h le_rfl) protected lemma mono' (h : ae_measurable f μ) (h' : ν ≪ μ) : ae_measurable f ν := ⟨h.mk f, h.measurable_mk, h' h.ae_eq_mk⟩ lemma ae_mem_imp_eq_mk {s} (h : ae_measurable f (μ.restrict s)) : ∀ᵐ x ∂μ, x ∈ s → f x = h.mk f x := ae_imp_of_ae_restrict h.ae_eq_mk lemma ae_inf_principal_eq_mk {s} (h : ae_measurable f (μ.restrict s)) : f =ᶠ[μ.ae ⊓ 𝓟 s] h.mk f := le_ae_restrict h.ae_eq_mk @[measurability] lemma sum_measure [countable ι] {μ : ι → measure α} (h : ∀ i, ae_measurable f (μ i)) : ae_measurable f (sum μ) := begin nontriviality β, inhabit β, set s : ι → set α := λ i, to_measurable (μ i) {x | f x ≠ (h i).mk f x}, have hsμ : ∀ i, μ i (s i) = 0, { intro i, rw measure_to_measurable, exact (h i).ae_eq_mk }, have hsm : measurable_set (⋂ i, s i), from measurable_set.Inter (λ i, measurable_set_to_measurable _ _), have hs : ∀ i x, x ∉ s i → f x = (h i).mk f x, { intros i x hx, contrapose! hx, exact subset_to_measurable _ _ hx }, set g : α → β := (⋂ i, s i).piecewise (const α default) f, refine ⟨g, measurable_of_restrict_of_restrict_compl hsm _ _, ae_sum_iff.mpr $ λ i, _⟩, { rw [restrict_piecewise], simp only [set.restrict, const], exact measurable_const }, { rw [restrict_piecewise_compl, compl_Inter], intros t ht, refine ⟨⋃ i, ((h i).mk f ⁻¹' t) ∩ (s i)ᶜ, measurable_set.Union $ λ i, (measurable_mk _ ht).inter (measurable_set_to_measurable _ _).compl, _⟩, ext ⟨x, hx⟩, simp only [mem_preimage, mem_Union, subtype.coe_mk, set.restrict, mem_inter_eq, mem_compl_iff] at hx ⊢, split, { rintro ⟨i, hxt, hxs⟩, rwa hs _ _ hxs }, { rcases hx with ⟨i, hi⟩, rw hs _ _ hi, exact λ h, ⟨i, h, hi⟩ } }, { refine measure_mono_null (λ x (hx : f x ≠ g x), _) (hsμ i), contrapose! hx, refine (piecewise_eq_of_not_mem _ _ _ _).symm, exact λ h, hx (mem_Inter.1 h i) } end @[simp] lemma _root_.ae_measurable_sum_measure_iff [countable ι] {μ : ι → measure α} : ae_measurable f (sum μ) ↔ ∀ i, ae_measurable f (μ i) := ⟨λ h i, h.mono_measure (le_sum _ _), sum_measure⟩ @[simp] lemma _root_.ae_measurable_add_measure_iff : ae_measurable f (μ + ν) ↔ ae_measurable f μ ∧ ae_measurable f ν := by { rw [← sum_cond, ae_measurable_sum_measure_iff, bool.forall_bool, and.comm], refl } @[measurability] lemma add_measure {f : α → β} (hμ : ae_measurable f μ) (hν : ae_measurable f ν) : ae_measurable f (μ + ν) := ae_measurable_add_measure_iff.2 ⟨hμ, hν⟩ @[measurability] protected lemma Union [countable ι] {s : ι → set α} (h : ∀ i, ae_measurable f (μ.restrict (s i))) : ae_measurable f (μ.restrict (⋃ i, s i)) := (sum_measure h).mono_measure $ restrict_Union_le @[simp] lemma _root_.ae_measurable_Union_iff [countable ι] {s : ι → set α} : ae_measurable f (μ.restrict (⋃ i, s i)) ↔ ∀ i, ae_measurable f (μ.restrict (s i)) := ⟨λ h i, h.mono_measure $ restrict_mono (subset_Union _ _) le_rfl, ae_measurable.Union⟩ @[simp] lemma _root_.ae_measurable_union_iff {s t : set α} : ae_measurable f (μ.restrict (s ∪ t)) ↔ ae_measurable f (μ.restrict s) ∧ ae_measurable f (μ.restrict t) := by simp only [union_eq_Union, ae_measurable_Union_iff, bool.forall_bool, cond, and.comm] @[measurability] lemma smul_measure [monoid R] [distrib_mul_action R ℝ≥0∞] [is_scalar_tower R ℝ≥0∞ ℝ≥0∞] (h : ae_measurable f μ) (c : R) : ae_measurable f (c • μ) := ⟨h.mk f, h.measurable_mk, ae_smul_measure h.ae_eq_mk c⟩ lemma comp_ae_measurable {f : α → δ} {g : δ → β} (hg : ae_measurable g (μ.map f)) (hf : ae_measurable f μ) : ae_measurable (g ∘ f) μ := ⟨hg.mk g ∘ hf.mk f, hg.measurable_mk.comp hf.measurable_mk, (ae_eq_comp hf hg.ae_eq_mk).trans ((hf.ae_eq_mk).fun_comp (mk g hg))⟩ lemma comp_measurable {f : α → δ} {g : δ → β} (hg : ae_measurable g (μ.map f)) (hf : measurable f) : ae_measurable (g ∘ f) μ := hg.comp_ae_measurable hf.ae_measurable lemma comp_measurable' {ν : measure δ} {f : α → δ} {g : δ → β} (hg : ae_measurable g ν) (hf : measurable f) (h : μ.map f ≪ ν) : ae_measurable (g ∘ f) μ := (hg.mono' h).comp_measurable hf lemma map_map_of_ae_measurable {g : β → γ} {f : α → β} (hg : ae_measurable g (measure.map f μ)) (hf : ae_measurable f μ) : (μ.map f).map g = μ.map (g ∘ f) := begin ext1 s hs, let g' := hg.mk g, have A : map g (map f μ) = map g' (map f μ), { apply measure_theory.measure.map_congr, exact hg.ae_eq_mk }, have B : map (g ∘ f) μ = map (g' ∘ f) μ, { apply measure_theory.measure.map_congr, exact ae_of_ae_map hf hg.ae_eq_mk }, simp only [A, B, hs, hg.measurable_mk.ae_measurable.comp_ae_measurable hf, hg.measurable_mk, hg.measurable_mk hs, hf, map_apply, map_apply_of_ae_measurable], refl, end @[measurability] lemma prod_mk {f : α → β} {g : α → γ} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ x, (f x, g x)) μ := ⟨λ a, (hf.mk f a, hg.mk g a), hf.measurable_mk.prod_mk hg.measurable_mk, eventually_eq.prod_mk hf.ae_eq_mk hg.ae_eq_mk⟩ lemma exists_ae_eq_range_subset (H : ae_measurable f μ) {t : set β} (ht : ∀ᵐ x ∂μ, f x ∈ t) (h₀ : t.nonempty) : ∃ g, measurable g ∧ range g ⊆ t ∧ f =ᵐ[μ] g := begin let s : set α := to_measurable μ {x | f x = H.mk f x ∧ f x ∈ t}ᶜ, let g : α → β := piecewise s (λ x, h₀.some) (H.mk f), refine ⟨g, _, _, _⟩, { exact measurable.piecewise (measurable_set_to_measurable _ _) measurable_const H.measurable_mk }, { rintros _ ⟨x, rfl⟩, by_cases hx : x ∈ s, { simpa [g, hx] using h₀.some_mem }, { simp only [g, hx, piecewise_eq_of_not_mem, not_false_iff], contrapose! hx, apply subset_to_measurable, simp only [hx, mem_compl_eq, mem_set_of_eq, not_and, not_false_iff, implies_true_iff] {contextual := tt} } }, { have A : μ (to_measurable μ {x | f x = H.mk f x ∧ f x ∈ t}ᶜ) = 0, { rw [measure_to_measurable, ← compl_mem_ae_iff, compl_compl], exact H.ae_eq_mk.and ht }, filter_upwards [compl_mem_ae_iff.2 A] with x hx, rw mem_compl_iff at hx, simp only [g, hx, piecewise_eq_of_not_mem, not_false_iff], contrapose! hx, apply subset_to_measurable, simp only [hx, mem_compl_eq, mem_set_of_eq, false_and, not_false_iff] } end lemma exists_measurable_nonneg {β} [preorder β] [has_zero β] {mβ : measurable_space β} {f : α → β} (hf : ae_measurable f μ) (f_nn : ∀ᵐ t ∂μ, 0 ≤ f t) : ∃ g, measurable g ∧ 0 ≤ g ∧ f =ᵐ[μ] g := begin obtain ⟨G, hG_meas, hG_mem, hG_ae_eq⟩ := hf.exists_ae_eq_range_subset f_nn ⟨0, le_rfl⟩, exact ⟨G, hG_meas, λ x, hG_mem (mem_range_self x), hG_ae_eq⟩, end lemma subtype_mk (h : ae_measurable f μ) {s : set β} {hfs : ∀ x, f x ∈ s} : ae_measurable (cod_restrict f s hfs) μ := begin nontriviality α, inhabit α, obtain ⟨g, g_meas, hg, fg⟩ : ∃ (g : α → β), measurable g ∧ range g ⊆ s ∧ f =ᵐ[μ] g := h.exists_ae_eq_range_subset (eventually_of_forall hfs) ⟨_, hfs default⟩, refine ⟨cod_restrict g s (λ x, hg (mem_range_self _)), measurable.subtype_mk g_meas, _⟩, filter_upwards [fg] with x hx, simpa [subtype.ext_iff], end protected lemma null_measurable (h : ae_measurable f μ) : null_measurable f μ := let ⟨g, hgm, hg⟩ := h in hgm.null_measurable.congr hg.symm end ae_measurable lemma ae_measurable_interval_oc_iff [linear_order α] {f : α → β} {a b : α} : (ae_measurable f $ μ.restrict $ Ι a b) ↔ (ae_measurable f $ μ.restrict $ Ioc a b) ∧ (ae_measurable f $ μ.restrict $ Ioc b a) := by rw [interval_oc_eq_union, ae_measurable_union_iff] lemma ae_measurable_iff_measurable [μ.is_complete] : ae_measurable f μ ↔ measurable f := ⟨λ h, h.null_measurable.measurable_of_complete, λ h, h.ae_measurable⟩ lemma measurable_embedding.ae_measurable_map_iff {g : β → γ} (hf : measurable_embedding f) : ae_measurable g (μ.map f) ↔ ae_measurable (g ∘ f) μ := begin refine ⟨λ H, H.comp_measurable hf.measurable, _⟩, rintro ⟨g₁, hgm₁, heq⟩, rcases hf.exists_measurable_extend hgm₁ (λ x, ⟨g x⟩) with ⟨g₂, hgm₂, rfl⟩, exact ⟨g₂, hgm₂, hf.ae_map_iff.2 heq⟩ end lemma measurable_embedding.ae_measurable_comp_iff {g : β → γ} (hg : measurable_embedding g) {μ : measure α} : ae_measurable (g ∘ f) μ ↔ ae_measurable f μ := begin refine ⟨λ H, _, hg.measurable.comp_ae_measurable⟩, suffices : ae_measurable ((range_splitting g ∘ range_factorization g) ∘ f) μ, by rwa [(right_inverse_range_splitting hg.injective).comp_eq_id] at this, exact hg.measurable_range_splitting.comp_ae_measurable H.subtype_mk end lemma ae_measurable_restrict_iff_comap_subtype {s : set α} (hs : measurable_set s) {μ : measure α} {f : α → β} : ae_measurable f (μ.restrict s) ↔ ae_measurable (f ∘ coe : s → β) (comap coe μ) := by rw [← map_comap_subtype_coe hs, (measurable_embedding.subtype_coe hs).ae_measurable_map_iff] @[simp, to_additive] lemma ae_measurable_one [has_one β] : ae_measurable (λ a : α, (1 : β)) μ := measurable_one.ae_measurable @[simp] lemma ae_measurable_smul_measure_iff {c : ℝ≥0∞} (hc : c ≠ 0) : ae_measurable f (c • μ) ↔ ae_measurable f μ := ⟨λ h, ⟨h.mk f, h.measurable_mk, (ae_smul_measure_iff hc).1 h.ae_eq_mk⟩, λ h, ⟨h.mk f, h.measurable_mk, (ae_smul_measure_iff hc).2 h.ae_eq_mk⟩⟩ lemma ae_measurable_of_ae_measurable_trim {α} {m m0 : measurable_space α} {μ : measure α} (hm : m ≤ m0) {f : α → β} (hf : ae_measurable f (μ.trim hm)) : ae_measurable f μ := ⟨hf.mk f, measurable.mono hf.measurable_mk hm le_rfl, ae_eq_of_ae_eq_trim hf.ae_eq_mk⟩ lemma ae_measurable_restrict_of_measurable_subtype {s : set α} (hs : measurable_set s) (hf : measurable (λ x : s, f x)) : ae_measurable f (μ.restrict s) := (ae_measurable_restrict_iff_comap_subtype hs).2 hf.ae_measurable lemma ae_measurable_map_equiv_iff (e : α ≃ᵐ β) {f : β → γ} : ae_measurable f (μ.map e) ↔ ae_measurable (f ∘ e) μ := e.measurable_embedding.ae_measurable_map_iff end lemma ae_measurable.restrict (hfm : ae_measurable f μ) {s} : ae_measurable f (μ.restrict s) := ⟨ae_measurable.mk f hfm, hfm.measurable_mk, ae_restrict_of_ae hfm.ae_eq_mk⟩ lemma ae_measurable_Ioi_of_forall_Ioc {β} {mβ : measurable_space β} [linear_order α] [(at_top : filter α).is_countably_generated] {x : α} {g : α → β} (g_meas : ∀ t > x, ae_measurable g (μ.restrict (Ioc x t))) : ae_measurable g (μ.restrict (Ioi x)) := begin haveI : nonempty α := ⟨x⟩, haveI : (at_top : filter α).ne_bot := at_top_ne_bot, obtain ⟨u, hu_tendsto⟩ := exists_seq_tendsto (at_top : filter α), have Ioi_eq_Union : Ioi x = ⋃ n : ℕ, Ioc x (u n), { rw Union_Ioc_eq_Ioi_self_iff.mpr _, rw tendsto_at_top_at_top at hu_tendsto, exact λ y _, ⟨(hu_tendsto y).some, (hu_tendsto y).some_spec (hu_tendsto y).some le_rfl⟩, }, rw [Ioi_eq_Union, ae_measurable_Union_iff], intros n, cases lt_or_le x (u n), { exact g_meas (u n) h, }, { rw Ioc_eq_empty (not_lt.mpr h), simp only [measure.restrict_empty], exact ae_measurable_zero_measure, }, end variables [has_zero β] lemma ae_measurable_indicator_iff {s} (hs : measurable_set s) : ae_measurable (indicator s f) μ ↔ ae_measurable f (μ.restrict s) := begin split, { intro h, exact (h.mono_measure measure.restrict_le_self).congr (indicator_ae_eq_restrict hs) }, { intro h, refine ⟨indicator s (h.mk f), h.measurable_mk.indicator hs, _⟩, have A : s.indicator f =ᵐ[μ.restrict s] s.indicator (ae_measurable.mk f h) := (indicator_ae_eq_restrict hs).trans (h.ae_eq_mk.trans $ (indicator_ae_eq_restrict hs).symm), have B : s.indicator f =ᵐ[μ.restrict sᶜ] s.indicator (ae_measurable.mk f h) := (indicator_ae_eq_restrict_compl hs).trans (indicator_ae_eq_restrict_compl hs).symm, exact ae_of_ae_restrict_of_ae_restrict_compl _ A B }, end @[measurability] lemma ae_measurable.indicator (hfm : ae_measurable f μ) {s} (hs : measurable_set s) : ae_measurable (s.indicator f) μ := (ae_measurable_indicator_iff hs).mpr hfm.restrict lemma measure_theory.measure.restrict_map_of_ae_measurable {f : α → δ} (hf : ae_measurable f μ) {s : set δ} (hs : measurable_set s) : (μ.map f).restrict s = (μ.restrict $ f ⁻¹' s).map f := calc (μ.map f).restrict s = (μ.map (hf.mk f)).restrict s : by { congr' 1, apply measure.map_congr hf.ae_eq_mk } ... = (μ.restrict $ (hf.mk f) ⁻¹' s).map (hf.mk f) : measure.restrict_map hf.measurable_mk hs ... = (μ.restrict $ (hf.mk f) ⁻¹' s).map f : measure.map_congr (ae_restrict_of_ae (hf.ae_eq_mk.symm)) ... = (μ.restrict $ f ⁻¹' s).map f : begin apply congr_arg, ext1 t ht, simp only [ht, measure.restrict_apply], apply measure_congr, apply (eventually_eq.refl _ _).inter (hf.ae_eq_mk.symm.preimage s) end lemma measure_theory.measure.map_mono_of_ae_measurable {f : α → δ} (h : μ ≤ ν) (hf : ae_measurable f ν) : μ.map f ≤ ν.map f := λ s hs, by simpa [hf, hs, hf.mono_measure h] using measure.le_iff'.1 h (f ⁻¹' s)
84060621d55b1f2d82381e70ae897a391ad8a6a7
e030b0259b777fedcdf73dd966f3f1556d392178
/library/init/logic.lean
334aee2423eae41a6834a39121aca58b88fb4bd0
[ "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
36,811
lean
/- 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, Floris van Doorn -/ prelude import init.core universe variables u v w @[reducible] def id {α : Type u} (a : α) : α := a def flip {α : Type u} {β : Type v} {φ : Type w} (f : α → β → φ) : β → α → φ := λ b a, f a b /- implication -/ def implies (a b : Prop) := a → b @[trans] lemma implies.trans {p q r : Prop} (h₁ : implies p q) (h₂ : implies q r) : implies p r := assume hp, h₂ (h₁ hp) def trivial : true := ⟨⟩ @[inline] def absurd {a : Prop} {b : Type v} (h₁ : a) (h₂ : ¬a) : b := false.rec b (h₂ h₁) lemma not.intro {a : Prop} (h : a → false) : ¬ a := h lemma mt {a b : Prop} (h₁ : a → b) (h₂ : ¬b) : ¬a := assume ha : a, absurd (h₁ ha) h₂ def implies.resolve {a b : Prop} (h : a → b) (nb : ¬ b) : ¬ a := assume ha, nb (h ha) /- not -/ lemma not_false : ¬false := assume h : false, h def non_contradictory (a : Prop) : Prop := ¬¬a lemma non_contradictory_intro {a : Prop} (ha : a) : ¬¬a := assume hna : ¬a, absurd ha hna /- false -/ lemma false.elim {c : Prop} (h : false) : c := false.rec c h /- eq -/ -- proof irrelevance is built in lemma proof_irrel {a : Prop} (h₁ h₂ : a) : h₁ = h₂ := rfl @[simp] lemma id.def {α : Type u} (a : α) : id a = a := rfl -- Remark: we provide the universe levels explicitly to make sure `eq.drec` has the same type of `eq.rec` in the hoTT library attribute [elab_as_eliminator] protected lemma {u₁ u₂} eq.drec {α : Type u₂} {a : α} {φ : Π (x : α), a = x → Type u₁} (h₁ : φ a (eq.refl a)) {b : α} (h₂ : a = b) : φ b h₂ := eq.rec (λ h₂ : a = a, show φ a h₂, from h₁) h₂ h₂ attribute [elab_as_eliminator] protected lemma drec_on {α : Type u} {a : α} {φ : Π (x : α), a = x → Type v} {b : α} (h₂ : a = b) (h₁ : φ a (eq.refl a)) : φ b h₂ := eq.drec h₁ h₂ lemma eq.mp {α β : Type u} : (α = β) → α → β := eq.rec_on lemma eq.mpr {α β : Type u} : (α = β) → β → α := λ h₁ h₂, eq.rec_on (eq.symm h₁) h₂ lemma eq.substr {α : Type u} {p : α → Prop} {a b : α} (h₁ : b = a) : p a → p b := eq.subst (eq.symm h₁) lemma congr {α : Type u} {β : Type v} {f₁ f₂ : α → β} {a₁ a₂ : α} (h₁ : f₁ = f₂) (h₂ : a₁ = a₂) : f₁ a₁ = f₂ a₂ := eq.subst h₁ (eq.subst h₂ rfl) lemma congr_fun {α : Type u} {β : α → Type v} {f g : Π x, β x} (h : f = g) (a : α) : f a = g a := eq.subst h (eq.refl (f a)) lemma congr_arg {α : Type u} {β : Type v} {a₁ a₂ : α} (f : α → β) : a₁ = a₂ → f a₁ = f a₂ := congr rfl lemma trans_rel_left {α : Type u} {a b c : α} (r : α → α → Prop) (h₁ : r a b) (h₂ : b = c) : r a c := h₂ ▸ h₁ lemma trans_rel_right {α : Type u} {a b c : α} (r : α → α → Prop) (h₁ : a = b) (h₂ : r b c) : r a c := h₁^.symm ▸ h₂ lemma of_eq_true {p : Prop} (h : p = true) : p := h^.symm ▸ trivial lemma not_of_eq_false {p : Prop} (h : p = false) : ¬p := assume hp, h ▸ hp @[inline] def cast {α β : Type u} (h : α = β) (a : α) : β := eq.rec a h lemma cast_proof_irrel {α β : Type u} (h₁ h₂ : α = β) (a : α) : cast h₁ a = cast h₂ a := rfl lemma cast_eq {α : Type u} (h : α = α) (a : α) : cast h a = a := rfl /- ne -/ @[reducible] def ne {α : Type u} (a b : α) := ¬(a = b) notation a ≠ b := ne a b @[simp] lemma ne.def {α : Type u} (a b : α) : a ≠ b = ¬ (a = b) := rfl namespace ne variable {α : Type u} variables {a b : α} lemma intro (h : a = b → false) : a ≠ b := h lemma elim (h : a ≠ b) : a = b → false := h lemma irrefl (h : a ≠ a) : false := h rfl lemma symm (h : a ≠ b) : b ≠ a := assume (h₁ : b = a), h (h₁^.symm) end ne lemma false_of_ne {α : Type u} {a : α} : a ≠ a → false := ne.irrefl section variables {p : Prop} lemma ne_false_of_self : p → p ≠ false := assume (hp : p) (heq : p = false), heq ▸ hp lemma ne_true_of_not : ¬p → p ≠ true := assume (hnp : ¬p) (heq : p = true), (heq ▸ hnp) trivial lemma true_ne_false : ¬true = false := ne_false_of_self trivial end attribute [refl] heq.refl section variables {α β φ : Type u} {a a' : α} {b b' : β} {c : φ} lemma eq_of_heq (h : a == a') : a = a' := have ∀ (α' : Type u) (a' : α') (h₁ : @heq α a α' a') (h₂ : α = α'), (eq.rec_on h₂ a : α') = a', from λ (α' : Type u) (a' : α') (h₁ : @heq α a α' a'), heq.rec_on h₁ (λ h₂ : α = α, rfl), show (eq.rec_on (eq.refl α) a : α) = a', from this α a' h (eq.refl α) lemma heq.elim {α : Type u} {a : α} {p : α → Type v} {b : α} (h₁ : a == b) : p a → p b := eq.rec_on (eq_of_heq h₁) lemma heq.subst {p : ∀ T : Type u, T → Prop} : a == b → p α a → p β b := heq.rec_on @[symm] lemma heq.symm (h : a == b) : b == a := heq.rec_on h (heq.refl a) lemma heq_of_eq (h : a = a') : a == a' := eq.subst h (heq.refl a) @[trans] lemma heq.trans (h₁ : a == b) (h₂ : b == c) : a == c := heq.subst h₂ h₁ @[trans] lemma heq_of_heq_of_eq (h₁ : a == b) (h₂ : b = b') : a == b' := heq.trans h₁ (heq_of_eq h₂) @[trans] lemma heq_of_eq_of_heq (h₁ : a = a') (h₂ : a' == b) : a == b := heq.trans (heq_of_eq h₁) h₂ def type_eq_of_heq (h : a == b) : α = β := heq.rec_on h (eq.refl α) end lemma eq_rec_heq {α : Type u} {φ : α → Type v} : ∀ {a a' : α} (h : a = a') (p : φ a), (eq.rec_on h p : φ a') == p | a .a rfl p := heq.refl p lemma heq_of_eq_rec_left {α : Type u} {φ : α → Type v} : ∀ {a a' : α} {p₁ : φ a} {p₂ : φ a'} (e : a = a') (h₂ : (eq.rec_on e p₁ : φ a') = p₂), p₁ == p₂ | a .a p₁ p₂ (eq.refl .a) h := eq.rec_on h (heq.refl p₁) lemma heq_of_eq_rec_right {α : Type u} {φ : α → Type v} : ∀ {a a' : α} {p₁ : φ a} {p₂ : φ a'} (e : a' = a) (h₂ : p₁ = eq.rec_on e p₂), p₁ == p₂ | a .a p₁ p₂ (eq.refl .a) h := have p₁ = p₂, from h, this ▸ heq.refl p₁ lemma of_heq_true {a : Prop} (h : a == true) : a := of_eq_true (eq_of_heq h) lemma eq_rec_compose : ∀ {α β φ : Type u} (p₁ : β = φ) (p₂ : α = β) (a : α), (eq.rec_on p₁ (eq.rec_on p₂ a : β) : φ) = eq.rec_on (eq.trans p₂ p₁) a | α .α .α (eq.refl .α) (eq.refl .α) a := rfl lemma eq_rec_eq_eq_rec : ∀ {α₁ α₂ : Type u} {p : α₁ = α₂} {a₁ : α₁} {a₂ : α₂}, (eq.rec_on p a₁ : α₂) = a₂ → a₁ = eq.rec_on (eq.symm p) a₂ | α .α rfl a .a rfl := rfl lemma eq_rec_of_heq_left : ∀ {α₁ α₂ : Type u} {a₁ : α₁} {a₂ : α₂} (h : a₁ == a₂), (eq.rec_on (type_eq_of_heq h) a₁ : α₂) = a₂ | α .α a .a (heq.refl .a) := rfl lemma eq_rec_of_heq_right {α₁ α₂ : Type u} {a₁ : α₁} {a₂ : α₂} (h : a₁ == a₂) : a₁ = eq.rec_on (eq.symm (type_eq_of_heq h)) a₂ := eq_rec_eq_eq_rec (eq_rec_of_heq_left h) lemma cast_heq : ∀ {α β : Type u} (h : α = β) (a : α), cast h a == a | α .α (eq.refl .α) a := heq.refl a /- and -/ notation a /\ b := and a b notation a ∧ b := and a b variables {a b c d : Prop} lemma and.elim (h₁ : a ∧ b) (h₂ : a → b → c) : c := and.rec h₂ h₁ lemma and.swap : a ∧ b → b ∧ a := assume ⟨ha, hb⟩, ⟨hb, ha⟩ def and.symm := @and.swap /- or -/ notation a \/ b := or a b notation a ∨ b := or a b namespace or lemma elim (h₁ : a ∨ b) (h₂ : a → c) (h₃ : b → c) : c := or.rec h₂ h₃ h₁ end or lemma non_contradictory_em (a : Prop) : ¬¬(a ∨ ¬a) := assume not_em : ¬(a ∨ ¬a), have neg_a : ¬a, from assume pos_a : a, absurd (or.inl pos_a) not_em, absurd (or.inr neg_a) not_em def not_not_em := non_contradictory_em lemma or.swap : a ∨ b → b ∨ a := or.rec or.inr or.inl def or.symm := @or.swap /- xor -/ def xor (a b : Prop) := (a ∧ ¬ b) ∨ (b ∧ ¬ a) /- iff -/ def iff (a b : Prop) := (a → b) ∧ (b → a) notation a <-> b := iff a b notation a ↔ b := iff a b lemma iff.intro : (a → b) → (b → a) → (a ↔ b) := and.intro lemma iff.elim : ((a → b) → (b → a) → c) → (a ↔ b) → c := and.rec attribute [recursor 5] iff.elim lemma iff.elim_left : (a ↔ b) → a → b := and.left def iff.mp := @iff.elim_left lemma iff.elim_right : (a ↔ b) → b → a := and.right def iff.mpr := @iff.elim_right attribute [refl] lemma iff.refl (a : Prop) : a ↔ a := iff.intro (assume h, h) (assume h, h) lemma iff.rfl {a : Prop} : a ↔ a := iff.refl a attribute [trans] lemma iff.trans (h₁ : a ↔ b) (h₂ : b ↔ c) : a ↔ c := iff.intro (assume ha, iff.mp h₂ (iff.mp h₁ ha)) (assume hc, iff.mpr h₁ (iff.mpr h₂ hc)) attribute [symm] lemma iff.symm (h : a ↔ b) : b ↔ a := iff.intro (iff.elim_right h) (iff.elim_left h) lemma iff.comm : (a ↔ b) ↔ (b ↔ a) := iff.intro iff.symm iff.symm lemma eq.to_iff {a b : Prop} (h : a = b) : a ↔ b := eq.rec_on h iff.rfl lemma neq_of_not_iff {a b : Prop} : ¬(a ↔ b) → a ≠ b := λ h₁ h₂, have a ↔ b, from eq.subst h₂ (iff.refl a), absurd this h₁ lemma not_iff_not_of_iff (h₁ : a ↔ b) : ¬a ↔ ¬b := iff.intro (assume (hna : ¬ a) (hb : b), hna (iff.elim_right h₁ hb)) (assume (hnb : ¬ b) (ha : a), hnb (iff.elim_left h₁ ha)) lemma of_iff_true (h : a ↔ true) : a := iff.mp (iff.symm h) trivial lemma not_of_iff_false : (a ↔ false) → ¬a := iff.mp lemma iff_true_intro (h : a) : a ↔ true := iff.intro (λ hl, trivial) (λ hr, h) lemma iff_false_intro (h : ¬a) : a ↔ false := iff.intro h (false.rec a) lemma not_non_contradictory_iff_absurd (a : Prop) : ¬¬¬a ↔ ¬a := iff.intro (λ (hl : ¬¬¬a) (ha : a), hl (non_contradictory_intro ha)) absurd def not_not_not_iff := not_non_contradictory_iff_absurd lemma imp_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a → b) ↔ (c → d) := iff.intro (λ hab hc, iff.mp h₂ (hab (iff.mpr h₁ hc))) (λ hcd ha, iff.mpr h₂ (hcd (iff.mp h₁ ha))) lemma imp_congr_ctx (h₁ : a ↔ c) (h₂ : c → (b ↔ d)) : (a → b) ↔ (c → d) := iff.intro (λ hab hc, have ha : a, from iff.mpr h₁ hc, have hb : b, from hab ha, iff.mp (h₂ hc) hb) (λ hcd ha, have hc : c, from iff.mp h₁ ha, have hd : d, from hcd hc, iff.mpr (h₂ hc) hd) lemma imp_congr_right (h : a → (b ↔ c)) : (a → b) ↔ (a → c) := iff.intro (take hab ha, iff.elim_left (h ha) (hab ha)) (take hab ha, iff.elim_right (h ha) (hab ha)) lemma not_not_intro (ha : a) : ¬¬a := assume hna : ¬a, hna ha lemma not_of_not_not_not (h : ¬¬¬a) : ¬a := λ ha, absurd (not_not_intro ha) h @[simp] lemma not_true : (¬ true) ↔ false := iff_false_intro (not_not_intro trivial) def not_true_iff := not_true @[simp] lemma not_false_iff : (¬ false) ↔ true := iff_true_intro not_false @[congr] lemma not_congr (h : a ↔ b) : ¬a ↔ ¬b := iff.intro (λ h₁ h₂, h₁ (iff.mpr h h₂)) (λ h₁ h₂, h₁ (iff.mp h h₂)) @[simp] lemma ne_self_iff_false {α : Type u} (a : α) : (not (a = a)) ↔ false := iff.intro false_of_ne false.elim @[simp] lemma eq_self_iff_true {α : Type u} (a : α) : (a = a) ↔ true := iff_true_intro rfl @[simp] lemma heq_self_iff_true {α : Type u} (a : α) : (a == a) ↔ true := iff_true_intro (heq.refl a) @[simp] lemma iff_not_self (a : Prop) : (a ↔ ¬a) ↔ false := iff_false_intro (λ h, have h' : ¬a, from (λ ha, (iff.mp h ha) ha), h' (iff.mpr h h')) @[simp] lemma not_iff_self (a : Prop) : (¬a ↔ a) ↔ false := iff_false_intro (λ h, have h' : ¬a, from (λ ha, (iff.mpr h ha) ha), h' (iff.mp h h')) @[simp] lemma true_iff_false : (true ↔ false) ↔ false := iff_false_intro (λ h, iff.mp h trivial) @[simp] lemma false_iff_true : (false ↔ true) ↔ false := iff_false_intro (λ h, iff.mpr h trivial) lemma false_of_true_iff_false : (true ↔ false) → false := assume h, iff.mp h trivial lemma false_of_true_eq_false : (true = false) → false := assume h, h ▸ trivial lemma true_eq_false_of_false : false → (true = false) := false.elim /- and simp rules -/ lemma and.imp (hac : a → c) (hbd : b → d) : a ∧ b → c ∧ d := assume ⟨ha, hb⟩, ⟨hac ha, hbd hb⟩ def and_implies := @and.imp @[congr] lemma and_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a ∧ b) ↔ (c ∧ d) := iff.intro (and.imp (iff.mp h₁) (iff.mp h₂)) (and.imp (iff.mpr h₁) (iff.mpr h₂)) lemma and_congr_right (h : a → (b ↔ c)) : (a ∧ b) ↔ (a ∧ c) := iff.intro (assume ⟨ha, hb⟩, ⟨ha, iff.elim_left (h ha) hb⟩) (assume ⟨ha, hc⟩, ⟨ha, iff.elim_right (h ha) hc⟩) @[simp] lemma and.comm : a ∧ b ↔ b ∧ a := iff.intro and.swap and.swap lemma and_comm (a b : Prop) : a ∧ b ↔ b ∧ a := and.comm @[simp] lemma and.assoc : (a ∧ b) ∧ c ↔ a ∧ (b ∧ c) := iff.intro (assume ⟨⟨ha, hb⟩, hc⟩, ⟨ha, ⟨hb, hc⟩⟩) (assume ⟨ha, ⟨hb, hc⟩⟩, ⟨⟨ha, hb⟩, hc⟩) lemma and_assoc (a b : Prop) : (a ∧ b) ∧ c ↔ a ∧ (b ∧ c) := and.assoc @[simp] lemma and.left_comm : a ∧ (b ∧ c) ↔ b ∧ (a ∧ c) := iff.trans (iff.symm and.assoc) (iff.trans (and_congr and.comm (iff.refl c)) and.assoc) lemma and_iff_left {a b : Prop} (hb : b) : (a ∧ b) ↔ a := iff.intro and.left (λ ha, ⟨ha, hb⟩) lemma and_iff_right {a b : Prop} (ha : a) : (a ∧ b) ↔ b := iff.intro and.right (and.intro ha) @[simp] lemma and_true (a : Prop) : a ∧ true ↔ a := and_iff_left trivial @[simp] lemma true_and (a : Prop) : true ∧ a ↔ a := and_iff_right trivial @[simp] lemma and_false (a : Prop) : a ∧ false ↔ false := iff_false_intro and.right @[simp] lemma false_and (a : Prop) : false ∧ a ↔ false := iff_false_intro and.left @[simp] lemma not_and_self (a : Prop) : (¬a ∧ a) ↔ false := iff_false_intro (λ h, and.elim h (λ h₁ h₂, absurd h₂ h₁)) @[simp] lemma and_not_self (a : Prop) : (a ∧ ¬a) ↔ false := iff_false_intro (assume ⟨h₁, h₂⟩, absurd h₁ h₂) @[simp] lemma and_self (a : Prop) : a ∧ a ↔ a := iff.intro and.left (assume h, ⟨h, h⟩) /- or simp rules -/ lemma or.imp (h₂ : a → c) (h₃ : b → d) : a ∨ b → c ∨ d := or.rec (λ h, or.inl (h₂ h)) (λ h, or.inr (h₃ h)) lemma or.imp_left (h : a → b) : a ∨ c → b ∨ c := or.imp h id lemma or.imp_right (h : a → b) : c ∨ a → c ∨ b := or.imp id h @[congr] lemma or_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a ∨ b) ↔ (c ∨ d) := iff.intro (or.imp (iff.mp h₁) (iff.mp h₂)) (or.imp (iff.mpr h₁) (iff.mpr h₂)) @[simp] lemma or.comm : a ∨ b ↔ b ∨ a := iff.intro or.swap or.swap lemma or_comm (a b : Prop) : a ∨ b ↔ b ∨ a := or.comm @[simp] lemma or.assoc : (a ∨ b) ∨ c ↔ a ∨ (b ∨ c) := iff.intro (or.rec (or.imp_right or.inl) (λ h, or.inr (or.inr h))) (or.rec (λ h, or.inl (or.inl h)) (or.imp_left or.inr)) lemma or_assoc (a b : Prop) : (a ∨ b) ∨ c ↔ a ∨ (b ∨ c) := or.assoc @[simp] lemma or.left_comm : a ∨ (b ∨ c) ↔ b ∨ (a ∨ c) := iff.trans (iff.symm or.assoc) (iff.trans (or_congr or.comm (iff.refl c)) or.assoc) @[simp] lemma or_true (a : Prop) : a ∨ true ↔ true := iff_true_intro (or.inr trivial) @[simp] lemma true_or (a : Prop) : true ∨ a ↔ true := iff_true_intro (or.inl trivial) @[simp] lemma or_false (a : Prop) : a ∨ false ↔ a := iff.intro (or.rec id false.elim) or.inl @[simp] lemma false_or (a : Prop) : false ∨ a ↔ a := iff.trans or.comm (or_false a) @[simp] lemma or_self (a : Prop) : a ∨ a ↔ a := iff.intro (or.rec id id) or.inl lemma not_or {a b : Prop} : ¬ a → ¬ b → ¬ (a ∨ b) | hna hnb (or.inl ha) := absurd ha hna | hna hnb (or.inr hb) := absurd hb hnb /- or resolution rulse -/ def or.resolve_left {a b : Prop} (h : a ∨ b) (na : ¬ a) : b := or.elim h (λ ha, absurd ha na) id def or.neg_resolve_left {a b : Prop} (h : ¬ a ∨ b) (ha : a) : b := or.elim h (λ na, absurd ha na) id def or.resolve_right {a b : Prop} (h : a ∨ b) (nb : ¬ b) : a := or.elim h id (λ hb, absurd hb nb) def or.neg_resolve_right {a b : Prop} (h : a ∨ ¬ b) (hb : b) : a := or.elim h id (λ nb, absurd hb nb) /- iff simp rules -/ @[simp] lemma iff_true (a : Prop) : (a ↔ true) ↔ a := iff.intro (assume h, iff.mpr h trivial) iff_true_intro @[simp] lemma true_iff (a : Prop) : (true ↔ a) ↔ a := iff.trans iff.comm (iff_true a) @[simp] lemma iff_false (a : Prop) : (a ↔ false) ↔ ¬ a := iff.intro and.left iff_false_intro @[simp] lemma false_iff (a : Prop) : (false ↔ a) ↔ ¬ a := iff.trans iff.comm (iff_false a) @[simp] lemma iff_self (a : Prop) : (a ↔ a) ↔ true := iff_true_intro iff.rfl @[congr] lemma iff_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a ↔ b) ↔ (c ↔ d) := and_congr (imp_congr h₁ h₂) (imp_congr h₂ h₁) /- implies simp rule -/ @[simp] lemma implies_true_iff (a : Prop) : (a → true) ↔ true := iff.intro (λ h, trivial) (λ ha h, trivial) @[simp] lemma false_implies_iff (a : Prop) : (false → a) ↔ true := iff.intro (λ h, trivial) (λ ha h, false.elim h) /- exists -/ inductive Exists {α : Type u} (p : α → Prop) : Prop | intro : ∀ (a : α), p a → Exists attribute [intro] Exists.intro @[pattern] def exists.intro := @Exists.intro notation `exists` binders `, ` r:(scoped P, Exists P) := r notation `∃` binders `, ` r:(scoped P, Exists P) := r lemma exists.elim {α : Type u} {p : α → Prop} {b : Prop} (h₁ : ∃ x, p x) (h₂ : ∀ (a : α), p a → b) : b := Exists.rec h₂ h₁ /- exists unique -/ def exists_unique {α : Type u} (p : α → Prop) := ∃ x, p x ∧ ∀ y, p y → y = x notation `∃!` binders `, ` r:(scoped P, exists_unique P) := r attribute [intro] lemma exists_unique.intro {α : Type u} {p : α → Prop} (w : α) (h₁ : p w) (h₂ : ∀ y, p y → y = w) : ∃! x, p x := exists.intro w ⟨h₁, h₂⟩ attribute [recursor 4] lemma exists_unique.elim {α : Type u} {p : α → Prop} {b : Prop} (h₂ : ∃! x, p x) (h₁ : ∀ x, p x → (∀ y, p y → y = x) → b) : b := exists.elim h₂ (λ w hw, h₁ w (and.left hw) (and.right hw)) lemma exists_unique_of_exists_of_unique {α : Type u} {p : α → Prop} (hex : ∃ x, p x) (hunique : ∀ y₁ y₂, p y₁ → p y₂ → y₁ = y₂) : ∃! x, p x := exists.elim hex (λ x px, exists_unique.intro x px (take y, suppose p y, hunique y x this px)) lemma exists_of_exists_unique {α : Type u} {p : α → Prop} (h : ∃! x, p x) : ∃ x, p x := exists.elim h (λ x hx, ⟨x, and.left hx⟩) lemma unique_of_exists_unique {α : Type u} {p : α → Prop} (h : ∃! x, p x) {y₁ y₂ : α} (py₁ : p y₁) (py₂ : p y₂) : y₁ = y₂ := exists_unique.elim h (take x, suppose p x, assume unique : ∀ y, p y → y = x, show y₁ = y₂, from eq.trans (unique _ py₁) (eq.symm (unique _ py₂))) /- exists, forall, exists unique congruences -/ @[congr] lemma forall_congr {α : Type u} {p q : α → Prop} (h : ∀ a, (p a ↔ q a)) : (∀ a, p a) ↔ ∀ a, q a := iff.intro (λ p a, iff.mp (h a) (p a)) (λ q a, iff.mpr (h a) (q a)) lemma exists_imp_exists {α : Type u} {p q : α → Prop} (h : ∀ a, (p a → q a)) (p : ∃ a, p a) : ∃ a, q a := exists.elim p (λ a hp, ⟨a, h a hp⟩) @[congr] lemma exists_congr {α : Type u} {p q : α → Prop} (h : ∀ a, (p a ↔ q a)) : (Exists p) ↔ ∃ a, q a := iff.intro (exists_imp_exists (λ a, iff.mp (h a))) (exists_imp_exists (λ a, iff.mpr (h a))) @[congr] lemma exists_unique_congr {α : Type u} {p₁ p₂ : α → Prop} (h : ∀ x, p₁ x ↔ p₂ x) : (exists_unique p₁) ↔ (∃! x, p₂ x) := -- exists_congr (λ x, and_congr (h x) (forall_congr (λ y, imp_congr (h y) iff.rfl))) lemma forall_not_of_not_exists {α : Type u} {p : α → Prop} : ¬(∃ x, p x) → (∀ x, ¬p x) := λ hne x hp, hne ⟨x, hp⟩ /- decidable -/ def decidable.to_bool (p : Prop) [h : decidable p] : bool := decidable.cases_on h (λ h₁, bool.ff) (λ h₂, bool.tt) export decidable (is_true is_false to_bool) instance decidable.true : decidable true := is_true trivial instance decidable.false : decidable false := is_false not_false -- We use "dependent" if-then-else to be able to communicate the if-then-else condition -- to the branches @[inline] def dite (c : Prop) [h : decidable c] {α : Type u} : (c → α) → (¬ c → α) → α := λ t e, decidable.rec_on h e t /- if-then-else -/ @[inline] def ite (c : Prop) [h : decidable c] {α : Type u} (t e : α) : α := decidable.rec_on h (λ hnc, e) (λ hc, t) namespace decidable variables {p q : Prop} def rec_on_true [h : decidable p] {h₁ : p → Type u} {h₂ : ¬p → Type u} (h₃ : p) (h₄ : h₁ h₃) : decidable.rec_on h h₂ h₁ := decidable.rec_on h (λ h, false.rec _ (h h₃)) (λ h, h₄) def rec_on_false [h : decidable p] {h₁ : p → Type u} {h₂ : ¬p → Type u} (h₃ : ¬p) (h₄ : h₂ h₃) : decidable.rec_on h h₂ h₁ := decidable.rec_on h (λ h, h₄) (λ h, false.rec _ (h₃ h)) def by_cases {q : Type u} [φ : decidable p] : (p → q) → (¬p → q) → q := dite _ lemma em (p : Prop) [decidable p] : p ∨ ¬p := by_cases or.inl or.inr lemma by_contradiction [decidable p] (h : ¬p → false) : p := if h₁ : p then h₁ else false.rec _ (h h₁) end decidable section variables {p q : Prop} def decidable_of_decidable_of_iff (hp : decidable p) (h : p ↔ q) : decidable q := if hp : p then is_true (iff.mp h hp) else is_false (iff.mp (not_iff_not_of_iff h) hp) def decidable_of_decidable_of_eq (hp : decidable p) (h : p = q) : decidable q := decidable_of_decidable_of_iff hp h^.to_iff protected def or.by_cases [decidable p] [decidable q] {α : Type u} (h : p ∨ q) (h₁ : p → α) (h₂ : q → α) : α := if hp : p then h₁ hp else if hq : q then h₂ hq else false.rec _ (or.elim h hp hq) end section variables {p q : Prop} instance [decidable p] [decidable q] : decidable (p ∧ q) := if hp : p then if hq : q then is_true ⟨hp, hq⟩ else is_false (assume h : p ∧ q, hq (and.right h)) else is_false (assume h : p ∧ q, hp (and.left h)) instance [decidable p] [decidable q] : decidable (p ∨ q) := if hp : p then is_true (or.inl hp) else if hq : q then is_true (or.inr hq) else is_false (or.rec hp hq) instance [decidable p] : decidable (¬p) := if hp : p then is_false (absurd hp) else is_true hp instance implies.decidable [decidable p] [decidable q] : decidable (p → q) := if hp : p then if hq : q then is_true (assume h, hq) else is_false (assume h : p → q, absurd (h hp) hq) else is_true (assume h, absurd h hp) instance [decidable p] [decidable q] : decidable (p ↔ q) := and.decidable end instance {α : Type u} [decidable_eq α] (a b : α) : decidable (a ≠ b) := implies.decidable lemma bool.ff_ne_tt : ff = tt → false . def is_dec_eq {α : Type u} (p : α → α → bool) : Prop := ∀ ⦃x y : α⦄, p x y = tt → x = y def is_dec_refl {α : Type u} (p : α → α → bool) : Prop := ∀ x, p x x = tt open decidable instance : decidable_eq bool | ff ff := is_true rfl | ff tt := is_false bool.ff_ne_tt | tt ff := is_false (ne.symm bool.ff_ne_tt) | tt tt := is_true rfl def decidable_eq_of_bool_pred {α : Type u} {p : α → α → bool} (h₁ : is_dec_eq p) (h₂ : is_dec_refl p) : decidable_eq α := take x y : α, if hp : p x y = tt then is_true (h₁ hp) else is_false (assume hxy : x = y, absurd (h₂ y) (@eq.rec_on _ _ (λ z, ¬p z y = tt) _ hxy hp)) lemma decidable_eq_inl_refl {α : Type u} [h : decidable_eq α] (a : α) : h a a = is_true (eq.refl a) := match (h a a) with | (is_true e) := rfl | (is_false n) := absurd rfl n end lemma decidable_eq_inr_neg {α : Type u} [h : decidable_eq α] {a b : α} : Π n : a ≠ b, h a b = is_false n := assume n, match (h a b) with | (is_true e) := absurd e n | (is_false n₁) := proof_irrel n n₁ ▸ eq.refl (is_false n) end /- inhabited -/ class inhabited (α : Type u) := (default : α) def default (α : Type u) [inhabited α] : α := inhabited.default α @[inline, irreducible] def arbitrary (α : Type u) [inhabited α] : α := default α instance prop.inhabited : inhabited Prop := ⟨true⟩ instance fun.inhabited (α : Type u) {β : Type v} [h : inhabited β] : inhabited (α → β) := inhabited.rec_on h (λ b, ⟨λ a, b⟩) instance pi.inhabited (α : Type u) {β : α → Type v} [Π x, inhabited (β x)] : inhabited (Π x, β x) := ⟨λ a, default (β a)⟩ instance : inhabited bool := ⟨ff⟩ instance : inhabited pos_num := ⟨pos_num.one⟩ instance : inhabited num := ⟨num.zero⟩ class inductive nonempty (α : Type u) : Prop | intro : α → nonempty protected def nonempty.elim {α : Type u} {p : Prop} (h₁ : nonempty α) (h₂ : α → p) : p := nonempty.rec h₂ h₁ instance nonempty_of_inhabited {α : Type u} [inhabited α] : nonempty α := ⟨default α⟩ lemma nonempty_of_exists {α : Type u} {p : α → Prop} : (∃ x, p x) → nonempty α | ⟨w, h⟩ := ⟨w⟩ /- subsingleton -/ class inductive subsingleton (α : Type u) : Prop | intro : (∀ a b : α, a = b) → subsingleton protected def subsingleton.elim {α : Type u} [h : subsingleton α] : ∀ (a b : α), a = b := subsingleton.rec (λ p, p) h protected def subsingleton.helim {α β : Type u} [h : subsingleton α] (h : α = β) : ∀ (a : α) (b : β), a == b := eq.rec_on h (λ a b : α, heq_of_eq (subsingleton.elim a b)) instance subsingleton_prop (p : Prop) : subsingleton p := ⟨λ a b, proof_irrel a b⟩ instance (p : Prop) : subsingleton (decidable p) := subsingleton.intro (λ d₁, match d₁ with | (is_true t₁) := (λ d₂, match d₂ with | (is_true t₂) := eq.rec_on (proof_irrel t₁ t₂) rfl | (is_false f₂) := absurd t₁ f₂ end) | (is_false f₁) := (λ d₂, match d₂ with | (is_true t₂) := absurd t₂ f₁ | (is_false f₂) := eq.rec_on (proof_irrel f₁ f₂) rfl end) end) protected lemma rec_subsingleton {p : Prop} [h : decidable p] {h₁ : p → Type u} {h₂ : ¬p → Type u} [h₃ : Π (h : p), subsingleton (h₁ h)] [h₄ : Π (h : ¬p), subsingleton (h₂ h)] : subsingleton (decidable.rec_on h h₂ h₁) := match h with | (is_true h) := h₃ h | (is_false h) := h₄ h end lemma if_pos {c : Prop} [h : decidable c] (hc : c) {α : Type u} {t e : α} : (ite c t e) = t := match h with | (is_true hc) := rfl | (is_false hnc) := absurd hc hnc end lemma if_neg {c : Prop} [h : decidable c] (hnc : ¬c) {α : Type u} {t e : α} : (ite c t e) = e := match h with | (is_true hc) := absurd hc hnc | (is_false hnc) := rfl end attribute [simp] lemma if_t_t (c : Prop) [h : decidable c] {α : Type u} (t : α) : (ite c t t) = t := match h with | (is_true hc) := rfl | (is_false hnc) := rfl end lemma implies_of_if_pos {c t e : Prop} [decidable c] (h : ite c t e) : c → t := assume hc, eq.rec_on (if_pos hc : ite c t e = t) h lemma implies_of_if_neg {c t e : Prop} [decidable c] (h : ite c t e) : ¬c → e := assume hnc, eq.rec_on (if_neg hnc : ite c t e = e) h lemma if_ctx_congr {α : Type u} {b c : Prop} [dec_b : decidable b] [dec_c : decidable c] {x y u v : α} (h_c : b ↔ c) (h_t : c → x = u) (h_e : ¬c → y = v) : ite b x y = ite c u v := match dec_b, dec_c with | (is_false h₁), (is_false h₂) := h_e h₂ | (is_true h₁), (is_true h₂) := h_t h₂ | (is_false h₁), (is_true h₂) := absurd h₂ (iff.mp (not_iff_not_of_iff h_c) h₁) | (is_true h₁), (is_false h₂) := absurd h₁ (iff.mpr (not_iff_not_of_iff h_c) h₂) end @[congr] lemma if_congr {α : Type u} {b c : Prop} [dec_b : decidable b] [dec_c : decidable c] {x y u v : α} (h_c : b ↔ c) (h_t : x = u) (h_e : y = v) : ite b x y = ite c u v := @if_ctx_congr α b c dec_b dec_c x y u v h_c (λ h, h_t) (λ h, h_e) lemma if_ctx_simp_congr {α : Type u} {b c : Prop} [dec_b : decidable b] {x y u v : α} (h_c : b ↔ c) (h_t : c → x = u) (h_e : ¬c → y = v) : ite b x y = (@ite c (decidable_of_decidable_of_iff dec_b h_c) α u v) := @if_ctx_congr α b c dec_b (decidable_of_decidable_of_iff dec_b h_c) x y u v h_c h_t h_e @[congr] lemma if_simp_congr {α : Type u} {b c : Prop} [dec_b : decidable b] {x y u v : α} (h_c : b ↔ c) (h_t : x = u) (h_e : y = v) : ite b x y = (@ite c (decidable_of_decidable_of_iff dec_b h_c) α u v) := @if_ctx_simp_congr α b c dec_b x y u v h_c (λ h, h_t) (λ h, h_e) @[simp] def if_true {α : Type u} {h : decidable true} (t e : α) : (@ite true h α t e) = t := if_pos trivial @[simp] def if_false {α : Type u} {h : decidable false} (t e : α) : (@ite false h α t e) = e := if_neg not_false lemma if_ctx_congr_prop {b c x y u v : Prop} [dec_b : decidable b] [dec_c : decidable c] (h_c : b ↔ c) (h_t : c → (x ↔ u)) (h_e : ¬c → (y ↔ v)) : ite b x y ↔ ite c u v := match dec_b, dec_c with | (is_false h₁), (is_false h₂) := h_e h₂ | (is_true h₁), (is_true h₂) := h_t h₂ | (is_false h₁), (is_true h₂) := absurd h₂ (iff.mp (not_iff_not_of_iff h_c) h₁) | (is_true h₁), (is_false h₂) := absurd h₁ (iff.mpr (not_iff_not_of_iff h_c) h₂) end @[congr] lemma if_congr_prop {b c x y u v : Prop} [dec_b : decidable b] [dec_c : decidable c] (h_c : b ↔ c) (h_t : x ↔ u) (h_e : y ↔ v) : ite b x y ↔ ite c u v := if_ctx_congr_prop h_c (λ h, h_t) (λ h, h_e) lemma if_ctx_simp_congr_prop {b c x y u v : Prop} [dec_b : decidable b] (h_c : b ↔ c) (h_t : c → (x ↔ u)) (h_e : ¬c → (y ↔ v)) : ite b x y ↔ (@ite c (decidable_of_decidable_of_iff dec_b h_c) Prop u v) := @if_ctx_congr_prop b c x y u v dec_b (decidable_of_decidable_of_iff dec_b h_c) h_c h_t h_e @[congr] lemma if_simp_congr_prop {b c x y u v : Prop} [dec_b : decidable b] (h_c : b ↔ c) (h_t : x ↔ u) (h_e : y ↔ v) : ite b x y ↔ (@ite c (decidable_of_decidable_of_iff dec_b h_c) Prop u v) := @if_ctx_simp_congr_prop b c x y u v dec_b h_c (λ h, h_t) (λ h, h_e) lemma dif_pos {c : Prop} [h : decidable c] (hc : c) {α : Type u} {t : c → α} {e : ¬ c → α} : dite c t e = t hc := match h with | (is_true hc) := rfl | (is_false hnc) := absurd hc hnc end lemma dif_neg {c : Prop} [h : decidable c] (hnc : ¬c) {α : Type u} {t : c → α} {e : ¬ c → α} : dite c t e = e hnc := match h with | (is_true hc) := absurd hc hnc | (is_false hnc) := rfl end lemma dif_ctx_congr {α : Type u} {b c : Prop} [dec_b : decidable b] [dec_c : decidable c] {x : b → α} {u : c → α} {y : ¬b → α} {v : ¬c → α} (h_c : b ↔ c) (h_t : ∀ (h : c), x (iff.mpr h_c h) = u h) (h_e : ∀ (h : ¬c), y (iff.mpr (not_iff_not_of_iff h_c) h) = v h) : (@dite b dec_b α x y) = (@dite c dec_c α u v) := match dec_b, dec_c with | (is_false h₁), (is_false h₂) := h_e h₂ | (is_true h₁), (is_true h₂) := h_t h₂ | (is_false h₁), (is_true h₂) := absurd h₂ (iff.mp (not_iff_not_of_iff h_c) h₁) | (is_true h₁), (is_false h₂) := absurd h₁ (iff.mpr (not_iff_not_of_iff h_c) h₂) end lemma dif_ctx_simp_congr {α : Type u} {b c : Prop} [dec_b : decidable b] {x : b → α} {u : c → α} {y : ¬b → α} {v : ¬c → α} (h_c : b ↔ c) (h_t : ∀ (h : c), x (iff.mpr h_c h) = u h) (h_e : ∀ (h : ¬c), y (iff.mpr (not_iff_not_of_iff h_c) h) = v h) : (@dite b dec_b α x y) = (@dite c (decidable_of_decidable_of_iff dec_b h_c) α u v) := @dif_ctx_congr α b c dec_b (decidable_of_decidable_of_iff dec_b h_c) x u y v h_c h_t h_e -- Remark: dite and ite are "defally equal" when we ignore the proofs. lemma dite_ite_eq (c : Prop) [h : decidable c] {α : Type u} (t : α) (e : α) : dite c (λ h, t) (λ h, e) = ite c t e := match h with | (is_true hc) := rfl | (is_false hnc) := rfl end def as_true (c : Prop) [decidable c] : Prop := if c then true else false def as_false (c : Prop) [decidable c] : Prop := if c then false else true def of_as_true {c : Prop} [h₁ : decidable c] (h₂ : as_true c) : c := match h₁, h₂ with | (is_true h_c), h₂ := h_c | (is_false h_c), h₂ := false.elim h₂ end /- Universe lifting operation -/ structure {r s} ulift (α : Type s) : Type (max 1 s r) := up :: (down : α) namespace ulift /- βijection between α and ulift.{v} α -/ lemma up_down {α : Type u} : ∀ (b : ulift.{v} α), up (down b) = b | (up a) := rfl lemma down_up {α : Type u} (a : α) : down (up.{v} a) = a := rfl end ulift /- Equalities for rewriting let-expressions -/ lemma let_value_eq {α : Type u} {β : Type v} {a₁ a₂ : α} (b : α → β) : a₁ = a₂ → (let x : α := a₁ in b x) = (let x : α := a₂ in b x) := λ h, eq.rec_on h rfl lemma let_value_heq {α : Type v} {β : α → Type u} {a₁ a₂ : α} (b : Π x : α, β x) : a₁ = a₂ → (let x : α := a₁ in b x) == (let x : α := a₂ in b x) := λ h, eq.rec_on h (heq.refl (b a₁)) lemma let_body_eq {α : Type v} {β : α → Type u} (a : α) {b₁ b₂ : Π x : α, β x} : (∀ x, b₁ x = b₂ x) → (let x : α := a in b₁ x) = (let x : α := a in b₂ x) := λ h, h a lemma let_eq {α : Type v} {β : Type u} {a₁ a₂ : α} {b₁ b₂ : α → β} : a₁ = a₂ → (∀ x, b₁ x = b₂ x) → (let x : α := a₁ in b₁ x) = (let x : α := a₂ in b₂ x) := λ h₁ h₂, eq.rec_on h₁ (h₂ a₁) section relation variables {α : Type u} {β : Type v} (r : β → β → Prop) local infix `≺`:50 := r def reflexive := ∀ x, x ≺ x def symmetric := ∀ ⦃x y⦄, x ≺ y → y ≺ x def transitive := ∀ ⦃x y z⦄, x ≺ y → y ≺ z → x ≺ z def equivalence := reflexive r ∧ symmetric r ∧ transitive r def total := ∀ x y, x ≺ y ∨ y ≺ x def mk_equivalence (rfl : reflexive r) (symm : symmetric r) (trans : transitive r) : equivalence r := ⟨rfl, symm, trans⟩ def irreflexive := ∀ x, ¬ x ≺ x def anti_symmetric := ∀ ⦃x y⦄, x ≺ y → y ≺ x → x = y def empty_relation := λ a₁ a₂ : α, false def subrelation (q r : β → β → Prop) := ∀ ⦃x y⦄, q x y → r x y def inv_image (f : α → β) : α → α → Prop := λ a₁ a₂, f a₁ ≺ f a₂ lemma inv_image.trans (f : α → β) (h : transitive r) : transitive (inv_image r f) := λ (a₁ a₂ a₃ : α) (h₁ : inv_image r f a₁ a₂) (h₂ : inv_image r f a₂ a₃), h h₁ h₂ lemma inv_image.irreflexive (f : α → β) (h : irreflexive r) : irreflexive (inv_image r f) := λ (a : α) (h₁ : inv_image r f a a), h (f a) h₁ inductive tc {α : Type u} (r : α → α → Prop) : α → α → Prop | base : ∀ a b, r a b → tc a b | trans : ∀ a b c, tc a b → tc b c → tc a c end relation section binary variables {α : Type u} {β : Type v} variable f : α → α → α variable inv : α → α variable one : α local notation a * b := f a b local notation a ⁻¹ := inv a variable g : α → α → α local notation a + b := g a b def commutative := ∀ a b, a * b = b * a def associative := ∀ a b c, (a * b) * c = a * (b * c) def left_identity := ∀ a, one * a = a def right_identity := ∀ a, a * one = a def right_inverse := ∀ a, a * a⁻¹ = one def left_cancelative := ∀ a b c, a * b = a * c → b = c def right_cancelative := ∀ a b c, a * b = c * b → a = c def left_distributive := ∀ a b c, a * (b + c) = a * b + a * c def right_distributive := ∀ a b c, (a + b) * c = a * c + b * c def right_commutative (h : β → α → β) := ∀ b a₁ a₂, h (h b a₁) a₂ = h (h b a₂) a₁ def left_commutative (h : α → β → β) := ∀ a₁ a₂ b, h a₁ (h a₂ b) = h a₂ (h a₁ b) lemma left_comm : commutative f → associative f → left_commutative f := assume hcomm hassoc, take a b c, calc a*(b*c) = (a*b)*c : eq.symm (hassoc a b c) ... = (b*a)*c : hcomm a b ▸ rfl ... = b*(a*c) : hassoc b a c lemma right_comm : commutative f → associative f → right_commutative f := assume hcomm hassoc, take a b c, calc (a*b)*c = a*(b*c) : hassoc a b c ... = a*(c*b) : hcomm b c ▸ rfl ... = (a*c)*b : eq.symm (hassoc a c b) end binary
306e72ac0ebb4a710c27ab1b5794fed4e19f1a95
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/data/fintype/basic.lean
29319a29fe413b63dd239cea698f04c41266bcdb
[ "Apache-2.0" ]
permissive
JLimperg/aesop3
306cc6570c556568897ed2e508c8869667252e8a
a4a116f650cc7403428e72bd2e2c4cda300fe03f
refs/heads/master
1,682,884,916,368
1,620,320,033,000
1,620,320,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
63,919
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Finite types. -/ import tactic.wlog import data.finset.powerset import data.finset.lattice import data.finset.pi import data.array.lemmas import order.well_founded import group_theory.perm.basic open_locale nat universes u v variables {α : Type*} {β : Type*} {γ : Type*} /-- `fintype α` means that `α` is finite, i.e. there are only finitely many distinct elements of type `α`. The evidence of this is a finset `elems` (a list up to permutation without duplicates), together with a proof that everything of type `α` is in the list. -/ class fintype (α : Type*) := (elems [] : finset α) (complete : ∀ x : α, x ∈ elems) namespace finset variable [fintype α] /-- `univ` is the universal finite set of type `finset α` implied from the assumption `fintype α`. -/ def univ : finset α := fintype.elems α @[simp] theorem mem_univ (x : α) : x ∈ (univ : finset α) := fintype.complete x @[simp] theorem mem_univ_val : ∀ x, x ∈ (univ : finset α).1 := mem_univ @[simp] lemma coe_univ : ↑(univ : finset α) = (set.univ : set α) := by ext; simp lemma univ_nonempty_iff : (univ : finset α).nonempty ↔ nonempty α := by rw [← coe_nonempty, coe_univ, set.nonempty_iff_univ_nonempty] lemma univ_nonempty [nonempty α] : (univ : finset α).nonempty := univ_nonempty_iff.2 ‹_› lemma univ_eq_empty : (univ : finset α) = ∅ ↔ ¬nonempty α := by rw [← univ_nonempty_iff, nonempty_iff_ne_empty, ne.def, not_not] @[simp] theorem subset_univ (s : finset α) : s ⊆ univ := λ a _, mem_univ a instance : order_top (finset α) := { top := univ, le_top := subset_univ, .. finset.partial_order } instance [decidable_eq α] : boolean_algebra (finset α) := { compl := λ s, univ \ s, inf_compl_le_bot := λ s x hx, by simpa using hx, top_le_sup_compl := λ s x hx, by simp, sdiff_eq := λ s t, by simp [ext_iff, compl], ..finset.order_top, ..finset.generalized_boolean_algebra } lemma compl_eq_univ_sdiff [decidable_eq α] (s : finset α) : sᶜ = univ \ s := rfl @[simp] lemma mem_compl [decidable_eq α] {s : finset α} {x : α} : x ∈ sᶜ ↔ x ∉ s := by simp [compl_eq_univ_sdiff] @[simp, norm_cast] lemma coe_compl [decidable_eq α] (s : finset α) : ↑(sᶜ) = (↑s : set α)ᶜ := set.ext $ λ x, mem_compl @[simp] theorem union_compl [decidable_eq α] (s : finset α) : s ∪ sᶜ = finset.univ := sup_compl_eq_top @[simp] lemma compl_filter [decidable_eq α] (p : α → Prop) [decidable_pred p] [Π x, decidable (¬p x)] : (univ.filter p)ᶜ = univ.filter (λ x, ¬p x) := (filter_not _ _).symm theorem eq_univ_iff_forall {s : finset α} : s = univ ↔ ∀ x, x ∈ s := by simp [ext_iff] lemma compl_ne_univ_iff_nonempty [decidable_eq α] (s : finset α) : sᶜ ≠ univ ↔ s.nonempty := by simp [eq_univ_iff_forall, finset.nonempty] @[simp] lemma univ_inter [decidable_eq α] (s : finset α) : univ ∩ s = s := ext $ λ a, by simp @[simp] lemma inter_univ [decidable_eq α] (s : finset α) : s ∩ univ = s := by rw [inter_comm, univ_inter] @[simp] lemma piecewise_univ [∀i : α, decidable (i ∈ (univ : finset α))] {δ : α → Sort*} (f g : Πi, δ i) : univ.piecewise f g = f := by { ext i, simp [piecewise] } lemma piecewise_compl [decidable_eq α] (s : finset α) [Π i : α, decidable (i ∈ s)] [Π i : α, decidable (i ∈ sᶜ)] {δ : α → Sort*} (f g : Π i, δ i) : sᶜ.piecewise f g = s.piecewise g f := by { ext i, simp [piecewise] } lemma univ_map_equiv_to_embedding {α β : Type*} [fintype α] [fintype β] (e : α ≃ β) : univ.map e.to_embedding = univ := begin apply eq_univ_iff_forall.mpr, intro b, rw [mem_map], use e.symm b, simp, end @[simp] lemma univ_filter_exists (f : α → β) [fintype β] [decidable_pred (λ y, ∃ x, f x = y)] [decidable_eq β] : finset.univ.filter (λ y, ∃ x, f x = y) = finset.univ.image f := by { ext, simp } /-- Note this is a special case of `(finset.image_preimage f univ _).symm`. -/ lemma univ_filter_mem_range (f : α → β) [fintype β] [decidable_pred (λ y, y ∈ set.range f)] [decidable_eq β] : finset.univ.filter (λ y, y ∈ set.range f) = finset.univ.image f := univ_filter_exists f end finset open finset function namespace fintype instance decidable_pi_fintype {α} {β : α → Type*} [∀a, decidable_eq (β a)] [fintype α] : decidable_eq (Πa, β a) := assume f g, decidable_of_iff (∀ a ∈ fintype.elems α, f a = g a) (by simp [function.funext_iff, fintype.complete]) instance decidable_forall_fintype {p : α → Prop} [decidable_pred p] [fintype α] : decidable (∀ a, p a) := decidable_of_iff (∀ a ∈ @univ α _, p a) (by simp) instance decidable_exists_fintype {p : α → Prop} [decidable_pred p] [fintype α] : decidable (∃ a, p a) := decidable_of_iff (∃ a ∈ @univ α _, p a) (by simp) instance decidable_mem_range_fintype [fintype α] [decidable_eq β] (f : α → β) : decidable_pred (∈ set.range f) := λ x, fintype.decidable_exists_fintype section bundled_homs instance decidable_eq_equiv_fintype [decidable_eq β] [fintype α] : decidable_eq (α ≃ β) := λ a b, decidable_of_iff (a.1 = b.1) equiv.coe_fn_injective.eq_iff instance decidable_eq_embedding_fintype [decidable_eq β] [fintype α] : decidable_eq (α ↪ β) := λ a b, decidable_of_iff (⇑a = b) function.embedding.coe_injective.eq_iff @[to_additive] instance decidable_eq_one_hom_fintype [decidable_eq β] [fintype α] [has_one α] [has_one β]: decidable_eq (one_hom α β) := λ a b, decidable_of_iff (⇑a = b) (injective.eq_iff one_hom.coe_inj) @[to_additive] instance decidable_eq_mul_hom_fintype [decidable_eq β] [fintype α] [has_mul α] [has_mul β]: decidable_eq (mul_hom α β) := λ a b, decidable_of_iff (⇑a = b) (injective.eq_iff mul_hom.coe_inj) @[to_additive] instance decidable_eq_monoid_hom_fintype [decidable_eq β] [fintype α] [mul_one_class α] [mul_one_class β]: decidable_eq (α →* β) := λ a b, decidable_of_iff (⇑a = b) (injective.eq_iff monoid_hom.coe_inj) instance decidable_eq_monoid_with_zero_hom_fintype [decidable_eq β] [fintype α] [mul_zero_one_class α] [mul_zero_one_class β]: decidable_eq (monoid_with_zero_hom α β) := λ a b, decidable_of_iff (⇑a = b) (injective.eq_iff monoid_with_zero_hom.coe_inj) instance decidable_eq_ring_hom_fintype [decidable_eq β] [fintype α] [semiring α] [semiring β]: decidable_eq (α →+* β) := λ a b, decidable_of_iff (⇑a = b) (injective.eq_iff ring_hom.coe_inj) end bundled_homs instance decidable_injective_fintype [decidable_eq α] [decidable_eq β] [fintype α] : decidable_pred (injective : (α → β) → Prop) := λ x, by unfold injective; apply_instance instance decidable_surjective_fintype [decidable_eq β] [fintype α] [fintype β] : decidable_pred (surjective : (α → β) → Prop) := λ x, by unfold surjective; apply_instance instance decidable_bijective_fintype [decidable_eq α] [decidable_eq β] [fintype α] [fintype β] : decidable_pred (bijective : (α → β) → Prop) := λ x, by unfold bijective; apply_instance instance decidable_right_inverse_fintype [decidable_eq α] [fintype α] (f : α → β) (g : β → α) : decidable (function.right_inverse f g) := show decidable (∀ x, g (f x) = x), by apply_instance instance decidable_left_inverse_fintype [decidable_eq β] [fintype β] (f : α → β) (g : β → α) : decidable (function.left_inverse f g) := show decidable (∀ x, f (g x) = x), by apply_instance lemma exists_max [fintype α] [nonempty α] {β : Type*} [linear_order β] (f : α → β) : ∃ x₀ : α, ∀ x, f x ≤ f x₀ := by simpa using exists_max_image univ f univ_nonempty lemma exists_min [fintype α] [nonempty α] {β : Type*} [linear_order β] (f : α → β) : ∃ x₀ : α, ∀ x, f x₀ ≤ f x := by simpa using exists_min_image univ f univ_nonempty /-- Construct a proof of `fintype α` from a universal multiset -/ def of_multiset [decidable_eq α] (s : multiset α) (H : ∀ x : α, x ∈ s) : fintype α := ⟨s.to_finset, by simpa using H⟩ /-- Construct a proof of `fintype α` from a universal list -/ def of_list [decidable_eq α] (l : list α) (H : ∀ x : α, x ∈ l) : fintype α := ⟨l.to_finset, by simpa using H⟩ theorem exists_univ_list (α) [fintype α] : ∃ l : list α, l.nodup ∧ ∀ x : α, x ∈ l := let ⟨l, e⟩ := quotient.exists_rep (@univ α _).1 in by have := and.intro univ.2 mem_univ_val; exact ⟨_, by rwa ← e at this⟩ /-- `card α` is the number of elements in `α`, defined when `α` is a fintype. -/ def card (α) [fintype α] : ℕ := (@univ α _).card /-- If `l` lists all the elements of `α` without duplicates, then `α ≃ fin (l.length)`. -/ def equiv_fin_of_forall_mem_list {α} [decidable_eq α] {l : list α} (h : ∀ x:α, x ∈ l) (nd : l.nodup) : α ≃ fin (l.length) := ⟨λ a, ⟨_, list.index_of_lt_length.2 (h a)⟩, λ i, l.nth_le i.1 i.2, λ a, by simp, λ ⟨i, h⟩, fin.eq_of_veq $ list.nodup_iff_nth_le_inj.1 nd _ _ (list.index_of_lt_length.2 (list.nth_le_mem _ _ _)) h $ by simp⟩ /-- There is (computably) a bijection between `α` and `fin (card α)`. Since it is not unique, and depends on which permutation of the universe list is used, the bijection is wrapped in `trunc` to preserve computability. See `fintype.equiv_fin` for the noncomputable version, and `fintype.trunc_equiv_fin_of_card_eq` and `fintype.equiv_fin_of_card_eq` for an equiv `α ≃ fin n` given `fintype.card α = n`. -/ def trunc_equiv_fin (α) [decidable_eq α] [fintype α] : trunc (α ≃ fin (card α)) := by unfold card finset.card; exact quot.rec_on_subsingleton (@univ α _).1 (λ l (h : ∀ x:α, x ∈ l) (nd : l.nodup), trunc.mk (equiv_fin_of_forall_mem_list h nd)) mem_univ_val univ.2 /-- There is a (noncomputable) bijection between `α` and `fin (card α)`. See `fintype.trunc_equiv_fin` for the computable version, and `fintype.trunc_equiv_fin_of_card_eq` and `fintype.equiv_fin_of_card_eq` for an equiv `α ≃ fin n` given `fintype.card α = n`. -/ noncomputable def equiv_fin (α) [fintype α] : α ≃ fin (card α) := by { letI := classical.dec_eq α, exact (trunc_equiv_fin α).out } instance (α : Type*) : subsingleton (fintype α) := ⟨λ ⟨s₁, h₁⟩ ⟨s₂, h₂⟩, by congr; simp [finset.ext_iff, h₁, h₂]⟩ /-- Given a predicate that can be represented by a finset, the subtype associated to the predicate is a fintype. -/ protected def subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) : fintype {x // p x} := ⟨⟨multiset.pmap subtype.mk s.1 (λ x, (H x).1), multiset.nodup_pmap (λ a _ b _, congr_arg subtype.val) s.2⟩, λ ⟨x, px⟩, multiset.mem_pmap.2 ⟨x, (H x).2 px, rfl⟩⟩ theorem subtype_card {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) : @card {x // p x} (fintype.subtype s H) = s.card := multiset.card_pmap _ _ _ theorem card_of_subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) [fintype {x // p x}] : card {x // p x} = s.card := by { rw ← subtype_card s H, congr } /-- Construct a fintype from a finset with the same elements. -/ def of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : fintype p := fintype.subtype s H @[simp] theorem card_of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : @fintype.card p (of_finset s H) = s.card := fintype.subtype_card s H theorem card_of_finset' {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) [fintype p] : fintype.card p = s.card := by rw ← card_of_finset s H; congr /-- If `f : α → β` is a bijection and `α` is a fintype, then `β` is also a fintype. -/ def of_bijective [fintype α] (f : α → β) (H : function.bijective f) : fintype β := ⟨univ.map ⟨f, H.1⟩, λ b, let ⟨a, e⟩ := H.2 b in e ▸ mem_map_of_mem _ (mem_univ _)⟩ /-- If `f : α → β` is a surjection and `α` is a fintype, then `β` is also a fintype. -/ def of_surjective [decidable_eq β] [fintype α] (f : α → β) (H : function.surjective f) : fintype β := ⟨univ.image f, λ b, let ⟨a, e⟩ := H b in e ▸ mem_image_of_mem _ (mem_univ _)⟩ end fintype section inv namespace function variables [fintype α] [decidable_eq β] namespace injective variables {f : α → β} (hf : function.injective f) /-- The inverse of an `hf : injective` function `f : α → β`, of the type `↥(set.range f) → α`. This is the computable version of `function.inv_fun` that requires `fintype α` and `decidable_eq β`, or the function version of applying `(equiv.of_injective f hf).symm`. This function should not usually be used for actual computation because for most cases, an explicit inverse can be stated that has better computational properties. This function computes by checking all terms `a : α` to find the `f a = b`, so it is O(N) where `N = fintype.card α`. -/ def inv_of_mem_range : set.range f → α := λ b, finset.choose (λ a, f a = b) finset.univ ((exists_unique_congr (by simp)).mp (hf.exists_unique_of_mem_range b.property)) lemma left_inv_of_inv_of_mem_range (b : set.range f) : f (hf.inv_of_mem_range b) = b := (finset.choose_spec (λ a, f a = b) _ _).right @[simp] lemma right_inv_of_inv_of_mem_range (a : α) : hf.inv_of_mem_range (⟨f a, set.mem_range_self a⟩) = a := hf (finset.choose_spec (λ a', f a' = f a) _ _).right lemma inv_fun_restrict [nonempty α] : (set.range f).restrict (inv_fun f) = hf.inv_of_mem_range := begin ext ⟨b, h⟩, apply hf, simp [hf.left_inv_of_inv_of_mem_range, @inv_fun_eq _ _ _ f b (set.mem_range.mp h)] end lemma inv_of_mem_range_surjective : function.surjective hf.inv_of_mem_range := λ a, ⟨⟨f a, set.mem_range_self a⟩, by simp⟩ end injective namespace embedding variables (f : α ↪ β) (b : set.range f) /-- The inverse of an embedding `f : α ↪ β`, of the type `↥(set.range f) → α`. This is the computable version of `function.inv_fun` that requires `fintype α` and `decidable_eq β`, or the function version of applying `(equiv.of_injective f f.injective).symm`. This function should not usually be used for actual computation because for most cases, an explicit inverse can be stated that has better computational properties. This function computes by checking all terms `a : α` to find the `f a = b`, so it is O(N) where `N = fintype.card α`. -/ def inv_of_mem_range : α := f.injective.inv_of_mem_range b @[simp] lemma left_inv_of_inv_of_mem_range : f (f.inv_of_mem_range b) = b := f.injective.left_inv_of_inv_of_mem_range b @[simp] lemma right_inv_of_inv_of_mem_range (a : α) : f.inv_of_mem_range ⟨f a, set.mem_range_self a⟩ = a := f.injective.right_inv_of_inv_of_mem_range a lemma inv_fun_restrict [nonempty α] : (set.range f).restrict (inv_fun f) = f.inv_of_mem_range := begin ext ⟨b, h⟩, apply f.injective, simp [f.left_inv_of_inv_of_mem_range, @inv_fun_eq _ _ _ f b (set.mem_range.mp h)] end lemma inv_of_mem_range_surjective : function.surjective f.inv_of_mem_range := λ a, ⟨⟨f a, set.mem_range_self a⟩, by simp⟩ end embedding end function end inv namespace fintype /-- Given an injective function to a fintype, the domain is also a fintype. This is noncomputable because injectivity alone cannot be used to construct preimages. -/ noncomputable def of_injective [fintype β] (f : α → β) (H : function.injective f) : fintype α := by letI := classical.dec; exact if hα : nonempty α then by letI := classical.inhabited_of_nonempty hα; exact of_surjective (inv_fun f) (inv_fun_surjective H) else ⟨∅, λ x, (hα ⟨x⟩).elim⟩ /-- If `f : α ≃ β` and `α` is a fintype, then `β` is also a fintype. -/ def of_equiv (α : Type*) [fintype α] (f : α ≃ β) : fintype β := of_bijective _ f.bijective theorem of_equiv_card [fintype α] (f : α ≃ β) : @card β (of_equiv α f) = card α := multiset.card_map _ _ theorem card_congr {α β} [fintype α] [fintype β] (f : α ≃ β) : card α = card β := by rw ← of_equiv_card f; congr section variables [fintype α] [fintype β] /-- If the cardinality of `α` is `n`, there is computably a bijection between `α` and `fin n`. See `fintype.equiv_fin_of_card_eq` for the noncomputable definition, and `fintype.trunc_equiv_fin` and `fintype.equiv_fin` for the bijection `α ≃ fin (card α)`. -/ def trunc_equiv_fin_of_card_eq [decidable_eq α] {n : ℕ} (h : fintype.card α = n) : trunc (α ≃ fin n) := (trunc_equiv_fin α).map (λ e, e.trans (fin.cast h).to_equiv) /-- If the cardinality of `α` is `n`, there is noncomputably a bijection between `α` and `fin n`. See `fintype.trunc_equiv_fin_of_card_eq` for the computable definition, and `fintype.trunc_equiv_fin` and `fintype.equiv_fin` for the bijection `α ≃ fin (card α)`. -/ noncomputable def equiv_fin_of_card_eq {n : ℕ} (h : fintype.card α = n) : α ≃ fin n := by { letI := classical.dec_eq α, exact (trunc_equiv_fin_of_card_eq h).out } /-- Two `fintype`s with the same cardinality are (computably) in bijection. See `fintype.equiv_of_card_eq` for the noncomputable version, and `fintype.trunc_equiv_fin_of_card_eq` and `fintype.equiv_fin_of_card_eq` for the specialization to `fin`. -/ def trunc_equiv_of_card_eq [decidable_eq α] [decidable_eq β] (h : card α = card β) : trunc (α ≃ β) := (trunc_equiv_fin_of_card_eq h).bind (λ e, (trunc_equiv_fin β).map (λ e', e.trans e'.symm)) /-- Two `fintype`s with the same cardinality are (noncomputably) in bijection. See `fintype.trunc_equiv_of_card_eq` for the computable version, and `fintype.trunc_equiv_fin_of_card_eq` and `fintype.equiv_fin_of_card_eq` for the specialization to `fin`. -/ noncomputable def equiv_of_card_eq (h : card α = card β) : α ≃ β := by { letI := classical.dec_eq α, letI := classical.dec_eq β, exact (trunc_equiv_of_card_eq h).out } end theorem card_eq {α β} [F : fintype α] [G : fintype β] : card α = card β ↔ nonempty (α ≃ β) := ⟨λ h, by { haveI := classical.prop_decidable, exact (trunc_equiv_of_card_eq h).nonempty }, λ ⟨f⟩, card_congr f⟩ /-- Any subsingleton type with a witness is a fintype (with one term). -/ def of_subsingleton (a : α) [subsingleton α] : fintype α := ⟨{a}, λ b, finset.mem_singleton.2 (subsingleton.elim _ _)⟩ @[simp] theorem univ_of_subsingleton (a : α) [subsingleton α] : @univ _ (of_subsingleton a) = {a} := rfl /-- Note: this lemma is specifically about `fintype.of_subsingleton`. For a statement about arbitrary `fintype` instances, use either `fintype.card_le_one_iff_subsingleton` or `fintype.card_unique`. -/ @[simp] theorem card_of_subsingleton (a : α) [subsingleton α] : @fintype.card _ (of_subsingleton a) = 1 := rfl @[simp] theorem card_unique [unique α] [h : fintype α] : fintype.card α = 1 := subsingleton.elim (of_subsingleton $ default α) h ▸ card_of_subsingleton _ open_locale classical variables (α) /-- Any subsingleton type is (noncomputably) a fintype (with zero or one terms). -/ @[priority 100] noncomputable instance of_subsingleton' [subsingleton α] : fintype α := if h : nonempty α then of_subsingleton (nonempty.some h) else ⟨∅, (λ a, false.elim (h ⟨a⟩))⟩ end fintype namespace set /-- Construct a finset enumerating a set `s`, given a `fintype` instance. -/ def to_finset (s : set α) [fintype s] : finset α := ⟨(@finset.univ s _).1.map subtype.val, multiset.nodup_map (λ a b, subtype.eq) finset.univ.2⟩ @[simp] theorem mem_to_finset {s : set α} [fintype s] {a : α} : a ∈ s.to_finset ↔ a ∈ s := by simp [to_finset] @[simp] theorem mem_to_finset_val {s : set α} [fintype s] {a : α} : a ∈ s.to_finset.1 ↔ a ∈ s := mem_to_finset -- We use an arbitrary `[fintype s]` instance here, -- not necessarily coming from a `[fintype α]`. @[simp] lemma to_finset_card {α : Type*} (s : set α) [fintype s] : s.to_finset.card = fintype.card s := multiset.card_map subtype.val finset.univ.val @[simp] theorem coe_to_finset (s : set α) [fintype s] : (↑s.to_finset : set α) = s := set.ext $ λ _, mem_to_finset @[simp] theorem to_finset_inj {s t : set α} [fintype s] [fintype t] : s.to_finset = t.to_finset ↔ s = t := ⟨λ h, by rw [← s.coe_to_finset, h, t.coe_to_finset], λ h, by simp [h]; congr⟩ @[simp, mono] theorem to_finset_mono {s t : set α} [fintype s] [fintype t] : s.to_finset ⊆ t.to_finset ↔ s ⊆ t := by simp [finset.subset_iff, set.subset_def] @[simp, mono] theorem to_finset_strict_mono {s t : set α} [fintype s] [fintype t] : s.to_finset ⊂ t.to_finset ↔ s ⊂ t := begin rw [←lt_eq_ssubset, ←finset.lt_iff_ssubset, lt_iff_le_and_ne, lt_iff_le_and_ne], simp end @[simp] theorem to_finset_disjoint_iff [decidable_eq α] {s t : set α} [fintype s] [fintype t] : disjoint s.to_finset t.to_finset ↔ disjoint s t := ⟨λ h x hx, h (by simpa using hx), λ h x hx, h (by simpa using hx)⟩ end set lemma finset.card_univ [fintype α] : (finset.univ : finset α).card = fintype.card α := rfl lemma finset.eq_univ_of_card [fintype α] (s : finset α) (hs : s.card = fintype.card α) : s = univ := eq_of_subset_of_card_le (subset_univ _) $ by rw [hs, finset.card_univ] lemma finset.card_eq_iff_eq_univ [fintype α] (s : finset α) : s.card = fintype.card α ↔ s = finset.univ := ⟨s.eq_univ_of_card, by { rintro rfl, exact finset.card_univ, }⟩ lemma finset.card_le_univ [fintype α] (s : finset α) : s.card ≤ fintype.card α := card_le_of_subset (subset_univ s) lemma finset.card_lt_univ_of_not_mem [fintype α] {s : finset α} {x : α} (hx : x ∉ s) : s.card < fintype.card α := card_lt_card ⟨subset_univ s, not_forall.2 ⟨x, λ hx', hx (hx' $ mem_univ x)⟩⟩ lemma finset.card_lt_iff_ne_univ [fintype α] (s : finset α) : s.card < fintype.card α ↔ s ≠ finset.univ := s.card_le_univ.lt_iff_ne.trans (not_iff_not_of_iff s.card_eq_iff_eq_univ) lemma finset.card_compl_lt_iff_nonempty [fintype α] [decidable_eq α] (s : finset α) : sᶜ.card < fintype.card α ↔ s.nonempty := sᶜ.card_lt_iff_ne_univ.trans s.compl_ne_univ_iff_nonempty lemma finset.card_univ_diff [decidable_eq α] [fintype α] (s : finset α) : (finset.univ \ s).card = fintype.card α - s.card := finset.card_sdiff (subset_univ s) lemma finset.card_compl [decidable_eq α] [fintype α] (s : finset α) : sᶜ.card = fintype.card α - s.card := finset.card_univ_diff s instance (n : ℕ) : fintype (fin n) := ⟨finset.fin_range n, finset.mem_fin_range⟩ lemma fin.univ_def (n : ℕ) : (univ : finset (fin n)) = finset.fin_range n := rfl @[simp] theorem fintype.card_fin (n : ℕ) : fintype.card (fin n) = n := list.length_fin_range n @[simp] lemma finset.card_fin (n : ℕ) : finset.card (finset.univ : finset (fin n)) = n := by rw [finset.card_univ, fintype.card_fin] lemma card_finset_fin_le {n : ℕ} (s : finset (fin n)) : s.card ≤ n := by simpa only [fintype.card_fin] using s.card_le_univ lemma fin.equiv_iff_eq {m n : ℕ} : nonempty (fin m ≃ fin n) ↔ m = n := ⟨λ ⟨h⟩, by simpa using fintype.card_congr h, λ h, ⟨equiv.cast $ h ▸ rfl ⟩ ⟩ /-- Embed `fin n` into `fin (n + 1)` by prepending zero to the `univ` -/ lemma fin.univ_succ (n : ℕ) : (univ : finset (fin (n + 1))) = insert 0 (univ.image fin.succ) := begin ext m, simp only [mem_univ, mem_insert, true_iff, mem_image, exists_prop], exact fin.cases (or.inl rfl) (λ i, or.inr ⟨i, trivial, rfl⟩) m end /-- Embed `fin n` into `fin (n + 1)` by appending a new `fin.last n` to the `univ` -/ lemma fin.univ_cast_succ (n : ℕ) : (univ : finset (fin (n + 1))) = insert (fin.last n) (univ.image fin.cast_succ) := begin ext m, simp only [mem_univ, mem_insert, true_iff, mem_image, exists_prop, true_and], by_cases h : m.val < n, { right, use fin.cast_lt m h, rw fin.cast_succ_cast_lt }, { left, exact fin.eq_last_of_not_lt h } end /-- Embed `fin n` into `fin (n + 1)` by inserting around a specified pivot `p : fin (n + 1)` into the `univ` -/ lemma fin.univ_succ_above (n : ℕ) (p : fin (n + 1)) : (univ : finset (fin (n + 1))) = insert p (univ.image (fin.succ_above p)) := begin rcases lt_or_eq_of_le (fin.le_last p) with hl|rfl, { ext m, simp only [finset.mem_univ, finset.mem_insert, true_iff, finset.mem_image, exists_prop], refine or_iff_not_imp_left.mpr _, { intro h, cases n, { have : m = p := by simp, exact absurd this h }, use p.cast_pred.pred_above m, { rw fin.pred_above, split_ifs with H, { simp only [fin.coe_cast_succ, true_and, fin.coe_coe_eq_self, coe_coe], rw fin.lt_last_iff_coe_cast_pred at hl, rw fin.succ_above_above, { simp }, { simp only [fin.lt_iff_coe_lt_coe, fin.coe_cast_succ] at H, simpa [fin.le_iff_coe_le_coe, ←hl] using nat.le_pred_of_lt H } }, { rw fin.succ_above_below, { simp }, { simp only [fin.cast_succ_cast_pred hl, not_lt] at H, simpa using lt_of_le_of_ne H h, } } } } }, { rw fin.succ_above_last, exact fin.univ_cast_succ n } end @[instance, priority 10] def unique.fintype {α : Type*} [unique α] : fintype α := fintype.of_subsingleton (default α) @[simp] lemma univ_unique {α : Type*} [unique α] [f : fintype α] : @finset.univ α _ = {default α} := by rw [subsingleton.elim f (@unique.fintype α _)]; refl instance : fintype empty := ⟨∅, empty.rec _⟩ @[simp] theorem fintype.univ_empty : @univ empty _ = ∅ := rfl @[simp] theorem fintype.card_empty : fintype.card empty = 0 := rfl instance : fintype pempty := ⟨∅, pempty.rec _⟩ @[simp] theorem fintype.univ_pempty : @univ pempty _ = ∅ := rfl @[simp] theorem fintype.card_pempty : fintype.card pempty = 0 := rfl instance : fintype unit := fintype.of_subsingleton () theorem fintype.univ_unit : @univ unit _ = {()} := rfl theorem fintype.card_unit : fintype.card unit = 1 := rfl instance : fintype punit := fintype.of_subsingleton punit.star @[simp] theorem fintype.univ_punit : @univ punit _ = {punit.star} := rfl @[simp] theorem fintype.card_punit : fintype.card punit = 1 := rfl instance : fintype bool := ⟨⟨tt ::ₘ ff ::ₘ 0, by simp⟩, λ x, by cases x; simp⟩ @[simp] theorem fintype.univ_bool : @univ bool _ = {tt, ff} := rfl instance units_int.fintype : fintype (units ℤ) := ⟨{1, -1}, λ x, by cases int.units_eq_one_or x; simp *⟩ instance additive.fintype : Π [fintype α], fintype (additive α) := id instance multiplicative.fintype : Π [fintype α], fintype (multiplicative α) := id @[simp] theorem fintype.card_units_int : fintype.card (units ℤ) = 2 := rfl noncomputable instance [monoid α] [fintype α] : fintype (units α) := by classical; exact fintype.of_injective units.val units.ext @[simp] theorem fintype.card_bool : fintype.card bool = 2 := rfl /-- Given a finset on `α`, lift it to being a finset on `option α` using `option.some` and then insert `option.none`. -/ def finset.insert_none (s : finset α) : finset (option α) := ⟨none ::ₘ s.1.map some, multiset.nodup_cons.2 ⟨by simp, multiset.nodup_map (λ a b, option.some.inj) s.2⟩⟩ @[simp] theorem finset.mem_insert_none {s : finset α} : ∀ {o : option α}, o ∈ s.insert_none ↔ ∀ a ∈ o, a ∈ s | none := iff_of_true (multiset.mem_cons_self _ _) (λ a h, by cases h) | (some a) := multiset.mem_cons.trans $ by simp; refl theorem finset.some_mem_insert_none {s : finset α} {a : α} : some a ∈ s.insert_none ↔ a ∈ s := by simp instance {α : Type*} [fintype α] : fintype (option α) := ⟨univ.insert_none, λ a, by simp⟩ @[simp] theorem fintype.card_option {α : Type*} [fintype α] : fintype.card (option α) = fintype.card α + 1 := (multiset.card_cons _ _).trans (by rw multiset.card_map; refl) instance {α : Type*} (β : α → Type*) [fintype α] [∀ a, fintype (β a)] : fintype (sigma β) := ⟨univ.sigma (λ _, univ), λ ⟨a, b⟩, by simp⟩ @[simp] lemma finset.univ_sigma_univ {α : Type*} {β : α → Type*} [fintype α] [∀ a, fintype (β a)] : (univ : finset α).sigma (λ a, (univ : finset (β a))) = univ := rfl instance (α β : Type*) [fintype α] [fintype β] : fintype (α × β) := ⟨univ.product univ, λ ⟨a, b⟩, by simp⟩ @[simp] lemma finset.univ_product_univ {α β : Type*} [fintype α] [fintype β] : (univ : finset α).product (univ : finset β) = univ := rfl @[simp] theorem fintype.card_prod (α β : Type*) [fintype α] [fintype β] : fintype.card (α × β) = fintype.card α * fintype.card β := card_product _ _ /-- Given that `α × β` is a fintype, `α` is also a fintype. -/ def fintype.fintype_prod_left {α β} [decidable_eq α] [fintype (α × β)] [nonempty β] : fintype α := ⟨(fintype.elems (α × β)).image prod.fst, assume a, let ⟨b⟩ := ‹nonempty β› in by simp; exact ⟨b, fintype.complete _⟩⟩ /-- Given that `α × β` is a fintype, `β` is also a fintype. -/ def fintype.fintype_prod_right {α β} [decidable_eq β] [fintype (α × β)] [nonempty α] : fintype β := ⟨(fintype.elems (α × β)).image prod.snd, assume b, let ⟨a⟩ := ‹nonempty α› in by simp; exact ⟨a, fintype.complete _⟩⟩ instance (α : Type*) [fintype α] : fintype (ulift α) := fintype.of_equiv _ equiv.ulift.symm @[simp] theorem fintype.card_ulift (α : Type*) [fintype α] : fintype.card (ulift α) = fintype.card α := fintype.of_equiv_card _ lemma univ_sum_type {α β : Type*} [fintype α] [fintype β] [fintype (α ⊕ β)] [decidable_eq (α ⊕ β)] : (univ : finset (α ⊕ β)) = map function.embedding.inl univ ∪ map function.embedding.inr univ := begin rw [eq_comm, eq_univ_iff_forall], simp only [mem_union, mem_map, exists_prop, mem_univ, true_and], rintro (x|y), exacts [or.inl ⟨x, rfl⟩, or.inr ⟨y, rfl⟩] end instance (α : Type u) (β : Type v) [fintype α] [fintype β] : fintype (α ⊕ β) := @fintype.of_equiv _ _ (@sigma.fintype _ (λ b, cond b (ulift α) (ulift.{(max u v) v} β)) _ (λ b, by cases b; apply ulift.fintype)) ((equiv.sum_equiv_sigma_bool _ _).symm.trans (equiv.sum_congr equiv.ulift equiv.ulift)) namespace fintype variables [fintype α] [fintype β] lemma card_le_of_injective (f : α → β) (hf : function.injective f) : card α ≤ card β := finset.card_le_card_of_inj_on f (λ _ _, finset.mem_univ _) (λ _ _ _ _ h, hf h) lemma card_le_of_embedding (f : α ↪ β) : card α ≤ card β := card_le_of_injective f f.2 lemma card_lt_of_injective_of_not_mem (f : α → β) (h : function.injective f) {b : β} (w : b ∉ set.range f) : card α < card β := calc card α = (univ.map ⟨f, h⟩).card : (card_map _).symm ... < card β : finset.card_lt_univ_of_not_mem $ by rwa [← mem_coe, coe_map, coe_univ, set.image_univ] lemma card_lt_of_injective_not_surjective (f : α → β) (h : function.injective f) (h' : ¬function.surjective f) : card α < card β := let ⟨y, hy⟩ := not_forall.1 h' in card_lt_of_injective_of_not_mem f h hy lemma card_le_of_surjective (f : α → β) (h : function.surjective f) : card β ≤ card α := card_le_of_injective _ (function.injective_surj_inv h) /-- The pigeonhole principle for finitely many pigeons and pigeonholes. This is the `fintype` version of `finset.exists_ne_map_eq_of_card_lt_of_maps_to`. -/ lemma exists_ne_map_eq_of_card_lt (f : α → β) (h : fintype.card β < fintype.card α) : ∃ x y, x ≠ y ∧ f x = f y := let ⟨x, _, y, _, h⟩ := finset.exists_ne_map_eq_of_card_lt_of_maps_to h (λ x _, mem_univ (f x)) in ⟨x, y, h⟩ lemma card_eq_one_iff : card α = 1 ↔ (∃ x : α, ∀ y, y = x) := by rw [← card_unit, card_eq]; exact ⟨λ ⟨a⟩, ⟨a.symm (), λ y, a.injective (subsingleton.elim _ _)⟩, λ ⟨x, hx⟩, ⟨⟨λ _, (), λ _, x, λ _, (hx _).trans (hx _).symm, λ _, subsingleton.elim _ _⟩⟩⟩ lemma card_eq_zero_iff : card α = 0 ↔ (α → false) := ⟨λ h a, have e : α ≃ empty := classical.choice (card_eq.1 (by simp [h])), (e a).elim, λ h, have e : α ≃ empty := ⟨λ a, (h a).elim, λ a, a.elim, λ a, (h a).elim, λ a, a.elim⟩, by simp [card_congr e]⟩ /-- A `fintype` with cardinality zero is (constructively) equivalent to `pempty`. -/ def card_eq_zero_equiv_equiv_pempty : card α = 0 ≃ (α ≃ pempty.{v+1}) := { to_fun := λ h, { to_fun := λ a, false.elim (card_eq_zero_iff.1 h a), inv_fun := λ a, pempty.elim a, left_inv := λ a, false.elim (card_eq_zero_iff.1 h a), right_inv := λ a, pempty.elim a, }, inv_fun := λ e, by { simp only [←of_equiv_card e], convert card_pempty, }, left_inv := λ h, rfl, right_inv := λ e, by { ext x, cases e x, } } lemma card_pos_iff : 0 < card α ↔ nonempty α := ⟨λ h, classical.by_contradiction (λ h₁, have card α = 0 := card_eq_zero_iff.2 (λ a, h₁ ⟨a⟩), lt_irrefl 0 $ by rwa this at h), λ ⟨a⟩, nat.pos_of_ne_zero (mt card_eq_zero_iff.1 (λ h, h a))⟩ lemma card_le_one_iff : card α ≤ 1 ↔ (∀ a b : α, a = b) := let n := card α in have hn : n = card α := rfl, match n, hn with | 0 := λ ha, ⟨λ h, λ a, (card_eq_zero_iff.1 ha.symm a).elim, λ _, ha ▸ nat.le_succ _⟩ | 1 := λ ha, ⟨λ h, λ a b, let ⟨x, hx⟩ := card_eq_one_iff.1 ha.symm in by rw [hx a, hx b], λ _, ha ▸ le_refl _⟩ | (n+2) := λ ha, ⟨λ h, by rw ← ha at h; exact absurd h dec_trivial, (λ h, card_unit ▸ card_le_of_injective (λ _, ()) (λ _ _ _, h _ _))⟩ end lemma card_le_one_iff_subsingleton : card α ≤ 1 ↔ subsingleton α := iff.trans card_le_one_iff subsingleton_iff.symm lemma one_lt_card_iff_nontrivial : 1 < card α ↔ nontrivial α := begin classical, rw ← not_iff_not, push_neg, rw [not_nontrivial_iff_subsingleton, card_le_one_iff_subsingleton] end lemma exists_ne_of_one_lt_card (h : 1 < card α) (a : α) : ∃ b : α, b ≠ a := by { haveI : nontrivial α := one_lt_card_iff_nontrivial.1 h, exact exists_ne a } lemma exists_pair_of_one_lt_card (h : 1 < card α) : ∃ (a b : α), a ≠ b := by { haveI : nontrivial α := one_lt_card_iff_nontrivial.1 h, exact exists_pair_ne α } lemma card_eq_one_of_forall_eq {i : α} (h : ∀ j, j = i) : card α = 1 := fintype.card_eq_one_iff.2 ⟨i,h⟩ lemma injective_iff_surjective {f : α → α} : injective f ↔ surjective f := by haveI := classical.prop_decidable; exact have ∀ {f : α → α}, injective f → surjective f, from λ f hinj x, have h₁ : image f univ = univ := eq_of_subset_of_card_le (subset_univ _) ((card_image_of_injective univ hinj).symm ▸ le_refl _), have h₂ : x ∈ image f univ := h₁.symm ▸ mem_univ _, exists_of_bex (mem_image.1 h₂), ⟨this, λ hsurj, has_left_inverse.injective ⟨surj_inv hsurj, left_inverse_of_surjective_of_right_inverse (this (injective_surj_inv _)) (right_inverse_surj_inv _)⟩⟩ lemma injective_iff_bijective {f : α → α} : injective f ↔ bijective f := by simp [bijective, injective_iff_surjective] lemma surjective_iff_bijective {f : α → α} : surjective f ↔ bijective f := by simp [bijective, injective_iff_surjective] lemma injective_iff_surjective_of_equiv {β : Type*} {f : α → β} (e : α ≃ β) : injective f ↔ surjective f := have injective (e.symm ∘ f) ↔ surjective (e.symm ∘ f), from injective_iff_surjective, ⟨λ hinj, by simpa [function.comp] using e.surjective.comp (this.1 (e.symm.injective.comp hinj)), λ hsurj, by simpa [function.comp] using e.injective.comp (this.2 (e.symm.surjective.comp hsurj))⟩ lemma bijective_iff_injective_and_card (f : α → β) : bijective f ↔ injective f ∧ card α = card β := begin split, { intro h, exact ⟨h.1, card_congr (equiv.of_bijective f h)⟩ }, { rintro ⟨hf, h⟩, refine ⟨hf, _⟩, rwa ← injective_iff_surjective_of_equiv (equiv_of_card_eq h) } end lemma bijective_iff_surjective_and_card (f : α → β) : bijective f ↔ surjective f ∧ card α = card β := begin split, { intro h, exact ⟨h.2, card_congr (equiv.of_bijective f h)⟩, }, { rintro ⟨hf, h⟩, refine ⟨_, hf⟩, rwa injective_iff_surjective_of_equiv (equiv_of_card_eq h) } end end fintype lemma fintype.coe_image_univ [fintype α] [decidable_eq β] {f : α → β} : ↑(finset.image f finset.univ) = set.range f := by { ext x, simp } instance list.subtype.fintype [decidable_eq α] (l : list α) : fintype {x // x ∈ l} := fintype.of_list l.attach l.mem_attach instance multiset.subtype.fintype [decidable_eq α] (s : multiset α) : fintype {x // x ∈ s} := fintype.of_multiset s.attach s.mem_attach instance finset.subtype.fintype (s : finset α) : fintype {x // x ∈ s} := ⟨s.attach, s.mem_attach⟩ instance finset_coe.fintype (s : finset α) : fintype (↑s : set α) := finset.subtype.fintype s @[simp] lemma fintype.card_coe (s : finset α) : fintype.card (↑s : set α) = s.card := card_attach lemma finset.attach_eq_univ {s : finset α} : s.attach = finset.univ := rfl instance plift.fintype (p : Prop) [decidable p] : fintype (plift p) := ⟨if h : p then {⟨h⟩} else ∅, λ ⟨h⟩, by simp [h]⟩ instance Prop.fintype : fintype Prop := ⟨⟨true ::ₘ false ::ₘ 0, by simp [true_ne_false]⟩, classical.cases (by simp) (by simp)⟩ instance subtype.fintype (p : α → Prop) [decidable_pred p] [fintype α] : fintype {x // p x} := fintype.subtype (univ.filter p) (by simp) /-- A set on a fintype, when coerced to a type, is a fintype. -/ def set_fintype {α} [fintype α] (s : set α) [decidable_pred s] : fintype s := subtype.fintype (λ x, x ∈ s) namespace function.embedding /-- An embedding from a `fintype` to itself can be promoted to an equivalence. -/ noncomputable def equiv_of_fintype_self_embedding {α : Type*} [fintype α] (e : α ↪ α) : α ≃ α := equiv.of_bijective e (fintype.injective_iff_bijective.1 e.2) @[simp] lemma equiv_of_fintype_self_embedding_to_embedding {α : Type*} [fintype α] (e : α ↪ α) : e.equiv_of_fintype_self_embedding.to_embedding = e := by { ext, refl, } end function.embedding @[simp] lemma finset.univ_map_embedding {α : Type*} [fintype α] (e : α ↪ α) : univ.map e = univ := by rw [← e.equiv_of_fintype_self_embedding_to_embedding, univ_map_equiv_to_embedding] namespace fintype lemma card_lt_of_surjective_not_injective [fintype α] [fintype β] (f : α → β) (h : function.surjective f) (h' : ¬function.injective f) : card β < card α := card_lt_of_injective_not_surjective _ (function.injective_surj_inv h) $ λ hg, have w : function.bijective (function.surj_inv h) := ⟨function.injective_surj_inv h, hg⟩, h' $ (injective_iff_surjective_of_equiv (equiv.of_bijective _ w).symm).mpr h variables [decidable_eq α] [fintype α] {δ : α → Type*} /-- Given for all `a : α` a finset `t a` of `δ a`, then one can define the finset `fintype.pi_finset t` of all functions taking values in `t a` for all `a`. This is the analogue of `finset.pi` where the base finset is `univ` (but formally they are not the same, as there is an additional condition `i ∈ finset.univ` in the `finset.pi` definition). -/ def pi_finset (t : Πa, finset (δ a)) : finset (Πa, δ a) := (finset.univ.pi t).map ⟨λ f a, f a (mem_univ a), λ _ _, by simp [function.funext_iff]⟩ @[simp] lemma mem_pi_finset {t : Πa, finset (δ a)} {f : Πa, δ a} : f ∈ pi_finset t ↔ (∀a, f a ∈ t a) := begin split, { simp only [pi_finset, mem_map, and_imp, forall_prop_of_true, exists_prop, mem_univ, exists_imp_distrib, mem_pi], assume g hg hgf a, rw ← hgf, exact hg a }, { simp only [pi_finset, mem_map, forall_prop_of_true, exists_prop, mem_univ, mem_pi], assume hf, exact ⟨λ a ha, f a, hf, rfl⟩ } end lemma pi_finset_subset (t₁ t₂ : Πa, finset (δ a)) (h : ∀ a, t₁ a ⊆ t₂ a) : pi_finset t₁ ⊆ pi_finset t₂ := λ g hg, mem_pi_finset.2 $ λ a, h a $ mem_pi_finset.1 hg a lemma pi_finset_disjoint_of_disjoint [∀ a, decidable_eq (δ a)] (t₁ t₂ : Πa, finset (δ a)) {a : α} (h : disjoint (t₁ a) (t₂ a)) : disjoint (pi_finset t₁) (pi_finset t₂) := disjoint_iff_ne.2 $ λ f₁ hf₁ f₂ hf₂ eq₁₂, disjoint_iff_ne.1 h (f₁ a) (mem_pi_finset.1 hf₁ a) (f₂ a) (mem_pi_finset.1 hf₂ a) (congr_fun eq₁₂ a) end fintype /-! ### pi -/ /-- A dependent product of fintypes, indexed by a fintype, is a fintype. -/ instance pi.fintype {α : Type*} {β : α → Type*} [decidable_eq α] [fintype α] [∀a, fintype (β a)] : fintype (Πa, β a) := ⟨fintype.pi_finset (λ _, univ), by simp⟩ @[simp] lemma fintype.pi_finset_univ {α : Type*} {β : α → Type*} [decidable_eq α] [fintype α] [∀a, fintype (β a)] : fintype.pi_finset (λ a : α, (finset.univ : finset (β a))) = (finset.univ : finset (Π a, β a)) := rfl instance d_array.fintype {n : ℕ} {α : fin n → Type*} [∀n, fintype (α n)] : fintype (d_array n α) := fintype.of_equiv _ (equiv.d_array_equiv_fin _).symm instance array.fintype {n : ℕ} {α : Type*} [fintype α] : fintype (array n α) := d_array.fintype instance vector.fintype {α : Type*} [fintype α] {n : ℕ} : fintype (vector α n) := fintype.of_equiv _ (equiv.vector_equiv_fin _ _).symm instance quotient.fintype [fintype α] (s : setoid α) [decidable_rel ((≈) : α → α → Prop)] : fintype (quotient s) := fintype.of_surjective quotient.mk (λ x, quotient.induction_on x (λ x, ⟨x, rfl⟩)) instance finset.fintype [fintype α] : fintype (finset α) := ⟨univ.powerset, λ x, finset.mem_powerset.2 (finset.subset_univ _)⟩ @[simp] lemma fintype.card_finset [fintype α] : fintype.card (finset α) = 2 ^ (fintype.card α) := finset.card_powerset finset.univ @[simp] lemma finset.univ_filter_card_eq (α : Type*) [fintype α] (k : ℕ) : (finset.univ : finset (finset α)).filter (λ s, s.card = k) = finset.univ.powerset_len k := by { ext, simp [finset.mem_powerset_len] } @[simp] lemma fintype.card_finset_len [fintype α] (k : ℕ) : fintype.card {s : finset α // s.card = k} = nat.choose (fintype.card α) k := by simp [fintype.subtype_card, finset.card_univ] @[simp] lemma set.to_finset_univ [fintype α] : (set.univ : set α).to_finset = finset.univ := by { ext, simp only [set.mem_univ, mem_univ, set.mem_to_finset] } @[simp] lemma set.to_finset_eq_empty_iff {s : set α} [fintype s] : s.to_finset = ∅ ↔ s = ∅ := by simp [ext_iff, set.ext_iff] instance : fintype (∅ : set α) := ⟨∅, subtype.property⟩ @[simp] lemma set.to_finset_empty : (∅ : set α).to_finset = ∅ := set.to_finset_eq_empty_iff.mpr rfl theorem fintype.card_subtype_le [fintype α] (p : α → Prop) [decidable_pred p] : fintype.card {x // p x} ≤ fintype.card α := fintype.card_le_of_embedding (function.embedding.subtype _) theorem fintype.card_subtype_lt [fintype α] {p : α → Prop} [decidable_pred p] {x : α} (hx : ¬ p x) : fintype.card {x // p x} < fintype.card α := fintype.card_lt_of_injective_of_not_mem coe subtype.coe_injective $ by rwa subtype.range_coe_subtype theorem fintype.card_quotient_le [fintype α] (s : setoid α) [decidable_rel ((≈) : α → α → Prop)] : fintype.card (quotient s) ≤ fintype.card α := fintype.card_le_of_surjective _ (surjective_quotient_mk _) theorem fintype.card_quotient_lt [fintype α] {s : setoid α} [decidable_rel ((≈) : α → α → Prop)] {x y : α} (h1 : x ≠ y) (h2 : x ≈ y) : fintype.card (quotient s) < fintype.card α := fintype.card_lt_of_surjective_not_injective _ (surjective_quotient_mk _) $ λ w, h1 (w $ quotient.eq.mpr h2) instance psigma.fintype {α : Type*} {β : α → Type*} [fintype α] [∀ a, fintype (β a)] : fintype (Σ' a, β a) := fintype.of_equiv _ (equiv.psigma_equiv_sigma _).symm instance psigma.fintype_prop_left {α : Prop} {β : α → Type*} [decidable α] [∀ a, fintype (β a)] : fintype (Σ' a, β a) := if h : α then fintype.of_equiv (β h) ⟨λ x, ⟨h, x⟩, psigma.snd, λ _, rfl, λ ⟨_, _⟩, rfl⟩ else ⟨∅, λ x, h x.1⟩ instance psigma.fintype_prop_right {α : Type*} {β : α → Prop} [∀ a, decidable (β a)] [fintype α] : fintype (Σ' a, β a) := fintype.of_equiv {a // β a} ⟨λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, rfl, λ ⟨x, y⟩, rfl⟩ instance psigma.fintype_prop_prop {α : Prop} {β : α → Prop} [decidable α] [∀ a, decidable (β a)] : fintype (Σ' a, β a) := if h : ∃ a, β a then ⟨{⟨h.fst, h.snd⟩}, λ ⟨_, _⟩, by simp⟩ else ⟨∅, λ ⟨x, y⟩, h ⟨x, y⟩⟩ instance set.fintype [fintype α] : fintype (set α) := ⟨(@finset.univ α _).powerset.map ⟨coe, coe_injective⟩, λ s, begin classical, refine mem_map.2 ⟨finset.univ.filter s, mem_powerset.2 (subset_univ _), _⟩, apply (coe_filter _ _).trans, rw [coe_univ, set.sep_univ], refl end⟩ instance pfun_fintype (p : Prop) [decidable p] (α : p → Type*) [Π hp, fintype (α hp)] : fintype (Π hp : p, α hp) := if hp : p then fintype.of_equiv (α hp) ⟨λ a _, a, λ f, f hp, λ _, rfl, λ _, rfl⟩ else ⟨singleton (λ h, (hp h).elim), by simp [hp, function.funext_iff]⟩ @[simp] lemma finset.univ_pi_univ {α : Type*} {β : α → Type*} [decidable_eq α] [fintype α] [∀a, fintype (β a)] : finset.univ.pi (λ a : α, (finset.univ : finset (β a))) = finset.univ := by { ext, simp } lemma mem_image_univ_iff_mem_range {α β : Type*} [fintype α] [decidable_eq β] {f : α → β} {b : β} : b ∈ univ.image f ↔ b ∈ set.range f := by simp /-- An auxiliary function for `quotient.fin_choice`. Given a collection of setoids indexed by a type `ι`, a (finite) list `l` of indices, and a function that for each `i ∈ l` gives a term of the corresponding quotient type, then there is a corresponding term in the quotient of the product of the setoids indexed by `l`. -/ def quotient.fin_choice_aux {ι : Type*} [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] : Π (l : list ι), (Π i ∈ l, quotient (S i)) → @quotient (Π i ∈ l, α i) (by apply_instance) | [] f := ⟦λ i, false.elim⟧ | (i::l) f := begin refine quotient.lift_on₂ (f i (list.mem_cons_self _ _)) (quotient.fin_choice_aux l (λ j h, f j (list.mem_cons_of_mem _ h))) _ _, exact λ a l, ⟦λ j h, if e : j = i then by rw e; exact a else l _ (h.resolve_left e)⟧, refine λ a₁ l₁ a₂ l₂ h₁ h₂, quotient.sound (λ j h, _), by_cases e : j = i; simp [e], { subst j, exact h₁ }, { exact h₂ _ _ } end theorem quotient.fin_choice_aux_eq {ι : Type*} [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] : ∀ (l : list ι) (f : Π i ∈ l, α i), quotient.fin_choice_aux l (λ i h, ⟦f i h⟧) = ⟦f⟧ | [] f := quotient.sound (λ i h, h.elim) | (i::l) f := begin simp [quotient.fin_choice_aux, quotient.fin_choice_aux_eq l], refine quotient.sound (λ j h, _), by_cases e : j = i; simp [e], subst j, refl end /-- Given a collection of setoids indexed by a fintype `ι` and a function that for each `i : ι` gives a term of the corresponding quotient type, then there is corresponding term in the quotient of the product of the setoids. -/ def quotient.fin_choice {ι : Type*} [decidable_eq ι] [fintype ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] (f : Π i, quotient (S i)) : @quotient (Π i, α i) (by apply_instance) := quotient.lift_on (@quotient.rec_on _ _ (λ l : multiset ι, @quotient (Π i ∈ l, α i) (by apply_instance)) finset.univ.1 (λ l, quotient.fin_choice_aux l (λ i _, f i)) (λ a b h, begin have := λ a, quotient.fin_choice_aux_eq a (λ i h, quotient.out (f i)), simp [quotient.out_eq] at this, simp [this], let g := λ a:multiset ι, ⟦λ (i : ι) (h : i ∈ a), quotient.out (f i)⟧, refine eq_of_heq ((eq_rec_heq _ _).trans (_ : g a == g b)), congr' 1, exact quotient.sound h, end)) (λ f, ⟦λ i, f i (finset.mem_univ _)⟧) (λ a b h, quotient.sound $ λ i, h _ _) theorem quotient.fin_choice_eq {ι : Type*} [decidable_eq ι] [fintype ι] {α : ι → Type*} [∀ i, setoid (α i)] (f : Π i, α i) : quotient.fin_choice (λ i, ⟦f i⟧) = ⟦f⟧ := begin let q, swap, change quotient.lift_on q _ _ = _, have : q = ⟦λ i h, f i⟧, { dsimp [q], exact quotient.induction_on (@finset.univ ι _).1 (λ l, quotient.fin_choice_aux_eq _ _) }, simp [this], exact setoid.refl _ end section equiv open list equiv equiv.perm variables [decidable_eq α] [decidable_eq β] /-- Given a list, produce a list of all permutations of its elements. -/ def perms_of_list : list α → list (perm α) | [] := [1] | (a :: l) := perms_of_list l ++ l.bind (λ b, (perms_of_list l).map (λ f, swap a b * f)) lemma length_perms_of_list : ∀ l : list α, length (perms_of_list l) = l.length! | [] := rfl | (a :: l) := begin rw [length_cons, nat.factorial_succ], simp [perms_of_list, length_bind, length_perms_of_list, function.comp, nat.succ_mul], cc end lemma mem_perms_of_list_of_mem {l : list α} {f : perm α} (h : ∀ x, f x ≠ x → x ∈ l) : f ∈ perms_of_list l := begin induction l with a l IH generalizing f h, { exact list.mem_singleton.2 (equiv.ext $ λ x, decidable.by_contradiction $ h _) }, by_cases hfa : f a = a, { refine mem_append_left _ (IH (λ x hx, mem_of_ne_of_mem _ (h x hx))), rintro rfl, exact hx hfa }, { have hfa' : f (f a) ≠ f a := mt (λ h, f.injective h) hfa, have : ∀ (x : α), (swap a (f a) * f) x ≠ x → x ∈ l, { intros x hx, have hxa : x ≠ a, { rintro rfl, apply hx, simp only [mul_apply, swap_apply_right] }, refine list.mem_of_ne_of_mem hxa (h x (λ h, _)), simp only [h, mul_apply, swap_apply_def, mul_apply, ne.def, apply_eq_iff_eq] at hx; split_ifs at hx, exacts [hxa (h.symm.trans h_1), hx h] }, suffices : f ∈ perms_of_list l ∨ ∃ (b ∈ l) (g ∈ perms_of_list l), swap a b * g = f, { simpa only [perms_of_list, exists_prop, list.mem_map, mem_append, list.mem_bind] }, refine or_iff_not_imp_left.2 (λ hfl, ⟨f a, _, swap a (f a) * f, IH this, _⟩), { by_cases hffa : f (f a) = a, { exact mem_of_ne_of_mem hfa (h _ (mt (λ h, f.injective h) hfa)) }, { apply this, simp only [mul_apply, swap_apply_def, mul_apply, ne.def, apply_eq_iff_eq], split_ifs; cc } }, { rw [← mul_assoc, mul_def (swap a (f a)) (swap a (f a)), swap_swap, ← equiv.perm.one_def, one_mul] } } end lemma mem_of_mem_perms_of_list : ∀ {l : list α} {f : perm α}, f ∈ perms_of_list l → ∀ {x}, f x ≠ x → x ∈ l | [] f h := have f = 1 := by simpa [perms_of_list] using h, by rw this; simp | (a::l) f h := (mem_append.1 h).elim (λ h x hx, mem_cons_of_mem _ (mem_of_mem_perms_of_list h hx)) (λ h x hx, let ⟨y, hy, hy'⟩ := list.mem_bind.1 h in let ⟨g, hg₁, hg₂⟩ := list.mem_map.1 hy' in if hxa : x = a then by simp [hxa] else if hxy : x = y then mem_cons_of_mem _ $ by rwa hxy else mem_cons_of_mem _ $ mem_of_mem_perms_of_list hg₁ $ by rw [eq_inv_mul_iff_mul_eq.2 hg₂, mul_apply, swap_inv, swap_apply_def]; split_ifs; cc) lemma mem_perms_of_list_iff {l : list α} {f : perm α} : f ∈ perms_of_list l ↔ ∀ {x}, f x ≠ x → x ∈ l := ⟨mem_of_mem_perms_of_list, mem_perms_of_list_of_mem⟩ lemma nodup_perms_of_list : ∀ {l : list α} (hl : l.nodup), (perms_of_list l).nodup | [] hl := by simp [perms_of_list] | (a::l) hl := have hl' : l.nodup, from nodup_of_nodup_cons hl, have hln' : (perms_of_list l).nodup, from nodup_perms_of_list hl', have hmeml : ∀ {f : perm α}, f ∈ perms_of_list l → f a = a, from λ f hf, not_not.1 (mt (mem_of_mem_perms_of_list hf) (nodup_cons.1 hl).1), by rw [perms_of_list, list.nodup_append, list.nodup_bind, pairwise_iff_nth_le]; exact ⟨hln', ⟨λ _ _, nodup_map (λ _ _, mul_left_cancel) hln', λ i j hj hij x hx₁ hx₂, let ⟨f, hf⟩ := list.mem_map.1 hx₁ in let ⟨g, hg⟩ := list.mem_map.1 hx₂ in have hix : x a = nth_le l i (lt_trans hij hj), by rw [← hf.2, mul_apply, hmeml hf.1, swap_apply_left], have hiy : x a = nth_le l j hj, by rw [← hg.2, mul_apply, hmeml hg.1, swap_apply_left], absurd (hf.2.trans (hg.2.symm)) $ λ h, ne_of_lt hij $ nodup_iff_nth_le_inj.1 hl' i j (lt_trans hij hj) hj $ by rw [← hix, hiy]⟩, λ f hf₁ hf₂, let ⟨x, hx, hx'⟩ := list.mem_bind.1 hf₂ in let ⟨g, hg⟩ := list.mem_map.1 hx' in have hgxa : g⁻¹ x = a, from f.injective $ by rw [hmeml hf₁, ← hg.2]; simp, have hxa : x ≠ a, from λ h, (list.nodup_cons.1 hl).1 (h ▸ hx), (list.nodup_cons.1 hl).1 $ hgxa ▸ mem_of_mem_perms_of_list hg.1 (by rwa [apply_inv_self, hgxa])⟩ /-- Given a finset, produce the finset of all permutations of its elements. -/ def perms_of_finset (s : finset α) : finset (perm α) := quotient.hrec_on s.1 (λ l hl, ⟨perms_of_list l, nodup_perms_of_list hl⟩) (λ a b hab, hfunext (congr_arg _ (quotient.sound hab)) (λ ha hb _, heq_of_eq $ finset.ext $ by simp [mem_perms_of_list_iff, hab.mem_iff])) s.2 lemma mem_perms_of_finset_iff : ∀ {s : finset α} {f : perm α}, f ∈ perms_of_finset s ↔ ∀ {x}, f x ≠ x → x ∈ s := by rintros ⟨⟨l⟩, hs⟩ f; exact mem_perms_of_list_iff lemma card_perms_of_finset : ∀ (s : finset α), (perms_of_finset s).card = s.card! := by rintros ⟨⟨l⟩, hs⟩; exact length_perms_of_list l /-- The collection of permutations of a fintype is a fintype. -/ def fintype_perm [fintype α] : fintype (perm α) := ⟨perms_of_finset (@finset.univ α _), by simp [mem_perms_of_finset_iff]⟩ instance [fintype α] [fintype β] : fintype (α ≃ β) := if h : fintype.card β = fintype.card α then trunc.rec_on_subsingleton (fintype.trunc_equiv_fin α) (λ eα, trunc.rec_on_subsingleton (fintype.trunc_equiv_fin β) (λ eβ, @fintype.of_equiv _ (perm α) fintype_perm (equiv_congr (equiv.refl α) (eα.trans (eq.rec_on h eβ.symm)) : (α ≃ α) ≃ (α ≃ β)))) else ⟨∅, λ x, false.elim (h (fintype.card_eq.2 ⟨x.symm⟩))⟩ lemma fintype.card_perm [fintype α] : fintype.card (perm α) = (fintype.card α)! := subsingleton.elim (@fintype_perm α _ _) (@equiv.fintype α α _ _ _ _) ▸ card_perms_of_finset _ lemma fintype.card_equiv [fintype α] [fintype β] (e : α ≃ β) : fintype.card (α ≃ β) = (fintype.card α)! := fintype.card_congr (equiv_congr (equiv.refl α) e) ▸ fintype.card_perm lemma univ_eq_singleton_of_card_one {α} [fintype α] (x : α) (h : fintype.card α = 1) : (univ : finset α) = {x} := begin symmetry, apply eq_of_subset_of_card_le (subset_univ ({x})), apply le_of_eq, simp [h, finset.card_univ] end end equiv namespace fintype section choose open fintype open equiv variables [fintype α] (p : α → Prop) [decidable_pred p] /-- Given a fintype `α` and a predicate `p`, associate to a proof that there is a unique element of `α` satisfying `p` this unique element, as an element of the corresponding subtype. -/ def choose_x (hp : ∃! a : α, p a) : {a // p a} := ⟨finset.choose p univ (by simp; exact hp), finset.choose_property _ _ _⟩ /-- Given a fintype `α` and a predicate `p`, associate to a proof that there is a unique element of `α` satisfying `p` this unique element, as an element of `α`. -/ def choose (hp : ∃! a, p a) : α := choose_x p hp lemma choose_spec (hp : ∃! a, p a) : p (choose p hp) := (choose_x p hp).property end choose section bijection_inverse open function variables [fintype α] variables [decidable_eq β] variables {f : α → β} /-- `bij_inv f` is the unique inverse to a bijection `f`. This acts as a computable alternative to `function.inv_fun`. -/ def bij_inv (f_bij : bijective f) (b : β) : α := fintype.choose (λ a, f a = b) begin rcases f_bij.right b with ⟨a', fa_eq_b⟩, rw ← fa_eq_b, exact ⟨a', ⟨rfl, (λ a h, f_bij.left h)⟩⟩ end lemma left_inverse_bij_inv (f_bij : bijective f) : left_inverse (bij_inv f_bij) f := λ a, f_bij.left (choose_spec (λ a', f a' = f a) _) lemma right_inverse_bij_inv (f_bij : bijective f) : right_inverse (bij_inv f_bij) f := λ b, choose_spec (λ a', f a' = b) _ lemma bijective_bij_inv (f_bij : bijective f) : bijective (bij_inv f_bij) := ⟨(right_inverse_bij_inv _).injective, (left_inverse_bij_inv _).surjective⟩ end bijection_inverse lemma well_founded_of_trans_of_irrefl [fintype α] (r : α → α → Prop) [is_trans α r] [is_irrefl α r] : well_founded r := by classical; exact have ∀ x y, r x y → (univ.filter (λ z, r z x)).card < (univ.filter (λ z, r z y)).card, from λ x y hxy, finset.card_lt_card $ by simp only [finset.lt_iff_ssubset.symm, lt_iff_le_not_le, finset.le_iff_subset, finset.subset_iff, mem_filter, true_and, mem_univ, hxy]; exact ⟨λ z hzx, trans hzx hxy, not_forall_of_exists_not ⟨x, not_imp.2 ⟨hxy, irrefl x⟩⟩⟩, subrelation.wf this (measure_wf _) lemma preorder.well_founded [fintype α] [preorder α] : well_founded ((<) : α → α → Prop) := well_founded_of_trans_of_irrefl _ @[instance, priority 10] lemma linear_order.is_well_order [fintype α] [linear_order α] : is_well_order α (<) := { wf := preorder.well_founded } end fintype /-- A type is said to be infinite if it has no fintype instance. -/ class infinite (α : Type*) : Prop := (not_fintype : fintype α → false) @[simp] lemma not_nonempty_fintype {α : Type*} : ¬nonempty (fintype α) ↔ infinite α := ⟨λf, ⟨λ x, f ⟨x⟩⟩, λ⟨f⟩ ⟨x⟩, f x⟩ lemma finset.exists_minimal {α : Type*} [preorder α] (s : finset α) (h : s.nonempty) : ∃ m ∈ s, ∀ x ∈ s, ¬ (x < m) := begin obtain ⟨c, hcs : c ∈ s⟩ := h, have : well_founded (@has_lt.lt {x // x ∈ s} _) := fintype.well_founded_of_trans_of_irrefl _, obtain ⟨⟨m, hms : m ∈ s⟩, -, H⟩ := this.has_min set.univ ⟨⟨c, hcs⟩, trivial⟩, exact ⟨m, hms, λ x hx hxm, H ⟨x, hx⟩ trivial hxm⟩, end lemma finset.exists_maximal {α : Type*} [preorder α] (s : finset α) (h : s.nonempty) : ∃ m ∈ s, ∀ x ∈ s, ¬ (m < x) := @finset.exists_minimal (order_dual α) _ s h namespace infinite lemma exists_not_mem_finset [infinite α] (s : finset α) : ∃ x, x ∉ s := not_forall.1 $ λ h, not_fintype ⟨s, h⟩ @[priority 100] -- see Note [lower instance priority] instance (α : Type*) [H : infinite α] : nontrivial α := ⟨let ⟨x, hx⟩ := exists_not_mem_finset (∅ : finset α) in let ⟨y, hy⟩ := exists_not_mem_finset ({x} : finset α) in ⟨y, x, by simpa only [mem_singleton] using hy⟩⟩ lemma nonempty (α : Type*) [infinite α] : nonempty α := by apply_instance lemma of_injective [infinite β] (f : β → α) (hf : injective f) : infinite α := ⟨λ I, by exactI not_fintype (fintype.of_injective f hf)⟩ lemma of_surjective [infinite β] (f : α → β) (hf : surjective f) : infinite α := ⟨λ I, by classical; exactI not_fintype (fintype.of_surjective f hf)⟩ private noncomputable def nat_embedding_aux (α : Type*) [infinite α] : ℕ → α | n := by letI := classical.dec_eq α; exact classical.some (exists_not_mem_finset ((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux m) (λ _, multiset.mem_range.1)).to_finset) private lemma nat_embedding_aux_injective (α : Type*) [infinite α] : function.injective (nat_embedding_aux α) := begin assume m n h, letI := classical.dec_eq α, wlog hmlen : m ≤ n using m n, by_contradiction hmn, have hmn : m < n, from lt_of_le_of_ne hmlen hmn, refine (classical.some_spec (exists_not_mem_finset ((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux α m) (λ _, multiset.mem_range.1)).to_finset)) _, refine multiset.mem_to_finset.2 (multiset.mem_pmap.2 ⟨m, multiset.mem_range.2 hmn, _⟩), rw [h, nat_embedding_aux] end /-- Embedding of `ℕ` into an infinite type. -/ noncomputable def nat_embedding (α : Type*) [infinite α] : ℕ ↪ α := ⟨_, nat_embedding_aux_injective α⟩ lemma exists_subset_card_eq (α : Type*) [infinite α] (n : ℕ) : ∃ s : finset α, s.card = n := ⟨(range n).map (nat_embedding α), by rw [card_map, card_range]⟩ end infinite lemma not_injective_infinite_fintype [infinite α] [fintype β] (f : α → β) : ¬ injective f := assume (hf : injective f), have H : fintype α := fintype.of_injective f hf, infinite.not_fintype H /-- The pigeonhole principle for infinitely many pigeons in finitely many pigeonholes. If there are infinitely many pigeons in finitely many pigeonholes, then there are at least two pigeons in the same pigeonhole. See also: `fintype.exists_ne_map_eq_of_card_lt`, `fintype.exists_infinite_fiber`. -/ lemma fintype.exists_ne_map_eq_of_infinite [infinite α] [fintype β] (f : α → β) : ∃ x y : α, x ≠ y ∧ f x = f y := begin classical, by_contra hf, push_neg at hf, apply not_injective_infinite_fintype f, intros x y, contrapose, apply hf, end /-- The strong pigeonhole principle for infinitely many pigeons in finitely many pigeonholes. If there are infinitely many pigeons in finitely many pigeonholes, then there is a pigeonhole with infinitely many pigeons. See also: `fintype.exists_ne_map_eq_of_infinite` -/ lemma fintype.exists_infinite_fiber [infinite α] [fintype β] (f : α → β) : ∃ y : β, infinite (f ⁻¹' {y}) := begin classical, by_contra hf, push_neg at hf, haveI h' : ∀ (y : β), fintype (f ⁻¹' {y}) := begin intro y, specialize hf y, rw [←not_nonempty_fintype, not_not] at hf, exact classical.choice hf, end, let key : fintype α := { elems := univ.bUnion (λ (y : β), (f ⁻¹' {y}).to_finset), complete := by simp }, exact infinite.not_fintype key, end lemma not_surjective_fintype_infinite [fintype α] [infinite β] (f : α → β) : ¬ surjective f := assume (hf : surjective f), have H : infinite α := infinite.of_surjective f hf, @infinite.not_fintype _ H infer_instance instance nat.infinite : infinite ℕ := ⟨λ ⟨s, hs⟩, finset.not_mem_range_self $ s.subset_range_sup_succ (hs _)⟩ instance int.infinite : infinite ℤ := infinite.of_injective int.of_nat (λ _ _, int.of_nat.inj) section trunc /-- For `s : multiset α`, we can lift the existential statement that `∃ x, x ∈ s` to a `trunc α`. -/ def trunc_of_multiset_exists_mem {α} (s : multiset α) : (∃ x, x ∈ s) → trunc α := quotient.rec_on_subsingleton s $ λ l h, match l, h with | [], _ := false.elim (by tauto) | (a :: _), _ := trunc.mk a end /-- A `nonempty` `fintype` constructively contains an element. -/ def trunc_of_nonempty_fintype (α) [nonempty α] [fintype α] : trunc α := trunc_of_multiset_exists_mem finset.univ.val (by simp) /-- A `fintype` with positive cardinality constructively contains an element. -/ def trunc_of_card_pos {α} [fintype α] (h : 0 < fintype.card α) : trunc α := by { letI := (fintype.card_pos_iff.mp h), exact trunc_of_nonempty_fintype α } /-- By iterating over the elements of a fintype, we can lift an existential statement `∃ a, P a` to `trunc (Σ' a, P a)`, containing data. -/ def trunc_sigma_of_exists {α} [fintype α] {P : α → Prop} [decidable_pred P] (h : ∃ a, P a) : trunc (Σ' a, P a) := @trunc_of_nonempty_fintype (Σ' a, P a) (exists.elim h $ λ a ha, ⟨⟨a, ha⟩⟩) _ end trunc namespace multiset variables [fintype α] [decidable_eq α] @[simp] lemma count_univ (a : α) : count a finset.univ.val = 1 := count_eq_one_of_mem finset.univ.nodup (finset.mem_univ _) end multiset
f404315fb7d2c6429afce15f074907bfa867e405
1a61aba1b67cddccce19532a9596efe44be4285f
/tests/lean/calc1.lean
521e440f178587dd0017ccef2b91eefde930bd93
[ "Apache-2.0" ]
permissive
eigengrau/lean
07986a0f2548688c13ba36231f6cdbee82abf4c6
f8a773be1112015e2d232661ce616d23f12874d0
refs/heads/master
1,610,939,198,566
1,441,352,386,000
1,441,352,494,000
41,903,576
0
0
null
1,441,352,210,000
1,441,352,210,000
null
UTF-8
Lean
false
false
1,631
lean
prelude constant A : Type.{1} definition bool : Type.{1} := Type.{0} constant eq : A → A → bool infixl `=`:50 := eq axiom subst (P : A → bool) (a b : A) (H1 : a = b) (H2 : P a) : P b axiom eq_trans (a b c : A) (H1 : a = b) (H2 : b = c) : a = c axiom eq_refl (a : A) : a = a constant le : A → A → bool infixl `≤`:50 := le axiom le_trans (a b c : A) (H1 : a ≤ b) (H2 : b ≤ c) : a ≤ c axiom le_refl (a : A) : a ≤ a axiom eq_le_trans (a b c : A) (H1 : a = b) (H2 : b ≤ c) : a ≤ c axiom le_eq_trans (a b c : A) (H1 : a ≤ b) (H2 : b = c) : a ≤ c attribute subst [subst] attribute eq_refl [refl] attribute le_refl [refl] attribute eq_trans [trans] attribute le_trans [trans] attribute eq_le_trans [trans] attribute le_eq_trans [trans] constants a b c d e f : A axiom H1 : a = b axiom H2 : b ≤ c axiom H3 : c ≤ d axiom H4 : d = e check calc a = b : H1 ... ≤ c : H2 ... ≤ d : H3 ... = e : H4 constant lt : A → A → bool infixl `<`:50 := lt axiom lt_trans (a b c : A) (H1 : a < b) (H2 : b < c) : a < c axiom le_lt_trans (a b c : A) (H1 : a ≤ b) (H2 : b < c) : a < c axiom lt_le_trans (a b c : A) (H1 : a < b) (H2 : b ≤ c) : a < c axiom H5 : c < d check calc b ≤ c : H2 ... < d : H5 -- Error le_lt_trans was not registered yet attribute le_lt_trans [trans] check calc b ≤ c : H2 ... < d : H5 constant le2 : A → A → bool infixl `≤`:50 := le2 constant le2_trans (a b c : A) (H1 : le2 a b) (H2 : le2 b c) : le2 a c attribute le2_trans [trans] print raw calc b ≤ c : H2 ... ≤ d : H3 ... ≤ e : H4
8f53b7ea735ad3e3187d37190c6b25a930e8502c
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/witt_vector/discrete_valuation_ring.lean
b21fa0fa572e626b4fcba16da04021b8e2ce8809
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
6,094
lean
/- Copyright (c) 2022 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis, Heather Macbeth, Johan Commelin -/ import ring_theory.witt_vector.domain import ring_theory.witt_vector.mul_coeff import ring_theory.discrete_valuation_ring import tactic.linear_combination /-! # Witt vectors over a perfect ring This file establishes that Witt vectors over a perfect field are a discrete valuation ring. When `k` is a perfect ring, a nonzero `a : 𝕎 k` can be written as `p^m * b` for some `m : ℕ` and `b : 𝕎 k` with nonzero 0th coefficient. When `k` is also a field, this `b` can be chosen to be a unit of `𝕎 k`. ## Main declarations * `witt_vector.exists_eq_pow_p_mul`: the existence of this element `b` over a perfect ring * `witt_vector.exists_eq_pow_p_mul'`: the existence of this unit `b` over a perfect field * `witt_vector.discrete_valuation_ring`: `𝕎 k` is a discrete valuation ring if `k` is a perfect field -/ noncomputable theory namespace witt_vector variables {p : ℕ} [hp : fact p.prime] include hp local notation `𝕎` := witt_vector p section comm_ring variables {k : Type*} [comm_ring k] [char_p k p] /-- This is the `n+1`st coefficient of our inverse. -/ def succ_nth_val_units (n : ℕ) (a : units k) (A : 𝕎 k) (bs : fin (n+1) → k) : k := - ↑(a⁻¹ ^ (p^(n+1))) * (A.coeff (n + 1) * ↑(a⁻¹ ^ (p^(n+1))) + nth_remainder p n (truncate_fun (n+1) A) bs) /-- Recursively defines the sequence of coefficients for the inverse to a Witt vector whose first entry is a unit. -/ noncomputable def inverse_coeff (a : units k) (A : 𝕎 k) : ℕ → k | 0 := ↑a⁻¹ | (n + 1) := succ_nth_val_units n a A (λ i, inverse_coeff i.val) using_well_founded { dec_tac := `[apply fin.is_lt] } /-- Upgrade a Witt vector `A` whose first entry `A.coeff 0` is a unit to be, itself, a unit in `𝕎 k`. -/ def mk_unit {a : units k} {A : 𝕎 k} (hA : A.coeff 0 = a) : units (𝕎 k) := units.mk_of_mul_eq_one A (witt_vector.mk p (inverse_coeff a A)) begin ext n, induction n with n ih, { simp [witt_vector.mul_coeff_zero, inverse_coeff, hA] }, let H_coeff := A.coeff (n + 1) * ↑(a⁻¹ ^ p ^ (n + 1)) + nth_remainder p n (truncate_fun (n + 1) A) (λ (i : fin (n + 1)), inverse_coeff a A i), have H := units.mul_inv (a ^ p ^ (n + 1)), linear_combination -H_coeff*H with { normalize := ff }, have ha : (a:k) ^ (p ^ (n + 1)) = ↑(a ^ (p ^ (n + 1))) := by norm_cast, have ha_inv : (↑(a⁻¹):k) ^ (p ^ (n + 1)) = ↑(a ^ (p ^ (n + 1)))⁻¹ := by exact_mod_cast inv_pow _ _, simp only [nth_remainder_spec, inverse_coeff, succ_nth_val_units, hA, fin.val_eq_coe, one_coeff_eq_of_pos, nat.succ_pos', H_coeff, ha_inv, ha, inv_pow], ring!, end @[simp] lemma coe_mk_unit {a : units k} {A : 𝕎 k} (hA : A.coeff 0 = a) : (mk_unit hA : 𝕎 k) = A := rfl end comm_ring section field variables {k : Type*} [field k] [char_p k p] lemma is_unit_of_coeff_zero_ne_zero (x : 𝕎 k) (hx : x.coeff 0 ≠ 0) : is_unit x := begin let y : kˣ := units.mk0 (x.coeff 0) hx, have hy : x.coeff 0 = y := rfl, exact (mk_unit hy).is_unit end variables (p) lemma irreducible : irreducible (p : 𝕎 k) := begin have hp : ¬ is_unit (p : 𝕎 k), { intro hp, simpa only [constant_coeff_apply, coeff_p_zero, not_is_unit_zero] using (constant_coeff : witt_vector p k →+* _).is_unit_map hp, }, refine ⟨hp, λ a b hab, _⟩, obtain ⟨ha0, hb0⟩ : a ≠ 0 ∧ b ≠ 0, { rw ← mul_ne_zero_iff, intro h, rw h at hab, exact p_nonzero p k hab }, obtain ⟨m, a, ha, rfl⟩ := verschiebung_nonzero ha0, obtain ⟨n, b, hb, rfl⟩ := verschiebung_nonzero hb0, cases m, { exact or.inl (is_unit_of_coeff_zero_ne_zero a ha) }, cases n, { exact or.inr (is_unit_of_coeff_zero_ne_zero b hb) }, rw iterate_verschiebung_mul at hab, apply_fun (λ x, coeff x 1) at hab, simp only [coeff_p_one, nat.add_succ, add_comm _ n, function.iterate_succ', function.comp_app, verschiebung_coeff_add_one, verschiebung_coeff_zero] at hab, exact (one_ne_zero hab).elim end end field section perfect_ring variables {k : Type*} [comm_ring k] [char_p k p] [perfect_ring k p] lemma exists_eq_pow_p_mul (a : 𝕎 k) (ha : a ≠ 0) : ∃ (m : ℕ) (b : 𝕎 k), b.coeff 0 ≠ 0 ∧ a = p ^ m * b := begin obtain ⟨m, c, hc, hcm⟩ := witt_vector.verschiebung_nonzero ha, obtain ⟨b, rfl⟩ := (frobenius_bijective p k).surjective.iterate m c, rw witt_vector.iterate_frobenius_coeff at hc, have := congr_fun (witt_vector.verschiebung_frobenius_comm.comp_iterate m) b, simp only [function.comp_app] at this, rw ← this at hcm, refine ⟨m, b, _, _⟩, { contrapose! hc, have : 0 < p ^ m := pow_pos (nat.prime.pos (fact.out _)) _, simp [hc, zero_pow this] }, { rw ← mul_left_iterate (p : 𝕎 k) m, convert hcm, ext1 x, rw [mul_comm, ← witt_vector.verschiebung_frobenius x] }, end end perfect_ring section perfect_field variables {k : Type*} [field k] [char_p k p] [perfect_ring k p] lemma exists_eq_pow_p_mul' (a : 𝕎 k) (ha : a ≠ 0) : ∃ (m : ℕ) (b : units (𝕎 k)), a = p ^ m * b := begin obtain ⟨m, b, h₁, h₂⟩ := exists_eq_pow_p_mul a ha, let b₀ := units.mk0 (b.coeff 0) h₁, have hb₀ : b.coeff 0 = b₀ := rfl, exact ⟨m, mk_unit hb₀, h₂⟩, end /- Note: The following lemma should be an instance, but it seems to cause some exponential blowups in certain typeclass resolution problems. See the following Lean4 issue as well as the zulip discussion linked there: https://github.com/leanprover/lean4/issues/1102 -/ /-- The ring of Witt Vectors of a perfect field of positive characteristic is a DVR. -/ lemma discrete_valuation_ring : discrete_valuation_ring (𝕎 k) := discrete_valuation_ring.of_has_unit_mul_pow_irreducible_factorization begin refine ⟨p, irreducible p, λ x hx, _⟩, obtain ⟨n, b, hb⟩ := exists_eq_pow_p_mul' x hx, exact ⟨n, b, hb.symm⟩, end end perfect_field end witt_vector
1d2d44b32911aa3ac7df0348cba80455105e9740
8b9f17008684d796c8022dab552e42f0cb6fb347
/hott/init/priority.hlean
01d5fcffdfbcdfdd3b226c38c410aa55839182a9
[ "Apache-2.0" ]
permissive
chubbymaggie/lean
0d06ae25f9dd396306fb02190e89422ea94afd7b
d2c7b5c31928c98f545b16420d37842c43b4ae9a
refs/heads/master
1,611,313,622,901
1,430,266,839,000
1,430,267,083,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
316
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: init.priority Authors: Leonardo de Moura -/ prelude import init.datatypes definition std.priority.default : num := 1000 definition std.priority.max : num := 4294967295
51cd70272fec5e699c055036ee07b24951c18613
82e44445c70db0f03e30d7be725775f122d72f3e
/src/data/finset/lattice.lean
389fc9050830af55c707ab75451ca6fb905ba835
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
41,887
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.finset.fold import data.multiset.lattice import order.order_dual import order.complete_lattice /-! # Lattice operations on finsets -/ variables {α β γ : Type*} namespace finset open multiset order_dual /-! ### sup -/ section sup variables [semilattice_sup_bot α] /-- Supremum of a finite set: `sup {a, b, c} f = f a ⊔ f b ⊔ f c` -/ def sup (s : finset β) (f : β → α) : α := s.fold (⊔) ⊥ f variables {s s₁ s₂ : finset β} {f : β → α} lemma sup_def : s.sup f = (s.1.map f).sup := rfl @[simp] lemma sup_empty : (∅ : finset β).sup f = ⊥ := fold_empty @[simp] lemma sup_cons {b : β} (h : b ∉ s) : (cons b s h).sup f = f b ⊔ s.sup f := fold_cons h @[simp] lemma sup_insert [decidable_eq β] {b : β} : (insert b s : finset β).sup f = f b ⊔ s.sup f := fold_insert_idem lemma sup_image [decidable_eq β] (s : finset γ) (f : γ → β) (g : β → α): (s.image f).sup g = s.sup (g ∘ f) := fold_image_idem @[simp] lemma sup_map (s : finset γ) (f : γ ↪ β) (g : β → α) : (s.map f).sup g = s.sup (g ∘ f) := fold_map @[simp] lemma sup_singleton {b : β} : ({b} : finset β).sup f = f b := sup_singleton lemma sup_union [decidable_eq β] : (s₁ ∪ s₂).sup f = s₁.sup f ⊔ s₂.sup f := finset.induction_on s₁ (by rw [empty_union, sup_empty, bot_sup_eq]) $ λ a s has ih, by rw [insert_union, sup_insert, sup_insert, ih, sup_assoc] theorem sup_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀a∈s₂, f a = g a) : s₁.sup f = s₂.sup g := by subst hs; exact finset.fold_congr hfg @[simp] lemma sup_le_iff {a : α} : s.sup f ≤ a ↔ (∀b ∈ s, f b ≤ a) := begin apply iff.trans multiset.sup_le, simp only [multiset.mem_map, and_imp, exists_imp_distrib], exact ⟨λ k b hb, k _ _ hb rfl, λ k a' b hb h, h ▸ k _ hb⟩, end lemma sup_const {s : finset β} (h : s.nonempty) (c : α) : s.sup (λ _, c) = c := eq_of_forall_ge_iff $ λ b, sup_le_iff.trans h.forall_const lemma sup_le {a : α} : (∀b ∈ s, f b ≤ a) → s.sup f ≤ a := sup_le_iff.2 lemma le_sup {b : β} (hb : b ∈ s) : f b ≤ s.sup f := sup_le_iff.1 (le_refl _) _ hb lemma sup_mono_fun {g : β → α} (h : ∀b∈s, f b ≤ g b) : s.sup f ≤ s.sup g := sup_le (λ b hb, le_trans (h b hb) (le_sup hb)) lemma sup_mono (h : s₁ ⊆ s₂) : s₁.sup f ≤ s₂.sup f := sup_le $ assume b hb, le_sup (h hb) @[simp] lemma sup_lt_iff [is_total α (≤)] {a : α} (ha : ⊥ < a) : s.sup f < a ↔ (∀ b ∈ s, f b < a) := ⟨(λ hs b hb, lt_of_le_of_lt (le_sup hb) hs), finset.cons_induction_on s (λ _, ha) (λ c t hc, by simpa only [sup_cons, sup_lt_iff, mem_cons, forall_eq_or_imp] using and.imp_right)⟩ @[simp] lemma le_sup_iff [is_total α (≤)] {a : α} (ha : ⊥ < a) : a ≤ s.sup f ↔ ∃ b ∈ s, a ≤ f b := ⟨finset.cons_induction_on s (λ h, absurd h (not_le_of_lt ha)) (λ c t hc ih, by simpa using @or.rec _ _ (∃ b, (b = c ∨ b ∈ t) ∧ a ≤ f b) (λ h, ⟨c, or.inl rfl, h⟩) (λ h, let ⟨b, hb, hle⟩ := ih h in ⟨b, or.inr hb, hle⟩)), (λ ⟨b, hb, hle⟩, trans hle (le_sup hb))⟩ @[simp] lemma lt_sup_iff [is_total α (≤)] {a : α} : a < s.sup f ↔ ∃ b ∈ s, a < f b := ⟨finset.cons_induction_on s (λ h, absurd h not_lt_bot) (λ c t hc ih, by simpa using @or.rec _ _ (∃ b, (b = c ∨ b ∈ t) ∧ a < f b) (λ h, ⟨c, or.inl rfl, h⟩) (λ h, let ⟨b, hb, hlt⟩ := ih h in ⟨b, or.inr hb, hlt⟩)), (λ ⟨b, hb, hlt⟩, lt_of_lt_of_le hlt (le_sup hb))⟩ lemma comp_sup_eq_sup_comp [semilattice_sup_bot γ] {s : finset β} {f : β → α} (g : α → γ) (g_sup : ∀ x y, g (x ⊔ y) = g x ⊔ g y) (bot : g ⊥ = ⊥) : g (s.sup f) = s.sup (g ∘ f) := finset.cons_induction_on s bot (λ c t hc ih, by rw [sup_cons, sup_cons, g_sup, ih]) lemma comp_sup_eq_sup_comp_of_is_total [is_total α (≤)] {γ : Type} [semilattice_sup_bot γ] (g : α → γ) (mono_g : monotone g) (bot : g ⊥ = ⊥) : g (s.sup f) = s.sup (g ∘ f) := comp_sup_eq_sup_comp g mono_g.map_sup bot /-- Computating `sup` in a subtype (closed under `sup`) is the same as computing it in `α`. -/ lemma sup_coe {P : α → Prop} {Pbot : P ⊥} {Psup : ∀{{x y}}, P x → P y → P (x ⊔ y)} (t : finset β) (f : β → {x : α // P x}) : (@sup _ _ (subtype.semilattice_sup_bot Pbot Psup) t f : α) = t.sup (λ x, f x) := by { rw [comp_sup_eq_sup_comp coe]; intros; refl } @[simp] lemma sup_to_finset {α β} [decidable_eq β] (s : finset α) (f : α → multiset β) : (s.sup f).to_finset = s.sup (λ x, (f x).to_finset) := comp_sup_eq_sup_comp multiset.to_finset to_finset_union rfl theorem subset_range_sup_succ (s : finset ℕ) : s ⊆ range (s.sup id).succ := λ n hn, mem_range.2 $ nat.lt_succ_of_le $ le_sup hn theorem exists_nat_subset_range (s : finset ℕ) : ∃n : ℕ, s ⊆ range n := ⟨_, s.subset_range_sup_succ⟩ lemma sup_induction {p : α → Prop} (hb : p ⊥) (hp : ∀ (a₁ a₂ : α), p a₁ → p a₂ → p (a₁ ⊔ a₂)) (hs : ∀ b ∈ s, p (f b)) : p (s.sup f) := begin induction s using finset.cons_induction with c s hc ih, { exact hb, }, { rw sup_cons, apply hp, { exact hs c (mem_cons.2 (or.inl rfl)), }, { exact ih (λ b h, hs b (mem_cons.2 (or.inr h))), }, }, end lemma sup_le_of_le_directed {α : Type*} [semilattice_sup_bot α] (s : set α) (hs : s.nonempty) (hdir : directed_on (≤) s) (t : finset α): (∀ x ∈ t, ∃ y ∈ s, x ≤ y) → ∃ x, x ∈ s ∧ t.sup id ≤ x := begin classical, apply finset.induction_on t, { simpa only [forall_prop_of_true, and_true, forall_prop_of_false, bot_le, not_false_iff, sup_empty, forall_true_iff, not_mem_empty], }, { intros a r har ih h, have incs : ↑r ⊆ ↑(insert a r), by { rw finset.coe_subset, apply finset.subset_insert, }, -- x ∈ s is above the sup of r obtain ⟨x, ⟨hxs, hsx_sup⟩⟩ := ih (λ x hx, h x $ incs hx), -- y ∈ s is above a obtain ⟨y, hys, hay⟩ := h a (finset.mem_insert_self a r), -- z ∈ s is above x and y obtain ⟨z, hzs, ⟨hxz, hyz⟩⟩ := hdir x hxs y hys, use [z, hzs], rw [sup_insert, id.def, _root_.sup_le_iff], exact ⟨le_trans hay hyz, le_trans hsx_sup hxz⟩, }, end -- If we acquire sublattices -- the hypotheses should be reformulated as `s : subsemilattice_sup_bot` lemma sup_mem (s : set α) (w₁ : ⊥ ∈ s) (w₂ : ∀ x y ∈ s, x ⊔ y ∈ s) {ι : Type*} (t : finset ι) (p : ι → α) (h : ∀ i ∈ t, p i ∈ s) : t.sup p ∈ s := @sup_induction _ _ _ _ _ (∈ s) w₁ w₂ h end sup lemma sup_eq_supr [complete_lattice β] (s : finset α) (f : α → β) : s.sup f = (⨆a∈s, f a) := le_antisymm (finset.sup_le $ assume a ha, le_supr_of_le a $ le_supr _ ha) (supr_le $ assume a, supr_le $ assume ha, le_sup ha) lemma sup_id_eq_Sup [complete_lattice α] (s : finset α) : s.sup id = Sup s := by simp [Sup_eq_supr, sup_eq_supr] lemma sup_eq_Sup_image [complete_lattice β] (s : finset α) (f : α → β) : s.sup f = Sup (f '' s) := begin classical, rw [←finset.coe_image, ←sup_id_eq_Sup, sup_image, function.comp.left_id], end /-! ### inf -/ section inf variables [semilattice_inf_top α] /-- Infimum of a finite set: `inf {a, b, c} f = f a ⊓ f b ⊓ f c` -/ def inf (s : finset β) (f : β → α) : α := s.fold (⊓) ⊤ f variables {s s₁ s₂ : finset β} {f : β → α} lemma inf_def : s.inf f = (s.1.map f).inf := rfl @[simp] lemma inf_empty : (∅ : finset β).inf f = ⊤ := fold_empty @[simp] lemma inf_cons {b : β} (h : b ∉ s) : (cons b s h).inf f = f b ⊓ s.inf f := @sup_cons (order_dual α) _ _ _ _ _ h @[simp] lemma inf_insert [decidable_eq β] {b : β} : (insert b s : finset β).inf f = f b ⊓ s.inf f := fold_insert_idem lemma inf_image [decidable_eq β] (s : finset γ) (f : γ → β) (g : β → α): (s.image f).inf g = s.inf (g ∘ f) := fold_image_idem @[simp] lemma inf_map (s : finset γ) (f : γ ↪ β) (g : β → α) : (s.map f).inf g = s.inf (g ∘ f) := fold_map @[simp] lemma inf_singleton {b : β} : ({b} : finset β).inf f = f b := inf_singleton lemma inf_union [decidable_eq β] : (s₁ ∪ s₂).inf f = s₁.inf f ⊓ s₂.inf f := @sup_union (order_dual α) _ _ _ _ _ _ theorem inf_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀a∈s₂, f a = g a) : s₁.inf f = s₂.inf g := by subst hs; exact finset.fold_congr hfg lemma le_inf_iff {a : α} : a ≤ s.inf f ↔ ∀ b ∈ s, a ≤ f b := @sup_le_iff (order_dual α) _ _ _ _ _ lemma inf_le {b : β} (hb : b ∈ s) : s.inf f ≤ f b := le_inf_iff.1 (le_refl _) _ hb lemma le_inf {a : α} : (∀b ∈ s, a ≤ f b) → a ≤ s.inf f := le_inf_iff.2 lemma inf_mono_fun {g : β → α} (h : ∀b∈s, f b ≤ g b) : s.inf f ≤ s.inf g := le_inf (λ b hb, le_trans (inf_le hb) (h b hb)) lemma inf_mono (h : s₁ ⊆ s₂) : s₂.inf f ≤ s₁.inf f := le_inf $ assume b hb, inf_le (h hb) @[simp] lemma lt_inf_iff [is_total α (≤)] {a : α} (ha : a < ⊤) : a < s.inf f ↔ (∀ b ∈ s, a < f b) := @sup_lt_iff (order_dual α) _ _ _ _ _ _ ha @[simp] lemma inf_le_iff [is_total α (≤)] {a : α} (ha : a < ⊤) : s.inf f ≤ a ↔ (∃ b ∈ s, f b ≤ a) := @le_sup_iff (order_dual α) _ _ _ _ _ _ ha @[simp] lemma inf_lt_iff [is_total α (≤)] {a : α} : s.inf f < a ↔ (∃ b ∈ s, f b < a) := @lt_sup_iff (order_dual α) _ _ _ _ _ _ lemma comp_inf_eq_inf_comp [semilattice_inf_top γ] {s : finset β} {f : β → α} (g : α → γ) (g_inf : ∀ x y, g (x ⊓ y) = g x ⊓ g y) (top : g ⊤ = ⊤) : g (s.inf f) = s.inf (g ∘ f) := @comp_sup_eq_sup_comp (order_dual α) _ (order_dual γ) _ _ _ _ _ g_inf top lemma comp_inf_eq_inf_comp_of_is_total [h : is_total α (≤)] {γ : Type} [semilattice_inf_top γ] (g : α → γ) (mono_g : monotone g) (top : g ⊤ = ⊤) : g (s.inf f) = s.inf (g ∘ f) := comp_inf_eq_inf_comp g mono_g.map_inf top /-- Computating `inf` in a subtype (closed under `inf`) is the same as computing it in `α`. -/ lemma inf_coe {P : α → Prop} {Ptop : P ⊤} {Pinf : ∀{{x y}}, P x → P y → P (x ⊓ y)} (t : finset β) (f : β → {x : α // P x}) : (@inf _ _ (subtype.semilattice_inf_top Ptop Pinf) t f : α) = t.inf (λ x, f x) := @sup_coe (order_dual α) _ _ _ Ptop Pinf t f lemma inf_induction {p : α → Prop} (ht : p ⊤) (hp : ∀ (a₁ a₂ : α), p a₁ → p a₂ → p (a₁ ⊓ a₂)) (hs : ∀ b ∈ s, p (f b)) : p (s.inf f) := @sup_induction (order_dual α) _ _ _ _ _ ht hp hs lemma inf_mem (s : set α) (w₁ : ⊤ ∈ s) (w₂ : ∀ x y ∈ s, x ⊓ y ∈ s) {ι : Type*} (t : finset ι) (p : ι → α) (h : ∀ i ∈ t, p i ∈ s) : t.inf p ∈ s := @inf_induction _ _ _ _ _ (∈ s) w₁ w₂ h end inf lemma inf_eq_infi [complete_lattice β] (s : finset α) (f : α → β) : s.inf f = (⨅a∈s, f a) := @sup_eq_supr _ (order_dual β) _ _ _ lemma inf_id_eq_Inf [complete_lattice α] (s : finset α) : s.inf id = Inf s := @sup_id_eq_Sup (order_dual α) _ _ lemma inf_eq_Inf_image [complete_lattice β] (s : finset α) (f : α → β) : s.inf f = Inf (f '' s) := @sup_eq_Sup_image _ (order_dual β) _ _ _ section sup' variables [semilattice_sup α] lemma sup_of_mem {s : finset β} (f : β → α) {b : β} (h : b ∈ s) : ∃ (a : α), s.sup (coe ∘ f : β → with_bot α) = ↑a := Exists.imp (λ a, Exists.fst) (@le_sup (with_bot α) _ _ _ _ _ h (f b) rfl) /-- Given nonempty finset `s` then `s.sup' H f` is the supremum of its image under `f` in (possibly unbounded) join-semilattice `α`, where `H` is a proof of nonemptiness. If `α` has a bottom element you may instead use `finset.sup` which does not require `s` nonempty. -/ def sup' (s : finset β) (H : s.nonempty) (f : β → α) : α := option.get $ let ⟨b, hb⟩ := H in option.is_some_iff_exists.2 (sup_of_mem f hb) variables {s : finset β} (H : s.nonempty) (f : β → α) @[simp] lemma coe_sup' : ((s.sup' H f : α) : with_bot α) = s.sup (coe ∘ f) := by rw [sup', ←with_bot.some_eq_coe, option.some_get] @[simp] lemma sup'_cons {b : β} {hb : b ∉ s} {h : (cons b s hb).nonempty} : (cons b s hb).sup' h f = f b ⊔ s.sup' H f := by { rw ←with_bot.coe_eq_coe, simp only [coe_sup', sup_cons, with_bot.coe_sup], } @[simp] lemma sup'_insert [decidable_eq β] {b : β} {h : (insert b s).nonempty} : (insert b s).sup' h f = f b ⊔ s.sup' H f := by { rw ←with_bot.coe_eq_coe, simp only [coe_sup', sup_insert, with_bot.coe_sup], } @[simp] lemma sup'_singleton {b : β} {h : ({b} : finset β).nonempty} : ({b} : finset β).sup' h f = f b := rfl lemma sup'_le {a : α} (hs : ∀ b ∈ s, f b ≤ a) : s.sup' H f ≤ a := by { rw [←with_bot.coe_le_coe, coe_sup'], exact sup_le (λ b h, with_bot.coe_le_coe.2 $ hs b h), } lemma le_sup' {b : β} (h : b ∈ s) : f b ≤ s.sup' ⟨b, h⟩ f := by { rw [←with_bot.coe_le_coe, coe_sup'], exact le_sup h, } @[simp] lemma sup'_const (a : α) : s.sup' H (λ b, a) = a := begin apply le_antisymm, { apply sup'_le, intros, apply le_refl, }, { apply le_sup' (λ b, a) H.some_spec, } end @[simp] lemma sup'_le_iff {a : α} : s.sup' H f ≤ a ↔ ∀ b ∈ s, f b ≤ a := iff.intro (λ h b hb, trans (le_sup' f hb) h) (sup'_le H f) @[simp] lemma sup'_lt_iff [is_total α (≤)] {a : α} : s.sup' H f < a ↔ (∀ b ∈ s, f b < a) := begin rw [←with_bot.coe_lt_coe, coe_sup', sup_lt_iff (with_bot.bot_lt_coe a)], exact ball_congr (λ b hb, with_bot.coe_lt_coe), end @[simp] lemma le_sup'_iff [is_total α (≤)] {a : α} : a ≤ s.sup' H f ↔ (∃ b ∈ s, a ≤ f b) := begin rw [←with_bot.coe_le_coe, coe_sup', le_sup_iff (with_bot.bot_lt_coe a)], exact bex_congr (λ b hb, with_bot.coe_le_coe), end @[simp] lemma lt_sup'_iff [is_total α (≤)] {a : α} : a < s.sup' H f ↔ (∃ b ∈ s, a < f b) := begin rw [←with_bot.coe_lt_coe, coe_sup', lt_sup_iff], exact bex_congr (λ b hb, with_bot.coe_lt_coe), end lemma comp_sup'_eq_sup'_comp [semilattice_sup γ] {s : finset β} (H : s.nonempty) {f : β → α} (g : α → γ) (g_sup : ∀ x y, g (x ⊔ y) = g x ⊔ g y) : g (s.sup' H f) = s.sup' H (g ∘ f) := begin rw [←with_bot.coe_eq_coe, coe_sup'], let g' : with_bot α → with_bot γ := with_bot.rec_bot_coe ⊥ (λ x, ↑(g x)), show g' ↑(s.sup' H f) = s.sup (λ a, g' ↑(f a)), rw coe_sup', refine comp_sup_eq_sup_comp g' _ rfl, intros f₁ f₂, cases f₁, { rw [with_bot.none_eq_bot, bot_sup_eq], exact bot_sup_eq.symm, }, { cases f₂, refl, exact congr_arg coe (g_sup f₁ f₂), }, end lemma sup'_induction {p : α → Prop} (hp : ∀ (a₁ a₂ : α), p a₁ → p a₂ → p (a₁ ⊔ a₂)) (hs : ∀ b ∈ s, p (f b)) : p (s.sup' H f) := begin show @with_bot.rec_bot_coe α (λ _, Prop) true p ↑(s.sup' H f), rw coe_sup', refine sup_induction trivial _ hs, intros a₁ a₂ h₁ h₂, cases a₁, { rw [with_bot.none_eq_bot, bot_sup_eq], exact h₂, }, { cases a₂, exact h₁, exact hp a₁ a₂ h₁ h₂, }, end lemma exists_mem_eq_sup' [is_total α (≤)] : ∃ b, b ∈ s ∧ s.sup' H f = f b := begin induction s using finset.cons_induction with c s hc ih, { exact false.elim (not_nonempty_empty H), }, { rcases s.eq_empty_or_nonempty with rfl | hs, { exact ⟨c, mem_singleton_self c, rfl⟩, }, { rcases ih hs with ⟨b, hb, h'⟩, rw [sup'_cons hs, h'], cases total_of (≤) (f b) (f c) with h h, { exact ⟨c, mem_cons.2 (or.inl rfl), sup_eq_left.2 h⟩, }, { exact ⟨b, mem_cons.2 (or.inr hb), sup_eq_right.2 h⟩, }, }, }, end lemma sup'_mem (s : set α) (w : ∀ x y ∈ s, x ⊔ y ∈ s) {ι : Type*} (t : finset ι) (H : t.nonempty) (p : ι → α) (h : ∀ i ∈ t, p i ∈ s) : t.sup' H p ∈ s := sup'_induction H p w h end sup' section inf' variables [semilattice_inf α] lemma inf_of_mem {s : finset β} (f : β → α) {b : β} (h : b ∈ s) : ∃ (a : α), s.inf (coe ∘ f : β → with_top α) = ↑a := @sup_of_mem (order_dual α) _ _ _ f _ h /-- Given nonempty finset `s` then `s.inf' H f` is the infimum of its image under `f` in (possibly unbounded) meet-semilattice `α`, where `H` is a proof of nonemptiness. If `α` has a top element you may instead use `finset.inf` which does not require `s` nonempty. -/ def inf' (s : finset β) (H : s.nonempty) (f : β → α) : α := @sup' (order_dual α) _ _ s H f variables {s : finset β} (H : s.nonempty) (f : β → α) @[simp] lemma coe_inf' : ((s.inf' H f : α) : with_top α) = s.inf (coe ∘ f) := @coe_sup' (order_dual α) _ _ _ H f @[simp] lemma inf'_cons {b : β} {hb : b ∉ s} {h : (cons b s hb).nonempty} : (cons b s hb).inf' h f = f b ⊓ s.inf' H f := @sup'_cons (order_dual α) _ _ _ H f _ _ _ @[simp] lemma inf'_insert [decidable_eq β] {b : β} {h : (insert b s).nonempty} : (insert b s).inf' h f = f b ⊓ s.inf' H f := @sup'_insert (order_dual α) _ _ _ H f _ _ _ @[simp] lemma inf'_singleton {b : β} {h : ({b} : finset β).nonempty} : ({b} : finset β).inf' h f = f b := rfl lemma le_inf' {a : α} (hs : ∀ b ∈ s, a ≤ f b) : a ≤ s.inf' H f := @sup'_le (order_dual α) _ _ _ H f _ hs lemma inf'_le {b : β} (h : b ∈ s) : s.inf' ⟨b, h⟩ f ≤ f b := @le_sup' (order_dual α) _ _ _ f _ h @[simp] lemma inf'_const (a : α) : s.inf' H (λ b, a) = a := @sup'_const (order_dual α) _ _ _ _ _ @[simp] lemma le_inf'_iff {a : α} : a ≤ s.inf' H f ↔ ∀ b ∈ s, a ≤ f b := @sup'_le_iff (order_dual α) _ _ _ H f _ @[simp] lemma lt_inf'_iff [is_total α (≤)] {a : α} : a < s.inf' H f ↔ (∀ b ∈ s, a < f b) := @sup'_lt_iff (order_dual α) _ _ _ H f _ _ @[simp] lemma inf'_le_iff [is_total α (≤)] {a : α} : s.inf' H f ≤ a ↔ (∃ b ∈ s, f b ≤ a) := @le_sup'_iff (order_dual α) _ _ _ H f _ _ @[simp] lemma inf'_lt_iff [is_total α (≤)] {a : α} : s.inf' H f < a ↔ (∃ b ∈ s, f b < a) := @lt_sup'_iff (order_dual α) _ _ _ H f _ _ lemma comp_inf'_eq_inf'_comp [semilattice_inf γ] {s : finset β} (H : s.nonempty) {f : β → α} (g : α → γ) (g_inf : ∀ x y, g (x ⊓ y) = g x ⊓ g y) : g (s.inf' H f) = s.inf' H (g ∘ f) := @comp_sup'_eq_sup'_comp (order_dual α) _ (order_dual γ) _ _ _ H f g g_inf lemma inf'_induction {p : α → Prop} (hp : ∀ (a₁ a₂ : α), p a₁ → p a₂ → p (a₁ ⊓ a₂)) (hs : ∀ b ∈ s, p (f b)) : p (s.inf' H f) := @sup'_induction (order_dual α) _ _ _ H f _ hp hs lemma exists_mem_eq_inf' [is_total α (≤)] : ∃ b, b ∈ s ∧ s.inf' H f = f b := @exists_mem_eq_sup' (order_dual α) _ _ _ H f _ lemma inf'_mem (s : set α) (w : ∀ x y ∈ s, x ⊓ y ∈ s) {ι : Type*} (t : finset ι) (H : t.nonempty) (p : ι → α) (h : ∀ i ∈ t, p i ∈ s) : t.inf' H p ∈ s := inf'_induction H p w h end inf' section sup variable [semilattice_sup_bot α] lemma sup'_eq_sup {s : finset β} (H : s.nonempty) (f : β → α) : s.sup' H f = s.sup f := le_antisymm (sup'_le H f (λ b, le_sup)) (sup_le (λ b, le_sup' f)) lemma sup_closed_of_sup_closed {s : set α} (t : finset α) (htne : t.nonempty) (h_subset : ↑t ⊆ s) (h : ∀⦃a b⦄, a ∈ s → b ∈ s → a ⊔ b ∈ s) : t.sup id ∈ s := sup'_eq_sup htne id ▸ sup'_induction _ _ h h_subset lemma exists_mem_eq_sup [is_total α (≤)] (s : finset β) (h : s.nonempty) (f : β → α) : ∃ b, b ∈ s ∧ s.sup f = f b := sup'_eq_sup h f ▸ exists_mem_eq_sup' h f end sup section inf variable [semilattice_inf_top α] lemma inf'_eq_inf {s : finset β} (H : s.nonempty) (f : β → α) : s.inf' H f = s.inf f := @sup'_eq_sup (order_dual α) _ _ _ H f lemma inf_closed_of_inf_closed {s : set α} (t : finset α) (htne : t.nonempty) (h_subset : ↑t ⊆ s) (h : ∀⦃a b⦄, a ∈ s → b ∈ s → a ⊓ b ∈ s) : t.inf id ∈ s := @sup_closed_of_sup_closed (order_dual α) _ _ t htne h_subset h lemma exists_mem_eq_inf [is_total α (≤)] (s : finset β) (h : s.nonempty) (f : β → α) : ∃ a, a ∈ s ∧ s.inf f = f a := @exists_mem_eq_sup (order_dual α) _ _ _ _ h f end inf section sup variables {C : β → Type*} [Π (b : β), semilattice_sup_bot (C b)] @[simp] protected lemma sup_apply (s : finset α) (f : α → Π (b : β), C b) (b : β) : s.sup f b = s.sup (λ a, f a b) := comp_sup_eq_sup_comp (λ x : Π b : β, C b, x b) (λ i j, rfl) rfl end sup section inf variables {C : β → Type*} [Π (b : β), semilattice_inf_top (C b)] @[simp] protected lemma inf_apply (s : finset α) (f : α → Π (b : β), C b) (b : β) : s.inf f b = s.inf (λ a, f a b) := @finset.sup_apply _ _ (λ b, order_dual (C b)) _ s f b end inf section sup' variables {C : β → Type*} [Π (b : β), semilattice_sup (C b)] @[simp] protected lemma sup'_apply {s : finset α} (H : s.nonempty) (f : α → Π (b : β), C b) (b : β) : s.sup' H f b = s.sup' H (λ a, f a b) := comp_sup'_eq_sup'_comp H (λ x : Π b : β, C b, x b) (λ i j, rfl) end sup' section inf' variables {C : β → Type*} [Π (b : β), semilattice_inf (C b)] @[simp] protected lemma inf'_apply {s : finset α} (H : s.nonempty) (f : α → Π (b : β), C b) (b : β) : s.inf' H f b = s.inf' H (λ a, f a b) := @finset.sup'_apply _ _ (λ b, order_dual (C b)) _ _ H f b end inf' /-! ### max and min of finite sets -/ section max_min variables [linear_order α] /-- Let `s` be a finset in a linear order. Then `s.max` is the maximum of `s` if `s` is not empty, and `none` otherwise. It belongs to `option α`. If you want to get an element of `α`, see `s.max'`. -/ protected def max : finset α → option α := fold (option.lift_or_get max) none some theorem max_eq_sup_with_bot (s : finset α) : s.max = @sup (with_bot α) α _ s some := rfl @[simp] theorem max_empty : (∅ : finset α).max = none := rfl @[simp] theorem max_insert {a : α} {s : finset α} : (insert a s).max = option.lift_or_get max (some a) s.max := fold_insert_idem @[simp] theorem max_singleton {a : α} : finset.max {a} = some a := by { rw [← insert_emptyc_eq], exact max_insert } theorem max_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ b, b ∈ s.max := (@le_sup (with_bot α) _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst theorem max_of_nonempty {s : finset α} (h : s.nonempty) : ∃ a, a ∈ s.max := let ⟨a, ha⟩ := h in max_of_mem ha theorem max_eq_none {s : finset α} : s.max = none ↔ s = ∅ := ⟨λ h, s.eq_empty_or_nonempty.elim id (λ H, let ⟨a, ha⟩ := max_of_nonempty H in by rw h at ha; cases ha), λ h, h.symm ▸ max_empty⟩ theorem mem_of_max {s : finset α} : ∀ {a : α}, a ∈ s.max → a ∈ s := finset.induction_on s (λ _ H, by cases H) (λ b s _ (ih : ∀ {a}, a ∈ s.max → a ∈ s) a (h : a ∈ (insert b s).max), begin by_cases p : b = a, { induction p, exact mem_insert_self b s }, { cases option.lift_or_get_choice max_choice (some b) s.max with q q; rw [max_insert, q] at h, { cases h, cases p rfl }, { exact mem_insert_of_mem (ih h) } } end) theorem le_max_of_mem {s : finset α} {a b : α} (h₁ : a ∈ s) (h₂ : b ∈ s.max) : a ≤ b := by rcases @le_sup (with_bot α) _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩; cases h₂.symm.trans hb; assumption /-- Let `s` be a finset in a linear order. Then `s.min` is the minimum of `s` if `s` is not empty, and `none` otherwise. It belongs to `option α`. If you want to get an element of `α`, see `s.min'`. -/ protected def min : finset α → option α := fold (option.lift_or_get min) none some theorem min_eq_inf_with_top (s : finset α) : s.min = @inf (with_top α) α _ s some := rfl @[simp] theorem min_empty : (∅ : finset α).min = none := rfl @[simp] theorem min_insert {a : α} {s : finset α} : (insert a s).min = option.lift_or_get min (some a) s.min := fold_insert_idem @[simp] theorem min_singleton {a : α} : finset.min {a} = some a := by { rw ← insert_emptyc_eq, exact min_insert } theorem min_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ b, b ∈ s.min := (@inf_le (with_top α) _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst theorem min_of_nonempty {s : finset α} (h : s.nonempty) : ∃ a, a ∈ s.min := let ⟨a, ha⟩ := h in min_of_mem ha theorem min_eq_none {s : finset α} : s.min = none ↔ s = ∅ := ⟨λ h, s.eq_empty_or_nonempty.elim id (λ H, let ⟨a, ha⟩ := min_of_nonempty H in by rw h at ha; cases ha), λ h, h.symm ▸ min_empty⟩ theorem mem_of_min {s : finset α} : ∀ {a : α}, a ∈ s.min → a ∈ s := @mem_of_max (order_dual α) _ s theorem min_le_of_mem {s : finset α} {a b : α} (h₁ : b ∈ s) (h₂ : a ∈ s.min) : a ≤ b := by rcases @inf_le (with_top α) _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩; cases h₂.symm.trans hb; assumption /-- Given a nonempty finset `s` in a linear order `α `, then `s.min' h` is its minimum, as an element of `α`, where `h` is a proof of nonemptiness. Without this assumption, use instead `s.min`, taking values in `option α`. -/ def min' (s : finset α) (H : s.nonempty) : α := @option.get _ s.min $ let ⟨k, hk⟩ := H in let ⟨b, hb⟩ := min_of_mem hk in by simp at hb; simp [hb] /-- Given a nonempty finset `s` in a linear order `α `, then `s.max' h` is its maximum, as an element of `α`, where `h` is a proof of nonemptiness. Without this assumption, use instead `s.max`, taking values in `option α`. -/ def max' (s : finset α) (H : s.nonempty) : α := @option.get _ s.max $ let ⟨k, hk⟩ := H in let ⟨b, hb⟩ := max_of_mem hk in by simp at hb; simp [hb] variables (s : finset α) (H : s.nonempty) theorem min'_mem : s.min' H ∈ s := mem_of_min $ by simp [min'] theorem min'_le (x) (H2 : x ∈ s) : s.min' ⟨x, H2⟩ ≤ x := min_le_of_mem H2 $ option.get_mem _ theorem le_min' (x) (H2 : ∀ y ∈ s, x ≤ y) : x ≤ s.min' H := H2 _ $ min'_mem _ _ theorem is_least_min' : is_least ↑s (s.min' H) := ⟨min'_mem _ _, min'_le _⟩ @[simp] lemma le_min'_iff {x} : x ≤ s.min' H ↔ ∀ y ∈ s, x ≤ y := le_is_glb_iff (is_least_min' s H).is_glb /-- `{a}.min' _` is `a`. -/ @[simp] lemma min'_singleton (a : α) : ({a} : finset α).min' (singleton_nonempty _) = a := by simp [min'] theorem max'_mem : s.max' H ∈ s := mem_of_max $ by simp [max'] theorem le_max' (x) (H2 : x ∈ s) : x ≤ s.max' ⟨x, H2⟩ := le_max_of_mem H2 $ option.get_mem _ theorem max'_le (x) (H2 : ∀ y ∈ s, y ≤ x) : s.max' H ≤ x := H2 _ $ max'_mem _ _ theorem is_greatest_max' : is_greatest ↑s (s.max' H) := ⟨max'_mem _ _, le_max' _⟩ @[simp] lemma max'_le_iff {x} : s.max' H ≤ x ↔ ∀ y ∈ s, y ≤ x := is_lub_le_iff (is_greatest_max' s H).is_lub /-- `{a}.max' _` is `a`. -/ @[simp] lemma max'_singleton (a : α) : ({a} : finset α).max' (singleton_nonempty _) = a := by simp [max'] theorem min'_lt_max' {i j} (H1 : i ∈ s) (H2 : j ∈ s) (H3 : i ≠ j) : s.min' ⟨i, H1⟩ < s.max' ⟨i, H1⟩ := is_glb_lt_is_lub_of_ne (s.is_least_min' _).is_glb (s.is_greatest_max' _).is_lub H1 H2 H3 /-- If there's more than 1 element, the min' is less than the max'. An alternate version of `min'_lt_max'` which is sometimes more convenient. -/ lemma min'_lt_max'_of_card (h₂ : 1 < card s) : s.min' (finset.card_pos.mp $ lt_trans zero_lt_one h₂) < s.max' (finset.card_pos.mp $ lt_trans zero_lt_one h₂) := begin rcases one_lt_card.1 h₂ with ⟨a, ha, b, hb, hab⟩, exact s.min'_lt_max' ha hb hab end lemma max'_eq_of_dual_min' {s : finset α} (hs : s.nonempty) : max' s hs = of_dual (min' (image to_dual s) (nonempty.image hs to_dual)) := begin rw [of_dual, to_dual, equiv.coe_fn_mk, equiv.coe_fn_symm_mk, id.def], simp_rw (@image_id (order_dual α) (s : finset (order_dual α))), refl, end lemma min'_eq_of_dual_max' {s : finset α} (hs : s.nonempty) : min' s hs = of_dual (max' (image to_dual s) (nonempty.image hs to_dual)) := begin rw [of_dual, to_dual, equiv.coe_fn_mk, equiv.coe_fn_symm_mk, id.def], simp_rw (@image_id (order_dual α) (s : finset (order_dual α))), refl, end @[simp] lemma of_dual_max_eq_min_of_dual {a b : α} : of_dual (max a b) = min (of_dual a) (of_dual b) := rfl @[simp] lemma of_dual_min_eq_max_of_dual {a b : α} : of_dual (min a b) = max (of_dual a) (of_dual b) := rfl lemma max'_subset {s t : finset α} (H : s.nonempty) (hst : s ⊆ t) : s.max' H ≤ t.max' (H.mono hst) := le_max' _ _ (hst (s.max'_mem H)) lemma min'_subset {s t : finset α} (H : s.nonempty) (hst : s ⊆ t) : t.min' (H.mono hst) ≤ s.min' H := min'_le _ _ (hst (s.min'_mem H)) lemma max'_insert (a : α) (s : finset α) (H : s.nonempty) : (insert a s).max' (s.insert_nonempty a) = max (s.max' H) a := (is_greatest_max' _ _).unique $ by { rw [coe_insert, max_comm], exact (is_greatest_max' _ _).insert _ } lemma min'_insert (a : α) (s : finset α) (H : s.nonempty) : (insert a s).min' (s.insert_nonempty a) = min (s.min' H) a := (is_least_min' _ _).unique $ by { rw [coe_insert, min_comm], exact (is_least_min' _ _).insert _ } /-- Induction principle for `finset`s in a linearly ordered type: a predicate is true on all `s : finset α` provided that: * it is true on the empty `finset`, * for every `s : finset α` and an element `a` strictly greater than all elements of `s`, `p s` implies `p (insert a s)`. -/ @[elab_as_eliminator] lemma induction_on_max [decidable_eq α] {p : finset α → Prop} (s : finset α) (h0 : p ∅) (step : ∀ a s, (∀ x ∈ s, x < a) → p s → p (insert a s)) : p s := begin induction hn : s.card with n ihn generalizing s, { rwa [card_eq_zero.1 hn] }, { have A : s.nonempty, from card_pos.1 (hn.symm ▸ n.succ_pos), have B : s.max' A ∈ s, from max'_mem s A, rw [← insert_erase B], refine step _ _ (λ x hx, _) (ihn _ _), { rw [mem_erase] at hx, exact (le_max' s x hx.2).lt_of_ne hx.1 }, { rw [card_erase_of_mem B, hn, nat.pred_succ] } } end /-- Induction principle for `finset`s in a linearly ordered type: a predicate is true on all `s : finset α` provided that: * it is true on the empty `finset`, * for every `s : finset α` and an element `a` strictly less than all elements of `s`, `p s` implies `p (insert a s)`. -/ @[elab_as_eliminator] lemma induction_on_min [decidable_eq α] {p : finset α → Prop} (s : finset α) (h0 : p ∅) (step : ∀ a s, (∀ x ∈ s, a < x) → p s → p (insert a s)) : p s := @induction_on_max (order_dual α) _ _ _ s h0 step end max_min section exists_max_min variables [linear_order α] lemma exists_max_image (s : finset β) (f : β → α) (h : s.nonempty) : ∃ x ∈ s, ∀ x' ∈ s, f x' ≤ f x := begin cases max_of_nonempty (h.image f) with y hy, rcases mem_image.mp (mem_of_max hy) with ⟨x, hx, rfl⟩, exact ⟨x, hx, λ x' hx', le_max_of_mem (mem_image_of_mem f hx') hy⟩, end lemma exists_min_image (s : finset β) (f : β → α) (h : s.nonempty) : ∃ x ∈ s, ∀ x' ∈ s, f x ≤ f x' := @exists_max_image (order_dual α) β _ s f h end exists_max_min end finset namespace multiset lemma count_sup [decidable_eq β] (s : finset α) (f : α → multiset β) (b : β) : count b (s.sup f) = s.sup (λa, count b (f a)) := begin letI := classical.dec_eq α, refine s.induction _ _, { exact count_zero _ }, { assume i s his ih, rw [finset.sup_insert, sup_eq_union, count_union, finset.sup_insert, ih], refl } end lemma mem_sup {α β} [decidable_eq β] {s : finset α} {f : α → multiset β} {x : β} : x ∈ s.sup f ↔ ∃ v ∈ s, x ∈ f v := begin classical, apply s.induction_on, { simp }, { intros a s has hxs, rw [finset.sup_insert, multiset.sup_eq_union, multiset.mem_union], split, { intro hxi, cases hxi with hf hf, { refine ⟨a, _, hf⟩, simp only [true_or, eq_self_iff_true, finset.mem_insert] }, { rcases hxs.mp hf with ⟨v, hv, hfv⟩, refine ⟨v, _, hfv⟩, simp only [hv, or_true, finset.mem_insert] } }, { rintros ⟨v, hv, hfv⟩, rw [finset.mem_insert] at hv, rcases hv with rfl | hv, { exact or.inl hfv }, { refine or.inr (hxs.mpr ⟨v, hv, hfv⟩) } } }, end end multiset namespace finset lemma mem_sup {α β} [decidable_eq β] {s : finset α} {f : α → finset β} {x : β} : x ∈ s.sup f ↔ ∃ v ∈ s, x ∈ f v := begin change _ ↔ ∃ v ∈ s, x ∈ (f v).val, rw [←multiset.mem_sup, ←multiset.mem_to_finset, sup_to_finset], simp_rw [val_to_finset], end lemma sup_eq_bUnion {α β} [decidable_eq β] (s : finset α) (t : α → finset β) : s.sup t = s.bUnion t := by { ext, rw [mem_sup, mem_bUnion], } end finset section lattice variables {ι : Type*} {ι' : Sort*} [complete_lattice α] /-- Supremum of `s i`, `i : ι`, is equal to the supremum over `t : finset ι` of suprema `⨆ i ∈ t, s i`. This version assumes `ι` is a `Type*`. See `supr_eq_supr_finset'` for a version that works for `ι : Sort*`. -/ lemma supr_eq_supr_finset (s : ι → α) : (⨆i, s i) = (⨆t:finset ι, ⨆i∈t, s i) := begin classical, exact le_antisymm (supr_le $ assume b, le_supr_of_le {b} $ le_supr_of_le b $ le_supr_of_le (by simp) $ le_refl _) (supr_le $ assume t, supr_le $ assume b, supr_le $ assume hb, le_supr _ _) end /-- Supremum of `s i`, `i : ι`, is equal to the supremum over `t : finset ι` of suprema `⨆ i ∈ t, s i`. This version works for `ι : Sort*`. See `supr_eq_supr_finset` for a version that assumes `ι : Type*` but has no `plift`s. -/ lemma supr_eq_supr_finset' (s : ι' → α) : (⨆i, s i) = (⨆t:finset (plift ι'), ⨆i∈t, s (plift.down i)) := by rw [← supr_eq_supr_finset, ← equiv.plift.surjective.supr_comp]; refl /-- Infimum of `s i`, `i : ι`, is equal to the infimum over `t : finset ι` of infima `⨆ i ∈ t, s i`. This version assumes `ι` is a `Type*`. See `infi_eq_infi_finset'` for a version that works for `ι : Sort*`. -/ lemma infi_eq_infi_finset (s : ι → α) : (⨅i, s i) = (⨅t:finset ι, ⨅i∈t, s i) := @supr_eq_supr_finset (order_dual α) _ _ _ /-- Infimum of `s i`, `i : ι`, is equal to the infimum over `t : finset ι` of infima `⨆ i ∈ t, s i`. This version works for `ι : Sort*`. See `infi_eq_infi_finset` for a version that assumes `ι : Type*` but has no `plift`s. -/ lemma infi_eq_infi_finset' (s : ι' → α) : (⨅i, s i) = (⨅t:finset (plift ι'), ⨅i∈t, s (plift.down i)) := @supr_eq_supr_finset' (order_dual α) _ _ _ end lattice namespace set variables {ι : Type*} {ι' : Sort*} /-- Union of an indexed family of sets `s : ι → set α` is equal to the union of the unions of finite subfamilies. This version assumes `ι : Type*`. See also `Union_eq_Union_finset'` for a version that works for `ι : Sort*`. -/ lemma Union_eq_Union_finset (s : ι → set α) : (⋃i, s i) = (⋃t:finset ι, ⋃i∈t, s i) := supr_eq_supr_finset s /-- Union of an indexed family of sets `s : ι → set α` is equal to the union of the unions of finite subfamilies. This version works for `ι : Sort*`. See also `Union_eq_Union_finset` for a version that assumes `ι : Type*` but avoids `plift`s in the right hand side. -/ lemma Union_eq_Union_finset' (s : ι' → set α) : (⋃i, s i) = (⋃t:finset (plift ι'), ⋃i∈t, s (plift.down i)) := supr_eq_supr_finset' s /-- Intersection of an indexed family of sets `s : ι → set α` is equal to the intersection of the intersections of finite subfamilies. This version assumes `ι : Type*`. See also `Inter_eq_Inter_finset'` for a version that works for `ι : Sort*`. -/ lemma Inter_eq_Inter_finset (s : ι → set α) : (⋂i, s i) = (⋂t:finset ι, ⋂i∈t, s i) := infi_eq_infi_finset s /-- Intersection of an indexed family of sets `s : ι → set α` is equal to the intersection of the intersections of finite subfamilies. This version works for `ι : Sort*`. See also `Inter_eq_Inter_finset` for a version that assumes `ι : Type*` but avoids `plift`s in the right hand side. -/ lemma Inter_eq_Inter_finset' (s : ι' → set α) : (⋂i, s i) = (⋂t:finset (plift ι'), ⋂i∈t, s (plift.down i)) := infi_eq_infi_finset' s end set namespace finset open function /-! ### Interaction with big lattice/set operations -/ section lattice lemma supr_coe [has_Sup β] (f : α → β) (s : finset α) : (⨆ x ∈ (↑s : set α), f x) = ⨆ x ∈ s, f x := rfl lemma infi_coe [has_Inf β] (f : α → β) (s : finset α) : (⨅ x ∈ (↑s : set α), f x) = ⨅ x ∈ s, f x := rfl variables [complete_lattice β] theorem supr_singleton (a : α) (s : α → β) : (⨆ x ∈ ({a} : finset α), s x) = s a := by simp theorem infi_singleton (a : α) (s : α → β) : (⨅ x ∈ ({a} : finset α), s x) = s a := by simp lemma supr_option_to_finset (o : option α) (f : α → β) : (⨆ x ∈ o.to_finset, f x) = ⨆ x ∈ o, f x := by simp lemma infi_option_to_finset (o : option α) (f : α → β) : (⨅ x ∈ o.to_finset, f x) = ⨅ x ∈ o, f x := @supr_option_to_finset _ (order_dual β) _ _ _ variables [decidable_eq α] theorem supr_union {f : α → β} {s t : finset α} : (⨆ x ∈ s ∪ t, f x) = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) := by simp [supr_or, supr_sup_eq] theorem infi_union {f : α → β} {s t : finset α} : (⨅ x ∈ s ∪ t, f x) = (⨅ x ∈ s, f x) ⊓ (⨅ x ∈ t, f x) := @supr_union α (order_dual β) _ _ _ _ _ lemma supr_insert (a : α) (s : finset α) (t : α → β) : (⨆ x ∈ insert a s, t x) = t a ⊔ (⨆ x ∈ s, t x) := by { rw insert_eq, simp only [supr_union, finset.supr_singleton] } lemma infi_insert (a : α) (s : finset α) (t : α → β) : (⨅ x ∈ insert a s, t x) = t a ⊓ (⨅ x ∈ s, t x) := @supr_insert α (order_dual β) _ _ _ _ _ lemma supr_finset_image {f : γ → α} {g : α → β} {s : finset γ} : (⨆ x ∈ s.image f, g x) = (⨆ y ∈ s, g (f y)) := by rw [← supr_coe, coe_image, supr_image, supr_coe] lemma sup_finset_image {β γ : Type*} [semilattice_sup_bot β] (f : γ → α) (g : α → β) (s : finset γ) : (s.image f).sup g = s.sup (g ∘ f) := begin classical, induction s using finset.induction_on with a s' ha ih; simp * end lemma infi_finset_image {f : γ → α} {g : α → β} {s : finset γ} : (⨅ x ∈ s.image f, g x) = (⨅ y ∈ s, g (f y)) := by rw [← infi_coe, coe_image, infi_image, infi_coe] lemma supr_insert_update {x : α} {t : finset α} (f : α → β) {s : β} (hx : x ∉ t) : (⨆ (i ∈ insert x t), function.update f x s i) = (s ⊔ ⨆ (i ∈ t), f i) := begin simp only [finset.supr_insert, update_same], rcongr i hi, apply update_noteq, rintro rfl, exact hx hi end lemma infi_insert_update {x : α} {t : finset α} (f : α → β) {s : β} (hx : x ∉ t) : (⨅ (i ∈ insert x t), update f x s i) = (s ⊓ ⨅ (i ∈ t), f i) := @supr_insert_update α (order_dual β) _ _ _ _ f _ hx lemma supr_bUnion (s : finset γ) (t : γ → finset α) (f : α → β) : (⨆ y ∈ s.bUnion t, f y) = ⨆ (x ∈ s) (y ∈ t x), f y := by simp [@supr_comm _ α, supr_and] lemma infi_bUnion (s : finset γ) (t : γ → finset α) (f : α → β) : (⨅ y ∈ s.bUnion t, f y) = ⨅ (x ∈ s) (y ∈ t x), f y := @supr_bUnion _ (order_dual β) _ _ _ _ _ _ end lattice theorem set_bUnion_coe (s : finset α) (t : α → set β) : (⋃ x ∈ (↑s : set α), t x) = ⋃ x ∈ s, t x := rfl theorem set_bInter_coe (s : finset α) (t : α → set β) : (⋂ x ∈ (↑s : set α), t x) = ⋂ x ∈ s, t x := rfl theorem set_bUnion_singleton (a : α) (s : α → set β) : (⋃ x ∈ ({a} : finset α), s x) = s a := supr_singleton a s theorem set_bInter_singleton (a : α) (s : α → set β) : (⋂ x ∈ ({a} : finset α), s x) = s a := infi_singleton a s @[simp] lemma set_bUnion_preimage_singleton (f : α → β) (s : finset β) : (⋃ y ∈ s, f ⁻¹' {y}) = f ⁻¹' s := set.bUnion_preimage_singleton f s lemma set_bUnion_option_to_finset (o : option α) (f : α → set β) : (⋃ x ∈ o.to_finset, f x) = ⋃ x ∈ o, f x := supr_option_to_finset o f lemma set_bInter_option_to_finset (o : option α) (f : α → set β) : (⋂ x ∈ o.to_finset, f x) = ⋂ x ∈ o, f x := infi_option_to_finset o f variables [decidable_eq α] lemma set_bUnion_union (s t : finset α) (u : α → set β) : (⋃ x ∈ s ∪ t, u x) = (⋃ x ∈ s, u x) ∪ (⋃ x ∈ t, u x) := supr_union lemma set_bInter_inter (s t : finset α) (u : α → set β) : (⋂ x ∈ s ∪ t, u x) = (⋂ x ∈ s, u x) ∩ (⋂ x ∈ t, u x) := infi_union lemma set_bUnion_insert (a : α) (s : finset α) (t : α → set β) : (⋃ x ∈ insert a s, t x) = t a ∪ (⋃ x ∈ s, t x) := supr_insert a s t lemma set_bInter_insert (a : α) (s : finset α) (t : α → set β) : (⋂ x ∈ insert a s, t x) = t a ∩ (⋂ x ∈ s, t x) := infi_insert a s t lemma set_bUnion_finset_image {f : γ → α} {g : α → set β} {s : finset γ} : (⋃x ∈ s.image f, g x) = (⋃y ∈ s, g (f y)) := supr_finset_image lemma set_bInter_finset_image {f : γ → α} {g : α → set β} {s : finset γ} : (⋂ x ∈ s.image f, g x) = (⋂ y ∈ s, g (f y)) := infi_finset_image lemma set_bUnion_insert_update {x : α} {t : finset α} (f : α → set β) {s : set β} (hx : x ∉ t) : (⋃ (i ∈ insert x t), @update _ _ _ f x s i) = (s ∪ ⋃ (i ∈ t), f i) := supr_insert_update f hx lemma set_bInter_insert_update {x : α} {t : finset α} (f : α → set β) {s : set β} (hx : x ∉ t) : (⋂ (i ∈ insert x t), @update _ _ _ f x s i) = (s ∩ ⋂ (i ∈ t), f i) := infi_insert_update f hx lemma set_bUnion_bUnion (s : finset γ) (t : γ → finset α) (f : α → set β) : (⋃ y ∈ s.bUnion t, f y) = ⋃ (x ∈ s) (y ∈ t x), f y := supr_bUnion s t f lemma set_bInter_bUnion (s : finset γ) (t : γ → finset α) (f : α → set β) : (⋂ y ∈ s.bUnion t, f y) = ⋂ (x ∈ s) (y ∈ t x), f y := infi_bUnion s t f end finset
7d9e76e04c00c698e07d418e25f88483c633a534
618003631150032a5676f229d13a079ac875ff77
/src/measure_theory/probability_mass_function.lean
f81b9401472af8cab0094cbfa607d27166afa931
[ "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
4,771
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl Probability mass function -- discrete probability measures -/ import topology.instances.ennreal noncomputable theory variables {α : Type*} {β : Type*} {γ : Type*} open_locale classical /-- Probability mass functions, i.e. discrete probability measures -/ def {u} pmf (α : Type u) : Type u := { f : α → nnreal // has_sum f 1 } namespace pmf instance : has_coe_to_fun (pmf α) := ⟨λp, α → nnreal, λp a, p.1 a⟩ @[ext] protected lemma ext : ∀{p q : pmf α}, (∀a, p a = q a) → p = q | ⟨f, hf⟩ ⟨g, hg⟩ eq := subtype.eq $ funext eq lemma has_sum_coe_one (p : pmf α) : has_sum p 1 := p.2 lemma summable_coe (p : pmf α) : summable p := (p.has_sum_coe_one).summable @[simp] lemma tsum_coe (p : pmf α) : (∑'a, p a) = 1 := tsum_eq_has_sum p.has_sum_coe_one def support (p : pmf α) : set α := {a | p.1 a ≠ 0} def pure (a : α) : pmf α := ⟨λa', if a' = a then 1 else 0, has_sum_ite_eq _ _⟩ @[simp] lemma pure_apply (a a' : α) : pure a a' = (if a' = a then 1 else 0) := rfl instance [inhabited α] : inhabited (pmf α) := ⟨pure (default α)⟩ lemma coe_le_one (p : pmf α) (a : α) : p a ≤ 1 := has_sum_le (by intro b; split_ifs; simp [h]; exact le_refl _) (has_sum_ite_eq a (p a)) p.2 protected lemma bind.summable (p : pmf α) (f : α → pmf β) (b : β) : summable (λa:α, p a * f a b) := begin refine nnreal.summable_of_le (assume a, _) p.summable_coe, suffices : p a * f a b ≤ p a * 1, { simpa }, exact mul_le_mul_of_nonneg_left ((f a).coe_le_one _) (p a).2 end def bind (p : pmf α) (f : α → pmf β) : pmf β := ⟨λb, (∑'a, p a * f a b), begin apply ennreal.has_sum_coe.1, simp only [ennreal.coe_tsum (bind.summable p f _)], rw [ennreal.summable.has_sum_iff, ennreal.tsum_comm], simp [ennreal.tsum_mul_left, (ennreal.coe_tsum (f _).summable_coe).symm, (ennreal.coe_tsum p.summable_coe).symm] end⟩ @[simp] lemma bind_apply (p : pmf α) (f : α → pmf β) (b : β) : p.bind f b = (∑'a, p a * f a b) := rfl lemma coe_bind_apply (p : pmf α) (f : α → pmf β) (b : β) : (p.bind f b : ennreal) = (∑'a, p a * f a b) := eq.trans (ennreal.coe_tsum $ bind.summable p f b) $ by simp @[simp] lemma pure_bind (a : α) (f : α → pmf β) : (pure a).bind f = f a := have ∀b a', ite (a' = a) 1 0 * f a' b = ite (a' = a) (f a b) 0, from assume b a', by split_ifs; simp; subst h; simp, by ext b; simp [this] @[simp] lemma bind_pure (p : pmf α) : p.bind pure = p := have ∀a a', (p a * ite (a' = a) 1 0) = ite (a = a') (p a') 0, from assume a a', begin split_ifs; try { subst a }; try { subst a' }; simp * at * end, by ext b; simp [this] @[simp] lemma bind_bind (p : pmf α) (f : α → pmf β) (g : β → pmf γ) : (p.bind f).bind g = p.bind (λa, (f a).bind g) := begin ext b, simp only [ennreal.coe_eq_coe.symm, coe_bind_apply, ennreal.tsum_mul_left.symm, ennreal.tsum_mul_right.symm], rw [ennreal.tsum_comm], simp [mul_assoc, mul_left_comm, mul_comm] end lemma bind_comm (p : pmf α) (q : pmf β) (f : α → β → pmf γ) : p.bind (λa, q.bind (f a)) = q.bind (λb, p.bind (λa, f a b)) := begin ext b, simp only [ennreal.coe_eq_coe.symm, coe_bind_apply, ennreal.tsum_mul_left.symm, ennreal.tsum_mul_right.symm], rw [ennreal.tsum_comm], simp [mul_assoc, mul_left_comm, mul_comm] end def map (f : α → β) (p : pmf α) : pmf β := bind p (pure ∘ f) lemma bind_pure_comp (f : α → β) (p : pmf α) : bind p (pure ∘ f) = map f p := rfl lemma map_id (p : pmf α) : map id p = p := by simp [map] lemma map_comp (p : pmf α) (f : α → β) (g : β → γ) : (p.map f).map g = p.map (g ∘ f) := by simp [map] lemma pure_map (a : α) (f : α → β) : (pure a).map f = pure (f a) := by simp [map] def seq (f : pmf (α → β)) (p : pmf α) : pmf β := f.bind (λm, p.bind $ λa, pure (m a)) def of_multiset (s : multiset α) (hs : s ≠ 0) : pmf α := ⟨λa, s.count a / s.card, have s.to_finset.sum (λa, (s.count a : ℝ) / s.card) = 1, by simp [div_eq_inv_mul, finset.mul_sum.symm, (finset.sum_nat_cast _ _).symm, hs], have s.to_finset.sum (λa, (s.count a : nnreal) / s.card) = 1, by rw [← nnreal.eq_iff, nnreal.coe_one, ← this, nnreal.coe_sum]; simp, begin rw ← this, apply has_sum_sum_of_ne_finset_zero, simp {contextual := tt}, end⟩ def of_fintype [fintype α] (f : α → nnreal) (h : finset.univ.sum f = 1) : pmf α := ⟨f, h ▸ has_sum_sum_of_ne_finset_zero (by simp)⟩ def bernoulli (p : nnreal) (h : p ≤ 1) : pmf bool := of_fintype (λb, cond b p (1 - p)) (nnreal.eq $ by simp [h]) end pmf
67571c8f979840530bf80a3a41f6b1473ea90471
cc62cd292c1acc80a10b1c645915b70d2cdee661
/src/category_theory/enriched.lean
dde16f5f0e5749772640365e7b091276c0343c90
[]
no_license
RitaAhmadi/lean-category-theory
4afb881c4b387ee2c8ce706c454fbf9db8897a29
a27b4ae5eac978e9188d2e867c3d11d9a5b87a9e
refs/heads/master
1,651,786,183,402
1,565,604,314,000
1,565,604,314,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,302
lean
-- import category_theory.limits.limits -- import category_theory.limits.preserves -- import category_theory.limits.types -- import category_theory.fully_faithful -- open category_theory.limits -- universes v u -- namespace category_theory -- variables {C : Type u} [𝒞 : category.{v} C] -- variables (V : Type (v+1)) [𝒱 : large_category V] -- [has_terminal.{v+1 v} V] [has_binary_products.{v+1 v} V] -- (ℱ : V ⥤ Type v) [faithful ℱ] [preserves_limits ℱ] -- include 𝒞 𝒱 -- class enriched_over := -- (enriched_hom : C → C → V) -- (enriched_id : Π {X : C}, terminal V ⟶ enriched_hom X X) -- (enriched_comp : Π {X Y Z : C}, limits.prod (enriched_hom X Y) (enriched_hom Y Z) ⟶ enriched_hom X Z) -- (fibre_hom : Π {X Y : C}, ℱ.obj (enriched_hom X Y) ≅ (X ⟶ Y)) -- /- to state compatibility between enriched_comp and comp, we need that the fibre functor preserves limits -/ -- -- TODO simple examples -- /- The category of types is enriched over itself. -/ -- -- instance : enriched_over.{u v} (Type v) (functor.id _) := -- -- { enriched_hom := λ X Y, X ⟶ Y, -- -- enriched_id := λ (X : C) _, 𝟙 X, -- -- enriched_comp := λ X Y Z, begin dsimp, exact λ p, p.1 ≫ p.2, end, -- -- fibre_hom := by obviously } -- end category_theory
3dba108692a5165bb1142cc9167ab7f1e4351524
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/metric_space/kuratowski.lean
99fd9607cca3707f3e389b170cc6ab99ca20e1de
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
5,216
lean
/- Copyright (c) 2018 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.normed_space.lp_space import topology.sets.compacts /-! # The Kuratowski embedding Any separable metric space can be embedded isometrically in `ℓ^∞(ℝ)`. -/ noncomputable theory open set metric topological_space open_locale ennreal local notation `ℓ_infty_ℝ`:= lp (λ n : ℕ, ℝ) ∞ universes u v w variables {α : Type u} {β : Type v} {γ : Type w} namespace Kuratowski_embedding /-! ### Any separable metric space can be embedded isometrically in ℓ^∞(ℝ) -/ variables {f g : ℓ_infty_ℝ} {n : ℕ} {C : ℝ} [metric_space α] (x : ℕ → α) (a b : α) /-- A metric space can be embedded in `l^∞(ℝ)` via the distances to points in a fixed countable set, if this set is dense. This map is given in `Kuratowski_embedding`, without density assumptions. -/ def embedding_of_subset : ℓ_infty_ℝ := ⟨ λ n, dist a (x n) - dist (x 0) (x n), begin apply mem_ℓp_infty, use dist a (x 0), rintros - ⟨n, rfl⟩, exact abs_dist_sub_le _ _ _ end ⟩ lemma embedding_of_subset_coe : embedding_of_subset x a n = dist a (x n) - dist (x 0) (x n) := rfl /-- The embedding map is always a semi-contraction. -/ lemma embedding_of_subset_dist_le (a b : α) : dist (embedding_of_subset x a) (embedding_of_subset x b) ≤ dist a b := begin refine lp.norm_le_of_forall_le dist_nonneg (λn, _), simp only [lp.coe_fn_sub, pi.sub_apply, embedding_of_subset_coe, real.dist_eq], convert abs_dist_sub_le a b (x n) using 2, ring end /-- When the reference set is dense, the embedding map is an isometry on its image. -/ lemma embedding_of_subset_isometry (H : dense_range x) : isometry (embedding_of_subset x) := begin refine isometry.of_dist_eq (λa b, _), refine (embedding_of_subset_dist_le x a b).antisymm (le_of_forall_pos_le_add (λe epos, _)), /- First step: find n with dist a (x n) < e -/ rcases metric.mem_closure_range_iff.1 (H a) (e/2) (half_pos epos) with ⟨n, hn⟩, /- Second step: use the norm control at index n to conclude -/ have C : dist b (x n) - dist a (x n) = embedding_of_subset x b n - embedding_of_subset x a n := by { simp only [embedding_of_subset_coe, sub_sub_sub_cancel_right] }, have := calc dist a b ≤ dist a (x n) + dist (x n) b : dist_triangle _ _ _ ... = 2 * dist a (x n) + (dist b (x n) - dist a (x n)) : by { simp [dist_comm], ring } ... ≤ 2 * dist a (x n) + |dist b (x n) - dist a (x n)| : by apply_rules [add_le_add_left, le_abs_self] ... ≤ 2 * (e/2) + |embedding_of_subset x b n - embedding_of_subset x a n| : begin rw C, apply_rules [add_le_add, mul_le_mul_of_nonneg_left, hn.le, le_refl], norm_num end ... ≤ 2 * (e/2) + dist (embedding_of_subset x b) (embedding_of_subset x a) : begin have : |embedding_of_subset x b n - embedding_of_subset x a n| ≤ dist (embedding_of_subset x b) (embedding_of_subset x a), { simpa [dist_eq_norm] using lp.norm_apply_le_norm ennreal.top_ne_zero (embedding_of_subset x b - embedding_of_subset x a) n }, nlinarith, end ... = dist (embedding_of_subset x b) (embedding_of_subset x a) + e : by ring, simpa [dist_comm] using this end /-- Every separable metric space embeds isometrically in `ℓ_infty_ℝ`. -/ theorem exists_isometric_embedding (α : Type u) [metric_space α] [separable_space α] : ∃(f : α → ℓ_infty_ℝ), isometry f := begin cases (univ : set α).eq_empty_or_nonempty with h h, { use (λ_, 0), assume x, exact absurd h (nonempty.ne_empty ⟨x, mem_univ x⟩) }, { /- We construct a map x : ℕ → α with dense image -/ rcases h with ⟨basepoint⟩, haveI : inhabited α := ⟨basepoint⟩, have : ∃s:set α, s.countable ∧ dense s := exists_countable_dense α, rcases this with ⟨S, ⟨S_countable, S_dense⟩⟩, rcases set.countable_iff_exists_subset_range.1 S_countable with ⟨x, x_range⟩, /- Use embedding_of_subset to construct the desired isometry -/ exact ⟨embedding_of_subset x, embedding_of_subset_isometry x (S_dense.mono x_range)⟩ } end end Kuratowski_embedding open topological_space Kuratowski_embedding /-- The Kuratowski embedding is an isometric embedding of a separable metric space in `ℓ^∞(ℝ)`. -/ def Kuratowski_embedding (α : Type u) [metric_space α] [separable_space α] : α → ℓ_infty_ℝ := classical.some (Kuratowski_embedding.exists_isometric_embedding α) /-- The Kuratowski embedding is an isometry. -/ protected lemma Kuratowski_embedding.isometry (α : Type u) [metric_space α] [separable_space α] : isometry (Kuratowski_embedding α) := classical.some_spec (exists_isometric_embedding α) /-- Version of the Kuratowski embedding for nonempty compacts -/ def nonempty_compacts.Kuratowski_embedding (α : Type u) [metric_space α] [compact_space α] [nonempty α] : nonempty_compacts ℓ_infty_ℝ := { carrier := range (Kuratowski_embedding α), is_compact' := is_compact_range (Kuratowski_embedding.isometry α).continuous, nonempty' := range_nonempty _ }
545204123fc12fb0434e43a5c0468c9d9ba1de34
626e312b5c1cb2d88fca108f5933076012633192
/src/topology/continuous_on.lean
b93e3932de15ee49c240cf9bf38612f0ec602419
[ "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
47,388
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.constructions /-! # Neighborhoods and continuity relative to a subset This file defines relative versions * `nhds_within` of `nhds` * `continuous_on` of `continuous` * `continuous_within_at` of `continuous_at` and proves their basic properties, including the relationships between these restricted notions and the corresponding notions for the subtype equipped with the subspace topology. ## Notation * `𝓝 x`: the filter of neighborhoods of a point `x`; * `𝓟 s`: the principal filter of a set `s`; * `𝓝[s] x`: the filter `nhds_within x s` of neighborhoods of a point `x` within a set `s`. -/ open set filter open_locale topological_space filter variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables [topological_space α] @[simp] lemma nhds_bind_nhds_within {a : α} {s : set α} : (𝓝 a).bind (λ x, 𝓝[s] x) = 𝓝[s] a := bind_inf_principal.trans $ congr_arg2 _ nhds_bind_nhds rfl @[simp] lemma eventually_nhds_nhds_within {a : α} {s : set α} {p : α → Prop} : (∀ᶠ y in 𝓝 a, ∀ᶠ x in 𝓝[s] y, p x) ↔ ∀ᶠ x in 𝓝[s] a, p x := filter.ext_iff.1 nhds_bind_nhds_within {x | p x} lemma eventually_nhds_within_iff {a : α} {s : set α} {p : α → Prop} : (∀ᶠ x in 𝓝[s] a, p x) ↔ ∀ᶠ x in 𝓝 a, x ∈ s → p x := eventually_inf_principal @[simp] lemma eventually_nhds_within_nhds_within {a : α} {s : set α} {p : α → Prop} : (∀ᶠ y in 𝓝[s] a, ∀ᶠ x in 𝓝[s] y, p x) ↔ ∀ᶠ x in 𝓝[s] a, p x := begin refine ⟨λ h, _, λ h, (eventually_nhds_nhds_within.2 h).filter_mono inf_le_left⟩, simp only [eventually_nhds_within_iff] at h ⊢, exact h.mono (λ x hx hxs, (hx hxs).self_of_nhds hxs) end theorem nhds_within_eq (a : α) (s : set α) : 𝓝[s] a = ⨅ t ∈ {t : set α | a ∈ t ∧ is_open t}, 𝓟 (t ∩ s) := ((nhds_basis_opens a).inf_principal s).eq_binfi theorem nhds_within_univ (a : α) : 𝓝[set.univ] a = 𝓝 a := by rw [nhds_within, principal_univ, inf_top_eq] lemma nhds_within_has_basis {p : β → Prop} {s : β → set α} {a : α} (h : (𝓝 a).has_basis p s) (t : set α) : (𝓝[t] a).has_basis p (λ i, s i ∩ t) := h.inf_principal t lemma nhds_within_basis_open (a : α) (t : set α) : (𝓝[t] a).has_basis (λ u, a ∈ u ∧ is_open u) (λ u, u ∩ t) := nhds_within_has_basis (nhds_basis_opens a) t theorem mem_nhds_within {t : set α} {a : α} {s : set α} : t ∈ 𝓝[s] a ↔ ∃ u, is_open u ∧ a ∈ u ∧ u ∩ s ⊆ t := by simpa only [exists_prop, and_assoc, and_comm] using (nhds_within_basis_open a s).mem_iff lemma mem_nhds_within_iff_exists_mem_nhds_inter {t : set α} {a : α} {s : set α} : t ∈ 𝓝[s] a ↔ ∃ u ∈ 𝓝 a, u ∩ s ⊆ t := (nhds_within_has_basis (𝓝 a).basis_sets s).mem_iff lemma diff_mem_nhds_within_compl {X : Type*} [topological_space X] {x : X} {s : set X} (hs : s ∈ 𝓝 x) (t : set X) : s \ t ∈ 𝓝[tᶜ] x := diff_mem_inf_principal_compl hs t lemma nhds_of_nhds_within_of_nhds {s t : set α} {a : α} (h1 : s ∈ 𝓝 a) (h2 : t ∈ 𝓝[s] a) : (t ∈ 𝓝 a) := begin rcases mem_nhds_within_iff_exists_mem_nhds_inter.mp h2 with ⟨_, Hw, hw⟩, exact (nhds a).sets_of_superset ((nhds a).inter_sets Hw h1) hw, end lemma preimage_nhds_within_coinduced' {π : α → β} {s : set β} {t : set α} {a : α} (h : a ∈ t) (ht : is_open t) (hs : s ∈ @nhds β (topological_space.coinduced (λ x : t, π x) subtype.topological_space) (π a)) : π ⁻¹' s ∈ 𝓝[t] a := begin letI := topological_space.coinduced (λ x : t, π x) subtype.topological_space, rcases mem_nhds_iff.mp hs with ⟨V, hVs, V_op, mem_V⟩, refine mem_nhds_within_iff_exists_mem_nhds_inter.mpr ⟨π ⁻¹' V, mem_nhds_iff.mpr ⟨t ∩ π ⁻¹' V, inter_subset_right t (π ⁻¹' V), _, mem_sep h mem_V⟩, subset.trans (inter_subset_left _ _) (preimage_mono hVs)⟩, obtain ⟨u, hu1, hu2⟩ := is_open_induced_iff.mp (is_open_coinduced.1 V_op), rw [preimage_comp] at hu2, rw [set.inter_comm, ←(subtype.preimage_coe_eq_preimage_coe_iff.mp hu2)], exact hu1.inter ht, end lemma mem_nhds_within_of_mem_nhds {s t : set α} {a : α} (h : s ∈ 𝓝 a) : s ∈ 𝓝[t] a := mem_inf_of_left h theorem self_mem_nhds_within {a : α} {s : set α} : s ∈ 𝓝[s] a := mem_inf_of_right (mem_principal_self s) theorem inter_mem_nhds_within (s : set α) {t : set α} {a : α} (h : t ∈ 𝓝 a) : s ∩ t ∈ 𝓝[s] a := inter_mem self_mem_nhds_within (mem_inf_of_left h) theorem nhds_within_mono (a : α) {s t : set α} (h : s ⊆ t) : 𝓝[s] a ≤ 𝓝[t] a := inf_le_inf_left _ (principal_mono.mpr h) lemma pure_le_nhds_within {a : α} {s : set α} (ha : a ∈ s) : pure a ≤ 𝓝[s] a := le_inf (pure_le_nhds a) (le_principal_iff.2 ha) lemma mem_of_mem_nhds_within {a : α} {s t : set α} (ha : a ∈ s) (ht : t ∈ 𝓝[s] a) : a ∈ t := pure_le_nhds_within ha ht lemma filter.eventually.self_of_nhds_within {p : α → Prop} {s : set α} {x : α} (h : ∀ᶠ y in 𝓝[s] x, p y) (hx : x ∈ s) : p x := mem_of_mem_nhds_within hx h lemma tendsto_const_nhds_within {l : filter β} {s : set α} {a : α} (ha : a ∈ s) : tendsto (λ x : β, a) l (𝓝[s] a) := tendsto_const_pure.mono_right $ pure_le_nhds_within ha theorem nhds_within_restrict'' {a : α} (s : set α) {t : set α} (h : t ∈ 𝓝[s] a) : 𝓝[s] a = 𝓝[s ∩ t] a := le_antisymm (le_inf inf_le_left (le_principal_iff.mpr (inter_mem self_mem_nhds_within h))) (inf_le_inf_left _ (principal_mono.mpr (set.inter_subset_left _ _))) theorem nhds_within_restrict' {a : α} (s : set α) {t : set α} (h : t ∈ 𝓝 a) : 𝓝[s] a = 𝓝[s ∩ t] a := nhds_within_restrict'' s $ mem_inf_of_left h theorem nhds_within_restrict {a : α} (s : set α) {t : set α} (h₀ : a ∈ t) (h₁ : is_open t) : 𝓝[s] a = 𝓝[s ∩ t] a := nhds_within_restrict' s (is_open.mem_nhds h₁ h₀) theorem nhds_within_le_of_mem {a : α} {s t : set α} (h : s ∈ 𝓝[t] a) : 𝓝[t] a ≤ 𝓝[s] a := begin rcases mem_nhds_within.1 h with ⟨u, u_open, au, uts⟩, have : 𝓝[t] a = 𝓝[t ∩ u] a := nhds_within_restrict _ au u_open, rw [this, inter_comm], exact nhds_within_mono _ uts end theorem nhds_within_le_nhds {a : α} {s : set α} : 𝓝[s] a ≤ 𝓝 a := by { rw ← nhds_within_univ, apply nhds_within_le_of_mem, exact univ_mem } theorem nhds_within_eq_nhds_within {a : α} {s t u : set α} (h₀ : a ∈ s) (h₁ : is_open s) (h₂ : t ∩ s = u ∩ s) : 𝓝[t] a = 𝓝[u] a := by rw [nhds_within_restrict t h₀ h₁, nhds_within_restrict u h₀ h₁, h₂] theorem nhds_within_eq_of_open {a : α} {s : set α} (h₀ : a ∈ s) (h₁ : is_open s) : 𝓝[s] a = 𝓝 a := inf_eq_left.2 $ le_principal_iff.2 $ is_open.mem_nhds h₁ h₀ lemma preimage_nhds_within_coinduced {π : α → β} {s : set β} {t : set α} {a : α} (h : a ∈ t) (ht : is_open t) (hs : s ∈ @nhds β (topological_space.coinduced (λ x : t, π x) subtype.topological_space) (π a)) : π ⁻¹' s ∈ 𝓝 a := by { rw ←nhds_within_eq_of_open h ht, exact preimage_nhds_within_coinduced' h ht hs } @[simp] theorem nhds_within_empty (a : α) : 𝓝[∅] a = ⊥ := by rw [nhds_within, principal_empty, inf_bot_eq] theorem nhds_within_union (a : α) (s t : set α) : 𝓝[s ∪ t] a = 𝓝[s] a ⊔ 𝓝[t] a := by { delta nhds_within, rw [←inf_sup_left, sup_principal] } theorem nhds_within_inter (a : α) (s t : set α) : 𝓝[s ∩ t] a = 𝓝[s] a ⊓ 𝓝[t] a := by { delta nhds_within, rw [inf_left_comm, inf_assoc, inf_principal, ←inf_assoc, inf_idem] } theorem nhds_within_inter' (a : α) (s t : set α) : 𝓝[s ∩ t] a = (𝓝[s] a) ⊓ 𝓟 t := by { delta nhds_within, rw [←inf_principal, inf_assoc] } theorem nhds_within_inter_of_mem {a : α} {s t : set α} (h : s ∈ 𝓝[t] a) : 𝓝[s ∩ t] a = 𝓝[t] a := by { rw [nhds_within_inter, inf_eq_right], exact nhds_within_le_of_mem h } @[simp] theorem nhds_within_singleton (a : α) : 𝓝[{a}] a = pure a := by rw [nhds_within, principal_singleton, inf_eq_right.2 (pure_le_nhds a)] @[simp] theorem nhds_within_insert (a : α) (s : set α) : 𝓝[insert a s] a = pure a ⊔ 𝓝[s] a := by rw [← singleton_union, nhds_within_union, nhds_within_singleton] lemma mem_nhds_within_insert {a : α} {s t : set α} : t ∈ 𝓝[insert a s] a ↔ a ∈ t ∧ t ∈ 𝓝[s] a := by simp lemma insert_mem_nhds_within_insert {a : α} {s t : set α} (h : t ∈ 𝓝[s] a) : insert a t ∈ 𝓝[insert a s] a := by simp [mem_of_superset h] lemma nhds_within_prod_eq {α : Type*} [topological_space α] {β : Type*} [topological_space β] (a : α) (b : β) (s : set α) (t : set β) : 𝓝[s.prod t] (a, b) = 𝓝[s] a ×ᶠ 𝓝[t] b := by { delta nhds_within, rw [nhds_prod_eq, ←filter.prod_inf_prod, filter.prod_principal_principal] } lemma nhds_within_prod {α : Type*} [topological_space α] {β : Type*} [topological_space β] {s u : set α} {t v : set β} {a : α} {b : β} (hu : u ∈ 𝓝[s] a) (hv : v ∈ 𝓝[t] b) : (u.prod v) ∈ 𝓝[s.prod t] (a, b) := by { rw nhds_within_prod_eq, exact prod_mem_prod hu hv, } lemma nhds_within_pi_eq' {ι : Type*} {α : ι → Type*} [Π i, topological_space (α i)] {I : set ι} (hI : finite I) (s : Π i, set (α i)) (x : Π i, α i) : 𝓝[pi I s] x = ⨅ i, comap (λ x, x i) (𝓝 (x i) ⊓ ⨅ (hi : i ∈ I), 𝓟 (s i)) := by simp only [nhds_within, nhds_pi, comap_inf, comap_infi, pi_def, comap_principal, ← infi_principal_finite hI, ← infi_inf_eq] lemma nhds_within_pi_eq {ι : Type*} {α : ι → Type*} [Π i, topological_space (α i)] {I : set ι} (hI : finite I) (s : Π i, set (α i)) (x : Π i, α i) : 𝓝[pi I s] x = (⨅ i ∈ I, comap (λ x, x i) (𝓝[s i] (x i))) ⊓ ⨅ (i ∉ I), comap (λ x, x i) (𝓝 (x i)) := begin simp only [nhds_within, nhds_pi, pi_def, ← infi_principal_finite hI, comap_inf, comap_principal, function.eval], rw [infi_split _ (λ i, i ∈ I), inf_right_comm], simp only [infi_inf_eq] end lemma nhds_within_pi_univ_eq {ι : Type*} {α : ι → Type*} [fintype ι] [Π i, topological_space (α i)] (s : Π i, set (α i)) (x : Π i, α i) : 𝓝[pi univ s] x = ⨅ i, comap (λ x, x i) 𝓝[s i] (x i) := by simpa [nhds_within] using nhds_within_pi_eq finite_univ s x lemma nhds_within_pi_univ_eq_bot {ι : Type*} {α : ι → Type*} [Π i, topological_space (α i)] {s : Π i, set (α i)} {x : Π i, α i} : 𝓝[pi univ s] x = ⊥ ↔ ∃ i, 𝓝[s i] (x i) = ⊥ := begin classical, split, { haveI : Π i, inhabited (α i) := λ i, ⟨x i⟩, simp only [nhds_within, nhds_pi, inf_principal_eq_bot, mem_infi', mem_comap], rintro ⟨I, hIf, V, hV, hVs⟩, choose! t htx htV using hV, contrapose! hVs, change ∀ i, ∃ᶠ y in 𝓝 (x i), y ∈ s i at hVs, have : ∀ i ∈ I, (s i ∩ t i).nonempty, from λ i hi, ((hVs i).and_eventually (htx i hi)).exists, choose! y hys hyt, choose z hzs using λ i, (hVs i).exists, suffices : I.piecewise y z ∈ (⋂ i ∈ I, V i) ∩ (pi univ s), { intro H, simpa [← H] }, refine ⟨mem_bInter $ λ i hi, htV i hi _, λ i hi', _⟩, { simp only [mem_preimage, piecewise_eq_of_mem _ _ _ hi, hyt i hi] }, { by_cases hi : i ∈ I; simp * } }, { rintro ⟨i, eq⟩, rw [← @map_eq_bot_iff _ _ _ (λ x : Π i, α i, x i)], refine eq_bot_mono _ eq, exact ((continuous_apply i).tendsto x).inf (tendsto_principal_principal.2 $ λ y hy, hy i trivial) } end lemma nhds_within_pi_eq_bot {ι : Type*} {α : ι → Type*} [Π i, topological_space (α i)] {I : set ι} {s : Π i, set (α i)} {x : Π i, α i} : 𝓝[pi I s] x = ⊥ ↔ ∃ i ∈ I, 𝓝[s i] (x i) = ⊥ := begin classical, rw [← univ_pi_piecewise I, nhds_within_pi_univ_eq_bot], refine exists_congr (λ i, _), by_cases hi : i ∈ I; simp [*, nhds_within_univ, nhds_ne_bot.ne] end lemma nhds_within_pi_ne_bot {ι : Type*} {α : ι → Type*} [Π i, topological_space (α i)] {I : set ι} {s : Π i, set (α i)} {x : Π i, α i} : (𝓝[pi I s] x).ne_bot ↔ ∀ i ∈ I, (𝓝[s i] (x i)).ne_bot := by simp [ne_bot_iff, nhds_within_pi_eq_bot] theorem filter.tendsto.piecewise_nhds_within {f g : α → β} {t : set α} [∀ x, decidable (x ∈ t)] {a : α} {s : set α} {l : filter β} (h₀ : tendsto f (𝓝[s ∩ t] a) l) (h₁ : tendsto g (𝓝[s ∩ tᶜ] a) l) : tendsto (piecewise t f g) (𝓝[s] a) l := by apply tendsto.piecewise; rwa ← nhds_within_inter' theorem filter.tendsto.if_nhds_within {f g : α → β} {p : α → Prop} [decidable_pred p] {a : α} {s : set α} {l : filter β} (h₀ : tendsto f (𝓝[s ∩ {x | p x}] a) l) (h₁ : tendsto g (𝓝[s ∩ {x | ¬ p x}] a) l) : tendsto (λ x, if p x then f x else g x) (𝓝[s] a) l := h₀.piecewise_nhds_within h₁ lemma map_nhds_within (f : α → β) (a : α) (s : set α) : map f (𝓝[s] a) = ⨅ t ∈ {t : set α | a ∈ t ∧ is_open t}, 𝓟 (f '' (t ∩ s)) := ((nhds_within_basis_open a s).map f).eq_binfi theorem tendsto_nhds_within_mono_left {f : α → β} {a : α} {s t : set α} {l : filter β} (hst : s ⊆ t) (h : tendsto f (𝓝[t] a) l) : tendsto f (𝓝[s] a) l := h.mono_left $ nhds_within_mono a hst theorem tendsto_nhds_within_mono_right {f : β → α} {l : filter β} {a : α} {s t : set α} (hst : s ⊆ t) (h : tendsto f l (𝓝[s] a)) : tendsto f l (𝓝[t] a) := h.mono_right (nhds_within_mono a hst) theorem tendsto_nhds_within_of_tendsto_nhds {f : α → β} {a : α} {s : set α} {l : filter β} (h : tendsto f (𝓝 a) l) : tendsto f (𝓝[s] a) l := h.mono_left inf_le_left theorem principal_subtype {α : Type*} (s : set α) (t : set {x // x ∈ s}) : 𝓟 t = comap coe (𝓟 ((coe : s → α) '' t)) := by rw [comap_principal, set.preimage_image_eq _ subtype.coe_injective] lemma nhds_within_ne_bot_of_mem {s : set α} {x : α} (hx : x ∈ s) : ne_bot (𝓝[s] x) := mem_closure_iff_nhds_within_ne_bot.1 $ subset_closure hx lemma is_closed.mem_of_nhds_within_ne_bot {s : set α} (hs : is_closed s) {x : α} (hx : ne_bot $ 𝓝[s] x) : x ∈ s := by simpa only [hs.closure_eq] using mem_closure_iff_nhds_within_ne_bot.2 hx lemma dense_range.nhds_within_ne_bot {ι : Type*} {f : ι → α} (h : dense_range f) (x : α) : ne_bot (𝓝[range f] x) := mem_closure_iff_cluster_pt.1 (h x) lemma mem_closure_pi {ι : Type*} {α : ι → Type*} [Π i, topological_space (α i)] {I : set ι} {s : Π i, set (α i)} {x : Π i, α i} : x ∈ closure (pi I s) ↔ ∀ i ∈ I, x i ∈ closure (s i) := by simp only [mem_closure_iff_nhds_within_ne_bot, nhds_within_pi_ne_bot] lemma closure_pi_set {ι : Type*} {α : ι → Type*} [Π i, topological_space (α i)] (I : set ι) (s : Π i, set (α i)) : closure (pi I s) = pi I (λ i, closure (s i)) := set.ext $ λ x, mem_closure_pi lemma dense_pi {ι : Type*} {α : ι → Type*} [Π i, topological_space (α i)] {s : Π i, set (α i)} (I : set ι) (hs : ∀ i ∈ I, dense (s i)) : dense (pi I s) := by simp only [dense_iff_closure_eq, closure_pi_set, pi_congr rfl (λ i hi, (hs i hi).closure_eq), pi_univ] lemma eventually_eq_nhds_within_iff {f g : α → β} {s : set α} {a : α} : (f =ᶠ[𝓝[s] a] g) ↔ ∀ᶠ x in 𝓝 a, x ∈ s → f x = g x := mem_inf_principal lemma eventually_eq_nhds_within_of_eq_on {f g : α → β} {s : set α} {a : α} (h : eq_on f g s) : f =ᶠ[𝓝[s] a] g := mem_inf_of_right h lemma set.eq_on.eventually_eq_nhds_within {f g : α → β} {s : set α} {a : α} (h : eq_on f g s) : f =ᶠ[𝓝[s] a] g := eventually_eq_nhds_within_of_eq_on h lemma tendsto_nhds_within_congr {f g : α → β} {s : set α} {a : α} {l : filter β} (hfg : ∀ x ∈ s, f x = g x) (hf : tendsto f (𝓝[s] a) l) : tendsto g (𝓝[s] a) l := (tendsto_congr' $ eventually_eq_nhds_within_of_eq_on hfg).1 hf lemma eventually_nhds_with_of_forall {s : set α} {a : α} {p : α → Prop} (h : ∀ x ∈ s, p x) : ∀ᶠ x in 𝓝[s] a, p x := mem_inf_of_right h lemma tendsto_nhds_within_of_tendsto_nhds_of_eventually_within {a : α} {l : filter β} {s : set α} (f : β → α) (h1 : tendsto f l (𝓝 a)) (h2 : ∀ᶠ x in l, f x ∈ s) : tendsto f l (𝓝[s] a) := tendsto_inf.2 ⟨h1, tendsto_principal.2 h2⟩ @[simp] lemma tendsto_nhds_within_range {a : α} {l : filter β} {f : β → α} : tendsto f l (𝓝[range f] a) ↔ tendsto f l (𝓝 a) := ⟨λ h, h.mono_right inf_le_left, λ h, tendsto_inf.2 ⟨h, tendsto_principal.2 $ eventually_of_forall mem_range_self⟩⟩ lemma filter.eventually_eq.eq_of_nhds_within {s : set α} {f g : α → β} {a : α} (h : f =ᶠ[𝓝[s] a] g) (hmem : a ∈ s) : f a = g a := h.self_of_nhds_within hmem lemma eventually_nhds_within_of_eventually_nhds {α : Type*} [topological_space α] {s : set α} {a : α} {p : α → Prop} (h : ∀ᶠ x in 𝓝 a, p x) : ∀ᶠ x in 𝓝[s] a, p x := mem_nhds_within_of_mem_nhds h /-! ### `nhds_within` and subtypes -/ theorem mem_nhds_within_subtype {s : set α} {a : {x // x ∈ s}} {t u : set {x // x ∈ s}} : t ∈ 𝓝[u] a ↔ t ∈ comap (coe : s → α) (𝓝[coe '' u] a) := by rw [nhds_within, nhds_subtype, principal_subtype, ←comap_inf, ←nhds_within] theorem nhds_within_subtype (s : set α) (a : {x // x ∈ s}) (t : set {x // x ∈ s}) : 𝓝[t] a = comap (coe : s → α) (𝓝[coe '' t] a) := filter.ext $ λ u, mem_nhds_within_subtype theorem nhds_within_eq_map_subtype_coe {s : set α} {a : α} (h : a ∈ s) : 𝓝[s] a = map (coe : s → α) (𝓝 ⟨a, h⟩) := by simpa only [subtype.range_coe] using (embedding_subtype_coe.map_nhds_eq ⟨a, h⟩).symm theorem mem_nhds_subtype_iff_nhds_within {s : set α} {a : s} {t : set s} : t ∈ 𝓝 a ↔ coe '' t ∈ 𝓝[s] (a : α) := by rw [nhds_within_eq_map_subtype_coe a.coe_prop, mem_map, preimage_image_eq _ subtype.coe_injective, subtype.coe_eta] theorem preimage_coe_mem_nhds_subtype {s t : set α} {a : s} : coe ⁻¹' t ∈ 𝓝 a ↔ t ∈ 𝓝[s] ↑a := by simp only [mem_nhds_subtype_iff_nhds_within, subtype.image_preimage_coe, inter_mem_iff, self_mem_nhds_within, and_true] theorem tendsto_nhds_within_iff_subtype {s : set α} {a : α} (h : a ∈ s) (f : α → β) (l : filter β) : tendsto f (𝓝[s] a) l ↔ tendsto (s.restrict f) (𝓝 ⟨a, h⟩) l := by simp only [tendsto, nhds_within_eq_map_subtype_coe h, filter.map_map, restrict] variables [topological_space β] [topological_space γ] [topological_space δ] /-- A function between topological spaces is continuous at a point `x₀` within a subset `s` if `f x` tends to `f x₀` when `x` tends to `x₀` while staying within `s`. -/ def continuous_within_at (f : α → β) (s : set α) (x : α) : Prop := tendsto f (𝓝[s] x) (𝓝 (f x)) /-- If a function is continuous within `s` at `x`, then it tends to `f x` within `s` by definition. We register this fact for use with the dot notation, especially to use `tendsto.comp` as `continuous_within_at.comp` will have a different meaning. -/ lemma continuous_within_at.tendsto {f : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) : tendsto f (𝓝[s] x) (𝓝 (f x)) := h /-- A function between topological spaces is continuous on a subset `s` when it's continuous at every point of `s` within `s`. -/ def continuous_on (f : α → β) (s : set α) : Prop := ∀ x ∈ s, continuous_within_at f s x lemma continuous_on.continuous_within_at {f : α → β} {s : set α} {x : α} (hf : continuous_on f s) (hx : x ∈ s) : continuous_within_at f s x := hf x hx theorem continuous_within_at_univ (f : α → β) (x : α) : continuous_within_at f set.univ x ↔ continuous_at f x := by rw [continuous_at, continuous_within_at, nhds_within_univ] theorem continuous_within_at_iff_continuous_at_restrict (f : α → β) {x : α} {s : set α} (h : x ∈ s) : continuous_within_at f s x ↔ continuous_at (s.restrict f) ⟨x, h⟩ := tendsto_nhds_within_iff_subtype h f _ theorem continuous_within_at.tendsto_nhds_within {f : α → β} {x : α} {s : set α} {t : set β} (h : continuous_within_at f s x) (ht : maps_to f s t) : tendsto f (𝓝[s] x) (𝓝[t] (f x)) := tendsto_inf.2 ⟨h, tendsto_principal.2 $ mem_inf_of_right $ mem_principal.2 $ ht⟩ theorem continuous_within_at.tendsto_nhds_within_image {f : α → β} {x : α} {s : set α} (h : continuous_within_at f s x) : tendsto f (𝓝[s] x) (𝓝[f '' s] (f x)) := h.tendsto_nhds_within (maps_to_image _ _) lemma continuous_within_at.prod_map {f : α → γ} {g : β → δ} {s : set α} {t : set β} {x : α} {y : β} (hf : continuous_within_at f s x) (hg : continuous_within_at g t y) : continuous_within_at (prod.map f g) (s.prod t) (x, y) := begin unfold continuous_within_at at *, rw [nhds_within_prod_eq, prod.map, nhds_prod_eq], exact hf.prod_map hg, end lemma continuous_within_at_pi {ι : Type*} {π : ι → Type*} [∀ i, topological_space (π i)] {f : α → Π i, π i} {s : set α} {x : α} : continuous_within_at f s x ↔ ∀ i, continuous_within_at (λ y, f y i) s x := tendsto_pi lemma continuous_on_pi {ι : Type*} {π : ι → Type*} [∀ i, topological_space (π i)] {f : α → Π i, π i} {s : set α} : continuous_on f s ↔ ∀ i, continuous_on (λ y, f y i) s := ⟨λ h i x hx, tendsto_pi.1 (h x hx) i, λ h x hx, tendsto_pi.2 (λ i, h i x hx)⟩ theorem continuous_on_iff {f : α → β} {s : set α} : continuous_on f s ↔ ∀ x ∈ s, ∀ t : set β, is_open t → f x ∈ t → ∃ u, is_open u ∧ x ∈ u ∧ u ∩ s ⊆ f ⁻¹' t := by simp only [continuous_on, continuous_within_at, tendsto_nhds, mem_nhds_within] theorem continuous_on_iff_continuous_restrict {f : α → β} {s : set α} : continuous_on f s ↔ continuous (s.restrict f) := begin rw [continuous_on, continuous_iff_continuous_at], split, { rintros h ⟨x, xs⟩, exact (continuous_within_at_iff_continuous_at_restrict f xs).mp (h x xs) }, intros h x xs, exact (continuous_within_at_iff_continuous_at_restrict f xs).mpr (h ⟨x, xs⟩) end theorem continuous_on_iff' {f : α → β} {s : set α} : continuous_on f s ↔ ∀ t : set β, is_open t → ∃ u, is_open u ∧ f ⁻¹' t ∩ s = u ∩ s := have ∀ t, is_open (s.restrict f ⁻¹' t) ↔ ∃ (u : set α), is_open u ∧ f ⁻¹' t ∩ s = u ∩ s, begin intro t, rw [is_open_induced_iff, set.restrict_eq, set.preimage_comp], simp only [subtype.preimage_coe_eq_preimage_coe_iff], split; { rintros ⟨u, ou, useq⟩, exact ⟨u, ou, useq.symm⟩ } end, by rw [continuous_on_iff_continuous_restrict, continuous_def]; simp only [this] theorem continuous_on_iff_is_closed {f : α → β} {s : set α} : continuous_on f s ↔ ∀ t : set β, is_closed t → ∃ u, is_closed u ∧ f ⁻¹' t ∩ s = u ∩ s := have ∀ t, is_closed (s.restrict f ⁻¹' t) ↔ ∃ (u : set α), is_closed u ∧ f ⁻¹' t ∩ s = u ∩ s, begin intro t, rw [is_closed_induced_iff, set.restrict_eq, set.preimage_comp], simp only [subtype.preimage_coe_eq_preimage_coe_iff, eq_comm] end, by rw [continuous_on_iff_continuous_restrict, continuous_iff_is_closed]; simp only [this] lemma continuous_on.prod_map {f : α → γ} {g : β → δ} {s : set α} {t : set β} (hf : continuous_on f s) (hg : continuous_on g t) : continuous_on (prod.map f g) (s.prod t) := λ ⟨x, y⟩ ⟨hx, hy⟩, continuous_within_at.prod_map (hf x hx) (hg y hy) lemma continuous_on_empty (f : α → β) : continuous_on f ∅ := λ x, false.elim theorem nhds_within_le_comap {x : α} {s : set α} {f : α → β} (ctsf : continuous_within_at f s x) : 𝓝[s] x ≤ comap f (𝓝[f '' s] (f x)) := map_le_iff_le_comap.1 ctsf.tendsto_nhds_within_image theorem continuous_within_at_iff_ptendsto_res (f : α → β) {x : α} {s : set α} : continuous_within_at f s x ↔ ptendsto (pfun.res f s) (𝓝 x) (𝓝 (f x)) := tendsto_iff_ptendsto _ _ _ _ lemma continuous_iff_continuous_on_univ {f : α → β} : continuous f ↔ continuous_on f univ := by simp [continuous_iff_continuous_at, continuous_on, continuous_at, continuous_within_at, nhds_within_univ] lemma continuous_within_at.mono {f : α → β} {s t : set α} {x : α} (h : continuous_within_at f t x) (hs : s ⊆ t) : continuous_within_at f s x := h.mono_left (nhds_within_mono x hs) lemma continuous_within_at.mono_of_mem {f : α → β} {s t : set α} {x : α} (h : continuous_within_at f t x) (hs : t ∈ 𝓝[s] x) : continuous_within_at f s x := h.mono_left (nhds_within_le_of_mem hs) lemma continuous_within_at_inter' {f : α → β} {s t : set α} {x : α} (h : t ∈ 𝓝[s] x) : continuous_within_at f (s ∩ t) x ↔ continuous_within_at f s x := by simp [continuous_within_at, nhds_within_restrict'' s h] lemma continuous_within_at_inter {f : α → β} {s t : set α} {x : α} (h : t ∈ 𝓝 x) : continuous_within_at f (s ∩ t) x ↔ continuous_within_at f s x := by simp [continuous_within_at, nhds_within_restrict' s h] lemma continuous_within_at_union {f : α → β} {s t : set α} {x : α} : continuous_within_at f (s ∪ t) x ↔ continuous_within_at f s x ∧ continuous_within_at f t x := by simp only [continuous_within_at, nhds_within_union, tendsto_sup] lemma continuous_within_at.union {f : α → β} {s t : set α} {x : α} (hs : continuous_within_at f s x) (ht : continuous_within_at f t x) : continuous_within_at f (s ∪ t) x := continuous_within_at_union.2 ⟨hs, ht⟩ lemma continuous_within_at.mem_closure_image {f : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) (hx : x ∈ closure s) : f x ∈ closure (f '' s) := by haveI := (mem_closure_iff_nhds_within_ne_bot.1 hx); exact (mem_closure_of_tendsto h $ mem_of_superset self_mem_nhds_within (subset_preimage_image f s)) lemma continuous_within_at.mem_closure {f : α → β} {s : set α} {x : α} {A : set β} (h : continuous_within_at f s x) (hx : x ∈ closure s) (hA : s ⊆ f⁻¹' A) : f x ∈ closure A := closure_mono (image_subset_iff.2 hA) (h.mem_closure_image hx) lemma continuous_within_at.image_closure {f : α → β} {s : set α} (hf : ∀ x ∈ closure s, continuous_within_at f s x) : f '' (closure s) ⊆ closure (f '' s) := begin rintros _ ⟨x, hx, rfl⟩, exact (hf x hx).mem_closure_image hx end lemma continuous_on.image_closure {f : α → β} {s : set α} (hf : continuous_on f (closure s)) : f '' (closure s) ⊆ closure (f '' s) := continuous_within_at.image_closure $ λ x hx, (hf x hx).mono subset_closure @[simp] lemma continuous_within_at_singleton {f : α → β} {x : α} : continuous_within_at f {x} x := by simp only [continuous_within_at, nhds_within_singleton, tendsto_pure_nhds] @[simp] lemma continuous_within_at_insert_self {f : α → β} {x : α} {s : set α} : continuous_within_at f (insert x s) x ↔ continuous_within_at f s x := by simp only [← singleton_union, continuous_within_at_union, continuous_within_at_singleton, true_and] alias continuous_within_at_insert_self ↔ _ continuous_within_at.insert_self lemma continuous_within_at.diff_iff {f : α → β} {s t : set α} {x : α} (ht : continuous_within_at f t x) : continuous_within_at f (s \ t) x ↔ continuous_within_at f s x := ⟨λ h, (h.union ht).mono $ by simp only [diff_union_self, subset_union_left], λ h, h.mono (diff_subset _ _)⟩ @[simp] lemma continuous_within_at_diff_self {f : α → β} {s : set α} {x : α} : continuous_within_at f (s \ {x}) x ↔ continuous_within_at f s x := continuous_within_at_singleton.diff_iff theorem is_open_map.continuous_on_image_of_left_inv_on {f : α → β} {s : set α} (h : is_open_map (s.restrict f)) {finv : β → α} (hleft : left_inv_on finv f s) : continuous_on finv (f '' s) := begin refine continuous_on_iff'.2 (λ t ht, ⟨f '' (t ∩ s), _, _⟩), { rw ← image_restrict, exact h _ (ht.preimage continuous_subtype_coe) }, { rw [inter_eq_self_of_subset_left (image_subset f (inter_subset_right t s)), hleft.image_inter'] }, end theorem is_open_map.continuous_on_range_of_left_inverse {f : α → β} (hf : is_open_map f) {finv : β → α} (hleft : function.left_inverse finv f) : continuous_on finv (range f) := begin rw [← image_univ], exact (hf.restrict is_open_univ).continuous_on_image_of_left_inv_on (λ x _, hleft x) end lemma continuous_on.congr_mono {f g : α → β} {s s₁ : set α} (h : continuous_on f s) (h' : eq_on g f s₁) (h₁ : s₁ ⊆ s) : continuous_on g s₁ := begin assume x hx, unfold continuous_within_at, have A := (h x (h₁ hx)).mono h₁, unfold continuous_within_at at A, rw ← h' hx at A, exact A.congr' h'.eventually_eq_nhds_within.symm end lemma continuous_on.congr {f g : α → β} {s : set α} (h : continuous_on f s) (h' : eq_on g f s) : continuous_on g s := h.congr_mono h' (subset.refl _) lemma continuous_on_congr {f g : α → β} {s : set α} (h' : eq_on g f s) : continuous_on g s ↔ continuous_on f s := ⟨λ h, continuous_on.congr h h'.symm, λ h, h.congr h'⟩ lemma continuous_at.continuous_within_at {f : α → β} {s : set α} {x : α} (h : continuous_at f x) : continuous_within_at f s x := continuous_within_at.mono ((continuous_within_at_univ f x).2 h) (subset_univ _) lemma continuous_within_at.continuous_at {f : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) (hs : s ∈ 𝓝 x) : continuous_at f x := begin have : s = univ ∩ s, by rw univ_inter, rwa [this, continuous_within_at_inter hs, continuous_within_at_univ] at h end lemma continuous_on.continuous_at {f : α → β} {s : set α} {x : α} (h : continuous_on f s) (hx : s ∈ 𝓝 x) : continuous_at f x := (h x (mem_of_mem_nhds hx)).continuous_at hx lemma continuous_at.continuous_on {f : α → β} {s : set α} (hcont : ∀ x ∈ s, continuous_at f x) : continuous_on f s := λ x hx, (hcont x hx).continuous_within_at lemma continuous_within_at.comp {g : β → γ} {f : α → β} {s : set α} {t : set β} {x : α} (hg : continuous_within_at g t (f x)) (hf : continuous_within_at f s x) (h : s ⊆ f ⁻¹' t) : continuous_within_at (g ∘ f) s x := hg.tendsto.comp (hf.tendsto_nhds_within h) lemma continuous_within_at.comp' {g : β → γ} {f : α → β} {s : set α} {t : set β} {x : α} (hg : continuous_within_at g t (f x)) (hf : continuous_within_at f s x) : continuous_within_at (g ∘ f) (s ∩ f⁻¹' t) x := hg.comp (hf.mono (inter_subset_left _ _)) (inter_subset_right _ _) lemma continuous_at.comp_continuous_within_at {g : β → γ} {f : α → β} {s : set α} {x : α} (hg : continuous_at g (f x)) (hf : continuous_within_at f s x) : continuous_within_at (g ∘ f) s x := hg.continuous_within_at.comp hf subset_preimage_univ lemma continuous_on.comp {g : β → γ} {f : α → β} {s : set α} {t : set β} (hg : continuous_on g t) (hf : continuous_on f s) (h : s ⊆ f ⁻¹' t) : continuous_on (g ∘ f) s := λx hx, continuous_within_at.comp (hg _ (h hx)) (hf x hx) h lemma continuous_on.mono {f : α → β} {s t : set α} (hf : continuous_on f s) (h : t ⊆ s) : continuous_on f t := λx hx, (hf x (h hx)).mono_left (nhds_within_mono _ h) lemma continuous_on.comp' {g : β → γ} {f : α → β} {s : set α} {t : set β} (hg : continuous_on g t) (hf : continuous_on f s) : continuous_on (g ∘ f) (s ∩ f⁻¹' t) := hg.comp (hf.mono (inter_subset_left _ _)) (inter_subset_right _ _) lemma continuous.continuous_on {f : α → β} {s : set α} (h : continuous f) : continuous_on f s := begin rw continuous_iff_continuous_on_univ at h, exact h.mono (subset_univ _) end lemma continuous.continuous_within_at {f : α → β} {s : set α} {x : α} (h : continuous f) : continuous_within_at f s x := h.continuous_at.continuous_within_at lemma continuous.comp_continuous_on {g : β → γ} {f : α → β} {s : set α} (hg : continuous g) (hf : continuous_on f s) : continuous_on (g ∘ f) s := hg.continuous_on.comp hf subset_preimage_univ lemma continuous_on.comp_continuous {g : β → γ} {f : α → β} {s : set β} (hg : continuous_on g s) (hf : continuous f) (hs : ∀ x, f x ∈ s) : continuous (g ∘ f) := begin rw continuous_iff_continuous_on_univ at *, exact hg.comp hf (λ x _, hs x), end lemma continuous_within_at.preimage_mem_nhds_within {f : α → β} {x : α} {s : set α} {t : set β} (h : continuous_within_at f s x) (ht : t ∈ 𝓝 (f x)) : f ⁻¹' t ∈ 𝓝[s] x := h ht lemma set.left_inv_on.map_nhds_within_eq {f : α → β} {g : β → α} {x : β} {s : set β} (h : left_inv_on f g s) (hx : f (g x) = x) (hf : continuous_within_at f (g '' s) (g x)) (hg : continuous_within_at g s x) : map g (𝓝[s] x) = 𝓝[g '' s] (g x) := begin apply le_antisymm, { exact hg.tendsto_nhds_within (maps_to_image _ _) }, { have A : g ∘ f =ᶠ[𝓝[g '' s] (g x)] id, from h.right_inv_on_image.eq_on.eventually_eq_of_mem self_mem_nhds_within, refine le_map_of_right_inverse A _, simpa only [hx] using hf.tendsto_nhds_within (h.maps_to (surj_on_image _ _)) } end lemma function.left_inverse.map_nhds_eq {f : α → β} {g : β → α} {x : β} (h : function.left_inverse f g) (hf : continuous_within_at f (range g) (g x)) (hg : continuous_at g x) : map g (𝓝 x) = 𝓝[range g] (g x) := by simpa only [nhds_within_univ, image_univ] using (h.left_inv_on univ).map_nhds_within_eq (h x) (by rwa image_univ) hg.continuous_within_at lemma continuous_within_at.preimage_mem_nhds_within' {f : α → β} {x : α} {s : set α} {t : set β} (h : continuous_within_at f s x) (ht : t ∈ 𝓝[f '' s] (f x)) : f ⁻¹' t ∈ 𝓝[s] x := h.tendsto_nhds_within (maps_to_image _ _) ht lemma continuous_within_at.congr_of_eventually_eq {f f₁ : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : continuous_within_at f₁ s x := by rwa [continuous_within_at, filter.tendsto, hx, filter.map_congr h₁] lemma continuous_within_at.congr {f f₁ : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) (h₁ : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) : continuous_within_at f₁ s x := h.congr_of_eventually_eq (mem_of_superset self_mem_nhds_within h₁) hx lemma continuous_within_at.congr_mono {f g : α → β} {s s₁ : set α} {x : α} (h : continuous_within_at f s x) (h' : eq_on g f s₁) (h₁ : s₁ ⊆ s) (hx : g x = f x): continuous_within_at g s₁ x := (h.mono h₁).congr h' hx lemma continuous_on_const {s : set α} {c : β} : continuous_on (λx, c) s := continuous_const.continuous_on lemma continuous_within_at_const {b : β} {s : set α} {x : α} : continuous_within_at (λ _:α, b) s x := continuous_const.continuous_within_at lemma continuous_on_id {s : set α} : continuous_on id s := continuous_id.continuous_on lemma continuous_within_at_id {s : set α} {x : α} : continuous_within_at id s x := continuous_id.continuous_within_at lemma continuous_on_open_iff {f : α → β} {s : set α} (hs : is_open s) : continuous_on f s ↔ (∀t, is_open t → is_open (s ∩ f⁻¹' t)) := begin rw continuous_on_iff', split, { assume h t ht, rcases h t ht with ⟨u, u_open, hu⟩, rw [inter_comm, hu], apply is_open.inter u_open hs }, { assume h t ht, refine ⟨s ∩ f ⁻¹' t, h t ht, _⟩, rw [@inter_comm _ s (f ⁻¹' t), inter_assoc, inter_self] } end lemma continuous_on.preimage_open_of_open {f : α → β} {s : set α} {t : set β} (hf : continuous_on f s) (hs : is_open s) (ht : is_open t) : is_open (s ∩ f⁻¹' t) := (continuous_on_open_iff hs).1 hf t ht lemma continuous_on.is_open_preimage {f : α → β} {s : set α} {t : set β} (h : continuous_on f s) (hs : is_open s) (hp : f ⁻¹' t ⊆ s) (ht : is_open t) : is_open (f ⁻¹' t) := begin convert (continuous_on_open_iff hs).mp h t ht, rw [inter_comm, inter_eq_self_of_subset_left hp], end lemma continuous_on.preimage_closed_of_closed {f : α → β} {s : set α} {t : set β} (hf : continuous_on f s) (hs : is_closed s) (ht : is_closed t) : is_closed (s ∩ f⁻¹' t) := begin rcases continuous_on_iff_is_closed.1 hf t ht with ⟨u, hu⟩, rw [inter_comm, hu.2], apply is_closed.inter hu.1 hs end lemma continuous_on.preimage_interior_subset_interior_preimage {f : α → β} {s : set α} {t : set β} (hf : continuous_on f s) (hs : is_open s) : s ∩ f⁻¹' (interior t) ⊆ s ∩ interior (f⁻¹' t) := calc s ∩ f ⁻¹' (interior t) ⊆ interior (s ∩ f ⁻¹' t) : interior_maximal (inter_subset_inter (subset.refl _) (preimage_mono interior_subset)) (hf.preimage_open_of_open hs is_open_interior) ... = s ∩ interior (f ⁻¹' t) : by rw [interior_inter, hs.interior_eq] lemma continuous_on_of_locally_continuous_on {f : α → β} {s : set α} (h : ∀x∈s, ∃t, is_open t ∧ x ∈ t ∧ continuous_on f (s ∩ t)) : continuous_on f s := begin assume x xs, rcases h x xs with ⟨t, open_t, xt, ct⟩, have := ct x ⟨xs, xt⟩, rwa [continuous_within_at, ← nhds_within_restrict _ xt open_t] at this end lemma continuous_on_open_of_generate_from {β : Type*} {s : set α} {T : set (set β)} {f : α → β} (hs : is_open s) (h : ∀t ∈ T, is_open (s ∩ f⁻¹' t)) : @continuous_on α β _ (topological_space.generate_from T) f s := begin rw continuous_on_open_iff, assume t ht, induction ht with u hu u v Tu Tv hu hv U hU hU', { exact h u hu }, { simp only [preimage_univ, inter_univ], exact hs }, { have : s ∩ f ⁻¹' (u ∩ v) = (s ∩ f ⁻¹' u) ∩ (s ∩ f ⁻¹' v), by { ext x, simp, split, finish, finish }, rw this, exact is_open.inter hu hv }, { rw [preimage_sUnion, inter_bUnion], exact is_open_bUnion hU' }, { exact hs } end lemma continuous_within_at.prod {f : α → β} {g : α → γ} {s : set α} {x : α} (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (λx, (f x, g x)) s x := hf.prod_mk_nhds hg lemma continuous_on.prod {f : α → β} {g : α → γ} {s : set α} (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λx, (f x, g x)) s := λx hx, continuous_within_at.prod (hf x hx) (hg x hx) lemma inducing.continuous_on_iff {f : α → β} {g : β → γ} (hg : inducing g) {s : set α} : continuous_on f s ↔ continuous_on (g ∘ f) s := begin simp only [continuous_on_iff_continuous_restrict, restrict_eq], conv_rhs { rw [function.comp.assoc, ← (inducing.continuous_iff hg)] }, end lemma embedding.continuous_on_iff {f : α → β} {g : β → γ} (hg : embedding g) {s : set α} : continuous_on f s ↔ continuous_on (g ∘ f) s := inducing.continuous_on_iff hg.1 lemma continuous_within_at_of_not_mem_closure {f : α → β} {s : set α} {x : α} : x ∉ closure s → continuous_within_at f s x := begin intros hx, rw [mem_closure_iff_nhds_within_ne_bot, ne_bot_iff, not_not] at hx, rw [continuous_within_at, hx], exact tendsto_bot, end lemma continuous_on.piecewise' {s t : set α} {f g : α → β} [∀ a, decidable (a ∈ t)] (hpf : ∀ a ∈ s ∩ frontier t, tendsto f (𝓝[s ∩ t] a) (𝓝 (piecewise t f g a))) (hpg : ∀ a ∈ s ∩ frontier t, tendsto g (𝓝[s ∩ tᶜ] a) (𝓝 (piecewise t f g a))) (hf : continuous_on f $ s ∩ t) (hg : continuous_on g $ s ∩ tᶜ) : continuous_on (piecewise t f g) s := begin intros x hx, by_cases hx' : x ∈ frontier t, { exact (hpf x ⟨hx, hx'⟩).piecewise_nhds_within (hpg x ⟨hx, hx'⟩) }, { rw [← inter_univ s, ← union_compl_self t, inter_union_distrib_left] at hx ⊢, cases hx, { apply continuous_within_at.union, { exact (hf x hx).congr (λ y hy, piecewise_eq_of_mem _ _ _ hy.2) (piecewise_eq_of_mem _ _ _ hx.2) }, { have : x ∉ closure tᶜ, from λ h, hx' ⟨subset_closure hx.2, by rwa closure_compl at h⟩, exact continuous_within_at_of_not_mem_closure (λ h, this (closure_inter_subset_inter_closure _ _ h).2) } }, { apply continuous_within_at.union, { have : x ∉ closure t, from (λ h, hx' ⟨h, (λ (h' : x ∈ interior t), hx.2 (interior_subset h'))⟩), exact continuous_within_at_of_not_mem_closure (λ h, this (closure_inter_subset_inter_closure _ _ h).2) }, { exact (hg x hx).congr (λ y hy, piecewise_eq_of_not_mem _ _ _ hy.2) (piecewise_eq_of_not_mem _ _ _ hx.2) } } } end lemma continuous_on.if' {s : set α} {p : α → Prop} {f g : α → β} [∀ a, decidable (p a)] (hpf : ∀ a ∈ s ∩ frontier {a | p a}, tendsto f (𝓝[s ∩ {a | p a}] a) (𝓝 $ if p a then f a else g a)) (hpg : ∀ a ∈ s ∩ frontier {a | p a}, tendsto g (𝓝[s ∩ {a | ¬p a}] a) (𝓝 $ if p a then f a else g a)) (hf : continuous_on f $ s ∩ {a | p a}) (hg : continuous_on g $ s ∩ {a | ¬p a}) : continuous_on (λ a, if p a then f a else g a) s := hf.piecewise' hpf hpg hg lemma continuous_on.if {α β : Type*} [topological_space α] [topological_space β] {p : α → Prop} [∀ a, decidable (p a)] {s : set α} {f g : α → β} (hp : ∀ a ∈ s ∩ frontier {a | p a}, f a = g a) (hf : continuous_on f $ s ∩ closure {a | p a}) (hg : continuous_on g $ s ∩ closure {a | ¬ p a}) : continuous_on (λa, if p a then f a else g a) s := begin apply continuous_on.if', { rintros a ha, simp only [← hp a ha, if_t_t], apply tendsto_nhds_within_mono_left (inter_subset_inter_right s subset_closure), exact hf a ⟨ha.1, ha.2.1⟩ }, { rintros a ha, simp only [hp a ha, if_t_t], apply tendsto_nhds_within_mono_left (inter_subset_inter_right s subset_closure), rcases ha with ⟨has, ⟨_, ha⟩⟩, rw [← mem_compl_iff, ← closure_compl] at ha, apply hg a ⟨has, ha⟩ }, { exact hf.mono (inter_subset_inter_right s subset_closure) }, { exact hg.mono (inter_subset_inter_right s subset_closure) } end lemma continuous_on.piecewise {s t : set α} {f g : α → β} [∀ a, decidable (a ∈ t)] (ht : ∀ a ∈ s ∩ frontier t, f a = g a) (hf : continuous_on f $ s ∩ closure t) (hg : continuous_on g $ s ∩ closure tᶜ) : continuous_on (piecewise t f g) s := hf.if ht hg lemma continuous_if' {p : α → Prop} {f g : α → β} [∀ a, decidable (p a)] (hpf : ∀ a ∈ frontier {x | p x}, tendsto f (𝓝[{x | p x}] a) (𝓝 $ ite (p a) (f a) (g a))) (hpg : ∀ a ∈ frontier {x | p x}, tendsto g (𝓝[{x | ¬p x}] a) (𝓝 $ ite (p a) (f a) (g a))) (hf : continuous_on f {x | p x}) (hg : continuous_on g {x | ¬p x}) : continuous (λ a, ite (p a) (f a) (g a)) := begin rw continuous_iff_continuous_on_univ, apply continuous_on.if'; simp *; assumption end lemma continuous_if {p : α → Prop} {f g : α → β} [∀ a, decidable (p a)] (hp : ∀ a ∈ frontier {x | p x}, f a = g a) (hf : continuous_on f (closure {x | p x})) (hg : continuous_on g (closure {x | ¬p x})) : continuous (λ a, if p a then f a else g a) := begin rw continuous_iff_continuous_on_univ, apply continuous_on.if; simp; assumption end lemma continuous.if {p : α → Prop} {f g : α → β} [∀ a, decidable (p a)] (hp : ∀ a ∈ frontier {x | p x}, f a = g a) (hf : continuous f) (hg : continuous g) : continuous (λ a, if p a then f a else g a) := continuous_if hp hf.continuous_on hg.continuous_on lemma continuous_piecewise {s : set α} {f g : α → β} [∀ a, decidable (a ∈ s)] (hs : ∀ a ∈ frontier s, f a = g a) (hf : continuous_on f (closure s)) (hg : continuous_on g (closure sᶜ)) : continuous (piecewise s f g) := continuous_if hs hf hg lemma continuous.piecewise {s : set α} {f g : α → β} [∀ a, decidable (a ∈ s)] (hs : ∀ a ∈ frontier s, f a = g a) (hf : continuous f) (hg : continuous g) : continuous (piecewise s f g) := hf.if hs hg lemma is_open.ite' {s s' t : set α} (hs : is_open s) (hs' : is_open s') (ht : ∀ x ∈ frontier t, x ∈ s ↔ x ∈ s') : is_open (t.ite s s') := begin classical, simp only [is_open_iff_continuous_mem, set.ite] at *, convert continuous_piecewise (λ x hx, propext (ht x hx)) hs.continuous_on hs'.continuous_on, ext x, by_cases hx : x ∈ t; simp [hx] end lemma is_open.ite {s s' t : set α} (hs : is_open s) (hs' : is_open s') (ht : s ∩ frontier t = s' ∩ frontier t) : is_open (t.ite s s') := hs.ite' hs' $ λ x hx, by simpa [hx] using ext_iff.1 ht x lemma ite_inter_closure_eq_of_inter_frontier_eq {s s' t : set α} (ht : s ∩ frontier t = s' ∩ frontier t) : t.ite s s' ∩ closure t = s ∩ closure t := by rw [closure_eq_self_union_frontier, inter_union_distrib_left, inter_union_distrib_left, ite_inter_self, ite_inter_of_inter_eq _ ht] lemma ite_inter_closure_compl_eq_of_inter_frontier_eq {s s' t : set α} (ht : s ∩ frontier t = s' ∩ frontier t) : t.ite s s' ∩ closure tᶜ = s' ∩ closure tᶜ := by { rw [← ite_compl, ite_inter_closure_eq_of_inter_frontier_eq], rwa [frontier_compl, eq_comm] } lemma continuous_on_piecewise_ite' {s s' t : set α} {f f' : α → β} [∀ x, decidable (x ∈ t)] (h : continuous_on f (s ∩ closure t)) (h' : continuous_on f' (s' ∩ closure tᶜ)) (H : s ∩ frontier t = s' ∩ frontier t) (Heq : eq_on f f' (s ∩ frontier t)) : continuous_on (t.piecewise f f') (t.ite s s') := begin apply continuous_on.piecewise, { rwa ite_inter_of_inter_eq _ H }, { rwa ite_inter_closure_eq_of_inter_frontier_eq H }, { rwa ite_inter_closure_compl_eq_of_inter_frontier_eq H } end lemma continuous_on_piecewise_ite {s s' t : set α} {f f' : α → β} [∀ x, decidable (x ∈ t)] (h : continuous_on f s) (h' : continuous_on f' s') (H : s ∩ frontier t = s' ∩ frontier t) (Heq : eq_on f f' (s ∩ frontier t)) : continuous_on (t.piecewise f f') (t.ite s s') := continuous_on_piecewise_ite' (h.mono (inter_subset_left _ _)) (h'.mono (inter_subset_left _ _)) H Heq lemma continuous_on_fst {s : set (α × β)} : continuous_on prod.fst s := continuous_fst.continuous_on lemma continuous_within_at_fst {s : set (α × β)} {p : α × β} : continuous_within_at prod.fst s p := continuous_fst.continuous_within_at lemma continuous_on_snd {s : set (α × β)} : continuous_on prod.snd s := continuous_snd.continuous_on lemma continuous_within_at_snd {s : set (α × β)} {p : α × β} : continuous_within_at prod.snd s p := continuous_snd.continuous_within_at lemma continuous_within_at.fst {f : α → β × γ} {s : set α} {a : α} (h : continuous_within_at f s a) : continuous_within_at (λ x, (f x).fst) s a := continuous_at_fst.comp_continuous_within_at h lemma continuous_within_at.snd {f : α → β × γ} {s : set α} {a : α} (h : continuous_within_at f s a) : continuous_within_at (λ x, (f x).snd) s a := continuous_at_snd.comp_continuous_within_at h lemma continuous_within_at_prod_iff {f : α → β × γ} {s : set α} {x : α} : continuous_within_at f s x ↔ continuous_within_at (prod.fst ∘ f) s x ∧ continuous_within_at (prod.snd ∘ f) s x := ⟨λ h, ⟨h.fst, h.snd⟩, by { rintro ⟨h1, h2⟩, convert h1.prod h2, ext, refl, refl }⟩
8a26abc3789f55de5bf96dcb7d3452508e5a291b
491068d2ad28831e7dade8d6dff871c3e49d9431
/hott/hit/trunc.hlean
68278b7efac462bfb7acbf591185bfbaebec055b
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,424
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 n-truncation of types. Ported from Coq HoTT -/ /- The hit n-truncation is primitive, declared in init.hit. -/ import types.sigma types.pointed open is_trunc eq equiv is_equiv function prod sum sigma namespace trunc protected definition elim [recursor 6] {n : trunc_index} {A : Type} {P : Type} [Pt : is_trunc n P] (H : A → P) : trunc n A → P := trunc.rec H protected definition elim_on {n : trunc_index} {A : Type} {P : Type} (aa : trunc n A) [Pt : is_trunc n P] (H : A → P) : P := trunc.elim H aa /- there are no theorems to eliminate to the universe here, because the universe is not a set -/ end trunc attribute trunc.elim_on [unfold 4] attribute trunc.rec [recursor] attribute trunc.elim [recursor 6] [unfold 6] namespace trunc variables {X Y Z : Type} {P : X → Type} (A B : Type) (n : trunc_index) local attribute is_trunc_eq [instance] variables {A n} definition untrunc_of_is_trunc [reducible] [H : is_trunc n A] : trunc n A → A := trunc.rec id variables (A n) definition is_equiv_tr [instance] [constructor] [H : is_trunc n A] : is_equiv (@tr n A) := adjointify _ (untrunc_of_is_trunc) (λaa, trunc.rec_on aa (λa, idp)) (λa, idp) definition trunc_equiv [constructor] [H : is_trunc n A] : trunc n A ≃ A := (equiv.mk tr _)⁻¹ᵉ definition is_trunc_of_is_equiv_tr [H : is_equiv (@tr n A)] : is_trunc n A := is_trunc_is_equiv_closed n (@tr n _)⁻¹ /- Functoriality -/ definition trunc_functor [unfold 5] (f : X → Y) : trunc n X → trunc n Y := λxx, trunc.rec_on xx (λx, tr (f x)) definition trunc_functor_compose (f : X → Y) (g : Y → Z) : trunc_functor n (g ∘ f) ~ trunc_functor n g ∘ trunc_functor n f := λxx, trunc.rec_on xx (λx, idp) definition trunc_functor_id : trunc_functor n (@id A) ~ id := λxx, trunc.rec_on xx (λx, idp) definition is_equiv_trunc_functor [constructor] (f : X → Y) [H : is_equiv f] : is_equiv (trunc_functor n f) := adjointify _ (trunc_functor n f⁻¹) (λyy, trunc.rec_on yy (λy, ap tr !right_inv)) (λxx, trunc.rec_on xx (λx, ap tr !left_inv)) definition trunc_homotopy {f g : X → Y} (p : f ~ g) : trunc_functor n f ~ trunc_functor n g := λxx, trunc.rec_on xx (λx, ap tr (p x)) section open equiv.ops definition trunc_equiv_trunc [constructor] (f : X ≃ Y) : trunc n X ≃ trunc n Y := equiv.mk _ (is_equiv_trunc_functor n f) end section open prod.ops definition trunc_prod_equiv [constructor] : trunc n (X × Y) ≃ trunc n X × trunc n Y := begin fapply equiv.MK, {exact (λpp, trunc.rec_on pp (λp, (tr p.1, tr p.2)))}, {intro p, cases p with xx yy, apply (trunc.rec_on xx), intro x, apply (trunc.rec_on yy), intro y, exact (tr (x,y))}, {intro p, cases p with xx yy, apply (trunc.rec_on xx), intro x, apply (trunc.rec_on yy), intro y, apply idp}, {intro pp, apply (trunc.rec_on pp), intro p, cases p, apply idp} end end /- Propositional truncation -/ -- should this live in hprop? definition merely [reducible] (A : Type) : Type := trunc -1 A notation `||`:max A `||`:0 := merely A notation `∥`:max A `∥`:0 := merely A definition Exists [reducible] (P : X → Type) : Type := ∥ sigma P ∥ definition or [reducible] (A B : Type) : Type := ∥ A ⊎ B ∥ notation `exists` binders `,` r:(scoped P, Exists P) := r notation `∃` binders `,` r:(scoped P, Exists P) := r notation A ` \/ ` B := or A B notation A ∨ B := or A B definition merely.intro [reducible] [constructor] (a : A) : ∥ A ∥ := tr a definition exists.intro [reducible] [constructor] (x : X) (p : P x) : ∃x, P x := tr ⟨x, p⟩ definition or.intro_left [reducible] [constructor] (x : X) : X ∨ Y := tr (inl x) definition or.intro_right [reducible] [constructor] (y : Y) : X ∨ Y := tr (inr y) definition is_contr_of_merely_hprop [H : is_hprop A] (aa : merely A) : is_contr A := is_contr_of_inhabited_hprop (trunc.rec_on aa id) section open sigma.ops definition trunc_sigma_equiv [constructor] : trunc n (Σ x, P x) ≃ trunc n (Σ x, trunc n (P x)) := equiv.MK (λpp, trunc.rec_on pp (λp, tr ⟨p.1, tr p.2⟩)) (λpp, trunc.rec_on pp (λp, trunc.rec_on p.2 (λb, tr ⟨p.1, b⟩))) (λpp, trunc.rec_on pp (λp, sigma.rec_on p (λa bb, trunc.rec_on bb (λb, by esimp)))) (λpp, trunc.rec_on pp (λp, sigma.rec_on p (λa b, by esimp))) definition trunc_sigma_equiv_of_is_trunc [H : is_trunc n X] : trunc n (Σ x, P x) ≃ Σ x, trunc n (P x) := calc trunc n (Σ x, P x) ≃ trunc n (Σ x, trunc n (P x)) : trunc_sigma_equiv ... ≃ Σ x, trunc n (P x) : !trunc_equiv end /- the (non-dependent) universal property -/ definition trunc_arrow_equiv [constructor] [H : is_trunc n B] : (trunc n A → B) ≃ (A → B) := begin fapply equiv.MK, { intro g a, exact g (tr a)}, { intro f x, exact trunc.rec_on x f}, { intro f, apply eq_of_homotopy, intro a, reflexivity}, { intro g, apply eq_of_homotopy, intro x, exact trunc.rec_on x (λa, idp)}, end end trunc
1d77ad517bb5a646c7707172b7d2b904c7440b70
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/linear_algebra/lagrange.lean
1e8ebf42f34e34a17958b008b9f422cf57a02218
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,260
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import ring_theory.polynomial import algebra.big_operators.basic /-! # Lagrange interpolation ## Main definitions * `lagrange.basis s x` where `s : finset F` and `x : F`: the Lagrange basis polynomial that evaluates to `1` at `x` and `0` at other elements of `s`. * `lagrange.interpolate s f` where `s : finset F` and `f : s → F`: the Lagrange interpolant that evaluates to `f x` at `x` for `x ∈ s`. -/ noncomputable theory open_locale big_operators classical universe u namespace lagrange variables {F : Type u} [decidable_eq F] [field F] (s : finset F) variables {F' : Type u} [field F'] (s' : finset F') open polynomial /-- Lagrange basis polynomials that evaluate to 1 at `x` and 0 at other elements of `s`. -/ def basis (x : F) : polynomial F := ∏ y in s.erase x, C (x - y)⁻¹ * (X - C y) @[simp] theorem basis_empty (x : F) : basis ∅ x = 1 := rfl @[simp] theorem eval_basis_self (x : F) : (basis s x).eval x = 1 := begin rw [basis, ← coe_eval_ring_hom, (eval_ring_hom x).map_prod, coe_eval_ring_hom, finset.prod_eq_one], intros y hy, simp_rw [eval_mul, eval_sub, eval_C, eval_X], exact inv_mul_cancel (sub_ne_zero_of_ne (finset.ne_of_mem_erase hy).symm) end @[simp] theorem eval_basis_ne (x y : F) (h1 : y ∈ s) (h2 : y ≠ x) : (basis s x).eval y = 0 := begin rw [basis, ← coe_eval_ring_hom, (eval_ring_hom y).map_prod, coe_eval_ring_hom, finset.prod_eq_zero (finset.mem_erase.2 ⟨h2, h1⟩)], simp_rw [eval_mul, eval_sub, eval_C, eval_X, sub_self, mul_zero] end theorem eval_basis (x y : F) (h : y ∈ s) : (basis s x).eval y = if y = x then 1 else 0 := by { split_ifs with H, { subst H, apply eval_basis_self }, { exact eval_basis_ne s x y h H } } @[simp] theorem nat_degree_basis (x : F) (hx : x ∈ s) : (basis s x).nat_degree = s.card - 1 := begin unfold basis, generalize hsx : s.erase x = sx, have : x ∉ sx := hsx ▸ finset.not_mem_erase x s, rw [← finset.insert_erase hx, hsx, finset.card_insert_of_not_mem this, add_tsub_cancel_right], clear hx hsx s, revert this, apply sx.induction_on, { intros hx, rw [finset.prod_empty, nat_degree_one], refl }, { intros y s hys ih hx, rw [finset.mem_insert, not_or_distrib] at hx, have h1 : C (x - y)⁻¹ ≠ C 0 := λ h, hx.1 (eq_of_sub_eq_zero $ inv_eq_zero.1 $ C_inj.1 h), have h2 : X ^ 1 - C y ≠ 0 := by convert X_pow_sub_C_ne_zero zero_lt_one y, rw C_0 at h1, rw pow_one at h2, rw [finset.prod_insert hys, nat_degree_mul (mul_ne_zero h1 h2), ih hx.2, finset.card_insert_of_not_mem hys, nat_degree_mul h1 h2, nat_degree_C, zero_add, nat_degree, degree_X_sub_C, add_comm], refl, rw [ne, finset.prod_eq_zero_iff], rintro ⟨z, hzs, hz⟩, rw mul_eq_zero at hz, cases hz with hz hz, { rw [← C_0, C_inj, inv_eq_zero, sub_eq_zero] at hz, exact hx.2 (hz.symm ▸ hzs) }, { rw ← pow_one (X : polynomial F) at hz, exact X_pow_sub_C_ne_zero zero_lt_one _ hz } } end variables (f : s → F) /-- Lagrange interpolation: given a finset `s` and a function `f : s → F`, `interpolate s f` is the unique polynomial of degree `< s.card` that takes value `f x` on all `x` in `s`. -/ def interpolate : polynomial F := ∑ x in s.attach, C (f x) * basis s x @[simp] theorem interpolate_empty (f) : interpolate (∅ : finset F) f = 0 := rfl @[simp] theorem eval_interpolate (x) (H : x ∈ s) : eval x (interpolate s f) = f ⟨x, H⟩ := begin rw [interpolate, ← coe_eval_ring_hom, (eval_ring_hom x).map_sum, coe_eval_ring_hom, finset.sum_eq_single (⟨x, H⟩ : { x // x ∈ s })], { rw [eval_mul, eval_C, subtype.coe_mk, eval_basis_self, mul_one] }, { rintros ⟨y, hy⟩ _ hyx, rw [eval_mul, subtype.coe_mk, eval_basis_ne s y x H, mul_zero], { rintros rfl, exact hyx rfl } }, { intro h, exact absurd (finset.mem_attach _ _) h } end theorem degree_interpolate_lt : (interpolate s f).degree < s.card := if H : s = ∅ then by { subst H, rw [interpolate_empty, degree_zero], exact with_bot.bot_lt_coe _ } else (degree_sum_le _ _).trans_lt $ (finset.sup_lt_iff $ with_bot.bot_lt_coe s.card).2 $ λ b _, calc (C (f b) * basis s b).degree ≤ (C (f b)).degree + (basis s b).degree : degree_mul_le _ _ ... ≤ 0 + (basis s b).degree : add_le_add_right degree_C_le _ ... = (basis s b).degree : zero_add _ ... ≤ (basis s b).nat_degree : degree_le_nat_degree ... = (s.card - 1 : ℕ) : by { rw nat_degree_basis s b b.2 } ... < s.card : with_bot.coe_lt_coe.2 (nat.pred_lt $ mt finset.card_eq_zero.1 H) /-- Linear version of `interpolate`. -/ def linterpolate : (s → F) →ₗ[F] polynomial F := { to_fun := interpolate s, map_add' := λ f g, by { simp_rw [interpolate, ← finset.sum_add_distrib, ← add_mul, ← C_add], refl }, map_smul' := λ c f, by { simp_rw [interpolate, finset.smul_sum, C_mul', smul_smul], refl } } @[simp] lemma interpolate_add (f g) : interpolate s (f + g) = interpolate s f + interpolate s g := (linterpolate s).map_add f g @[simp] lemma interpolate_zero : interpolate s 0 = 0 := (linterpolate s).map_zero @[simp] lemma interpolate_neg (f) : interpolate s (-f) = -interpolate s f := (linterpolate s).map_neg f @[simp] lemma interpolate_sub (f g) : interpolate s (f - g) = interpolate s f - interpolate s g := (linterpolate s).map_sub f g @[simp] lemma interpolate_smul (c : F) (f) : interpolate s (c • f) = c • interpolate s f := (linterpolate s).map_smul c f theorem eq_zero_of_eval_eq_zero {f : polynomial F'} (hf1 : f.degree < s'.card) (hf2 : ∀ x ∈ s', f.eval x = 0) : f = 0 := by_contradiction $ λ hf3, not_le_of_lt hf1 $ calc (s'.card : with_bot ℕ) ≤ f.roots.to_finset.card : with_bot.coe_le_coe.2 $ finset.card_le_of_subset $ λ x hx, (multiset.mem_to_finset).mpr $ (mem_roots hf3).2 $ hf2 x hx ... ≤ f.roots.card : with_bot.coe_le_coe.2 $ f.roots.to_finset_card_le ... ≤ f.degree : card_roots hf3 theorem eq_of_eval_eq {f g : polynomial F'} (hf : f.degree < s'.card) (hg : g.degree < s'.card) (hfg : ∀ x ∈ s', f.eval x = g.eval x) : f = g := eq_of_sub_eq_zero $ eq_zero_of_eval_eq_zero s' (lt_of_le_of_lt (degree_sub_le f g) $ max_lt hf hg) (λ x hx, by rw [eval_sub, hfg x hx, sub_self]) theorem eq_interpolate (f : polynomial F) (hf : f.degree < s.card) : interpolate s (λ x, f.eval x) = f := eq_of_eval_eq s (degree_interpolate_lt s _) hf $ λ x hx, eval_interpolate s _ x hx /-- Lagrange interpolation induces isomorphism between functions from `s` and polynomials of degree less than `s.card`. -/ def fun_equiv_degree_lt : degree_lt F s.card ≃ₗ[F] (s → F) := { to_fun := λ f x, f.1.eval x, map_add' := λ f g, funext $ λ x, eval_add, map_smul' := λ c f, funext $ λ x, by { change eval ↑x (c • f).val = (c • λ (x : s), eval ↑x f.val) x, rw [pi.smul_apply, smul_eq_mul, ← @eval_C F c _ x, ← eval_mul, eval_C, C_mul'], refl }, inv_fun := λ f, ⟨interpolate s f, mem_degree_lt.2 $ degree_interpolate_lt s f⟩, left_inv := λ f, subtype.eq $ eq_interpolate s f $ mem_degree_lt.1 f.2, right_inv := λ f, funext $ λ ⟨x, hx⟩, eval_interpolate s f x hx } end lagrange
c79a1238b1cb4db0bb183491c933c732687bb178
b9d8165d695e844c92d9d4cdcac7b5ab9efe09f7
/src/order/filter/basic.lean
d53b5d7c955a7089f8b025d807686c6f13d2c684
[ "Apache-2.0" ]
permissive
spapinistarkware/mathlib
e917d9c44bf85ef51db18e7a11615959f714efc5
0a9a1ff463a1f26e27d7c391eb7f6334f0d90383
refs/heads/master
1,606,808,129,547
1,577,478,369,000
1,577,478,369,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
89,578
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jeremy Avigad Theory of filters on sets. -/ import order.galois_connection order.zorn import data.set.finite open lattice set universes u v w x y open_locale classical namespace lattice variables {α : Type u} {ι : Sort v} def complete_lattice.copy (c : complete_lattice α) (le : α → α → Prop) (eq_le : le = @complete_lattice.le α c) (top : α) (eq_top : top = @complete_lattice.top α c) (bot : α) (eq_bot : bot = @complete_lattice.bot α c) (sup : α → α → α) (eq_sup : sup = @complete_lattice.sup α c) (inf : α → α → α) (eq_inf : inf = @complete_lattice.inf α c) (Sup : set α → α) (eq_Sup : Sup = @complete_lattice.Sup α c) (Inf : set α → α) (eq_Inf : Inf = @complete_lattice.Inf α c) : complete_lattice α := begin refine { le := le, top := top, bot := bot, sup := sup, inf := inf, Sup := Sup, Inf := Inf, ..}; subst_vars, exact @complete_lattice.le_refl α c, exact @complete_lattice.le_trans α c, exact @complete_lattice.le_antisymm α c, exact @complete_lattice.le_sup_left α c, exact @complete_lattice.le_sup_right α c, exact @complete_lattice.sup_le α c, exact @complete_lattice.inf_le_left α c, exact @complete_lattice.inf_le_right α c, exact @complete_lattice.le_inf α c, exact @complete_lattice.le_top α c, exact @complete_lattice.bot_le α c, exact @complete_lattice.le_Sup α c, exact @complete_lattice.Sup_le α c, exact @complete_lattice.Inf_le α c, exact @complete_lattice.le_Inf α c end end lattice open set lattice section order variables {α : Type u} (r : α → α → Prop) local infix ` ≼ ` : 50 := r lemma directed_on_Union {r} {ι : Sort v} {f : ι → set α} (hd : directed (⊆) f) (h : ∀x, directed_on r (f x)) : directed_on r (⋃x, f x) := by simp only [directed_on, exists_prop, mem_Union, exists_imp_distrib]; exact assume a₁ b₁ fb₁ a₂ b₂ fb₂, let ⟨z, zb₁, zb₂⟩ := hd b₁ b₂, ⟨x, xf, xa₁, xa₂⟩ := h z a₁ (zb₁ fb₁) a₂ (zb₂ fb₂) in ⟨x, ⟨z, xf⟩, xa₁, xa₂⟩ end order theorem directed_of_chain {α β r} [is_refl β r] {f : α → β} {c : set α} (h : zorn.chain (f ⁻¹'o r) c) : directed r (λx:{a:α // a ∈ c}, f (x.val)) := assume ⟨a, ha⟩ ⟨b, hb⟩, classical.by_cases (assume : a = b, by simp only [this, exists_prop, and_self, subtype.exists]; exact ⟨b, hb, refl _⟩) (assume : a ≠ b, (h a ha b hb this).elim (λ h : r (f a) (f b), ⟨⟨b, hb⟩, h, refl _⟩) (λ h : r (f b) (f a), ⟨⟨a, ha⟩, refl _, h⟩)) structure filter (α : Type*) := (sets : set (set α)) (univ_sets : set.univ ∈ sets) (sets_of_superset {x y} : x ∈ sets → x ⊆ y → y ∈ sets) (inter_sets {x y} : x ∈ sets → y ∈ sets → x ∩ y ∈ sets) /-- If `F` is a filter on `α`, and `U` a subset of `α` then we can write `U ∈ F` as on paper. -/ @[reducible] instance {α : Type*}: has_mem (set α) (filter α) := ⟨λ U F, U ∈ F.sets⟩ namespace filter variables {α : Type u} {f g : filter α} {s t : set α} lemma filter_eq : ∀{f g : filter α}, f.sets = g.sets → f = g | ⟨a, _, _, _⟩ ⟨._, _, _, _⟩ rfl := rfl lemma filter_eq_iff : f = g ↔ f.sets = g.sets := ⟨congr_arg _, filter_eq⟩ protected lemma ext_iff : f = g ↔ ∀ s, s ∈ f ↔ s ∈ g := by rw [filter_eq_iff, ext_iff] @[ext] protected lemma ext : (∀ s, s ∈ f ↔ s ∈ g) → f = g := filter.ext_iff.2 lemma univ_mem_sets : univ ∈ f := f.univ_sets lemma mem_sets_of_superset : ∀{x y : set α}, x ∈ f → x ⊆ y → y ∈ f := f.sets_of_superset lemma inter_mem_sets : ∀{s t}, s ∈ f → t ∈ f → s ∩ t ∈ f := f.inter_sets lemma univ_mem_sets' (h : ∀ a, a ∈ s) : s ∈ f := mem_sets_of_superset univ_mem_sets (assume x _, h x) lemma mp_sets (hs : s ∈ f) (h : {x | x ∈ s → x ∈ t} ∈ f) : t ∈ f := mem_sets_of_superset (inter_mem_sets hs h) $ assume x ⟨h₁, h₂⟩, h₂ h₁ lemma congr_sets (h : {x | x ∈ s ↔ x ∈ t} ∈ f) : s ∈ f ↔ t ∈ f := ⟨λ hs, mp_sets hs (mem_sets_of_superset h (λ x, iff.mp)), λ hs, mp_sets hs (mem_sets_of_superset h (λ x, iff.mpr))⟩ lemma Inter_mem_sets {β : Type v} {s : β → set α} {is : set β} (hf : finite is) : (∀i∈is, s i ∈ f) → (⋂i∈is, s i) ∈ f := finite.induction_on hf (assume hs, by simp only [univ_mem_sets, mem_empty_eq, Inter_neg, Inter_univ, not_false_iff]) (assume i is _ hf hi hs, have h₁ : s i ∈ f, from hs i (by simp), have h₂ : (⋂x∈is, s x) ∈ f, from hi $ assume a ha, hs _ $ by simp only [ha, mem_insert_iff, or_true], by simp [inter_mem_sets h₁ h₂]) lemma Inter_mem_sets_of_fintype {β : Type v} {s : β → set α} [fintype β] (h : ∀i, s i ∈ f) : (⋂i, s i) ∈ f := by simpa using Inter_mem_sets finite_univ (λi hi, h i) lemma exists_sets_subset_iff : (∃t ∈ f, t ⊆ s) ↔ s ∈ f := ⟨assume ⟨t, ht, ts⟩, mem_sets_of_superset ht ts, assume hs, ⟨s, hs, subset.refl _⟩⟩ lemma monotone_mem_sets {f : filter α} : monotone (λs, s ∈ f) := assume s t hst h, mem_sets_of_superset h hst end filter namespace tactic.interactive open tactic interactive /-- `filter_upwards [h1, ⋯, hn]` replaces a goal of the form `s ∈ f` and terms `h1 : t1 ∈ f, ⋯, hn : tn ∈ f` with `∀x, x ∈ t1 → ⋯ → x ∈ tn → x ∈ s`. `filter_upwards [h1, ⋯, hn] e` is a short form for `{ filter_upwards [h1, ⋯, hn], exact e }`. -/ meta def filter_upwards (s : parse types.pexpr_list) (e' : parse $ optional types.texpr) : tactic unit := do s.reverse.mmap (λ e, eapplyc `filter.mp_sets >> eapply e), eapplyc `filter.univ_mem_sets', match e' with | some e := interactive.exact e | none := skip end end tactic.interactive namespace filter variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} section principal /-- The principal filter of `s` is the collection of all supersets of `s`. -/ def principal (s : set α) : filter α := { sets := {t | s ⊆ t}, univ_sets := subset_univ s, sets_of_superset := assume x y hx hy, subset.trans hx hy, inter_sets := assume x y, subset_inter } instance : inhabited (filter α) := ⟨principal ∅⟩ @[simp] lemma mem_principal_sets {s t : set α} : s ∈ principal t ↔ t ⊆ s := iff.rfl lemma mem_principal_self (s : set α) : s ∈ principal s := subset.refl _ end principal section join /-- The join of a filter of filters is defined by the relation `s ∈ join f ↔ {t | s ∈ t} ∈ f`. -/ def join (f : filter (filter α)) : filter α := { sets := {s | {t : filter α | s ∈ t} ∈ f}, univ_sets := by simp only [univ_mem_sets, mem_set_of_eq]; exact univ_mem_sets, sets_of_superset := assume x y hx xy, mem_sets_of_superset hx $ assume f h, mem_sets_of_superset h xy, inter_sets := assume x y hx hy, mem_sets_of_superset (inter_mem_sets hx hy) $ assume f ⟨h₁, h₂⟩, inter_mem_sets h₁ h₂ } @[simp] lemma mem_join_sets {s : set α} {f : filter (filter α)} : s ∈ join f ↔ {t | s ∈ filter.sets t} ∈ f := iff.rfl end join section lattice instance : partial_order (filter α) := { le := λf g, ∀ ⦃U : set α⦄, U ∈ g → U ∈ f, le_antisymm := assume a b h₁ h₂, filter_eq $ subset.antisymm h₂ h₁, le_refl := assume a, subset.refl _, le_trans := assume a b c h₁ h₂, subset.trans h₂ h₁ } theorem le_def {f g : filter α} : f ≤ g ↔ ∀ x ∈ g, x ∈ f := iff.rfl /-- `generate_sets g s`: `s` is in the filter closure of `g`. -/ inductive generate_sets (g : set (set α)) : set α → Prop | basic {s : set α} : s ∈ g → generate_sets s | univ {} : generate_sets univ | superset {s t : set α} : generate_sets s → s ⊆ t → generate_sets t | inter {s t : set α} : generate_sets s → generate_sets t → generate_sets (s ∩ t) /-- `generate g` is the smallest filter containing the sets `g`. -/ def generate (g : set (set α)) : filter α := { sets := generate_sets g, univ_sets := generate_sets.univ, sets_of_superset := assume x y, generate_sets.superset, inter_sets := assume s t, generate_sets.inter } lemma sets_iff_generate {s : set (set α)} {f : filter α} : f ≤ filter.generate s ↔ s ⊆ f.sets := iff.intro (assume h u hu, h $ generate_sets.basic $ hu) (assume h u hu, hu.rec_on h univ_mem_sets (assume x y _ hxy hx, mem_sets_of_superset hx hxy) (assume x y _ _ hx hy, inter_mem_sets hx hy)) protected def mk_of_closure (s : set (set α)) (hs : (generate s).sets = s) : filter α := { sets := s, univ_sets := hs ▸ (univ_mem_sets : univ ∈ generate s), sets_of_superset := assume x y, hs ▸ (mem_sets_of_superset : x ∈ generate s → x ⊆ y → y ∈ generate s), inter_sets := assume x y, hs ▸ (inter_mem_sets : x ∈ generate s → y ∈ generate s → x ∩ y ∈ generate s) } lemma mk_of_closure_sets {s : set (set α)} {hs : (generate s).sets = s} : filter.mk_of_closure s hs = generate s := filter.ext $ assume u, show u ∈ (filter.mk_of_closure s hs).sets ↔ u ∈ (generate s).sets, from hs.symm ▸ iff.rfl /- Galois insertion from sets of sets into a filters. -/ def gi_generate (α : Type*) : @galois_insertion (set (set α)) (order_dual (filter α)) _ _ filter.generate filter.sets := { gc := assume s f, sets_iff_generate, le_l_u := assume f u h, generate_sets.basic h, choice := λs hs, filter.mk_of_closure s (le_antisymm hs $ sets_iff_generate.1 $ le_refl _), choice_eq := assume s hs, mk_of_closure_sets } /-- The infimum of filters is the filter generated by intersections of elements of the two filters. -/ instance : has_inf (filter α) := ⟨λf g : filter α, { sets := {s | ∃ (a ∈ f) (b ∈ g), a ∩ b ⊆ s }, univ_sets := ⟨_, univ_mem_sets, _, univ_mem_sets, inter_subset_left _ _⟩, sets_of_superset := assume x y ⟨a, ha, b, hb, h⟩ xy, ⟨a, ha, b, hb, subset.trans h xy⟩, inter_sets := assume x y ⟨a, ha, b, hb, hx⟩ ⟨c, hc, d, hd, hy⟩, ⟨_, inter_mem_sets ha hc, _, inter_mem_sets hb hd, calc a ∩ c ∩ (b ∩ d) = (a ∩ b) ∩ (c ∩ d) : by ac_refl ... ⊆ x ∩ y : inter_subset_inter hx hy⟩ }⟩ @[simp] lemma mem_inf_sets {f g : filter α} {s : set α} : s ∈ f ⊓ g ↔ ∃t₁∈f.sets, ∃t₂∈g.sets, t₁ ∩ t₂ ⊆ s := iff.rfl lemma mem_inf_sets_of_left {f g : filter α} {s : set α} (h : s ∈ f) : s ∈ f ⊓ g := ⟨s, h, univ, univ_mem_sets, inter_subset_left _ _⟩ lemma mem_inf_sets_of_right {f g : filter α} {s : set α} (h : s ∈ g) : s ∈ f ⊓ g := ⟨univ, univ_mem_sets, s, h, inter_subset_right _ _⟩ lemma inter_mem_inf_sets {α : Type u} {f g : filter α} {s t : set α} (hs : s ∈ f) (ht : t ∈ g) : s ∩ t ∈ f ⊓ g := inter_mem_sets (mem_inf_sets_of_left hs) (mem_inf_sets_of_right ht) instance : has_top (filter α) := ⟨{ sets := {s | ∀x, x ∈ s}, univ_sets := assume x, mem_univ x, sets_of_superset := assume x y hx hxy a, hxy (hx a), inter_sets := assume x y hx hy a, mem_inter (hx _) (hy _) }⟩ lemma mem_top_sets_iff_forall {s : set α} : s ∈ (⊤ : filter α) ↔ (∀x, x ∈ s) := iff.rfl @[simp] lemma mem_top_sets {s : set α} : s ∈ (⊤ : filter α) ↔ s = univ := by rw [mem_top_sets_iff_forall, eq_univ_iff_forall] section complete_lattice /- We lift the complete lattice along the Galois connection `generate` / `sets`. Unfortunately, we want to have different definitional equalities for the lattice operations. So we define them upfront and change the lattice operations for the complete lattice instance. -/ private def original_complete_lattice : complete_lattice (filter α) := @order_dual.lattice.complete_lattice _ (gi_generate α).lift_complete_lattice local attribute [instance] original_complete_lattice instance : complete_lattice (filter α) := original_complete_lattice.copy /- le -/ filter.partial_order.le rfl /- top -/ (filter.lattice.has_top).1 (top_unique $ assume s hs, by have := univ_mem_sets ; finish) /- bot -/ _ rfl /- sup -/ _ rfl /- inf -/ (filter.lattice.has_inf).1 begin ext f g : 2, exact le_antisymm (le_inf (assume s, mem_inf_sets_of_left) (assume s, mem_inf_sets_of_right)) (assume s ⟨a, ha, b, hb, hs⟩, show s ∈ complete_lattice.inf f g, from mem_sets_of_superset (inter_mem_sets (@inf_le_left (filter α) _ _ _ _ ha) (@inf_le_right (filter α) _ _ _ _ hb)) hs) end /- Sup -/ (join ∘ principal) (by ext s x; exact (@mem_bInter_iff _ _ s filter.sets x).symm) /- Inf -/ _ rfl end complete_lattice lemma bot_sets_eq : (⊥ : filter α).sets = univ := rfl lemma sup_sets_eq {f g : filter α} : (f ⊔ g).sets = f.sets ∩ g.sets := (gi_generate α).gc.u_inf lemma Sup_sets_eq {s : set (filter α)} : (Sup s).sets = (⋂f∈s, (f:filter α).sets) := (gi_generate α).gc.u_Inf lemma supr_sets_eq {f : ι → filter α} : (supr f).sets = (⋂i, (f i).sets) := (gi_generate α).gc.u_infi lemma generate_empty : filter.generate ∅ = (⊤ : filter α) := (gi_generate α).gc.l_bot lemma generate_univ : filter.generate univ = (⊥ : filter α) := mk_of_closure_sets.symm lemma generate_union {s t : set (set α)} : filter.generate (s ∪ t) = filter.generate s ⊓ filter.generate t := (gi_generate α).gc.l_sup lemma generate_Union {s : ι → set (set α)} : filter.generate (⋃ i, s i) = (⨅ i, filter.generate (s i)) := (gi_generate α).gc.l_supr @[simp] lemma mem_bot_sets {s : set α} : s ∈ (⊥ : filter α) := trivial @[simp] lemma mem_sup_sets {f g : filter α} {s : set α} : s ∈ f ⊔ g ↔ s ∈ f ∧ s ∈ g := iff.rfl @[simp] lemma mem_Sup_sets {x : set α} {s : set (filter α)} : x ∈ Sup s ↔ (∀f∈s, x ∈ (f:filter α)) := iff.rfl @[simp] lemma mem_supr_sets {x : set α} {f : ι → filter α} : x ∈ supr f ↔ (∀i, x ∈ f i) := by simp only [supr_sets_eq, iff_self, mem_Inter] @[simp] lemma le_principal_iff {s : set α} {f : filter α} : f ≤ principal s ↔ s ∈ f := show (∀{t}, s ⊆ t → t ∈ f) ↔ s ∈ f, from ⟨assume h, h (subset.refl s), assume hs t ht, mem_sets_of_superset hs ht⟩ lemma principal_mono {s t : set α} : principal s ≤ principal t ↔ s ⊆ t := by simp only [le_principal_iff, iff_self, mem_principal_sets] lemma monotone_principal : monotone (principal : set α → filter α) := λ _ _, principal_mono.2 @[simp] lemma principal_eq_iff_eq {s t : set α} : principal s = principal t ↔ s = t := by simp only [le_antisymm_iff, le_principal_iff, mem_principal_sets]; refl @[simp] lemma join_principal_eq_Sup {s : set (filter α)} : join (principal s) = Sup s := rfl /- lattice equations -/ lemma empty_in_sets_eq_bot {f : filter α} : ∅ ∈ f ↔ f = ⊥ := ⟨assume h, bot_unique $ assume s _, mem_sets_of_superset h (empty_subset s), assume : f = ⊥, this.symm ▸ mem_bot_sets⟩ lemma inhabited_of_mem_sets {f : filter α} {s : set α} (hf : f ≠ ⊥) (hs : s ∈ f) : ∃x, x ∈ s := have ∅ ∉ f.sets, from assume h, hf $ empty_in_sets_eq_bot.mp h, have s ≠ ∅, from assume h, this (h ▸ hs), exists_mem_of_ne_empty this lemma filter_eq_bot_of_not_nonempty {f : filter α} (ne : ¬ nonempty α) : f = ⊥ := empty_in_sets_eq_bot.mp $ univ_mem_sets' $ assume x, false.elim (ne ⟨x⟩) lemma forall_sets_neq_empty_iff_neq_bot {f : filter α} : (∀ (s : set α), s ∈ f → s ≠ ∅) ↔ f ≠ ⊥ := by simp only [(@empty_in_sets_eq_bot α f).symm, ne.def]; exact ⟨assume h hs, h _ hs rfl, assume h s hs eq, h $ eq ▸ hs⟩ lemma mem_sets_of_neq_bot {f : filter α} {s : set α} (h : f ⊓ principal (-s) = ⊥) : s ∈ f := have ∅ ∈ f ⊓ principal (- s), from h.symm ▸ mem_bot_sets, let ⟨s₁, hs₁, s₂, (hs₂ : -s ⊆ s₂), (hs : s₁ ∩ s₂ ⊆ ∅)⟩ := this in by filter_upwards [hs₁] assume a ha, classical.by_contradiction $ assume ha', hs ⟨ha, hs₂ ha'⟩ lemma eq_Inf_of_mem_sets_iff_exists_mem {S : set (filter α)} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ f ∈ S, s ∈ f) : l = Inf S := le_antisymm (le_Inf $ λ f hf s hs, h.2 ⟨f, hf, hs⟩) (λ s hs, let ⟨f, hf, hs⟩ := h.1 hs in (Inf_le hf : Inf S ≤ f) hs) lemma eq_infi_of_mem_sets_iff_exists_mem {f : ι → filter α} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ i, s ∈ f i) : l = infi f := eq_Inf_of_mem_sets_iff_exists_mem $ λ s, h.trans exists_range_iff.symm lemma eq_binfi_of_mem_sets_iff_exists_mem {f : ι → filter α} {p : ι → Prop} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ i (_ : p i), s ∈ f i) : l = ⨅ i (_ : p i), f i := begin rw [infi_subtype'], apply eq_infi_of_mem_sets_iff_exists_mem, intro s, exact h.trans ⟨λ ⟨i, pi, si⟩, ⟨⟨i, pi⟩, si⟩, λ ⟨⟨i, pi⟩, si⟩, ⟨i, pi, si⟩⟩ end lemma infi_sets_eq {f : ι → filter α} (h : directed (≥) f) (ne : nonempty ι) : (infi f).sets = (⋃ i, (f i).sets) := let ⟨i⟩ := ne, u := { filter . sets := (⋃ i, (f i).sets), univ_sets := by simp only [mem_Union]; exact ⟨i, univ_mem_sets⟩, sets_of_superset := by simp only [mem_Union, exists_imp_distrib]; intros x y i hx hxy; exact ⟨i, mem_sets_of_superset hx hxy⟩, inter_sets := begin simp only [mem_Union, exists_imp_distrib], assume x y a hx b hy, rcases h a b with ⟨c, ha, hb⟩, exact ⟨c, inter_mem_sets (ha hx) (hb hy)⟩ end } in have u = infi f, from eq_infi_of_mem_sets_iff_exists_mem (λ s, by simp only [mem_Union]), congr_arg filter.sets this.symm lemma mem_infi {f : ι → filter α} (h : directed (≥) f) (ne : nonempty ι) (s) : s ∈ infi f ↔ s ∈ ⋃ i, (f i).sets := show s ∈ (infi f).sets ↔ s ∈ ⋃ i, (f i).sets, by rw infi_sets_eq h ne @[nolint] -- Intentional use of `≥` lemma binfi_sets_eq {f : β → filter α} {s : set β} (h : directed_on (f ⁻¹'o (≥)) s) (ne : ∃i, i ∈ s) : (⨅ i∈s, f i).sets = (⋃ i ∈ s, (f i).sets) := let ⟨i, hi⟩ := ne in calc (⨅ i ∈ s, f i).sets = (⨅ t : {t // t ∈ s}, (f t.val)).sets : by rw [infi_subtype]; refl ... = (⨆ t : {t // t ∈ s}, (f t.val).sets) : infi_sets_eq (assume ⟨x, hx⟩ ⟨y, hy⟩, match h x hx y hy with ⟨z, h₁, h₂, h₃⟩ := ⟨⟨z, h₁⟩, h₂, h₃⟩ end) ⟨⟨i, hi⟩⟩ ... = (⨆ t ∈ {t | t ∈ s}, (f t).sets) : by rw [supr_subtype]; refl @[nolint] -- Intentional use of `≥` lemma mem_binfi {f : β → filter α} {s : set β} (h : directed_on (f ⁻¹'o (≥)) s) (ne : ∃i, i ∈ s) {t : set α} : t ∈ (⨅ i∈s, f i) ↔ t ∈ ⋃ i ∈ s, (f i).sets := by rw [← binfi_sets_eq h ne] lemma infi_sets_eq_finite (f : ι → filter α) : (⨅i, f i).sets = (⋃t:finset (plift ι), (⨅i∈t, f (plift.down i)).sets) := begin rw [infi_eq_infi_finset, infi_sets_eq], exact (directed_of_sup $ λs₁ s₂ hs, infi_le_infi $ λi, infi_le_infi_const $ λh, hs h), apply_instance end lemma mem_infi_finite {f : ι → filter α} (s) : s ∈ infi f ↔ s ∈ ⋃t:finset (plift ι), (⨅i∈t, f (plift.down i)).sets := show s ∈ (infi f).sets ↔ s ∈ ⋃t:finset (plift ι), (⨅i∈t, f (plift.down i)).sets, by rw infi_sets_eq_finite @[simp] lemma sup_join {f₁ f₂ : filter (filter α)} : (join f₁ ⊔ join f₂) = join (f₁ ⊔ f₂) := filter_eq $ set.ext $ assume x, by simp only [supr_sets_eq, join, mem_sup_sets, iff_self, mem_set_of_eq] @[simp] lemma supr_join {ι : Sort w} {f : ι → filter (filter α)} : (⨆x, join (f x)) = join (⨆x, f x) := filter_eq $ set.ext $ assume x, by simp only [supr_sets_eq, join, iff_self, mem_Inter, mem_set_of_eq] instance : bounded_distrib_lattice (filter α) := { le_sup_inf := begin assume x y z s, simp only [and_assoc, mem_inf_sets, mem_sup_sets, exists_prop, exists_imp_distrib, and_imp], intros hs t₁ ht₁ t₂ ht₂ hts, exact ⟨s ∪ t₁, x.sets_of_superset hs $ subset_union_left _ _, y.sets_of_superset ht₁ $ subset_union_right _ _, s ∪ t₂, x.sets_of_superset hs $ subset_union_left _ _, z.sets_of_superset ht₂ $ subset_union_right _ _, subset.trans (@le_sup_inf (set α) _ _ _ _) (union_subset (subset.refl _) hts)⟩ end, ..filter.lattice.complete_lattice } /- the complementary version with ⨆i, f ⊓ g i does not hold! -/ lemma infi_sup_eq {f : filter α} {g : ι → filter α} : (⨅ x, f ⊔ g x) = f ⊔ infi g := begin refine le_antisymm _ (le_infi $ assume i, sup_le_sup (le_refl f) $ infi_le _ _), rintros t ⟨h₁, h₂⟩, rw [infi_sets_eq_finite] at h₂, simp only [mem_Union, (finset.inf_eq_infi _ _).symm] at h₂, rcases h₂ with ⟨s, hs⟩, suffices : (⨅i, f ⊔ g i) ≤ f ⊔ s.inf (λi, g i.down), { exact this ⟨h₁, hs⟩ }, refine finset.induction_on s _ _, { exact le_sup_right_of_le le_top }, { rintros ⟨i⟩ s his ih, rw [finset.inf_insert, sup_inf_left], exact le_inf (infi_le _ _) ih } end lemma mem_infi_sets_finset {s : finset α} {f : α → filter β} : ∀t, t ∈ (⨅a∈s, f a) ↔ (∃p:α → set β, (∀a∈s, p a ∈ f a) ∧ (⋂a∈s, p a) ⊆ t) := show ∀t, t ∈ (⨅a∈s, f a) ↔ (∃p:α → set β, (∀a∈s, p a ∈ f a) ∧ (⨅a∈s, p a) ≤ t), begin simp only [(finset.inf_eq_infi _ _).symm], refine finset.induction_on s _ _, { simp only [finset.not_mem_empty, false_implies_iff, finset.inf_empty, top_le_iff, imp_true_iff, mem_top_sets, true_and, exists_const], intros; refl }, { intros a s has ih t, simp only [ih, finset.forall_mem_insert, finset.inf_insert, mem_inf_sets, exists_prop, iff_iff_implies_and_implies, exists_imp_distrib, and_imp, and_assoc] {contextual := tt}, split, { intros t₁ ht₁ t₂ p hp ht₂ ht, existsi function.update p a t₁, have : ∀a'∈s, function.update p a t₁ a' = p a', from assume a' ha', have a' ≠ a, from assume h, has $ h ▸ ha', function.update_noteq this, have eq : s.inf (λj, function.update p a t₁ j) = s.inf (λj, p j) := finset.inf_congr rfl this, simp only [this, ht₁, hp, function.update_same, true_and, imp_true_iff, eq] {contextual := tt}, exact subset.trans (inter_subset_inter (subset.refl _) ht₂) ht }, assume p hpa hp ht, exact ⟨p a, hpa, (s.inf p), ⟨⟨p, hp, le_refl _⟩, ht⟩⟩ } end /- principal equations -/ @[simp] lemma inf_principal {s t : set α} : principal s ⊓ principal t = principal (s ∩ t) := le_antisymm (by simp; exact ⟨s, subset.refl s, t, subset.refl t, by simp⟩) (by simp [le_inf_iff, inter_subset_left, inter_subset_right]) @[simp] lemma sup_principal {s t : set α} : principal s ⊔ principal t = principal (s ∪ t) := filter_eq $ set.ext $ by simp only [union_subset_iff, union_subset_iff, mem_sup_sets, forall_const, iff_self, mem_principal_sets] @[simp] lemma supr_principal {ι : Sort w} {s : ι → set α} : (⨆x, principal (s x)) = principal (⋃i, s i) := filter_eq $ set.ext $ assume x, by simp only [supr_sets_eq, mem_principal_sets, mem_Inter]; exact (@supr_le_iff (set α) _ _ _ _).symm lemma principal_univ : principal (univ : set α) = ⊤ := top_unique $ by simp only [le_principal_iff, mem_top_sets, eq_self_iff_true] lemma principal_empty : principal (∅ : set α) = ⊥ := bot_unique $ assume s _, empty_subset _ @[simp] lemma principal_eq_bot_iff {s : set α} : principal s = ⊥ ↔ s = ∅ := ⟨assume h, principal_eq_iff_eq.mp $ by simp only [principal_empty, h, eq_self_iff_true], assume h, by simp only [h, principal_empty, eq_self_iff_true]⟩ lemma inf_principal_eq_bot {f : filter α} {s : set α} (hs : -s ∈ f) : f ⊓ principal s = ⊥ := empty_in_sets_eq_bot.mp ⟨_, hs, s, mem_principal_self s, assume x ⟨h₁, h₂⟩, h₁ h₂⟩ theorem mem_inf_principal (f : filter α) (s t : set α) : s ∈ f ⊓ principal t ↔ { x | x ∈ t → x ∈ s } ∈ f := begin simp only [mem_inf_sets, mem_principal_sets, exists_prop], split, { rintros ⟨u, ul, v, tsubv, uvinter⟩, apply filter.mem_sets_of_superset ul, intros x xu xt, exact uvinter ⟨xu, tsubv xt⟩ }, intro h, refine ⟨_, h, t, set.subset.refl t, _⟩, rintros x ⟨hx, xt⟩, exact hx xt end @[simp] lemma infi_principal_finset {ι : Type w} (s : finset ι) (f : ι → set α) : (⨅i∈s, principal (f i)) = principal (⋂i∈s, f i) := begin ext t, simp [mem_infi_sets_finset], split, { rintros ⟨p, hp, ht⟩, calc (⋂ (i : ι) (H : i ∈ s), f i) ≤ (⋂ (i : ι) (H : i ∈ s), p i) : infi_le_infi (λi, infi_le_infi (λhi, mem_principal_sets.1 (hp i hi))) ... ≤ t : ht }, { assume h, exact ⟨f, λi hi, subset.refl _, h⟩ } end @[simp] lemma infi_principal_fintype {ι : Type w} [fintype ι] (f : ι → set α) : (⨅i, principal (f i)) = principal (⋂i, f i) := by simpa using infi_principal_finset finset.univ f end lattice section map /-- The forward map of a filter -/ def map (m : α → β) (f : filter α) : filter β := { sets := preimage m ⁻¹' f.sets, univ_sets := univ_mem_sets, sets_of_superset := assume s t hs st, mem_sets_of_superset hs $ preimage_mono st, inter_sets := assume s t hs ht, inter_mem_sets hs ht } @[simp] lemma map_principal {s : set α} {f : α → β} : map f (principal s) = principal (set.image f s) := filter_eq $ set.ext $ assume a, image_subset_iff.symm variables {f : filter α} {m : α → β} {m' : β → γ} {s : set α} {t : set β} @[simp] lemma mem_map : t ∈ map m f ↔ {x | m x ∈ t} ∈ f := iff.rfl lemma image_mem_map (hs : s ∈ f) : m '' s ∈ map m f := f.sets_of_superset hs $ subset_preimage_image m s lemma range_mem_map : range m ∈ map m f := by rw ←image_univ; exact image_mem_map univ_mem_sets lemma mem_map_sets_iff : t ∈ map m f ↔ (∃s∈f, m '' s ⊆ t) := iff.intro (assume ht, ⟨set.preimage m t, ht, image_preimage_subset _ _⟩) (assume ⟨s, hs, ht⟩, mem_sets_of_superset (image_mem_map hs) ht) @[simp] lemma map_id : filter.map id f = f := filter_eq $ rfl @[simp] lemma map_compose : filter.map m' ∘ filter.map m = filter.map (m' ∘ m) := funext $ assume _, filter_eq $ rfl @[simp] lemma map_map : filter.map m' (filter.map m f) = filter.map (m' ∘ m) f := congr_fun (@@filter.map_compose m m') f end map section comap /-- The inverse map of a filter -/ def comap (m : α → β) (f : filter β) : filter α := { sets := { s | ∃t∈ f, m ⁻¹' t ⊆ s }, univ_sets := ⟨univ, univ_mem_sets, by simp only [subset_univ, preimage_univ]⟩, sets_of_superset := assume a b ⟨a', ha', ma'a⟩ ab, ⟨a', ha', subset.trans ma'a ab⟩, inter_sets := assume a b ⟨a', ha₁, ha₂⟩ ⟨b', hb₁, hb₂⟩, ⟨a' ∩ b', inter_mem_sets ha₁ hb₁, inter_subset_inter ha₂ hb₂⟩ } end comap /-- The cofinite filter is the filter of subsets whose complements are finite. -/ def cofinite : filter α := { sets := {s | finite (- s)}, univ_sets := by simp only [compl_univ, finite_empty, mem_set_of_eq], sets_of_superset := assume s t (hs : finite (-s)) (st: s ⊆ t), finite_subset hs $ @lattice.neg_le_neg (set α) _ _ _ st, inter_sets := assume s t (hs : finite (-s)) (ht : finite (-t)), by simp only [compl_inter, finite_union, ht, hs, mem_set_of_eq] } lemma cofinite_ne_bot (hi : set.infinite (@set.univ α)) : @cofinite α ≠ ⊥ := forall_sets_neq_empty_iff_neq_bot.mp $ λ s hs hn, by change set.finite _ at hs; rw [hn, set.compl_empty] at hs; exact hi hs /-- The monadic bind operation on filter is defined the usual way in terms of `map` and `join`. Unfortunately, this `bind` does not result in the expected applicative. See `filter.seq` for the applicative instance. -/ def bind (f : filter α) (m : α → filter β) : filter β := join (map m f) /-- The applicative sequentiation operation. This is not induced by the bind operation. -/ def seq (f : filter (α → β)) (g : filter α) : filter β := ⟨{ s | ∃u∈ f, ∃t∈ g, (∀m∈u, ∀x∈t, (m : α → β) x ∈ s) }, ⟨univ, univ_mem_sets, univ, univ_mem_sets, by simp only [forall_prop_of_true, mem_univ, forall_true_iff]⟩, assume s₀ s₁ ⟨t₀, t₁, h₀, h₁, h⟩ hst, ⟨t₀, t₁, h₀, h₁, assume x hx y hy, hst $ h _ hx _ hy⟩, assume s₀ s₁ ⟨t₀, ht₀, t₁, ht₁, ht⟩ ⟨u₀, hu₀, u₁, hu₁, hu⟩, ⟨t₀ ∩ u₀, inter_mem_sets ht₀ hu₀, t₁ ∩ u₁, inter_mem_sets ht₁ hu₁, assume x ⟨hx₀, hx₁⟩ x ⟨hy₀, hy₁⟩, ⟨ht _ hx₀ _ hy₀, hu _ hx₁ _ hy₁⟩⟩⟩ instance : has_pure filter := ⟨λ(α : Type u) x, principal {x}⟩ instance : has_bind filter := ⟨@filter.bind⟩ instance : has_seq filter := ⟨@filter.seq⟩ instance : functor filter := { map := @filter.map } section -- this section needs to be before applicative, otherwise the wrong instance will be chosen protected def monad : monad filter := { map := @filter.map } local attribute [instance] filter.monad protected lemma is_lawful_monad : is_lawful_monad filter := { id_map := assume α f, filter_eq rfl, pure_bind := assume α β a f, by simp only [has_bind.bind, pure, bind, Sup_image, image_singleton, join_principal_eq_Sup, lattice.Sup_singleton, map_principal, eq_self_iff_true], bind_assoc := assume α β γ f m₁ m₂, filter_eq rfl, bind_pure_comp_eq_map := assume α β f x, filter_eq $ by simp only [has_bind.bind, pure, functor.map, bind, join, map, preimage, principal, set.subset_univ, eq_self_iff_true, function.comp_app, mem_set_of_eq, singleton_subset_iff] } end instance : applicative filter := { map := @filter.map, seq := @filter.seq } instance : alternative filter := { failure := λα, ⊥, orelse := λα x y, x ⊔ y } @[simp] lemma pure_def (x : α) : pure x = principal {x} := rfl @[simp] lemma mem_pure {a : α} {s : set α} : a ∈ s → s ∈ (pure a : filter α) := by simp only [imp_self, pure_def, mem_principal_sets, singleton_subset_iff]; exact id @[simp] lemma mem_pure_iff {a : α} {s : set α} : s ∈ (pure a : filter α) ↔ a ∈ s := by rw [pure_def, mem_principal_sets, set.singleton_subset_iff] @[simp] lemma map_def {α β} (m : α → β) (f : filter α) : m <$> f = map m f := rfl @[simp] lemma bind_def {α β} (f : filter α) (m : α → filter β) : f >>= m = bind f m := rfl /- map and comap equations -/ section map variables {f f₁ f₂ : filter α} {g g₁ g₂ : filter β} {m : α → β} {m' : β → γ} {s : set α} {t : set β} @[simp] theorem mem_comap_sets : s ∈ comap m g ↔ ∃t∈ g, m ⁻¹' t ⊆ s := iff.rfl theorem preimage_mem_comap (ht : t ∈ g) : m ⁻¹' t ∈ comap m g := ⟨t, ht, subset.refl _⟩ lemma comap_id : comap id f = f := le_antisymm (assume s, preimage_mem_comap) (assume s ⟨t, ht, hst⟩, mem_sets_of_superset ht hst) lemma comap_comap_comp {m : γ → β} {n : β → α} : comap m (comap n f) = comap (n ∘ m) f := le_antisymm (assume c ⟨b, hb, (h : preimage (n ∘ m) b ⊆ c)⟩, ⟨preimage n b, preimage_mem_comap hb, h⟩) (assume c ⟨b, ⟨a, ha, (h₁ : preimage n a ⊆ b)⟩, (h₂ : preimage m b ⊆ c)⟩, ⟨a, ha, show preimage m (preimage n a) ⊆ c, from subset.trans (preimage_mono h₁) h₂⟩) @[simp] theorem comap_principal {t : set β} : comap m (principal t) = principal (m ⁻¹' t) := filter_eq $ set.ext $ assume s, ⟨assume ⟨u, (hu : t ⊆ u), (b : preimage m u ⊆ s)⟩, subset.trans (preimage_mono hu) b, assume : preimage m t ⊆ s, ⟨t, subset.refl t, this⟩⟩ lemma map_le_iff_le_comap : map m f ≤ g ↔ f ≤ comap m g := ⟨assume h s ⟨t, ht, hts⟩, mem_sets_of_superset (h ht) hts, assume h s ht, h ⟨_, ht, subset.refl _⟩⟩ lemma gc_map_comap (m : α → β) : galois_connection (map m) (comap m) := assume f g, map_le_iff_le_comap lemma map_mono : monotone (map m) := (gc_map_comap m).monotone_l lemma comap_mono : monotone (comap m) := (gc_map_comap m).monotone_u @[simp] lemma map_bot : map m ⊥ = ⊥ := (gc_map_comap m).l_bot @[simp] lemma map_sup : map m (f₁ ⊔ f₂) = map m f₁ ⊔ map m f₂ := (gc_map_comap m).l_sup @[simp] lemma map_supr {f : ι → filter α} : map m (⨆i, f i) = (⨆i, map m (f i)) := (gc_map_comap m).l_supr @[simp] lemma comap_top : comap m ⊤ = ⊤ := (gc_map_comap m).u_top @[simp] lemma comap_inf : comap m (g₁ ⊓ g₂) = comap m g₁ ⊓ comap m g₂ := (gc_map_comap m).u_inf @[simp] lemma comap_infi {f : ι → filter β} : comap m (⨅i, f i) = (⨅i, comap m (f i)) := (gc_map_comap m).u_infi lemma le_comap_top (f : α → β) (l : filter α) : l ≤ comap f ⊤ := by rw [comap_top]; exact le_top lemma map_comap_le : map m (comap m g) ≤ g := (gc_map_comap m).l_u_le _ lemma le_comap_map : f ≤ comap m (map m f) := (gc_map_comap m).le_u_l _ @[simp] lemma comap_bot : comap m ⊥ = ⊥ := bot_unique $ assume s _, ⟨∅, by simp only [mem_bot_sets], by simp only [empty_subset, preimage_empty]⟩ lemma comap_supr {ι} {f : ι → filter β} {m : α → β} : comap m (supr f) = (⨆i, comap m (f i)) := le_antisymm (assume s hs, have ∀i, ∃t, t ∈ f i ∧ m ⁻¹' t ⊆ s, by simpa only [mem_comap_sets, exists_prop, mem_supr_sets] using mem_supr_sets.1 hs, let ⟨t, ht⟩ := classical.axiom_of_choice this in ⟨⋃i, t i, mem_supr_sets.2 $ assume i, (f i).sets_of_superset (ht i).1 (subset_Union _ _), begin rw [preimage_Union, Union_subset_iff], assume i, exact (ht i).2 end⟩) (supr_le $ assume i, comap_mono $ le_supr _ _) lemma comap_Sup {s : set (filter β)} {m : α → β} : comap m (Sup s) = (⨆f∈s, comap m f) := by simp only [Sup_eq_supr, comap_supr, eq_self_iff_true] lemma comap_sup : comap m (g₁ ⊔ g₂) = comap m g₁ ⊔ comap m g₂ := le_antisymm (assume s ⟨⟨t₁, ht₁, hs₁⟩, ⟨t₂, ht₂, hs₂⟩⟩, ⟨t₁ ∪ t₂, ⟨g₁.sets_of_superset ht₁ (subset_union_left _ _), g₂.sets_of_superset ht₂ (subset_union_right _ _)⟩, union_subset hs₁ hs₂⟩) ((@comap_mono _ _ m).le_map_sup _ _) lemma map_comap {f : filter β} {m : α → β} (hf : range m ∈ f) : (f.comap m).map m = f := le_antisymm map_comap_le (assume t' ⟨t, ht, sub⟩, by filter_upwards [ht, hf]; rintros x hxt ⟨y, rfl⟩; exact sub hxt) lemma comap_map {f : filter α} {m : α → β} (h : ∀ x y, m x = m y → x = y) : comap m (map m f) = f := have ∀s, preimage m (image m s) = s, from assume s, preimage_image_eq s h, le_antisymm (assume s hs, ⟨ image m s, f.sets_of_superset hs $ by simp only [this, subset.refl], by simp only [this, subset.refl]⟩) le_comap_map lemma le_of_map_le_map_inj' {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y) (h : map m f ≤ map m g) : f ≤ g := assume t ht, by filter_upwards [hsf, h $ image_mem_map (inter_mem_sets hsg ht)] assume a has ⟨b, ⟨hbs, hb⟩, h⟩, have b = a, from hm _ hbs _ has h, this ▸ hb lemma le_of_map_le_map_inj_iff {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y) : map m f ≤ map m g ↔ f ≤ g := iff.intro (le_of_map_le_map_inj' hsf hsg hm) (λ h, map_mono h) lemma eq_of_map_eq_map_inj' {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y) (h : map m f = map m g) : f = g := le_antisymm (le_of_map_le_map_inj' hsf hsg hm $ le_of_eq h) (le_of_map_le_map_inj' hsg hsf hm $ le_of_eq h.symm) lemma map_inj {f g : filter α} {m : α → β} (hm : ∀ x y, m x = m y → x = y) (h : map m f = map m g) : f = g := have comap m (map m f) = comap m (map m g), by rw h, by rwa [comap_map hm, comap_map hm] at this theorem le_map_comap_of_surjective' {f : α → β} {l : filter β} {u : set β} (ul : u ∈ l) (hf : ∀ y ∈ u, ∃ x, f x = y) : l ≤ map f (comap f l) := assume s ⟨t, tl, ht⟩, have t ∩ u ⊆ s, from assume x ⟨xt, xu⟩, exists.elim (hf x xu) $ λ a faeq, by { rw ←faeq, apply ht, change f a ∈ t, rw faeq, exact xt }, mem_sets_of_superset (inter_mem_sets tl ul) this theorem map_comap_of_surjective' {f : α → β} {l : filter β} {u : set β} (ul : u ∈ l) (hf : ∀ y ∈ u, ∃ x, f x = y) : map f (comap f l) = l := le_antisymm map_comap_le (le_map_comap_of_surjective' ul hf) theorem le_map_comap_of_surjective {f : α → β} (hf : function.surjective f) (l : filter β) : l ≤ map f (comap f l) := le_map_comap_of_surjective' univ_mem_sets (λ y _, hf y) theorem map_comap_of_surjective {f : α → β} (hf : function.surjective f) (l : filter β) : map f (comap f l) = l := le_antisymm map_comap_le (le_map_comap_of_surjective hf l) lemma comap_neq_bot {f : filter β} {m : α → β} (hm : ∀t∈ f, ∃a, m a ∈ t) : comap m f ≠ ⊥ := forall_sets_neq_empty_iff_neq_bot.mp $ assume s ⟨t, ht, t_s⟩, let ⟨a, (ha : a ∈ preimage m t)⟩ := hm t ht in neq_bot_of_le_neq_bot (ne_empty_of_mem ha) t_s lemma comap_ne_bot_of_range_mem {f : filter β} {m : α → β} (hf : f ≠ ⊥) (hm : range m ∈ f) : comap m f ≠ ⊥ := comap_neq_bot $ assume t ht, let ⟨_, ha, a, rfl⟩ := inhabited_of_mem_sets hf (inter_mem_sets ht hm) in ⟨a, ha⟩ lemma comap_inf_principal_ne_bot_of_image_mem {f : filter β} {m : α → β} (hf : f ≠ ⊥) {s : set α} (hs : m '' s ∈ f) : (comap m f ⊓ principal s) ≠ ⊥ := begin refine compl_compl s ▸ mt mem_sets_of_neq_bot _, rintros ⟨t, ht, hts⟩, rcases inhabited_of_mem_sets hf (inter_mem_sets hs ht) with ⟨_, ⟨x, hxs, rfl⟩, hxt⟩, exact absurd hxs (hts hxt) end lemma comap_neq_bot_of_surj {f : filter β} {m : α → β} (hf : f ≠ ⊥) (hm : function.surjective m) : comap m f ≠ ⊥ := comap_ne_bot_of_range_mem hf $ univ_mem_sets' hm @[simp] lemma map_eq_bot_iff : map m f = ⊥ ↔ f = ⊥ := ⟨by rw [←empty_in_sets_eq_bot, ←empty_in_sets_eq_bot]; exact id, assume h, by simp only [h, eq_self_iff_true, map_bot]⟩ lemma map_ne_bot (hf : f ≠ ⊥) : map m f ≠ ⊥ := assume h, hf $ by rwa [map_eq_bot_iff] at h lemma sInter_comap_sets (f : α → β) (F : filter β) : ⋂₀(comap f F).sets = ⋂ U ∈ F, f ⁻¹' U := begin ext x, suffices : (∀ (A : set α) (B : set β), B ∈ F → f ⁻¹' B ⊆ A → x ∈ A) ↔ ∀ (B : set β), B ∈ F → f x ∈ B, by simp only [mem_sInter, mem_Inter, mem_comap_sets, this, and_imp, mem_comap_sets, exists_prop, mem_sInter, iff_self, mem_Inter, mem_preimage, exists_imp_distrib], split, { intros h U U_in, simpa only [set.subset.refl, forall_prop_of_true, mem_preimage] using h (f ⁻¹' U) U U_in }, { intros h V U U_in f_U_V, exact f_U_V (h U U_in) }, end end map lemma map_cong {m₁ m₂ : α → β} {f : filter α} (h : {x | m₁ x = m₂ x} ∈ f) : map m₁ f = map m₂ f := have ∀(m₁ m₂ : α → β) (h : {x | m₁ x = m₂ x} ∈ f), map m₁ f ≤ map m₂ f, begin intros m₁ m₂ h s hs, show {x | m₁ x ∈ s} ∈ f, filter_upwards [h, hs], simp only [subset_def, mem_preimage, mem_set_of_eq, forall_true_iff] {contextual := tt} end, le_antisymm (this m₁ m₂ h) (this m₂ m₁ $ mem_sets_of_superset h $ assume x, eq.symm) -- this is a generic rule for monotone functions: lemma map_infi_le {f : ι → filter α} {m : α → β} : map m (infi f) ≤ (⨅ i, map m (f i)) := le_infi $ assume i, map_mono $ infi_le _ _ lemma map_infi_eq {f : ι → filter α} {m : α → β} (hf : directed (≥) f) (hι : nonempty ι) : map m (infi f) = (⨅ i, map m (f i)) := le_antisymm map_infi_le (assume s (hs : preimage m s ∈ infi f), have ∃i, preimage m s ∈ f i, by simp only [infi_sets_eq hf hι, mem_Union] at hs; assumption, let ⟨i, hi⟩ := this in have (⨅ i, map m (f i)) ≤ principal s, from infi_le_of_le i $ by simp only [le_principal_iff, mem_map]; assumption, by simp only [filter.le_principal_iff] at this; assumption) lemma map_binfi_eq {ι : Type w} {f : ι → filter α} {m : α → β} {p : ι → Prop} (h : directed_on (f ⁻¹'o (≥)) {x | p x}) (ne : ∃i, p i) : map m (⨅i (h : p i), f i) = (⨅i (h: p i), map m (f i)) := let ⟨i, hi⟩ := ne in calc map m (⨅i (h : p i), f i) = map m (⨅i:subtype p, f i.val) : by simp only [infi_subtype, eq_self_iff_true] ... = (⨅i:subtype p, map m (f i.val)) : map_infi_eq (assume ⟨x, hx⟩ ⟨y, hy⟩, match h x hx y hy with ⟨z, h₁, h₂, h₃⟩ := ⟨⟨z, h₁⟩, h₂, h₃⟩ end) ⟨⟨i, hi⟩⟩ ... = (⨅i (h : p i), map m (f i)) : by simp only [infi_subtype, eq_self_iff_true] lemma map_inf_le {f g : filter α} {m : α → β} : map m (f ⊓ g) ≤ map m f ⊓ map m g := (@map_mono _ _ m).map_inf_le f g lemma map_inf' {f g : filter α} {m : α → β} {t : set α} (htf : t ∈ f) (htg : t ∈ g) (h : ∀x∈t, ∀y∈t, m x = m y → x = y) : map m (f ⊓ g) = map m f ⊓ map m g := begin refine le_antisymm map_inf_le (assume s hs, _), simp only [map, mem_inf_sets, exists_prop, mem_map, mem_preimage, mem_inf_sets] at hs ⊢, rcases hs with ⟨t₁, h₁, t₂, h₂, hs⟩, refine ⟨m '' (t₁ ∩ t), _, m '' (t₂ ∩ t), _, _⟩, { filter_upwards [h₁, htf] assume a h₁ h₂, mem_image_of_mem _ ⟨h₁, h₂⟩ }, { filter_upwards [h₂, htg] assume a h₁ h₂, mem_image_of_mem _ ⟨h₁, h₂⟩ }, { rw [image_inter_on], { refine image_subset_iff.2 _, exact λ x ⟨⟨h₁, _⟩, h₂, _⟩, hs ⟨h₁, h₂⟩ }, { exact λ x ⟨_, hx⟩ y ⟨_, hy⟩, h x hx y hy } } end lemma map_inf {f g : filter α} {m : α → β} (h : function.injective m) : map m (f ⊓ g) = map m f ⊓ map m g := map_inf' univ_mem_sets univ_mem_sets (assume x _ y _ hxy, h hxy) lemma map_eq_comap_of_inverse {f : filter α} {m : α → β} {n : β → α} (h₁ : m ∘ n = id) (h₂ : n ∘ m = id) : map m f = comap n f := le_antisymm (assume b ⟨a, ha, (h : preimage n a ⊆ b)⟩, f.sets_of_superset ha $ calc a = preimage (n ∘ m) a : by simp only [h₂, preimage_id, eq_self_iff_true] ... ⊆ preimage m b : preimage_mono h) (assume b (hb : preimage m b ∈ f), ⟨preimage m b, hb, show preimage (m ∘ n) b ⊆ b, by simp only [h₁]; apply subset.refl⟩) lemma map_swap_eq_comap_swap {f : filter (α × β)} : prod.swap <$> f = comap prod.swap f := map_eq_comap_of_inverse prod.swap_swap_eq prod.swap_swap_eq lemma le_map {f : filter α} {m : α → β} {g : filter β} (h : ∀s∈ f, m '' s ∈ g) : g ≤ f.map m := assume s hs, mem_sets_of_superset (h _ hs) $ image_preimage_subset _ _ section applicative @[simp] lemma mem_pure_sets {a : α} {s : set α} : s ∈ (pure a : filter α) ↔ a ∈ s := by simp only [iff_self, pure_def, mem_principal_sets, singleton_subset_iff] lemma singleton_mem_pure_sets {a : α} : {a} ∈ (pure a : filter α) := by simp only [mem_singleton, pure_def, mem_principal_sets, singleton_subset_iff] @[simp] lemma pure_neq_bot {α : Type u} {a : α} : pure a ≠ (⊥ : filter α) := by simp only [pure, has_pure.pure, ne.def, not_false_iff, singleton_ne_empty, principal_eq_bot_iff] lemma mem_seq_sets_def {f : filter (α → β)} {g : filter α} {s : set β} : s ∈ f.seq g ↔ (∃u ∈ f, ∃t ∈ g, ∀x∈u, ∀y∈t, (x : α → β) y ∈ s) := iff.rfl lemma mem_seq_sets_iff {f : filter (α → β)} {g : filter α} {s : set β} : s ∈ f.seq g ↔ (∃u ∈ f, ∃t ∈ g, set.seq u t ⊆ s) := by simp only [mem_seq_sets_def, seq_subset, exists_prop, iff_self] lemma mem_map_seq_iff {f : filter α} {g : filter β} {m : α → β → γ} {s : set γ} : s ∈ (f.map m).seq g ↔ (∃t u, t ∈ g ∧ u ∈ f ∧ ∀x∈u, ∀y∈t, m x y ∈ s) := iff.intro (assume ⟨t, ht, s, hs, hts⟩, ⟨s, m ⁻¹' t, hs, ht, assume a, hts _⟩) (assume ⟨t, s, ht, hs, hts⟩, ⟨m '' s, image_mem_map hs, t, ht, assume f ⟨a, has, eq⟩, eq ▸ hts _ has⟩) lemma seq_mem_seq_sets {f : filter (α → β)} {g : filter α} {s : set (α → β)} {t : set α} (hs : s ∈ f) (ht : t ∈ g) : s.seq t ∈ f.seq g := ⟨s, hs, t, ht, assume f hf a ha, ⟨f, hf, a, ha, rfl⟩⟩ lemma le_seq {f : filter (α → β)} {g : filter α} {h : filter β} (hh : ∀t ∈ f, ∀u ∈ g, set.seq t u ∈ h) : h ≤ seq f g := assume s ⟨t, ht, u, hu, hs⟩, mem_sets_of_superset (hh _ ht _ hu) $ assume b ⟨m, hm, a, ha, eq⟩, eq ▸ hs _ hm _ ha lemma seq_mono {f₁ f₂ : filter (α → β)} {g₁ g₂ : filter α} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁.seq g₁ ≤ f₂.seq g₂ := le_seq $ assume s hs t ht, seq_mem_seq_sets (hf hs) (hg ht) @[simp] lemma pure_seq_eq_map (g : α → β) (f : filter α) : seq (pure g) f = f.map g := begin refine le_antisymm (le_map $ assume s hs, _) (le_seq $ assume s hs t ht, _), { rw ← singleton_seq, apply seq_mem_seq_sets _ hs, simp only [mem_singleton, pure_def, mem_principal_sets, singleton_subset_iff] }, { rw mem_pure_sets at hs, refine sets_of_superset (map g f) (image_mem_map ht) _, rintros b ⟨a, ha, rfl⟩, exact ⟨g, hs, a, ha, rfl⟩ } end @[simp] lemma map_pure (f : α → β) (a : α) : map f (pure a) = pure (f a) := le_antisymm (le_principal_iff.2 $ sets_of_superset (map f (pure a)) (image_mem_map singleton_mem_pure_sets) $ by simp only [image_singleton, mem_singleton, singleton_subset_iff]) (le_map $ assume s, begin simp only [mem_image, pure_def, mem_principal_sets, singleton_subset_iff], exact assume has, ⟨a, has, rfl⟩ end) @[simp] lemma seq_pure (f : filter (α → β)) (a : α) : seq f (pure a) = map (λg:α → β, g a) f := begin refine le_antisymm (le_map $ assume s hs, _) (le_seq $ assume s hs t ht, _), { rw ← seq_singleton, exact seq_mem_seq_sets hs (by simp only [mem_singleton, pure_def, mem_principal_sets, singleton_subset_iff]) }, { rw mem_pure_sets at ht, refine sets_of_superset (map (λg:α→β, g a) f) (image_mem_map hs) _, rintros b ⟨g, hg, rfl⟩, exact ⟨g, hg, a, ht, rfl⟩ } end @[simp] lemma seq_assoc (x : filter α) (g : filter (α → β)) (h : filter (β → γ)) : seq h (seq g x) = seq (seq (map (∘) h) g) x := begin refine le_antisymm (le_seq $ assume s hs t ht, _) (le_seq $ assume s hs t ht, _), { rcases mem_seq_sets_iff.1 hs with ⟨u, hu, v, hv, hs⟩, rcases mem_map_sets_iff.1 hu with ⟨w, hw, hu⟩, refine mem_sets_of_superset _ (set.seq_mono (subset.trans (set.seq_mono hu (subset.refl _)) hs) (subset.refl _)), rw ← set.seq_seq, exact seq_mem_seq_sets hw (seq_mem_seq_sets hv ht) }, { rcases mem_seq_sets_iff.1 ht with ⟨u, hu, v, hv, ht⟩, refine mem_sets_of_superset _ (set.seq_mono (subset.refl _) ht), rw set.seq_seq, exact seq_mem_seq_sets (seq_mem_seq_sets (image_mem_map hs) hu) hv } end lemma prod_map_seq_comm (f : filter α) (g : filter β) : (map prod.mk f).seq g = seq (map (λb a, (a, b)) g) f := begin refine le_antisymm (le_seq $ assume s hs t ht, _) (le_seq $ assume s hs t ht, _), { rcases mem_map_sets_iff.1 hs with ⟨u, hu, hs⟩, refine mem_sets_of_superset _ (set.seq_mono hs (subset.refl _)), rw ← set.prod_image_seq_comm, exact seq_mem_seq_sets (image_mem_map ht) hu }, { rcases mem_map_sets_iff.1 hs with ⟨u, hu, hs⟩, refine mem_sets_of_superset _ (set.seq_mono hs (subset.refl _)), rw set.prod_image_seq_comm, exact seq_mem_seq_sets (image_mem_map ht) hu } end instance : is_lawful_functor (filter : Type u → Type u) := { id_map := assume α f, map_id, comp_map := assume α β γ f g a, map_map.symm } instance : is_lawful_applicative (filter : Type u → Type u) := { pure_seq_eq_map := assume α β, pure_seq_eq_map, map_pure := assume α β, map_pure, seq_pure := assume α β, seq_pure, seq_assoc := assume α β γ, seq_assoc } instance : is_comm_applicative (filter : Type u → Type u) := ⟨assume α β f g, prod_map_seq_comm f g⟩ lemma {l} seq_eq_filter_seq {α β : Type l} (f : filter (α → β)) (g : filter α) : f <*> g = seq f g := rfl end applicative /- bind equations -/ section bind @[simp] lemma mem_bind_sets {s : set β} {f : filter α} {m : α → filter β} : s ∈ bind f m ↔ ∃t ∈ f, ∀x ∈ t, s ∈ m x := calc s ∈ bind f m ↔ {a | s ∈ m a} ∈ f : by simp only [bind, mem_map, iff_self, mem_join_sets, mem_set_of_eq] ... ↔ (∃t ∈ f, t ⊆ {a | s ∈ m a}) : exists_sets_subset_iff.symm ... ↔ (∃t ∈ f, ∀x ∈ t, s ∈ m x) : iff.rfl lemma bind_mono {f : filter α} {g h : α → filter β} (h₁ : {a | g a ≤ h a} ∈ f) : bind f g ≤ bind f h := assume x h₂, show (_ ∈ f), by filter_upwards [h₁, h₂] assume s gh' h', gh' h' lemma bind_sup {f g : filter α} {h : α → filter β} : bind (f ⊔ g) h = bind f h ⊔ bind g h := by simp only [bind, sup_join, map_sup, eq_self_iff_true] lemma bind_mono2 {f g : filter α} {h : α → filter β} (h₁ : f ≤ g) : bind f h ≤ bind g h := assume s h', h₁ h' lemma principal_bind {s : set α} {f : α → filter β} : (bind (principal s) f) = (⨆x ∈ s, f x) := show join (map f (principal s)) = (⨆x ∈ s, f x), by simp only [Sup_image, join_principal_eq_Sup, map_principal, eq_self_iff_true] end bind lemma infi_neq_bot_of_directed {f : ι → filter α} (hn : nonempty α) (hd : directed (≥) f) (hb : ∀i, f i ≠ ⊥) : (infi f) ≠ ⊥ := let ⟨x⟩ := hn in assume h, have he: ∅ ∈ (infi f), from h.symm ▸ (mem_bot_sets : ∅ ∈ (⊥ : filter α)), classical.by_cases (assume : nonempty ι, have ∃i, ∅ ∈ f i, by rw [mem_infi hd this] at he; simp only [mem_Union] at he; assumption, let ⟨i, hi⟩ := this in hb i $ bot_unique $ assume s _, (f i).sets_of_superset hi $ empty_subset _) (assume : ¬ nonempty ι, have univ ⊆ (∅ : set α), begin rw [←principal_mono, principal_univ, principal_empty, ←h], exact (le_infi $ assume i, false.elim $ this ⟨i⟩) end, this $ mem_univ x) lemma infi_neq_bot_iff_of_directed {f : ι → filter α} (hn : nonempty α) (hd : directed (≥) f) : (infi f) ≠ ⊥ ↔ (∀i, f i ≠ ⊥) := ⟨assume neq_bot i eq_bot, neq_bot $ bot_unique $ infi_le_of_le i $ eq_bot ▸ le_refl _, infi_neq_bot_of_directed hn hd⟩ lemma mem_infi_sets {f : ι → filter α} (i : ι) : ∀{s}, s ∈ f i → s ∈ ⨅i, f i := show (⨅i, f i) ≤ f i, from infi_le _ _ @[elab_as_eliminator] lemma infi_sets_induct {f : ι → filter α} {s : set α} (hs : s ∈ infi f) {p : set α → Prop} (uni : p univ) (ins : ∀{i s₁ s₂}, s₁ ∈ f i → p s₂ → p (s₁ ∩ s₂)) (upw : ∀{s₁ s₂}, s₁ ⊆ s₂ → p s₁ → p s₂) : p s := begin rw [mem_infi_finite] at hs, simp only [mem_Union, (finset.inf_eq_infi _ _).symm] at hs, rcases hs with ⟨is, his⟩, revert s, refine finset.induction_on is _ _, { assume s hs, rwa [mem_top_sets.1 hs] }, { rintros ⟨i⟩ js his ih s hs, rw [finset.inf_insert, mem_inf_sets] at hs, rcases hs with ⟨s₁, hs₁, s₂, hs₂, hs⟩, exact upw hs (ins hs₁ (ih hs₂)) } end /- tendsto -/ /-- `tendsto` is the generic "limit of a function" predicate. `tendsto f l₁ l₂` asserts that for every `l₂` neighborhood `a`, the `f`-preimage of `a` is an `l₁` neighborhood. -/ def tendsto (f : α → β) (l₁ : filter α) (l₂ : filter β) := l₁.map f ≤ l₂ lemma tendsto_def {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ ∀ s ∈ l₂, f ⁻¹' s ∈ l₁ := iff.rfl lemma tendsto_iff_comap {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ l₁ ≤ l₂.comap f := map_le_iff_le_comap lemma tendsto.congr' {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (hl : {x | f₁ x = f₂ x} ∈ l₁) (h : tendsto f₁ l₁ l₂) : tendsto f₂ l₁ l₂ := by rwa [tendsto, ←map_cong hl] theorem tendsto.congr'r {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (h : ∀ x, f₁ x = f₂ x) : tendsto f₁ l₁ l₂ ↔ tendsto f₂ l₁ l₂ := iff_of_eq (by congr'; exact funext h) theorem tendsto.congr {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (h : ∀ x, f₁ x = f₂ x) : tendsto f₁ l₁ l₂ → tendsto f₂ l₁ l₂ := (tendsto.congr'r h).1 lemma tendsto_id' {x y : filter α} : x ≤ y → tendsto id x y := by simp only [tendsto, map_id, forall_true_iff] {contextual := tt} lemma tendsto_id {x : filter α} : tendsto id x x := tendsto_id' $ le_refl x lemma tendsto.comp {f : α → β} {g : β → γ} {x : filter α} {y : filter β} {z : filter γ} (hg : tendsto g y z) (hf : tendsto f x y) : tendsto (g ∘ f) x z := calc map (g ∘ f) x = map g (map f x) : by rw [map_map] ... ≤ map g y : map_mono hf ... ≤ z : hg lemma tendsto_le_left {f : α → β} {x y : filter α} {z : filter β} (h : y ≤ x) : tendsto f x z → tendsto f y z := le_trans (map_mono h) lemma tendsto_le_right {f : α → β} {x : filter α} {y z : filter β} (h₁ : y ≤ z) (h₂ : tendsto f x y) : tendsto f x z := le_trans h₂ h₁ lemma tendsto.ne_bot {f : α → β} {x : filter α} {y : filter β} (h : tendsto f x y) (hx : x ≠ ⊥) : y ≠ ⊥ := neq_bot_of_le_neq_bot (map_ne_bot hx) h lemma tendsto_map {f : α → β} {x : filter α} : tendsto f x (map f x) := le_refl (map f x) lemma tendsto_map' {f : β → γ} {g : α → β} {x : filter α} {y : filter γ} (h : tendsto (f ∘ g) x y) : tendsto f (map g x) y := by rwa [tendsto, map_map] lemma tendsto_map'_iff {f : β → γ} {g : α → β} {x : filter α} {y : filter γ} : tendsto f (map g x) y ↔ tendsto (f ∘ g) x y := by rw [tendsto, map_map]; refl lemma tendsto_comap {f : α → β} {x : filter β} : tendsto f (comap f x) x := map_comap_le lemma tendsto_comap_iff {f : α → β} {g : β → γ} {a : filter α} {c : filter γ} : tendsto f a (c.comap g) ↔ tendsto (g ∘ f) a c := ⟨assume h, tendsto_comap.comp h, assume h, map_le_iff_le_comap.mp $ by rwa [map_map]⟩ lemma tendsto_comap'_iff {m : α → β} {f : filter α} {g : filter β} {i : γ → α} (h : range i ∈ f) : tendsto (m ∘ i) (comap i f) g ↔ tendsto m f g := by rw [tendsto, ← map_compose]; simp only [(∘), map_comap h, tendsto] lemma comap_eq_of_inverse {f : filter α} {g : filter β} {φ : α → β} (ψ : β → α) (eq : ψ ∘ φ = id) (hφ : tendsto φ f g) (hψ : tendsto ψ g f) : comap φ g = f := begin refine le_antisymm (le_trans (comap_mono $ map_le_iff_le_comap.1 hψ) _) (map_le_iff_le_comap.1 hφ), rw [comap_comap_comp, eq, comap_id], exact le_refl _ end lemma map_eq_of_inverse {f : filter α} {g : filter β} {φ : α → β} (ψ : β → α) (eq : φ ∘ ψ = id) (hφ : tendsto φ f g) (hψ : tendsto ψ g f) : map φ f = g := begin refine le_antisymm hφ (le_trans _ (map_mono hψ)), rw [map_map, eq, map_id], exact le_refl _ end lemma tendsto_inf {f : α → β} {x : filter α} {y₁ y₂ : filter β} : tendsto f x (y₁ ⊓ y₂) ↔ tendsto f x y₁ ∧ tendsto f x y₂ := by simp only [tendsto, lattice.le_inf_iff, iff_self] lemma tendsto_inf_left {f : α → β} {x₁ x₂ : filter α} {y : filter β} (h : tendsto f x₁ y) : tendsto f (x₁ ⊓ x₂) y := le_trans (map_mono inf_le_left) h lemma tendsto_inf_right {f : α → β} {x₁ x₂ : filter α} {y : filter β} (h : tendsto f x₂ y) : tendsto f (x₁ ⊓ x₂) y := le_trans (map_mono inf_le_right) h lemma tendsto.inf {f : α → β} {x₁ x₂ : filter α} {y₁ y₂ : filter β} (h₁ : tendsto f x₁ y₁) (h₂ : tendsto f x₂ y₂) : tendsto f (x₁ ⊓ x₂) (y₁ ⊓ y₂) := tendsto_inf.2 ⟨tendsto_inf_left h₁, tendsto_inf_right h₂⟩ lemma tendsto_infi {f : α → β} {x : filter α} {y : ι → filter β} : tendsto f x (⨅i, y i) ↔ ∀i, tendsto f x (y i) := by simp only [tendsto, iff_self, lattice.le_infi_iff] lemma tendsto_infi' {f : α → β} {x : ι → filter α} {y : filter β} (i : ι) : tendsto f (x i) y → tendsto f (⨅i, x i) y := tendsto_le_left (infi_le _ _) lemma tendsto_principal {f : α → β} {a : filter α} {s : set β} : tendsto f a (principal s) ↔ {a | f a ∈ s} ∈ a := by simp only [tendsto, le_principal_iff, mem_map, iff_self] lemma tendsto_principal_principal {f : α → β} {s : set α} {t : set β} : tendsto f (principal s) (principal t) ↔ ∀a∈s, f a ∈ t := by simp only [tendsto, image_subset_iff, le_principal_iff, map_principal, mem_principal_sets]; refl lemma tendsto_pure_pure (f : α → β) (a : α) : tendsto f (pure a) (pure (f a)) := show filter.map f (pure a) ≤ pure (f a), by rw [filter.map_pure]; exact le_refl _ lemma tendsto_const_pure {a : filter α} {b : β} : tendsto (λa, b) a (pure b) := by simp [tendsto]; exact univ_mem_sets lemma tendsto_if {l₁ : filter α} {l₂ : filter β} {f g : α → β} {p : α → Prop} [decidable_pred p] (h₀ : tendsto f (l₁ ⊓ principal p) l₂) (h₁ : tendsto g (l₁ ⊓ principal { x | ¬ p x }) l₂) : tendsto (λ x, if p x then f x else g x) l₁ l₂ := begin revert h₀ h₁, simp only [tendsto_def, mem_inf_principal], intros h₀ h₁ s hs, apply mem_sets_of_superset (inter_mem_sets (h₀ s hs) (h₁ s hs)), rintros x ⟨hp₀, hp₁⟩, simp only [mem_preimage], by_cases h : p x, { rw if_pos h, exact hp₀ h }, rw if_neg h, exact hp₁ h end section prod variables {s : set α} {t : set β} {f : filter α} {g : filter β} /- The product filter cannot be defined using the monad structure on filters. For example: F := do {x ← seq, y ← top, return (x, y)} hence: s ∈ F ↔ ∃n, [n..∞] × univ ⊆ s G := do {y ← top, x ← seq, return (x, y)} hence: s ∈ G ↔ ∀i:ℕ, ∃n, [n..∞] × {i} ⊆ s Now ⋃i, [i..∞] × {i} is in G but not in F. As product filter we want to have F as result. -/ /-- Product of filters. This is the filter generated by cartesian products of elements of the component filters. -/ protected def prod (f : filter α) (g : filter β) : filter (α × β) := f.comap prod.fst ⊓ g.comap prod.snd lemma prod_mem_prod {s : set α} {t : set β} {f : filter α} {g : filter β} (hs : s ∈ f) (ht : t ∈ g) : set.prod s t ∈ filter.prod f g := inter_mem_inf_sets (preimage_mem_comap hs) (preimage_mem_comap ht) lemma mem_prod_iff {s : set (α×β)} {f : filter α} {g : filter β} : s ∈ filter.prod f g ↔ (∃ t₁ ∈ f, ∃ t₂ ∈ g, set.prod t₁ t₂ ⊆ s) := begin simp only [filter.prod], split, exact assume ⟨t₁, ⟨s₁, hs₁, hts₁⟩, t₂, ⟨s₂, hs₂, hts₂⟩, h⟩, ⟨s₁, hs₁, s₂, hs₂, subset.trans (inter_subset_inter hts₁ hts₂) h⟩, exact assume ⟨t₁, ht₁, t₂, ht₂, h⟩, ⟨prod.fst ⁻¹' t₁, ⟨t₁, ht₁, subset.refl _⟩, prod.snd ⁻¹' t₂, ⟨t₂, ht₂, subset.refl _⟩, h⟩ end lemma tendsto_fst {f : filter α} {g : filter β} : tendsto prod.fst (filter.prod f g) f := tendsto_inf_left tendsto_comap lemma tendsto_snd {f : filter α} {g : filter β} : tendsto prod.snd (filter.prod f g) g := tendsto_inf_right tendsto_comap lemma tendsto.prod_mk {f : filter α} {g : filter β} {h : filter γ} {m₁ : α → β} {m₂ : α → γ} (h₁ : tendsto m₁ f g) (h₂ : tendsto m₂ f h) : tendsto (λx, (m₁ x, m₂ x)) f (filter.prod g h) := tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩ lemma prod_infi_left {f : ι → filter α} {g : filter β} (i : ι) : filter.prod (⨅i, f i) g = (⨅i, filter.prod (f i) g) := by rw [filter.prod, comap_infi, infi_inf i]; simp only [filter.prod, eq_self_iff_true] lemma prod_infi_right {f : filter α} {g : ι → filter β} (i : ι) : filter.prod f (⨅i, g i) = (⨅i, filter.prod f (g i)) := by rw [filter.prod, comap_infi, inf_infi i]; simp only [filter.prod, eq_self_iff_true] lemma prod_mono {f₁ f₂ : filter α} {g₁ g₂ : filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : filter.prod f₁ g₁ ≤ filter.prod f₂ g₂ := inf_le_inf (comap_mono hf) (comap_mono hg) lemma prod_comap_comap_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : β₁ → α₁} {m₂ : β₂ → α₂} : filter.prod (comap m₁ f₁) (comap m₂ f₂) = comap (λp:β₁×β₂, (m₁ p.1, m₂ p.2)) (filter.prod f₁ f₂) := by simp only [filter.prod, comap_comap_comp, eq_self_iff_true, comap_inf] lemma prod_comm' : filter.prod f g = comap (prod.swap) (filter.prod g f) := by simp only [filter.prod, comap_comap_comp, (∘), inf_comm, prod.fst_swap, eq_self_iff_true, prod.snd_swap, comap_inf] lemma prod_comm : filter.prod f g = map (λp:β×α, (p.2, p.1)) (filter.prod g f) := by rw [prod_comm', ← map_swap_eq_comap_swap]; refl lemma prod_map_map_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : α₁ → β₁} {m₂ : α₂ → β₂} : filter.prod (map m₁ f₁) (map m₂ f₂) = map (λp:α₁×α₂, (m₁ p.1, m₂ p.2)) (filter.prod f₁ f₂) := le_antisymm (assume s hs, let ⟨s₁, hs₁, s₂, hs₂, h⟩ := mem_prod_iff.mp hs in filter.sets_of_superset _ (prod_mem_prod (image_mem_map hs₁) (image_mem_map hs₂)) $ calc set.prod (m₁ '' s₁) (m₂ '' s₂) = (λp:α₁×α₂, (m₁ p.1, m₂ p.2)) '' set.prod s₁ s₂ : set.prod_image_image_eq ... ⊆ _ : by rwa [image_subset_iff]) ((tendsto.comp (le_refl _) tendsto_fst).prod_mk (tendsto.comp (le_refl _) tendsto_snd)) lemma map_prod (m : α × β → γ) (f : filter α) (g : filter β) : map m (f.prod g) = (f.map (λa b, m (a, b))).seq g := begin simp [filter.ext_iff, mem_prod_iff, mem_map_seq_iff], assume s, split, exact assume ⟨t, ht, s, hs, h⟩, ⟨s, hs, t, ht, assume x hx y hy, @h ⟨x, y⟩ ⟨hx, hy⟩⟩, exact assume ⟨s, hs, t, ht, h⟩, ⟨t, ht, s, hs, assume ⟨x, y⟩ ⟨hx, hy⟩, h x hx y hy⟩ end lemma prod_eq {f : filter α} {g : filter β} : f.prod g = (f.map prod.mk).seq g := have h : _ := map_prod id f g, by rwa [map_id] at h lemma prod_inf_prod {f₁ f₂ : filter α} {g₁ g₂ : filter β} : filter.prod f₁ g₁ ⊓ filter.prod f₂ g₂ = filter.prod (f₁ ⊓ f₂) (g₁ ⊓ g₂) := by simp only [filter.prod, comap_inf, inf_comm, inf_assoc, lattice.inf_left_comm] @[simp] lemma prod_bot {f : filter α} : filter.prod f (⊥ : filter β) = ⊥ := by simp [filter.prod] @[simp] lemma bot_prod {g : filter β} : filter.prod (⊥ : filter α) g = ⊥ := by simp [filter.prod] @[simp] lemma prod_principal_principal {s : set α} {t : set β} : filter.prod (principal s) (principal t) = principal (set.prod s t) := by simp only [filter.prod, comap_principal, principal_eq_iff_eq, comap_principal, inf_principal]; refl @[simp] lemma prod_pure_pure {a : α} {b : β} : filter.prod (pure a) (pure b) = pure (a, b) := by simp lemma prod_eq_bot {f : filter α} {g : filter β} : filter.prod f g = ⊥ ↔ (f = ⊥ ∨ g = ⊥) := begin split, { assume h, rcases mem_prod_iff.1 (empty_in_sets_eq_bot.2 h) with ⟨s, hs, t, ht, hst⟩, rw [subset_empty_iff, set.prod_eq_empty_iff] at hst, cases hst with s_eq t_eq, { left, exact empty_in_sets_eq_bot.1 (s_eq ▸ hs) }, { right, exact empty_in_sets_eq_bot.1 (t_eq ▸ ht) } }, { rintros (rfl | rfl), exact bot_prod, exact prod_bot } end lemma prod_neq_bot {f : filter α} {g : filter β} : filter.prod f g ≠ ⊥ ↔ (f ≠ ⊥ ∧ g ≠ ⊥) := by rw [(≠), prod_eq_bot, not_or_distrib] lemma tendsto_prod_iff {f : α × β → γ} {x : filter α} {y : filter β} {z : filter γ} : filter.tendsto f (filter.prod x y) z ↔ ∀ W ∈ z, ∃ U ∈ x, ∃ V ∈ y, ∀ x y, x ∈ U → y ∈ V → f (x, y) ∈ W := by simp only [tendsto_def, mem_prod_iff, prod_sub_preimage_iff, exists_prop, iff_self] end prod /- at_top and at_bot -/ /-- `at_top` is the filter representing the limit `→ ∞` on an ordered set. It is generated by the collection of up-sets `{b | a ≤ b}`. (The preorder need not have a top element for this to be well defined, and indeed is trivial when a top element exists.) -/ def at_top [preorder α] : filter α := ⨅ a, principal {b | a ≤ b} /-- `at_bot` is the filter representing the limit `→ -∞` on an ordered set. It is generated by the collection of down-sets `{b | b ≤ a}`. (The preorder need not have a bottom element for this to be well defined, and indeed is trivial when a bottom element exists.) -/ def at_bot [preorder α] : filter α := ⨅ a, principal {b | b ≤ a} lemma mem_at_top [preorder α] (a : α) : {b : α | a ≤ b} ∈ @at_top α _ := mem_infi_sets a $ subset.refl _ @[simp] lemma at_top_ne_bot [nonempty α] [semilattice_sup α] : (at_top : filter α) ≠ ⊥ := infi_neq_bot_of_directed (by apply_instance) (assume a b, ⟨a ⊔ b, by simp only [ge, le_principal_iff, forall_const, set_of_subset_set_of, mem_principal_sets, and_self, sup_le_iff, forall_true_iff] {contextual := tt}⟩) (assume a, by simp only [principal_eq_bot_iff, ne.def, principal_eq_bot_iff]; exact ne_empty_of_mem (le_refl a)) @[simp] lemma mem_at_top_sets [nonempty α] [semilattice_sup α] {s : set α} : s ∈ (at_top : filter α) ↔ ∃a:α, ∀b≥a, b ∈ s := let ⟨a⟩ := ‹nonempty α› in iff.intro (assume h, infi_sets_induct h ⟨a, by simp only [forall_const, mem_univ, forall_true_iff]⟩ (assume a s₁ s₂ ha ⟨b, hb⟩, ⟨a ⊔ b, assume c hc, ⟨ha $ le_trans le_sup_left hc, hb _ $ le_trans le_sup_right hc⟩⟩) (assume s₁ s₂ h ⟨a, ha⟩, ⟨a, assume b hb, h $ ha _ hb⟩)) (assume ⟨a, h⟩, mem_infi_sets a $ assume x, h x) lemma map_at_top_eq [nonempty α] [semilattice_sup α] {f : α → β} : at_top.map f = (⨅a, principal $ f '' {a' | a ≤ a'}) := calc map f (⨅a, principal {a' | a ≤ a'}) = (⨅a, map f $ principal {a' | a ≤ a'}) : map_infi_eq (assume a b, ⟨a ⊔ b, by simp only [ge, le_principal_iff, forall_const, set_of_subset_set_of, mem_principal_sets, and_self, sup_le_iff, forall_true_iff] {contextual := tt}⟩) (by apply_instance) ... = (⨅a, principal $ f '' {a' | a ≤ a'}) : by simp only [map_principal, eq_self_iff_true] lemma tendsto_at_top [preorder β] (m : α → β) (f : filter α) : tendsto m f at_top ↔ (∀b, {a | b ≤ m a} ∈ f) := by simp only [at_top, tendsto_infi, tendsto_principal]; refl lemma tendsto_at_top_mono' [preorder β] (l : filter α) ⦃f₁ f₂ : α → β⦄ (h : {x | f₁ x ≤ f₂ x} ∈ l) : tendsto f₁ l at_top → tendsto f₂ l at_top := assume h₁, (tendsto_at_top _ _).2 $ λ b, mp_sets ((tendsto_at_top _ _).1 h₁ b) (monotone_mem_sets (λ a ha ha₁, le_trans ha₁ ha) h) lemma tendsto_at_top_mono [preorder β] (l : filter α) : monotone (λ f : α → β, tendsto f l at_top) := λ f₁ f₂ h, tendsto_at_top_mono' l $ univ_mem_sets' h section ordered_monoid variables [ordered_cancel_comm_monoid β] (l : filter α) {f g : α → β} lemma tendsto_at_top_add_nonneg_left' (hf : {x | 0 ≤ f x} ∈ l) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_mono' l (monotone_mem_sets (λ x, le_add_of_nonneg_left) hf) hg lemma tendsto_at_top_add_nonneg_left (hf : ∀ x, 0 ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_nonneg_left' l (univ_mem_sets' hf) hg lemma tendsto_at_top_add_nonneg_right' (hf : tendsto f l at_top) (hg : {x | 0 ≤ g x} ∈ l) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_mono' l (monotone_mem_sets (λ x, le_add_of_nonneg_right) hg) hf lemma tendsto_at_top_add_nonneg_right (hf : tendsto f l at_top) (hg : ∀ x, 0 ≤ g x) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_nonneg_right' l hf (univ_mem_sets' hg) lemma tendsto_at_top_of_add_const_left (C : β) (hf : tendsto (λ x, C + f x) l at_top) : tendsto f l at_top := (tendsto_at_top _ l).2 $ assume b, monotone_mem_sets (λ x, le_of_add_le_add_left) ((tendsto_at_top _ _).1 hf (C + b)) lemma tendsto_at_top_of_add_const_right (C : β) (hf : tendsto (λ x, f x + C) l at_top) : tendsto f l at_top := (tendsto_at_top _ l).2 $ assume b, monotone_mem_sets (λ x, le_of_add_le_add_right) ((tendsto_at_top _ _).1 hf (b + C)) lemma tendsto_at_top_of_add_bdd_above_left' (C) (hC : {x | f x ≤ C} ∈ l) (h : tendsto (λ x, f x + g x) l at_top) : tendsto g l at_top := tendsto_at_top_of_add_const_left l C (tendsto_at_top_mono' l (monotone_mem_sets (λ x (hx : f x ≤ C), add_le_add_right hx (g x)) hC) h) lemma tendsto_at_top_of_add_bdd_above_left (C) (hC : ∀ x, f x ≤ C) : tendsto (λ x, f x + g x) l at_top → tendsto g l at_top := tendsto_at_top_of_add_bdd_above_left' l C (univ_mem_sets' hC) lemma tendsto_at_top_of_add_bdd_above_right' (C) (hC : {x | g x ≤ C} ∈ l) (h : tendsto (λ x, f x + g x) l at_top) : tendsto f l at_top := tendsto_at_top_of_add_const_right l C (tendsto_at_top_mono' l (monotone_mem_sets (λ x (hx : g x ≤ C), add_le_add_left hx (f x)) hC) h) lemma tendsto_at_top_of_add_bdd_above_right (C) (hC : ∀ x, g x ≤ C) : tendsto (λ x, f x + g x) l at_top → tendsto f l at_top := tendsto_at_top_of_add_bdd_above_right' l C (univ_mem_sets' hC) end ordered_monoid section ordered_group variables [ordered_comm_group β] (l : filter α) {f g : α → β} lemma tendsto_at_top_add_left_of_le' (C : β) (hf : {x | C ≤ f x} ∈ l) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := @tendsto_at_top_of_add_bdd_above_left' _ _ _ l (λ x, -(f x)) (λ x, f x + g x) (-C) (by simp [hf]) (by simp [hg]) lemma tendsto_at_top_add_left_of_le (C : β) (hf : ∀ x, C ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_left_of_le' l C (univ_mem_sets' hf) hg lemma tendsto_at_top_add_right_of_le' (C : β) (hf : tendsto f l at_top) (hg : {x | C ≤ g x} ∈ l) : tendsto (λ x, f x + g x) l at_top := @tendsto_at_top_of_add_bdd_above_right' _ _ _ l (λ x, f x + g x) (λ x, -(g x)) (-C) (by simp [hg]) (by simp [hf]) lemma tendsto_at_top_add_right_of_le (C : β) (hf : tendsto f l at_top) (hg : ∀ x, C ≤ g x) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_right_of_le' l C hf (univ_mem_sets' hg) lemma tendsto_at_top_add_const_left (C : β) (hf : tendsto f l at_top) : tendsto (λ x, C + f x) l at_top := tendsto_at_top_add_left_of_le' l C (univ_mem_sets' $ λ _, le_refl C) hf lemma tendsto_at_top_add_const_right (C : β) (hf : tendsto f l at_top) : tendsto (λ x, f x + C) l at_top := tendsto_at_top_add_right_of_le' l C hf (univ_mem_sets' $ λ _, le_refl C) end ordered_group lemma tendsto_at_top' [nonempty α] [semilattice_sup α] (f : α → β) (l : filter β) : tendsto f at_top l ↔ (∀s ∈ l, ∃a, ∀b≥a, f b ∈ s) := by simp only [tendsto_def, mem_at_top_sets]; refl theorem tendsto_at_top_principal [nonempty β] [semilattice_sup β] {f : β → α} {s : set α} : tendsto f at_top (principal s) ↔ ∃N, ∀n≥N, f n ∈ s := by rw [tendsto_iff_comap, comap_principal, le_principal_iff, mem_at_top_sets]; refl /-- A function `f` grows to infinity independent of an order-preserving embedding `e`. -/ lemma tendsto_at_top_embedding {α β γ : Type*} [preorder β] [preorder γ] {f : α → β} {e : β → γ} {l : filter α} (hm : ∀b₁ b₂, e b₁ ≤ e b₂ ↔ b₁ ≤ b₂) (hu : ∀c, ∃b, c ≤ e b) : tendsto (e ∘ f) l at_top ↔ tendsto f l at_top := begin rw [tendsto_at_top, tendsto_at_top], split, { assume hc b, filter_upwards [hc (e b)] assume a, (hm b (f a)).1 }, { assume hb c, rcases hu c with ⟨b, hc⟩, filter_upwards [hb b] assume a ha, le_trans hc ((hm b (f a)).2 ha) } end lemma tendsto_at_top_at_top [nonempty α] [semilattice_sup α] [preorder β] (f : α → β) : tendsto f at_top at_top ↔ ∀ b : β, ∃ i : α, ∀ a : α, i ≤ a → b ≤ f a := iff.trans tendsto_infi $ forall_congr $ assume b, tendsto_at_top_principal lemma tendsto_at_top_at_bot [nonempty α] [decidable_linear_order α] [preorder β] (f : α → β) : tendsto f at_top at_bot ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), i ≤ a → b ≥ f a := @tendsto_at_top_at_top α (order_dual β) _ _ _ f lemma tendsto_at_top_at_top_of_monotone [nonempty α] [semilattice_sup α] [preorder β] {f : α → β} (hf : monotone f) : tendsto f at_top at_top ↔ ∀ b : β, ∃ a : α, b ≤ f a := (tendsto_at_top_at_top f).trans $ forall_congr $ λ b, exists_congr $ λ a, ⟨λ h, h a (le_refl a), λ h a' ha', le_trans h $ hf ha'⟩ alias tendsto_at_top_at_top_of_monotone ← monotone.tendsto_at_top_at_top lemma tendsto_finset_range : tendsto finset.range at_top at_top := finset.range_mono.tendsto_at_top_at_top.2 finset.exists_nat_subset_range lemma tendsto_finset_image_at_top_at_top {i : β → γ} {j : γ → β} (h : ∀x, j (i x) = x) : tendsto (finset.image j) at_top at_top := have j ∘ i = id, from funext h, (finset.image_mono j).tendsto_at_top_at_top.2 $ assume s, ⟨s.image i, by simp only [finset.image_image, this, finset.image_id, le_refl]⟩ lemma prod_at_top_at_top_eq {β₁ β₂ : Type*} [inhabited β₁] [inhabited β₂] [semilattice_sup β₁] [semilattice_sup β₂] : filter.prod (@at_top β₁ _) (@at_top β₂ _) = @at_top (β₁ × β₂) _ := by simp [at_top, prod_infi_left (default β₁), prod_infi_right (default β₂), infi_prod]; exact infi_comm lemma prod_map_at_top_eq {α₁ α₂ β₁ β₂ : Type*} [inhabited β₁] [inhabited β₂] [semilattice_sup β₁] [semilattice_sup β₂] (u₁ : β₁ → α₁) (u₂ : β₂ → α₂) : filter.prod (map u₁ at_top) (map u₂ at_top) = map (prod.map u₁ u₂) at_top := by rw [prod_map_map_eq, prod_at_top_at_top_eq, prod.map_def] /-- A function `f` maps upwards closed sets (at_top sets) to upwards closed sets when it is a Galois insertion. The Galois "insertion" and "connection" is weakened to only require it to be an insertion and a connetion above `b'`. -/ lemma map_at_top_eq_of_gc [semilattice_sup α] [semilattice_sup β] {f : α → β} (g : β → α) (b' : β)(hf : monotone f) (gc : ∀a, ∀b≥b', f a ≤ b ↔ a ≤ g b) (hgi : ∀b≥b', b ≤ f (g b)) : map f at_top = at_top := begin rw [@map_at_top_eq α _ ⟨g b'⟩], refine le_antisymm (le_infi $ assume b, infi_le_of_le (g (b ⊔ b')) $ principal_mono.2 $ image_subset_iff.2 _) (le_infi $ assume a, infi_le_of_le (f a ⊔ b') $ principal_mono.2 _), { assume a ha, exact (le_trans le_sup_left $ le_trans (hgi _ le_sup_right) $ hf ha) }, { assume b hb, have hb' : b' ≤ b := le_trans le_sup_right hb, exact ⟨g b, (gc _ _ hb').1 (le_trans le_sup_left hb), le_antisymm ((gc _ _ hb').2 (le_refl _)) (hgi _ hb')⟩ } end lemma map_add_at_top_eq_nat (k : ℕ) : map (λa, a + k) at_top = at_top := map_at_top_eq_of_gc (λa, a - k) k (assume a b h, add_le_add_right h k) (assume a b h, (nat.le_sub_right_iff_add_le h).symm) (assume a h, by rw [nat.sub_add_cancel h]) lemma map_sub_at_top_eq_nat (k : ℕ) : map (λa, a - k) at_top = at_top := map_at_top_eq_of_gc (λa, a + k) 0 (assume a b h, nat.sub_le_sub_right h _) (assume a b _, nat.sub_le_right_iff_le_add) (assume b _, by rw [nat.add_sub_cancel]) lemma tendso_add_at_top_nat (k : ℕ) : tendsto (λa, a + k) at_top at_top := le_of_eq (map_add_at_top_eq_nat k) lemma tendso_sub_at_top_nat (k : ℕ) : tendsto (λa, a - k) at_top at_top := le_of_eq (map_sub_at_top_eq_nat k) lemma tendsto_add_at_top_iff_nat {f : ℕ → α} {l : filter α} (k : ℕ) : tendsto (λn, f (n + k)) at_top l ↔ tendsto f at_top l := show tendsto (f ∘ (λn, n + k)) at_top l ↔ tendsto f at_top l, by rw [← tendsto_map'_iff, map_add_at_top_eq_nat] lemma map_div_at_top_eq_nat (k : ℕ) (hk : k > 0) : map (λa, a / k) at_top = at_top := map_at_top_eq_of_gc (λb, b * k + (k - 1)) 1 (assume a b h, nat.div_le_div_right h) (assume a b _, calc a / k ≤ b ↔ a / k < b + 1 : by rw [← nat.succ_eq_add_one, nat.lt_succ_iff] ... ↔ a < (b + 1) * k : nat.div_lt_iff_lt_mul _ _ hk ... ↔ _ : begin cases k, exact (lt_irrefl _ hk).elim, simp [mul_add, add_mul, nat.succ_add, nat.lt_succ_iff] end) (assume b _, calc b = (b * k) / k : by rw [nat.mul_div_cancel b hk] ... ≤ (b * k + (k - 1)) / k : nat.div_le_div_right $ nat.le_add_right _ _) /- ultrafilter -/ section ultrafilter open zorn variables {f g : filter α} /-- An ultrafilter is a minimal (maximal in the set order) proper filter. -/ def is_ultrafilter (f : filter α) := f ≠ ⊥ ∧ ∀g, g ≠ ⊥ → g ≤ f → f ≤ g lemma ultrafilter_unique (hg : is_ultrafilter g) (hf : f ≠ ⊥) (h : f ≤ g) : f = g := le_antisymm h (hg.right _ hf h) lemma le_of_ultrafilter {g : filter α} (hf : is_ultrafilter f) (h : f ⊓ g ≠ ⊥) : f ≤ g := le_of_inf_eq $ ultrafilter_unique hf h inf_le_left /-- Equivalent characterization of ultrafilters: A filter f is an ultrafilter if and only if for each set s, -s belongs to f if and only if s does not belong to f. -/ lemma ultrafilter_iff_compl_mem_iff_not_mem : is_ultrafilter f ↔ (∀ s, -s ∈ f ↔ s ∉ f) := ⟨assume hf s, ⟨assume hns hs, hf.1 $ empty_in_sets_eq_bot.mp $ by convert f.inter_sets hs hns; rw [inter_compl_self], assume hs, have f ≤ principal (-s), from le_of_ultrafilter hf $ assume h, hs $ mem_sets_of_neq_bot $ by simp only [h, eq_self_iff_true, lattice.neg_neg], by simp only [le_principal_iff] at this; assumption⟩, assume hf, ⟨mt empty_in_sets_eq_bot.mpr ((hf ∅).mp (by convert f.univ_sets; rw [compl_empty])), assume g hg g_le s hs, classical.by_contradiction $ mt (hf s).mpr $ assume : - s ∈ f, have s ∩ -s ∈ g, from inter_mem_sets hs (g_le this), by simp only [empty_in_sets_eq_bot, hg, inter_compl_self] at this; contradiction⟩⟩ lemma mem_or_compl_mem_of_ultrafilter (hf : is_ultrafilter f) (s : set α) : s ∈ f ∨ - s ∈ f := classical.or_iff_not_imp_left.2 (ultrafilter_iff_compl_mem_iff_not_mem.mp hf s).mpr lemma mem_or_mem_of_ultrafilter {s t : set α} (hf : is_ultrafilter f) (h : s ∪ t ∈ f) : s ∈ f ∨ t ∈ f := (mem_or_compl_mem_of_ultrafilter hf s).imp_right (assume : -s ∈ f, by filter_upwards [this, h] assume x hnx hx, hx.resolve_left hnx) lemma mem_of_finite_sUnion_ultrafilter {s : set (set α)} (hf : is_ultrafilter f) (hs : finite s) : ⋃₀ s ∈ f → ∃t∈s, t ∈ f := finite.induction_on hs (by simp only [empty_in_sets_eq_bot, hf.left, mem_empty_eq, sUnion_empty, forall_prop_of_false, exists_false, not_false_iff, exists_prop_of_false]) $ λ t s' ht' hs' ih, by simp only [exists_prop, mem_insert_iff, set.sUnion_insert]; exact assume h, (mem_or_mem_of_ultrafilter hf h).elim (assume : t ∈ f, ⟨t, or.inl rfl, this⟩) (assume h, let ⟨t, hts', ht⟩ := ih h in ⟨t, or.inr hts', ht⟩) lemma mem_of_finite_Union_ultrafilter {is : set β} {s : β → set α} (hf : is_ultrafilter f) (his : finite is) (h : (⋃i∈is, s i) ∈ f) : ∃i∈is, s i ∈ f := have his : finite (image s is), from finite_image s his, have h : (⋃₀ image s is) ∈ f, from by simp only [sUnion_image, set.sUnion_image]; assumption, let ⟨t, ⟨i, hi, h_eq⟩, (ht : t ∈ f)⟩ := mem_of_finite_sUnion_ultrafilter hf his h in ⟨i, hi, h_eq.symm ▸ ht⟩ lemma ultrafilter_map {f : filter α} {m : α → β} (h : is_ultrafilter f) : is_ultrafilter (map m f) := by rw ultrafilter_iff_compl_mem_iff_not_mem at ⊢ h; exact assume s, h (m ⁻¹' s) lemma ultrafilter_pure {a : α} : is_ultrafilter (pure a) := begin rw ultrafilter_iff_compl_mem_iff_not_mem, intro s, rw [mem_pure_sets, mem_pure_sets], exact iff.rfl end lemma ultrafilter_bind {f : filter α} (hf : is_ultrafilter f) {m : α → filter β} (hm : ∀ a, is_ultrafilter (m a)) : is_ultrafilter (f.bind m) := begin simp only [ultrafilter_iff_compl_mem_iff_not_mem] at ⊢ hf hm, intro s, dsimp [bind, join, map, preimage], simp only [hm], apply hf end /-- The ultrafilter lemma: Any proper filter is contained in an ultrafilter. -/ lemma exists_ultrafilter (h : f ≠ ⊥) : ∃u, u ≤ f ∧ is_ultrafilter u := let τ := {f' // f' ≠ ⊥ ∧ f' ≤ f}, r : τ → τ → Prop := λt₁ t₂, t₂.val ≤ t₁.val, ⟨a, ha⟩ := inhabited_of_mem_sets h univ_mem_sets, top : τ := ⟨f, h, le_refl f⟩, sup : Π(c:set τ), chain r c → τ := λc hc, ⟨⨅a:{a:τ // a ∈ insert top c}, a.val.val, infi_neq_bot_of_directed ⟨a⟩ (directed_of_chain $ chain_insert hc $ assume ⟨b, _, hb⟩ _ _, or.inl hb) (assume ⟨⟨a, ha, _⟩, _⟩, ha), infi_le_of_le ⟨top, mem_insert _ _⟩ (le_refl _)⟩ in have ∀c (hc: chain r c) a (ha : a ∈ c), r a (sup c hc), from assume c hc a ha, infi_le_of_le ⟨a, mem_insert_of_mem _ ha⟩ (le_refl _), have (∃ (u : τ), ∀ (a : τ), r u a → r a u), from exists_maximal_of_chains_bounded (assume c hc, ⟨sup c hc, this c hc⟩) (assume f₁ f₂ f₃ h₁ h₂, le_trans h₂ h₁), let ⟨uτ, hmin⟩ := this in ⟨uτ.val, uτ.property.right, uτ.property.left, assume g hg₁ hg₂, hmin ⟨g, hg₁, le_trans hg₂ uτ.property.right⟩ hg₂⟩ /-- Construct an ultrafilter extending a given filter. The ultrafilter lemma is the assertion that such a filter exists; we use the axiom of choice to pick one. -/ noncomputable def ultrafilter_of (f : filter α) : filter α := if h : f = ⊥ then ⊥ else classical.epsilon (λu, u ≤ f ∧ is_ultrafilter u) lemma ultrafilter_of_spec (h : f ≠ ⊥) : ultrafilter_of f ≤ f ∧ is_ultrafilter (ultrafilter_of f) := begin have h' := classical.epsilon_spec (exists_ultrafilter h), simp only [ultrafilter_of, dif_neg, h, dif_neg, not_false_iff], simp only at h', assumption end lemma ultrafilter_of_le : ultrafilter_of f ≤ f := if h : f = ⊥ then by simp only [ultrafilter_of, dif_pos, h, dif_pos, eq_self_iff_true, le_bot_iff]; exact le_refl _ else (ultrafilter_of_spec h).left lemma ultrafilter_ultrafilter_of (h : f ≠ ⊥) : is_ultrafilter (ultrafilter_of f) := (ultrafilter_of_spec h).right lemma ultrafilter_of_ultrafilter (h : is_ultrafilter f) : ultrafilter_of f = f := ultrafilter_unique h (ultrafilter_ultrafilter_of h.left).left ultrafilter_of_le /-- A filter equals the intersection of all the ultrafilters which contain it. -/ lemma sup_of_ultrafilters (f : filter α) : f = ⨆ (g) (u : is_ultrafilter g) (H : g ≤ f), g := begin refine le_antisymm _ (supr_le $ λ g, supr_le $ λ u, supr_le $ λ H, H), intros s hs, -- If s ∉ f.sets, we'll apply the ultrafilter lemma to the restriction of f to -s. by_contradiction hs', let j : (-s) → α := subtype.val, have j_inv_s : j ⁻¹' s = ∅, by erw [←preimage_inter_range, subtype.val_range, inter_compl_self, preimage_empty], let f' := comap j f, have : f' ≠ ⊥, { apply mt empty_in_sets_eq_bot.mpr, rintro ⟨t, htf, ht⟩, suffices : t ⊆ s, from absurd (f.sets_of_superset htf this) hs', rw [subset_empty_iff] at ht, have : j '' (j ⁻¹' t) = ∅, by rw [ht, image_empty], erw [image_preimage_eq_inter_range, subtype.val_range, ←subset_compl_iff_disjoint, set.compl_compl] at this, exact this }, rcases exists_ultrafilter this with ⟨g', g'f', u'⟩, simp only [supr_sets_eq, mem_Inter] at hs, have := hs (g'.map subtype.val) (ultrafilter_map u') (map_le_iff_le_comap.mpr g'f'), rw [←le_principal_iff, map_le_iff_le_comap, comap_principal, j_inv_s, principal_empty, le_bot_iff] at this, exact absurd this u'.1 end /-- The `tendsto` relation can be checked on ultrafilters. -/ lemma tendsto_iff_ultrafilter (f : α → β) (l₁ : filter α) (l₂ : filter β) : tendsto f l₁ l₂ ↔ ∀ g, is_ultrafilter g → g ≤ l₁ → g.map f ≤ l₂ := ⟨assume h g u gx, le_trans (map_mono gx) h, assume h, by rw [sup_of_ultrafilters l₁]; simpa only [tendsto, map_supr, supr_le_iff]⟩ /- The ultrafilter monad. The monad structure on ultrafilters is the restriction of the one on filters. -/ def ultrafilter (α : Type u) : Type u := {f : filter α // is_ultrafilter f} def ultrafilter.map (m : α → β) (u : ultrafilter α) : ultrafilter β := ⟨u.val.map m, ultrafilter_map u.property⟩ def ultrafilter.pure (x : α) : ultrafilter α := ⟨pure x, ultrafilter_pure⟩ def ultrafilter.bind (u : ultrafilter α) (m : α → ultrafilter β) : ultrafilter β := ⟨u.val.bind (λ a, (m a).val), ultrafilter_bind u.property (λ a, (m a).property)⟩ instance ultrafilter.has_pure : has_pure ultrafilter := ⟨@ultrafilter.pure⟩ instance ultrafilter.has_bind : has_bind ultrafilter := ⟨@ultrafilter.bind⟩ instance ultrafilter.functor : functor ultrafilter := { map := @ultrafilter.map } instance ultrafilter.monad : monad ultrafilter := { map := @ultrafilter.map } noncomputable def hyperfilter : filter α := ultrafilter_of cofinite lemma hyperfilter_le_cofinite (hi : set.infinite (@set.univ α)) : @hyperfilter α ≤ cofinite := (ultrafilter_of_spec (cofinite_ne_bot hi)).1 lemma is_ultrafilter_hyperfilter (hi : set.infinite (@set.univ α)) : is_ultrafilter (@hyperfilter α) := (ultrafilter_of_spec (cofinite_ne_bot hi)).2 theorem nmem_hyperfilter_of_finite (hi : set.infinite (@set.univ α)) {s : set α} (hf : set.finite s) : s ∉ @hyperfilter α := λ hy, have hx : -s ∉ hyperfilter := λ hs, (ultrafilter_iff_compl_mem_iff_not_mem.mp (is_ultrafilter_hyperfilter hi) s).mp hs hy, have ht : -s ∈ cofinite.sets := by show -s ∈ {s | _}; rwa [set.mem_set_of_eq, lattice.neg_neg], hx $ hyperfilter_le_cofinite hi ht theorem compl_mem_hyperfilter_of_finite (hi : set.infinite (@set.univ α)) {s : set α} (hf : set.finite s) : -s ∈ @hyperfilter α := (ultrafilter_iff_compl_mem_iff_not_mem.mp (is_ultrafilter_hyperfilter hi) s).mpr $ nmem_hyperfilter_of_finite hi hf theorem mem_hyperfilter_of_finite_compl (hi : set.infinite (@set.univ α)) {s : set α} (hf : set.finite (-s)) : s ∈ @hyperfilter α := have h : _ := compl_mem_hyperfilter_of_finite hi hf, by rwa [lattice.neg_neg] at h section local attribute [instance] filter.monad filter.is_lawful_monad instance ultrafilter.is_lawful_monad : is_lawful_monad ultrafilter := { id_map := assume α f, subtype.eq (id_map f.val), pure_bind := assume α β a f, subtype.eq (pure_bind a (subtype.val ∘ f)), bind_assoc := assume α β γ f m₁ m₂, subtype.eq (filter_eq rfl), bind_pure_comp_eq_map := assume α β f x, subtype.eq (bind_pure_comp_eq_map _ f x.val) } end lemma ultrafilter.eq_iff_val_le_val {u v : ultrafilter α} : u = v ↔ u.val ≤ v.val := ⟨assume h, by rw h; exact le_refl _, assume h, by rw subtype.ext; apply ultrafilter_unique v.property u.property.1 h⟩ lemma exists_ultrafilter_iff (f : filter α) : (∃ (u : ultrafilter α), u.val ≤ f) ↔ f ≠ ⊥ := ⟨assume ⟨u, uf⟩, lattice.neq_bot_of_le_neq_bot u.property.1 uf, assume h, let ⟨u, uf, hu⟩ := exists_ultrafilter h in ⟨⟨u, hu⟩, uf⟩⟩ end ultrafilter end filter namespace filter variables {α β γ : Type u} {f : β → filter α} {s : γ → set α} open list lemma mem_traverse_sets : ∀(fs : list β) (us : list γ), forall₂ (λb c, s c ∈ f b) fs us → traverse s us ∈ traverse f fs | [] [] forall₂.nil := mem_pure_sets.2 $ mem_singleton _ | (f::fs) (u::us) (forall₂.cons h hs) := seq_mem_seq_sets (image_mem_map h) (mem_traverse_sets fs us hs) lemma mem_traverse_sets_iff (fs : list β) (t : set (list α)) : t ∈ traverse f fs ↔ (∃us:list (set α), forall₂ (λb (s : set α), s ∈ f b) fs us ∧ sequence us ⊆ t) := begin split, { induction fs generalizing t, case nil { simp only [sequence, pure_def, imp_self, forall₂_nil_left_iff, pure_def, exists_eq_left, mem_principal_sets, set.pure_def, singleton_subset_iff, traverse_nil] }, case cons : b fs ih t { assume ht, rcases mem_seq_sets_iff.1 ht with ⟨u, hu, v, hv, ht⟩, rcases mem_map_sets_iff.1 hu with ⟨w, hw, hwu⟩, rcases ih v hv with ⟨us, hus, hu⟩, exact ⟨w :: us, forall₂.cons hw hus, subset.trans (set.seq_mono hwu hu) ht⟩ } }, { rintros ⟨us, hus, hs⟩, exact mem_sets_of_superset (mem_traverse_sets _ _ hus) hs } end lemma sequence_mono : ∀(as bs : list (filter α)), forall₂ (≤) as bs → sequence as ≤ sequence bs | [] [] forall₂.nil := le_refl _ | (a::as) (b::bs) (forall₂.cons h hs) := seq_mono (map_mono h) (sequence_mono as bs hs) end filter
4c3832189e12b6570146f3ae5103523d361938dc
ea5678cc400c34ff95b661fa26d15024e27ea8cd
/HoTT-play-area.lean
93c5c72c78073e77ff3f7a85dca9dc32f0b14a7e
[]
no_license
ChrisHughes24/leanstuff
dca0b5349c3ed893e8792ffbd98cbcadaff20411
9efa85f72efaccd1d540385952a6acc18fce8687
refs/heads/master
1,654,883,241,759
1,652,873,885,000
1,652,873,885,000
134,599,537
1
0
null
null
null
null
UTF-8
Lean
false
false
1,433
lean
import hott.init hott.types.sigma hott.types.nat set_option pp.notation false #print hott.univalence namespace hott local infix ` = `:50 := hott.eq @[hott] lemma X : bool = bool := eq.refl _ @[hott] def Y (a b : unit) : ∀ (x y : a = b), x = y := punit.rec_on a (λ x, @eq.rec_on _ _ (λ b h, ∀ y, eq h y) _ _ $ λ y, @eq.rec_on unit () (λ a, punit.rec_on a (eq (eq.refl ()))) () y (eq.refl _)) #print nat.no_confusion @[hott] lemma eq.symm {α : Sort*} {x y : α} (h : x = y) : y = x := eq.rec_on h rfl @[hott] example (a b : ℕ) : ∀ (x y : a = b), x = y := begin assume x, hinduction x, assume y, hinduction a, exact @eq.rec_on ℕ 0 begin end _ _ _ _, end @[hott] def bool_not : equiv bool bool := equiv.mk bnot $ is_equiv.mk _ bnot (λ b, bool.rec_on b rfl rfl) (λ b, bool.rec_on b rfl rfl) (λ b, bool.rec_on b rfl rfl) axiom choice : Π {α : Sort*}, trunc 0 α → α noncomputable example : empty := let b := choice (trunc.tr tt) in let e : bool = bool := ua bool_not in let b' : bool := eq.cast e b in have hb' : b' = choice (trunc.tr ff), from sorry, have h : b' = bnot b, from cast_ua bool_not b, have h' : b' = b, from @eq.rec_on _ (choice (trunc.tr ff)) (λ c _, b' = c) _ (@eq.rec_on _ (choice (trunc.tr tt)) (λ c _, c = b) _ (@eq.rec_on _ (trunc.tr ff) (λ c _, choice c = choice (trunc.tr ff)) _ sorry rfl) rfl) hb', end hott
81d4d8c034e73ae1cc31a02c1b0e8cbfaadc7633
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/measure_theory/function/lp_order.lean
8f027a5b464039092d2ee146d67662847b8dd779
[ "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
1,979
lean
/- Copyright (c) 2021 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne -/ import measure_theory.function.lp_space import analysis.normed_space.lattice_ordered_group /-! # Order related properties of Lp spaces ### Results - `Lp E p μ` is an `ordered_add_comm_group` when `E` is a `normed_lattice_add_comm_group`. ### TODO - move definitions of `Lp.pos_part` and `Lp.neg_part` to this file, and define them as `has_pos_part.pos` and `has_pos_part.neg` given by the lattice structure. - show that if `E` is a `normed_lattice_add_comm_group` then so is `Lp E p μ` for `1 ≤ p`. In particular, this shows `order_closed_topology` for `Lp`. -/ open topological_space measure_theory lattice_ordered_comm_group open_locale ennreal variables {α E : Type*} {m : measurable_space α} {μ : measure α} {p : ℝ≥0∞} namespace measure_theory namespace Lp section order variables [normed_lattice_add_comm_group E] [measurable_space E] [borel_space E] [second_countable_topology E] lemma coe_fn_le (f g : Lp E p μ) : f ≤ᵐ[μ] g ↔ f ≤ g := by rw [← subtype.coe_le_coe, ← ae_eq_fun.coe_fn_le, ← coe_fn_coe_base, ← coe_fn_coe_base] lemma coe_fn_nonneg (f : Lp E p μ) : 0 ≤ᵐ[μ] f ↔ 0 ≤ f := begin rw ← coe_fn_le, have h0 := Lp.coe_fn_zero E p μ, split; intro h; filter_upwards [h, h0] with _ _ h2, { rwa h2, }, { rwa ← h2, }, end instance : covariant_class (Lp E p μ) (Lp E p μ) (+) (≤) := begin refine ⟨λ f g₁ g₂ hg₁₂, _⟩, rw ← coe_fn_le at hg₁₂ ⊢, filter_upwards [coe_fn_add f g₁, coe_fn_add f g₂, hg₁₂] with _ h1 h2 h3, rw [h1, h2, pi.add_apply, pi.add_apply], exact add_le_add le_rfl h3, end instance : ordered_add_comm_group (Lp E p μ) := { add_le_add_left := λ f g hfg f', add_le_add_left hfg f', ..subtype.partial_order _, ..add_subgroup.to_add_comm_group _} end order end Lp end measure_theory
e10f8122341e97b73ed73bd216af50d7b307ef3a
7cef822f3b952965621309e88eadf618da0c8ae9
/src/tactic/algebra.lean
6c9c057ae8f415bffe1347cbb9f9bce954d1cb55
[ "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
2,313
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import tactic.core open lean.parser namespace tactic @[user_attribute] meta def ancestor_attr : user_attribute unit (list name) := { name := `ancestor, descr := "ancestor of old structures", parser := many ident } meta def get_ancestors (cl : name) : tactic (list name) := (++) <$> (prod.fst <$> subobject_names cl <|> pure []) <*> (user_attribute.get_param ancestor_attr cl <|> pure []) meta def find_ancestors : name → expr → tactic (list expr) | cl arg := do cs ← get_ancestors cl, r ← cs.mmap $ λ c, list.ret <$> (mk_app c [arg] >>= mk_instance) <|> find_ancestors c arg, return r.join end tactic attribute [ancestor has_mul] semigroup attribute [ancestor semigroup] comm_semigroup attribute [ancestor semigroup has_one] monoid attribute [ancestor monoid comm_semigroup] comm_monoid attribute [ancestor monoid has_inv] group attribute [ancestor group comm_monoid] comm_group attribute [ancestor has_add] add_semigroup attribute [ancestor add_semigroup] add_comm_semigroup attribute [ancestor add_semigroup has_zero] add_monoid attribute [ancestor add_monoid add_comm_semigroup] add_comm_monoid attribute [ancestor add_monoid has_neg] add_group attribute [ancestor add_group add_comm_monoid] add_comm_group attribute [ancestor semigroup] left_cancel_semigroup attribute [ancestor semigroup] right_cancel_semigroup attribute [ancestor add_semigroup] add_left_cancel_semigroup attribute [ancestor add_semigroup] add_right_cancel_semigroup attribute [ancestor ring has_inv zero_ne_one_class] division_ring attribute [ancestor division_ring comm_ring] field attribute [ancestor field] discrete_field attribute [ancestor has_mul has_add] distrib attribute [ancestor has_mul has_zero] mul_zero_class attribute [ancestor has_zero has_one] zero_ne_one_class attribute [ancestor add_comm_monoid monoid distrib mul_zero_class] semiring attribute [ancestor semiring comm_monoid] comm_semiring attribute [ancestor add_comm_group monoid distrib] ring attribute [ancestor ring comm_semigroup] comm_ring attribute [ancestor has_mul has_zero] no_zero_divisors attribute [ancestor comm_ring no_zero_divisors zero_ne_one_class] integral_domain
f240f20804f1cc931cc5e0790866cbcb8cdf0fde
26ac254ecb57ffcb886ff709cf018390161a9225
/src/linear_algebra/dimension.lean
58d12231e714044dd4763d16cdb599952c057046
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
18,353
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro, Johannes Hölzl, Sander Dahmen -/ import linear_algebra.basis import set_theory.ordinal /-! # Dimension of modules and vector spaces ## Main definitions * The dimension of a vector space is defined as `vector_space.dim : cardinal`. ## Main statements * `mk_eq_mk_of_basis`: the dimension theorem, any two bases of the same vector space have the same cardinality. * `dim_quotient_add_dim`: if V' is a submodule of V, then dim (V/V') + dim V' = dim V. * `dim_range_add_dim_ker`: the rank-nullity theorem. -/ noncomputable theory universes u u' u'' v' w w' variables {K : Type u} {V V₂ V₃ V₄ : Type u'} variables {ι : Type w} {ι' : Type w'} {η : Type u''} {φ : η → Type*} -- TODO: relax these universe constraints open_locale classical big_operators section vector_space variables [field K] [add_comm_group V] [vector_space K V] include K open submodule function set variables (K V) /-- the dimension of a vector space, defined as a term of type `cardinal` -/ def vector_space.dim : cardinal := cardinal.min (nonempty_subtype.2 (@exists_is_basis K V _ _ _)) (λ b, cardinal.mk b.1) variables {K V} open vector_space section theorem is_basis.le_span {v : ι → V} {J : set V} (hv : is_basis K v) (hJ : span K J = ⊤) : cardinal.mk (range v) ≤ cardinal.mk J := begin cases le_or_lt cardinal.omega (cardinal.mk J) with oJ oJ, { have := cardinal.mk_range_eq_of_injective (linear_independent.injective zero_ne_one hv.1), let S : J → set ι := λ j, ↑(is_basis.repr hv j).support, let S' : J → set V := λ j, v '' S j, have hs : range v ⊆ ⋃ j, S' j, { intros b hb, rcases mem_range.1 hb with ⟨i, hi⟩, have : span K J ≤ comap hv.repr (finsupp.supported K K (⋃ j, S j)) := span_le.2 (λ j hj x hx, ⟨_, ⟨⟨j, hj⟩, rfl⟩, hx⟩), rw hJ at this, replace : hv.repr (v i) ∈ (finsupp.supported K K (⋃ j, S j)) := this trivial, rw [hv.repr_eq_single, finsupp.mem_supported, finsupp.support_single_ne_zero one_ne_zero] at this, { subst b, rcases mem_Union.1 (this (finset.mem_singleton_self _)) with ⟨j, hj⟩, exact mem_Union.2 ⟨j, (mem_image _ _ _).2 ⟨i, hj, rfl⟩⟩ }, { apply_instance } }, refine le_of_not_lt (λ IJ, _), suffices : cardinal.mk (⋃ j, S' j) < cardinal.mk (range v), { exact not_le_of_lt this ⟨set.embedding_of_subset _ _ hs⟩ }, refine lt_of_le_of_lt (le_trans cardinal.mk_Union_le_sum_mk (cardinal.sum_le_sum _ (λ _, cardinal.omega) _)) _, { exact λ j, le_of_lt (cardinal.lt_omega_iff_finite.2 $ (finset.finite_to_set _).image _) }, { rwa [cardinal.sum_const, cardinal.mul_eq_max oJ (le_refl _), max_eq_left oJ] } }, { rcases exists_finite_card_le_of_finite_of_linear_independent_of_span (cardinal.lt_omega_iff_finite.1 oJ) hv.1.to_subtype_range _ with ⟨fI, hi⟩, { rwa [← cardinal.nat_cast_le, cardinal.finset_card, set.finite.coe_to_finset, cardinal.finset_card, set.finite.coe_to_finset] at hi, }, { rw hJ, apply set.subset_univ } }, end end /-- dimension theorem -/ theorem mk_eq_mk_of_basis {v : ι → V} {v' : ι' → V} (hv : is_basis K v) (hv' : is_basis K v') : cardinal.lift.{w w'} (cardinal.mk ι) = cardinal.lift.{w' w} (cardinal.mk ι') := begin rw ←cardinal.lift_inj.{(max w w') u'}, rw [cardinal.lift_lift, cardinal.lift_lift], apply le_antisymm, { convert cardinal.lift_le.{u' (max w w')}.2 (hv.le_span hv'.2), { rw cardinal.lift_max.{w u' w'}, apply (cardinal.mk_range_eq_of_injective (hv.injective zero_ne_one)).symm, }, { rw cardinal.lift_max.{w' u' w}, apply (cardinal.mk_range_eq_of_injective (hv'.injective zero_ne_one)).symm, }, }, { convert cardinal.lift_le.{u' (max w w')}.2 (hv'.le_span hv.2), { rw cardinal.lift_max.{w' u' w}, apply (cardinal.mk_range_eq_of_injective (hv'.injective zero_ne_one)).symm, }, { rw cardinal.lift_max.{w u' w'}, apply (cardinal.mk_range_eq_of_injective (hv.injective zero_ne_one)).symm, }, } end theorem is_basis.mk_range_eq_dim {v : ι → V} (h : is_basis K v) : cardinal.mk (range v) = dim K V := begin have := show ∃ v', dim K V = _, from cardinal.min_eq _ _, rcases this with ⟨v', e⟩, rw e, apply cardinal.lift_inj.1, rw cardinal.mk_range_eq_of_injective (h.injective zero_ne_one), convert @mk_eq_mk_of_basis _ _ _ _ _ _ _ _ _ h v'.property end theorem is_basis.mk_eq_dim {v : ι → V} (h : is_basis K v) : cardinal.lift.{w u'} (cardinal.mk ι) = cardinal.lift.{u' w} (dim K V) := by rw [←h.mk_range_eq_dim, cardinal.mk_range_eq_of_injective (h.injective zero_ne_one)] variables [add_comm_group V₂] [vector_space K V₂] /-- Two linearly equivalent vector spaces have the same dimension. -/ theorem linear_equiv.dim_eq (f : V ≃ₗ[K] V₂) : dim K V = dim K V₂ := by letI := classical.dec_eq V; letI := classical.dec_eq V₂; exact let ⟨b, hb⟩ := exists_is_basis K V in cardinal.lift_inj.1 $ hb.mk_eq_dim.symm.trans (f.is_basis hb).mk_eq_dim @[simp] lemma dim_bot : dim K (⊥ : submodule K V) = 0 := by letI := classical.dec_eq V; rw [← cardinal.lift_inj, ← (@is_basis_empty_bot pempty K V _ _ _ not_nonempty_pempty).mk_eq_dim, cardinal.mk_pempty] @[simp] lemma dim_top : dim K (⊤ : submodule K V) = dim K V := linear_equiv.dim_eq (linear_equiv.of_top _ rfl) lemma dim_of_field (K : Type*) [field K] : dim K K = 1 := by rw [←cardinal.lift_inj, ← (@is_basis_singleton_one punit K _ _).mk_eq_dim, cardinal.mk_punit] lemma dim_span {v : ι → V} (hv : linear_independent K v) : dim K ↥(span K (range v)) = cardinal.mk (range v) := by rw [←cardinal.lift_inj, ← (is_basis_span hv).mk_eq_dim, cardinal.mk_range_eq_of_injective (@linear_independent.injective ι K V v _ _ _ zero_ne_one hv)] lemma dim_span_set {s : set V} (hs : linear_independent K (λ x, x : s → V)) : dim K ↥(span K s) = cardinal.mk s := by { rw [← @set_of_mem_eq _ s, ← subtype.range_coe_subtype], exact dim_span hs } lemma cardinal_le_dim_of_linear_independent {ι : Type u'} {v : ι → V} (hv : linear_independent K v) : (cardinal.mk ι) ≤ (dim.{u u'} K V) := begin obtain ⟨ι', v', is⟩ := exists_sum_is_basis hv, simpa using le_trans (cardinal.lift_mk_le.{u' u' u'}.2 ⟨@function.embedding.inl ι ι'⟩) (le_of_eq is.mk_eq_dim), end lemma cardinal_le_dim_of_linear_independent' {s : set V} (hs : linear_independent K (λ x, x : s → V)) : cardinal.mk s ≤ dim K V := begin -- extend s to a basis obtain ⟨b, ss, h⟩ := exists_subset_is_basis hs, rw [←h.mk_range_eq_dim, subtype.range_coe], apply cardinal.mk_le_of_injective (inclusion_injective ss), end lemma dim_span_le (s : set V) : dim K (span K s) ≤ cardinal.mk s := begin classical, rcases exists_linear_independent (linear_independent_empty K V) (set.empty_subset s) with ⟨b, hb, _, hsb, hlib⟩, have hsab : span K s = span K b, from span_eq_of_le _ hsb (span_le.2 (λ x hx, subset_span (hb hx))), convert cardinal.mk_le_mk_of_subset hb, rw [hsab, dim_span_set hlib] end lemma dim_span_of_finset (s : finset V) : dim K (span K (↑s : set V)) < cardinal.omega := calc dim K (span K (↑s : set V)) ≤ cardinal.mk (↑s : set V) : dim_span_le ↑s ... = s.card : by rw ←cardinal.finset_card ... < cardinal.omega : cardinal.nat_lt_omega _ theorem dim_prod : dim K (V × V₂) = dim K V + dim K V₂ := begin letI := classical.dec_eq V, letI := classical.dec_eq V₂, rcases exists_is_basis K V with ⟨b, hb⟩, rcases exists_is_basis K V₂ with ⟨c, hc⟩, rw [← cardinal.lift_inj, ← @is_basis.mk_eq_dim K (V × V₂) _ _ _ _ _ (is_basis_inl_union_inr hb hc), cardinal.lift_add, cardinal.lift_mk, ← hb.mk_eq_dim, ← hc.mk_eq_dim, cardinal.lift_mk, cardinal.lift_mk, cardinal.add_def (ulift b) (ulift c)], exact cardinal.lift_inj.1 (cardinal.lift_mk_eq.2 ⟨equiv.ulift.trans (equiv.sum_congr (@equiv.ulift b) (@equiv.ulift c)).symm ⟩), end theorem dim_quotient_add_dim (p : submodule K V) : dim K p.quotient + dim K p = dim K V := by classical; exact let ⟨f⟩ := quotient_prod_linear_equiv p in dim_prod.symm.trans f.dim_eq theorem dim_quotient_le (p : submodule K V) : dim K p.quotient ≤ dim K V := by { rw ← dim_quotient_add_dim p, exact cardinal.le_add_right _ _ } /-- rank-nullity theorem -/ theorem dim_range_add_dim_ker (f : V →ₗ[K] V₂) : dim K f.range + dim K f.ker = dim K V := begin haveI := λ (p : submodule K V), classical.dec_eq p.quotient, rw [← f.quot_ker_equiv_range.dim_eq, dim_quotient_add_dim] end lemma dim_range_le (f : V →ₗ[K] V₂) : dim K f.range ≤ dim K V := by rw ← dim_range_add_dim_ker f; exact le_add_right (le_refl _) lemma dim_map_le (f : V →ₗ V₂) (p : submodule K V) : dim K (p.map f) ≤ dim K p := begin have h := dim_range_le (f.comp (submodule.subtype p)), rwa [linear_map.range_comp, range_subtype] at h, end lemma dim_range_of_surjective (f : V →ₗ[K] V₂) (h : surjective f) : dim K f.range = dim K V₂ := begin refine linear_equiv.dim_eq (linear_equiv.of_bijective (submodule.subtype _) _ _), exact linear_map.ker_eq_bot.2 subtype.val_injective, rwa [range_subtype, linear_map.range_eq_top] end lemma dim_eq_of_surjective (f : V →ₗ[K] V₂) (h : surjective f) : dim K V = dim K V₂ + dim K f.ker := by rw [← dim_range_add_dim_ker f, ← dim_range_of_surjective f h] lemma dim_le_of_surjective (f : V →ₗ[K] V₂) (h : surjective f) : dim K V₂ ≤ dim K V := by rw [dim_eq_of_surjective f h]; refine le_add_right (le_refl _) lemma dim_eq_of_injective (f : V →ₗ[K] V₂) (h : injective f) : dim K V = dim K f.range := by rw [← dim_range_add_dim_ker f, linear_map.ker_eq_bot.2 h]; simp [dim_bot] lemma dim_submodule_le (s : submodule K V) : dim K s ≤ dim K V := by { rw ← dim_quotient_add_dim s, exact cardinal.le_add_left _ _ } lemma dim_le_of_injective (f : V →ₗ[K] V₂) (h : injective f) : dim K V ≤ dim K V₂ := by { rw [dim_eq_of_injective f h], exact dim_submodule_le _ } lemma dim_le_of_submodule (s t : submodule K V) (h : s ≤ t) : dim K s ≤ dim K t := dim_le_of_injective (of_le h) $ assume ⟨x, hx⟩ ⟨y, hy⟩ eq, subtype.eq $ show x = y, from subtype.ext_iff_val.1 eq section variables [add_comm_group V₃] [vector_space K V₃] variables [add_comm_group V₄] [vector_space K V₄] open linear_map /-- This is mostly an auxiliary lemma for `dim_sup_add_dim_inf_eq`. -/ lemma dim_add_dim_split (db : V₃ →ₗ[K] V) (eb : V₄ →ₗ[K] V) (cd : V₂ →ₗ[K] V₃) (ce : V₂ →ₗ[K] V₄) (hde : ⊤ ≤ db.range ⊔ eb.range) (hgd : ker cd = ⊥) (eq : db.comp cd = eb.comp ce) (eq₂ : ∀d e, db d = eb e → (∃c, cd c = d ∧ ce c = e)) : dim K V + dim K V₂ = dim K V₃ + dim K V₄ := have hf : surjective (coprod db eb), begin refine (range_eq_top.1 $ top_unique $ _), rwa [← map_top, ← prod_top, map_coprod_prod] end, begin conv {to_rhs, rw [← dim_prod, dim_eq_of_surjective _ hf] }, congr' 1, apply linear_equiv.dim_eq, refine linear_equiv.of_bijective _ _ _, { refine cod_restrict _ (prod cd (- ce)) _, { assume c, simp only [add_eq_zero_iff_eq_neg, prod_apply, mem_ker, coprod_apply, neg_neg, map_neg, neg_apply], exact linear_map.ext_iff.1 eq c } }, { rw [ker_cod_restrict, ker_prod, hgd, bot_inf_eq] }, { rw [eq_top_iff, range_cod_restrict, ← map_le_iff_le_comap, map_top, range_subtype], rintros ⟨d, e⟩, have h := eq₂ d (-e), simp only [add_eq_zero_iff_eq_neg, prod_apply, mem_ker, mem_coe, prod.mk.inj_iff, coprod_apply, map_neg, neg_apply, linear_map.mem_range] at ⊢ h, assume hde, rcases h hde with ⟨c, h₁, h₂⟩, refine ⟨c, h₁, _⟩, rw [h₂, _root_.neg_neg] } end lemma dim_sup_add_dim_inf_eq (s t : submodule K V) : dim K (s ⊔ t : submodule K V) + dim K (s ⊓ t : submodule K V) = dim K s + dim K t := dim_add_dim_split (of_le le_sup_left) (of_le le_sup_right) (of_le inf_le_left) (of_le inf_le_right) begin rw [← map_le_map_iff' (ker_subtype $ s ⊔ t), map_sup, map_top, ← linear_map.range_comp, ← linear_map.range_comp, subtype_comp_of_le, subtype_comp_of_le, range_subtype, range_subtype, range_subtype], exact le_refl _ end (ker_of_le _ _ _) begin ext ⟨x, hx⟩, refl end begin rintros ⟨b₁, hb₁⟩ ⟨b₂, hb₂⟩ eq, have : b₁ = b₂ := congr_arg subtype.val eq, subst this, exact ⟨⟨b₁, hb₁, hb₂⟩, rfl, rfl⟩ end lemma dim_add_le_dim_add_dim (s t : submodule K V) : dim K (s ⊔ t : submodule K V) ≤ dim K s + dim K t := by rw [← dim_sup_add_dim_inf_eq]; exact le_add_right (le_refl _) end section fintype variable [fintype η] variables [∀i, add_comm_group (φ i)] [∀i, vector_space K (φ i)] open linear_map lemma dim_pi : vector_space.dim K (Πi, φ i) = cardinal.sum (λi, vector_space.dim K (φ i)) := begin choose b hb using assume i, exists_is_basis K (φ i), have : is_basis K (λ (ji : Σ j, b j), std_basis K (λ j, φ j) ji.fst ji.snd.val), by apply pi.is_basis_std_basis _ hb, rw [←cardinal.lift_inj, ← this.mk_eq_dim], simp [λ i, (hb i).mk_range_eq_dim.symm, cardinal.sum_mk] end lemma dim_fun {V η : Type u} [fintype η] [add_comm_group V] [vector_space K V] : vector_space.dim K (η → V) = fintype.card η * vector_space.dim K V := by rw [dim_pi, cardinal.sum_const, cardinal.fintype_card] lemma dim_fun_eq_lift_mul : vector_space.dim K (η → V) = (fintype.card η : cardinal.{max u'' u'}) * cardinal.lift.{u' u''} (vector_space.dim K V) := by rw [dim_pi, cardinal.sum_const_eq_lift_mul, cardinal.fintype_card, cardinal.lift_nat_cast] lemma dim_fun' : vector_space.dim K (η → K) = fintype.card η := by rw [dim_fun_eq_lift_mul, dim_of_field K, cardinal.lift_one, mul_one, cardinal.nat_cast_inj] lemma dim_fin_fun (n : ℕ) : dim K (fin n → K) = n := by simp [dim_fun'] end fintype lemma exists_mem_ne_zero_of_ne_bot {s : submodule K V} (h : s ≠ ⊥) : ∃ b : V, b ∈ s ∧ b ≠ 0 := begin classical, by_contradiction hex, have : ∀x∈s, (x:V) = 0, { simpa only [not_exists, not_and, not_not, ne.def] using hex }, exact (h $ bot_unique $ assume s hs, (submodule.mem_bot K).2 $ this s hs) end lemma exists_mem_ne_zero_of_dim_pos {s : submodule K V} (h : 0 < vector_space.dim K s) : ∃ b : V, b ∈ s ∧ b ≠ 0 := exists_mem_ne_zero_of_ne_bot $ assume eq, by rw [eq, dim_bot] at h; exact lt_irrefl _ h lemma exists_is_basis_fintype (h : dim K V < cardinal.omega) : ∃ s : (set V), (is_basis K (subtype.val : s → V)) ∧ nonempty (fintype s) := begin cases exists_is_basis K V with s hs, rw [←cardinal.lift_lt, ← is_basis.mk_eq_dim hs, cardinal.lift_lt, cardinal.lt_omega_iff_fintype] at h, exact ⟨s, hs, h⟩ end section rank /-- `rank f` is the rank of a `linear_map f`, defined as the dimension of `f.range`. -/ def rank (f : V →ₗ[K] V₂) : cardinal := dim K f.range lemma rank_le_domain (f : V →ₗ[K] V₂) : rank f ≤ dim K V := by rw [← dim_range_add_dim_ker f]; exact le_add_right (le_refl _) lemma rank_le_range (f : V →ₗ[K] V₂) : rank f ≤ dim K V₂ := dim_submodule_le _ lemma rank_add_le (f g : V →ₗ[K] V₂) : rank (f + g) ≤ rank f + rank g := calc rank (f + g) ≤ dim K (f.range ⊔ g.range : submodule K V₂) : begin refine dim_le_of_submodule _ _ _, exact (linear_map.range_le_iff_comap.2 $ eq_top_iff'.2 $ assume x, show f x + g x ∈ (f.range ⊔ g.range : submodule K V₂), from mem_sup.2 ⟨_, mem_image_of_mem _ (mem_univ _), _, mem_image_of_mem _ (mem_univ _), rfl⟩) end ... ≤ rank f + rank g : dim_add_le_dim_add_dim _ _ @[simp] lemma rank_zero : rank (0 : V →ₗ[K] V₂) = 0 := by rw [rank, linear_map.range_zero, dim_bot] lemma rank_finset_sum_le {η} (s : finset η) (f : η → V →ₗ[K] V₂) : rank (∑ d in s, f d) ≤ ∑ d in s, rank (f d) := @finset.sum_hom_rel _ _ _ _ _ (λa b, rank a ≤ b) f (λ d, rank (f d)) s (le_of_eq rank_zero) (λ i g c h, le_trans (rank_add_le _ _) (add_le_add_left h _)) variables [add_comm_group V₃] [vector_space K V₃] lemma rank_comp_le1 (g : V →ₗ[K] V₂) (f : V₂ →ₗ[K] V₃) : rank (f.comp g) ≤ rank f := begin refine dim_le_of_submodule _ _ _, rw [linear_map.range_comp], exact image_subset _ (subset_univ _) end lemma rank_comp_le2 (g : V →ₗ[K] V₂) (f : V₂ →ₗ V₃) : rank (f.comp g) ≤ rank g := by rw [rank, rank, linear_map.range_comp]; exact dim_map_le _ _ end rank lemma dim_zero_iff_forall_zero : vector_space.dim K V = 0 ↔ ∀ x : V, x = 0 := begin split, { intros h x, cases exists_is_basis K V with w hw, have card_mk_range := hw.mk_range_eq_dim, rw [h, cardinal.mk_emptyc_iff, subtype.range_coe] at card_mk_range, simpa [card_mk_range] using hw.mem_span x }, { intro h, have : (⊤ : submodule K V) = ⊥, { ext x, simp [h x] }, rw [←dim_top, this, dim_bot] } end lemma dim_pos_iff_exists_ne_zero : 0 < vector_space.dim K V ↔ ∃ x : V, x ≠ 0 := begin rw ←not_iff_not, simpa using dim_zero_iff_forall_zero end lemma dim_pos_iff_nontrivial : 0 < vector_space.dim K V ↔ nontrivial V := begin rw dim_pos_iff_exists_ne_zero, split, { rintros ⟨x, h⟩, exact ⟨⟨x, 0, h⟩⟩ }, { introsI, exact exists_ne 0 } end lemma dim_pos [h : nontrivial V] : 0 < vector_space.dim K V := dim_pos_iff_nontrivial.2 h end vector_space section unconstrained_universes variables {E : Type v'} variables [field K] [add_comm_group V] [vector_space K V] [add_comm_group E] [vector_space K E] open vector_space /-- Version of linear_equiv.dim_eq without universe constraints. -/ theorem linear_equiv.dim_eq_lift (f : V ≃ₗ[K] E) : cardinal.lift.{u' v'} (dim K V) = cardinal.lift.{v' u'} (dim K E) := begin cases exists_is_basis K V with b hb, rw [← cardinal.lift_inj.1 hb.mk_eq_dim, ← (f.is_basis hb).mk_eq_dim, cardinal.lift_mk], end end unconstrained_universes
aff0723d093fa6c386370ffa1b9db362b83b0c47
5d166a16ae129621cb54ca9dde86c275d7d2b483
/library/tools/debugger/cli.lean
cac54e070ce60b0edbe206c6455d991dcc014855
[ "Apache-2.0" ]
permissive
jcarlson23/lean
b00098763291397e0ac76b37a2dd96bc013bd247
8de88701247f54d325edd46c0eed57aeacb64baf
refs/heads/master
1,611,571,813,719
1,497,020,963,000
1,497,021,515,000
93,882,536
1
0
null
1,497,029,896,000
1,497,029,896,000
null
UTF-8
Lean
false
false
8,276
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 Simple command line interface for debugging Lean programs and tactics. -/ import tools.debugger.util namespace debugger inductive mode | init | step | run | done instance : decidable_eq mode := by tactic.mk_dec_eq_instance structure state := (md : mode) (csz : nat) (fn_bps : list name) (active_bps : list (nat × name)) def init_state : state := { md := mode.init, csz := 0, fn_bps := [], active_bps := [] } meta def show_help : vm unit := do vm.put_str "exit - stop debugger\n", vm.put_str "help - display this message\n", vm.put_str "run - continue execution\n", vm.put_str "step - execute until another function in on the top of the stack\n", vm.put_str "stack trace\n", vm.put_str " up - move up in the stack trace\n", vm.put_str " down - move down in the stack trace\n", vm.put_str " vars - display variables in the current stack frame\n", vm.put_str " stack - display all functions on the call stack\n", vm.put_str " print var - display the value of variable named 'var' in the current stack frame\n", vm.put_str " pidx idx - display the value of variable at position #idx in the current stack frame\n", vm.put_str "breakpoints\n", vm.put_str " break fn - add breakpoint for fn\n", vm.put_str " rbreak fn - remove breakpoint\n", vm.put_str " bs - show breakpoints\n" meta def add_breakpoint (s : state) (args : list string) : vm state := match args with | [arg] := do fn ← return $ to_qualified_name arg, ok ← is_valid_fn_prefix fn, if ok then return {s with fn_bps := fn :: list.filter (λ fn', fn ≠ fn') s.fn_bps} else vm.put_str "invalid 'break' command, given name is not the prefix for any function\n" >> return s | _ := vm.put_str "invalid 'break <fn>' command, incorrect number of arguments\n" >> return s end meta def remove_breakpoint (s : state) (args : list string) : vm state := match args with | [arg] := do fn ← return $ to_qualified_name arg, return {s with fn_bps := list.filter (λ fn', fn ≠ fn') s.fn_bps} | _ := vm.put_str "invalid 'rbreak <fn>' command, incorrect number of arguments\n" >> return s end meta def show_breakpoints : list name → vm unit | [] := return () | (fn::fns) := do vm.put_str " ", vm.put_str fn.to_string, vm.put_str "\n", show_breakpoints fns meta def up_cmd (frame : nat) : vm nat := if frame = 0 then return 0 else show_frame (frame - 1) >> return (frame - 1) meta def down_cmd (frame : nat) : vm nat := do sz ← vm.call_stack_size, if frame >= sz - 1 then return frame else show_frame (frame + 1) >> return (frame + 1) meta def pidx_cmd : nat → list string → vm unit | frame [arg] := do idx ← return $ arg.to_nat, sz ← vm.stack_size, (bp, ep) ← vm.call_stack_var_range frame, if bp + idx >= ep then vm.put_str "invalid 'pidx <idx>' command, index out of bounds\n" else do v ← vm.pp_stack_obj (bp+idx), (n, t) ← vm.stack_obj_info (bp+idx), opts ← vm.get_options, vm.put_str n.to_string, vm.put_str " := ", vm.put_str (v.to_string opts), vm.put_str "\n" | _ _ := vm.put_str "invalid 'pidx <idx>' command, incorrect number of arguments\n" meta def print_var : nat → nat → name → vm unit | i ep v := do if i = ep then vm.put_str "invalid 'print <var>', unknown variable\n" else do (n, t) ← vm.stack_obj_info i, if n = v then do v ← vm.pp_stack_obj i, opts ← vm.get_options, vm.put_str n.to_string, vm.put_str " := ", vm.put_str (v.to_string opts), vm.put_str "\n" else print_var (i+1) ep v meta def print_cmd : nat → list string → vm unit | frame [arg] := do (bp, ep) ← vm.call_stack_var_range frame, print_var bp ep (to_qualified_name arg) | _ _ := vm.put_str "invalid 'print <var>' command, incorrect number of arguments\n" meta def cmd_loop_core : state → nat → list string → vm state | s frame default_cmd := do is_eof ← vm.eof, if is_eof then do vm.put_str "stopping debugger... 'end of file' has been found\n", return {s with md := mode.done } else do vm.put_str "% ", l ← vm.get_line, tks ← return $ split l, tks ← return $ if tks = [] then default_cmd else tks, match tks with | [] := cmd_loop_core s frame default_cmd | (cmd::args) := if cmd = "help" ∨ cmd = "h" then show_help >> cmd_loop_core s frame [] else if cmd = "exit" then return {s with md := mode.done } else if cmd = "run" ∨ cmd = "r" then return {s with md := mode.run } else if cmd = "step" ∨ cmd = "s" then return {s with md := mode.step } else if cmd = "break" ∨ cmd = "b" then do new_s ← add_breakpoint s args, cmd_loop_core new_s frame [] else if cmd = "rbreak" then do new_s ← remove_breakpoint s args, cmd_loop_core new_s frame [] else if cmd = "bs" then do vm.put_str "breakpoints\n", show_breakpoints s.fn_bps, cmd_loop_core s frame default_cmd else if cmd = "up" ∨ cmd = "u" then do frame ← up_cmd frame, cmd_loop_core s frame ["u"] else if cmd = "down" ∨ cmd = "d" then do frame ← down_cmd frame, cmd_loop_core s frame ["d"] else if cmd = "vars" ∨ cmd = "v" then do show_vars frame, cmd_loop_core s frame [] else if cmd = "stack" then do show_stack, cmd_loop_core s frame [] else if cmd = "pidx" then do pidx_cmd frame args, cmd_loop_core s frame [] else if cmd = "print" ∨ cmd = "p" then do print_cmd frame args, cmd_loop_core s frame [] else do vm.put_str "unknown command, type 'help' for help\n", cmd_loop_core s frame default_cmd end meta def cmd_loop (s : state) (default_cmd : list string) : vm state := do csz ← vm.call_stack_size, cmd_loop_core s (csz - 1) default_cmd def prune_active_bps_core (csz : nat) : list (nat × name) → list (nat × name) | [] := [] | ((csz', n)::ls) := if csz < csz' then prune_active_bps_core ls else ((csz',n)::ls) meta def prune_active_bps (s : state) : vm state := do sz ← vm.call_stack_size, return {s with active_bps := prune_active_bps_core sz s.active_bps} meta def updt_csz (s : state) : vm state := do sz ← vm.call_stack_size, return {s with csz := sz} meta def init_transition (s : state) : vm state := do opts ← vm.get_options, if opts.get_bool `server ff then return {s with md := mode.done} else do bps ← vm.get_attribute `breakpoint, new_s ← return {s with fn_bps := bps}, if opts.get_bool `debugger.autorun ff then return {new_s with md := mode.run} else do vm.put_str "Lean debugger\n", show_curr_fn "debugging", vm.put_str "type 'help' for help\n", cmd_loop new_s [] meta def step_transition (s : state) : vm state := do sz ← vm.call_stack_size, if sz = s.csz then return s else do show_curr_fn "step", cmd_loop s ["s"] meta def bp_reached (s : state) : vm bool := (do fn ← vm.curr_fn, return $ s.fn_bps.any (λ p, p.is_prefix_of fn)) <|> return ff meta def in_active_bps (s : state) : vm bool := do sz ← vm.call_stack_size, match s.active_bps with | [] := return ff | (csz, _)::_ := return (sz = csz) end meta def run_transition (s : state) : vm state := do b1 ← in_active_bps s, b2 ← bp_reached s, if b1 ∨ not b2 then return s else do show_curr_fn "breakpoint", fn ← vm.curr_fn, sz ← vm.call_stack_size, new_s ← return $ {s with active_bps := (sz, fn) :: s.active_bps}, cmd_loop new_s ["r"] meta def step_fn (s : state) : vm state := do s ← prune_active_bps s, if s.md = mode.init then do new_s ← init_transition s, updt_csz new_s else if s.md = mode.done then return s else if s.md = mode.step then do new_s ← step_transition s, updt_csz new_s else if s.md = mode.run then do new_s ← run_transition s, updt_csz new_s else return s @[vm_monitor] meta def monitor : vm_monitor state := { init := init_state, step := step_fn } end debugger
636005e1b94e4a5438da5e3d1582ae10f784f0a9
b328e8ebb2ba923140e5137c83f09fa59516b793
/src/Lean/Meta/Tactic/ElimInfo.lean
d35bc80c8fc5e8f5b110edc1228893ee59a4d642
[ "Apache-2.0" ]
permissive
DrMaxis/lean4
a781bcc095511687c56ab060e816fd948553e162
5a02c4facc0658aad627cfdcc3db203eac0cb544
refs/heads/master
1,677,051,517,055
1,611,876,226,000
1,611,876,226,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,994
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Basic namespace Lean.Meta structure ElimAltInfo where name : Name numFields : Nat structure ElimInfo where motivePos : Nat targetsPos : Array Nat := #[] altsInfo : Array ElimAltInfo := #[] def getElimInfo (declName : Name) : MetaM ElimInfo := do let declInfo ← getConstInfo declName forallTelescopeReducing declInfo.type fun xs type => do let motive := type.getAppFn let targets := type.getAppArgs unless motive.isFVar && targets.all (·.isFVar) && targets.size > 0 do throwError! "unexpected eliminator resulting type{indentExpr type}" let motiveType ← inferType motive forallTelescopeReducing motiveType fun motiveArgs motiveResultType => do unless motiveArgs.size == targets.size do throwError! "unexpected number of arguments at motive type{indentExpr motiveType}" unless motiveResultType.isSort do throwError! "motive result type must be a sort{indentExpr motiveType}" let some motivePos ← pure (xs.indexOf? motive) | throwError! "unexpected eliminator type{indentExpr declInfo.type}" let targetsPos ← targets.mapM fun target => do match xs.indexOf? target with | none => throwError! "unexpected eliminator type{indentExpr declInfo.type}" | some targetPos => pure targetPos.val let mut altsInfo := #[] for i in [:xs.size] do let x := xs[i] if x != motive && !targets.contains x then let xDecl ← getLocalDecl x.fvarId! if xDecl.binderInfo.isExplicit then let numFields ← forallTelescopeReducing xDecl.type fun args _ => pure args.size altsInfo := altsInfo.push { name := xDecl.userName, numFields := numFields : ElimAltInfo } pure { motivePos := motivePos, targetsPos := targetsPos, altsInfo := altsInfo } end Lean.Meta
ec18cc87d92176597547b0f9867a8f6305f7b63d
a047a4718edfa935d17231e9e6ecec8c7b701e05
/src/topology/uniform_space/basic.lean
aa8b76b2b2b880078c71f987883c8506f2132fdc
[ "Apache-2.0" ]
permissive
utensil-contrib/mathlib
bae0c9fafe5e2bdb516efc89d6f8c1502ecc9767
b91909e77e219098a2f8cc031f89d595fe274bd2
refs/heads/master
1,668,048,976,965
1,592,442,701,000
1,592,442,701,000
273,197,855
0
0
null
1,592,472,812,000
1,592,472,811,000
null
UTF-8
Lean
false
false
61,584
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot -/ import order.filter.lift import topology.separation /-! # Uniform spaces Uniform spaces are a generalization of metric spaces and topological groups. Many concepts directly generalize to uniform spaces, e.g. * uniform continuity (in this file) * completeness (in `cauchy.lean`) * extension of uniform continuous functions to complete spaces (in `uniform_embedding.lean`) * totally bounded sets (in `cauchy.lean`) * totally bounded complete sets are compact (in `cauchy.lean`) A uniform structure on a type `X` is a filter `𝓤 X` on `X × X` satisfying some conditions which makes it reasonable to say that `∀ᶠ (p : X × X) in 𝓤 X, ...` means "for all p.1 and p.2 in X close enough, ...". Elements of this filter are called entourages of `X`. The two main examples are: * If `X` is a metric space, `V ∈ 𝓤 X ↔ ∃ ε > 0, { p | dist p.1 p.2 < ε } ⊆ V` * If `G` is an additive topological group, `V ∈ 𝓤 G ↔ ∃ U ∈ 𝓝 (0 : G), {p | p.2 - p.1 ∈ U} ⊆ V` Those examples are generalizations in two different directions of the elementary example where `X = ℝ` and `V ∈ 𝓤 ℝ ↔ ∃ ε > 0, { p | |p.2 - p.1| < ε } ⊆ V` which features both the topological group structure on `ℝ` and its metric space structure. Each uniform structure on `X` induces a topology on `X` characterized by: > `nhds_eq_comap_uniformity : ∀ {x : X}, 𝓝 x = comap (prod.mk x) (𝓤 X)` where `prod.mk x : X → X × X := (λ y, (x, y))` is the partial evaluation of the product constructor. The dictionary with metric spaces includes: * an upper bound for `dist x y` translates into `(x, y) ∈ V` for some `V ∈ 𝓤 X` * a ball `ball x r` roughly corresponds to `uniform_space.ball x V := {y | (x, y) ∈ V}` for some `V ∈ 𝓤 X`, but the later is more general (it includes in particular both open and closed balls for suitable `V`). In particular we have: `is_open_iff_ball_subset {s : set X} : is_open s ↔ ∀ x ∈ s, ∃ V ∈ 𝓤 X, ball x V ⊆ s` The triangle inequality is abstracted to a statement involving the composition of relations in `X`. First note that the triangle inequality in a metric space is equivalent to `∀ (x y z : X) (r r' : ℝ), dist x y ≤ r → dist y z ≤ r' → dist x z ≤ r + r'`. Then, for any `V` and `W` with type `set (X × X)`, the composition `V ○ W : set (X × X)` is defined as `{ p : X × X | ∃ z, (p.1, z) ∈ V ∧ (z, p.2) ∈ W }`. In the metric space case, if `V = { p | dist p.1 p.2 ≤ r }` and `W = { p | dist p.1 p.2 ≤ r' }` then the triangle inequality, as reformulated above, says `V ○ W` is contained in `{p | dist p.1 p.2 ≤ r + r'}` which is the entourage associated to the radius `r + r'`. In general we have `mem_ball_comp (h : y ∈ ball x V) (h' : z ∈ ball y W) : z ∈ ball x (V ○ W)`. Note that this discussion does not depend on any axiom imposed on the uniformity filter, it is simply captured by the definition of composition. The uniform space axioms ask the filter `𝓤 X` to satisfy the following: * every `V ∈ 𝓤 X` contains the diagonal `id_rel = { p | p.1 = p.2 }`. This abstracts the fact that `dist x x ≤ r` for every non-negative radius `r` in the metric space case and also that `x - x` belongs to every neighborhood of zero in the topological group case. * `V ∈ 𝓤 X → prod.swap '' V ∈ 𝓤 X`. This is tightly related the fact that `dist x y = dist y x` in a metric space, and to continuity of negation in the topological group case. * `∀ V ∈ 𝓤 X, ∃ W ∈ 𝓤 X, W ○ W ⊆ V`. In the metric space case, it corresponds to cutting the radius of a ball in half and applying the triangle inequality. In the topological group case, it comes from continuity of addition at `(0, 0)`. These three axioms are stated more abstractly in the definition below, in terms of operations on filters, without directly manipulating entourages. ## Main definitions * `uniform_space X` is a uniform space structure on a type `X` * `uniform_continuous f` is a predicate saying a function `f : α → β` between uniform spaces is uniformly continuous : `∀ r ∈ 𝓤 β, ∀ᶠ (x : α × α) in 𝓤 α, (f x.1, f x.2) ∈ r` In this file we also define a complete lattice structure on the type `uniform_space X` of uniform structures on `X`, as well as the pullback (`uniform_space.comap`) of uniform structures coming from the pullback of filters. Like distance functions, uniform structures cannot be pushed forward in general. ## Notations Localized in `uniformity`, we have the notation `𝓤 X` for the uniformity on a uniform space `X`, and `○` for composition of relations, seen as terms with type `set (X × X)`. ## Implementation notes There is already a theory of relations in `data/rel.lean` where the main definition is `def rel (α β : Type*) := α → β → Prop`. The relations used in the current file involve only one type, but this is not the reason why we don't reuse `data/rel.lean`. We use `set (α × α)` instead of `rel α α` because we really need sets to use the filter library, and elements of filters on `α × α` have type `set (α × α)`. The structure `uniform_space X` bundles a uniform structure on `X`, a topology on `X` and an assumption saying those are compatible. This may not seem mathematically reasonable at first, but is in fact an instance of the forgetful inheritance pattern. See Note [forgetful inheritance] below. ## References The formalization uses the books: * [N. Bourbaki, *General Topology*][bourbaki1966] * [I. M. James, *Topologies and Uniformities*][james1999] But it makes a more systematic use of the filter library. -/ open set filter classical open_locale classical topological_space set_option eqn_compiler.zeta true universes u /-! ### Relations, seen as `set (α × α)` -/ variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Sort*} /-- The identity relation, or the graph of the identity function -/ def id_rel {α : Type*} := {p : α × α | p.1 = p.2} @[simp] theorem mem_id_rel {a b : α} : (a, b) ∈ @id_rel α ↔ a = b := iff.rfl @[simp] theorem id_rel_subset {s : set (α × α)} : id_rel ⊆ s ↔ ∀ a, (a, a) ∈ s := by simp [subset_def]; exact forall_congr (λ a, by simp) /-- The composition of relations -/ def comp_rel {α : Type u} (r₁ r₂ : set (α×α)) := {p : α × α | ∃z:α, (p.1, z) ∈ r₁ ∧ (z, p.2) ∈ r₂} localized "infix ` ○ `:55 := comp_rel" in uniformity @[simp] theorem mem_comp_rel {r₁ r₂ : set (α×α)} {x y : α} : (x, y) ∈ r₁ ○ r₂ ↔ ∃ z, (x, z) ∈ r₁ ∧ (z, y) ∈ r₂ := iff.rfl @[simp] theorem swap_id_rel : prod.swap '' id_rel = @id_rel α := set.ext $ assume ⟨a, b⟩, by simp [image_swap_eq_preimage_swap]; exact eq_comm theorem monotone_comp_rel [preorder β] {f g : β → set (α×α)} (hf : monotone f) (hg : monotone g) : monotone (λx, (f x) ○ (g x)) := assume a b h p ⟨z, h₁, h₂⟩, ⟨z, hf h h₁, hg h h₂⟩ lemma prod_mk_mem_comp_rel {a b c : α} {s t : set (α×α)} (h₁ : (a, c) ∈ s) (h₂ : (c, b) ∈ t) : (a, b) ∈ s ○ t := ⟨c, h₁, h₂⟩ @[simp] lemma id_comp_rel {r : set (α×α)} : id_rel ○ r = r := set.ext $ assume ⟨a, b⟩, by simp lemma comp_rel_assoc {r s t : set (α×α)} : (r ○ s) ○ t = r ○ (s ○ t) := by ext p; cases p; simp only [mem_comp_rel]; tauto /-- The relation is invariant under swapping factors. -/ def symmetric_rel (V : set (α × α)) : Prop := prod.swap ⁻¹' V = V /-- The maximal symmetric relation contained in a given relation. -/ def symmetrize_rel (V : set (α × α)) : set (α × α) := V ∩ prod.swap ⁻¹' V lemma symmetric_symmetrize_rel (V : set (α × α)) : symmetric_rel (symmetrize_rel V) := by simp [symmetric_rel, symmetrize_rel, preimage_inter, inter_comm, ← preimage_comp] lemma symmetrize_rel_subset_self (V : set (α × α)) : symmetrize_rel V ⊆ V := sep_subset _ _ @[mono] lemma symmetrize_mono {V W: set (α × α)} (h : V ⊆ W) : symmetrize_rel V ⊆ symmetrize_rel W := inter_subset_inter h $ preimage_mono h /-- This core description of a uniform space is outside of the type class hierarchy. It is useful for constructions of uniform spaces, when the topology is derived from the uniform space. -/ structure uniform_space.core (α : Type u) := (uniformity : filter (α × α)) (refl : principal id_rel ≤ uniformity) (symm : tendsto prod.swap uniformity uniformity) (comp : uniformity.lift' (λs, s ○ s) ≤ uniformity) /-- An alternative constructor for `uniform_space.core`. This version unfolds various `filter`-related definitions. -/ def uniform_space.core.mk' {α : Type u} (U : filter (α × α)) (refl : ∀ (r ∈ U) x, (x, x) ∈ r) (symm : ∀ r ∈ U, prod.swap ⁻¹' r ∈ U) (comp : ∀ r ∈ U, ∃ t ∈ U, t ○ t ⊆ r) : uniform_space.core α := ⟨U, λ r ru, id_rel_subset.2 (refl _ ru), symm, begin intros r ru, rw [mem_lift'_sets], exact comp _ ru, apply monotone_comp_rel; exact monotone_id, end⟩ /-- A uniform space generates a topological space -/ def uniform_space.core.to_topological_space {α : Type u} (u : uniform_space.core α) : topological_space α := { is_open := λs, ∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ u.uniformity, is_open_univ := by simp; intro; exact univ_mem_sets, is_open_inter := assume s t hs ht x ⟨xs, xt⟩, by filter_upwards [hs x xs, ht x xt]; simp {contextual := tt}, is_open_sUnion := assume s hs x ⟨t, ts, xt⟩, by filter_upwards [hs t ts x xt] assume p ph h, ⟨t, ts, ph h⟩ } lemma uniform_space.core_eq : ∀{u₁ u₂ : uniform_space.core α}, u₁.uniformity = u₂.uniformity → u₁ = u₂ | ⟨u₁, _, _, _⟩ ⟨u₂, _, _, _⟩ h := have u₁ = u₂, from h, by simp [*] section prio /-- Suppose that one can put two mathematical structures on a type, a rich one `R` and a poor one `P`, and that one can deduce the poor structure from the rich structure through a map `F` (called a forgetful functor) (think `R = metric_space` and `P = topological_space`). A possible implementation would be to have a type class `rich` containing a field `R`, a type class `poor` containing a field `P`, and an instance from `rich` to `poor`. However, this creates diamond problems, and a better approach is to let `rich` extend `poor` and have a field saying that `F R = P`. To illustrate this, consider the pair `metric_space` / `topological_space`. Consider the topology on a product of two metric spaces. With the first approach, it could be obtained by going first from each metric space to its topology, and then taking the product topology. But it could also be obtained by considering the product metric space (with its sup distance) and then the topology coming from this distance. These would be the same topology, but not definitionally, which means that from the point of view of Lean's kernel, there would be two different `topological_space` instances on the product. This is not compatible with the way instances are designed and used: there should be at most one instance of a kind on each type. This approach has created an instance diamond that does not commute definitionally. The second approach solves this issue. Now, a metric space contains both a distance, a topology, and a proof that the topology coincides with the one coming from the distance. When one defines the product of two metric spaces, one uses the sup distance and the product topology, and one has to give the proof that the sup distance induces the product topology. Following both sides of the instance diamond then gives rise (definitionally) to the product topology on the product space. Another approach would be to have the rich type class take the poor type class as an instance parameter. It would solve the diamond problem, but it would lead to a blow up of the number of type classes one would need to declare to work with complicated classes, say a real inner product space, and would create exponential complexity when working with products of such complicated spaces, that are avoided by bundling things carefully as above. Note that this description of this specific case of the product of metric spaces is oversimplified compared to mathlib, as there is an intermediate typeclass between `metric_space` and `topological_space` called `uniform_space`. The above scheme is used at both levels, embedding a topology in the uniform space structure, and a uniform structure in the metric space structure. Note also that, when `P` is a proposition, there is no such issue as any two proofs of `P` are definitionally equivalent in Lean. To avoid boilerplate, there are some designs that can automatically fill the poor fields when creating a rich structure if one doesn't want to do something special about them. For instance, in the definition of metric spaces, default tactics fill the uniform space fields if they are not given explicitly. One can also have a helper function creating the rich structure from a structure with less fields, where the helper function fills the remaining fields. See for instance `uniform_space.of_core` or `real_inner_product.of_core`. For more details on this question, called the forgetful inheritance pattern, see [Competing inheritance paths in dependent type theory: a case study in functional analysis](https://hal.inria.fr/hal-02463336). -/ library_note "forgetful inheritance" set_option default_priority 100 -- see Note [default priority] /-- A uniform space is a generalization of the "uniform" topological aspects of a metric space. It consists of a filter on `α × α` called the "uniformity", which satisfies properties analogous to the reflexivity, symmetry, and triangle properties of a metric. A metric space has a natural uniformity, and a uniform space has a natural topology. A topological group also has a natural uniformity, even when it is not metrizable. -/ class uniform_space (α : Type u) extends topological_space α, uniform_space.core α := (is_open_uniformity : ∀s, is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ uniformity)) end prio /-- Alternative constructor for `uniform_space α` when a topology is already given. -/ @[pattern] def uniform_space.mk' {α} (t : topological_space α) (c : uniform_space.core α) (is_open_uniformity : ∀s:set α, t.is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ c.uniformity)) : uniform_space α := ⟨c, is_open_uniformity⟩ /-- Construct a `uniform_space` from a `uniform_space.core`. -/ def uniform_space.of_core {α : Type u} (u : uniform_space.core α) : uniform_space α := { to_core := u, to_topological_space := u.to_topological_space, is_open_uniformity := assume a, iff.rfl } /-- Construct a `uniform_space` from a `u : uniform_space.core` and a `topological_space` structure that is equal to `u.to_topological_space`. -/ def uniform_space.of_core_eq {α : Type u} (u : uniform_space.core α) (t : topological_space α) (h : t = u.to_topological_space) : uniform_space α := { to_core := u, to_topological_space := t, is_open_uniformity := assume a, h.symm ▸ iff.rfl } lemma uniform_space.to_core_to_topological_space (u : uniform_space α) : u.to_core.to_topological_space = u.to_topological_space := topological_space_eq $ funext $ assume s, by rw [uniform_space.core.to_topological_space, uniform_space.is_open_uniformity] @[ext] lemma uniform_space_eq : ∀{u₁ u₂ : uniform_space α}, u₁.uniformity = u₂.uniformity → u₁ = u₂ | (uniform_space.mk' t₁ u₁ o₁) (uniform_space.mk' t₂ u₂ o₂) h := have u₁ = u₂, from uniform_space.core_eq h, have t₁ = t₂, from topological_space_eq $ funext $ assume s, by rw [o₁, o₂]; simp [this], by simp [*] lemma uniform_space.of_core_eq_to_core (u : uniform_space α) (t : topological_space α) (h : t = u.to_core.to_topological_space) : uniform_space.of_core_eq u.to_core t h = u := uniform_space_eq rfl section uniform_space variables [uniform_space α] /-- The uniformity is a filter on α × α (inferred from an ambient uniform space structure on α). -/ def uniformity (α : Type u) [uniform_space α] : filter (α × α) := (@uniform_space.to_core α _).uniformity localized "notation `𝓤` := uniformity" in uniformity lemma is_open_uniformity {s : set α} : is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ 𝓤 α) := uniform_space.is_open_uniformity s lemma refl_le_uniformity : principal id_rel ≤ 𝓤 α := (@uniform_space.to_core α _).refl lemma refl_mem_uniformity {x : α} {s : set (α × α)} (h : s ∈ 𝓤 α) : (x, x) ∈ s := refl_le_uniformity h rfl lemma symm_le_uniformity : map (@prod.swap α α) (𝓤 _) ≤ (𝓤 _) := (@uniform_space.to_core α _).symm lemma comp_le_uniformity : (𝓤 α).lift' (λs:set (α×α), s ○ s) ≤ 𝓤 α := (@uniform_space.to_core α _).comp lemma tendsto_swap_uniformity : tendsto (@prod.swap α α) (𝓤 α) (𝓤 α) := symm_le_uniformity lemma comp_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, t ○ t ⊆ s := have s ∈ (𝓤 α).lift' (λt:set (α×α), t ○ t), from comp_le_uniformity hs, (mem_lift'_sets $ monotone_comp_rel monotone_id monotone_id).mp this /-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is transitive. -/ lemma filter.tendsto.uniformity_trans {l : filter β} {f₁ f₂ f₃ : β → α} (h₁₂ : tendsto (λ x, (f₁ x, f₂ x)) l (𝓤 α)) (h₂₃ : tendsto (λ x, (f₂ x, f₃ x)) l (𝓤 α)) : tendsto (λ x, (f₁ x, f₃ x)) l (𝓤 α) := begin refine le_trans (le_lift' $ λ s hs, mem_map.2 _) comp_le_uniformity, filter_upwards [h₁₂ hs, h₂₃ hs], exact λ x hx₁₂ hx₂₃, ⟨_, hx₁₂, hx₂₃⟩ end /-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is symmetric -/ lemma filter.tendsto.uniformity_symm {l : filter β} {f : β → α × α} (h : tendsto f l (𝓤 α)) : tendsto (λ x, ((f x).2, (f x).1)) l (𝓤 α) := tendsto_swap_uniformity.comp h /-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is reflexive. -/ lemma tendsto_diag_uniformity (f : β → α) (l : filter β) : tendsto (λ x, (f x, f x)) l (𝓤 α) := assume s hs, mem_map.2 $ univ_mem_sets' $ λ x, refl_mem_uniformity hs lemma tendsto_const_uniformity {a : α} {f : filter β} : tendsto (λ _, (a, a)) f (𝓤 α) := tendsto_diag_uniformity (λ _, a) f lemma symm_of_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, (∀a b, (a, b) ∈ t → (b, a) ∈ t) ∧ t ⊆ s := have preimage prod.swap s ∈ 𝓤 α, from symm_le_uniformity hs, ⟨s ∩ preimage prod.swap s, inter_mem_sets hs this, assume a b ⟨h₁, h₂⟩, ⟨h₂, h₁⟩, inter_subset_left _ _⟩ lemma comp_symm_of_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, (∀{a b}, (a, b) ∈ t → (b, a) ∈ t) ∧ t ○ t ⊆ s := let ⟨t, ht₁, ht₂⟩ := comp_mem_uniformity_sets hs in let ⟨t', ht', ht'₁, ht'₂⟩ := symm_of_uniformity ht₁ in ⟨t', ht', ht'₁, subset.trans (monotone_comp_rel monotone_id monotone_id ht'₂) ht₂⟩ lemma uniformity_le_symm : 𝓤 α ≤ (@prod.swap α α) <$> 𝓤 α := by rw [map_swap_eq_comap_swap]; from map_le_iff_le_comap.1 tendsto_swap_uniformity lemma uniformity_eq_symm : 𝓤 α = (@prod.swap α α) <$> 𝓤 α := le_antisymm uniformity_le_symm symm_le_uniformity lemma symmetrize_mem_uniformity {V : set (α × α)} (h : V ∈ 𝓤 α) : symmetrize_rel V ∈ 𝓤 α := begin apply (𝓤 α).inter_sets h, rw [← image_swap_eq_preimage_swap, uniformity_eq_symm], exact image_mem_map h, end theorem uniformity_lift_le_swap {g : set (α×α) → filter β} {f : filter β} (hg : monotone g) (h : (𝓤 α).lift (λs, g (preimage prod.swap s)) ≤ f) : (𝓤 α).lift g ≤ f := calc (𝓤 α).lift g ≤ (filter.map (@prod.swap α α) $ 𝓤 α).lift g : lift_mono uniformity_le_symm (le_refl _) ... ≤ _ : by rw [map_lift_eq2 hg, image_swap_eq_preimage_swap]; exact h lemma uniformity_lift_le_comp {f : set (α×α) → filter β} (h : monotone f) : (𝓤 α).lift (λs, f (s ○ s)) ≤ (𝓤 α).lift f := calc (𝓤 α).lift (λs, f (s ○ s)) = ((𝓤 α).lift' (λs:set (α×α), s ○ s)).lift f : begin rw [lift_lift'_assoc], exact monotone_comp_rel monotone_id monotone_id, exact h end ... ≤ (𝓤 α).lift f : lift_mono comp_le_uniformity (le_refl _) lemma comp_le_uniformity3 : (𝓤 α).lift' (λs:set (α×α), s ○ (s ○ s)) ≤ (𝓤 α) := calc (𝓤 α).lift' (λd, d ○ (d ○ d)) = (𝓤 α).lift (λs, (𝓤 α).lift' (λt:set(α×α), s ○ (t ○ t))) : begin rw [lift_lift'_same_eq_lift'], exact (assume x, monotone_comp_rel monotone_const $ monotone_comp_rel monotone_id monotone_id), exact (assume x, monotone_comp_rel monotone_id monotone_const), end ... ≤ (𝓤 α).lift (λs, (𝓤 α).lift' (λt:set(α×α), s ○ t)) : lift_mono' $ assume s hs, @uniformity_lift_le_comp α _ _ (principal ∘ (○) s) $ monotone_principal.comp (monotone_comp_rel monotone_const monotone_id) ... = (𝓤 α).lift' (λs:set(α×α), s ○ s) : lift_lift'_same_eq_lift' (assume s, monotone_comp_rel monotone_const monotone_id) (assume s, monotone_comp_rel monotone_id monotone_const) ... ≤ (𝓤 α) : comp_le_uniformity /-! ### Balls in uniform spaces -/ /-- The ball around `(x : β)` with respect to `(V : set (β × β))`. Intended to be used for `V ∈ 𝓤 β`, but this is not needed for the definition. Recovers the notions of metric space ball when `V = {p | dist p.1 p.2 < r }`. -/ def uniform_space.ball (x : β) (V : set (β × β)) : set β := (prod.mk x) ⁻¹' V open uniform_space (ball) /-- The triangle inequality for `uniform_space.ball` -/ lemma mem_ball_comp {V W : set (β × β)} {x y z} (h : y ∈ ball x V) (h' : z ∈ ball y W) : z ∈ ball x (V ○ W) := prod_mk_mem_comp_rel h h' lemma ball_subset_of_comp_subset {V W : set (β × β)} {x y} (h : x ∈ ball y W) (h' : W ○ W ⊆ V) : ball x W ⊆ ball y V := λ z z_in, h' (mem_ball_comp h z_in) lemma ball_mono {V W : set (β × β)} (h : V ⊆ W) (x : β) : ball x V ⊆ ball x W := by tauto lemma mem_ball_symmetry {V : set (β × β)} (hV : symmetric_rel V) {x y} : x ∈ ball y V ↔ y ∈ ball x V := show (x, y) ∈ prod.swap ⁻¹' V ↔ (x, y) ∈ V, by { unfold symmetric_rel at hV, rw hV } lemma ball_eq_of_symmetry {V : set (β × β)} (hV : symmetric_rel V) {x} : ball x V = {y | (y, x) ∈ V} := by { ext y, rw mem_ball_symmetry hV, exact iff.rfl } /-! ### Neighborhoods in uniform spaces -/ lemma mem_nhds_uniformity_iff_right {x : α} {s : set α} : s ∈ 𝓝 x ↔ {p : α × α | p.1 = x → p.2 ∈ s} ∈ 𝓤 α := ⟨ begin simp only [mem_nhds_sets_iff, is_open_uniformity, and_imp, exists_imp_distrib], exact assume t ts ht xt, by filter_upwards [ht x xt] assume ⟨x', y⟩ h eq, ts $ h eq end, assume hs, mem_nhds_sets_iff.mpr ⟨{x | {p : α × α | p.1 = x → p.2 ∈ s} ∈ 𝓤 α}, assume x' hx', refl_mem_uniformity hx' rfl, is_open_uniformity.mpr $ assume x' hx', let ⟨t, ht, tr⟩ := comp_mem_uniformity_sets hx' in by filter_upwards [ht] assume ⟨a, b⟩ hp' (hax' : a = x'), by filter_upwards [ht] assume ⟨a, b'⟩ hp'' (hab : a = b), have hp : (x', b) ∈ t, from hax' ▸ hp', have (b, b') ∈ t, from hab ▸ hp'', have (x', b') ∈ t ○ t, from ⟨b, hp, this⟩, show b' ∈ s, from tr this rfl, hs⟩⟩ lemma mem_nhds_uniformity_iff_left {x : α} {s : set α} : s ∈ 𝓝 x ↔ {p : α × α | p.2 = x → p.1 ∈ s} ∈ 𝓤 α := by { rw [uniformity_eq_symm, mem_nhds_uniformity_iff_right], refl } lemma nhds_eq_comap_uniformity {x : α} : 𝓝 x = (𝓤 α).comap (prod.mk x) := by ext s; rw [mem_nhds_uniformity_iff_right, mem_comap_sets]; from iff.intro (assume hs, ⟨_, hs, assume x hx, hx rfl⟩) (assume ⟨t, h, ht⟩, (𝓤 α).sets_of_superset h $ assume ⟨p₁, p₂⟩ hp (h : p₁ = x), ht $ by simp [h.symm, hp]) lemma is_open_iff_ball_subset {s : set α} : is_open s ↔ ∀ x ∈ s, ∃ V ∈ 𝓤 α, ball x V ⊆ s := begin simp_rw [is_open_iff_mem_nhds, nhds_eq_comap_uniformity], exact iff.rfl, end lemma nhds_basis_uniformity' {p : β → Prop} {s : β → set (α × α)} (h : (𝓤 α).has_basis p s) {x : α} : (𝓝 x).has_basis p (λ i, {y | (x, y) ∈ s i}) := by { rw [nhds_eq_comap_uniformity], exact h.comap (prod.mk x) } lemma nhds_basis_uniformity {p : β → Prop} {s : β → set (α × α)} (h : (𝓤 α).has_basis p s) {x : α} : (𝓝 x).has_basis p (λ i, {y | (y, x) ∈ s i}) := begin replace h := h.comap prod.swap, rw [← map_swap_eq_comap_swap, ← uniformity_eq_symm] at h, exact nhds_basis_uniformity' h end lemma nhds_eq_uniformity {x : α} : 𝓝 x = (𝓤 α).lift' (λs:set (α×α), {y | (x, y) ∈ s}) := (nhds_basis_uniformity' (𝓤 α).basis_sets).eq_binfi lemma mem_nhds_left (x : α) {s : set (α×α)} (h : s ∈ 𝓤 α) : {y : α | (x, y) ∈ s} ∈ 𝓝 x := (nhds_basis_uniformity' (𝓤 α).basis_sets).mem_of_mem h lemma mem_nhds_right (y : α) {s : set (α×α)} (h : s ∈ 𝓤 α) : {x : α | (x, y) ∈ s} ∈ 𝓝 y := mem_nhds_left _ (symm_le_uniformity h) lemma tendsto_right_nhds_uniformity {a : α} : tendsto (λa', (a', a)) (𝓝 a) (𝓤 α) := assume s, mem_nhds_right a lemma tendsto_left_nhds_uniformity {a : α} : tendsto (λa', (a, a')) (𝓝 a) (𝓤 α) := assume s, mem_nhds_left a lemma lift_nhds_left {x : α} {g : set α → filter β} (hg : monotone g) : (𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ s}) := eq.trans begin rw [nhds_eq_uniformity], exact (filter.lift_assoc $ monotone_principal.comp $ monotone_preimage.comp monotone_preimage ) end (congr_arg _ $ funext $ assume s, filter.lift_principal hg) lemma lift_nhds_right {x : α} {g : set α → filter β} (hg : monotone g) : (𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (y, x) ∈ s}) := calc (𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ s}) : lift_nhds_left hg ... = ((@prod.swap α α) <$> (𝓤 α)).lift (λs:set (α×α), g {y | (x, y) ∈ s}) : by rw [←uniformity_eq_symm] ... = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ image prod.swap s}) : map_lift_eq2 $ hg.comp monotone_preimage ... = _ : by simp [image_swap_eq_preimage_swap] lemma nhds_nhds_eq_uniformity_uniformity_prod {a b : α} : filter.prod (𝓝 a) (𝓝 b) = (𝓤 α).lift (λs:set (α×α), (𝓤 α).lift' (λt:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ t})) := begin rw [prod_def], show (𝓝 a).lift (λs:set α, (𝓝 b).lift (λt:set α, principal (set.prod s t))) = _, rw [lift_nhds_right], apply congr_arg, funext s, rw [lift_nhds_left], refl, exact monotone_principal.comp (monotone_prod monotone_const monotone_id), exact (monotone_lift' monotone_const $ monotone_lam $ assume x, monotone_prod monotone_id monotone_const) end lemma nhds_eq_uniformity_prod {a b : α} : 𝓝 (a, b) = (𝓤 α).lift' (λs:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ s}) := begin rw [nhds_prod_eq, nhds_nhds_eq_uniformity_uniformity_prod, lift_lift'_same_eq_lift'], { intro s, exact monotone_prod monotone_const monotone_preimage }, { intro t, exact monotone_prod monotone_preimage monotone_const } end lemma nhdset_of_mem_uniformity {d : set (α×α)} (s : set (α×α)) (hd : d ∈ 𝓤 α) : ∃(t : set (α×α)), is_open t ∧ s ⊆ t ∧ t ⊆ {p | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} := let cl_d := {p:α×α | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} in have ∀p ∈ s, ∃t ⊆ cl_d, is_open t ∧ p ∈ t, from assume ⟨x, y⟩ hp, mem_nhds_sets_iff.mp $ show cl_d ∈ 𝓝 (x, y), begin rw [nhds_eq_uniformity_prod, mem_lift'_sets], exact ⟨d, hd, assume ⟨a, b⟩ ⟨ha, hb⟩, ⟨x, y, ha, hp, hb⟩⟩, exact monotone_prod monotone_preimage monotone_preimage end, have ∃t:(Π(p:α×α) (h:p ∈ s), set (α×α)), ∀p, ∀h:p ∈ s, t p h ⊆ cl_d ∧ is_open (t p h) ∧ p ∈ t p h, by simp [classical.skolem] at this; simp; assumption, match this with | ⟨t, ht⟩ := ⟨(⋃ p:α×α, ⋃ h : p ∈ s, t p h : set (α×α)), is_open_Union $ assume (p:α×α), is_open_Union $ assume hp, (ht p hp).right.left, assume ⟨a, b⟩ hp, begin simp; exact ⟨a, b, hp, (ht (a,b) hp).right.right⟩ end, Union_subset $ assume p, Union_subset $ assume hp, (ht p hp).left⟩ end /-! ### Closure and interior in uniform spaces -/ lemma closure_eq_inter_uniformity {t : set (α×α)} : closure t = (⋂ d ∈ 𝓤 α, d ○ (t ○ d)) := set.ext $ assume ⟨a, b⟩, calc (a, b) ∈ closure t ↔ (𝓝 (a, b) ⊓ principal t ≠ ⊥) : by simp [closure_eq_nhds] ... ↔ (((@prod.swap α α) <$> 𝓤 α).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ principal t ≠ ⊥) : by rw [←uniformity_eq_symm, nhds_eq_uniformity_prod] ... ↔ ((map (@prod.swap α α) (𝓤 α)).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ principal t ≠ ⊥) : by refl ... ↔ ((𝓤 α).lift' (λ (s : set (α × α)), set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s}) ⊓ principal t ≠ ⊥) : begin rw [map_lift'_eq2], simp [image_swap_eq_preimage_swap, function.comp], exact monotone_prod monotone_preimage monotone_preimage end ... ↔ (∀s ∈ 𝓤 α, (set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s} ∩ t).nonempty) : begin rw [lift'_inf_principal_eq, lift'_ne_bot_iff], exact monotone_inter (monotone_prod monotone_preimage monotone_preimage) monotone_const end ... ↔ (∀ s ∈ 𝓤 α, (a, b) ∈ s ○ (t ○ s)) : forall_congr $ assume s, forall_congr $ assume hs, ⟨assume ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩, ⟨x, hx, y, hxyt, hy⟩, assume ⟨x, hx, y, hxyt, hy⟩, ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩⟩ ... ↔ _ : by simp lemma uniformity_eq_uniformity_closure : 𝓤 α = (𝓤 α).lift' closure := le_antisymm (le_infi $ assume s, le_infi $ assume hs, by simp; filter_upwards [hs] subset_closure) (calc (𝓤 α).lift' closure ≤ (𝓤 α).lift' (λd, d ○ (d ○ d)) : lift'_mono' (by intros s hs; rw [closure_eq_inter_uniformity]; exact bInter_subset_of_mem hs) ... ≤ (𝓤 α) : comp_le_uniformity3) lemma uniformity_eq_uniformity_interior : 𝓤 α = (𝓤 α).lift' interior := le_antisymm (le_infi $ assume d, le_infi $ assume hd, let ⟨s, hs, hs_comp⟩ := (mem_lift'_sets $ monotone_comp_rel monotone_id $ monotone_comp_rel monotone_id monotone_id).mp (comp_le_uniformity3 hd) in let ⟨t, ht, hst, ht_comp⟩ := nhdset_of_mem_uniformity s hs in have s ⊆ interior d, from calc s ⊆ t : hst ... ⊆ interior d : (subset_interior_iff_subset_of_open ht).mpr $ assume x, assume : x ∈ t, let ⟨x, y, h₁, h₂, h₃⟩ := ht_comp this in hs_comp ⟨x, h₁, y, h₂, h₃⟩, have interior d ∈ 𝓤 α, by filter_upwards [hs] this, by simp [this]) (assume s hs, ((𝓤 α).lift' interior).sets_of_superset (mem_lift' hs) interior_subset) lemma interior_mem_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) : interior s ∈ 𝓤 α := by rw [uniformity_eq_uniformity_interior]; exact mem_lift' hs lemma mem_uniformity_is_closed {s : set (α×α)} (h : s ∈ 𝓤 α) : ∃t ∈ 𝓤 α, is_closed t ∧ t ⊆ s := have s ∈ (𝓤 α).lift' closure, by rwa [uniformity_eq_uniformity_closure] at h, have ∃ t ∈ 𝓤 α, closure t ⊆ s, by rwa [mem_lift'_sets] at this; apply closure_mono, let ⟨t, ht, hst⟩ := this in ⟨closure t, (𝓤 α).sets_of_superset ht subset_closure, is_closed_closure, hst⟩ /-! ### Uniformity bases -/ lemma filter.has_basis.mem_uniformity_iff {p : β → Prop} {s : β → set (α×α)} (h : (𝓤 α).has_basis p s) {t : set (α × α)} : t ∈ 𝓤 α ↔ ∃ i (hi : p i), ∀ a b, (a, b) ∈ s i → (a, b) ∈ t := h.mem_iff.trans $ by simp only [prod.forall, subset_def] /-- Symmetric entourages form a basis of `𝓤 α` -/ lemma uniform_space.has_basis_symmetric : (𝓤 α).has_basis (λ s : set (α × α), s ∈ 𝓤 α ∧ symmetric_rel s) id := ⟨λ t, ⟨λ t_in, ⟨symmetrize_rel t, ⟨⟨symmetrize_mem_uniformity t_in, symmetric_symmetrize_rel t⟩, symmetrize_rel_subset_self _⟩⟩, λ ⟨s, ⟨s_in, h⟩, hst⟩, mem_sets_of_superset s_in hst⟩⟩ lemma uniform_space.has_seq_basis (h : is_countably_generated $ 𝓤 α) : ∃ V : ℕ → set (α × α), has_antimono_basis (𝓤 α) (λ _, true) V ∧ ∀ n, symmetric_rel (V n) := begin rcases h.has_antimono_basis with ⟨U, hbasis, hdec, monotrue⟩, clear monotrue, simp only [forall_prop_of_true] at hdec, use λ n, symmetrize_rel (U n), refine ⟨⟨⟨_⟩, by intros ; mono, by tauto⟩, λ n, symmetric_symmetrize_rel _⟩, intros t, rw hbasis.mem_iff, split, { rintro ⟨i, _, hi⟩, exact ⟨i, trivial, subset.trans (inter_subset_left _ _) hi⟩ }, { rintro ⟨i, _, hi⟩, rcases hbasis.mem_iff.mp (symmetrize_mem_uniformity $ hbasis.mem_of_mem trivial) with ⟨j, _, hj⟩, use j, tauto } end /-! ### Uniform continuity -/ /-- A function `f : α → β` is *uniformly continuous* if `(f x, f y)` tends to the diagonal as `(x, y)` tends to the diagonal. In other words, if `x` is sufficiently close to `y`, then `f x` is close to `f y` no matter where `x` and `y` are located in `α`. -/ def uniform_continuous [uniform_space β] (f : α → β) := tendsto (λx:α×α, (f x.1, f x.2)) (𝓤 α) (𝓤 β) theorem uniform_continuous_def [uniform_space β] {f : α → β} : uniform_continuous f ↔ ∀ r ∈ 𝓤 β, { x : α × α | (f x.1, f x.2) ∈ r} ∈ 𝓤 α := iff.rfl theorem uniform_continuous_iff_eventually [uniform_space β] {f : α → β} : uniform_continuous f ↔ ∀ r ∈ 𝓤 β, ∀ᶠ (x : α × α) in 𝓤 α, (f x.1, f x.2) ∈ r := iff.rfl lemma uniform_continuous_of_const [uniform_space β] {c : α → β} (h : ∀a b, c a = c b) : uniform_continuous c := have (λ (x : α × α), (c (x.fst), c (x.snd))) ⁻¹' id_rel = univ, from eq_univ_iff_forall.2 $ assume ⟨a, b⟩, h a b, le_trans (map_le_iff_le_comap.2 $ by simp [comap_principal, this, univ_mem_sets]) refl_le_uniformity lemma uniform_continuous_id : uniform_continuous (@id α) := by simp [uniform_continuous]; exact tendsto_id lemma uniform_continuous_const [uniform_space β] {b : β} : uniform_continuous (λa:α, b) := uniform_continuous_of_const $ λ _ _, rfl lemma uniform_continuous.comp [uniform_space β] [uniform_space γ] {g : β → γ} {f : α → β} (hg : uniform_continuous g) (hf : uniform_continuous f) : uniform_continuous (g ∘ f) := hg.comp hf lemma filter.has_basis.uniform_continuous_iff [uniform_space β] {p : γ → Prop} {s : γ → set (α×α)} (ha : (𝓤 α).has_basis p s) {q : δ → Prop} {t : δ → set (β×β)} (hb : (𝓤 β).has_basis q t) {f : α → β} : uniform_continuous f ↔ ∀ i (hi : q i), ∃ j (hj : p j), ∀ x y, (x, y) ∈ s j → (f x, f y) ∈ t i := (ha.tendsto_iff hb).trans $ by simp only [prod.forall] end uniform_space open_locale uniformity section constructions instance : partial_order (uniform_space α) := { le := λt s, t.uniformity ≤ s.uniformity, le_antisymm := assume t s h₁ h₂, uniform_space_eq $ le_antisymm h₁ h₂, le_refl := assume t, le_refl _, le_trans := assume a b c h₁ h₂, le_trans h₁ h₂ } instance : has_Inf (uniform_space α) := ⟨assume s, uniform_space.of_core { uniformity := (⨅u∈s, @uniformity α u), refl := le_infi $ assume u, le_infi $ assume hu, u.refl, symm := le_infi $ assume u, le_infi $ assume hu, le_trans (map_mono $ infi_le_of_le _ $ infi_le _ hu) u.symm, comp := le_infi $ assume u, le_infi $ assume hu, le_trans (lift'_mono (infi_le_of_le _ $ infi_le _ hu) $ le_refl _) u.comp }⟩ private lemma Inf_le {tt : set (uniform_space α)} {t : uniform_space α} (h : t ∈ tt) : Inf tt ≤ t := show (⨅u∈tt, @uniformity α u) ≤ t.uniformity, from infi_le_of_le t $ infi_le _ h private lemma le_Inf {tt : set (uniform_space α)} {t : uniform_space α} (h : ∀t'∈tt, t ≤ t') : t ≤ Inf tt := show t.uniformity ≤ (⨅u∈tt, @uniformity α u), from le_infi $ assume t', le_infi $ assume ht', h t' ht' instance : has_top (uniform_space α) := ⟨uniform_space.of_core { uniformity := ⊤, refl := le_top, symm := le_top, comp := le_top }⟩ instance : has_bot (uniform_space α) := ⟨{ to_topological_space := ⊥, uniformity := principal id_rel, refl := le_refl _, symm := by simp [tendsto]; apply subset.refl, comp := begin rw [lift'_principal], {simp}, exact monotone_comp_rel monotone_id monotone_id end, is_open_uniformity := assume s, by simp [is_open_fold, subset_def, id_rel] {contextual := tt } } ⟩ instance : complete_lattice (uniform_space α) := { sup := λa b, Inf {x | a ≤ x ∧ b ≤ x}, le_sup_left := λ a b, le_Inf (λ _ ⟨h, _⟩, h), le_sup_right := λ a b, le_Inf (λ _ ⟨_, h⟩, h), sup_le := λ a b c h₁ h₂, Inf_le ⟨h₁, h₂⟩, inf := λ a b, Inf {a, b}, le_inf := λ a b c h₁ h₂, le_Inf (λ u h, by { cases h, exact h.symm ▸ h₁, exact (mem_singleton_iff.1 h).symm ▸ h₂ }), inf_le_left := λ a b, Inf_le (by simp), inf_le_right := λ a b, Inf_le (by simp), top := ⊤, le_top := λ a, show a.uniformity ≤ ⊤, from le_top, bot := ⊥, bot_le := λ u, u.refl, Sup := λ tt, Inf {t | ∀ t' ∈ tt, t' ≤ t}, le_Sup := λ s u h, le_Inf (λ u' h', h' u h), Sup_le := λ s u h, Inf_le h, Inf := Inf, le_Inf := λ s a hs, le_Inf hs, Inf_le := λ s a ha, Inf_le ha, ..uniform_space.partial_order } lemma infi_uniformity {ι : Sort*} {u : ι → uniform_space α} : (infi u).uniformity = (⨅i, (u i).uniformity) := show (⨅a (h : ∃i:ι, u i = a), a.uniformity) = _, from le_antisymm (le_infi $ assume i, infi_le_of_le (u i) $ infi_le _ ⟨i, rfl⟩) (le_infi $ assume a, le_infi $ assume ⟨i, (ha : u i = a)⟩, ha ▸ infi_le _ _) lemma inf_uniformity {u v : uniform_space α} : (u ⊓ v).uniformity = u.uniformity ⊓ v.uniformity := have (u ⊓ v) = (⨅i (h : i = u ∨ i = v), i), by simp [infi_or, infi_inf_eq], calc (u ⊓ v).uniformity = ((⨅i (h : i = u ∨ i = v), i) : uniform_space α).uniformity : by rw [this] ... = _ : by simp [infi_uniformity, infi_or, infi_inf_eq] instance inhabited_uniform_space : inhabited (uniform_space α) := ⟨⊥⟩ instance inhabited_uniform_space_core : inhabited (uniform_space.core α) := ⟨@uniform_space.to_core _ (default _)⟩ /-- Given `f : α → β` and a uniformity `u` on `β`, the inverse image of `u` under `f` is the inverse image in the filter sense of the induced function `α × α → β × β`. -/ def uniform_space.comap (f : α → β) (u : uniform_space β) : uniform_space α := { uniformity := u.uniformity.comap (λp:α×α, (f p.1, f p.2)), to_topological_space := u.to_topological_space.induced f, refl := le_trans (by simp; exact assume ⟨a, b⟩ (h : a = b), h ▸ rfl) (comap_mono u.refl), symm := by simp [tendsto_comap_iff, prod.swap, (∘)]; exact tendsto_swap_uniformity.comp tendsto_comap, comp := le_trans begin rw [comap_lift'_eq, comap_lift'_eq2], exact (lift'_mono' $ assume s hs ⟨a₁, a₂⟩ ⟨x, h₁, h₂⟩, ⟨f x, h₁, h₂⟩), repeat { exact monotone_comp_rel monotone_id monotone_id } end (comap_mono u.comp), is_open_uniformity := λ s, begin change (@is_open α (u.to_topological_space.induced f) s ↔ _), simp [is_open_iff_nhds, nhds_induced, mem_nhds_uniformity_iff_right, filter.comap, and_comm], refine ball_congr (λ x hx, ⟨_, _⟩), { rintro ⟨t, hts, ht⟩, refine ⟨_, ht, _⟩, rintro ⟨x₁, x₂⟩ h rfl, exact hts (h rfl) }, { rintro ⟨t, ht, hts⟩, exact ⟨{y | (f x, y) ∈ t}, λ y hy, @hts (x, y) hy rfl, mem_nhds_uniformity_iff_right.1 $ mem_nhds_left _ ht⟩ } end } lemma uniform_space_comap_id {α : Type*} : uniform_space.comap (id : α → α) = id := by ext u ; dsimp [uniform_space.comap] ; rw [prod.id_prod, filter.comap_id] lemma uniform_space.comap_comap_comp {α β γ} [uγ : uniform_space γ] {f : α → β} {g : β → γ} : uniform_space.comap (g ∘ f) uγ = uniform_space.comap f (uniform_space.comap g uγ) := by ext ; dsimp [uniform_space.comap] ; rw filter.comap_comap_comp lemma uniform_continuous_iff {α β} [uα : uniform_space α] [uβ : uniform_space β] {f : α → β} : uniform_continuous f ↔ uα ≤ uβ.comap f := filter.map_le_iff_le_comap lemma uniform_continuous_comap {f : α → β} [u : uniform_space β] : @uniform_continuous α β (uniform_space.comap f u) u f := tendsto_comap theorem to_topological_space_comap {f : α → β} {u : uniform_space β} : @uniform_space.to_topological_space _ (uniform_space.comap f u) = topological_space.induced f (@uniform_space.to_topological_space β u) := rfl lemma uniform_continuous_comap' {f : γ → β} {g : α → γ} [v : uniform_space β] [u : uniform_space α] (h : uniform_continuous (f ∘ g)) : @uniform_continuous α γ u (uniform_space.comap f v) g := tendsto_comap_iff.2 h lemma to_topological_space_mono {u₁ u₂ : uniform_space α} (h : u₁ ≤ u₂) : @uniform_space.to_topological_space _ u₁ ≤ @uniform_space.to_topological_space _ u₂ := le_of_nhds_le_nhds $ assume a, by rw [@nhds_eq_uniformity α u₁ a, @nhds_eq_uniformity α u₂ a]; exact (lift'_mono h $ le_refl _) lemma uniform_continuous.continuous [uniform_space α] [uniform_space β] {f : α → β} (hf : uniform_continuous f) : continuous f := continuous_iff_le_induced.mpr $ to_topological_space_mono $ uniform_continuous_iff.1 hf lemma to_topological_space_bot : @uniform_space.to_topological_space α ⊥ = ⊥ := rfl lemma to_topological_space_top : @uniform_space.to_topological_space α ⊤ = ⊤ := top_unique $ assume s hs, s.eq_empty_or_nonempty.elim (assume : s = ∅, this.symm ▸ @is_open_empty _ ⊤) (assume ⟨x, hx⟩, have s = univ, from top_unique $ assume y hy, hs x hx (x, y) rfl, this.symm ▸ @is_open_univ _ ⊤) lemma to_topological_space_infi {ι : Sort*} {u : ι → uniform_space α} : (infi u).to_topological_space = ⨅i, (u i).to_topological_space := classical.by_cases (assume h : nonempty ι, eq_of_nhds_eq_nhds $ assume a, begin rw [nhds_infi, nhds_eq_uniformity], change (infi u).uniformity.lift' (preimage $ prod.mk a) = _, begin rw [infi_uniformity, lift'_infi], exact (congr_arg _ $ funext $ assume i, (@nhds_eq_uniformity α (u i) a).symm), exact h, exact assume a b, rfl end end) (assume : ¬ nonempty ι, le_antisymm (le_infi $ assume i, to_topological_space_mono $ infi_le _ _) (have infi u = ⊤, from top_unique $ le_infi $ assume i, (this ⟨i⟩).elim, have @uniform_space.to_topological_space _ (infi u) = ⊤, from this.symm ▸ to_topological_space_top, this.symm ▸ le_top)) lemma to_topological_space_Inf {s : set (uniform_space α)} : (Inf s).to_topological_space = (⨅i∈s, @uniform_space.to_topological_space α i) := begin rw [Inf_eq_infi, to_topological_space_infi], apply congr rfl, funext x, exact to_topological_space_infi end lemma to_topological_space_inf {u v : uniform_space α} : (u ⊓ v).to_topological_space = u.to_topological_space ⊓ v.to_topological_space := by rw [to_topological_space_Inf, infi_pair] instance : uniform_space empty := ⊥ instance : uniform_space unit := ⊥ instance : uniform_space bool := ⊥ instance : uniform_space ℕ := ⊥ instance : uniform_space ℤ := ⊥ instance {p : α → Prop} [t : uniform_space α] : uniform_space (subtype p) := uniform_space.comap subtype.val t lemma uniformity_subtype {p : α → Prop} [t : uniform_space α] : 𝓤 (subtype p) = comap (λq:subtype p × subtype p, (q.1.1, q.2.1)) (𝓤 α) := rfl lemma uniform_continuous_subtype_val {p : α → Prop} [uniform_space α] : uniform_continuous (subtype.val : {a : α // p a} → α) := uniform_continuous_comap lemma uniform_continuous_subtype_mk {p : α → Prop} [uniform_space α] [uniform_space β] {f : β → α} (hf : uniform_continuous f) (h : ∀x, p (f x)) : uniform_continuous (λx, ⟨f x, h x⟩ : β → subtype p) := uniform_continuous_comap' hf lemma tendsto_of_uniform_continuous_subtype [uniform_space α] [uniform_space β] {f : α → β} {s : set α} {a : α} (hf : uniform_continuous (λx:s, f x.val)) (ha : s ∈ 𝓝 a) : tendsto f (𝓝 a) (𝓝 (f a)) := by rw [(@map_nhds_subtype_val_eq α _ s a (mem_of_nhds ha) ha).symm]; exact tendsto_map' (continuous_iff_continuous_at.mp hf.continuous _) section prod /- a similar product space is possible on the function space (uniformity of pointwise convergence), but we want to have the uniformity of uniform convergence on function spaces -/ instance [u₁ : uniform_space α] [u₂ : uniform_space β] : uniform_space (α × β) := uniform_space.of_core_eq (u₁.comap prod.fst ⊓ u₂.comap prod.snd).to_core prod.topological_space (calc prod.topological_space = (u₁.comap prod.fst ⊓ u₂.comap prod.snd).to_topological_space : by rw [to_topological_space_inf, to_topological_space_comap, to_topological_space_comap]; refl ... = _ : by rw [uniform_space.to_core_to_topological_space]) theorem uniformity_prod [uniform_space α] [uniform_space β] : 𝓤 (α × β) = (𝓤 α).comap (λp:(α × β) × α × β, (p.1.1, p.2.1)) ⊓ (𝓤 β).comap (λp:(α × β) × α × β, (p.1.2, p.2.2)) := inf_uniformity lemma uniformity_prod_eq_prod [uniform_space α] [uniform_space β] : 𝓤 (α×β) = map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) (filter.prod (𝓤 α) (𝓤 β)) := have map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) = comap (λp:(α×β)×(α×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))), from funext $ assume f, map_eq_comap_of_inverse (funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl) (funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl), by rw [this, uniformity_prod, filter.prod, comap_inf, comap_comap_comp, comap_comap_comp] lemma mem_map_sets_iff' {α : Type*} {β : Type*} {f : filter α} {m : α → β} {t : set β} : t ∈ (map m f).sets ↔ (∃s∈f, m '' s ⊆ t) := mem_map_sets_iff lemma mem_uniformity_of_uniform_continuous_invariant [uniform_space α] {s:set (α×α)} {f : α → α → α} (hf : uniform_continuous (λp:α×α, f p.1 p.2)) (hs : s ∈ 𝓤 α) : ∃u∈𝓤 α, ∀a b c, (a, b) ∈ u → (f a c, f b c) ∈ s := begin rw [uniform_continuous, uniformity_prod_eq_prod, tendsto_map'_iff, (∘)] at hf, rcases mem_map_sets_iff'.1 (hf hs) with ⟨t, ht, hts⟩, clear hf, rcases mem_prod_iff.1 ht with ⟨u, hu, v, hv, huvt⟩, clear ht, refine ⟨u, hu, assume a b c hab, hts $ (mem_image _ _ _).2 ⟨⟨⟨a, b⟩, ⟨c, c⟩⟩, huvt ⟨_, _⟩, _⟩⟩, exact hab, exact refl_mem_uniformity hv, refl end lemma mem_uniform_prod [t₁ : uniform_space α] [t₂ : uniform_space β] {a : set (α × α)} {b : set (β × β)} (ha : a ∈ 𝓤 α) (hb : b ∈ 𝓤 β) : {p:(α×β)×(α×β) | (p.1.1, p.2.1) ∈ a ∧ (p.1.2, p.2.2) ∈ b } ∈ (@uniformity (α × β) _) := by rw [uniformity_prod]; exact inter_mem_inf_sets (preimage_mem_comap ha) (preimage_mem_comap hb) lemma tendsto_prod_uniformity_fst [uniform_space α] [uniform_space β] : tendsto (λp:(α×β)×(α×β), (p.1.1, p.2.1)) (𝓤 (α × β)) (𝓤 α) := le_trans (map_mono (@inf_le_left (uniform_space (α×β)) _ _ _)) map_comap_le lemma tendsto_prod_uniformity_snd [uniform_space α] [uniform_space β] : tendsto (λp:(α×β)×(α×β), (p.1.2, p.2.2)) (𝓤 (α × β)) (𝓤 β) := le_trans (map_mono (@inf_le_right (uniform_space (α×β)) _ _ _)) map_comap_le lemma uniform_continuous_fst [uniform_space α] [uniform_space β] : uniform_continuous (λp:α×β, p.1) := tendsto_prod_uniformity_fst lemma uniform_continuous_snd [uniform_space α] [uniform_space β] : uniform_continuous (λp:α×β, p.2) := tendsto_prod_uniformity_snd variables [uniform_space α] [uniform_space β] [uniform_space γ] lemma uniform_continuous.prod_mk {f₁ : α → β} {f₂ : α → γ} (h₁ : uniform_continuous f₁) (h₂ : uniform_continuous f₂) : uniform_continuous (λa, (f₁ a, f₂ a)) := by rw [uniform_continuous, uniformity_prod]; exact tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩ lemma uniform_continuous.prod_mk_left {f : α × β → γ} (h : uniform_continuous f) (b) : uniform_continuous (λ a, f (a,b)) := h.comp (uniform_continuous_id.prod_mk uniform_continuous_const) lemma uniform_continuous.prod_mk_right {f : α × β → γ} (h : uniform_continuous f) (a) : uniform_continuous (λ b, f (a,b)) := h.comp (uniform_continuous_const.prod_mk uniform_continuous_id) lemma uniform_continuous.prod_map [uniform_space δ] {f : α → γ} {g : β → δ} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (prod.map f g) := (hf.comp uniform_continuous_fst).prod_mk (hg.comp uniform_continuous_snd) lemma to_topological_space_prod {α} {β} [u : uniform_space α] [v : uniform_space β] : @uniform_space.to_topological_space (α × β) prod.uniform_space = @prod.topological_space α β u.to_topological_space v.to_topological_space := rfl end prod section open uniform_space function variables {δ' : Type*} [uniform_space α] [uniform_space β] [uniform_space γ] [uniform_space δ] [uniform_space δ'] local notation f `∘₂` g := function.bicompr f g /-- Uniform continuity for functions of two variables. -/ def uniform_continuous₂ (f : α → β → γ) := uniform_continuous (uncurry f) lemma uniform_continuous₂_def (f : α → β → γ) : uniform_continuous₂ f ↔ uniform_continuous (uncurry f) := iff.rfl lemma uniform_continuous₂.uniform_continuous {f : α → β → γ} (h : uniform_continuous₂ f) : uniform_continuous (uncurry f) := h lemma uniform_continuous₂_curry (f : α × β → γ) : uniform_continuous₂ (function.curry f) ↔ uniform_continuous f := by rw [uniform_continuous₂, uncurry_curry] lemma uniform_continuous₂.comp {f : α → β → γ} {g : γ → δ} (hg : uniform_continuous g) (hf : uniform_continuous₂ f) : uniform_continuous₂ (g ∘₂ f) := hg.comp hf lemma uniform_continuous₂.bicompl {f : α → β → γ} {ga : δ → α} {gb : δ' → β} (hf : uniform_continuous₂ f) (hga : uniform_continuous ga) (hgb : uniform_continuous gb) : uniform_continuous₂ (bicompl f ga gb) := hf.uniform_continuous.comp (hga.prod_map hgb) end lemma to_topological_space_subtype [u : uniform_space α] {p : α → Prop} : @uniform_space.to_topological_space (subtype p) subtype.uniform_space = @subtype.topological_space α p u.to_topological_space := rfl section sum variables [uniform_space α] [uniform_space β] open sum /-- Uniformity on a disjoint union. Entourages of the diagonal in the union are obtained by taking independently an entourage of the diagonal in the first part, and an entourage of the diagonal in the second part. -/ def uniform_space.core.sum : uniform_space.core (α ⊕ β) := uniform_space.core.mk' (map (λ p : α × α, (inl p.1, inl p.2)) (𝓤 α) ⊔ map (λ p : β × β, (inr p.1, inr p.2)) (𝓤 β)) (λ r ⟨H₁, H₂⟩ x, by cases x; [apply refl_mem_uniformity H₁, apply refl_mem_uniformity H₂]) (λ r ⟨H₁, H₂⟩, ⟨symm_le_uniformity H₁, symm_le_uniformity H₂⟩) (λ r ⟨Hrα, Hrβ⟩, begin rcases comp_mem_uniformity_sets Hrα with ⟨tα, htα, Htα⟩, rcases comp_mem_uniformity_sets Hrβ with ⟨tβ, htβ, Htβ⟩, refine ⟨_, ⟨mem_map_sets_iff.2 ⟨tα, htα, subset_union_left _ _⟩, mem_map_sets_iff.2 ⟨tβ, htβ, subset_union_right _ _⟩⟩, _⟩, rintros ⟨_, _⟩ ⟨z, ⟨⟨a, b⟩, hab, ⟨⟩⟩ | ⟨⟨a, b⟩, hab, ⟨⟩⟩, ⟨⟨_, c⟩, hbc, ⟨⟩⟩ | ⟨⟨_, c⟩, hbc, ⟨⟩⟩⟩, { have A : (a, c) ∈ tα ○ tα := ⟨b, hab, hbc⟩, exact Htα A }, { have A : (a, c) ∈ tβ ○ tβ := ⟨b, hab, hbc⟩, exact Htβ A } end) /-- The union of an entourage of the diagonal in each set of a disjoint union is again an entourage of the diagonal. -/ lemma union_mem_uniformity_sum {a : set (α × α)} (ha : a ∈ 𝓤 α) {b : set (β × β)} (hb : b ∈ 𝓤 β) : ((λ p : (α × α), (inl p.1, inl p.2)) '' a ∪ (λ p : (β × β), (inr p.1, inr p.2)) '' b) ∈ (@uniform_space.core.sum α β _ _).uniformity := ⟨mem_map_sets_iff.2 ⟨_, ha, subset_union_left _ _⟩, mem_map_sets_iff.2 ⟨_, hb, subset_union_right _ _⟩⟩ /- To prove that the topology defined by the uniform structure on the disjoint union coincides with the disjoint union topology, we need two lemmas saying that open sets can be characterized by the uniform structure -/ lemma uniformity_sum_of_open_aux {s : set (α ⊕ β)} (hs : is_open s) {x : α ⊕ β} (xs : x ∈ s) : { p : ((α ⊕ β) × (α ⊕ β)) | p.1 = x → p.2 ∈ s } ∈ (@uniform_space.core.sum α β _ _).uniformity := begin cases x, { refine mem_sets_of_superset (union_mem_uniformity_sum (mem_nhds_uniformity_iff_right.1 (mem_nhds_sets hs.1 xs)) univ_mem_sets) (union_subset _ _); rintro _ ⟨⟨_, b⟩, h, ⟨⟩⟩ ⟨⟩, exact h rfl }, { refine mem_sets_of_superset (union_mem_uniformity_sum univ_mem_sets (mem_nhds_uniformity_iff_right.1 (mem_nhds_sets hs.2 xs))) (union_subset _ _); rintro _ ⟨⟨a, _⟩, h, ⟨⟩⟩ ⟨⟩, exact h rfl }, end lemma open_of_uniformity_sum_aux {s : set (α ⊕ β)} (hs : ∀x ∈ s, { p : ((α ⊕ β) × (α ⊕ β)) | p.1 = x → p.2 ∈ s } ∈ (@uniform_space.core.sum α β _ _).uniformity) : is_open s := begin split, { refine (@is_open_iff_mem_nhds α _ _).2 (λ a ha, mem_nhds_uniformity_iff_right.2 _), rcases mem_map_sets_iff.1 (hs _ ha).1 with ⟨t, ht, st⟩, refine mem_sets_of_superset ht _, rintro p pt rfl, exact st ⟨_, pt, rfl⟩ rfl }, { refine (@is_open_iff_mem_nhds β _ _).2 (λ b hb, mem_nhds_uniformity_iff_right.2 _), rcases mem_map_sets_iff.1 (hs _ hb).2 with ⟨t, ht, st⟩, refine mem_sets_of_superset ht _, rintro p pt rfl, exact st ⟨_, pt, rfl⟩ rfl } end /- We can now define the uniform structure on the disjoint union -/ instance sum.uniform_space : uniform_space (α ⊕ β) := { to_core := uniform_space.core.sum, is_open_uniformity := λ s, ⟨uniformity_sum_of_open_aux, open_of_uniformity_sum_aux⟩ } lemma sum.uniformity : 𝓤 (α ⊕ β) = map (λ p : α × α, (inl p.1, inl p.2)) (𝓤 α) ⊔ map (λ p : β × β, (inr p.1, inr p.2)) (𝓤 β) := rfl end sum end constructions -- For a version of the Lebesgue number lemma assuming only a sequentially compact space, -- see topology/sequences.lean lemma lebesgue_number_lemma {α : Type u} [uniform_space α] {s : set α} {ι} {c : ι → set α} (hs : compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) : ∃ n ∈ 𝓤 α, ∀ x ∈ s, ∃ i, {y | (x, y) ∈ n} ⊆ c i := begin let u := λ n, {x | ∃ i (m ∈ 𝓤 α), {y | (x, y) ∈ m ○ n} ⊆ c i}, have hu₁ : ∀ n ∈ 𝓤 α, is_open (u n), { refine λ n hn, is_open_uniformity.2 _, rintro x ⟨i, m, hm, h⟩, rcases comp_mem_uniformity_sets hm with ⟨m', hm', mm'⟩, apply (𝓤 α).sets_of_superset hm', rintros ⟨x, y⟩ hp rfl, refine ⟨i, m', hm', λ z hz, h (monotone_comp_rel monotone_id monotone_const mm' _)⟩, dsimp at hz ⊢, rw comp_rel_assoc, exact ⟨y, hp, hz⟩ }, have hu₂ : s ⊆ ⋃ n ∈ 𝓤 α, u n, { intros x hx, rcases mem_Union.1 (hc₂ hx) with ⟨i, h⟩, rcases comp_mem_uniformity_sets (is_open_uniformity.1 (hc₁ i) x h) with ⟨m', hm', mm'⟩, exact mem_bUnion hm' ⟨i, _, hm', λ y hy, mm' hy rfl⟩ }, rcases hs.elim_finite_subcover_image hu₁ hu₂ with ⟨b, bu, b_fin, b_cover⟩, refine ⟨_, Inter_mem_sets b_fin bu, λ x hx, _⟩, rcases mem_bUnion_iff.1 (b_cover hx) with ⟨n, bn, i, m, hm, h⟩, refine ⟨i, λ y hy, h _⟩, exact prod_mk_mem_comp_rel (refl_mem_uniformity hm) (bInter_subset_of_mem bn hy) end lemma lebesgue_number_lemma_sUnion {α : Type u} [uniform_space α] {s : set α} {c : set (set α)} (hs : compact s) (hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) : ∃ n ∈ 𝓤 α, ∀ x ∈ s, ∃ t ∈ c, ∀ y, (x, y) ∈ n → y ∈ t := by rw sUnion_eq_Union at hc₂; simpa using lebesgue_number_lemma hs (by simpa) hc₂ /-! ### Expressing continuity properties in uniform spaces We reformulate the various continuity properties of functions taking values in a uniform space in terms of the uniformity in the target. Since the same lemmas (essentially with the same names) also exist for metric spaces and emetric spaces (reformulating things in terms of the distance or the edistance in the target), we put them in a namespace `uniform` here. In the metric and emetric space setting, there are also similar lemmas where one assumes that both the source and the target are metric spaces, reformulating things in terms of the distance on both sides. These lemmas are generally written without primes, and the versions where only the target is a metric space is primed. We follow the same convention here, thus giving lemmas with primes. -/ namespace uniform variables [uniform_space α] theorem tendsto_nhds_right {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ tendsto (λ x, (a, u x)) f (𝓤 α) := ⟨λ H, tendsto_left_nhds_uniformity.comp H, λ H s hs, by simpa [mem_of_nhds hs] using H (mem_nhds_uniformity_iff_right.1 hs)⟩ theorem tendsto_nhds_left {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ tendsto (λ x, (u x, a)) f (𝓤 α) := ⟨λ H, tendsto_right_nhds_uniformity.comp H, λ H s hs, by simpa [mem_of_nhds hs] using H (mem_nhds_uniformity_iff_left.1 hs)⟩ theorem continuous_at_iff'_right [topological_space β] {f : β → α} {b : β} : continuous_at f b ↔ tendsto (λ x, (f b, f x)) (𝓝 b) (𝓤 α) := by rw [continuous_at, tendsto_nhds_right] theorem continuous_at_iff'_left [topological_space β] {f : β → α} {b : β} : continuous_at f b ↔ tendsto (λ x, (f x, f b)) (𝓝 b) (𝓤 α) := by rw [continuous_at, tendsto_nhds_left] theorem continuous_within_at_iff'_right [topological_space β] {f : β → α} {b : β} {s : set β} : continuous_within_at f s b ↔ tendsto (λ x, (f b, f x)) (nhds_within b s) (𝓤 α) := by rw [continuous_within_at, tendsto_nhds_right] theorem continuous_within_at_iff'_left [topological_space β] {f : β → α} {b : β} {s : set β} : continuous_within_at f s b ↔ tendsto (λ x, (f x, f b)) (nhds_within b s) (𝓤 α) := by rw [continuous_within_at, tendsto_nhds_left] theorem continuous_on_iff'_right [topological_space β] {f : β → α} {s : set β} : continuous_on f s ↔ ∀ b ∈ s, tendsto (λ x, (f b, f x)) (nhds_within b s) (𝓤 α) := by simp [continuous_on, continuous_within_at_iff'_right] theorem continuous_on_iff'_left [topological_space β] {f : β → α} {s : set β} : continuous_on f s ↔ ∀ b ∈ s, tendsto (λ x, (f x, f b)) (nhds_within b s) (𝓤 α) := by simp [continuous_on, continuous_within_at_iff'_left] theorem continuous_iff'_right [topological_space β] {f : β → α} : continuous f ↔ ∀ b, tendsto (λ x, (f b, f x)) (𝓝 b) (𝓤 α) := continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_right theorem continuous_iff'_left [topological_space β] {f : β → α} : continuous f ↔ ∀ b, tendsto (λ x, (f x, f b)) (𝓝 b) (𝓤 α) := continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_left end uniform lemma filter.tendsto.congr_uniformity {α β} [uniform_space β] {f g : α → β} {l : filter α} {b : β} (hf : tendsto f l (𝓝 b)) (hg : tendsto (λ x, (f x, g x)) l (𝓤 β)) : tendsto g l (𝓝 b) := uniform.tendsto_nhds_right.2 $ (uniform.tendsto_nhds_right.1 hf).uniformity_trans hg lemma uniform.tendsto_congr {α β} [uniform_space β] {f g : α → β} {l : filter α} {b : β} (hfg : tendsto (λ x, (f x, g x)) l (𝓤 β)) : tendsto f l (𝓝 b) ↔ tendsto g l (𝓝 b) := ⟨λ h, h.congr_uniformity hfg, λ h, h.congr_uniformity hfg.uniformity_symm⟩
fb445251415db20a1c3c6e8ef7d3f19f3f995f2a
bb31430994044506fa42fd667e2d556327e18dfe
/src/linear_algebra/affine_space/basis.lean
56ad63b78851ce8a45f31bdde7566ed422b3b6b9
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
10,345
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 linear_algebra.affine_space.independent import linear_algebra.basis /-! # Affine bases and barycentric coordinates Suppose `P` is an affine space modelled on the module `V` over the ring `k`, and `p : ι → P` is an affine-independent family of points spanning `P`. Given this data, each point `q : P` may be written uniquely as an affine combination: `q = w₀ p₀ + w₁ p₁ + ⋯` for some (finitely-supported) weights `wᵢ`. For each `i : ι`, we thus have an affine map `P →ᵃ[k] k`, namely `q ↦ wᵢ`. This family of maps is known as the family of barycentric coordinates. It is defined in this file. ## The construction Fixing `i : ι`, and allowing `j : ι` to range over the values `j ≠ i`, we obtain a basis `bᵢ` of `V` defined by `bᵢ j = p j -ᵥ p i`. Let `fᵢ j : V →ₗ[k] k` be the corresponding dual basis and let `fᵢ = ∑ j, fᵢ j : V →ₗ[k] k` be the corresponding "sum of all coordinates" form. Then the `i`th barycentric coordinate of `q : P` is `1 - fᵢ (q -ᵥ p i)`. ## Main definitions * `affine_basis`: a structure representing an affine basis of an affine space. * `affine_basis.coord`: the map `P →ᵃ[k] k` corresponding to `i : ι`. * `affine_basis.coord_apply_eq`: the behaviour of `affine_basis.coord i` on `p i`. * `affine_basis.coord_apply_neq`: the behaviour of `affine_basis.coord i` on `p j` when `j ≠ i`. * `affine_basis.coord_apply`: the behaviour of `affine_basis.coord i` on `p j` for general `j`. * `affine_basis.coord_apply_combination`: the characterisation of `affine_basis.coord i` in terms of affine combinations, i.e., `affine_basis.coord i (w₀ p₀ + w₁ p₁ + ⋯) = wᵢ`. ## TODO * Construct the affine equivalence between `P` and `{ f : ι →₀ k | f.sum = 1 }`. -/ open_locale affine big_operators open set universes u₁ u₂ u₃ u₄ /-- An affine basis is a family of affine-independent points whose span is the top subspace. -/ structure affine_basis (ι : Type u₁) (k : Type u₂) {V : Type u₃} (P : Type u₄) [add_comm_group V] [affine_space V P] [ring k] [module k V] := (points : ι → P) (ind : affine_independent k points) (tot : affine_span k (range points) = ⊤) variables {ι : Type u₁} {k : Type u₂} {V : Type u₃} {P : Type u₄} variables [add_comm_group V] [affine_space V P] namespace affine_basis section ring variables [ring k] [module k V] (b : affine_basis ι k P) /-- The unique point in a single-point space is the simplest example of an affine basis. -/ instance : inhabited (affine_basis punit k punit) := ⟨{ points := id, ind := affine_independent_of_subsingleton k id, tot := by simp }⟩ include b protected lemma nonempty : nonempty ι := not_is_empty_iff.mp $ λ hι, by simpa only [@range_eq_empty _ _ hι, affine_subspace.span_empty, bot_ne_top] using b.tot /-- Composition of an affine basis and an equivalence of index types. -/ def comp_equiv {ι'} (e : ι' ≃ ι) : affine_basis ι' k P := ⟨b.points ∘ e, b.ind.comp_embedding e.to_embedding, by { rw [e.surjective.range_comp], exact b.3 }⟩ /-- Given an affine basis for an affine space `P`, if we single out one member of the family, we obtain a linear basis for the model space `V`. The linear basis correpsonding to the singled-out member `i : ι` is indexed by `{j : ι // j ≠ i}` and its `j`th element is `points j -ᵥ points i`. (See `basis_of_apply`.) -/ noncomputable def basis_of (i : ι) : basis {j : ι // j ≠ i} k V := basis.mk ((affine_independent_iff_linear_independent_vsub k b.points i).mp b.ind) begin suffices : submodule.span k (range (λ (j : {x // x ≠ i}), b.points ↑j -ᵥ b.points i)) = vector_span k (range b.points), { rw [this, ← direction_affine_span, b.tot, affine_subspace.direction_top], exact le_rfl }, conv_rhs { rw ← image_univ, }, rw vector_span_image_eq_span_vsub_set_right_ne k b.points (mem_univ i), congr, ext v, simp, end @[simp] lemma basis_of_apply (i : ι) (j : {j : ι // j ≠ i}) : b.basis_of i j = b.points ↑j -ᵥ b.points i := by simp [basis_of] /-- The `i`th barycentric coordinate of a point. -/ noncomputable def coord (i : ι) : P →ᵃ[k] k := { to_fun := λ q, 1 - (b.basis_of i).sum_coords (q -ᵥ b.points i), linear := -(b.basis_of i).sum_coords, map_vadd' := λ q v, by rw [vadd_vsub_assoc, linear_map.map_add, vadd_eq_add, linear_map.neg_apply, sub_add_eq_sub_sub_swap, add_comm, sub_eq_add_neg], } @[simp] lemma linear_eq_sum_coords (i : ι) : (b.coord i).linear = -(b.basis_of i).sum_coords := rfl @[simp] lemma coord_apply_eq (i : ι) : b.coord i (b.points i) = 1 := by simp only [coord, basis.coe_sum_coords, linear_equiv.map_zero, linear_equiv.coe_coe, sub_zero, affine_map.coe_mk, finsupp.sum_zero_index, vsub_self] @[simp] lemma coord_apply_neq (i j : ι) (h : j ≠ i) : b.coord i (b.points j) = 0 := by rw [coord, affine_map.coe_mk, ← subtype.coe_mk j h, ← b.basis_of_apply i ⟨j, h⟩, basis.sum_coords_self_apply, sub_self] lemma coord_apply [decidable_eq ι] (i j : ι) : b.coord i (b.points j) = if i = j then 1 else 0 := by { cases eq_or_ne i j; simp [h.symm], simp [h], } @[simp] lemma coord_apply_combination_of_mem {s : finset ι} {i : ι} (hi : i ∈ s) {w : ι → k} (hw : s.sum w = 1) : b.coord i (s.affine_combination b.points w) = w i := begin classical, simp only [coord_apply, hi, finset.affine_combination_eq_linear_combination, if_true, mul_boole, hw, function.comp_app, smul_eq_mul, s.sum_ite_eq, s.map_affine_combination b.points w hw], end @[simp] lemma coord_apply_combination_of_not_mem {s : finset ι} {i : ι} (hi : i ∉ s) {w : ι → k} (hw : s.sum w = 1) : b.coord i (s.affine_combination b.points w) = 0 := begin classical, simp only [coord_apply, hi, finset.affine_combination_eq_linear_combination, if_false, mul_boole, hw, function.comp_app, smul_eq_mul, s.sum_ite_eq, s.map_affine_combination b.points w hw], end @[simp] lemma sum_coord_apply_eq_one [fintype ι] (q : P) : ∑ i, b.coord i q = 1 := begin have hq : q ∈ affine_span k (range b.points), { rw b.tot, exact affine_subspace.mem_top k V q, }, obtain ⟨w, hw, rfl⟩ := eq_affine_combination_of_mem_affine_span_of_fintype hq, convert hw, ext i, exact b.coord_apply_combination_of_mem (finset.mem_univ i) hw, end @[simp] lemma affine_combination_coord_eq_self [fintype ι] (q : P) : finset.univ.affine_combination b.points (λ i, b.coord i q) = q := begin have hq : q ∈ affine_span k (range b.points), { rw b.tot, exact affine_subspace.mem_top k V q, }, obtain ⟨w, hw, rfl⟩ := eq_affine_combination_of_mem_affine_span_of_fintype hq, congr, ext i, exact b.coord_apply_combination_of_mem (finset.mem_univ i) hw, end /-- A variant of `affine_basis.affine_combination_coord_eq_self` for the special case when the affine space is a module so we can talk about linear combinations. -/ @[simp] lemma linear_combination_coord_eq_self [fintype ι] (b : affine_basis ι k V) (v : V) : ∑ i, (b.coord i v) • (b.points i) = v := begin have hb := b.affine_combination_coord_eq_self v, rwa finset.univ.affine_combination_eq_linear_combination _ _ (b.sum_coord_apply_eq_one v) at hb, end lemma ext_elem [fintype ι] {q₁ q₂ : P} (h : ∀ i, b.coord i q₁ = b.coord i q₂) : q₁ = q₂ := begin rw [← b.affine_combination_coord_eq_self q₁, ← b.affine_combination_coord_eq_self q₂], simp only [h], end @[simp] lemma coe_coord_of_subsingleton_eq_one [subsingleton ι] (i : ι) : (b.coord i : P → k) = 1 := begin ext q, have hp : (range b.points).subsingleton, { rw ← image_univ, apply subsingleton.image, apply subsingleton_of_subsingleton, }, haveI := affine_subspace.subsingleton_of_subsingleton_span_eq_top hp b.tot, let s : finset ι := {i}, have hi : i ∈ s, { simp, }, have hw : s.sum (function.const ι (1 : k)) = 1, { simp, }, have hq : q = s.affine_combination b.points (function.const ι (1 : k)), { simp, }, rw [pi.one_apply, hq, b.coord_apply_combination_of_mem hi hw], end lemma surjective_coord [nontrivial ι] (i : ι) : function.surjective $ b.coord i := begin classical, intros x, obtain ⟨j, hij⟩ := exists_ne i, let s : finset ι := {i, j}, have hi : i ∈ s, { simp, }, have hj : j ∈ s, { simp, }, let w : ι → k := λ j', if j' = i then x else 1-x, have hw : s.sum w = 1, { simp [hij, finset.sum_ite, finset.filter_insert, finset.filter_eq'], }, use s.affine_combination b.points w, simp [b.coord_apply_combination_of_mem hi hw], end /-- Barycentric coordinates as an affine map. -/ noncomputable def coords : P →ᵃ[k] ι → k := { to_fun := λ q i, b.coord i q, linear := { to_fun := λ v i, -(b.basis_of i).sum_coords v, map_add' := λ v w, by { ext i, simp only [linear_map.map_add, pi.add_apply, neg_add], }, map_smul' := λ t v, by { ext i, simpa only [linear_map.map_smul, pi.smul_apply, smul_neg] } }, map_vadd' := λ p v, by { ext i, simp only [linear_eq_sum_coords, linear_map.coe_mk, linear_map.neg_apply, pi.vadd_apply', affine_map.map_vadd], }, } @[simp] lemma coords_apply (q : P) (i : ι) : b.coords q i = b.coord i q := rfl end ring section division_ring variables [division_ring k] [module k V] include V @[simp] lemma coord_apply_centroid [char_zero k] (b : affine_basis ι k P) {s : finset ι} {i : ι} (hi : i ∈ s) : b.coord i (s.centroid k b.points) = (s.card : k) ⁻¹ := by rw [finset.centroid, b.coord_apply_combination_of_mem hi (s.sum_centroid_weights_eq_one_of_nonempty _ ⟨i, hi⟩), finset.centroid_weights] lemma exists_affine_subbasis {t : set P} (ht : affine_span k t = ⊤) : ∃ (s ⊆ t) (b : affine_basis ↥s k P), b.points = coe := begin obtain ⟨s, hst, h_tot, h_ind⟩ := exists_affine_independent k V t, refine ⟨s, hst, ⟨coe, h_ind, _⟩, rfl⟩, rw [subtype.range_coe, h_tot, ht] end variables (k V P) lemma exists_affine_basis : ∃ (s : set P) (b : affine_basis ↥s k P), b.points = coe := let ⟨s, _, hs⟩ := exists_affine_subbasis (affine_subspace.span_univ k V P) in ⟨s, hs⟩ end division_ring end affine_basis
971349b497624342fae81cbdb41f2129fd68a752
8f83e52da30f74edd26b394c8cbbaa68b2ac41aa
/06-formalizacija-dokazov/vaje-imp.lean
6a468b23ac36a063941c8a29af59a9fcbb63f2ac
[]
no_license
petrapodlogar/teorija-programskih-jezikov
ec790e2a6cd293d54b6c1bdd48cbb8bd7e2b2421
def21623d0b6bf1090e5d05e7c1d391aacdc70f2
refs/heads/master
1,599,611,534,895
1,574,856,756,000
1,574,856,756,000
221,290,046
0
0
null
1,573,585,033,000
1,573,585,033,000
null
UTF-8
Lean
false
false
8,266
lean
-- ==================== Syntax ==================== def loc := string inductive aexp : Type | Lookup : loc -> aexp | Int : int -> aexp | Plus : aexp -> aexp -> aexp | Minus : aexp -> aexp -> aexp | Times : aexp -> aexp -> aexp inductive bexp : Type | Bool : bool -> bexp | Equal : aexp -> aexp -> bexp | Less : aexp -> aexp -> bexp inductive cmd : Type | Assign : loc -> aexp -> cmd | IfThenElse : bexp -> cmd -> cmd -> cmd | Seq : cmd -> cmd -> cmd | Skip : cmd | WhileDo : bexp -> cmd -> cmd -- ================== Example 'fact.imp' in LEAN notation. ================== def fact : cmd := cmd.Seq (cmd.Seq (cmd.Assign "n" (aexp.Int 10)) (cmd.Assign "fact" (aexp.Int 1)) ) (cmd.WhileDo (bexp.Less (aexp.Int 0) (aexp.Lookup "n")) (cmd.Seq (cmd.Assign "fact" (aexp.Times (aexp.Lookup "fact") (aexp.Lookup "n")) ) (cmd.Assign "n" (aexp.Minus (aexp.Lookup "n") (aexp.Int 1)) ) ) ) -- ==================== Environment ==================== inductive env : Type | Nil : env | Cons : loc -> int -> env -> env inductive lookup : loc -> env -> int -> Prop | Find {loc i E} : lookup loc (env.Cons loc i E) i | Search {loc loc' i' E' i} : loc≠loc' -> lookup loc E' i -> lookup loc (env.Cons loc' i' E') i -- ==================== Operational Semantics ==================== inductive aeval : env -> aexp -> int -> Prop | Lookup {E loc i} : lookup loc E i -> aeval E (aexp.Lookup loc) i | Int {E i}: aeval E (aexp.Int i) i | Plus {E a1 i1 a2 i2}: aeval E a1 i1 -> aeval E a2 i2 -> aeval E (aexp.Plus a1 a2) (i1 + i2) | Minus {E a1 i1 a2 i2}: aeval E a1 i1 -> aeval E a2 i2 -> aeval E (aexp.Minus a1 a2) (i1 - i2) | Times {E a1 i1 a2 i2}: aeval E a1 i1 -> aeval E a2 i2 -> aeval E (aexp.Times a1 a2) (i1 * i2) -- Lean works best with '<' and '≤' so we use them instead of '>' and '≥'. inductive beval : env -> bexp -> bool -> Prop | Bool {E b} : beval E (bexp.Bool b) b | Equal_t {E a1 a2 i1 i2}: aeval E a1 i1 -> aeval E a2 i2 -> i1 = i2 -> beval E (bexp.Equal a1 a2) true | Equal_f {E a1 a2 i1 i2}: aeval E a1 i1 -> aeval E a2 i2 -> i1 ≠ i2 -> beval E (bexp.Equal a1 a2) false | Less_t {E a1 a2 i1 i2}: aeval E a1 i1 -> aeval E a2 i2 -> i1 < i2 -> beval E (bexp.Less a1 a2) true | Less_f {E a1 a2 i1 i2}: aeval E a1 i1 -> aeval E a2 i2 -> ¬ i1 < i2 -> beval E (bexp.Less a1 a2) false inductive ceval : env -> cmd -> env -> Prop | Assign {E a i l}: aeval E a i -> ceval E (cmd.Assign l a) (env.Cons l i E) | IfThenElse_t {E b c1 c2 E'} : beval E b true -> ceval E c1 E' -> ceval E (cmd.IfThenElse b c1 c2) E' | IfThenElse_f {E b c1 c2 E'} : beval E b false ->ceval E c2 E' -> ceval E (cmd.IfThenElse b c1 c2) E' | Seq {c1 c2 E E' E''}: ceval E c1 E' -> ceval E' c2 E'' -> ceval E (cmd.Seq c1 c2) E'' | Skip {E} : ceval E cmd.Skip E | WhileDo_t {E b c E' E''}: beval E b true -> ceval E c E' -> ceval E' (cmd.WhileDo b c) E'' -> ceval E (cmd.WhileDo b c) E'' | WhileDo_f {E b c}: beval E b false -> ceval E (cmd.WhileDo b c) E -- ==================== Safety ==================== -- Contains all the names of already assigned locations. inductive locs : Type | Nil : locs | Cons : loc -> locs -> locs inductive loc_safe : loc -> locs -> Prop | Find {loc L} : loc_safe loc (locs.Cons loc L) | Search {loc loc' L} : loc'≠loc -> loc_safe loc L -> loc_safe loc (locs.Cons loc' L) inductive asafe : locs -> aexp -> Prop | Lookup {L l}: loc_safe l L -> asafe L (aexp.Lookup l) | Int {L i}: asafe L (aexp.Int i) | Plus {L a1 a2} : asafe L a1 -> asafe L a2 -> asafe L (aexp.Plus a1 a2) | Minus {L a1 a2} : asafe L a1 -> asafe L a2 -> asafe L (aexp.Minus a1 a2) | Times {L a1 a2} : asafe L a1 -> asafe L a2 -> asafe L (aexp.Times a1 a2) inductive bsafe : locs -> bexp -> Prop | Bool {L b} : bsafe L (bexp.Bool b) | Equal {L a1 a2} : asafe L a1 -> asafe L a2 -> bsafe L (bexp.Equal a1 a2) | Less {L a1 a2} : asafe L a1 -> asafe L a2 -> bsafe L (bexp.Less a1 a2) inductive csafe : locs -> cmd -> locs -> Prop | Assign {L l a} : asafe L a -> csafe L (cmd.Assign l a) (locs.Cons l L) -- | IfThenElse -- bsafe L b -> csafe L c1 L1 -> csafe L c2 L2 -- csafe L (cmd.IfThenElse b c1 c2) (L1 ∩ L2) -- Note: This part requires a definition of locs intersection. | Seq {L c1 L' c2 L''} : csafe L c1 L' -> csafe L' c2 L'' -> csafe L (cmd.Seq c1 c2) L'' | Skip {L} : csafe L (cmd.Skip) L | WhileDo {L b c L'} : bsafe L b -> csafe L c L' -> csafe L (cmd.WhileDo b c) L' -- ==================== Auxiliary safety for lookup ==================== -- Ensures that the given environment maps all the required locations. inductive env_maps : env -> locs -> Prop | Nil {E} : env_maps E locs.Nil | Cons {loc E L} : env_maps E L -> (∃i, lookup loc E i) -> env_maps E (locs.Cons loc L) -- Increasing the environment does not break its safety. theorem env_maps_weaken {E L loc i}: env_maps E L -> env_maps (env.Cons loc i E) L := begin intro es, induction es with E' loc' E' L' maps finds ih, case env_maps.Nil { apply env_maps.Nil, }, case env_maps.Cons { apply env_maps.Cons, assumption, -- we compare the the strings to know which lookup result is correct cases string.has_decidable_eq loc' loc with neq eq, { cases finds with i', existsi i', -- lookup must search deeper apply lookup.Search, assumption, assumption, }, existsi i, -- loc' and loc are equal, 'subst eq' will rewrite them to the same name. subst eq, apply lookup.Find, } end -- If the location is safe in the same specification as the environment -- then we are guaranteed to look up a value theorem safe_lookup {L E loc}: loc_safe loc L -> env_maps E L -> ∃ (i:int), lookup loc E i := begin -- if we have an impossible hypothesis 'h' (such as a safety check in -- an empty locs list) we can complete the proof with 'cases h' sorry end -- ==================== Safety theorems ==================== theorem asafety {L E a}: asafe L a -> env_maps E L -> ∃ (i:int), aeval E a i := begin intros s es, induction s, case asafe.Lookup { cases safe_lookup s_a es with i, -- cases safe_lookup ... applies the theorem and eliminates the ∃ existsi i, apply aeval.Lookup, assumption, }, case asafe.Int { existsi s_i, apply aeval.Int, }, case asafe.Plus { cases s_ih_a es with i1, cases s_ih_a_1 es with i2, existsi (i1 + i2), apply aeval.Plus, assumption, assumption, }, -- podobno kot za Plus case asafe.Minus { sorry }, case asafe.Times { sorry }, end theorem bsafety {L E b}: bsafe L b -> env_maps E L -> ∃ (v:bool), beval E b v := begin intros s es, induction s, case bsafe.Bool { existsi s_b, apply beval.Bool, }, case bsafe.Equal { cases asafety s_a es with i1, cases asafety s_a_1 es with i2, cases int.decidable_eq i1 i2 with neq eq, -- we cannot just do a case analysis on logical formulas because -- we are not using classical logic. Luckily integer equality is -- decidable, so we can specify to do a case analysis on that -- i1 ≠ i2 -- ff je false tipa bool { existsi ff, apply beval.Equal_f, assumption, assumption, assumption, }, -- i1 = i2 { sorry }, }, case bsafe.Less { sorry, cases int.decidable_lt i1 i2 with neq eq, -- i1 ≰ i2 { sorry }, -- i1 < i2 { sorry }, }, end theorem csafety {L L' E c }: csafe L c L' -> env_maps E L -> ∃ (E':env), ceval E c E' ∧ env_maps E' L' := begin -- constructor splits ∧ into two subgoals intros s, revert E, -- we revert to obtain a stronger induction induction s; intros E es, case csafe.Assign { cases asafety s_a_1 es with i, existsi (env.Cons s_loc i E), constructor, -- constructor splits ∧ into two subgoals { sorry }, sorry }, case csafe.Seq { sorry }, case csafe.Skip { sorry }, case csafe.WhileDo { -- this part can't really be done in big step semantics sorry }, end
cc75084b2b07e0e8efa5fd93965501049b79c3d1
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/tests/lean/run/tactic1.lean
76df973beb61b42527d9defef99470c1c76e93ce
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,128
lean
theorem ex1 (x : Nat) (y : { v // v > x }) (z : Nat) : Nat := by { clear y x; exact z } theorem ex2 (x : Nat) (y : { v // v > x }) (z : Nat) : Nat := by { clear x y; exact z } theorem ex3 (x y z : Nat) (h₁ : x = y) (h₂ : z = y) : x = z := by { have y = z from h₂.symm; apply Eq.trans; exact h₁; assumption } theorem ex4 (x y z : Nat) (h₁ : x = y) (h₂ : z = y) : x = z := by { let h₃ : y = z := h₂.symm; apply Eq.trans; exact h₁; exact h₃ } theorem ex5 (x y z : Nat) (h₁ : x = y) (h₂ : z = y) : x = z := by { let! h₃ : y = z := h₂.symm; apply Eq.trans; exact h₁; exact h₃ } theorem ex6 (x y z : Nat) (h₁ : x = y) (h₂ : z = y) : id (x + 0 = z) := by { show x = z; let! h₃ : y = z := h₂.symm; apply Eq.trans; exact h₁; exact h₃ } theorem ex7 (x y z : Nat) (h₁ : x = y) (h₂ : z = y) : x = z := by have y = z by apply Eq.symm; assumption apply Eq.trans exact h₁ assumption theorem ex8 (x y z : Nat) (h₁ : x = y) (h₂ : z = y) : x = z := by apply Eq.trans h₁; have y = z by apply Eq.symm; assumption; exact this
089de7d08d573f166784c599897fd80001d77a0c
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/analysis/special_functions/sqrt.lean
e33567aaa02f46998ef3c4865b42e8ff33aa3367
[ "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
6,633
lean
/- Copyright (c) 2021 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import data.real.sqrt import analysis.calculus.inverse import measure_theory.borel_space /-! # Smoothness of `real.sqrt` In this file we prove that `real.sqrt` is infinitely smooth at all points `x ≠ 0` and provide some dot-notation lemmas. ## Tags sqrt, differentiable -/ open set open_locale topological_space namespace real /-- Local homeomorph between `(0, +∞)` and `(0, +∞)` with `to_fun = λ x, x ^ 2` and `inv_fun = sqrt`. -/ noncomputable def sq_local_homeomorph : local_homeomorph ℝ ℝ := { to_fun := λ x, x ^ 2, inv_fun := sqrt, source := Ioi 0, target := Ioi 0, map_source' := λ x hx, mem_Ioi.2 (pow_pos hx _), map_target' := λ x hx, mem_Ioi.2 (sqrt_pos.2 hx), left_inv' := λ x hx, sqrt_sq (le_of_lt hx), right_inv' := λ x hx, sq_sqrt (le_of_lt hx), open_source := is_open_Ioi, open_target := is_open_Ioi, continuous_to_fun := (continuous_pow 2).continuous_on, continuous_inv_fun := continuous_on_id.sqrt } lemma deriv_sqrt_aux {x : ℝ} (hx : x ≠ 0) : has_strict_deriv_at sqrt (1 / (2 * sqrt x)) x ∧ ∀ n, times_cont_diff_at ℝ n sqrt x := begin cases hx.lt_or_lt with hx hx, { rw [sqrt_eq_zero_of_nonpos hx.le, mul_zero, div_zero], have : sqrt =ᶠ[𝓝 x] (λ _, 0) := (gt_mem_nhds hx).mono (λ x hx, sqrt_eq_zero_of_nonpos hx.le), exact ⟨(has_strict_deriv_at_const x (0 : ℝ)).congr_of_eventually_eq this.symm, λ n, times_cont_diff_at_const.congr_of_eventually_eq this⟩ }, { have : ↑2 * sqrt x ^ (2 - 1) ≠ 0, by simp [(sqrt_pos.2 hx).ne', @two_ne_zero ℝ], split, { simpa using sq_local_homeomorph.has_strict_deriv_at_symm hx this (has_strict_deriv_at_pow 2 _) }, { exact λ n, sq_local_homeomorph.times_cont_diff_at_symm_deriv this hx (has_deriv_at_pow 2 (sqrt x)) (times_cont_diff_at_id.pow 2) } } end lemma has_strict_deriv_at_sqrt {x : ℝ} (hx : x ≠ 0) : has_strict_deriv_at sqrt (1 / (2 * sqrt x)) x := (deriv_sqrt_aux hx).1 lemma times_cont_diff_at_sqrt {x : ℝ} {n : with_top ℕ} (hx : x ≠ 0) : times_cont_diff_at ℝ n sqrt x := (deriv_sqrt_aux hx).2 n lemma has_deriv_at_sqrt {x : ℝ} (hx : x ≠ 0) : has_deriv_at sqrt (1 / (2 * sqrt x)) x := (has_strict_deriv_at_sqrt hx).has_deriv_at end real open real lemma measurable.sqrt {α : Type*} [measurable_space α] {f : α → ℝ} (hf : measurable f) : measurable (λ x, sqrt (f x)) := continuous_sqrt.measurable.comp hf section deriv variables {f : ℝ → ℝ} {s : set ℝ} {f' x : ℝ} lemma has_deriv_within_at.sqrt (hf : has_deriv_within_at f f' s x) (hx : f x ≠ 0) : has_deriv_within_at (λ y, sqrt (f y)) (f' / (2 * sqrt (f x))) s x := by simpa only [(∘), div_eq_inv_mul, mul_one] using (has_deriv_at_sqrt hx).comp_has_deriv_within_at x hf lemma has_deriv_at.sqrt (hf : has_deriv_at f f' x) (hx : f x ≠ 0) : has_deriv_at (λ y, sqrt (f y)) (f' / (2 * sqrt(f x))) x := by simpa only [(∘), div_eq_inv_mul, mul_one] using (has_deriv_at_sqrt hx).comp x hf lemma has_strict_deriv_at.sqrt (hf : has_strict_deriv_at f f' x) (hx : f x ≠ 0) : has_strict_deriv_at (λ t, sqrt (f t)) (f' / (2 * sqrt (f x))) x := by simpa only [(∘), div_eq_inv_mul, mul_one] using (has_strict_deriv_at_sqrt hx).comp x hf lemma deriv_within_sqrt (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, sqrt (f x)) s x = (deriv_within f s x) / (2 * sqrt (f x)) := (hf.has_deriv_within_at.sqrt hx).deriv_within hxs @[simp] lemma deriv_sqrt (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) : deriv (λx, sqrt (f x)) x = (deriv f x) / (2 * sqrt (f x)) := (hf.has_deriv_at.sqrt hx).deriv end deriv section fderiv variables {E : Type*} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {n : with_top ℕ} {s : set E} {x : E} {f' : E →L[ℝ] ℝ} lemma has_fderiv_at.sqrt (hf : has_fderiv_at f f' x) (hx : f x ≠ 0) : has_fderiv_at (λ y, sqrt (f y)) ((1 / (2 * sqrt (f x))) • f') x := (has_deriv_at_sqrt hx).comp_has_fderiv_at x hf lemma has_strict_fderiv_at.sqrt (hf : has_strict_fderiv_at f f' x) (hx : f x ≠ 0) : has_strict_fderiv_at (λ y, sqrt (f y)) ((1 / (2 * sqrt (f x))) • f') x := (has_strict_deriv_at_sqrt hx).comp_has_strict_fderiv_at x hf lemma has_fderiv_within_at.sqrt (hf : has_fderiv_within_at f f' s x) (hx : f x ≠ 0) : has_fderiv_within_at (λ y, sqrt (f y)) ((1 / (2 * sqrt (f x))) • f') s x := (has_deriv_at_sqrt hx).comp_has_fderiv_within_at x hf lemma differentiable_within_at.sqrt (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0) : differentiable_within_at ℝ (λ y, sqrt (f y)) s x := (hf.has_fderiv_within_at.sqrt hx).differentiable_within_at lemma differentiable_at.sqrt (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) : differentiable_at ℝ (λ y, sqrt (f y)) x := (hf.has_fderiv_at.sqrt hx).differentiable_at lemma differentiable_on.sqrt (hf : differentiable_on ℝ f s) (hs : ∀ x ∈ s, f x ≠ 0) : differentiable_on ℝ (λ y, sqrt (f y)) s := λ x hx, (hf x hx).sqrt (hs x hx) lemma differentiable.sqrt (hf : differentiable ℝ f) (hs : ∀ x, f x ≠ 0) : differentiable ℝ (λ y, sqrt (f y)) := λ x, (hf x).sqrt (hs x) lemma fderiv_within_sqrt (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0) (hxs : unique_diff_within_at ℝ s x) : fderiv_within ℝ (λx, sqrt (f x)) s x = (1 / (2 * sqrt (f x))) • fderiv_within ℝ f s x := (hf.has_fderiv_within_at.sqrt hx).fderiv_within hxs @[simp] lemma fderiv_sqrt (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) : fderiv ℝ (λx, sqrt (f x)) x = (1 / (2 * sqrt (f x))) • fderiv ℝ f x := (hf.has_fderiv_at.sqrt hx).fderiv lemma times_cont_diff_at.sqrt (hf : times_cont_diff_at ℝ n f x) (hx : f x ≠ 0) : times_cont_diff_at ℝ n (λ y, sqrt (f y)) x := (times_cont_diff_at_sqrt hx).comp x hf lemma times_cont_diff_within_at.sqrt (hf : times_cont_diff_within_at ℝ n f s x) (hx : f x ≠ 0) : times_cont_diff_within_at ℝ n (λ y, sqrt (f y)) s x := (times_cont_diff_at_sqrt hx).comp_times_cont_diff_within_at x hf lemma times_cont_diff_on.sqrt (hf : times_cont_diff_on ℝ n f s) (hs : ∀ x ∈ s, f x ≠ 0) : times_cont_diff_on ℝ n (λ y, sqrt (f y)) s := λ x hx, (hf x hx).sqrt (hs x hx) lemma times_cont_diff.sqrt (hf : times_cont_diff ℝ n f) (h : ∀ x, f x ≠ 0) : times_cont_diff ℝ n (λ y, sqrt (f y)) := times_cont_diff_iff_times_cont_diff_at.2 $ λ x, (hf.times_cont_diff_at.sqrt (h x)) end fderiv
ef7721f5c594c08ed7e990e3f86e4f20b80bd5b1
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/tactic/to_additive.lean
c0aa488aa028cfc3ea355fdb5e611b140399cfcd
[ "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
28,515
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Yury Kudryashov, Floris van Doorn -/ import tactic.transform_decl import tactic.algebra import tactic.lint.basic import tactic.alias /-! # Transport multiplicative to additive This file defines an attribute `to_additive` that can be used to automatically transport theorems and definitions (but not inductive types and structures) from a multiplicative theory to an additive theory. Usage information is contained in the doc string of `to_additive.attr`. ### Missing features * Automatically transport structures and other inductive types. * For structures, automatically generate theorems like `group α ↔ add_group (additive α)`. -/ namespace to_additive open tactic setup_tactic_parser section performance_hack -- see Note [user attribute parameters] local attribute [semireducible] reflected /-- Temporarily change the `has_reflect` instance for `name`. -/ local attribute [instance, priority 9000] meta def hacky_name_reflect : has_reflect name := λ n, `(id %%(expr.const n []) : name) /-- An auxiliary attribute used to store the names of the additive versions of declarations that have been processed by `to_additive`. -/ @[user_attribute] meta def aux_attr : user_attribute (name_map name) name := { name := `to_additive_aux, descr := "Auxiliary attribute for `to_additive`. DON'T USE IT", parser := failed, cache_cfg := ⟨λ ns, ns.mfoldl (λ dict n', do let n := match n' with | name.mk_string s pre := if s = "_to_additive" then pre else n' | _ := n' end, param ← aux_attr.get_param_untyped n', pure $ dict.insert n param.app_arg.const_name) mk_name_map, []⟩ } end performance_hack section extra_attributes /-- An attribute that tells `@[to_additive]` that certain arguments of this definition are not involved when using `@[to_additive]`. This helps the heuristic of `@[to_additive]` by also transforming definitions if `ℕ` or another fixed type occurs as one of these arguments. -/ @[user_attribute] meta def ignore_args_attr : user_attribute (name_map $ list ℕ) (list ℕ) := { name := `to_additive_ignore_args, descr := "Auxiliary attribute for `to_additive` stating that certain arguments are not additivized.", cache_cfg := ⟨λ ns, ns.mfoldl (λ dict n, do param ← ignore_args_attr.get_param_untyped n, -- see Note [user attribute parameters] return $ dict.insert n (param.to_list expr.to_nat).iget) mk_name_map, []⟩, parser := (lean.parser.small_nat)* } /-- An attribute that is automatically added to declarations tagged with `@[to_additive]`, if needed. This attribute tells which argument is the type where this declaration uses the multiplicative structure. If there are multiple argument, we typically tag the first one. If this argument contains a fixed type, this declaration will note be additivized. See the Heuristics section of `to_additive.attr` for more details. If a declaration is not tagged, it is presumed that the first argument is relevant. `@[to_additive]` uses the function `to_additive.first_multiplicative_arg` to automatically tag declarations. It is ok to update it manually if the automatic tagging made an error. Implementation note: we only allow exactly 1 relevant argument, even though some declarations (like `prod.group`) have multiple arguments with a multiplicative structure on it. The reason is that whether we additivize a declaration is an all-or-nothing decision, and if we will not be able to additivize declarations that (e.g.) talk about multiplication on `ℕ × α` anyway. Warning: adding `@[to_additive_reorder]` with an equal or smaller number than the number in this attribute is currently not supported. -/ @[user_attribute] meta def relevant_arg_attr : user_attribute (name_map ℕ) ℕ := { name := `to_additive_relevant_arg, descr := "Auxiliary attribute for `to_additive` stating which arguments are the types with a " ++ "multiplicative structure.", cache_cfg := ⟨λ ns, ns.mfoldl (λ dict n, do param ← relevant_arg_attr.get_param_untyped n, -- see Note [user attribute parameters] -- we subtract 1 from the values provided by the user. return $ dict.insert n $ param.to_nat.iget.pred) mk_name_map, []⟩, parser := lean.parser.small_nat } /-- An attribute that stores all the declarations that needs their arguments reordered when applying `@[to_additive]`. Currently, we only support swapping consecutive arguments. The list of the natural numbers contains the positions of the first of the two arguments to be swapped. If the first two arguments are swapped, the first two universe variables are also swapped. Example: `@[to_additive_reorder 1 4]` swaps the first two arguments and the arguments in positions 4 and 5. -/ @[user_attribute] meta def reorder_attr : user_attribute (name_map $ list ℕ) (list ℕ) := { name := `to_additive_reorder, descr := "Auxiliary attribute for `to_additive` that stores arguments that need to be reordered.", cache_cfg := ⟨λ ns, ns.mfoldl (λ dict n, do param ← reorder_attr.get_param_untyped n, -- see Note [user attribute parameters] return $ dict.insert n (param.to_list expr.to_nat).iget) mk_name_map, []⟩, parser := do l ← (lean.parser.small_nat)*, guard (l.all (≠ 0)) <|> exceptional.fail "The reorder positions must be positive", return l } end extra_attributes /-- Find the first argument of `nm` that has a multiplicative type-class on it. Returns 1 if there are no types with a multiplicative class as arguments. E.g. `prod.group` returns 1, and `pi.has_one` returns 2. -/ meta def first_multiplicative_arg (nm : name) : tactic ℕ := do d ← get_decl nm, let (es, _) := d.type.pi_binders, l ← es.mmap_with_index $ λ n bi, do { let tgt := bi.type.pi_codomain, let n_bi := bi.type.pi_binders.fst.length, tt ← has_attribute' `to_additive tgt.get_app_fn.const_name | return none, let n2 := tgt.get_app_args.head.get_app_fn.match_var.map $ λ m, n + n_bi - m, return $ n2 }, let l := l.reduce_option, return $ if l = [] then 1 else l.foldr min l.head /-- A command that can be used to have future uses of `to_additive` change the `src` namespace to the `tgt` namespace. For example: ``` run_cmd to_additive.map_namespace `quotient_group `quotient_add_group ``` Later uses of `to_additive` on declarations in the `quotient_group` namespace will be created in the `quotient_add_group` namespaces. -/ meta def map_namespace (src tgt : name) : command := do let n := src.mk_string "_to_additive", let decl := declaration.thm n [] `(unit) (pure (reflect ())), add_decl decl, aux_attr.set n tgt tt /-- `value_type` is the type of the arguments that can be provided to `to_additive`. `to_additive.parser` parses the provided arguments: * `replace_all`: replace all multiplicative declarations, do not use the heuristic. * `trace`: output the generated additive declaration. * `tgt : name`: the name of the target (the additive declaration). * `doc`: an optional doc string. * if `allow_auto_name` is `ff` (default) then `@[to_additive]` will check whether the given name can be auto-generated. -/ @[derive has_reflect, derive inhabited] structure value_type : Type := (replace_all : bool) (trace : bool) (tgt : name) (doc : option string) (allow_auto_name : bool) /-- `add_comm_prefix x s` returns `"comm_" ++ s` if `x = tt` and `s` otherwise. -/ meta def add_comm_prefix : bool → string → string | tt s := "comm_" ++ s | ff s := s /-- Dictionary used by `to_additive.guess_name` to autogenerate names. -/ meta def tr : bool → list string → list string | is_comm ("one" :: "le" :: s) := add_comm_prefix is_comm "nonneg" :: tr ff s | is_comm ("one" :: "lt" :: s) := add_comm_prefix is_comm "pos" :: tr ff s | is_comm ("le" :: "one" :: s) := add_comm_prefix is_comm "nonpos" :: tr ff s | is_comm ("lt" :: "one" :: s) := add_comm_prefix is_comm "neg" :: tr ff s | is_comm ("mul" :: "single" :: s) := add_comm_prefix is_comm "single" :: tr ff s | is_comm ("mul" :: "support" :: s) := add_comm_prefix is_comm "support" :: tr ff s | is_comm ("mul" :: "tsupport" :: s) := add_comm_prefix is_comm "tsupport" :: tr ff s | is_comm ("mul" :: "indicator" :: s) := add_comm_prefix is_comm "indicator" :: tr ff s | is_comm ("mul" :: s) := add_comm_prefix is_comm "add" :: tr ff s | is_comm ("smul" :: s) := add_comm_prefix is_comm "vadd" :: tr ff s | is_comm ("inv" :: s) := add_comm_prefix is_comm "neg" :: tr ff s | is_comm ("div" :: s) := add_comm_prefix is_comm "sub" :: tr ff s | is_comm ("one" :: s) := add_comm_prefix is_comm "zero" :: tr ff s | is_comm ("prod" :: s) := add_comm_prefix is_comm "sum" :: tr ff s | is_comm ("finprod" :: s) := add_comm_prefix is_comm "finsum" :: tr ff s | is_comm ("pow" :: s) := add_comm_prefix is_comm "nsmul" :: tr ff s | is_comm ("npow" :: s) := add_comm_prefix is_comm "nsmul" :: tr ff s | is_comm ("zpow" :: s) := add_comm_prefix is_comm "zsmul" :: tr ff s | is_comm ("is" :: "square" :: s) := add_comm_prefix is_comm "even" :: tr ff s | is_comm ("is" :: "scalar" :: "tower" :: s) := add_comm_prefix is_comm "vadd_assoc_class" :: tr ff s | is_comm ("is" :: "central" :: "scalar" :: s) := add_comm_prefix is_comm "is_central_vadd" :: tr ff s | is_comm ("is" :: "regular" :: s) := add_comm_prefix is_comm "is_add_regular" :: tr ff s | is_comm ("is" :: "left" :: "regular" :: s) := add_comm_prefix is_comm "is_add_left_regular" :: tr ff s | is_comm ("is" :: "right" :: "regular" :: s) := add_comm_prefix is_comm "is_add_right_regular" :: tr ff s | is_comm ("division" :: "monoid" :: s) := "subtraction" :: add_comm_prefix is_comm "monoid" :: tr ff s | is_comm ("monoid" :: s) := ("add_" ++ add_comm_prefix is_comm "monoid") :: tr ff s | is_comm ("submonoid" :: s) := ("add_" ++ add_comm_prefix is_comm "submonoid") :: tr ff s | is_comm ("group" :: s) := ("add_" ++ add_comm_prefix is_comm "group") :: tr ff s | is_comm ("subgroup" :: s) := ("add_" ++ add_comm_prefix is_comm "subgroup") :: tr ff s | is_comm ("semigroup" :: s) := ("add_" ++ add_comm_prefix is_comm "semigroup") :: tr ff s | is_comm ("magma" :: s) := ("add_" ++ add_comm_prefix is_comm "magma") :: tr ff s | is_comm ("haar" :: s) := ("add_" ++ add_comm_prefix is_comm "haar") :: tr ff s | is_comm ("prehaar" :: s) := ("add_" ++ add_comm_prefix is_comm "prehaar") :: tr ff s | is_comm ("unit" :: s) := ("add_" ++ add_comm_prefix is_comm "unit") :: tr ff s | is_comm ("units" :: s) := ("add_" ++ add_comm_prefix is_comm "units") :: tr ff s | is_comm ("comm" :: s) := tr tt s | is_comm ("root" :: s) := add_comm_prefix is_comm "div" :: tr ff s | is_comm ("rootable" :: s) := add_comm_prefix is_comm "divisible" :: tr ff s | is_comm ("prods" :: s) := add_comm_prefix is_comm "sums" :: tr ff s | is_comm (x :: s) := (add_comm_prefix is_comm x :: tr ff s) | tt [] := ["comm"] | ff [] := [] /-- Autogenerate target name for `to_additive`. -/ meta def guess_name : string → string := string.map_tokens ''' $ λ s, string.intercalate (string.singleton '_') $ tr ff (s.split_on '_') /-- Return the provided target name or autogenerate one if one was not provided. -/ meta def target_name (src tgt : name) (dict : name_map name) (allow_auto_name : bool) : tactic name := (if tgt.get_prefix ≠ name.anonymous ∨ allow_auto_name -- `tgt` is a full name then pure tgt else match src with | (name.mk_string s pre) := do let tgt_auto := guess_name s, guard (tgt.to_string ≠ tgt_auto ∨ tgt = src) <|> trace ("`to_additive " ++ src.to_string ++ "`: correctly autogenerated target " ++ "name, you may remove the explicit " ++ tgt_auto ++ " argument."), pure $ name.mk_string (if tgt = name.anonymous then tgt_auto else tgt.to_string) (pre.map_prefix dict.find) | _ := fail ("to_additive: can't transport " ++ src.to_string) end) >>= (λ res, if res = src ∧ tgt ≠ src then fail ("to_additive: can't transport " ++ src.to_string ++ " to itself. Give the desired additive name explicitly using `@[to_additive additive_name]`. ") else pure res) /-- the parser for the arguments to `to_additive`. -/ meta def parser : lean.parser value_type := do bang ← option.is_some <$> (tk "!")?, ques ← option.is_some <$> (tk "?")?, tgt ← ident?, e ← texpr?, doc ← match e with | some pe := some <$> ((to_expr pe >>= eval_expr string) : tactic string) | none := pure none end, return ⟨bang, ques, tgt.get_or_else name.anonymous, doc, ff⟩ private meta def proceed_fields_aux (src tgt : name) (prio : ℕ) (f : name → tactic (list string)) : command := do src_fields ← f src, tgt_fields ← f tgt, guard (src_fields.length = tgt_fields.length) <|> fail ("Failed to map fields of " ++ src.to_string), (src_fields.zip tgt_fields).mmap' $ λ names, guard (names.fst = names.snd) <|> aux_attr.set (src.append names.fst) (tgt.append names.snd) tt prio /-- Add the `aux_attr` attribute to the structure fields of `src` so that future uses of `to_additive` will map them to the corresponding `tgt` fields. -/ meta def proceed_fields (env : environment) (src tgt : name) (prio : ℕ) : command := let aux := proceed_fields_aux src tgt prio in do aux (λ n, pure $ list.map name.to_string $ (env.structure_fields n).get_or_else []) >> aux (λ n, (list.map (λ (x : name), "to_" ++ x.to_string) <$> get_tagged_ancestors n)) >> aux (λ n, (env.constructors_of n).mmap $ λ cs, match cs with | (name.mk_string s pre) := (guard (pre = n) <|> fail "Bad constructor name") >> pure s | _ := fail "Bad constructor name" end) /-- The attribute `to_additive` can be used to automatically transport theorems and definitions (but not inductive types and structures) from a multiplicative theory to an additive theory. To use this attribute, just write: ``` @[to_additive] theorem mul_comm' {α} [comm_semigroup α] (x y : α) : x * y = y * x := comm_semigroup.mul_comm ``` This code will generate a theorem named `add_comm'`. It is also possible to manually specify the name of the new declaration: ``` @[to_additive add_foo] theorem foo := sorry ``` An existing documentation string will _not_ be automatically used, so if the theorem or definition has a doc string, a doc string for the additive version should be passed explicitly to `to_additive`. ``` /-- Multiplication is commutative -/ @[to_additive "Addition is commutative"] theorem mul_comm' {α} [comm_semigroup α] (x y : α) : x * y = y * x := comm_semigroup.mul_comm ``` The transport tries to do the right thing in most cases using several heuristics described below. However, in some cases it fails, and requires manual intervention. If the declaration to be transported has attributes which need to be copied to the additive version, then `to_additive` should come last: ``` @[simp, to_additive] lemma mul_one' {G : Type*} [group G] (x : G) : x * 1 = x := mul_one x ``` The following attributes are supported and should be applied correctly by `to_additive` to the new additivized declaration, if they were present on the original one: ``` reducible, _refl_lemma, simp, norm_cast, instance, refl, symm, trans, elab_as_eliminator, no_rsimp, continuity, ext, ematch, measurability, alias, _ext_core, _ext_lemma_core, nolint ``` The exception to this rule is the `simps` attribute, which should come after `to_additive`: ``` @[to_additive, simps] instance {M N} [has_mul M] [has_mul N] : has_mul (M × N) := ⟨λ p q, ⟨p.1 * q.1, p.2 * q.2⟩⟩ ``` Additionally the `mono` attribute is not handled by `to_additive` and should be applied afterwards to both the original and additivized lemma. ## Implementation notes The transport process generally works by taking all the names of identifiers appearing in the name, type, and body of a declaration and creating a new declaration by mapping those names to additive versions using a simple string-based dictionary and also using all declarations that have previously been labeled with `to_additive`. In the `mul_comm'` example above, `to_additive` maps: * `mul_comm'` to `add_comm'`, * `comm_semigroup` to `add_comm_semigroup`, * `x * y` to `x + y` and `y * x` to `y + x`, and * `comm_semigroup.mul_comm'` to `add_comm_semigroup.add_comm'`. ### Heuristics `to_additive` uses heuristics to determine whether a particular identifier has to be mapped to its additive version. The basic heuristic is * Only map an identifier to its additive version if its first argument doesn't contain any unapplied identifiers. Examples: * `@has_mul.mul ℕ n m` (i.e. `(n * m : ℕ)`) will not change to `+`, since its first argument is `ℕ`, an identifier not applied to any arguments. * `@has_mul.mul (α × β) x y` will change to `+`. It's first argument contains only the identifier `prod`, but this is applied to arguments, `α` and `β`. * `@has_mul.mul (α × ℤ) x y` will not change to `+`, since its first argument contains `ℤ`. The reasoning behind the heuristic is that the first argument is the type which is "additivized", and this usually doesn't make sense if this is on a fixed type. There are some exceptions to this heuristic: * Identifiers that have the `@[to_additive]` attribute are ignored. For example, multiplication in `↥Semigroup` is replaced by addition in `↥AddSemigroup`. * If an identifier `d` has attribute `@[to_additive_relevant_arg n]` then the argument in position `n` is checked for a fixed type, instead of checking the first argument. `@[to_additive]` will automatically add the attribute `@[to_additive_relevant_arg n]` to a declaration when the first argument has no multiplicative type-class, but argument `n` does. * If an identifier has attribute `@[to_additive_ignore_args n1 n2 ...]` then all the arguments in positions `n1`, `n2`, ... will not be checked for unapplied identifiers (start counting from 1). For example, `cont_mdiff_map` has attribute `@[to_additive_ignore_args 21]`, which means that its 21st argument `(n : ℕ∞)` can contain `ℕ` (usually in the form `has_top.top ℕ ...`) and still be additivized. So `@has_mul.mul (C^∞⟮I, N; I', G⟯) _ f g` will be additivized. ### Troubleshooting If `@[to_additive]` fails because the additive declaration raises a type mismatch, there are various things you can try. The first thing to do is to figure out what `@[to_additive]` did wrong by looking at the type mismatch error. * Option 1: It additivized a declaration `d` that should remain multiplicative. Solution: * Make sure the first argument of `d` is a type with a multiplicative structure. If not, can you reorder the (implicit) arguments of `d` so that the first argument becomes a type with a multiplicative structure (and not some indexing type)? The reason is that `@[to_additive]` doesn't additivize declarations if their first argument contains fixed types like `ℕ` or `ℝ`. See section Heuristics. If the first argument is not the argument with a multiplicative type-class, `@[to_additive]` should have automatically added the attribute `@[to_additive_relevant_arg]` to the declaration. You can test this by running the following (where `d` is the full name of the declaration): ``` run_cmd to_additive.relevant_arg_attr.get_param `d >>= tactic.trace ``` The expected output is `n` where the `n`-th argument of `d` is a type (family) with a multiplicative structure on it. If you get a different output (or a failure), you could add the attribute `@[to_additive_relevant_arg n]` manually, where `n` is an argument with a multiplicative structure. * Option 2: It didn't additivize a declaration that should be additivized. This happened because the heuristic applied, and the first argument contains a fixed type, like `ℕ` or `ℝ`. Solutions: * If the fixed type has an additive counterpart (like `↥Semigroup`), give it the `@[to_additive]` attribute. * If the fixed type occurs inside the `k`-th argument of a declaration `d`, and the `k`-th argument is not connected to the multiplicative structure on `d`, consider adding attribute `[to_additive_ignore_args k]` to `d`. * If you want to disable the heuristic and replace all multiplicative identifiers with their additive counterpart, use `@[to_additive!]`. * Option 3: Arguments / universe levels are incorrectly ordered in the additive version. This likely only happens when the multiplicative declaration involves `pow`/`^`. Solutions: * Ensure that the order of arguments of all relevant declarations are the same for the multiplicative and additive version. This might mean that arguments have an "unnatural" order (e.g. `monoid.npow n x` corresponds to `x ^ n`, but it is convenient that `monoid.npow` has this argument order, since it matches `add_monoid.nsmul n x`. * If this is not possible, add the `[to_additive_reorder k]` to the multiplicative declaration to indicate that the `k`-th and `(k+1)`-st arguments are reordered in the additive version. If neither of these solutions work, and `to_additive` is unable to automatically generate the additive version of a declaration, manually write and prove the additive version. Often the proof of a lemma/theorem can just be the multiplicative version of the lemma applied to `multiplicative G`. Afterwards, apply the attribute manually: ``` attribute [to_additive foo_add_bar] foo_bar ``` This will allow future uses of `to_additive` to recognize that `foo_bar` should be replaced with `foo_add_bar`. ### Handling of hidden definitions Before transporting the “main” declaration `src`, `to_additive` first scans its type and value for names starting with `src`, and transports them. This includes auxiliary definitions like `src._match_1`, `src._proof_1`. In addition to transporting the “main” declaration, `to_additive` transports its equational lemmas and tags them as equational lemmas for the new declaration, attributes present on the original equational lemmas are also transferred first (notably `_refl_lemma`). ### Structure fields and constructors If `src` is a structure, then `to_additive` automatically adds structure fields to its mapping, and similarly for constructors of inductive types. For new structures this means that `to_additive` automatically handles coercions, and for old structures it does the same, if ancestry information is present in `@[ancestor]` attributes. The `ancestor` attribute must come before the `to_additive` attribute, and it is essential that the order of the base structures passed to `ancestor` matches between the multiplicative and additive versions of the structure. ### Name generation * If `@[to_additive]` is called without a `name` argument, then the new name is autogenerated. First, it takes the longest prefix of the source name that is already known to `to_additive`, and replaces this prefix with its additive counterpart. Second, it takes the last part of the name (i.e., after the last dot), and replaces common name parts (“mul”, “one”, “inv”, “prod”) with their additive versions. * Namespaces can be transformed using `map_namespace`. For example: ``` run_cmd to_additive.map_namespace `quotient_group `quotient_add_group ``` Later uses of `to_additive` on declarations in the `quotient_group` namespace will be created in the `quotient_add_group` namespaces. * If `@[to_additive]` is called with a `name` argument `new_name` /without a dot/, then `to_additive` updates the prefix as described above, then replaces the last part of the name with `new_name`. * If `@[to_additive]` is called with a `name` argument `new_namespace.new_name` /with a dot/, then `to_additive` uses this new name as is. As a safety check, in the first case `to_additive` double checks that the new name differs from the original one. -/ @[user_attribute] protected meta def attr : user_attribute unit value_type := { name := `to_additive, descr := "Transport multiplicative to additive", parser := parser, after_set := some $ λ src prio persistent, do guard persistent <|> fail "`to_additive` can't be used as a local attribute", env ← get_env, val ← attr.get_param src, dict ← aux_attr.get_cache, ignore ← ignore_args_attr.get_cache, relevant ← relevant_arg_attr.get_cache, reorder ← reorder_attr.get_cache, tgt ← target_name src val.tgt dict val.allow_auto_name, aux_attr.set src tgt tt, let dict := dict.insert src tgt, first_mult_arg ← first_multiplicative_arg src, when (first_mult_arg ≠ 1) $ relevant_arg_attr.set src first_mult_arg tt, if env.contains tgt then proceed_fields env src tgt prio else do transform_decl_with_prefix_dict dict val.replace_all val.trace relevant ignore reorder src tgt [`reducible, `_refl_lemma, `simp, `norm_cast, `instance, `refl, `symm, `trans, `elab_as_eliminator, `no_rsimp, `continuity, `ext, `ematch, `measurability, `alias, `_ext_core, `_ext_lemma_core, `nolint, `protected], mwhen (has_attribute' `simps src) (trace "Apply the simps attribute after the to_additive attribute"), mwhen (has_attribute' `mono src) (trace $ "to_additive does not work with mono, apply the mono attribute to both" ++ "versions after"), match val.doc with | some doc := add_doc_string tgt doc | none := do some alias_target ← tactic.alias.get_alias_target src | skip, let alias_name := alias_target.to_name, some add_alias_name ← pure (dict.find alias_name) | skip, add_doc_string tgt alias_target.to_string end } add_tactic_doc { name := "to_additive", category := doc_category.attr, decl_names := [`to_additive.attr], tags := ["transport", "environment", "lemma derivation"] } end to_additive /- map operations -/ attribute [to_additive] has_mul has_one has_inv has_div /- the following types are supported by `@[to_additive]` and mapped to themselves. -/ attribute [to_additive empty] empty attribute [to_additive pempty] pempty attribute [to_additive punit] punit attribute [to_additive unit] unit section linter open tactic expr /-- A linter that checks that multiplicative and additive lemmas have both doc strings if one of them has one -/ @[linter] meta def linter.to_additive_doc : linter := { test := (λ d, do let mul_name := d.to_name, dict ← to_additive.aux_attr.get_cache, match dict.find mul_name with | some add_name := do mul_doc ← try_core $ doc_string mul_name, add_doc ← try_core $ doc_string add_name, match mul_doc.is_some, add_doc.is_some with | tt, ff := return $ some $ "declaration has a docstring, but its additive version `" ++ add_name.to_string ++ "` does not. You might want to pass a string argument to " ++ "`to_additive`." | ff, tt := return $ some $ "declaration has no docstring, but its additive version `" ++ add_name.to_string ++ "` does. You might want to add a doc string to the declaration." | _, _ := return none end | none := return none end), auto_decls := ff, no_errors_found := "Multiplicative and additive lemmas are consistently documented", errors_found := "The following declarations have doc strings, but their additive versions do " ++ "not (or vice versa).", is_fast := ff } end linter
68e7f0fc963fc3c8a7de11d3fe0f5b2d33fa3869
acc85b4be2c618b11fc7cb3005521ae6858a8d07
/data/nat/basic.lean
d4303d2d6ea32a77d27900d6a4f04ddf5c89d409
[ "Apache-2.0" ]
permissive
linpingchuan/mathlib
d49990b236574df2a45d9919ba43c923f693d341
5ad8020f67eb13896a41cc7691d072c9331b1f76
refs/heads/master
1,626,019,377,808
1,508,048,784,000
1,508,048,784,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,775
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, Mario Carneiro Basic operations on the natural numbers. -/ import logic.basic algebra.order universe u namespace nat variables {m n k : ℕ} theorem pos_iff_ne_zero : n > 0 ↔ n ≠ 0 := ⟨ne_of_gt, nat.pos_of_ne_zero⟩ theorem pos_iff_ne_zero' : 0 < n ↔ n ≠ 0 := pos_iff_ne_zero protected theorem le_sub_add (n m : ℕ) : n ≤ n - m + m := or.elim (le_total n m) (assume : n ≤ m, begin rw [sub_eq_zero_of_le this, zero_add], exact this end) (assume : m ≤ n, begin rw (nat.sub_add_cancel this) end) protected theorem add_sub_cancel' {n m : ℕ} (h : n ≥ m) : m + (n - m) = n := by rw [add_comm, nat.sub_add_cancel h] protected theorem sub_eq_of_eq_add (h : k = m + n) : k - m = n := begin rw [h, nat.add_sub_cancel_left] end protected theorem lt_of_sub_pos (h : n - m > 0) : m < n := lt_of_not_ge (assume : m ≥ n, have n - m = 0, from sub_eq_zero_of_le this, begin rw this at h, exact lt_irrefl _ h end) protected theorem lt_of_sub_lt_sub_right : m - k < n - k → m < n := le_imp_le_iff_lt_imp_lt.1 (λ h, nat.sub_le_sub_right h _) protected theorem lt_of_sub_lt_sub_left : m - n < m - k → k < n := le_imp_le_iff_lt_imp_lt.1 (nat.sub_le_sub_left _) protected theorem sub_lt_self (h₁ : m > 0) (h₂ : n > 0) : m - n < m := calc m - n = succ (pred m) - succ (pred n) : by rw [succ_pred_eq_of_pos h₁, succ_pred_eq_of_pos h₂] ... = pred m - pred n : by rw succ_sub_succ ... ≤ pred m : sub_le _ _ ... < succ (pred m) : lt_succ_self _ ... = m : succ_pred_eq_of_pos h₁ protected theorem le_sub_right_of_add_le (h : m + k ≤ n) : m ≤ n - k := by rw ← nat.add_sub_cancel m k; exact nat.sub_le_sub_right h k protected theorem le_sub_left_of_add_le (h : k + m ≤ n) : m ≤ n - k := nat.le_sub_right_of_add_le (by rwa add_comm at h) protected theorem lt_sub_right_of_add_lt (h : m + k < n) : m < n - k := lt_of_succ_le $ nat.le_sub_right_of_add_le $ by rw succ_add; exact succ_le_of_lt h protected theorem lt_sub_left_of_add_lt (h : k + m < n) : m < n - k := nat.lt_sub_right_of_add_lt (by rwa add_comm at h) protected theorem add_lt_of_lt_sub_right (h : m < n - k) : m + k < n := @nat.lt_of_sub_lt_sub_right _ _ k (by rwa nat.add_sub_cancel) protected theorem add_lt_of_lt_sub_left (h : m < n - k) : k + m < n := by rw add_comm; exact nat.add_lt_of_lt_sub_right h protected theorem le_add_of_sub_le_right : n - k ≤ m → n ≤ m + k := le_imp_le_iff_lt_imp_lt.2 nat.lt_sub_right_of_add_lt protected theorem le_add_of_sub_le_left : n - k ≤ m → n ≤ k + m := le_imp_le_iff_lt_imp_lt.2 nat.lt_sub_left_of_add_lt protected theorem lt_add_of_sub_lt_right : n - k < m → n < m + k := le_imp_le_iff_lt_imp_lt.1 nat.le_sub_right_of_add_le protected theorem lt_add_of_sub_lt_left : n - k < m → n < k + m := le_imp_le_iff_lt_imp_lt.1 nat.le_sub_left_of_add_le protected theorem sub_le_left_of_le_add : n ≤ k + m → n - k ≤ m := le_imp_le_iff_lt_imp_lt.2 nat.add_lt_of_lt_sub_left protected theorem sub_le_right_of_le_add : n ≤ m + k → n - k ≤ m := le_imp_le_iff_lt_imp_lt.2 nat.add_lt_of_lt_sub_right protected theorem sub_lt_left_iff_lt_add (H : n ≤ k) : k - n < m ↔ k < n + m := ⟨nat.lt_add_of_sub_lt_left, λ h₁, have succ k ≤ n + m, from succ_le_of_lt h₁, have succ (k - n) ≤ m, from calc succ (k - n) = succ k - n : by rw (succ_sub H) ... ≤ n + m - n : nat.sub_le_sub_right this n ... = m : by rw nat.add_sub_cancel_left, lt_of_succ_le this⟩ protected theorem le_sub_left_iff_add_le (H : m ≤ k) : n ≤ k - m ↔ m + n ≤ k := le_iff_le_iff_lt_iff_lt.2 (nat.sub_lt_left_iff_lt_add H) @[simp] protected theorem le_sub_right_iff_add_le (H : n ≤ k) : m ≤ k - n ↔ m + n ≤ k := by rw [nat.le_sub_left_iff_add_le H, add_comm] protected theorem lt_sub_left_iff_add_lt (H : m ≤ k) : n < k - m ↔ m + n < k := ⟨λ h, by have := nat.add_le_add_left h m; rwa [nat.add_sub_cancel' H] at this, nat.lt_sub_left_of_add_lt⟩ @[simp] protected theorem lt_sub_right_iff_add_lt (H : n ≤ k) : m < k - n ↔ m + n < k := by rw [nat.lt_sub_left_iff_add_lt H, add_comm] theorem sub_le_left_iff_le_add (H : n ≤ m) : m - n ≤ k ↔ m ≤ n + k := le_iff_le_iff_lt_iff_lt.2 (nat.lt_sub_left_iff_add_lt H) @[simp] theorem sub_le_right_iff_le_add (H : k ≤ m) : m - k ≤ n ↔ m ≤ n + k := by rw [nat.sub_le_left_iff_le_add H, add_comm] @[simp] protected theorem sub_lt_right_iff_lt_add (H : k ≤ m) : m - k < n ↔ m < n + k := by rw [nat.sub_lt_left_iff_lt_add H, add_comm] protected theorem sub_le_sub_left_iff (H : k ≤ m) : m - n ≤ m - k ↔ k ≤ n := ⟨λ h, have k + (m - k) - n ≤ m - k, by rwa nat.add_sub_cancel' H, nat.le_of_add_le_add_right (nat.le_add_of_sub_le_left this), nat.sub_le_sub_left _⟩ protected theorem sub_lt_sub_right_iff (H : k ≤ m) : m - k < n - k ↔ m < n := le_iff_le_iff_lt_iff_lt.1 (nat.sub_le_sub_right_iff _ _ _ H) protected theorem sub_lt_sub_left_iff (H : n ≤ m) : m - n < m - k ↔ k < n := le_iff_le_iff_lt_iff_lt.1 (nat.sub_le_sub_left_iff H) protected theorem sub_le_iff (h₁ : n ≤ m) (h₂ : k ≤ m) : m - n ≤ k ↔ m - k ≤ n := (nat.sub_le_left_iff_le_add h₁).trans (nat.sub_le_right_iff_le_add h₂).symm protected theorem sub_lt_iff (h₁ : n ≤ m) (h₂ : k ≤ m) : m - n < k ↔ m - k < n := (nat.sub_lt_left_iff_lt_add h₁).trans (nat.sub_lt_right_iff_lt_add h₂).symm lemma lt_pred_of_succ_lt {n m : ℕ} : succ n < m → n < pred m := @nat.lt_sub_right_of_add_lt n m 1 protected theorem mul_ne_zero {n m : ℕ} (n0 : n ≠ 0) (m0 : m ≠ 0) : n * m ≠ 0 | nm := (eq_zero_of_mul_eq_zero nm).elim n0 m0 protected theorem eq_mul_of_div_eq_right {a b c : ℕ} (H1 : b ∣ a) (H2 : a / b = c) : a = b * c := by rw [← H2, nat.mul_div_cancel' H1] protected theorem div_eq_iff_eq_mul_right {a b c : ℕ} (H : b > 0) (H' : b ∣ a) : a / b = c ↔ a = b * c := ⟨nat.eq_mul_of_div_eq_right H', nat.div_eq_of_eq_mul_right H⟩ protected theorem div_eq_iff_eq_mul_left {a b c : ℕ} (H : b > 0) (H' : b ∣ a) : a / b = c ↔ a = c * b := by rw mul_comm; exact nat.div_eq_iff_eq_mul_right H H' protected theorem eq_mul_of_div_eq_left {a b c : ℕ} (H1 : b ∣ a) (H2 : a / b = c) : a = c * b := by rw [mul_comm, nat.eq_mul_of_div_eq_right H1 H2] protected theorem mul_right_inj {a b c : ℕ} (ha : a > 0) : b * a = c * a ↔ b = c := ⟨nat.eq_of_mul_eq_mul_right ha, λ e, e ▸ rfl⟩ protected theorem mul_left_inj {a b c : ℕ} (ha : a > 0) : a * b = a * c ↔ b = c := ⟨nat.eq_of_mul_eq_mul_left ha, λ e, e ▸ rfl⟩ @[simp] protected theorem dvd_one {n : ℕ} : n ∣ 1 ↔ n = 1 := ⟨eq_one_of_dvd_one, λ e, e.symm ▸ dvd_refl _⟩ protected theorem mul_dvd_mul_iff_left {a b c : ℕ} (ha : a > 0) : a * b ∣ a * c ↔ b ∣ c := exists_congr $ λ d, by rw [mul_assoc, nat.mul_left_inj ha] protected theorem mul_dvd_mul_iff_right {a b c : ℕ} (hc : c > 0) : a * c ∣ b * c ↔ a ∣ b := exists_congr $ λ d, by rw [mul_right_comm, nat.mul_right_inj hc] theorem add_pos_left {m : ℕ} (h : m > 0) (n : ℕ) : m + n > 0 := calc m + n > 0 + n : nat.add_lt_add_right h n ... = n : nat.zero_add n ... ≥ 0 : zero_le n theorem add_pos_right (m : ℕ) {n : ℕ} (h : n > 0) : m + n > 0 := begin rw add_comm, exact add_pos_left h m end theorem add_pos_iff_pos_or_pos (m n : ℕ) : m + n > 0 ↔ m > 0 ∨ n > 0 := iff.intro begin intro h, cases m with m, {simp [zero_add] at h, exact or.inr h}, exact or.inl (succ_pos _) end begin intro h, cases h with mpos npos, { apply add_pos_left mpos }, apply add_pos_right _ npos end theorem succ_le_succ_iff {m n : ℕ} : succ m ≤ succ n ↔ m ≤ n := ⟨le_of_succ_le_succ, succ_le_succ⟩ theorem lt_succ_iff {m n : ℕ} : m < succ n ↔ m ≤ n := succ_le_succ_iff lemma lt_succ_iff_lt_or_eq {n i : ℕ} : n < i.succ ↔ (n < i ∨ n = i) := lt_succ_iff.trans le_iff_lt_or_eq theorem le_zero_iff {i : ℕ} : i ≤ 0 ↔ i = 0 := ⟨nat.eq_zero_of_le_zero, assume h, h ▸ le_refl i⟩ theorem le_add_one_iff {i j : ℕ} : i ≤ j + 1 ↔ (i ≤ j ∨ i = j + 1) := ⟨assume h, match nat.eq_or_lt_of_le h with | or.inl h := or.inr h | or.inr h := or.inl $ nat.le_of_succ_le_succ h end, or.rec (assume h, le_trans h $ nat.le_add_right _ _) le_of_eq⟩ theorem mul_self_inj {n m : ℕ} : n * n = m * m ↔ n = m := le_antisymm_iff.trans (le_antisymm_iff.trans (and_congr mul_self_le_mul_self_iff mul_self_le_mul_self_iff)).symm instance decidable_ball_lt (n : nat) (P : Π k < n, Prop) [H : ∀ n h, decidable (P n h)] : decidable (∀ n h, P n h) := begin induction n with n IH, { exact is_true (λ n, dec_trivial) }, cases IH (λ k h, P k (lt_succ_of_lt h)), { refine is_false (mt _ a), intros hn k h, apply hn }, by_cases P n (lt_succ_self n) with p, { exact is_true (λ k h, (lt_or_eq_of_le $ le_of_lt_succ h).elim (a _) (λ e, match k, e, h with _, rfl, h := p end)) }, { exact is_false (mt (λ hn, hn _ _) p) } end instance decidable_forall_fin {n : ℕ} (P : fin n → Prop) [H : decidable_pred P] : decidable (∀ i, P i) := decidable_of_iff (∀ k h, P ⟨k, h⟩) ⟨λ a ⟨k, h⟩, a k h, λ a k h, a ⟨k, h⟩⟩ instance decidable_ball_le (n : ℕ) (P : Π k ≤ n, Prop) [H : ∀ n h, decidable (P n h)] : decidable (∀ n h, P n h) := decidable_of_iff (∀ k (h : k < succ n), P k (le_of_lt_succ h)) ⟨λ a k h, a k (lt_succ_of_le h), λ a k h, a k _⟩ instance decidable_lo_hi (lo hi : ℕ) (P : ℕ → Prop) [H : decidable_pred P] : decidable (∀x, lo ≤ x → x < hi → P x) := decidable_of_iff (∀ x < hi - lo, P (lo + x)) ⟨λal x hl hh, by have := al (x - lo) (lt_of_not_ge $ (not_congr (nat.sub_le_sub_right_iff _ _ _ hl)).2 $ not_le_of_gt hh); rwa [nat.add_sub_of_le hl] at this, λal x h, al _ (nat.le_add_right _ _) (nat.add_lt_of_lt_sub_left h)⟩ instance decidable_lo_hi_le (lo hi : ℕ) (P : ℕ → Prop) [H : decidable_pred P] : decidable (∀x, lo ≤ x → x ≤ hi → P x) := decidable_of_iff (∀x, lo ≤ x → x < hi + 1 → P x) $ ball_congr $ λ x hl, imp_congr lt_succ_iff iff.rfl protected theorem bit0_le {n m : ℕ} (h : n ≤ m) : bit0 n ≤ bit0 m := add_le_add h h protected theorem bit1_le {n m : ℕ} (h : n ≤ m) : bit1 n ≤ bit1 m := succ_le_succ (add_le_add h h) theorem bit_le : ∀ (b : bool) {n m : ℕ}, n ≤ m → bit b n ≤ bit b m | tt n m h := nat.bit1_le h | ff n m h := nat.bit0_le h theorem bit_ne_zero (b) {n} (h : n ≠ 0) : bit b n ≠ 0 := by cases b; [exact nat.bit0_ne_zero h, exact nat.bit1_ne_zero _] theorem bit0_le_bit : ∀ (b) {m n : ℕ}, m ≤ n → bit0 m ≤ bit b n | tt m n h := le_of_lt $ nat.bit0_lt_bit1 h | ff m n h := nat.bit0_le h theorem bit_le_bit1 : ∀ (b) {m n : ℕ}, m ≤ n → bit b m ≤ bit1 n | ff m n h := le_of_lt $ nat.bit0_lt_bit1 h | tt m n h := nat.bit1_le h theorem bit_lt_bit0 : ∀ (b) {n m : ℕ}, n < m → bit b n < bit0 m | tt n m h := nat.bit1_lt_bit0 h | ff n m h := nat.bit0_lt h theorem bit_lt_bit (a b) {n m : ℕ} (h : n < m) : bit a n < bit b m := lt_of_lt_of_le (bit_lt_bit0 _ h) (bit0_le_bit _ (le_refl _)) /- pow -/ theorem pow_add (a m n : ℕ) : a^(m + n) = a^m * a^n := by induction n; simp [*, pow_succ] theorem pow_dvd_pow (a : ℕ) {m n : ℕ} (h : m ≤ n) : a^m ∣ a^n := by rw [← nat.add_sub_cancel' h, pow_add]; apply dvd_mul_right @[simp] theorem bodd_div2_eq (n : ℕ) : bodd_div2 n = (bodd n, div2 n) := by unfold bodd div2; cases bodd_div2 n; refl /- size and shift -/ theorem shiftl'_ne_zero_left (b) {m} (h : m ≠ 0) (n) : shiftl' b m n ≠ 0 := by induction n; simp [shiftl', bit_ne_zero, *] theorem shiftl'_tt_ne_zero (m) : ∀ {n} (h : n ≠ 0), shiftl' tt m n ≠ 0 | 0 h := absurd rfl h | (succ n) _ := nat.bit1_ne_zero _ @[simp] theorem size_zero : size 0 = 0 := rfl @[simp] theorem size_bit {b n} (h : bit b n ≠ 0) : size (bit b n) = succ (size n) := begin rw size, conv { to_lhs, rw [binary_rec], simp [h] }, rw div2_bit, refl end @[simp] theorem size_bit0 {n} (h : n ≠ 0) : size (bit0 n) = succ (size n) := @size_bit ff n (nat.bit0_ne_zero h) @[simp] theorem size_bit1 (n) : size (bit1 n) = succ (size n) := @size_bit tt n (nat.bit1_ne_zero n) @[simp] theorem size_shiftl' {b m n} (h : shiftl' b m n ≠ 0) : size (shiftl' b m n) = size m + n := begin induction n with n IH; simp [shiftl'] at h ⊢, rw [size_bit h, nat.add_succ], by_cases shiftl' b m n = 0 with s0; [skip, rw [IH s0]], rw s0 at h ⊢, cases b, {exact absurd rfl h}, have : shiftl' tt m n + 1 = 1 := congr_arg (+1) s0, rw [shiftl'_tt_eq_mul_pow] at this, have m0 := succ_inj (eq_one_of_dvd_one ⟨_, this.symm⟩), subst m0, simp at this, have : n = 0 := eq_zero_of_le_zero (le_of_not_gt $ λ hn, ne_of_gt (pow_lt_pow_of_lt_right dec_trivial hn) this), subst n, refl end @[simp] theorem size_shiftl {m} (h : m ≠ 0) (n) : size (shiftl m n) = size m + n := size_shiftl' (shiftl'_ne_zero_left _ h _) theorem lt_size_self (n : ℕ) : n < 2^size n := begin rw [← one_shiftl], have : ∀ {n}, n = 0 → n < shiftl 1 (size n) := λ n e, by subst e; exact dec_trivial, apply binary_rec _ _ n, {apply this rfl}, intros b n IH, by_cases bit b n = 0, {apply this h}, rw [size_bit h, shiftl_succ], exact bit_lt_bit0 _ IH end theorem size_le {m n : ℕ} : size m ≤ n ↔ m < 2^n := ⟨λ h, lt_of_lt_of_le (lt_size_self _) (pow_le_pow_of_le_right dec_trivial h), begin rw [← one_shiftl], revert n, apply binary_rec _ _ m, { intros n h, apply zero_le }, { intros b m IH n h, by_cases bit b m = 0 with e, { rw e, apply zero_le }, rw [size_bit e], cases n with n, { exact e.elim (eq_zero_of_le_zero (le_of_lt_succ h)) }, { apply succ_le_succ (IH _), apply le_imp_le_iff_lt_imp_lt.1 (λ h', bit0_le_bit _ h') h } } end⟩ theorem lt_size {m n : ℕ} : m < size n ↔ 2^m ≤ n := by rw [← not_lt, iff_not_comm, not_lt, size_le] theorem size_pos {n : ℕ} : 0 < size n ↔ 0 < n := by rw lt_size; refl theorem size_eq_zero {n : ℕ} : size n = 0 ↔ n = 0 := by have := @size_pos n; simp [pos_iff_ne_zero'] at this; exact not_iff_not.1 this theorem size_pow {n : ℕ} : size (2^n) = n+1 := le_antisymm (size_le.2 $ pow_lt_pow_of_lt_right dec_trivial (lt_succ_self _)) (lt_size.2 $ le_refl _) theorem size_le_size {m n : ℕ} (h : m ≤ n) : size m ≤ size n := size_le.2 $ lt_of_le_of_lt h (lt_size_self _) /- factorial -/ @[simp] def fact : nat → nat | 0 := 1 | (succ n) := (succ n) * fact n @[simp] theorem fact_zero : fact 0 = 1 := rfl @[simp] theorem fact_one : fact 1 = 1 := rfl @[simp] theorem fact_succ (n) : fact (succ n) = succ n * fact n := rfl theorem fact_pos : ∀ n, fact n > 0 | 0 := zero_lt_one | (succ n) := mul_pos (succ_pos _) (fact_pos n) theorem fact_ne_zero (n : ℕ) : fact n ≠ 0 := ne_of_gt (fact_pos _) theorem fact_dvd_fact {m n} (h : m ≤ n) : fact m ∣ fact n := begin induction n with n IH; simp, { have := eq_zero_of_le_zero h, subst m, simp }, { cases eq_or_lt_of_le h with he hl, { subst m, simp }, { apply dvd_mul_of_dvd_left (IH (le_of_lt_succ hl)) } } end theorem dvd_fact : ∀ {m n}, m > 0 → m ≤ n → m ∣ fact n | (succ m) n _ h := dvd_of_mul_right_dvd (fact_dvd_fact h) theorem fact_le {m n} (h : m ≤ n) : fact m ≤ fact n := le_of_dvd (fact_pos _) (fact_dvd_fact h) end nat
a1d1b231aa63bc70f276dff6a2de2240b74cd9ae
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/data/fintype/basic.lean
455b5ad7999b52f310e5263d95027a0dd8241498
[ "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
9,216
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 Finite type (type class). -/ import data.list.perm data.list.as_type data.bool data.equiv open list bool unit decidable option function structure fintype [class] (A : Type) : Type := (elems : list A) (unique : nodup elems) (complete : ∀ a, a ∈ elems) definition elements_of (A : Type) [h : fintype A] : list A := @fintype.elems A h section open equiv definition fintype_of_equiv {A B : Type} [h : fintype A] : A ≃ B → fintype B | (mk f g l r) := fintype.mk (map f (elements_of A)) (nodup_map (injective_of_left_inverse l) !fintype.unique) (λ b, have g b ∈ elements_of A, from fintype.complete (g b), have f (g b) ∈ map f (elements_of A), from mem_map f this, by rewrite r at this; exact this) end attribute [instance] definition fintype_unit : fintype unit := fintype.mk [star] dec_trivial (λ u, match u with star := dec_trivial end) attribute [instance] definition fintype_bool : fintype bool := fintype.mk [ff, tt] dec_trivial (λ b, match b with | tt := dec_trivial | ff := dec_trivial end) attribute [instance] definition fintype_product {A B : Type} : Π [h₁ : fintype A] [h₂ : fintype B], fintype (A × B) | (fintype.mk e₁ u₁ c₁) (fintype.mk e₂ u₂ c₂) := fintype.mk (product e₁ e₂) (nodup_product u₁ u₂) (λ p, match p with (a, b) := mem_product (c₁ a) (c₂ b) end) /- auxiliary function for finding 'a' s.t. f a ≠ g a -/ section find_discr variables {A B : Type} variable [h : decidable_eq B] include h definition find_discr (f g : A → B) : list A → option A | [] := none | (a::l) := if f a = g a then find_discr l else some a theorem find_discr_nil (f g : A → B) : find_discr f g [] = none := rfl theorem find_discr_cons_of_ne {f g : A → B} {a : A} (l : list A) : f a ≠ g a → find_discr f g (a::l) = some a := assume ne, if_neg ne theorem find_discr_cons_of_eq {f g : A → B} {a : A} (l : list A) : f a = g a → find_discr f g (a::l) = find_discr f g l := assume eq, if_pos eq theorem ne_of_find_discr_eq_some {f g : A → B} {a : A} : ∀ {l}, find_discr f g l = some a → f a ≠ g a | [] e := by contradiction | (x::l) e := by_cases (suppose f x = g x, have find_discr f g l = some a, by rewrite [find_discr_cons_of_eq l this at e]; exact e, ne_of_find_discr_eq_some this) (assume h : f x ≠ g x, have some x = some a, by rewrite [find_discr_cons_of_ne l h at e]; exact e, by clear ne_of_find_discr_eq_some; injection this; subst a; exact h) theorem all_eq_of_find_discr_eq_none {f g : A → B} : ∀ {l}, find_discr f g l = none → ∀ a, a ∈ l → f a = g a | [] e a i := absurd i !not_mem_nil | (x::l) e a i := by_cases (assume fx_eq_gx : f x = g x, or.elim (eq_or_mem_of_mem_cons i) (suppose a = x, by rewrite [-this at fx_eq_gx]; exact fx_eq_gx) (suppose a ∈ l, have aux : find_discr f g l = none, by rewrite [find_discr_cons_of_eq l fx_eq_gx at e]; exact e, all_eq_of_find_discr_eq_none aux a this)) (suppose f x ≠ g x, by rewrite [find_discr_cons_of_ne l this at e]; contradiction) end find_discr attribute [instance] definition decidable_eq_fun {A B : Type} [h₁ : fintype A] [h₂ : decidable_eq B] : decidable_eq (A → B) := λ f g, match h₁ with | fintype.mk e u c := match find_discr f g e with | some a := λ h : find_discr f g e = some a, inr (λ f_eq_g : f = g, absurd (by rewrite f_eq_g; reflexivity) (ne_of_find_discr_eq_some h)) | none := λ h : find_discr f g e = none, inl (show f = g, from funext (λ a : A, all_eq_of_find_discr_eq_none h a (c a))) end rfl end section check_pred variables {A : Type} definition check_pred (p : A → Prop) [h : decidable_pred p] : list A → bool | [] := tt | (a::l) := if p a then check_pred l else ff theorem check_pred_cons_of_pos {p : A → Prop} [h : decidable_pred p] {a : A} (l : list A) : p a → check_pred p (a::l) = check_pred p l := assume pa, if_pos pa theorem check_pred_cons_of_neg {p : A → Prop} [h : decidable_pred p] {a : A} (l : list A) : ¬ p a → check_pred p (a::l) = ff := assume npa, if_neg npa theorem all_of_check_pred_eq_tt {p : A → Prop} [h : decidable_pred p] : ∀ {l : list A}, check_pred p l = tt → ∀ {a}, a ∈ l → p a | [] eqtt a ainl := absurd ainl !not_mem_nil | (b::l) eqtt a ainbl := by_cases (suppose p b, or.elim (eq_or_mem_of_mem_cons ainbl) (suppose a = b, by rewrite [this]; exact `p b`) (suppose a ∈ l, have check_pred p l = tt, by rewrite [check_pred_cons_of_pos _ `p b` at eqtt]; exact eqtt, all_of_check_pred_eq_tt this `a ∈ l`)) (suppose ¬ p b, by rewrite [check_pred_cons_of_neg _ this at eqtt]; exact (bool.no_confusion eqtt)) theorem ex_of_check_pred_eq_ff {p : A → Prop} [h : decidable_pred p] : ∀ {l : list A}, check_pred p l = ff → ∃ w, ¬ p w | [] eqtt := bool.no_confusion eqtt | (a::l) eqtt := by_cases (suppose p a, have check_pred p l = ff, by rewrite [check_pred_cons_of_pos _ this at eqtt]; exact eqtt, ex_of_check_pred_eq_ff this) (suppose ¬ p a, exists.intro a this) end check_pred attribute [instance] definition decidable_forall_finite {A : Type} {p : A → Prop} [h₁ : fintype A] [h₂ : decidable_pred p] : decidable (∀ x : A, p x) := match h₁ with | fintype.mk e u c := match check_pred p e with | tt := suppose check_pred p e = tt, inl (take a : A, all_of_check_pred_eq_tt this (c a)) | ff := suppose check_pred p e = ff, inr (suppose ∀ x, p x, obtain (a : A) (w : ¬ p a), from ex_of_check_pred_eq_ff `check_pred p e = ff`, absurd (this a) w) end rfl end attribute [instance] definition decidable_exists_finite {A : Type} {p : A → Prop} [h₁ : fintype A] [h₂ : decidable_pred p] : decidable (∃ x : A, p x) := match h₁ with | fintype.mk e u c := match check_pred (λ a, ¬ p a) e with | tt := λ h : check_pred (λ a, ¬ p a) e = tt, inr (λ ex : (∃ x, p x), obtain x px, from ex, absurd px (all_of_check_pred_eq_tt h (c x))) | ff := λ h : check_pred (λ a, ¬ p a) e = ff, inl ( have ∃ x, ¬¬p x, from ex_of_check_pred_eq_ff h, obtain x nnpx, from this, exists.intro x (not_not_elim nnpx)) end rfl end open list.as_type -- Auxiliary function for returning a list with all elements of the type: (list.as_type l) -- Remark ⟪s⟫ is notation for (list.as_type l) -- We use this function to define the instance for (fintype ⟪s⟫) private definition ltype_elems {A : Type} {s : list A} : Π {l : list A}, l ⊆ s → list ⟪s⟫ | [] h := [] | (a::l) h := lval a (h a !mem_cons) :: ltype_elems (sub_of_cons_sub h) private theorem mem_of_mem_ltype_elems {A : Type} {a : A} {s : list A} : Π {l : list A} {h : l ⊆ s} {m : a ∈ s}, mk a m ∈ ltype_elems h → a ∈ l | [] h m lin := absurd lin !not_mem_nil | (b::l) h m lin := or.elim (eq_or_mem_of_mem_cons lin) (suppose mk a m = mk b (h b (mem_cons b l)), as_type.no_confusion this (λ aeqb em, by rewrite [aeqb]; exact !mem_cons)) (suppose mk a m ∈ ltype_elems (sub_of_cons_sub h), have a ∈ l, from mem_of_mem_ltype_elems this, mem_cons_of_mem _ this) private theorem nodup_ltype_elems {A : Type} {s : list A} : Π {l : list A} (d : nodup l) (h : l ⊆ s), nodup (ltype_elems h) | [] d h := nodup_nil | (a::l) d h := have d₁ : nodup l, from nodup_of_nodup_cons d, have nainl : a ∉ l, from not_mem_of_nodup_cons d, let h₁ : l ⊆ s := sub_of_cons_sub h in have d₂ : nodup (ltype_elems h₁), from nodup_ltype_elems d₁ h₁, have nin : mk a (h a (mem_cons a l)) ∉ ltype_elems h₁, from assume ab, absurd (mem_of_mem_ltype_elems ab) nainl, nodup_cons nin d₂ private theorem mem_ltype_elems {A : Type} {s : list A} {a : ⟪s⟫} : Π {l : list A} (h : l ⊆ s), value a ∈ l → a ∈ ltype_elems h | [] h vainl := absurd vainl !not_mem_nil | (b::l) h vainbl := or.elim (eq_or_mem_of_mem_cons vainbl) (λ vaeqb : value a = b, begin revert vaeqb h, -- TODO(Leo): check why 'cases a with va, ma' produces an incorrect proof eapply as_type.cases_on a, intro va ma vaeqb, rewrite -vaeqb, intro h, apply mem_cons end) (λ vainl : value a ∈ l, have aux : a ∈ ltype_elems (sub_of_cons_sub h), from mem_ltype_elems (sub_of_cons_sub h) vainl, mem_cons_of_mem _ aux) attribute [instance] definition fintype_list_as_type {A : Type} [h : decidable_eq A] {s : list A} : fintype ⟪s⟫ := let nds : list A := erase_dup s in have sub₁ : nds ⊆ s, from erase_dup_sub s, have sub₂ : s ⊆ nds, from sub_erase_dup s, have dnds : nodup nds, from nodup_erase_dup s, let e : list ⟪s⟫ := ltype_elems sub₁ in fintype.mk e (nodup_ltype_elems dnds sub₁) (take a : ⟪s⟫, show a ∈ e, from have value a ∈ s, from is_member a, have value a ∈ nds, from sub₂ this, mem_ltype_elems sub₁ this)
47e6a09b6fae9fb95863cfa199664cda0138a66e
ad0c7d243dc1bd563419e2767ed42fb323d7beea
/analysis/measure_theory/lebesgue_measure.lean
da2fa93af2b3fbddc360766bf1c777c58b3e8ebd
[ "Apache-2.0" ]
permissive
sebzim4500/mathlib
e0b5a63b1655f910dee30badf09bd7e191d3cf30
6997cafbd3a7325af5cb318561768c316ceb7757
refs/heads/master
1,585,549,958,618
1,538,221,723,000
1,538,221,723,000
150,869,076
0
0
Apache-2.0
1,538,229,323,000
1,538,229,323,000
null
UTF-8
Lean
false
false
10,864
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl Lebesgue measure on the real line -/ import analysis.measure_theory.measure_space analysis.measure_theory.borel_space noncomputable theory open classical set lattice filter open nnreal (of_real) namespace measure_theory /-- Length of an interval. This is the largest monotonic function which correctly measures all intervals. -/ def lebesgue_length (s : set ℝ) : ennreal := ⨅a b (h : s ⊆ Ico a b), of_real (b - a) @[simp] lemma lebesgue_length_empty : lebesgue_length ∅ = 0 := le_zero_iff_eq.1 $ infi_le_of_le 0 $ infi_le_of_le 0 $ by simp @[simp] lemma lebesgue_length_Ico (a b : ℝ) : lebesgue_length (Ico a b) = of_real (b - a) := begin refine le_antisymm (infi_le_of_le a $ infi_le_of_le b $ infi_le _ (by refl)) (le_infi $ λ a', le_infi $ λ b', le_infi $ λ h, ennreal.coe_le_coe.2 _), cases le_or_lt b a with ab ab, { rw nnreal.of_real_of_nonpos (sub_nonpos.2 ab), simp }, cases (Ico_subset_Ico_iff ab).1 h with h₁ h₂, exact nnreal.of_real_le_of_real (sub_le_sub h₂ h₁) end lemma lebesgue_length_mono {s₁ s₂ : set ℝ} (h : s₁ ⊆ s₂) : lebesgue_length s₁ ≤ lebesgue_length s₂ := infi_le_infi $ λ a, infi_le_infi $ λ b, infi_le_infi2 $ λ h', ⟨subset.trans h h', le_refl _⟩ lemma lebesgue_length_eq_infi_Ioo (s) : lebesgue_length s = ⨅a b (h : s ⊆ Ioo a b), of_real (b - a) := begin refine le_antisymm (infi_le_infi $ λ a, infi_le_infi $ λ b, infi_le_infi2 $ λ h, ⟨subset.trans h Ioo_subset_Ico_self, le_refl _⟩) _, refine le_infi (λ a, le_infi $ λ b, le_infi $ λ h, _), refine ennreal.le_of_forall_epsilon_le (λ ε ε0 _, _), refine infi_le_of_le (a - ε) (infi_le_of_le b $ infi_le_of_le (subset.trans h $ Ico_subset_Ioo_left $ (sub_lt_self_iff _).2 ε0) _), rw [← sub_add, ← ennreal.coe_add, ennreal.coe_le_coe], apply le_trans nnreal.of_real_add_le _, simp, end @[simp] lemma lebesgue_length_Ioo (a b : ℝ) : lebesgue_length (Ioo a b) = of_real (b - a) := begin rw ← lebesgue_length_Ico, refine le_antisymm (lebesgue_length_mono Ioo_subset_Ico_self) _, rw lebesgue_length_eq_infi_Ioo (Ioo a b), refine (le_infi $ λ a', le_infi $ λ b', le_infi $ λ h, _), cases le_or_lt b a with ab ab, {simp [ab]}, cases (Ioo_subset_Ioo_iff ab).1 h with h₁ h₂, rw [lebesgue_length_Ico, ennreal.coe_le_coe], exact nnreal.of_real_le_of_real (sub_le_sub h₂ h₁) end lemma lebesgue_length_eq_infi_Icc (s) : lebesgue_length s = ⨅a b (h : s ⊆ Icc a b), of_real (b - a) := begin refine le_antisymm _ (infi_le_infi $ λ a, infi_le_infi $ λ b, infi_le_infi2 $ λ h, ⟨subset.trans h Ico_subset_Icc_self, le_refl _⟩), refine le_infi (λ a, le_infi $ λ b, le_infi $ λ h, _), refine ennreal.le_of_forall_epsilon_le (λ ε ε0 _, _), refine infi_le_of_le a (infi_le_of_le (b + ε) $ infi_le_of_le (subset.trans h $ Icc_subset_Ico_right $ (lt_add_iff_pos_right _).2 ε0) _), rw [sub_eq_add_neg, add_right_comm, ←ennreal.coe_add, ennreal.coe_le_coe], apply le_trans nnreal.of_real_add_le, simp end @[simp] lemma lebesgue_length_Icc (a b : ℝ) : lebesgue_length (Icc a b) = of_real (b - a) := begin rw ← lebesgue_length_Ico, refine le_antisymm _ (lebesgue_length_mono Ico_subset_Icc_self), rw lebesgue_length_eq_infi_Icc (Icc a b), exact infi_le_of_le a (infi_le_of_le b $ infi_le_of_le (by refl) (by simp)) end /-- The Lebesgue outer measure, as an outer measure of ℝ. -/ def lebesgue_outer : outer_measure ℝ := outer_measure.of_function lebesgue_length lebesgue_length_empty lemma lebesgue_outer_le_length (s : set ℝ) : lebesgue_outer s ≤ lebesgue_length s := outer_measure.of_function_le _ _ _ lemma lebesgue_length_subadditive {a b : ℝ} {c d : ℕ → ℝ} (ss : Icc a b ⊆ ⋃i, Ioo (c i) (d i)) : (of_real (b - a) : ennreal) ≤ ∑ i, of_real (d i - c i) := begin suffices : ∀ (s:finset ℕ) b (cv : Icc a b ⊆ ⋃ i ∈ (↑s:set ℕ), Ioo (c i) (d i)), (of_real (b - a) : ennreal) ≤ s.sum (λ i, of_real (d i - c i)), { rcases @compact_elim_finite_subcover_image _ _ _ (Icc a b) univ (λ i, Ioo (c i) (d i)) compact_Icc (λ i _, is_open_Ioo) (by simpa using ss) with ⟨s, su, hf, hs⟩, have e : (⋃ i ∈ (↑hf.to_finset:set ℕ), Ioo (c i) (d i)) = (⋃ i ∈ s, Ioo (c i) (d i)), {simp [set.ext_iff]}, rw ennreal.tsum_eq_supr_sum, refine le_trans _ (le_supr _ hf.to_finset), exact this hf.to_finset _ (by simpa [e]) }, clear ss b, refine λ s, finset.strong_induction_on s (λ s IH b cv, _), cases le_total b a with ab ab, { rw nnreal.of_real_of_nonpos (sub_nonpos.2 ab), simp }, have := cv ⟨ab, le_refl _⟩, simp at this, rcases this with ⟨i, is, cb, bd⟩, rw [← finset.insert_erase is] at cv ⊢, rw [finset.coe_insert, bUnion_insert] at cv, rw [finset.sum_insert (finset.not_mem_erase _ _)], refine le_trans _ (add_le_add_left' (IH _ (finset.erase_ssubset is) (c i) _)), { rw [← ennreal.coe_add, ennreal.coe_le_coe], refine le_trans (nnreal.of_real_le_of_real _) nnreal.of_real_add_le, rw sub_add_sub_cancel, exact sub_le_sub_right (le_of_lt bd) _ }, { rintro x ⟨h₁, h₂⟩, refine (cv ⟨h₁, le_trans h₂ (le_of_lt cb)⟩).resolve_left (mt and.left (not_lt_of_le h₂)) } end @[simp] lemma lebesgue_outer_Icc (a b : ℝ) : lebesgue_outer (Icc a b) = of_real (b - a) := begin refine le_antisymm (by rw ← lebesgue_length_Icc; apply lebesgue_outer_le_length) (le_infi $ λ f, le_infi $ λ hf, ennreal.le_of_forall_epsilon_le $ λ ε ε0 h, _), rcases ennreal.exists_pos_sum_of_encodable (ennreal.zero_lt_coe_iff.2 ε0) ℕ with ⟨ε', ε'0, hε⟩, refine le_trans _ (add_le_add_left' (le_of_lt hε)), rw ← ennreal.tsum_add, have : ∀ i, ∃ p:ℝ×ℝ, f i ⊆ Ioo p.1 p.2 ∧ (of_real (p.2 - p.1) : ennreal) < lebesgue_length (f i) + ε' i, { intro i, have := (ennreal.lt_add_right (lt_of_le_of_lt (ennreal.le_tsum i) h) (ennreal.zero_lt_coe_iff.2 (ε'0 i))), conv at this {to_lhs, rw lebesgue_length_eq_infi_Ioo}, simpa [infi_lt_iff] }, cases axiom_of_choice this with g hg, dsimp only at g hg, refine le_trans _ (ennreal.tsum_le_tsum $ λ i, le_of_lt (hg i).2), exact lebesgue_length_subadditive (subset.trans hf $ Union_subset_Union $ λ i, (hg i).1) end @[simp] lemma lebesgue_outer_singleton (a : ℝ) : lebesgue_outer {a} = 0 := by simpa using lebesgue_outer_Icc a a @[simp] lemma lebesgue_outer_Ico (a b : ℝ) : lebesgue_outer (Ico a b) = of_real (b - a) := begin refine le_antisymm (by rw ← lebesgue_length_Ico; apply lebesgue_outer_le_length) (ennreal.le_of_forall_epsilon_le $ λ ε ε0 h, _), have := @nnreal.of_real_add_le (b - a - ε) ε, rw [← ennreal.coe_le_coe, ennreal.coe_add, sub_add_cancel, sub_right_comm, ← lebesgue_outer_Icc a (b-ε), nnreal.of_real_coe] at this, exact le_trans this (add_le_add_right' $ lebesgue_outer.mono $ Icc_subset_Ico_right $ (sub_lt_self_iff _).2 ε0) end @[simp] lemma lebesgue_outer_Ioo (a b : ℝ) : lebesgue_outer (Ioo a b) = of_real (b - a) := begin refine le_antisymm (by rw ← lebesgue_length_Ioo; apply lebesgue_outer_le_length) (ennreal.le_of_forall_epsilon_le $ λ ε ε0 h, _), have := @nnreal.of_real_add_le (b - a - ε) ε, rw [← ennreal.coe_le_coe, ennreal.coe_add, sub_add_cancel, sub_sub, ← lebesgue_outer_Ico (a+ε) b, nnreal.of_real_coe] at this, exact le_trans this (add_le_add_right' $ lebesgue_outer.mono $ Ico_subset_Ioo_left $ (lt_add_iff_pos_right _).2 ε0) end lemma is_lebesgue_measurable_Iio {c : ℝ} : lebesgue_outer.caratheodory.is_measurable (Iio c) := outer_measure.caratheodory_is_measurable $ λ t, le_infi $ λ a, le_infi $ λ b, le_infi $ λ h, begin refine le_trans (add_le_add' (lebesgue_length_mono $ inter_subset_inter_left _ h) (lebesgue_length_mono $ diff_subset_diff_left h)) _, cases le_total a c with hac hca; cases le_total b c with hbc hcb; simp [*, -sub_eq_add_neg, sub_add_sub_cancel']; rw [← ennreal.coe_add, ennreal.coe_le_coe], { simp [*, nnreal.of_real_add_of_real, -sub_eq_add_neg, sub_add_sub_cancel'] }, { rw nnreal.of_real_of_nonpos, { simp }, exact sub_nonpos.2 (le_trans hbc hca) } end theorem lebesgue_outer_trim : lebesgue_outer.trim = lebesgue_outer := begin refine le_antisymm (λ s, _) (outer_measure.trim_ge _), rw outer_measure.trim_eq_infi, refine le_infi (λ f, le_infi $ λ hf, ennreal.le_of_forall_epsilon_le $ λ ε ε0 h, _), rcases ennreal.exists_pos_sum_of_encodable (ennreal.zero_lt_coe_iff.2 ε0) ℕ with ⟨ε', ε'0, hε⟩, refine le_trans _ (add_le_add_left' (le_of_lt hε)), rw ← ennreal.tsum_add, have : ∀ i, ∃ s, f i ⊆ s ∧ is_measurable s ∧ lebesgue_outer s ≤ lebesgue_length (f i) + of_real (ε' i), { intro i, have := (ennreal.lt_add_right (lt_of_le_of_lt (ennreal.le_tsum i) h) (ennreal.zero_lt_coe_iff.2 (ε'0 i))), conv at this {to_lhs, rw lebesgue_length}, simp only [infi_lt_iff] at this, rcases this with ⟨a, b, h₁, h₂⟩, rw ← lebesgue_outer_Ico at h₂, exact ⟨_, h₁, is_measurable_Ico, le_of_lt $ by simpa using h₂⟩ }, cases axiom_of_choice this with g hg, simp at g hg, apply infi_le_of_le (Union g) _, apply infi_le_of_le (subset.trans hf $ Union_subset_Union (λ i, (hg i).1)) _, apply infi_le_of_le (is_measurable.Union (λ i, (hg i).2.1)) _, exact le_trans (lebesgue_outer.Union _) (ennreal.tsum_le_tsum $ λ i, (hg i).2.2) end /-- Lebesgue measure on the Borel sets The outer Lebesgue measure is the completion of this measure. (TODO: proof this) -/ def lebesgue : measure ℝ := lebesgue_outer.to_measure $ calc borel ℝ = measurable_space.generate_from (⋃a:ℚ, {Iio a}) : real.borel_eq_generate_from_Iio_rat ... ≤ lebesgue_outer.caratheodory : measurable_space.generate_from_le $ by simp [is_lebesgue_measurable_Iio] {contextual := tt} @[simp] theorem lebesgue_to_outer_measure : lebesgue.to_outer_measure = lebesgue_outer := (to_measure_to_outer_measure _ _).trans lebesgue_outer_trim theorem lebesgue_val (s) : lebesgue s = lebesgue_outer s := (congr_arg (λ m:outer_measure ℝ, m s) lebesgue_to_outer_measure : _) @[simp] lemma lebesgue_Ico {a b : ℝ} : lebesgue (Ico a b) = of_real (b - a) := by simp [lebesgue_val] @[simp] lemma lebesgue_Icc {a b : ℝ} : lebesgue (Icc a b) = of_real (b - a) := by simp [lebesgue_val] @[simp] lemma lebesgue_Ioo {a b : ℝ} : lebesgue (Ioo a b) = of_real (b - a) := by simp [lebesgue_val] @[simp] lemma lebesgue_singleton {a : ℝ} : lebesgue {a} = 0 := by simp [lebesgue_val] end measure_theory
b6e7afd3e23ea22872a4f629f8ec87b082bb452d
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Elab/Mixfix.lean
8c26c72f7f531a1ad17086ae1d10cd4a237ef704
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
1,752
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.Attributes namespace Lean.Elab.Command @[builtinMacro Lean.Parser.Command.mixfix] def expandMixfix : Macro := fun stx => withAttrKindGlobal stx fun stx => do match stx with | `(infixl:$prec $[(name := $name)]? $[(priority := $prio)]? $op => $f) => let prec1 := quote <| (← evalPrec prec) + 1 `(notation:$prec $[(name := $name)]? $[(priority := $prio)]? lhs:$prec $op:strLit rhs:$prec1 => $f lhs rhs) | `(infix:$prec $[(name := $name)]? $[(priority := $prio)]? $op => $f) => let prec1 := quote <| (← evalPrec prec) + 1 `(notation:$prec $[(name := $name)]? $[(priority := $prio)]? lhs:$prec1 $op:strLit rhs:$prec1 => $f lhs rhs) | `(infixr:$prec $[(name := $name)]? $[(priority := $prio)]? $op => $f) => let prec1 := quote <| (← evalPrec prec) + 1 `(notation:$prec $[(name := $name)]? $[(priority := $prio)]? lhs:$prec1 $op:strLit rhs:$prec => $f lhs rhs) | `(prefix:$prec $[(name := $name)]? $[(priority := $prio)]? $op => $f) => `(notation:$prec $[(name := $name)]? $[(priority := $prio)]? $op:strLit arg:$prec => $f arg) | `(postfix:$prec $[(name := $name)]? $[(priority := $prio)]? $op => $f) => `(notation:$prec $[(name := $name)]? $[(priority := $prio)]? arg:$prec $op:strLit => $f arg) | _ => Macro.throwUnsupported where -- set "global" `attrKind`, apply `f`, and restore `attrKind` to result withAttrKindGlobal stx f := do let attrKind := stx[0] let stx := stx.setArg 0 mkAttrKindGlobal let stx ← f stx return stx.setArg 0 attrKind end Lean.Elab.Command
130c55f1faa00c21d228f5a5f43890f3009476b4
853df553b1d6ca524e3f0a79aedd32dde5d27ec3
/src/data/complex/exponential.lean
1ffae819a8a6cc8721f73754e886ea15d8fe57f9
[ "Apache-2.0" ]
permissive
DanielFabian/mathlib
efc3a50b5dde303c59eeb6353ef4c35a345d7112
f520d07eba0c852e96fe26da71d85bf6d40fcc2a
refs/heads/master
1,668,739,922,971
1,595,201,756,000
1,595,201,756,000
279,469,476
0
0
null
1,594,696,604,000
1,594,696,604,000
null
UTF-8
Lean
false
false
49,791
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir -/ import algebra.geom_sum import data.nat.choose import data.complex.basic /-! # Exponential, trigonometric and hyperbolic trigonometric functions This file containss the definitions of the real and complex exponential, sine, cosine, tangent, hyperbolic sine, hypebolic cosine, and hyperbolic tangent functions. -/ local notation `abs'` := _root_.abs open is_absolute_value open_locale classical big_operators section open real is_absolute_value finset lemma forall_ge_le_of_forall_le_succ {α : Type*} [preorder α] (f : ℕ → α) {m : ℕ} (h : ∀ n ≥ m, f n.succ ≤ f n) : ∀ {l}, ∀ k ≥ m, k ≤ l → f l ≤ f k := begin assume l k hkm hkl, generalize hp : l - k = p, have : l = k + p := add_comm p k ▸ (nat.sub_eq_iff_eq_add hkl).1 hp, subst this, clear hkl hp, induction p with p ih, { simp }, { exact le_trans (h _ (le_trans hkm (nat.le_add_right _ _))) ih } end section variables {α : Type*} {β : Type*} [ring β] [discrete_linear_ordered_field α] [archimedean α] {abv : β → α} [is_absolute_value abv] lemma is_cau_of_decreasing_bounded (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, abs (f n) ≤ a) (hnm : ∀ n ≥ m, f n.succ ≤ f n) : is_cau_seq abs f := λ ε ε0, let ⟨k, hk⟩ := archimedean.arch a ε0 in have h : ∃ l, ∀ n ≥ m, a - l •ℕ ε < f n := ⟨k + k + 1, λ n hnm, lt_of_lt_of_le (show a - (k + (k + 1)) •ℕ ε < -abs (f n), from lt_neg.1 $ lt_of_le_of_lt (ham n hnm) (begin rw [neg_sub, lt_sub_iff_add_lt, add_nsmul], exact add_lt_add_of_le_of_lt hk (lt_of_le_of_lt hk (lt_add_of_pos_left _ ε0)), end)) (neg_le.2 $ (abs_neg (f n)) ▸ le_abs_self _)⟩, let l := nat.find h in have hl : ∀ (n : ℕ), n ≥ m → f n > a - l •ℕ ε := nat.find_spec h, have hl0 : l ≠ 0 := λ hl0, not_lt_of_ge (ham m (le_refl _)) (lt_of_lt_of_le (by have := hl m (le_refl m); simpa [hl0] using this) (le_abs_self (f m))), begin cases classical.not_forall.1 (nat.find_min h (nat.pred_lt hl0)) with i hi, rw [not_imp, not_lt] at hi, existsi i, assume j hj, have hfij : f j ≤ f i := forall_ge_le_of_forall_le_succ f hnm _ hi.1 hj, rw [abs_of_nonpos (sub_nonpos.2 hfij), neg_sub, sub_lt_iff_lt_add'], exact calc f i ≤ a - (nat.pred l) •ℕ ε : hi.2 ... = a - l •ℕ ε + ε : by conv {to_rhs, rw [← nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero hl0), succ_nsmul', sub_add, add_sub_cancel] } ... < f j + ε : add_lt_add_right (hl j (le_trans hi.1 hj)) _ end lemma is_cau_of_mono_bounded (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, abs (f n) ≤ a) (hnm : ∀ n ≥ m, f n ≤ f n.succ) : is_cau_seq abs f := begin refine @eq.rec_on (ℕ → α) _ (is_cau_seq abs) _ _ (-⟨_, @is_cau_of_decreasing_bounded _ _ _ (λ n, -f n) a m (by simpa) (by simpa)⟩ : cau_seq α abs).2, ext, exact neg_neg _ end end section no_archimedean variables {α : Type*} {β : Type*} [ring β] [discrete_linear_ordered_field α] {abv : β → α} [is_absolute_value abv] lemma is_cau_series_of_abv_le_cau {f : ℕ → β} {g : ℕ → α} (n : ℕ) : (∀ m, n ≤ m → abv (f m) ≤ g m) → is_cau_seq abs (λ n, ∑ i in range n, g i) → is_cau_seq abv (λ n, ∑ i in range n, f i) := begin assume hm hg ε ε0, cases hg (ε / 2) (div_pos ε0 (by norm_num)) with i hi, existsi max n i, assume j ji, have hi₁ := hi j (le_trans (le_max_right n i) ji), have hi₂ := hi (max n i) (le_max_right n i), have sub_le := abs_sub_le (∑ k in range j, g k) (∑ k in range i, g k) (∑ k in range (max n i), g k), have := add_lt_add hi₁ hi₂, rw [abs_sub (∑ k in range (max n i), g k), add_halves ε] at this, refine lt_of_le_of_lt (le_trans (le_trans _ (le_abs_self _)) sub_le) this, generalize hk : j - max n i = k, clear this hi₂ hi₁ hi ε0 ε hg sub_le, rw nat.sub_eq_iff_eq_add ji at hk, rw hk, clear hk ji j, induction k with k' hi, { simp [abv_zero abv] }, { dsimp at *, simp only [nat.succ_add, sum_range_succ, sub_eq_add_neg, add_assoc], refine le_trans (abv_add _ _ _) _, exact add_le_add (hm _ (le_add_of_nonneg_of_le (nat.zero_le _) (le_max_left _ _))) hi }, end lemma is_cau_series_of_abv_cau {f : ℕ → β} : is_cau_seq abs (λ m, ∑ n in range m, abv (f n)) → is_cau_seq abv (λ m, ∑ n in range m, f n) := is_cau_series_of_abv_le_cau 0 (λ n h, le_refl _) end no_archimedean section variables {α : Type*} {β : Type*} [ring β] [discrete_linear_ordered_field α] [archimedean α] {abv : β → α} [is_absolute_value abv] lemma is_cau_geo_series {β : Type*} [field β] {abv : β → α} [is_absolute_value abv] (x : β) (hx1 : abv x < 1) : is_cau_seq abv (λ n, ∑ m in range n, x ^ m) := have hx1' : abv x ≠ 1 := λ h, by simpa [h, lt_irrefl] using hx1, is_cau_series_of_abv_cau begin simp only [abv_pow abv] {eta := ff}, have : (λ (m : ℕ), ∑ n in range m, (abv x) ^ n) = λ m, geom_series (abv x) m := rfl, simp only [this, geom_sum hx1'] {eta := ff}, conv in (_ / _) { rw [← neg_div_neg_eq, neg_sub, neg_sub] }, refine @is_cau_of_mono_bounded _ _ _ _ ((1 : α) / (1 - abv x)) 0 _ _, { assume n hn, rw abs_of_nonneg, refine div_le_div_of_le_of_pos (sub_le_self _ (abv_pow abv x n ▸ abv_nonneg _ _)) (sub_pos.2 hx1), refine div_nonneg (sub_nonneg.2 _) (sub_pos.2 hx1), clear hn, induction n with n ih, { simp }, { rw [pow_succ, ← one_mul (1 : α)], refine mul_le_mul (le_of_lt hx1) ih (abv_pow abv x n ▸ abv_nonneg _ _) (by norm_num) } }, { assume n hn, refine div_le_div_of_le_of_pos (sub_le_sub_left _ _) (sub_pos.2 hx1), rw [← one_mul (_ ^ n), pow_succ], exact mul_le_mul_of_nonneg_right (le_of_lt hx1) (pow_nonneg (abv_nonneg _ _) _) } end lemma is_cau_geo_series_const (a : α) {x : α} (hx1 : abs x < 1) : is_cau_seq abs (λ m, ∑ n in range m, a * x ^ n) := have is_cau_seq abs (λ m, a * ∑ n in range m, x ^ n) := (cau_seq.const abs a * ⟨_, is_cau_geo_series x hx1⟩).2, by simpa only [mul_sum] lemma series_ratio_test {f : ℕ → β} (n : ℕ) (r : α) (hr0 : 0 ≤ r) (hr1 : r < 1) (h : ∀ m, n ≤ m → abv (f m.succ) ≤ r * abv (f m)) : is_cau_seq abv (λ m, ∑ n in range m, f n) := have har1 : abs r < 1, by rwa abs_of_nonneg hr0, begin refine is_cau_series_of_abv_le_cau n.succ _ (is_cau_geo_series_const (abv (f n.succ) * r⁻¹ ^ n.succ) har1), assume m hmn, cases classical.em (r = 0) with r_zero r_ne_zero, { have m_pos := lt_of_lt_of_le (nat.succ_pos n) hmn, have := h m.pred (nat.le_of_succ_le_succ (by rwa [nat.succ_pred_eq_of_pos m_pos])), simpa [r_zero, nat.succ_pred_eq_of_pos m_pos, pow_succ] }, generalize hk : m - n.succ = k, have r_pos : 0 < r := lt_of_le_of_ne hr0 (ne.symm r_ne_zero), replace hk : m = k + n.succ := (nat.sub_eq_iff_eq_add hmn).1 hk, induction k with k ih generalizing m n, { rw [hk, zero_add, mul_right_comm, inv_pow' _ _, ← div_eq_mul_inv, mul_div_cancel], exact (ne_of_lt (pow_pos r_pos _)).symm }, { have kn : k + n.succ ≥ n.succ, by rw ← zero_add n.succ; exact add_le_add (zero_le _) (by simp), rw [hk, nat.succ_add, pow_succ' r, ← mul_assoc], exact le_trans (by rw mul_comm; exact h _ (nat.le_of_succ_le kn)) (mul_le_mul_of_nonneg_right (ih (k + n.succ) n h kn rfl) hr0) } end lemma sum_range_diag_flip {α : Type*} [add_comm_monoid α] (n : ℕ) (f : ℕ → ℕ → α) : ∑ m in range n, ∑ k in range (m + 1), f k (m - k) = ∑ m in range n, ∑ k in range (n - m), f m k := have h₁ : ∑ a in (range n).sigma (range ∘ nat.succ), f (a.2) (a.1 - a.2) = ∑ m in range n, ∑ k in range (m + 1), f k (m - k) := sum_sigma, have h₂ : ∑ a in (range n).sigma (λ m, range (n - m)), f (a.1) (a.2) = ∑ m in range n, ∑ k in range (n - m), f m k := sum_sigma, h₁ ▸ h₂ ▸ sum_bij (λ a _, ⟨a.2, a.1 - a.2⟩) (λ a ha, have h₁ : a.1 < n := mem_range.1 (mem_sigma.1 ha).1, have h₂ : a.2 < nat.succ a.1 := mem_range.1 (mem_sigma.1 ha).2, mem_sigma.2 ⟨mem_range.2 (lt_of_lt_of_le h₂ h₁), mem_range.2 ((nat.sub_lt_sub_right_iff (nat.le_of_lt_succ h₂)).2 h₁)⟩) (λ _ _, rfl) (λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩ ha hb h, have ha : a₁ < n ∧ a₂ ≤ a₁ := ⟨mem_range.1 (mem_sigma.1 ha).1, nat.le_of_lt_succ (mem_range.1 (mem_sigma.1 ha).2)⟩, have hb : b₁ < n ∧ b₂ ≤ b₁ := ⟨mem_range.1 (mem_sigma.1 hb).1, nat.le_of_lt_succ (mem_range.1 (mem_sigma.1 hb).2)⟩, have h : a₂ = b₂ ∧ _ := sigma.mk.inj h, have h' : a₁ = b₁ - b₂ + a₂ := (nat.sub_eq_iff_eq_add ha.2).1 (eq_of_heq h.2), sigma.mk.inj_iff.2 ⟨nat.sub_add_cancel hb.2 ▸ h'.symm ▸ h.1 ▸ rfl, (heq_of_eq h.1)⟩) (λ ⟨a₁, a₂⟩ ha, have ha : a₁ < n ∧ a₂ < n - a₁ := ⟨mem_range.1 (mem_sigma.1 ha).1, (mem_range.1 (mem_sigma.1 ha).2)⟩, ⟨⟨a₂ + a₁, a₁⟩, ⟨mem_sigma.2 ⟨mem_range.2 (nat.lt_sub_right_iff_add_lt.1 ha.2), mem_range.2 (nat.lt_succ_of_le (nat.le_add_left _ _))⟩, sigma.mk.inj_iff.2 ⟨rfl, heq_of_eq (nat.add_sub_cancel _ _).symm⟩⟩⟩) lemma sum_range_sub_sum_range {α : Type*} [add_comm_group α] {f : ℕ → α} {n m : ℕ} (hnm : n ≤ m) : ∑ k in range m, f k - ∑ k in range n, f k = ∑ k in (range m).filter (λ k, n ≤ k), f k := begin rw [← sum_sdiff (@filter_subset _ (λ k, n ≤ k) _ (range m)), sub_eq_iff_eq_add, ← eq_sub_iff_add_eq, add_sub_cancel'], refine finset.sum_congr (finset.ext $ λ a, ⟨λ h, by simp at *; finish, λ h, have ham : a < m := lt_of_lt_of_le (mem_range.1 h) hnm, by simp * at *⟩) (λ _ _, rfl), end end section no_archimedean variables {α : Type*} {β : Type*} [ring β] [discrete_linear_ordered_field α] {abv : β → α} [is_absolute_value abv] lemma abv_sum_le_sum_abv {γ : Type*} (f : γ → β) (s : finset γ) : abv (∑ k in s, f k) ≤ ∑ k in s, abv (f k) := by haveI := classical.dec_eq γ; exact finset.induction_on s (by simp [abv_zero abv]) (λ a s has ih, by rw [sum_insert has, sum_insert has]; exact le_trans (abv_add abv _ _) (add_le_add_left ih _)) @[nolint ge_or_gt] -- see Note [nolint_ge] lemma cauchy_product {a b : ℕ → β} (ha : is_cau_seq abs (λ m, ∑ n in range m, abv (a n))) (hb : is_cau_seq abv (λ m, ∑ n in range m, b n)) (ε : α) (ε0 : 0 < ε) : ∃ i : ℕ, ∀ j ≥ i, abv ((∑ k in range j, a k) * (∑ k in range j, b k) - ∑ n in range j, ∑ m in range (n + 1), a m * b (n - m)) < ε := let ⟨Q, hQ⟩ := cau_seq.bounded ⟨_, hb⟩ in let ⟨P, hP⟩ := cau_seq.bounded ⟨_, ha⟩ in have hP0 : 0 < P, from lt_of_le_of_lt (abs_nonneg _) (hP 0), have hPε0 : 0 < ε / (2 * P), from div_pos ε0 (mul_pos (show (2 : α) > 0, from by norm_num) hP0), let ⟨N, hN⟩ := cau_seq.cauchy₂ ⟨_, hb⟩ hPε0 in have hQε0 : 0 < ε / (4 * Q), from div_pos ε0 (mul_pos (show (0 : α) < 4, by norm_num) (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))), let ⟨M, hM⟩ := cau_seq.cauchy₂ ⟨_, ha⟩ hQε0 in ⟨2 * (max N M + 1), λ K hK, have h₁ : ∑ m in range K, ∑ k in range (m + 1), a k * b (m - k) = ∑ m in range K, ∑ n in range (K - m), a m * b n, by simpa using sum_range_diag_flip K (λ m n, a m * b n), have h₂ : (λ i, ∑ k in range (K - i), a i * b k) = (λ i, a i * ∑ k in range (K - i), b k), by simp [finset.mul_sum], have h₃ : ∑ i in range K, a i * ∑ k in range (K - i), b k = ∑ i in range K, a i * (∑ k in range (K - i), b k - ∑ k in range K, b k) + ∑ i in range K, a i * ∑ k in range K, b k, by rw ← sum_add_distrib; simp [(mul_add _ _ _).symm], have two_mul_two : (4 : α) = 2 * 2, by norm_num, have hQ0 : Q ≠ 0, from λ h, by simpa [h, lt_irrefl] using hQε0, have h2Q0 : 2 * Q ≠ 0, from mul_ne_zero two_ne_zero hQ0, have hε : ε / (2 * P) * P + ε / (4 * Q) * (2 * Q) = ε, by rw [← div_div_eq_div_mul, div_mul_cancel _ (ne.symm (ne_of_lt hP0)), two_mul_two, mul_assoc, ← div_div_eq_div_mul, div_mul_cancel _ h2Q0, add_halves], have hNMK : max N M + 1 < K, from lt_of_lt_of_le (by rw two_mul; exact lt_add_of_pos_left _ (nat.succ_pos _)) hK, have hKN : N < K, from calc N ≤ max N M : le_max_left _ _ ... < max N M + 1 : nat.lt_succ_self _ ... < K : hNMK, have hsumlesum : ∑ i in range (max N M + 1), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) ≤ ∑ i in range (max N M + 1), abv (a i) * (ε / (2 * P)), from sum_le_sum (λ m hmJ, mul_le_mul_of_nonneg_left (le_of_lt (hN (K - m) K (nat.le_sub_left_of_add_le (le_trans (by rw two_mul; exact add_le_add (le_of_lt (mem_range.1 hmJ)) (le_trans (le_max_left _ _) (le_of_lt (lt_add_one _)))) hK)) (le_of_lt hKN))) (abv_nonneg abv _)), have hsumltP : ∑ n in range (max N M + 1), abv (a n) < P := calc ∑ n in range (max N M + 1), abv (a n) = abs (∑ n in range (max N M + 1), abv (a n)) : eq.symm (abs_of_nonneg (sum_nonneg (λ x h, abv_nonneg abv (a x)))) ... < P : hP (max N M + 1), begin rw [h₁, h₂, h₃, sum_mul, ← sub_sub, sub_right_comm, sub_self, zero_sub, abv_neg abv], refine lt_of_le_of_lt (abv_sum_le_sum_abv _ _) _, suffices : ∑ i in range (max N M + 1), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) + (∑ i in range K, abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) - ∑ i in range (max N M + 1), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k)) < ε / (2 * P) * P + ε / (4 * Q) * (2 * Q), { rw hε at this, simpa [abv_mul abv] }, refine add_lt_add (lt_of_le_of_lt hsumlesum (by rw [← sum_mul, mul_comm]; exact (mul_lt_mul_left hPε0).mpr hsumltP)) _, rw sum_range_sub_sum_range (le_of_lt hNMK), exact calc ∑ i in (range K).filter (λ k, max N M + 1 ≤ k), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) ≤ ∑ i in (range K).filter (λ k, max N M + 1 ≤ k), abv (a i) * (2 * Q) : sum_le_sum (λ n hn, begin refine mul_le_mul_of_nonneg_left _ (abv_nonneg _ _), rw sub_eq_add_neg, refine le_trans (abv_add _ _ _) _, rw [two_mul, abv_neg abv], exact add_le_add (le_of_lt (hQ _)) (le_of_lt (hQ _)), end) ... < ε / (4 * Q) * (2 * Q) : by rw [← sum_mul, ← sum_range_sub_sum_range (le_of_lt hNMK)]; refine (mul_lt_mul_right $ by rw two_mul; exact add_pos (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0)) (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))).2 (lt_of_le_of_lt (le_abs_self _) (hM _ _ (le_trans (nat.le_succ_of_le (le_max_right _ _)) (le_of_lt hNMK)) (nat.le_succ_of_le (le_max_right _ _)))) end⟩ end no_archimedean end open finset open cau_seq namespace complex lemma is_cau_abs_exp (z : ℂ) : is_cau_seq _root_.abs (λ n, ∑ m in range n, abs (z ^ m / nat.fact m)) := let ⟨n, hn⟩ := exists_nat_gt (abs z) in have hn0 : (0 : ℝ) < n, from lt_of_le_of_lt (abs_nonneg _) hn, series_ratio_test n (complex.abs z / n) (div_nonneg_of_nonneg_of_pos (complex.abs_nonneg _) hn0) (by rwa [div_lt_iff hn0, one_mul]) (λ m hm, by rw [abs_abs, abs_abs, nat.fact_succ, pow_succ, mul_comm m.succ, nat.cast_mul, ← div_div_eq_div_mul, mul_div_assoc, mul_div_right_comm, abs_mul, abs_div, abs_cast_nat]; exact mul_le_mul_of_nonneg_right (div_le_div_of_le_left (abs_nonneg _) hn0 (nat.cast_le.2 (le_trans hm (nat.le_succ _)))) (abs_nonneg _)) noncomputable theory lemma is_cau_exp (z : ℂ) : is_cau_seq abs (λ n, ∑ m in range n, z ^ m / nat.fact m) := is_cau_series_of_abv_cau (is_cau_abs_exp z) /-- The Cauchy sequence consisting of partial sums of the Taylor series of the complex exponential function -/ @[pp_nodot] def exp' (z : ℂ) : cau_seq ℂ complex.abs := ⟨λ n, ∑ m in range n, z ^ m / nat.fact m, is_cau_exp z⟩ /-- The complex exponential function, defined via its Taylor series -/ @[pp_nodot] def exp (z : ℂ) : ℂ := lim (exp' z) /-- The complex sine function, defined via `exp` -/ @[pp_nodot] def sin (z : ℂ) : ℂ := ((exp (-z * I) - exp (z * I)) * I) / 2 /-- The complex cosine function, defined via `exp` -/ @[pp_nodot] def cos (z : ℂ) : ℂ := (exp (z * I) + exp (-z * I)) / 2 /-- The complex tangent function, defined as `sin z / cos z` -/ @[pp_nodot] def tan (z : ℂ) : ℂ := sin z / cos z /-- The complex hyperbolic sine function, defined via `exp` -/ @[pp_nodot] def sinh (z : ℂ) : ℂ := (exp z - exp (-z)) / 2 /-- The complex hyperbolic cosine function, defined via `exp` -/ @[pp_nodot] def cosh (z : ℂ) : ℂ := (exp z + exp (-z)) / 2 /-- The complex hyperbolic tangent function, defined as `sinh z / cosh z` -/ @[pp_nodot] def tanh (z : ℂ) : ℂ := sinh z / cosh z end complex namespace real open complex /-- The real exponential function, defined as the real part of the complex exponential -/ @[pp_nodot] def exp (x : ℝ) : ℝ := (exp x).re /-- The real sine function, defined as the real part of the complex sine -/ @[pp_nodot] def sin (x : ℝ) : ℝ := (sin x).re /-- The real cosine function, defined as the real part of the complex cosine -/ @[pp_nodot] def cos (x : ℝ) : ℝ := (cos x).re /-- The real tangent function, defined as the real part of the complex tangent -/ @[pp_nodot] def tan (x : ℝ) : ℝ := (tan x).re /-- The real hypebolic sine function, defined as the real part of the complex hyperbolic sine -/ @[pp_nodot] def sinh (x : ℝ) : ℝ := (sinh x).re /-- The real hypebolic cosine function, defined as the real part of the complex hyperbolic cosine -/ @[pp_nodot] def cosh (x : ℝ) : ℝ := (cosh x).re /-- The real hypebolic tangent function, defined as the real part of the complex hyperbolic tangent -/ @[pp_nodot] def tanh (x : ℝ) : ℝ := (tanh x).re end real namespace complex variables (x y : ℂ) @[simp] lemma exp_zero : exp 0 = 1 := lim_eq_of_equiv_const $ λ ε ε0, ⟨1, λ j hj, begin convert ε0, cases j, { exact absurd hj (not_le_of_gt zero_lt_one) }, { dsimp [exp'], induction j with j ih, { dsimp [exp']; simp }, { rw ← ih dec_trivial, simp only [sum_range_succ, pow_succ], simp } } end⟩ lemma exp_add : exp (x + y) = exp x * exp y := show lim (⟨_, is_cau_exp (x + y)⟩ : cau_seq ℂ abs) = lim (show cau_seq ℂ abs, from ⟨_, is_cau_exp x⟩) * lim (show cau_seq ℂ abs, from ⟨_, is_cau_exp y⟩), from have hj : ∀ j : ℕ, ∑ m in range j, (x + y) ^ m / m.fact = ∑ i in range j, ∑ k in range (i + 1), x ^ k / k.fact * (y ^ (i - k) / (i - k).fact), from assume j, finset.sum_congr rfl (λ m hm, begin rw [add_pow, div_eq_mul_inv, sum_mul], refine finset.sum_congr rfl (λ i hi, _), have h₁ : (m.choose i : ℂ) ≠ 0 := nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 (nat.choose_pos (nat.le_of_lt_succ (mem_range.1 hi)))), have h₂ := nat.choose_mul_fact_mul_fact (nat.le_of_lt_succ $ finset.mem_range.1 hi), rw [← h₂, nat.cast_mul, nat.cast_mul, mul_inv', mul_inv'], simp only [mul_left_comm (m.choose i : ℂ), mul_assoc, mul_left_comm (m.choose i : ℂ)⁻¹, mul_comm (m.choose i : ℂ)], rw inv_mul_cancel h₁, simp [div_eq_mul_inv, mul_comm, mul_assoc, mul_left_comm] end), by rw lim_mul_lim; exact eq.symm (lim_eq_lim_of_equiv (by dsimp; simp only [hj]; exact cauchy_product (is_cau_abs_exp x) (is_cau_exp y))) attribute [irreducible] complex.exp lemma exp_list_sum (l : list ℂ) : exp l.sum = (l.map exp).prod := @monoid_hom.map_list_prod (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ l lemma exp_multiset_sum (s : multiset ℂ) : exp s.sum = (s.map exp).prod := @monoid_hom.map_multiset_prod (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ s lemma exp_sum {α : Type*} (s : finset α) (f : α → ℂ) : exp (∑ x in s, f x) = ∏ x in s, exp (f x) := @monoid_hom.map_prod α (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ f s lemma exp_nat_mul (x : ℂ) : ∀ n : ℕ, exp(n*x) = (exp x)^n | 0 := by rw [nat.cast_zero, zero_mul, exp_zero, pow_zero] | (nat.succ n) := by rw [pow_succ', nat.cast_add_one, add_mul, exp_add, ←exp_nat_mul, one_mul] lemma exp_ne_zero : exp x ≠ 0 := λ h, zero_ne_one $ by rw [← exp_zero, ← add_neg_self x, exp_add, h]; simp lemma exp_neg : exp (-x) = (exp x)⁻¹ := by rw [← mul_right_inj' (exp_ne_zero x), ← exp_add]; simp [mul_inv_cancel (exp_ne_zero x)] lemma exp_sub : exp (x - y) = exp x / exp y := by simp [sub_eq_add_neg, exp_add, exp_neg, div_eq_mul_inv] @[simp] lemma exp_conj : exp (conj x) = conj (exp x) := begin dsimp [exp], rw [← lim_conj], refine congr_arg lim (cau_seq.ext (λ _, _)), dsimp [exp', function.comp, cau_seq_conj], rw ← sum_hom _ conj, refine sum_congr rfl (λ n hn, _), rw [conj.map_div, conj.map_pow, ← of_real_nat_cast, conj_of_real] end @[simp] lemma of_real_exp_of_real_re (x : ℝ) : ((exp x).re : ℂ) = exp x := eq_conj_iff_re.1 $ by rw [← exp_conj, conj_of_real] @[simp] lemma of_real_exp (x : ℝ) : (real.exp x : ℂ) = exp x := of_real_exp_of_real_re _ @[simp] lemma exp_of_real_im (x : ℝ) : (exp x).im = 0 := by rw [← of_real_exp_of_real_re, of_real_im] lemma exp_of_real_re (x : ℝ) : (exp x).re = real.exp x := rfl lemma two_sinh : 2 * sinh x = exp x - exp (-x) := mul_div_cancel' _ two_ne_zero' lemma two_cosh : 2 * cosh x = exp x + exp (-x) := mul_div_cancel' _ two_ne_zero' @[simp] lemma sinh_zero : sinh 0 = 0 := by simp [sinh] @[simp] lemma sinh_neg : sinh (-x) = -sinh x := by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul] private lemma sinh_add_aux {a b c d : ℂ} : (a - b) * (c + d) + (a + b) * (c - d) = 2 * (a * c - b * d) := by ring lemma sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y := begin rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), two_sinh, exp_add, neg_add, exp_add, eq_comm, mul_add, ← mul_assoc, two_sinh, mul_left_comm, two_sinh, ← mul_right_inj' (@two_ne_zero' ℂ _ _ _), mul_add, mul_left_comm, two_cosh, ← mul_assoc, two_cosh], exact sinh_add_aux end @[simp] lemma cosh_zero : cosh 0 = 1 := by simp [cosh] @[simp] lemma cosh_neg : cosh (-x) = cosh x := by simp [add_comm, cosh, exp_neg] private lemma cosh_add_aux {a b c d : ℂ} : (a + b) * (c + d) + (a - b) * (c - d) = 2 * (a * c + b * d) := by ring lemma cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y := begin rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), two_cosh, exp_add, neg_add, exp_add, eq_comm, mul_add, ← mul_assoc, two_cosh, ← mul_assoc, two_sinh, ← mul_right_inj' (@two_ne_zero' ℂ _ _ _), mul_add, mul_left_comm, two_cosh, mul_left_comm, two_sinh], exact cosh_add_aux end lemma sinh_sub : sinh (x - y) = sinh x * cosh y - cosh x * sinh y := by simp [sub_eq_add_neg, sinh_add, sinh_neg, cosh_neg] lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y := by simp [sub_eq_add_neg, cosh_add, sinh_neg, cosh_neg] lemma sinh_conj : sinh (conj x) = conj (sinh x) := by rw [sinh, ← conj.map_neg, exp_conj, exp_conj, ← conj.map_sub, sinh, conj.map_div, conj_bit0, conj.map_one] @[simp] lemma of_real_sinh_of_real_re (x : ℝ) : ((sinh x).re : ℂ) = sinh x := eq_conj_iff_re.1 $ by rw [← sinh_conj, conj_of_real] @[simp] lemma of_real_sinh (x : ℝ) : (real.sinh x : ℂ) = sinh x := of_real_sinh_of_real_re _ @[simp] lemma sinh_of_real_im (x : ℝ) : (sinh x).im = 0 := by rw [← of_real_sinh_of_real_re, of_real_im] lemma sinh_of_real_re (x : ℝ) : (sinh x).re = real.sinh x := rfl lemma cosh_conj : cosh (conj x) = conj (cosh x) := begin rw [cosh, ← conj.map_neg, exp_conj, exp_conj, ← conj.map_add, cosh, conj.map_div, conj_bit0, conj.map_one] end @[simp] lemma of_real_cosh_of_real_re (x : ℝ) : ((cosh x).re : ℂ) = cosh x := eq_conj_iff_re.1 $ by rw [← cosh_conj, conj_of_real] @[simp] lemma of_real_cosh (x : ℝ) : (real.cosh x : ℂ) = cosh x := of_real_cosh_of_real_re _ @[simp] lemma cosh_of_real_im (x : ℝ) : (cosh x).im = 0 := by rw [← of_real_cosh_of_real_re, of_real_im] lemma cosh_of_real_re (x : ℝ) : (cosh x).re = real.cosh x := rfl lemma tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x := rfl @[simp] lemma tanh_zero : tanh 0 = 0 := by simp [tanh] @[simp] lemma tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div] lemma tanh_conj : tanh (conj x) = conj (tanh x) := by rw [tanh, sinh_conj, cosh_conj, ← conj.map_div, tanh] @[simp] lemma of_real_tanh_of_real_re (x : ℝ) : ((tanh x).re : ℂ) = tanh x := eq_conj_iff_re.1 $ by rw [← tanh_conj, conj_of_real] @[simp] lemma of_real_tanh (x : ℝ) : (real.tanh x : ℂ) = tanh x := of_real_tanh_of_real_re _ @[simp] lemma tanh_of_real_im (x : ℝ) : (tanh x).im = 0 := by rw [← of_real_tanh_of_real_re, of_real_im] lemma tanh_of_real_re (x : ℝ) : (tanh x).re = real.tanh x := rfl lemma cosh_add_sinh : cosh x + sinh x = exp x := by rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), mul_add, two_cosh, two_sinh, add_add_sub_cancel, two_mul] lemma sinh_add_cosh : sinh x + cosh x = exp x := by rw [add_comm, cosh_add_sinh] lemma cosh_sub_sinh : cosh x - sinh x = exp (-x) := by rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), mul_sub, two_cosh, two_sinh, add_sub_sub_cancel, two_mul] lemma cosh_sq_sub_sinh_sq : cosh x ^ 2 - sinh x ^ 2 = 1 := by rw [sq_sub_sq, cosh_add_sinh, cosh_sub_sinh, ← exp_add, add_neg_self, exp_zero] @[simp] lemma sin_zero : sin 0 = 0 := by simp [sin] @[simp] lemma sin_neg : sin (-x) = -sin x := by simp [sin, sub_eq_add_neg, exp_neg, (neg_div _ _).symm, add_mul] lemma two_sin : 2 * sin x = (exp (-x * I) - exp (x * I)) * I := mul_div_cancel' _ two_ne_zero' lemma two_cos : 2 * cos x = exp (x * I) + exp (-x * I) := mul_div_cancel' _ two_ne_zero' lemma sinh_mul_I : sinh (x * I) = sin x * I := by rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), two_sinh, ← mul_assoc, two_sin, mul_assoc, I_mul_I, mul_neg_one, neg_sub, neg_mul_eq_neg_mul] lemma cosh_mul_I : cosh (x * I) = cos x := by rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), two_cosh, two_cos, neg_mul_eq_neg_mul] lemma sin_add : sin (x + y) = sin x * cos y + cos x * sin y := by rw [← mul_left_inj' I_ne_zero, ← sinh_mul_I, add_mul, add_mul, mul_right_comm, ← sinh_mul_I, mul_assoc, ← sinh_mul_I, ← cosh_mul_I, ← cosh_mul_I, sinh_add] @[simp] lemma cos_zero : cos 0 = 1 := by simp [cos] @[simp] lemma cos_neg : cos (-x) = cos x := by simp [cos, sub_eq_add_neg, exp_neg, add_comm] private lemma cos_add_aux {a b c d : ℂ} : (a + b) * (c + d) - (b - a) * (d - c) * (-1) = 2 * (a * c + b * d) := by ring lemma cos_add : cos (x + y) = cos x * cos y - sin x * sin y := by rw [← cosh_mul_I, add_mul, cosh_add, cosh_mul_I, cosh_mul_I, sinh_mul_I, sinh_mul_I, mul_mul_mul_comm, I_mul_I, mul_neg_one, sub_eq_add_neg] lemma sin_sub : sin (x - y) = sin x * cos y - cos x * sin y := by simp [sub_eq_add_neg, sin_add, sin_neg, cos_neg] lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y := by simp [sub_eq_add_neg, cos_add, sin_neg, cos_neg] lemma sin_conj : sin (conj x) = conj (sin x) := by rw [← mul_left_inj' I_ne_zero, ← sinh_mul_I, ← conj_neg_I, ← conj.map_mul, ← conj.map_mul, sinh_conj, mul_neg_eq_neg_mul_symm, sinh_neg, sinh_mul_I, mul_neg_eq_neg_mul_symm] @[simp] lemma of_real_sin_of_real_re (x : ℝ) : ((sin x).re : ℂ) = sin x := eq_conj_iff_re.1 $ by rw [← sin_conj, conj_of_real] @[simp] lemma of_real_sin (x : ℝ) : (real.sin x : ℂ) = sin x := of_real_sin_of_real_re _ @[simp] lemma sin_of_real_im (x : ℝ) : (sin x).im = 0 := by rw [← of_real_sin_of_real_re, of_real_im] lemma sin_of_real_re (x : ℝ) : (sin x).re = real.sin x := rfl lemma cos_conj : cos (conj x) = conj (cos x) := by rw [← cosh_mul_I, ← conj_neg_I, ← conj.map_mul, ← cosh_mul_I, cosh_conj, mul_neg_eq_neg_mul_symm, cosh_neg] @[simp] lemma of_real_cos_of_real_re (x : ℝ) : ((cos x).re : ℂ) = cos x := eq_conj_iff_re.1 $ by rw [← cos_conj, conj_of_real] @[simp] lemma of_real_cos (x : ℝ) : (real.cos x : ℂ) = cos x := of_real_cos_of_real_re _ @[simp] lemma cos_of_real_im (x : ℝ) : (cos x).im = 0 := by rw [← of_real_cos_of_real_re, of_real_im] lemma cos_of_real_re (x : ℝ) : (cos x).re = real.cos x := rfl @[simp] lemma tan_zero : tan 0 = 0 := by simp [tan] lemma tan_eq_sin_div_cos : tan x = sin x / cos x := rfl @[simp] lemma tan_neg : tan (-x) = -tan x := by simp [tan, neg_div] lemma tan_conj : tan (conj x) = conj (tan x) := by rw [tan, sin_conj, cos_conj, ← conj.map_div, tan] @[simp] lemma of_real_tan_of_real_re (x : ℝ) : ((tan x).re : ℂ) = tan x := eq_conj_iff_re.1 $ by rw [← tan_conj, conj_of_real] @[simp] lemma of_real_tan (x : ℝ) : (real.tan x : ℂ) = tan x := of_real_tan_of_real_re _ @[simp] lemma tan_of_real_im (x : ℝ) : (tan x).im = 0 := by rw [← of_real_tan_of_real_re, of_real_im] lemma tan_of_real_re (x : ℝ) : (tan x).re = real.tan x := rfl lemma cos_add_sin_I : cos x + sin x * I = exp (x * I) := by rw [← cosh_add_sinh, sinh_mul_I, cosh_mul_I] lemma cos_sub_sin_I : cos x - sin x * I = exp (-x * I) := by rw [← neg_mul_eq_neg_mul, ← cosh_sub_sinh, sinh_mul_I, cosh_mul_I] lemma sin_sq_add_cos_sq : sin x ^ 2 + cos x ^ 2 = 1 := eq.trans (by rw [cosh_mul_I, sinh_mul_I, mul_pow, I_sq, mul_neg_one, sub_neg_eq_add, add_comm]) (cosh_sq_sub_sinh_sq (x * I)) lemma cos_two_mul' : cos (2 * x) = cos x ^ 2 - sin x ^ 2 := by rw [two_mul, cos_add, ← pow_two, ← pow_two] lemma cos_two_mul : cos (2 * x) = 2 * cos x ^ 2 - 1 := by rw [cos_two_mul', eq_sub_iff_add_eq.2 (sin_sq_add_cos_sq x), ← sub_add, sub_add_eq_add_sub, two_mul] lemma sin_two_mul : sin (2 * x) = 2 * sin x * cos x := by rw [two_mul, sin_add, two_mul, add_mul, mul_comm] lemma cos_square : cos x ^ 2 = 1 / 2 + cos (2 * x) / 2 := by simp [cos_two_mul, div_add_div_same, mul_div_cancel_left, two_ne_zero', -one_div_eq_inv] lemma sin_square : sin x ^ 2 = 1 - cos x ^ 2 := by { rw [←sin_sq_add_cos_sq x], simp } lemma exp_mul_I : exp (x * I) = cos x + sin x * I := (cos_add_sin_I _).symm lemma exp_add_mul_I : exp (x + y * I) = exp x * (cos y + sin y * I) := by rw [exp_add, exp_mul_I] lemma exp_eq_exp_re_mul_sin_add_cos : exp x = exp x.re * (cos x.im + sin x.im * I) := by rw [← exp_add_mul_I, re_add_im] theorem cos_add_sin_mul_I_pow (n : ℕ) (z : ℂ) : (cos z + sin z * I) ^ n = cos (↑n * z) + sin (↑n * z) * I := begin rw [← exp_mul_I, ← exp_mul_I], induction n with n ih, { rw [pow_zero, nat.cast_zero, zero_mul, zero_mul, exp_zero] }, { rw [pow_succ', ih, nat.cast_succ, add_mul, add_mul, one_mul, exp_add] } end end complex namespace real open complex variables (x y : ℝ) @[simp] lemma exp_zero : exp 0 = 1 := by simp [real.exp] lemma exp_add : exp (x + y) = exp x * exp y := by simp [exp_add, exp] lemma exp_list_sum (l : list ℝ) : exp l.sum = (l.map exp).prod := @monoid_hom.map_list_prod (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ l lemma exp_multiset_sum (s : multiset ℝ) : exp s.sum = (s.map exp).prod := @monoid_hom.map_multiset_prod (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ s lemma exp_sum {α : Type*} (s : finset α) (f : α → ℝ) : exp (∑ x in s, f x) = ∏ x in s, exp (f x) := @monoid_hom.map_prod α (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ f s lemma exp_nat_mul (x : ℝ) : ∀ n : ℕ, exp(n*x) = (exp x)^n | 0 := by rw [nat.cast_zero, zero_mul, exp_zero, pow_zero] | (nat.succ n) := by rw [pow_succ', nat.cast_add_one, add_mul, exp_add, ←exp_nat_mul, one_mul] lemma exp_ne_zero : exp x ≠ 0 := λ h, exp_ne_zero x $ by rw [exp, ← of_real_inj] at h; simp * at * lemma exp_neg : exp (-x) = (exp x)⁻¹ := by rw [← of_real_inj, exp, of_real_exp_of_real_re, of_real_neg, exp_neg, of_real_inv, of_real_exp] lemma exp_sub : exp (x - y) = exp x / exp y := by simp [sub_eq_add_neg, exp_add, exp_neg, div_eq_mul_inv] @[simp] lemma sin_zero : sin 0 = 0 := by simp [sin] @[simp] lemma sin_neg : sin (-x) = -sin x := by simp [sin, exp_neg, (neg_div _ _).symm, add_mul] lemma sin_add : sin (x + y) = sin x * cos y + cos x * sin y := by rw [← of_real_inj]; simp [sin, sin_add] @[simp] lemma cos_zero : cos 0 = 1 := by simp [cos] @[simp] lemma cos_neg : cos (-x) = cos x := by simp [cos, exp_neg] lemma cos_add : cos (x + y) = cos x * cos y - sin x * sin y := by rw ← of_real_inj; simp [cos, cos_add] lemma sin_sub : sin (x - y) = sin x * cos y - cos x * sin y := by simp [sub_eq_add_neg, sin_add, sin_neg, cos_neg] lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y := by simp [sub_eq_add_neg, cos_add, sin_neg, cos_neg] lemma tan_eq_sin_div_cos : tan x = sin x / cos x := if h : complex.cos x = 0 then by simp [sin, cos, tan, *, complex.tan, div_eq_mul_inv] at * else by rw [sin, cos, tan, complex.tan, ← of_real_inj, div_eq_mul_inv, mul_re]; simp [norm_sq, (div_div_eq_div_mul _ _ _).symm, div_self h]; refl @[simp] lemma tan_zero : tan 0 = 0 := by simp [tan] @[simp] lemma tan_neg : tan (-x) = -tan x := by simp [tan, neg_div] lemma sin_sq_add_cos_sq : sin x ^ 2 + cos x ^ 2 = 1 := of_real_inj.1 $ by simpa using sin_sq_add_cos_sq x lemma sin_sq_le_one : sin x ^ 2 ≤ 1 := by rw ← sin_sq_add_cos_sq x; exact le_add_of_nonneg_right (pow_two_nonneg _) lemma cos_sq_le_one : cos x ^ 2 ≤ 1 := by rw ← sin_sq_add_cos_sq x; exact le_add_of_nonneg_left (pow_two_nonneg _) lemma abs_sin_le_one : abs' (sin x) ≤ 1 := (mul_self_le_mul_self_iff (_root_.abs_nonneg (sin x)) (by exact zero_le_one)).2 $ by rw [← _root_.abs_mul, abs_mul_self, mul_one, ← pow_two]; apply sin_sq_le_one lemma abs_cos_le_one : abs' (cos x) ≤ 1 := (mul_self_le_mul_self_iff (_root_.abs_nonneg (cos x)) (by exact zero_le_one)).2 $ by rw [← _root_.abs_mul, abs_mul_self, mul_one, ← pow_two]; apply cos_sq_le_one lemma sin_le_one : sin x ≤ 1 := (abs_le.1 (abs_sin_le_one _)).2 lemma cos_le_one : cos x ≤ 1 := (abs_le.1 (abs_cos_le_one _)).2 lemma neg_one_le_sin : -1 ≤ sin x := (abs_le.1 (abs_sin_le_one _)).1 lemma neg_one_le_cos : -1 ≤ cos x := (abs_le.1 (abs_cos_le_one _)).1 lemma cos_two_mul : cos (2 * x) = 2 * cos x ^ 2 - 1 := by rw ← of_real_inj; simp [cos_two_mul] lemma sin_two_mul : sin (2 * x) = 2 * sin x * cos x := by rw ← of_real_inj; simp [sin_two_mul] lemma cos_square : cos x ^ 2 = 1 / 2 + cos (2 * x) / 2 := of_real_inj.1 $ by simpa using cos_square x lemma sin_square : sin x ^ 2 = 1 - cos x ^ 2 := eq_sub_iff_add_eq.2 $ sin_sq_add_cos_sq _ @[simp] lemma sinh_zero : sinh 0 = 0 := by simp [sinh] @[simp] lemma sinh_neg : sinh (-x) = -sinh x := by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul] lemma sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y := by rw ← of_real_inj; simp [sinh_add] @[simp] lemma cosh_zero : cosh 0 = 1 := by simp [cosh] @[simp] lemma cosh_neg : cosh (-x) = cosh x := by simp [cosh, exp_neg] lemma cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y := by rw ← of_real_inj; simp [cosh, cosh_add] lemma sinh_sub : sinh (x - y) = sinh x * cosh y - cosh x * sinh y := by simp [sub_eq_add_neg, sinh_add, sinh_neg, cosh_neg] lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y := by simp [sub_eq_add_neg, cosh_add, sinh_neg, cosh_neg] lemma tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x := of_real_inj.1 $ by simp [tanh_eq_sinh_div_cosh] @[simp] lemma tanh_zero : tanh 0 = 0 := by simp [tanh] @[simp] lemma tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div] open is_absolute_value /- TODO make this private and prove ∀ x -/ lemma add_one_le_exp_of_nonneg {x : ℝ} (hx : 0 ≤ x) : x + 1 ≤ exp x := calc x + 1 ≤ lim (⟨(λ n : ℕ, ((exp' x) n).re), is_cau_seq_re (exp' x)⟩ : cau_seq ℝ abs') : le_lim (cau_seq.le_of_exists ⟨2, λ j hj, show x + (1 : ℝ) ≤ (∑ m in range j, (x ^ m / m.fact : ℂ)).re, from have h₁ : (((λ m : ℕ, (x ^ m / m.fact : ℂ)) ∘ nat.succ) 0).re = x, by simp, have h₂ : ((x : ℂ) ^ 0 / nat.fact 0).re = 1, by simp, begin rw [← nat.sub_add_cancel hj, sum_range_succ', sum_range_succ', add_re, add_re, h₁, h₂, add_assoc, ← @sum_hom _ _ _ _ _ _ _ complex.re (is_add_group_hom.to_is_add_monoid_hom _)], refine le_add_of_nonneg_of_le (sum_nonneg (λ m hm, _)) (le_refl _), rw [← of_real_pow, ← of_real_nat_cast, ← of_real_div, of_real_re], exact div_nonneg (pow_nonneg hx _) (nat.cast_pos.2 (nat.fact_pos _)), end⟩) ... = exp x : by rw [exp, complex.exp, ← cau_seq_re, lim_re] lemma one_le_exp {x : ℝ} (hx : 0 ≤ x) : 1 ≤ exp x := by linarith [add_one_le_exp_of_nonneg hx] lemma exp_pos (x : ℝ) : 0 < exp x := (le_total 0 x).elim (lt_of_lt_of_le zero_lt_one ∘ one_le_exp) (λ h, by rw [← neg_neg x, real.exp_neg]; exact inv_pos.2 (lt_of_lt_of_le zero_lt_one (one_le_exp (neg_nonneg.2 h)))) @[simp] lemma abs_exp (x : ℝ) : abs' (exp x) = exp x := abs_of_pos (exp_pos _) lemma exp_strict_mono : strict_mono exp := λ x y h, by rw [← sub_add_cancel y x, real.exp_add]; exact (lt_mul_iff_one_lt_left (exp_pos _)).2 (lt_of_lt_of_le (by linarith) (add_one_le_exp_of_nonneg (by linarith))) lemma exp_lt_exp {x y : ℝ} : exp x < exp y ↔ x < y := exp_strict_mono.lt_iff_lt lemma exp_le_exp {x y : ℝ} : exp x ≤ exp y ↔ x ≤ y := exp_strict_mono.le_iff_le lemma exp_injective : function.injective exp := exp_strict_mono.injective @[simp] lemma exp_eq_one_iff : exp x = 1 ↔ x = 0 := by rw [← exp_zero, exp_injective.eq_iff] lemma one_lt_exp_iff {x : ℝ} : 1 < exp x ↔ 0 < x := by rw [← exp_zero, exp_lt_exp] lemma exp_lt_one_iff {x : ℝ} : exp x < 1 ↔ x < 0 := by rw [← exp_zero, exp_lt_exp] end real namespace complex lemma sum_div_fact_le {α : Type*} [discrete_linear_ordered_field α] (n j : ℕ) (hn : 0 < n) : ∑ m in filter (λ k, n ≤ k) (range j), (1 / m.fact : α) ≤ n.succ * (n.fact * n)⁻¹ := calc ∑ m in filter (λ k, n ≤ k) (range j), (1 / m.fact : α) = ∑ m in range (j - n), 1 / (m + n).fact : sum_bij (λ m _, m - n) (λ m hm, mem_range.2 $ (nat.sub_lt_sub_right_iff (by simp at hm; tauto)).2 (by simp at hm; tauto)) (λ m hm, by rw nat.sub_add_cancel; simp at *; tauto) (λ a₁ a₂ ha₁ ha₂ h, by rwa [nat.sub_eq_iff_eq_add, ← nat.sub_add_comm, eq_comm, nat.sub_eq_iff_eq_add, add_left_inj, eq_comm] at h; simp at *; tauto) (λ b hb, ⟨b + n, mem_filter.2 ⟨mem_range.2 $ nat.add_lt_of_lt_sub_right (mem_range.1 hb), nat.le_add_left _ _⟩, by rw nat.add_sub_cancel⟩) ... ≤ ∑ m in range (j - n), (nat.fact n * n.succ ^ m)⁻¹ : begin refine sum_le_sum (assume m n, _), rw [one_div_eq_inv, inv_le_inv], { rw [← nat.cast_pow, ← nat.cast_mul, nat.cast_le, add_comm], exact nat.fact_mul_pow_le_fact }, { exact nat.cast_pos.2 (nat.fact_pos _) }, { exact mul_pos (nat.cast_pos.2 (nat.fact_pos _)) (pow_pos (nat.cast_pos.2 (nat.succ_pos _)) _) }, end ... = (nat.fact n)⁻¹ * ∑ m in range (j - n), n.succ⁻¹ ^ m : by simp [mul_inv', mul_sum.symm, sum_mul.symm, -nat.fact_succ, mul_comm, inv_pow'] ... = (n.succ - n.succ * n.succ⁻¹ ^ (j - n)) / (n.fact * n) : have h₁ : (n.succ : α) ≠ 1, from @nat.cast_one α _ _ ▸ mt nat.cast_inj.1 (mt nat.succ.inj (nat.pos_iff_ne_zero.1 hn)), have h₂ : (n.succ : α) ≠ 0, from nat.cast_ne_zero.2 (nat.succ_ne_zero _), have h₃ : (n.fact * n : α) ≠ 0, from mul_ne_zero (nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 (nat.fact_pos _))) (nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 hn)), have h₄ : (n.succ - 1 : α) = n, by simp, by rw [← geom_series_def, geom_sum_inv h₁ h₂, eq_div_iff_mul_eq h₃, mul_comm _ (n.fact * n : α), ← mul_assoc (n.fact⁻¹ : α), ← mul_inv_rev', h₄, ← mul_assoc (n.fact * n : α), mul_comm (n : α) n.fact, mul_inv_cancel h₃]; simp [mul_add, add_mul, mul_assoc, mul_comm] ... ≤ n.succ / (n.fact * n) : begin refine iff.mpr (div_le_div_right (mul_pos _ _)) _, exact nat.cast_pos.2 (nat.fact_pos _), exact nat.cast_pos.2 hn, exact sub_le_self _ (mul_nonneg (nat.cast_nonneg _) (pow_nonneg (inv_nonneg.2 (nat.cast_nonneg _)) _)) end lemma exp_bound {x : ℂ} (hx : abs x ≤ 1) {n : ℕ} (hn : 0 < n) : abs (exp x - ∑ m in range n, x ^ m / m.fact) ≤ abs x ^ n * (n.succ * (n.fact * n)⁻¹) := begin rw [← lim_const (∑ m in range n, _), exp, sub_eq_add_neg, ← lim_neg, lim_add, ← lim_abs], refine lim_le (cau_seq.le_of_exists ⟨n, λ j hj, _⟩), show abs (∑ m in range j, x ^ m / m.fact - ∑ m in range n, x ^ m / m.fact) ≤ abs x ^ n * (n.succ * (n.fact * n)⁻¹), rw sum_range_sub_sum_range hj, exact calc abs (∑ m in (range j).filter (λ k, n ≤ k), (x ^ m / m.fact : ℂ)) = abs (∑ m in (range j).filter (λ k, n ≤ k), (x ^ n * (x ^ (m - n) / m.fact) : ℂ)) : congr_arg abs (sum_congr rfl (λ m hm, by rw [← mul_div_assoc, ← pow_add, nat.add_sub_cancel']; simp at hm; tauto)) ... ≤ ∑ m in filter (λ k, n ≤ k) (range j), abs (x ^ n * (_ / m.fact)) : abv_sum_le_sum_abv _ _ ... ≤ ∑ m in filter (λ k, n ≤ k) (range j), abs x ^ n * (1 / m.fact) : begin refine sum_le_sum (λ m hm, _), rw [abs_mul, abv_pow abs, abs_div, abs_cast_nat], refine mul_le_mul_of_nonneg_left ((div_le_div_right _).2 _) _, exact nat.cast_pos.2 (nat.fact_pos _), rw abv_pow abs, exact (pow_le_one _ (abs_nonneg _) hx), exact pow_nonneg (abs_nonneg _) _ end ... = abs x ^ n * (∑ m in (range j).filter (λ k, n ≤ k), (1 / m.fact : ℝ)) : by simp [abs_mul, abv_pow abs, abs_div, mul_sum.symm] ... ≤ abs x ^ n * (n.succ * (n.fact * n)⁻¹) : mul_le_mul_of_nonneg_left (sum_div_fact_le _ _ hn) (pow_nonneg (abs_nonneg _) _) end lemma abs_exp_sub_one_le {x : ℂ} (hx : abs x ≤ 1) : abs (exp x - 1) ≤ 2 * abs x := calc abs (exp x - 1) = abs (exp x - ∑ m in range 1, x ^ m / m.fact) : by simp [sum_range_succ] ... ≤ abs x ^ 1 * ((nat.succ 1) * (nat.fact 1 * (1 : ℕ))⁻¹) : exp_bound hx dec_trivial ... = 2 * abs x : by simp [two_mul, mul_two, mul_add, mul_comm] lemma abs_exp_sub_one_sub_id_le {x : ℂ} (hx : abs x ≤ 1) : abs (exp x - 1 - x) ≤ (abs x)^2 := calc abs (exp x - 1 - x) = abs (exp x - ∑ m in range 2, x ^ m / m.fact) : by simp [sub_eq_add_neg, sum_range_succ, add_assoc] ... ≤ (abs x)^2 * (nat.succ 2 * (nat.fact 2 * (2 : ℕ))⁻¹) : exp_bound hx dec_trivial ... ≤ (abs x)^2 * 1 : mul_le_mul_of_nonneg_left (by norm_num) (pow_two_nonneg (abs x)) ... = (abs x)^2 : by rw [mul_one] end complex namespace real open complex finset lemma cos_bound {x : ℝ} (hx : abs' x ≤ 1) : abs' (cos x - (1 - x ^ 2 / 2)) ≤ abs' x ^ 4 * (5 / 96) := calc abs' (cos x - (1 - x ^ 2 / 2)) = abs (complex.cos x - (1 - x ^ 2 / 2)) : by rw ← abs_of_real; simp [of_real_bit0, of_real_one, of_real_inv] ... = abs ((complex.exp (x * I) + complex.exp (-x * I) - (2 - x ^ 2)) / 2) : by simp [complex.cos, sub_div, add_div, neg_div, div_self (@two_ne_zero' ℂ _ _ _)] ... = abs (((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m.fact) + ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m.fact))) / 2) : congr_arg abs (congr_arg (λ x : ℂ, x / 2) begin simp only [sum_range_succ], simp [pow_succ], apply complex.ext; simp [div_eq_mul_inv, norm_sq]; ring end) ... ≤ abs ((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m.fact) / 2) + abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m.fact) / 2) : by rw add_div; exact abs_add _ _ ... = (abs ((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m.fact)) / 2 + abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m.fact)) / 2) : by simp [complex.abs_div] ... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2 + (complex.abs (-x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2) : add_le_add ((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial)) ((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial)) ... ≤ abs' x ^ 4 * (5 / 96) : by norm_num; simp [mul_assoc, mul_comm, mul_left_comm, mul_div_assoc] lemma sin_bound {x : ℝ} (hx : abs' x ≤ 1) : abs' (sin x - (x - x ^ 3 / 6)) ≤ abs' x ^ 4 * (5 / 96) := calc abs' (sin x - (x - x ^ 3 / 6)) = abs (complex.sin x - (x - x ^ 3 / 6)) : by rw ← abs_of_real; simp [of_real_bit0, of_real_one, of_real_inv] ... = abs (((complex.exp (-x * I) - complex.exp (x * I)) * I - (2 * x - x ^ 3 / 3)) / 2) : by simp [complex.sin, sub_div, add_div, neg_div, mul_div_cancel_left _ (@two_ne_zero' ℂ _ _ _), div_div_eq_div_mul, show (3 : ℂ) * 2 = 6, by norm_num] ... = abs ((((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m.fact) - (complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m.fact)) * I) / 2) : congr_arg abs (congr_arg (λ x : ℂ, x / 2) begin simp only [sum_range_succ], simp [pow_succ], apply complex.ext; simp [div_eq_mul_inv, norm_sq]; ring end) ... ≤ abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m.fact) * I / 2) + abs (-((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m.fact) * I) / 2) : by rw [sub_mul, sub_eq_add_neg, add_div]; exact abs_add _ _ ... = (abs ((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m.fact)) / 2 + abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m.fact)) / 2) : by simp [add_comm, complex.abs_div, complex.abs_mul] ... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2 + (complex.abs (-x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2) : add_le_add ((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial)) ((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial)) ... ≤ abs' x ^ 4 * (5 / 96) : by norm_num; simp [mul_assoc, mul_comm, mul_left_comm, mul_div_assoc] lemma cos_pos_of_le_one {x : ℝ} (hx : abs' x ≤ 1) : 0 < cos x := calc 0 < (1 - x ^ 2 / 2) - abs' x ^ 4 * (5 / 96) : sub_pos.2 $ lt_sub_iff_add_lt.2 (calc abs' x ^ 4 * (5 / 96) + x ^ 2 / 2 ≤ 1 * (5 / 96) + 1 / 2 : add_le_add (mul_le_mul_of_nonneg_right (pow_le_one _ (abs_nonneg _) hx) (by norm_num)) ((div_le_div_right (by norm_num)).2 (by rw [pow_two, ← abs_mul_self, _root_.abs_mul]; exact mul_le_one hx (abs_nonneg _) hx)) ... < 1 : by norm_num) ... ≤ cos x : sub_le.1 (abs_sub_le_iff.1 (cos_bound hx)).2 lemma sin_pos_of_pos_of_le_one {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 1) : 0 < sin x := calc 0 < x - x ^ 3 / 6 - abs' x ^ 4 * (5 / 96) : sub_pos.2 $ lt_sub_iff_add_lt.2 (calc abs' x ^ 4 * (5 / 96) + x ^ 3 / 6 ≤ x * (5 / 96) + x / 6 : add_le_add (mul_le_mul_of_nonneg_right (calc abs' x ^ 4 ≤ abs' x ^ 1 : pow_le_pow_of_le_one (abs_nonneg _) (by rwa _root_.abs_of_nonneg (le_of_lt hx0)) dec_trivial ... = x : by simp [_root_.abs_of_nonneg (le_of_lt (hx0))]) (by norm_num)) ((div_le_div_right (by norm_num)).2 (calc x ^ 3 ≤ x ^ 1 : pow_le_pow_of_le_one (le_of_lt hx0) hx dec_trivial ... = x : pow_one _)) ... < x : by linarith) ... ≤ sin x : sub_le.1 (abs_sub_le_iff.1 (sin_bound (by rwa [_root_.abs_of_nonneg (le_of_lt hx0)]))).2 lemma sin_pos_of_pos_of_le_two {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 2) : 0 < sin x := have x / 2 ≤ 1, from div_le_of_le_mul (by norm_num) (by simpa), calc 0 < 2 * sin (x / 2) * cos (x / 2) : mul_pos (mul_pos (by norm_num) (sin_pos_of_pos_of_le_one (half_pos hx0) this)) (cos_pos_of_le_one (by rwa [_root_.abs_of_nonneg (le_of_lt (half_pos hx0))])) ... = sin x : by rw [← sin_two_mul, two_mul, add_halves] lemma cos_one_le : cos 1 ≤ 2 / 3 := calc cos 1 ≤ abs' (1 : ℝ) ^ 4 * (5 / 96) + (1 - 1 ^ 2 / 2) : sub_le_iff_le_add.1 (abs_sub_le_iff.1 (cos_bound (by simp))).1 ... ≤ 2 / 3 : by norm_num lemma cos_one_pos : 0 < cos 1 := cos_pos_of_le_one (by simp) lemma cos_two_neg : cos 2 < 0 := calc cos 2 = cos (2 * 1) : congr_arg cos (mul_one _).symm ... = _ : real.cos_two_mul 1 ... ≤ 2 * (2 / 3) ^ 2 - 1 : sub_le_sub_right (mul_le_mul_of_nonneg_left (by rw [pow_two, pow_two]; exact mul_self_le_mul_self (le_of_lt cos_one_pos) cos_one_le) (by norm_num)) _ ... < 0 : by norm_num end real namespace complex lemma abs_cos_add_sin_mul_I (x : ℝ) : abs (cos x + sin x * I) = 1 := have _ := real.sin_sq_add_cos_sq x, by simp [add_comm, abs, norm_sq, pow_two, *, sin_of_real_re, cos_of_real_re, mul_re] at * lemma abs_exp_eq_iff_re_eq {x y : ℂ} : abs (exp x) = abs (exp y) ↔ x.re = y.re := by rw [exp_eq_exp_re_mul_sin_add_cos, exp_eq_exp_re_mul_sin_add_cos y, abs_mul, abs_mul, abs_cos_add_sin_mul_I, abs_cos_add_sin_mul_I, ← of_real_exp, ← of_real_exp, abs_of_nonneg (le_of_lt (real.exp_pos _)), abs_of_nonneg (le_of_lt (real.exp_pos _)), mul_one, mul_one]; exact ⟨λ h, real.exp_injective h, congr_arg _⟩ @[simp] lemma abs_exp_of_real (x : ℝ) : abs (exp x) = real.exp x := by rw [← of_real_exp]; exact abs_of_nonneg (le_of_lt (real.exp_pos _)) end complex
d27144763fec2bd7b42622fdf68b574afc210704
e61a235b8468b03aee0120bf26ec615c045005d2
/src/Init/Lean/Compiler/IR/Boxing.lean
87b1bb0cf501aa642134072edb2e938634d833d4
[ "Apache-2.0" ]
permissive
SCKelemen/lean4
140dc63a80539f7c61c8e43e1c174d8500ec3230
e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc
refs/heads/master
1,660,973,595,917
1,590,278,033,000
1,590,278,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,980
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Control.EState import Init.Control.Reader import Init.Data.AssocList import Init.Data.Nat import Init.Lean.Runtime import Init.Lean.Compiler.ClosedTermCache import Init.Lean.Compiler.ExternAttr import Init.Lean.Compiler.IR.Basic import Init.Lean.Compiler.IR.CompilerM import Init.Lean.Compiler.IR.FreeVars import Init.Lean.Compiler.IR.ElimDeadVars namespace Lean namespace IR namespace ExplicitBoxing /- Add explicit boxing and unboxing instructions. Recall that the Lean to λ_pure compiler produces code without these instructions. Assumptions: - This transformation is applied before explicit RC instructions (`inc`, `dec`) are inserted. - This transformation is applied before `FnBody.case` has been simplified and `Alt.default` is used. Reason: if there is no `Alt.default` branch, then we can decide whether `x` at `FnBody.case x alts` is an enumeration type by simply inspecting the `CtorInfo` values at `alts`. - This transformation is applied before lower level optimizations are applied which use `Expr.isShared`, `Expr.isTaggedPtr`, and `FnBody.set`. - This transformation is applied after `reset` and `reuse` instructions have been added. Reason: `resetreuse.lean` ignores `box` and `unbox` instructions. -/ def mkBoxedName (n : Name) : Name := mkNameStr n "_boxed" def isBoxedName : Name → Bool | Name.str _ "_boxed" _ => true | _ => false abbrev N := StateM Nat private def mkFresh : N VarId := modifyGet $ fun n => ({ idx := n }, n + 1) def requiresBoxedVersion (env : Environment) (decl : Decl) : Bool := let ps := decl.params; (ps.size > 0 && (decl.resultType.isScalar || ps.any (fun p => p.ty.isScalar || p.borrow) || isExtern env decl.name)) || ps.size > closureMaxArgs def mkBoxedVersionAux (decl : Decl) : N Decl := do let ps := decl.params; qs ← ps.mapM (fun _ => do x ← mkFresh; pure { x := x, ty := IRType.object, borrow := false : Param }); (newVDecls, xs) ← qs.size.foldM (fun i (r : Array FnBody × Array Arg) => let (newVDecls, xs) := r; let p := ps.get! i; let q := qs.get! i; if !p.ty.isScalar then pure (newVDecls, xs.push (Arg.var q.x)) else do x ← mkFresh; pure (newVDecls.push (FnBody.vdecl x p.ty (Expr.unbox q.x) (arbitrary _)), xs.push (Arg.var x))) (#[], #[]); r ← mkFresh; let newVDecls := newVDecls.push (FnBody.vdecl r decl.resultType (Expr.fap decl.name xs) (arbitrary _)); body ← if !decl.resultType.isScalar then do { pure $ reshape newVDecls (FnBody.ret (Arg.var r)) } else do { newR ← mkFresh; let newVDecls := newVDecls.push (FnBody.vdecl newR IRType.object (Expr.box decl.resultType r) (arbitrary _)); pure $ reshape newVDecls (FnBody.ret (Arg.var newR)) }; pure $ Decl.fdecl (mkBoxedName decl.name) qs IRType.object body def mkBoxedVersion (decl : Decl) : Decl := (mkBoxedVersionAux decl).run' 1 def addBoxedVersions (env : Environment) (decls : Array Decl) : Array Decl := let boxedDecls := decls.foldl (fun (newDecls : Array Decl) decl => if requiresBoxedVersion env decl then newDecls.push (mkBoxedVersion decl) else newDecls) #[]; decls ++ boxedDecls /- Infer scrutinee type using `case` alternatives. This can be done whenever `alts` does not contain an `Alt.default _` value. -/ def getScrutineeType (alts : Array Alt) : IRType := let isScalar := alts.size > 1 && -- Recall that we encode Unit and PUnit using `object`. alts.all (fun alt => match alt with | Alt.ctor c _ => c.isScalar | Alt.default _ => false); match isScalar with | false => IRType.object | true => let n := alts.size; if n < 256 then IRType.uint8 else if n < 65536 then IRType.uint16 else if n < 4294967296 then IRType.uint32 else IRType.object -- in practice this should be unreachable def eqvTypes (t₁ t₂ : IRType) : Bool := (t₁.isScalar == t₂.isScalar) && (!t₁.isScalar || t₁ == t₂) structure BoxingContext := (f : FunId := arbitrary _) (localCtx : LocalContext := {}) (resultType : IRType := IRType.irrelevant) (decls : Array Decl) (env : Environment) structure BoxingState := (nextIdx : Index) /- We create auxiliary declarations when boxing constant and literals. The idea is to avoid code such as ``` let x1 := Uint64.inhabited; let x2 := box x1; ... ``` We currently do not cache these declarations in an environment extension, but we use auxDeclCache to avoid creating equivalent auxiliary declarations more than once when processing the same IR declaration. -/ (auxDecls : Array Decl := #[]) (auxDeclCache : AssocList FnBody Expr := AssocList.empty) (nextAuxId : Nat := 1) abbrev M := ReaderT BoxingContext (StateT BoxingState Id) def mkFresh : M VarId := do oldS ← getModify (fun s => { s with nextIdx := s.nextIdx + 1 }); pure { idx := oldS.nextIdx } def getEnv : M Environment := BoxingContext.env <$> read def getLocalContext : M LocalContext := BoxingContext.localCtx <$> read def getResultType : M IRType := BoxingContext.resultType <$> read def getVarType (x : VarId) : M IRType := do localCtx ← getLocalContext; match localCtx.getType x with | some t => pure t | none => pure IRType.object -- unreachable, we assume the code is well formed def getJPParams (j : JoinPointId) : M (Array Param) := do localCtx ← getLocalContext; match localCtx.getJPParams j with | some ys => pure ys | none => pure #[] -- unreachable, we assume the code is well formed def getDecl (fid : FunId) : M Decl := do ctx ← read; match findEnvDecl' ctx.env fid ctx.decls with | some decl => pure decl | none => pure (arbitrary _) -- unreachable if well-formed @[inline] def withParams {α : Type} (xs : Array Param) (k : M α) : M α := adaptReader (fun (ctx : BoxingContext) => { ctx with localCtx := ctx.localCtx.addParams xs }) k @[inline] def withVDecl {α : Type} (x : VarId) (ty : IRType) (v : Expr) (k : M α) : M α := adaptReader (fun (ctx : BoxingContext) => { ctx with localCtx := ctx.localCtx.addLocal x ty v }) k @[inline] def withJDecl {α : Type} (j : JoinPointId) (xs : Array Param) (v : FnBody) (k : M α) : M α := adaptReader (fun (ctx : BoxingContext) => { ctx with localCtx := ctx.localCtx.addJP j xs v }) k /- If `x` declaration is of the form `x := Expr.lit _` or `x := Expr.fap c #[]`, and `x`'s type is not cheap to box (e.g., it is `UInt64), then return its value. -/ private def isExpensiveConstantValueBoxing (x : VarId) (xType : IRType) : M (Option Expr) := if !xType.isScalar then pure none -- We assume unboxing is always cheap else match xType with | IRType.uint8 => pure none | IRType.uint16 => pure none | _ => do localCtx ← getLocalContext; match localCtx.getValue x with | some val => match val with | Expr.lit _ => pure $ some val | Expr.fap _ args => pure $ if args.size == 0 then some val else none | _ => pure none | _ => pure none /- Auxiliary function used by castVarIfNeeded. It is used when the expected type does not match `xType`. If `xType` is scalar, then we need to "box" it. Otherwise, we need to "unbox" it. -/ def mkCast (x : VarId) (xType : IRType) (expectedType : IRType) : M Expr := do opt? ← isExpensiveConstantValueBoxing x xType; match opt? with | some v => do ctx ← read; s ← get; /- Create auxiliary FnBody ``` let x_1 : xType := v; let x_2 : expectedType := Expr.box xType x_1; ret x_2 ``` -/ let body : FnBody := FnBody.vdecl { idx := 1 } xType v $ FnBody.vdecl { idx := 2 } expectedType (Expr.box xType { idx := 1 }) $ FnBody.ret (mkVarArg { idx := 2 }); match s.auxDeclCache.find? body with | some v => pure v | none => do let auxName := ctx.f ++ ((`_boxed_const).appendIndexAfter s.nextAuxId); let auxConst := Expr.fap auxName #[]; let auxDecl := Decl.fdecl auxName #[] expectedType body; modify $ fun s => { s with auxDecls := s.auxDecls.push auxDecl, auxDeclCache := s.auxDeclCache.cons body auxConst, nextAuxId := s.nextAuxId + 1 }; pure auxConst | none => pure $ if xType.isScalar then Expr.box xType x else Expr.unbox x @[inline] def castVarIfNeeded (x : VarId) (expected : IRType) (k : VarId → M FnBody) : M FnBody := do xType ← getVarType x; if eqvTypes xType expected then k x else do y ← mkFresh; v ← mkCast x xType expected; FnBody.vdecl y expected v <$> k y @[inline] def castArgIfNeeded (x : Arg) (expected : IRType) (k : Arg → M FnBody) : M FnBody := match x with | Arg.var x => castVarIfNeeded x expected (fun x => k (Arg.var x)) | _ => k x @[specialize] def castArgsIfNeededAux (xs : Array Arg) (typeFromIdx : Nat → IRType) : M (Array Arg × Array FnBody) := xs.iterateM (#[], #[]) $ fun i (x : Arg) (r : Array Arg × Array FnBody) => let expected := typeFromIdx i.val; let (xs, bs) := r; match x with | Arg.irrelevant => pure (xs.push x, bs) | Arg.var x => do xType ← getVarType x; if eqvTypes xType expected then pure (xs.push (Arg.var x), bs) else do y ← mkFresh; v ← mkCast x xType expected; let b := FnBody.vdecl y expected v FnBody.nil; pure (xs.push (Arg.var y), bs.push b) @[inline] def castArgsIfNeeded (xs : Array Arg) (ps : Array Param) (k : Array Arg → M FnBody) : M FnBody := do (ys, bs) ← castArgsIfNeededAux xs (fun i => (ps.get! i).ty); b ← k ys; pure (reshape bs b) @[inline] def boxArgsIfNeeded (xs : Array Arg) (k : Array Arg → M FnBody) : M FnBody := do (ys, bs) ← castArgsIfNeededAux xs (fun _ => IRType.object); b ← k ys; pure (reshape bs b) def unboxResultIfNeeded (x : VarId) (ty : IRType) (e : Expr) (b : FnBody) : M FnBody := if ty.isScalar then do y ← mkFresh; pure $ FnBody.vdecl y IRType.object e (FnBody.vdecl x ty (Expr.unbox y) b) else pure $ FnBody.vdecl x ty e b def castResultIfNeeded (x : VarId) (ty : IRType) (e : Expr) (eType : IRType) (b : FnBody) : M FnBody := if eqvTypes ty eType then pure $ FnBody.vdecl x ty e b else do y ← mkFresh; v ← mkCast y eType ty; pure $ FnBody.vdecl y eType e (FnBody.vdecl x ty v b) def visitVDeclExpr (x : VarId) (ty : IRType) (e : Expr) (b : FnBody) : M FnBody := match e with | Expr.ctor c ys => if c.isScalar && ty.isScalar then pure $ FnBody.vdecl x ty (Expr.lit (LitVal.num c.cidx)) b else boxArgsIfNeeded ys $ fun ys => pure $ FnBody.vdecl x ty (Expr.ctor c ys) b | Expr.reuse w c u ys => boxArgsIfNeeded ys $ fun ys => pure $ FnBody.vdecl x ty (Expr.reuse w c u ys) b | Expr.fap f ys => do decl ← getDecl f; castArgsIfNeeded ys decl.params $ fun ys => castResultIfNeeded x ty (Expr.fap f ys) decl.resultType b | Expr.pap f ys => do env ← getEnv; decl ← getDecl f; let f := if requiresBoxedVersion env decl then mkBoxedName f else f; boxArgsIfNeeded ys $ fun ys => pure $ FnBody.vdecl x ty (Expr.pap f ys) b | Expr.ap f ys => boxArgsIfNeeded ys $ fun ys => unboxResultIfNeeded x ty (Expr.ap f ys) b | other => pure $ FnBody.vdecl x ty e b partial def visitFnBody : FnBody → M FnBody | FnBody.vdecl x t v b => do b ← withVDecl x t v (visitFnBody b); visitVDeclExpr x t v b | FnBody.jdecl j xs v b => do v ← withParams xs (visitFnBody v); b ← withJDecl j xs v (visitFnBody b); pure $ FnBody.jdecl j xs v b | FnBody.uset x i y b => do b ← visitFnBody b; castVarIfNeeded y IRType.usize $ fun y => pure $ FnBody.uset x i y b | FnBody.sset x i o y ty b => do b ← visitFnBody b; castVarIfNeeded y ty $ fun y => pure $ FnBody.sset x i o y ty b | FnBody.mdata d b => FnBody.mdata d <$> visitFnBody b | FnBody.case tid x _ alts => do let expected := getScrutineeType alts; alts ← alts.mapM $ fun alt => alt.mmodifyBody visitFnBody; castVarIfNeeded x expected $ fun x => do pure $ FnBody.case tid x expected alts | FnBody.ret x => do expected ← getResultType; castArgIfNeeded x expected (fun x => pure $ FnBody.ret x) | FnBody.jmp j ys => do ps ← getJPParams j; castArgsIfNeeded ys ps (fun ys => pure $ FnBody.jmp j ys) | other => pure other def run (env : Environment) (decls : Array Decl) : Array Decl := let ctx : BoxingContext := { decls := decls, env := env }; let decls := decls.foldl (fun (newDecls : Array Decl) (decl : Decl) => match decl with | Decl.fdecl f xs t b => let nextIdx := decl.maxIndex + 1; let (b, s) := (withParams xs (visitFnBody b) { ctx with f := f, resultType := t }).run { nextIdx := nextIdx }; let newDecls := newDecls ++ s.auxDecls; let newDecl := Decl.fdecl f xs t b; let newDecl := newDecl.elimDead; newDecls.push newDecl | d => newDecls.push d) #[]; addBoxedVersions env decls end ExplicitBoxing def explicitBoxing (decls : Array Decl) : CompilerM (Array Decl) := do env ← getEnv; pure $ ExplicitBoxing.run env decls end IR end Lean
0eb9ae830b5c5d2a71733d6e915d33c05ea6d7d0
510e96af568b060ed5858226ad954c258549f143
/topology/topological_space.lean
11edf5515bc57f0f009280599a06182c3db35258
[]
no_license
Shamrock-Frost/library_dev
cb6d1739237d81e17720118f72ba0a6db8a5906b
0245c71e4931d3aceeacf0aea776454f6ee03c9c
refs/heads/master
1,609,481,034,595
1,500,165,215,000
1,500,165,347,000
97,350,162
0
0
null
1,500,164,969,000
1,500,164,969,000
null
UTF-8
Lean
false
false
26,017
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 Theory of topological spaces. -/ import algebra.lattice.filter open set filter lattice universes u v w structure topological_space (α : Type u) := (open' : set α → Prop) (open_univ : open' univ) (open_inter : ∀s t, open' s → open' t → open' (s ∩ t)) (open_sUnion : ∀s, (∀t∈s, open' t) → open' (⋃₀ s)) attribute [class] topological_space section topological_space variables {α : Type u} {β : Type v} {ι : Sort w} {a a₁ a₂ : α} {s s₁ s₂ : set α} lemma topological_space_eq {f g : topological_space α} (h' : f^.open' = g^.open') : f = g := begin cases f with a, cases g with b, have h : a = b, assumption, clear h', subst h end section variables [t : topological_space α] include t /- open -/ def open' (s : set α) : Prop := topological_space.open' t s @[simp] lemma open_univ : open' (univ : set α) := topological_space.open_univ t lemma open_inter (h₁ : open' s₁) (h₂ : open' s₂) : open' (s₁ ∩ s₂) := topological_space.open_inter t s₁ s₂ h₁ h₂ lemma open_sUnion {s : set (set α)} (h : ∀t ∈ s, open' t) : open' (⋃₀ s) := topological_space.open_sUnion t s h end variables [topological_space α] lemma open_Union {f : ι → set α} (h : ∀i, open' (f i)) : open' (⋃i, f i) := open_sUnion $ assume t ⟨i, (heq : t = f i)⟩, heq^.symm ▸ h i @[simp] lemma open_empty : open' (∅ : set α) := have open' (⋃₀ ∅ : set α), from open_sUnion (assume a, false.elim), by simp at this; assumption /- closed -/ def closed (s : set α) : Prop := open' (-s) @[simp] lemma closed_empty : closed (∅ : set α) := by simp [closed] @[simp] lemma closed_univ : closed (univ : set α) := by simp [closed] lemma closed_union : closed s₁ → closed s₂ → closed (s₁ ∪ s₂) := by simp [closed]; exact open_inter lemma closed_sInter {s : set (set α)} : (∀t ∈ s, closed t) → closed (⋂₀ s) := by simp [closed, compl_sInter]; exact assume h, open_Union $ assume t, open_Union $ assume ht, h t ht lemma closed_Inter {f : ι → set α} (h : ∀i, closed (f i)) : closed (⋂i, f i ) := closed_sInter $ assume t ⟨i, (heq : t = f i)⟩, heq^.symm ▸ h i @[simp] lemma closed_compl_iff_open {s : set α} : open' (-s) ↔ closed s := by refl @[simp] lemma open_compl_iff_closed {s : set α} : closed (-s) ↔ open' s := by rw [←closed_compl_iff_open, compl_compl] lemma open_diff {s t : set α} (h₁ : open' s) (h₂ : closed t) : open' (s - t) := open_inter h₁ $ closed_compl_iff_open^.mpr h₂ /- interior -/ def interior (s : set α) : set α := ⋃₀ {t | open' t ∧ t ⊆ s} @[simp] lemma open_interior {s : set α} : open' (interior s) := open_sUnion $ assume t ⟨h₁, h₂⟩, h₁ lemma interior_subset {s : set α} : interior s ⊆ s := sUnion_subset $ assume t ⟨h₁, h₂⟩, h₂ lemma interior_maximal {s t : set α} (h₁ : t ⊆ s) (h₂ : open' t) : t ⊆ interior s := subset_sUnion_of_mem ⟨h₂, h₁⟩ lemma interior_eq_of_open {s : set α} (h : open' s) : interior s = s := subset.antisymm interior_subset (interior_maximal (subset.refl s) h) lemma interior_eq_iff_open {s : set α} : interior s = s ↔ open' s := ⟨assume h, h ▸ open_interior, interior_eq_of_open⟩ lemma subset_interior_iff_subset_of_open {s t : set α} (h₁ : open' s) : s ⊆ interior t ↔ s ⊆ t := ⟨assume h, subset.trans h interior_subset, assume h₂, interior_maximal h₂ h₁⟩ lemma interior_mono {s t : set α} (h : s ⊆ t) : interior s ⊆ interior t := interior_maximal (subset.trans interior_subset h) open_interior @[simp] lemma interior_empty : interior (∅ : set α) = ∅ := interior_eq_of_open open_empty @[simp] lemma interior_univ : interior (univ : set α) = univ := interior_eq_of_open open_univ @[simp] lemma interior_interior {s : set α} : interior (interior s) = interior s := interior_eq_of_open open_interior @[simp] lemma interior_inter {s t : set α} : interior (s ∩ t) = interior s ∩ interior t := subset.antisymm (subset_inter (interior_mono $ inter_subset_left s t) (interior_mono $ inter_subset_right s t)) (interior_maximal (inter_subset_inter interior_subset interior_subset) $ by simp [open_inter]) lemma interior_union_closed_of_interior_empty {s t : set α} (h₁ : closed s) (h₂ : interior t = ∅) : interior (s ∪ t) = interior s := have interior (s ∪ t) ⊆ s, from assume x ⟨u, ⟨(hu₁ : open' u), (hu₂ : u ⊆ s ∪ t)⟩, (hx₁ : x ∈ u)⟩, classical.by_contradiction $ assume hx₂ : x ∉ s, have u - s ⊆ t, from assume x ⟨h₁, h₂⟩, or.resolve_left (hu₂ h₁) h₂, have u - s ⊆ interior t, by simp [subset_interior_iff_subset_of_open, this, open_diff hu₁ h₁], have u - s ⊆ ∅, by rw [h₂] at this; assumption, this ⟨hx₁, hx₂⟩, subset.antisymm (interior_maximal this open_interior) (interior_mono $ subset_union_left _ _) /- closure -/ def closure (s : set α) : set α := ⋂₀ {t | closed t ∧ s ⊆ t} @[simp] lemma closed_closure {s : set α} : closed (closure s) := closed_sInter $ assume t ⟨h₁, h₂⟩, h₁ lemma subset_closure {s : set α} : s ⊆ closure s := subset_sInter $ assume t ⟨h₁, h₂⟩, h₂ lemma closure_minimal {s t : set α} (h₁ : s ⊆ t) (h₂ : closed t) : closure s ⊆ t := sInter_subset_of_mem ⟨h₂, h₁⟩ lemma closure_eq_of_closed {s : set α} (h : closed s) : closure s = s := subset.antisymm (closure_minimal (subset.refl s) h) subset_closure lemma closure_eq_iff_closed {s : set α} : closure s = s ↔ closed s := ⟨assume h, h ▸ closed_closure, closure_eq_of_closed⟩ lemma closure_subset_iff_subset_of_closed {s t : set α} (h₁ : closed t) : closure s ⊆ t ↔ s ⊆ t := ⟨subset.trans subset_closure, assume h, closure_minimal h h₁⟩ lemma closure_mono {s t : set α} (h : s ⊆ t) : closure s ⊆ closure t := closure_minimal (subset.trans h subset_closure) closed_closure @[simp] lemma closure_empty : closure (∅ : set α) = ∅ := closure_eq_of_closed closed_empty @[simp] lemma closure_univ : closure (univ : set α) = univ := closure_eq_of_closed closed_univ @[simp] lemma closure_closure {s : set α} : closure (closure s) = closure s := closure_eq_of_closed closed_closure @[simp] lemma closure_union {s t : set α} : closure (s ∪ t) = closure s ∪ closure t := subset.antisymm (closure_minimal (union_subset_union subset_closure subset_closure) $ by simp [closed_union]) (union_subset (closure_mono $ subset_union_left _ _) (closure_mono $ subset_union_right _ _)) lemma interior_subset_closure {s : set α} : interior s ⊆ closure s := subset.trans interior_subset subset_closure lemma closure_eq_compl_interior_compl {s : set α} : closure s = - interior (- s) := begin simp [interior, closure], rw [compl_sUnion, compl_image_set_of], simp [neg_subset_neg_iff_subset] end @[simp] lemma interior_compl_eq {s : set α} : interior (- s) = - closure s := by simp [closure_eq_compl_interior_compl] @[simp] lemma closure_compl_eq {s : set α} : closure (- s) = - interior s := by simp [closure_eq_compl_interior_compl] /- neighbourhood filter -/ def nhds (a : α) : filter α := (⨅ s ∈ {s : set α | a ∈ s ∧ open' s}, principal s) lemma nhds_sets {a : α} : (nhds a)^.sets = {s | ∃t⊆s, open' t ∧ a ∈ t} := calc (nhds a)^.sets = (⋃s∈{s : set α| a ∈ s ∧ open' s}, (principal s)^.sets) : infi_sets_eq' begin simp, exact assume x ⟨hx₁, hx₂⟩ y ⟨hy₁, hy₂⟩, ⟨_, ⟨open_inter hx₁ hy₁, ⟨hx₂, hy₂⟩⟩, ⟨inter_subset_left _ _, inter_subset_right _ _⟩⟩ end ⟨univ, by simp⟩ ... = {s | ∃t⊆s, open' t ∧ a ∈ t} : le_antisymm (supr_le $ assume i, supr_le $ assume ⟨hi₁, hi₂⟩ t ht, ⟨i, ht, hi₂, hi₁⟩) (assume t ⟨i, hi₁, hi₂, hi₃⟩, begin simp; exact ⟨i, hi₂, hi₁, hi₃⟩ end) lemma map_nhds {a : α} {f : α → β} : map f (nhds a) = (⨅ s ∈ {s : set α | a ∈ s ∧ open' s}, principal (image f s)) := calc map f (nhds a) = (⨅ s ∈ {s : set α | a ∈ s ∧ open' s}, map f (principal s)) : map_binfi_eq begin simp, exact assume x ⟨hx₁, hx₂⟩ y ⟨hy₁, hy₂⟩, ⟨_, ⟨open_inter hx₁ hy₁, ⟨hx₂, hy₂⟩⟩, ⟨inter_subset_left _ _, inter_subset_right _ _⟩⟩ end ⟨univ, by simp⟩ ... = _ : by simp lemma mem_nhds_sets_iff {a : α} {s : set α} : s ∈ (nhds a)^.sets ↔ ∃t⊆s, open' t ∧ a ∈ t := by simp [nhds_sets] lemma mem_nhds_sets {a : α} {s : set α} (hs : open' s) (ha : a ∈ s) : s ∈ (nhds a)^.sets := by simp [nhds_sets]; exact ⟨s, hs, subset.refl _, ha⟩ lemma return_le_nhds : return ≤ (nhds : α → filter α) := assume a, le_infi $ assume s, le_infi $ assume ⟨h₁, _⟩, principal_mono^.mpr $ by simp [h₁] @[simp] lemma nhds_neq_bot {a : α} : nhds a ≠ ⊥ := suppose nhds a = ⊥, have return a = (⊥ : filter α), from lattice.bot_unique $ this ▸ return_le_nhds a, return_neq_bot this lemma interior_eq_nhds {s : set α} : interior s = {a | nhds a ≤ principal s} := set.ext $ by simp [interior, nhds_sets] lemma open_iff_nhds {s : set α} : open' s ↔ (∀a∈s, nhds a ≤ principal s) := calc open' s ↔ interior s = s : by rw [interior_eq_iff_open] ... ↔ s ⊆ interior s : ⟨assume h, by simp [*, subset.refl], subset.antisymm interior_subset⟩ ... ↔ (∀a∈s, nhds a ≤ principal s) : by rw [interior_eq_nhds]; refl lemma closure_eq_nhds {s : set α} : closure s = {a | nhds a ⊓ principal s ≠ ⊥} := calc closure s = - interior (- s) : closure_eq_compl_interior_compl ... = {a | ¬ nhds a ≤ principal (-s)} : by rw [interior_eq_nhds]; refl ... = {a | nhds a ⊓ principal s ≠ ⊥} : set.ext $ assume a, not_congr (inf_eq_bot_iff_le_compl (show principal s ⊔ principal (-s) = ⊤, by simp [principal_univ]) (by simp))^.symm lemma closed_iff_nhds {s : set α} : closed s ↔ (∀a, nhds a ⊓ principal s ≠ ⊥ → a ∈ s) := calc closed s ↔ closure s = s : by rw [closure_eq_iff_closed] ... ↔ closure s ⊆ s : ⟨assume h, by simp [*, subset.refl], assume h, subset.antisymm h subset_closure⟩ ... ↔ (∀a, nhds a ⊓ principal s ≠ ⊥ → a ∈ s) : by rw [closure_eq_nhds]; refl /- locally finite family [General Topology (Bourbaki, 1995)] -/ section locally_finite def locally_finite (f : β → set α) := ∀x:α, ∃t∈(nhds x)^.sets, finite {i | f i ∩ t ≠ ∅ } theorem not_eq_empty_iff_exists {s : set α} : ¬ (s = ∅) ↔ ∃ x, x ∈ s := ⟨exists_mem_of_ne_empty, assume ⟨x, (hx : x ∈ s)⟩ h_eq, by rw [h_eq] at hx; assumption⟩ lemma closed_Union_of_locally_finite {f : β → set α} (h₁ : locally_finite f) (h₂ : ∀i, closed (f i)) : closed (⋃i, f i) := open_iff_nhds^.mpr $ assume a, assume h : a ∉ (⋃i, f i), have ∀i, a ∈ -f i, from assume i hi, by simp at h; exact h ⟨i, hi⟩, have ∀i, - f i ∈ (nhds a).sets, by rw [nhds_sets]; exact assume i, ⟨- f i, subset.refl _, h₂ i, this i⟩, let ⟨t, h_sets, (h_fin : finite {i | f i ∩ t ≠ ∅ })⟩ := h₁ a in calc nhds a ≤ principal (t ∩ (⋂ i∈{i | f i ∩ t ≠ ∅ }, - f i)) : begin simp, apply @filter.inter_mem_sets _ (nhds a) _ _ h_sets, apply @filter.Inter_mem_sets _ _ (nhds a) _ _ h_fin, exact assume i h, this i end ... ≤ principal (- ⋃i, f i) : begin simp, intro x, simp [not_eq_empty_iff_exists], exact assume ⟨xt, ht⟩ i xfi, ht i ⟨x, xt, xfi⟩ xfi end end locally_finite section compact def compact (s : set α) := ∀{f}, f ≠ ⊥ → f ≤ principal s → ∃a∈s, f ⊓ nhds a ≠ ⊥ lemma compact_adherence_nhdset {s t : set α} {f : filter α} (hs : compact s) (hf₂ : f ≤ principal s) (ht₁ : open' t) (ht₂ : ∀a∈s, nhds a ⊓ f ≠ ⊥ → a ∈ t) : t ∈ f.sets := classical.by_cases mem_sets_of_neq_bot $ suppose f ⊓ principal (- t) ≠ ⊥, let ⟨a, ha, (hfa : f ⊓ principal (-t) ⊓ nhds a ≠ ⊥)⟩ := hs this $ inf_le_left_of_le hf₂ in have a ∈ t, from ht₂ a ha $ neq_bot_of_le_neq_bot hfa $ le_inf inf_le_right $ inf_le_left_of_le inf_le_left, have nhds a ⊓ principal (-t) ≠ ⊥, from neq_bot_of_le_neq_bot hfa $ le_inf inf_le_right $ inf_le_left_of_le inf_le_right, have ∀s∈(nhds a ⊓ principal (-t)).sets, s ≠ ∅, from forall_sets_neq_empty_iff_neq_bot.mpr this, have false, from this _ ⟨t, mem_nhds_sets ht₁ ‹a ∈ t ›, -t, subset.refl _, subset.refl _⟩ (by simp), by contradiction lemma compact_iff_ultrafilter_le_nhds {s : set α} : compact s ↔ (∀f, ultrafilter f → f ≤ principal s → ∃a∈s, f ≤ nhds a) := ⟨assume hs : compact s, assume f hf hfs, let ⟨a, ha, h⟩ := hs hf.left hfs in ⟨a, ha, le_of_ultrafilter hf h⟩, assume hs : (∀f, ultrafilter f → f ≤ principal s → ∃a∈s, f ≤ nhds a), assume f hf hfs, let ⟨a, ha, (h : ultrafilter_of f ≤ nhds a)⟩ := hs (ultrafilter_of f) (ultrafilter_ultrafilter_of hf) (le_trans ultrafilter_of_le hfs) in have ultrafilter_of f ⊓ nhds a ≠ ⊥, by simp [inf_of_le_left, h]; exact (ultrafilter_ultrafilter_of hf).left, ⟨a, ha, neq_bot_of_le_neq_bot this (inf_le_inf ultrafilter_of_le (le_refl _))⟩⟩ lemma finite_subcover_of_compact {s : set α} {c : set (set α)} (hs : compact s) (hc₁ : ∀t∈c, open' t) (hc₂ : s ⊆ ⋃₀ c) : ∃c'⊆c, finite c' ∧ s ⊆ ⋃₀ c' := classical.by_contradiction $ assume h, have h : ∀{c'}, c' ⊆ c → finite c' → ¬ s ⊆ ⋃₀ c', from assume c' h₁ h₂ h₃, h ⟨c', h₁, h₂, h₃⟩, let f : filter α := (⨅c':{c' : set (set α) // c' ⊆ c ∧ finite c'}, principal (s - ⋃₀ c')), ⟨a, ha⟩ := @exists_mem_of_ne_empty α s (assume h', h (empty_subset _) finite.empty $ h'.symm ▸ empty_subset _) in have f ≠ ⊥, from infi_neq_bot_of_directed ⟨a⟩ (assume ⟨c₁, hc₁, hc'₁⟩ ⟨c₂, hc₂, hc'₂⟩, ⟨⟨c₁ ∪ c₂, union_subset hc₁ hc₂, finite_union hc'₁ hc'₂⟩, principal_mono.mpr $ diff_right_antimono $ sUnion_mono $ subset_union_left _ _, principal_mono.mpr $ diff_right_antimono $ sUnion_mono $ subset_union_right _ _⟩) (assume ⟨c', hc'₁, hc'₂⟩, by simp [diff_neq_empty]; exact h hc'₁ hc'₂), have f ≤ principal s, from infi_le_of_le ⟨∅, empty_subset _, finite.empty⟩ $ show principal (s - ⋃₀∅) ≤ principal s, by simp; exact subset.refl s, let ⟨a, ha, (h : f ⊓ nhds a ≠ ⊥)⟩ := hs ‹f ≠ ⊥› this, ⟨t, ht₁, (ht₂ : a ∈ t)⟩ := hc₂ ha in have f ≤ principal (-t), from infi_le_of_le ⟨{t}, by simp [ht₁], finite_insert finite.empty⟩ $ principal_mono.mpr $ show s - ⋃₀{t} ⊆ - t, begin simp; exact assume x ⟨_, hnt⟩, hnt end, have closed (- t), from closed_compl_iff_open.mp $ by simp; exact hc₁ t ht₁, have a ∈ - t, from closed_iff_nhds.mp this _ $ neq_bot_of_le_neq_bot h $ le_inf inf_le_right (inf_le_left_of_le $ ‹f ≤ principal (- t)›), this ‹a ∈ t› end compact section separation class t1_space (α : Type u) [topological_space α] := (t1 : ∀x, closed ({x} : set α)) class t2_space (α : Type u) [topological_space α] := (t2 : ∀x y, x ≠ y → ∃u v : set α, open' u ∧ open' v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅) lemma eq_of_nhds_neq_bot [ht : t2_space α] {x y : α} (h : nhds x ⊓ nhds y ≠ ⊥) : x = y := classical.by_contradiction $ suppose x ≠ y, let ⟨u, v, hu, hv, hx, hy, huv⟩ := t2_space.t2 _ x y this in have h₁ : u ∈ (nhds x ⊓ nhds y).sets, from @mem_inf_sets_of_left α (nhds x) (nhds y) _ $ mem_nhds_sets hu hx, have h₂ : v ∈ (nhds x ⊓ nhds y).sets, from @mem_inf_sets_of_right α (nhds x) (nhds y) _ $ mem_nhds_sets hv hy, have u ∩ v ∈ (nhds x ⊓ nhds y).sets, from @inter_mem_sets α (nhds x ⊓ nhds y) _ _ h₁ h₂, h $ empty_in_sets_eq_bot.mp $ huv ▸ this end separation end topological_space namespace topological_space variables {α : Type u} inductive generate_open (g : set (set α)) : set α → Prop | basic : ∀s∈g, generate_open s | univ : generate_open univ | inter : ∀s t, generate_open s → generate_open t → generate_open (s ∩ t) | sUnion : ∀k, (∀s∈k, generate_open s) → generate_open (⋃₀ k) def generate_from (g : set (set α)) : topological_space α := { topological_space . open' := generate_open g, open_univ := generate_open.univ g, open_inter := generate_open.inter, open_sUnion := generate_open.sUnion } lemma nhds_generate_from {g : set (set α)} {a : α} : @nhds α (generate_from g) a = (⨅s∈{s | a ∈ s ∧ s ∈ g}, principal s) := le_antisymm (infi_le_infi $ assume s, infi_le_infi_const $ assume ⟨as, sg⟩, ⟨as, generate_open.basic _ sg⟩) (le_infi $ assume s, le_infi $ assume ⟨as, hs⟩, have ∀s, generate_open g s → a ∈ s → (⨅s∈{s | a ∈ s ∧ s ∈ g}, principal s) ≤ principal s, begin intros s hs, induction hs, case generate_open.basic s hs { exact assume as, infi_le_of_le s $ infi_le _ ⟨as, hs⟩ }, case generate_open.univ { rw [principal_univ], exact assume _, le_top }, case generate_open.inter s t hs' ht' hs ht { exact assume ⟨has, hat⟩, calc _ ≤ principal s ⊓ principal t : le_inf (hs has) (ht hat) ... = _ : by simp }, case generate_open.sUnion k hk' hk { intro h, simp at h, revert h, exact assume ⟨t, hat, htk⟩, calc _ ≤ principal t : hk t htk hat ... ≤ _ : begin simp; exact subset_sUnion_of_mem htk end }, end, this s hs as) end topological_space section constructions variables {α : Type u} {β : Type v} instance : weak_order (topological_space α) := { weak_order . le := λt s, t^.open' ≤ s^.open', le_antisymm := assume t s h₁ h₂, topological_space_eq $ le_antisymm h₁ h₂, le_refl := assume t, le_refl t^.open', le_trans := assume a b c h₁ h₂, @le_trans _ _ a^.open' b^.open' c^.open' h₁ h₂ } instance : has_Inf (topological_space α) := ⟨assume (tt : set (topological_space α)), { topological_space . open' := λs, ∀t∈tt, topological_space.open' t s, open_univ := assume t h, t^.open_univ, open_inter := assume s₁ s₂ h₁ h₂ t ht, t^.open_inter s₁ s₂ (h₁ t ht) (h₂ t ht), open_sUnion := assume s h t ht, t^.open_sUnion _ $ assume s' hss', h _ hss' _ ht }⟩ private lemma Inf_le {tt : set (topological_space α)} {t : topological_space α} (h : t ∈ tt) : Inf tt ≤ t := assume s hs, hs t h private lemma le_Inf {tt : set (topological_space α)} {t : topological_space α} (h : ∀t'∈tt, t ≤ t') : t ≤ Inf tt := assume s hs t' ht', h t' ht' s hs def topological_space.induced {α : Type u} {β : Type v} (f : α → β) (t : topological_space β) : topological_space α := { topological_space . open' := λs, ∃s', t^.open' s' ∧ s = vimage f s', open_univ := ⟨univ, by simp; exact t^.open_univ⟩, open_inter := assume s₁ s₂ ⟨s'₁, hs₁, eq₁⟩ ⟨s'₂, hs₂, eq₂⟩, ⟨s'₁ ∩ s'₂, by simp [eq₁, eq₂]; exact t^.open_inter _ _ hs₁ hs₂⟩, open_sUnion := assume s h, begin simp [classical.skolem] at h, cases h with f hf, apply exists.intro (⋃(x : set α) (h : x ∈ s), f x h), simp [sUnion_eq_Union, (λx h, (hf x h)^.right^.symm)], exact (@open_Union β _ t _ $ assume i, show open' (⋃h, f i h), from @open_Union β _ t _ $ assume h, (hf i h)^.left) end } def topological_space.coinduced {α : Type u} {β : Type v} (f : α → β) (t : topological_space α) : topological_space β := { topological_space . open' := λs, t^.open' (vimage f s), open_univ := by simp; exact t^.open_univ, open_inter := assume s₁ s₂ h₁ h₂, by simp; exact t^.open_inter _ _ h₁ h₂, open_sUnion := assume s h, by rw [vimage_sUnion]; exact (@open_Union _ _ t _ $ assume i, show open' (⋃ (H : i ∈ s), vimage f i), from @open_Union _ _ t _ $ assume hi, h i hi) } instance : has_inf (topological_space α) := ⟨assume t₁ t₂ : topological_space α, { topological_space . open' := λs, t₁.open' s ∧ t₂.open' s, open_univ := ⟨t₁^.open_univ, t₂^.open_univ⟩, open_inter := assume s₁ s₂ ⟨h₁₁, h₁₂⟩ ⟨h₂₁, h₂₂⟩, ⟨t₁.open_inter s₁ s₂ h₁₁ h₂₁, t₂.open_inter s₁ s₂ h₁₂ h₂₂⟩, open_sUnion := assume s h, ⟨t₁.open_sUnion _ $ assume t ht, (h t ht).left, t₂.open_sUnion _ $ assume t ht, (h t ht).right⟩ }⟩ instance : has_top (topological_space α) := ⟨{topological_space . open' := λs, true, open_univ := trivial, open_inter := assume a b ha hb, trivial, open_sUnion := assume s h, trivial }⟩ instance {α : Type u} : complete_lattice (topological_space α) := { topological_space.weak_order with sup := λa b, Inf {x | a ≤ x ∧ b ≤ x}, le_sup_left := assume a b, le_Inf $ assume x, assume h : a ≤ x ∧ b ≤ x, h^.left, le_sup_right := assume a b, le_Inf $ assume x, assume h : a ≤ x ∧ b ≤ x, h^.right, sup_le := assume a b c h₁ h₂, Inf_le $ show c ∈ {x | a ≤ x ∧ b ≤ x}, from ⟨h₁, h₂⟩, inf := (⊓), le_inf := assume a b h h₁ h₂ s hs, ⟨h₁ s hs, h₂ s hs⟩, inf_le_left := assume a b s ⟨h₁, h₂⟩, h₁, inf_le_right := assume a b s ⟨h₁, h₂⟩, h₂, top := ⊤, le_top := assume a t ht, trivial, bot := Inf univ, bot_le := assume a, Inf_le $ mem_univ a, Sup := λtt, Inf {t | ∀t'∈tt, t' ≤ t}, le_Sup := assume s f h, le_Inf $ assume t ht, ht _ h, Sup_le := assume s f h, Inf_le $ assume t ht, h _ ht, Inf := Inf, le_Inf := assume s a, le_Inf, Inf_le := assume s a, Inf_le } instance inhabited_topological_space {α : Type u} : inhabited (topological_space α) := ⟨⊤⟩ lemma t2_space_top : @t2_space α ⊤ := ⟨assume x y hxy, ⟨{x}, {y}, trivial, trivial, mem_insert _ _, mem_insert _ _, eq_empty_of_forall_not_mem $ by intros z hz; simp at hz; cc⟩⟩ lemma le_of_nhds_le_nhds {t₁ t₂ : topological_space α} (h : ∀x, @nhds α t₂ x ≤ @nhds α t₁ x) : t₁ ≤ t₂ := assume s, show @open' α t₁ s → @open' α t₂ s, begin simp [open_iff_nhds]; exact assume hs a ha, h _ $ hs _ ha end lemma eq_of_nhds_eq_nhds {t₁ t₂ : topological_space α} (h : ∀x, @nhds α t₂ x = @nhds α t₁ x) : t₁ = t₂ := le_antisymm (le_of_nhds_le_nhds $ assume x, le_of_eq $ h x) (le_of_nhds_le_nhds $ assume x, le_of_eq $ (h x).symm) instance : topological_space empty := ⊤ instance : topological_space unit := ⊤ instance : topological_space bool := ⊤ instance : topological_space ℕ := ⊤ instance : topological_space ℤ := ⊤ instance sierpinski_space : topological_space Prop := topological_space.generate_from {{true}} instance {p : α → Prop} [t : topological_space α] : topological_space (subtype p) := topological_space.induced subtype.val t instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α × β) := topological_space.induced prod.fst t₁ ⊔ topological_space.induced prod.snd t₂ instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α ⊕ β) := topological_space.coinduced sum.inl t₁ ⊓ topological_space.coinduced sum.inr t₂ instance {β : α → Type v} [t₂ : Πa, topological_space (β a)] : topological_space (sigma β) := ⨅a, topological_space.coinduced (sigma.mk a) (t₂ a) instance topological_space_Pi {β : α → Type v} [t₂ : Πa, topological_space (β a)] : topological_space (Πa, β a) := ⨆a, topological_space.induced (λf, f a) (t₂ a) section open topological_space lemma generate_from_le {t : topological_space α} { g : set (set α) } (h : ∀s∈g, open' s) : generate_from g ≤ t := assume s (hs : generate_open g s), generate_open.rec_on hs h open_univ (assume s t _ _ hs ht, open_inter hs ht) (assume k _ hk, open_sUnion hk) lemma supr_eq_generate_from {ι : Sort w} { g : ι → topological_space α } : supr g = generate_from (⋃i, {s | (g i).open' s}) := le_antisymm (supr_le $ assume i s open_s, generate_open.basic _ $ by simp; exact ⟨i, open_s⟩) (generate_from_le $ assume s, begin simp, exact assume ⟨i, open_s⟩, have g i ≤ supr g, from le_supr _ _, this s open_s end) lemma sup_eq_generate_from { g₁ g₂ : topological_space α } : g₁ ⊔ g₂ = generate_from {s | g₁.open' s ∨ g₂.open' s} := le_antisymm (sup_le (assume s, generate_open.basic _ ∘ or.inl) (assume s, generate_open.basic _ ∘ or.inr)) (generate_from_le $ assume s hs, have h₁ : g₁ ≤ g₁ ⊔ g₂, from le_sup_left, have h₂ : g₂ ≤ g₁ ⊔ g₂, from le_sup_right, or.rec_on hs (h₁ s) (h₂ s)) lemma nhds_mono {t₁ t₂ : topological_space α} {a : α} (h : t₁ ≤ t₂) : @nhds α t₂ a ≤ @nhds α t₁ a := infi_le_infi $ assume s, infi_le_infi2 $ assume ⟨ha, hs⟩, ⟨⟨ha, h _ hs⟩, le_refl _⟩ lemma nhds_supr {ι : Sort w} {t : ι → topological_space α} {a : α} : @nhds α (supr t) a = (⨅i, @nhds α (t i) a) := le_antisymm (le_infi $ assume i, nhds_mono $ le_supr _ _) begin rw [supr_eq_generate_from, nhds_generate_from], simp, exact (le_infi $ assume s, le_infi $ assume ⟨⟨i, hi⟩, hs⟩, infi_le_of_le i $ le_principal_iff.mpr $ @mem_nhds_sets α (t i) _ _ hi hs) end end end constructions
32354accb55a269f5078f2e21e2f2ff6a486992c
07f5f86b00fed90a419ccda4298d8b795a68f657
/library/init/meta/injection_tactic.lean
d647a724324b1acba18158c6f177592dd7d8be58
[ "Apache-2.0" ]
permissive
VBaratham/lean
8ec5c3167b4835cfbcd7f25e2173d61ad9416b3a
450ca5834c1c35318e4b47d553bb9820c1b3eee7
refs/heads/master
1,629,649,471,814
1,512,060,373,000
1,512,060,469,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,970
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.tactic init.function namespace tactic open nat tactic environment expr list private meta def at_end₂ (e₁ e₂ : expr) : ℕ → tactic (list (option expr)) | 2 := return [some e₁, some e₂] | (n+3) := (λ xs, none :: xs) <$> at_end₂ (n+2) | _ := fail "at_end expected arity > 1" private meta def mk_next_name : name → nat → tactic (name × nat) | n i := do let n' := n.append_after i, (get_local n' >> mk_next_name n (i+1)) <|> (return (n', i+1)) /- Auxiliary function for introducing the new equalities produced by the injection tactic. -/ private meta def injection_intro : expr → nat → list name → tactic (list expr × list name) | (pi n bi b d) i ns := do (hname, i) ← if ns.empty then mk_next_name `h i else return (head ns, i), h ← intro hname, (l, ns') ← injection_intro d i (tail ns), return (h :: l, ns') | e i ns := return ([], ns) /- Tries to decompose the given expression by constructor injectivity. Returns the list of new hypotheses, and the remaining names from the given list. -/ meta def injection_with (h : expr) (ns : list name) : tactic (list expr × list name) := do ht ← infer_type h, (lhs0, rhs0) ← match_eq ht, env ← get_env, lhs ← whnf lhs0, rhs ← whnf rhs0, let n_fl := const_name (get_app_fn lhs), let n_fr := const_name (get_app_fn rhs), if n_fl = n_fr then do let n_inj := n_fl <.> "inj_arrow", if env.contains n_inj then do c_inj ← mk_const n_inj, arity ← get_arity c_inj, tgt ← target, args ← at_end₂ h tgt (arity - 1), pr ← mk_mapp n_inj args, pr_type ← infer_type pr, pr_type ← whnf pr_type, eapply pr, injection_intro (binding_domain pr_type) 1 ns else fail "injection tactic failed, argument must be an equality proof where lhs and rhs are of the form (c ...), where c is a constructor" else do tgt ← target, let I_name := name.get_prefix n_fl, pr ← mk_app (I_name <.> "no_confusion") [tgt, lhs, rhs, h], exact pr, return ([], ns) meta def injection (h : expr) : tactic (list expr) := do (t, _) ← injection_with h [], return t private meta def injections_with_inner : nat → list expr → list name → tactic unit | 0 lc ns := fail "recursion depth exceeded" | (n+1) [] ns := skip | (n+1) (h :: lc) ns := do o ← try_core (injection_with h ns), match o with | none := injections_with_inner (n+1) lc ns | some ([], _) := skip -- This means that the contradiction part was triggered and the goal is done | some (t, ns') := injections_with_inner n (t ++ lc) ns' end meta def injections_with (ns : list name) : tactic unit := do lc ← local_context, injections_with_inner 5 lc ns end tactic
43e32fb47ba447067b94abc78a187844228c383a
6094e25ea0b7699e642463b48e51b2ead6ddc23f
/library/data/set/basic.lean
0d346ffd103f315f9d42ae4c9f95fc1ed74871c4
[ "Apache-2.0" ]
permissive
gbaz/lean
a7835c4e3006fbbb079e8f8ffe18aacc45adebfb
a501c308be3acaa50a2c0610ce2e0d71becf8032
refs/heads/master
1,611,198,791,433
1,451,339,111,000
1,451,339,111,000
48,713,797
0
0
null
1,451,338,939,000
1,451,338,939,000
null
UTF-8
Lean
false
false
23,728
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad, Leonardo de Moura -/ import logic.connectives logic.identities algebra.binary open eq.ops binary function definition set (X : Type) := X → Prop namespace set variable {X : Type} /- membership and subset -/ definition mem (x : X) (a : set X) := a x infix ∈ := mem notation a ∉ b := ¬ mem a b theorem ext {a b : set X} (H : ∀x, x ∈ a ↔ x ∈ b) : a = b := funext (take x, propext (H x)) definition subset (a b : set X) := ∀⦃x⦄, x ∈ a → x ∈ b infix ⊆ := subset definition superset (s t : set X) : Prop := t ⊆ s infix ⊇ := superset theorem subset.refl (a : set X) : a ⊆ a := take x, assume H, H theorem subset.trans {a b c : set X} (subab : a ⊆ b) (subbc : b ⊆ c) : a ⊆ c := take x, assume ax, subbc (subab ax) theorem subset.antisymm {a b : set X} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b := ext (λ x, iff.intro (λ ina, h₁ ina) (λ inb, h₂ inb)) -- an alterantive name theorem eq_of_subset_of_subset {a b : set X} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b := subset.antisymm h₁ h₂ theorem mem_of_subset_of_mem {s₁ s₂ : set X} {a : X} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := assume h₁ h₂, h₁ _ h₂ /- strict subset -/ definition strict_subset (a b : set X) := a ⊆ b ∧ a ≠ b infix ` ⊂ `:50 := strict_subset theorem strict_subset.irrefl (a : set X) : ¬ a ⊂ a := assume h, absurd rfl (and.elim_right h) /- bounded quantification -/ abbreviation bounded_forall (a : set X) (P : X → Prop) := ∀⦃x⦄, x ∈ a → P x notation `forallb` binders `∈` a `, ` r:(scoped:1 P, P) := bounded_forall a r notation `∀₀` binders `∈` a `, ` r:(scoped:1 P, P) := bounded_forall a r abbreviation bounded_exists (a : set X) (P : X → Prop) := ∃⦃x⦄, x ∈ a ∧ P x notation `existsb` binders `∈` a `, ` r:(scoped:1 P, P) := bounded_exists a r notation `∃₀` binders `∈` a `, ` r:(scoped:1 P, P) := bounded_exists a r theorem bounded_exists.intro {P : X → Prop} {s : set X} {x : X} (xs : x ∈ s) (Px : P x) : ∃₀ x ∈ s, P x := exists.intro x (and.intro xs Px) /- empty set -/ definition empty : set X := λx, false notation `∅` := empty theorem not_mem_empty (x : X) : ¬ (x ∈ ∅) := assume H : x ∈ ∅, H theorem mem_empty_eq (x : X) : x ∈ ∅ = false := rfl theorem eq_empty_of_forall_not_mem {s : set X} (H : ∀ x, x ∉ s) : s = ∅ := ext (take x, iff.intro (assume xs, absurd xs (H x)) (assume xe, absurd xe !not_mem_empty)) theorem empty_subset (s : set X) : ∅ ⊆ s := take x, assume H, false.elim H theorem eq_empty_of_subset_empty {s : set X} (H : s ⊆ ∅) : s = ∅ := subset.antisymm H (empty_subset s) theorem subset_empty_iff (s : set X) : s ⊆ ∅ ↔ s = ∅ := iff.intro eq_empty_of_subset_empty (take xeq, by rewrite xeq; apply subset.refl ∅) /- universal set -/ definition univ : set X := λx, true theorem mem_univ (x : X) : x ∈ univ := trivial theorem mem_univ_iff (x : X) : x ∈ univ ↔ true := !iff.refl theorem mem_univ_eq (x : X) : x ∈ univ = true := rfl theorem empty_ne_univ [h : inhabited X] : (empty : set X) ≠ univ := assume H : empty = univ, absurd (mem_univ (inhabited.value h)) (eq.rec_on H (not_mem_empty _)) theorem subset_univ (s : set X) : s ⊆ univ := λ x H, trivial theorem eq_univ_of_univ_subset {s : set X} (H : univ ⊆ s) : s = univ := eq_of_subset_of_subset (subset_univ s) H theorem eq_univ_of_forall {s : set X} (H : ∀ x, x ∈ s) : s = univ := ext (take x, iff.intro (assume H', trivial) (assume H', H x)) /- union -/ definition union (a b : set X) : set X := λx, x ∈ a ∨ x ∈ b notation a ∪ b := union a b theorem mem_union_left {x : X} {a : set X} (b : set X) : x ∈ a → x ∈ a ∪ b := assume h, or.inl h theorem mem_union_right {x : X} {b : set X} (a : set X) : x ∈ b → x ∈ a ∪ b := assume h, or.inr h theorem mem_unionl {x : X} {a b : set X} : x ∈ a → x ∈ a ∪ b := assume h, or.inl h theorem mem_unionr {x : X} {a b : set X} : x ∈ b → x ∈ a ∪ b := assume h, or.inr h theorem mem_or_mem_of_mem_union {x : X} {a b : set X} (H : x ∈ a ∪ b) : x ∈ a ∨ x ∈ b := H theorem mem_union.elim {x : X} {a b : set X} {P : Prop} (H₁ : x ∈ a ∪ b) (H₂ : x ∈ a → P) (H₃ : x ∈ b → P) : P := or.elim H₁ H₂ H₃ theorem mem_union_iff (x : X) (a b : set X) : x ∈ a ∪ b ↔ x ∈ a ∨ x ∈ b := !iff.refl theorem mem_union_eq (x : X) (a b : set X) : x ∈ a ∪ b = (x ∈ a ∨ x ∈ b) := rfl theorem union_self (a : set X) : a ∪ a = a := ext (take x, !or_self) theorem union_empty (a : set X) : a ∪ ∅ = a := ext (take x, !or_false) theorem empty_union (a : set X) : ∅ ∪ a = a := ext (take x, !false_or) theorem union.comm (a b : set X) : a ∪ b = b ∪ a := ext (take x, or.comm) theorem union.assoc (a b c : set X) : (a ∪ b) ∪ c = a ∪ (b ∪ c) := ext (take x, or.assoc) theorem union.left_comm (s₁ s₂ s₃ : set X) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := !left_comm union.comm union.assoc s₁ s₂ s₃ theorem union.right_comm (s₁ s₂ s₃ : set X) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := !right_comm union.comm union.assoc s₁ s₂ s₃ theorem subset_union_left (s t : set X) : s ⊆ s ∪ t := λ x H, or.inl H theorem subset_union_right (s t : set X) : t ⊆ s ∪ t := λ x H, or.inr H theorem union_subset {s t r : set X} (sr : s ⊆ r) (tr : t ⊆ r) : s ∪ t ⊆ r := λ x xst, or.elim xst (λ xs, sr xs) (λ xt, tr xt) /- intersection -/ definition inter (a b : set X) : set X := λx, x ∈ a ∧ x ∈ b notation a ∩ b := inter a b theorem mem_inter_iff (x : X) (a b : set X) : x ∈ a ∩ b ↔ x ∈ a ∧ x ∈ b := !iff.refl theorem mem_inter_eq (x : X) (a b : set X) : x ∈ a ∩ b = (x ∈ a ∧ x ∈ b) := rfl theorem mem_inter {x : X} {a b : set X} (Ha : x ∈ a) (Hb : x ∈ b) : x ∈ a ∩ b := and.intro Ha Hb theorem mem_of_mem_inter_left {x : X} {a b : set X} (H : x ∈ a ∩ b) : x ∈ a := and.left H theorem mem_of_mem_inter_right {x : X} {a b : set X} (H : x ∈ a ∩ b) : x ∈ b := and.right H theorem inter_self (a : set X) : a ∩ a = a := ext (take x, !and_self) theorem inter_empty (a : set X) : a ∩ ∅ = ∅ := ext (take x, !and_false) theorem empty_inter (a : set X) : ∅ ∩ a = ∅ := ext (take x, !false_and) theorem inter.comm (a b : set X) : a ∩ b = b ∩ a := ext (take x, !and.comm) theorem inter.assoc (a b c : set X) : (a ∩ b) ∩ c = a ∩ (b ∩ c) := ext (take x, !and.assoc) theorem inter.left_comm (s₁ s₂ s₃ : set X) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := !left_comm inter.comm inter.assoc s₁ s₂ s₃ theorem inter.right_comm (s₁ s₂ s₃ : set X) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := !right_comm inter.comm inter.assoc s₁ s₂ s₃ theorem inter_univ (a : set X) : a ∩ univ = a := ext (take x, !and_true) theorem univ_inter (a : set X) : univ ∩ a = a := ext (take x, !true_and) theorem inter_subset_left (s t : set X) : s ∩ t ⊆ s := λ x H, and.left H theorem inter_subset_right (s t : set X) : s ∩ t ⊆ t := λ x H, and.right H theorem subset_inter {s t r : set X} (rs : r ⊆ s) (rt : r ⊆ t) : r ⊆ s ∩ t := λ x xr, and.intro (rs xr) (rt xr) /- distributivity laws -/ theorem inter.distrib_left (s t u : set X) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := ext (take x, !and.left_distrib) theorem inter.distrib_right (s t u : set X) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := ext (take x, !and.right_distrib) theorem union.distrib_left (s t u : set X) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := ext (take x, !or.left_distrib) theorem union.distrib_right (s t u : set X) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := ext (take x, !or.right_distrib) /- set-builder notation -/ -- {x : X | P} definition set_of (P : X → Prop) : set X := P notation `{` binder ` | ` r:(scoped:1 P, set_of P) `}` := r -- {x ∈ s | P} definition sep (P : X → Prop) (s : set X) : set X := λx, x ∈ s ∧ P x notation `{` binder ` ∈ ` s ` | ` r:(scoped:1 p, sep p s) `}` := r /- insert -/ definition insert (x : X) (a : set X) : set X := {y : X | y = x ∨ y ∈ a} -- '{x, y, z} notation `'{`:max a:(foldr `, ` (x b, insert x b) ∅) `}`:0 := a theorem subset_insert (x : X) (a : set X) : a ⊆ insert x a := take y, assume ys, or.inr ys theorem mem_insert (x : X) (s : set X) : x ∈ insert x s := or.inl rfl theorem mem_insert_of_mem {x : X} {s : set X} (y : X) : x ∈ s → x ∈ insert y s := assume h, or.inr h theorem eq_or_mem_of_mem_insert {x a : X} {s : set X} : x ∈ insert a s → x = a ∨ x ∈ s := assume h, h theorem mem_of_mem_insert_of_ne {x a : X} {s : set X} (xin : x ∈ insert a s) : x ≠ a → x ∈ s := or_resolve_right (eq_or_mem_of_mem_insert xin) theorem mem_insert_eq (x a : X) (s : set X) : x ∈ insert a s = (x = a ∨ x ∈ s) := propext (iff.intro !eq_or_mem_of_mem_insert (or.rec (λH', (eq.substr H' !mem_insert)) !mem_insert_of_mem)) theorem insert_eq_of_mem {a : X} {s : set X} (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 insert.comm (x y : X) (s : set X) : insert x (insert y s) = insert y (insert x s) := ext (take a, by rewrite [*mem_insert_eq, propext !or.left_comm]) -- useful in proofs by induction theorem forall_of_forall_insert {P : X → Prop} {a : X} {s : set X} (H : ∀ x, x ∈ insert a s → P x) : ∀ x, x ∈ s → P x := λ x xs, H x (!mem_insert_of_mem xs) /- singleton -/ theorem mem_singleton_iff (a b : X) : a ∈ '{b} ↔ a = b := iff.intro (assume ainb, or.elim ainb (λ aeqb, aeqb) (λ f, false.elim f)) (assume aeqb, or.inl aeqb) theorem mem_singleton (a : X) : a ∈ '{a} := !mem_insert theorem eq_of_mem_singleton {x y : X} : x ∈ insert y ∅ → x = y := assume h, or.elim (eq_or_mem_of_mem_insert h) (suppose x = y, this) (suppose x ∈ ∅, absurd this !not_mem_empty) theorem insert_eq (x : X) (s : set X) : insert x s = '{x} ∪ s := ext (take y, iff.intro (suppose y ∈ insert x s, or.elim this (suppose y = x, or.inl (or.inl this)) (suppose y ∈ s, or.inr this)) (suppose y ∈ '{x} ∪ s, or.elim this (suppose y ∈ '{x}, or.inl (eq_of_mem_singleton this)) (suppose y ∈ s, or.inr this))) /- separation -/ theorem mem_sep {s : set X} {P : X → Prop} {x : X} (xs : x ∈ s) (Px : P x) : x ∈ {x ∈ s | P x} := and.intro xs Px theorem eq_sep_of_subset {s t : set X} (ssubt : s ⊆ t) : s = {x ∈ t | x ∈ s} := ext (take x, iff.intro (suppose x ∈ s, and.intro (ssubt this) this) (suppose x ∈ {x ∈ t | x ∈ s}, and.right this)) theorem mem_sep_iff {s : set X} {P : X → Prop} {x : X} : x ∈ {x ∈ s | P x} ↔ x ∈ s ∧ P x := !iff.refl theorem sep_subset (s : set X) (P : X → Prop) : {x ∈ s | P x} ⊆ s := take x, assume H, and.left H /- complement -/ definition complement (s : set X) : set X := {x | x ∉ s} prefix `-` := complement theorem mem_comp {s : set X} {x : X} (H : x ∉ s) : x ∈ -s := H theorem not_mem_of_mem_comp {s : set X} {x : X} (H : x ∈ -s) : x ∉ s := H theorem mem_comp_iff (s : set X) (x : X) : x ∈ -s ↔ x ∉ s := !iff.refl theorem inter_comp_self (s : set X) : s ∩ -s = ∅ := ext (take x, !and_not_self_iff) theorem comp_inter_self (s : set X) : -s ∩ s = ∅ := ext (take x, !not_and_self_iff) /- some classical identities -/ section open classical theorem comp_empty : -(∅ : set X) = univ := ext (take x, iff.intro (assume H, trivial) (assume H, not_false)) theorem comp_union (s t : set X) : -(s ∪ t) = -s ∩ -t := ext (take x, !not_or_iff_not_and_not) theorem comp_comp (s : set X) : -(-s) = s := ext (take x, !not_not_iff) theorem comp_inter (s t : set X) : -(s ∩ t) = -s ∪ -t := ext (take x, !not_and_iff_not_or_not) theorem comp_univ : -(univ : set X) = ∅ := by rewrite [-comp_empty, comp_comp] theorem union_eq_comp_comp_inter_comp (s t : set X) : s ∪ t = -(-s ∩ -t) := ext (take x, !or_iff_not_and_not) theorem inter_eq_comp_comp_union_comp (s t : set X) : s ∩ t = -(-s ∪ -t) := ext (take x, !and_iff_not_or_not) theorem union_comp_self (s : set X) : s ∪ -s = univ := ext (take x, !or_not_self_iff) theorem comp_union_self (s : set X) : -s ∪ s = univ := ext (take x, !not_or_self_iff) theorem complement_compose_complement : #function complement ∘ complement = @id (set X) := funext (λ s, comp_comp s) end /- set difference -/ definition diff (s t : set X) : set X := {x ∈ s | x ∉ t} infix `\`:70 := diff theorem mem_diff {s t : set X} {x : X} (H1 : x ∈ s) (H2 : x ∉ t) : x ∈ s \ t := and.intro H1 H2 theorem mem_of_mem_diff {s t : set X} {x : X} (H : x ∈ s \ t) : x ∈ s := and.left H theorem not_mem_of_mem_diff {s t : set X} {x : X} (H : x ∈ s \ t) : x ∉ t := and.right H theorem mem_diff_iff (s t : set X) (x : X) : x ∈ s \ t ↔ x ∈ s ∧ x ∉ t := !iff.refl theorem mem_diff_eq (s t : set X) (x : X) : x ∈ s \ t = (x ∈ s ∧ x ∉ t) := rfl theorem diff_eq (s t : set X) : s \ t = s ∩ -t := rfl theorem union_diff_cancel {s t : set X} [dec : Π x, decidable (x ∈ s)] (H : s ⊆ t) : s ∪ (t \ s) = t := ext (take x, iff.intro (assume H1 : x ∈ s ∪ (t \ s), or.elim H1 (assume H2, !H H2) (assume H2, and.left H2)) (assume H1 : x ∈ t, decidable.by_cases (suppose x ∈ s, or.inl this) (suppose x ∉ s, or.inr (and.intro H1 this)))) theorem diff_subset (s t : set X) : s \ t ⊆ s := inter_subset_left s _ theorem comp_eq_univ_diff (s : set X) : -s = univ \ s := ext (take x, iff.intro (assume H, and.intro trivial H) (assume H, and.right H)) /- powerset -/ definition powerset (s : set X) : set (set X) := {x : set X | x ⊆ s} prefix `𝒫`:100 := powerset theorem mem_powerset {x s : set X} (H : x ⊆ s) : x ∈ 𝒫 s := H theorem subset_of_mem_powerset {x s : set X} (H : x ∈ 𝒫 s) : x ⊆ s := H theorem mem_powerset_iff (x s : set X) : x ∈ 𝒫 s ↔ x ⊆ s := !iff.refl /- function image -/ section image variables {Y Z : Type} abbreviation eq_on (f1 f2 : X → Y) (a : set X) : Prop := ∀₀ x ∈ a, f1 x = f2 x definition image (f : X → Y) (a : set X) : set Y := {y : Y | ∃x, x ∈ a ∧ f x = y} notation f `'[`:max a `]` := image f a theorem image_eq_image_of_eq_on {f1 f2 : X → Y} {a : set X} (H1 : eq_on f1 f2 a) : f1 '[a] = f2 '[a] := ext (take y, iff.intro (assume H2, obtain x (H3 : x ∈ a ∧ f1 x = y), from H2, have H4 : x ∈ a, from and.left H3, have H5 : f2 x = y, from (H1 H4)⁻¹ ⬝ and.right H3, exists.intro x (and.intro H4 H5)) (assume H2, obtain x (H3 : x ∈ a ∧ f2 x = y), from H2, have H4 : x ∈ a, from and.left H3, have H5 : f1 x = y, from (H1 H4) ⬝ and.right H3, exists.intro x (and.intro H4 H5))) theorem mem_image {f : X → Y} {a : set X} {x : X} {y : Y} (H1 : x ∈ a) (H2 : f x = y) : y ∈ f '[a] := exists.intro x (and.intro H1 H2) theorem mem_image_of_mem (f : X → Y) {x : X} {a : set X} (H : x ∈ a) : f x ∈ image f a := mem_image H rfl lemma image_compose (f : Y → Z) (g : X → Y) (a : set X) : (f ∘ g) '[a] = f '[g '[a]] := ext (take z, iff.intro (assume Hz : z ∈ (f ∘ g) '[a], obtain x (Hx₁ : x ∈ a) (Hx₂ : f (g x) = z), from Hz, have Hgx : g x ∈ g '[a], from mem_image Hx₁ rfl, show z ∈ f '[g '[a]], from mem_image Hgx Hx₂) (assume Hz : z ∈ f '[g '[a]], obtain y (Hy₁ : y ∈ g '[a]) (Hy₂ : f y = z), from Hz, obtain x (Hz₁ : x ∈ a) (Hz₂ : g x = y), from Hy₁, show z ∈ (f ∘ g) '[a], from mem_image Hz₁ (Hz₂⁻¹ ▸ Hy₂))) lemma image_subset {a b : set X} (f : X → Y) (H : a ⊆ b) : f '[a] ⊆ f '[b] := take y, assume Hy : y ∈ f '[a], obtain x (Hx₁ : x ∈ a) (Hx₂ : f x = y), from Hy, mem_image (H Hx₁) Hx₂ theorem image_union (f : X → Y) (s t : set X) : image f (s ∪ t) = image f s ∪ image f t := ext (take y, iff.intro (assume H : y ∈ image f (s ∪ t), obtain x [(xst : x ∈ s ∪ t) (fxy : f x = y)], from H, or.elim xst (assume xs, or.inl (mem_image xs fxy)) (assume xt, or.inr (mem_image xt fxy))) (assume H : y ∈ image f s ∪ image f t, or.elim H (assume yifs : y ∈ image f s, obtain x [(xs : x ∈ s) (fxy : f x = y)], from yifs, mem_image (or.inl xs) fxy) (assume yift : y ∈ image f t, obtain x [(xt : x ∈ t) (fxy : f x = y)], from yift, mem_image (or.inr xt) fxy))) theorem image_empty (f : X → Y) : image f ∅ = ∅ := eq_empty_of_forall_not_mem (take y, suppose y ∈ image f ∅, obtain x [(H : x ∈ empty) H'], from this, H) theorem mem_image_complement (t : set X) (S : set (set X)) : t ∈ complement '[S] ↔ -t ∈ S := iff.intro (suppose t ∈ complement '[S], obtain t' [(Ht' : t' ∈ S) (Ht : -t' = t)], from this, show -t ∈ S, by rewrite [-Ht, comp_comp]; exact Ht') (suppose -t ∈ S, have -(-t) ∈ complement '[S], from mem_image_of_mem complement this, show t ∈ complement '[S], from comp_comp t ▸ this) theorem image_id (s : set X) : id '[s] = s := ext (take x, iff.intro (suppose x ∈ id '[s], obtain x' [(Hx' : x' ∈ s) (x'eq : x' = x)], from this, show x ∈ s, by rewrite [-x'eq]; apply Hx') (suppose x ∈ s, mem_image_of_mem id this)) theorem complement_complement_image (S : set (set X)) : complement '[complement '[S]] = S := by rewrite [-image_compose, complement_compose_complement, image_id] end image /- large unions -/ section large_unions variables {I : Type} variable a : set I variable b : I → set X variable C : set (set X) definition Inter : set X := {x : X | ∀i, x ∈ b i} definition bInter : set X := {x : X | ∀₀ i ∈ a, x ∈ b i} definition sInter : set X := {x : X | ∀₀ c ∈ C, x ∈ c} definition Union : set X := {x : X | ∃i, x ∈ b i} definition bUnion : set X := {x : X | ∃₀ i ∈ a, x ∈ b i} definition sUnion : set X := {x : X | ∃₀ c ∈ C, x ∈ c} notation `⋃` binders, r:(scoped f, Union f) := r notation `⋃` binders `∈` s, r:(scoped f, bUnion s f) := r prefix `⋃₀`:110 := sUnion notation `⋂` binders, r:(scoped f, Inter f) := r notation `⋂` binders `∈` s, r:(scoped f, bInter s f) := r prefix `⋂₀`:110 := sInter end large_unions theorem Union_subset {I : Type} {b : I → set X} {c : set X} (H : ∀ i, b i ⊆ c) : Union b ⊆ c := take x, suppose x ∈ Union b, obtain i (Hi : x ∈ b i), from this, show x ∈ c, from H i Hi theorem mem_sUnion {x : X} {t : set X} {S : set (set X)} (Hx : x ∈ t) (Ht : t ∈ S) : x ∈ ⋃₀ S := exists.intro t (and.intro Ht Hx) theorem Union_eq_sUnion_image {X I : Type} (s : I → set X) : (⋃ i, s i) = ⋃₀ (s '[univ]) := ext (take x, iff.intro (suppose x ∈ Union s, obtain i (Hi : x ∈ s i), from this, mem_sUnion Hi (mem_image_of_mem s trivial)) (suppose x ∈ sUnion (s '[univ]), obtain t [(Ht : t ∈ s '[univ]) (Hx : x ∈ t)], from this, obtain i [univi (Hi : s i = t)], from Ht, exists.intro i (show x ∈ s i, by rewrite Hi; apply Hx))) theorem Inter_eq_sInter_image {X I : Type} (s : I → set X) : (⋂ i, s i) = ⋂₀ (s '[univ]) := ext (take x, iff.intro (assume H : x ∈ Inter s, take t, suppose t ∈ s '[univ], obtain i [univi (Hi : s i = t)], from this, show x ∈ t, by rewrite -Hi; exact H i) (assume H : x ∈ ⋂₀ (s '[univ]), take i, have s i ∈ s '[univ], from mem_image_of_mem s trivial, show x ∈ s i, from H this)) theorem sUnion_empty : ⋃₀ ∅ = (∅ : set X) := eq_empty_of_forall_not_mem (take x, suppose x ∈ sUnion ∅, obtain t [(Ht : t ∈ ∅) Ht'], from this, show false, from Ht) theorem sInter_empty : ⋂₀ ∅ = (univ : set X) := eq_univ_of_forall (λ x s H, false.elim H) theorem sUnion_singleton (s : set X) : ⋃₀ '{s} = s := ext (take x, iff.intro (suppose x ∈ sUnion '{s}, obtain u [(Hu : u ∈ '{s}) (xu : x ∈ u)], from this, have u = s, from eq_of_mem_singleton Hu, show x ∈ s, using this, by rewrite -this; apply xu) (suppose x ∈ s, mem_sUnion this (mem_singleton s))) theorem sInter_singleton (s : set X) : ⋂₀ '{s} = s := ext (take x, iff.intro (suppose x ∈ ⋂₀ '{s}, show x ∈ s, from this (mem_singleton s)) (suppose x ∈ s, take u, suppose u ∈ '{s}, show x ∈ u, by+ rewrite [eq_of_mem_singleton this]; assumption)) theorem sUnion_union (S T : set (set X)) : ⋃₀ (S ∪ T) = ⋃₀ S ∪ ⋃₀ T := ext (take x, iff.intro (suppose x ∈ sUnion (S ∪ T), obtain u [(Hu : u ∈ S ∪ T) (xu : x ∈ u)], from this, or.elim Hu (assume uS, or.inl (mem_sUnion xu uS)) (assume uT, or.inr (mem_sUnion xu uT))) (suppose x ∈ sUnion S ∪ sUnion T, or.elim this (suppose x ∈ sUnion S, obtain u [(uS : u ∈ S) (xu : x ∈ u)], from this, mem_sUnion xu (or.inl uS)) (suppose x ∈ sUnion T, obtain u [(uT : u ∈ T) (xu : x ∈ u)], from this, mem_sUnion xu (or.inr uT)))) theorem sInter_union (S T : set (set X)) : ⋂₀ (S ∪ T) = ⋂₀ S ∩ ⋂₀ T := ext (take x, iff.intro (assume H : x ∈ ⋂₀ (S ∪ T), and.intro (λ u uS, H (or.inl uS)) (λ u uT, H (or.inr uT))) (assume H : x ∈ ⋂₀ S ∩ ⋂₀ T, take u, suppose u ∈ S ∪ T, or.elim this (λ uS, and.left H u uS) (λ uT, and.right H u uT))) theorem sUnion_insert (s : set X) (T : set (set X)) : ⋃₀ (insert s T) = s ∪ ⋃₀ T := by rewrite [insert_eq, sUnion_union, sUnion_singleton] theorem sInter_insert (s : set X) (T : set (set X)) : ⋂₀ (insert s T) = s ∩ ⋂₀ T := by rewrite [insert_eq, sInter_union, sInter_singleton] theorem comp_sUnion (S : set (set X)) : - ⋃₀ S = ⋂₀ (complement '[S]) := ext (take x, iff.intro (assume H : x ∈ -(⋃₀ S), take t, suppose t ∈ complement '[S], obtain t' [(Ht' : t' ∈ S) (Ht : -t' = t)], from this, have x ∈ -t', from suppose x ∈ t', H (mem_sUnion this Ht'), show x ∈ t, using this, by rewrite -Ht; apply this) (assume H : x ∈ ⋂₀ (complement '[S]), suppose x ∈ ⋃₀ S, obtain t [(tS : t ∈ S) (xt : x ∈ t)], from this, have -t ∈ complement '[S], from mem_image_of_mem complement tS, have x ∈ -t, from H this, show false, proof this xt qed)) theorem sUnion_eq_comp_sInter_comp (S : set (set X)) : ⋃₀ S = - ⋂₀ (complement '[S]) := by rewrite [-comp_comp, comp_sUnion] theorem comp_sInter (S : set (set X)) : - ⋂₀ S = ⋃₀ (complement '[S]) := by rewrite [sUnion_eq_comp_sInter_comp, complement_complement_image] theorem sInter_eq_comp_sUnion_comp (S : set (set X)) : ⋂₀ S = -(⋃₀ (complement '[S])) := by rewrite [-comp_comp, comp_sInter] theorem comp_Union {X I : Type} (s : I → set X) : - (⋃ i, s i) = (⋂ i, - s i) := by rewrite [Union_eq_sUnion_image, comp_sUnion, -image_compose, -Inter_eq_sInter_image] theorem Union_eq_comp_Inter_comp {X I : Type} (s : I → set X) : (⋃ i, s i) = - (⋂ i, - s i) := by rewrite [-comp_comp, comp_Union] theorem comp_Inter {X I : Type} (s : I → set X) : -(⋂ i, s i) = (⋃ i, - s i) := by rewrite [Inter_eq_sInter_image, comp_sInter, -image_compose, -Union_eq_sUnion_image] theorem Inter_eq_comp_Union_comp {X I : Type} (s : I → set X) : (⋂ i, s i) = - (⋃ i, -s i) := by rewrite [-comp_comp, comp_Inter] end set
d727eb955eb7c15c669bb7e60c027cde1ea70fb0
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/tests/lean/run/doNotation3.lean
58ec09e97e8ba4013d86c9fe44d81f52721ba5b3
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,623
lean
theorem zeroLtOfLt : {a b : Nat} → a < b → 0 < b | 0, _, h => h | a+1, b, h => have a < b from Nat.ltTrans (Nat.ltSuccSelf _) h zeroLtOfLt this def fold {m α β} [Monad m] (as : Array α) (b : β) (f : α → β → m β) : m β := do let rec loop : (i : Nat) → i ≤ as.size → β → m β | 0, h, b => b | i+1, h, b => do have h' : i < as.size from Nat.ltOfLtOfLe (Nat.ltSuccSelf i) h have as.size - 1 < as.size from Nat.subLt (zeroLtOfLt h') (decide! : 0 < 1) have as.size - 1 - i < as.size from Nat.ltOfLeOfLt (Nat.subLe (as.size - 1) i) this let b ← f (as.get ⟨as.size - 1 - i, this⟩) b loop i (Nat.leOfLt h') b loop as.size (Nat.leRefl _) b #eval Id.run $ fold #[1, 2, 3, 4] 0 (pure $ · + ·) theorem ex : (Id.run $ fold #[1, 2, 3, 4] 0 (pure $ · + ·)) = 10 := rfl def fold2 {m α β} [Monad m] (as : Array α) (b : β) (f : α → β → m β) : m β := let rec loop (i : Nat) (h : i ≤ as.size) (b : β) : m β := do match i, h with | 0, h => return b | i+1, h => have h' : i < as.size from Nat.ltOfLtOfLe (Nat.ltSuccSelf i) h have as.size - 1 < as.size from Nat.subLt (zeroLtOfLt h') (decide! : 0 < 1) have as.size - 1 - i < as.size from Nat.ltOfLeOfLt (Nat.subLe (as.size - 1) i) this let b ← f (as.get ⟨as.size - 1 - i, this⟩) b loop i (Nat.leOfLt h') b loop as.size (Nat.leRefl _) b def f (x : Nat) (ref : IO.Ref Nat) : IO Nat := do let mut x := x if x == 0 then x ← ref.get IO.println x return x + 1 def fTest : IO Unit := do unless (← f 0 (← IO.mkRef 10)) == 11 do throw $ IO.userError "unexpected" unless (← f 1 (← IO.mkRef 10)) == 2 do throw $ IO.userError "unexpected" def g (x y : Nat) (ref : IO.Ref (Nat × Nat)) : IO (Nat × Nat) := do let mut (x, y) := (x, y) if x == 0 then (x, y) ← ref.get IO.println ("x: " ++ toString x ++ ", y: " ++ toString y) return (x, y) def gTest : IO Unit := do unless (← g 2 1 (← IO.mkRef (10, 20))) == (2, 1) do throw $ IO.userError "unexpected" unless (← g 0 1 (← IO.mkRef (10, 20))) == (10, 20) do throw $ IO.userError "unexpected" return () #eval gTest macro "ret!" x:term : doElem => `(return $x) def f1 (x : Nat) : Nat := do let mut x := x if x == 0 then ret! 100 x := x + 1 ret! x theorem ex1 : f1 0 = 100 := rfl theorem ex2 : f1 1 = 2 := rfl theorem ex3 : f1 3 = 4 := rfl syntax "inc!" ident : doElem macro_rules | `(doElem| inc! $x) => `(doElem| $x:ident := $x + 1) def f2 (x : Nat) : Nat := do let mut x := x inc! x ret! x theorem ex4 : f2 0 = 1 := rfl theorem ex5 : f2 3 = 4 := rfl
ffc592f0e74ca9999c85a27121042f0b32d7301c
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/linear_algebra/affine_space/finite_dimensional.lean
a8d31e4dd08ab99373eb4e668b6c6a984eefa362
[ "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
29,371
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers -/ import linear_algebra.affine_space.independent import linear_algebra.finite_dimensional /-! # Finite-dimensional subspaces of affine spaces. This file provides a few results relating to finite-dimensional subspaces of affine spaces. ## Main definitions * `collinear` defines collinear sets of points as those that span a subspace of dimension at most 1. -/ noncomputable theory open_locale big_operators affine section affine_space' variables (k : Type*) {V : Type*} {P : Type*} variables {ι : Type*} include V open affine_subspace finite_dimensional module variables [division_ring k] [add_comm_group V] [module k V] [affine_space V P] /-- The `vector_span` of a finite set is finite-dimensional. -/ lemma finite_dimensional_vector_span_of_finite {s : set P} (h : set.finite s) : finite_dimensional k (vector_span k s) := span_of_finite k $ h.vsub h /-- The `vector_span` of a family indexed by a `fintype` is finite-dimensional. -/ instance finite_dimensional_vector_span_range [_root_.finite ι] (p : ι → P) : finite_dimensional k (vector_span k (set.range p)) := finite_dimensional_vector_span_of_finite k (set.finite_range _) /-- The `vector_span` of a subset of a family indexed by a `fintype` is finite-dimensional. -/ instance finite_dimensional_vector_span_image_of_finite [_root_.finite ι] (p : ι → P) (s : set ι) : finite_dimensional k (vector_span k (p '' s)) := finite_dimensional_vector_span_of_finite k (set.to_finite _) /-- The direction of the affine span of a finite set is finite-dimensional. -/ lemma finite_dimensional_direction_affine_span_of_finite {s : set P} (h : set.finite s) : finite_dimensional k (affine_span k s).direction := (direction_affine_span k s).symm ▸ finite_dimensional_vector_span_of_finite k h /-- The direction of the affine span of a family indexed by a `fintype` is finite-dimensional. -/ instance finite_dimensional_direction_affine_span_range [_root_.finite ι] (p : ι → P) : finite_dimensional k (affine_span k (set.range p)).direction := finite_dimensional_direction_affine_span_of_finite k (set.finite_range _) /-- The direction of the affine span of a subset of a family indexed by a `fintype` is finite-dimensional. -/ instance finite_dimensional_direction_affine_span_image_of_finite [_root_.finite ι] (p : ι → P) (s : set ι) : finite_dimensional k (affine_span k (p '' s)).direction := finite_dimensional_direction_affine_span_of_finite k (set.to_finite _) /-- An affine-independent family of points in a finite-dimensional affine space is finite. -/ lemma finite_of_fin_dim_affine_independent [finite_dimensional k V] {p : ι → P} (hi : affine_independent k p) : _root_.finite ι := begin nontriviality ι, inhabit ι, rw affine_independent_iff_linear_independent_vsub k p default at hi, letI : is_noetherian k V := is_noetherian.iff_fg.2 infer_instance, exact (set.finite_singleton default).finite_of_compl (set.finite_coe_iff.1 hi.finite_of_is_noetherian) end /-- An affine-independent subset of a finite-dimensional affine space is finite. -/ lemma finite_set_of_fin_dim_affine_independent [finite_dimensional k V] {s : set ι} {f : s → P} (hi : affine_independent k f) : s.finite := @set.to_finite _ s (finite_of_fin_dim_affine_independent k hi) open_locale classical variables {k} /-- The `vector_span` of a finite subset of an affinely independent family has dimension one less than its cardinality. -/ lemma affine_independent.finrank_vector_span_image_finset {p : ι → P} (hi : affine_independent k p) {s : finset ι} {n : ℕ} (hc : finset.card s = n + 1) : finrank k (vector_span k (s.image p : set P)) = n := begin have hi' := hi.range.mono (set.image_subset_range p ↑s), have hc' : (s.image p).card = n + 1, { rwa s.card_image_of_injective hi.injective }, have hn : (s.image p).nonempty, { simp [hc', ←finset.card_pos] }, rcases hn with ⟨p₁, hp₁⟩, have hp₁' : p₁ ∈ p '' s := by simpa using hp₁, rw [affine_independent_set_iff_linear_independent_vsub k hp₁', ← finset.coe_singleton, ← finset.coe_image, ← finset.coe_sdiff, finset.sdiff_singleton_eq_erase, ← finset.coe_image] at hi', have hc : (finset.image (λ (p : P), p -ᵥ p₁) ((finset.image p s).erase p₁)).card = n, { rw [finset.card_image_of_injective _ (vsub_left_injective _), finset.card_erase_of_mem hp₁], exact nat.pred_eq_of_eq_succ hc' }, rwa [vector_span_eq_span_vsub_finset_right_ne k hp₁, finrank_span_finset_eq_card, hc] end /-- The `vector_span` of a finite affinely independent family has dimension one less than its cardinality. -/ lemma affine_independent.finrank_vector_span [fintype ι] {p : ι → P} (hi : affine_independent k p) {n : ℕ} (hc : fintype.card ι = n + 1) : finrank k (vector_span k (set.range p)) = n := begin rw ← finset.card_univ at hc, rw [← set.image_univ, ← finset.coe_univ, ← finset.coe_image], exact hi.finrank_vector_span_image_finset hc end /-- The `vector_span` of a finite affinely independent family whose cardinality is one more than that of the finite-dimensional space is `⊤`. -/ lemma affine_independent.vector_span_eq_top_of_card_eq_finrank_add_one [finite_dimensional k V] [fintype ι] {p : ι → P} (hi : affine_independent k p) (hc : fintype.card ι = finrank k V + 1) : vector_span k (set.range p) = ⊤ := eq_top_of_finrank_eq $ hi.finrank_vector_span hc variables (k) /-- The `vector_span` of `n + 1` points in an indexed family has dimension at most `n`. -/ lemma finrank_vector_span_image_finset_le (p : ι → P) (s : finset ι) {n : ℕ} (hc : finset.card s = n + 1) : finrank k (vector_span k (s.image p : set P)) ≤ n := begin have hn : (s.image p).nonempty, { rw [finset.nonempty.image_iff, ← finset.card_pos, hc], apply nat.succ_pos }, rcases hn with ⟨p₁, hp₁⟩, rw [vector_span_eq_span_vsub_finset_right_ne k hp₁], refine le_trans (finrank_span_finset_le_card (((s.image p).erase p₁).image (λ p, p -ᵥ p₁))) _, rw [finset.card_image_of_injective _ (vsub_left_injective p₁), finset.card_erase_of_mem hp₁, tsub_le_iff_right, ← hc], apply finset.card_image_le end /-- The `vector_span` of an indexed family of `n + 1` points has dimension at most `n`. -/ lemma finrank_vector_span_range_le [fintype ι] (p : ι → P) {n : ℕ} (hc : fintype.card ι = n + 1) : finrank k (vector_span k (set.range p)) ≤ n := begin rw [←set.image_univ, ←finset.coe_univ, ← finset.coe_image], rw ←finset.card_univ at hc, exact finrank_vector_span_image_finset_le _ _ _ hc end /-- `n + 1` points are affinely independent if and only if their `vector_span` has dimension `n`. -/ lemma affine_independent_iff_finrank_vector_span_eq [fintype ι] (p : ι → P) {n : ℕ} (hc : fintype.card ι = n + 1) : affine_independent k p ↔ finrank k (vector_span k (set.range p)) = n := begin have hn : nonempty ι, by simp [←fintype.card_pos_iff, hc], cases hn with i₁, rw [affine_independent_iff_linear_independent_vsub _ _ i₁, linear_independent_iff_card_eq_finrank_span, eq_comm, vector_span_range_eq_span_range_vsub_right_ne k p i₁], congr', rw ←finset.card_univ at hc, rw fintype.subtype_card, simp [finset.filter_ne', finset.card_erase_of_mem, hc] end /-- `n + 1` points are affinely independent if and only if their `vector_span` has dimension at least `n`. -/ lemma affine_independent_iff_le_finrank_vector_span [fintype ι] (p : ι → P) {n : ℕ} (hc : fintype.card ι = n + 1) : affine_independent k p ↔ n ≤ finrank k (vector_span k (set.range p)) := begin rw affine_independent_iff_finrank_vector_span_eq k p hc, split, { rintro rfl, refl }, { exact λ hle, le_antisymm (finrank_vector_span_range_le k p hc) hle } end /-- `n + 2` points are affinely independent if and only if their `vector_span` does not have dimension at most `n`. -/ lemma affine_independent_iff_not_finrank_vector_span_le [fintype ι] (p : ι → P) {n : ℕ} (hc : fintype.card ι = n + 2) : affine_independent k p ↔ ¬ finrank k (vector_span k (set.range p)) ≤ n := by rw [affine_independent_iff_le_finrank_vector_span k p hc, ←nat.lt_iff_add_one_le, lt_iff_not_ge] /-- `n + 2` points have a `vector_span` with dimension at most `n` if and only if they are not affinely independent. -/ lemma finrank_vector_span_le_iff_not_affine_independent [fintype ι] (p : ι → P) {n : ℕ} (hc : fintype.card ι = n + 2) : finrank k (vector_span k (set.range p)) ≤ n ↔ ¬ affine_independent k p := (not_iff_comm.1 (affine_independent_iff_not_finrank_vector_span_le k p hc).symm).symm variables {k} /-- If the `vector_span` of a finite subset of an affinely independent family lies in a submodule with dimension one less than its cardinality, it equals that submodule. -/ lemma affine_independent.vector_span_image_finset_eq_of_le_of_card_eq_finrank_add_one {p : ι → P} (hi : affine_independent k p) {s : finset ι} {sm : submodule k V} [finite_dimensional k sm] (hle : vector_span k (s.image p : set P) ≤ sm) (hc : finset.card s = finrank k sm + 1) : vector_span k (s.image p : set P) = sm := eq_of_le_of_finrank_eq hle $ hi.finrank_vector_span_image_finset hc /-- If the `vector_span` of a finite affinely independent family lies in a submodule with dimension one less than its cardinality, it equals that submodule. -/ lemma affine_independent.vector_span_eq_of_le_of_card_eq_finrank_add_one [fintype ι] {p : ι → P} (hi : affine_independent k p) {sm : submodule k V} [finite_dimensional k sm] (hle : vector_span k (set.range p) ≤ sm) (hc : fintype.card ι = finrank k sm + 1) : vector_span k (set.range p) = sm := eq_of_le_of_finrank_eq hle $ hi.finrank_vector_span hc /-- If the `affine_span` of a finite subset of an affinely independent family lies in an affine subspace whose direction has dimension one less than its cardinality, it equals that subspace. -/ lemma affine_independent.affine_span_image_finset_eq_of_le_of_card_eq_finrank_add_one {p : ι → P} (hi : affine_independent k p) {s : finset ι} {sp : affine_subspace k P} [finite_dimensional k sp.direction] (hle : affine_span k (s.image p : set P) ≤ sp) (hc : finset.card s = finrank k sp.direction + 1) : affine_span k (s.image p : set P) = sp := begin have hn : (s.image p).nonempty, { rw [finset.nonempty.image_iff, ← finset.card_pos, hc], apply nat.succ_pos }, refine eq_of_direction_eq_of_nonempty_of_le _ ((affine_span_nonempty k _).2 hn) hle, have hd := direction_le hle, rw direction_affine_span at ⊢ hd, exact hi.vector_span_image_finset_eq_of_le_of_card_eq_finrank_add_one hd hc end /-- If the `affine_span` of a finite affinely independent family lies in an affine subspace whose direction has dimension one less than its cardinality, it equals that subspace. -/ lemma affine_independent.affine_span_eq_of_le_of_card_eq_finrank_add_one [fintype ι] {p : ι → P} (hi : affine_independent k p) {sp : affine_subspace k P} [finite_dimensional k sp.direction] (hle : affine_span k (set.range p) ≤ sp) (hc : fintype.card ι = finrank k sp.direction + 1) : affine_span k (set.range p) = sp := begin rw ←finset.card_univ at hc, rw [←set.image_univ, ←finset.coe_univ, ← finset.coe_image] at ⊢ hle, exact hi.affine_span_image_finset_eq_of_le_of_card_eq_finrank_add_one hle hc end /-- The `affine_span` of a finite affinely independent family is `⊤` iff the family's cardinality is one more than that of the finite-dimensional space. -/ lemma affine_independent.affine_span_eq_top_iff_card_eq_finrank_add_one [finite_dimensional k V] [fintype ι] {p : ι → P} (hi : affine_independent k p) : affine_span k (set.range p) = ⊤ ↔ fintype.card ι = finrank k V + 1 := begin split, { intros h_tot, let n := fintype.card ι - 1, have hn : fintype.card ι = n + 1, { exact (nat.succ_pred_eq_of_pos (card_pos_of_affine_span_eq_top k V P h_tot)).symm, }, rw [hn, ← finrank_top, ← (vector_span_eq_top_of_affine_span_eq_top k V P) h_tot, ← hi.finrank_vector_span hn], }, { intros hc, rw [← finrank_top, ← direction_top k V P] at hc, exact hi.affine_span_eq_of_le_of_card_eq_finrank_add_one le_top hc, }, end /-- The `vector_span` of adding a point to a finite-dimensional subspace is finite-dimensional. -/ instance finite_dimensional_vector_span_insert (s : affine_subspace k P) [finite_dimensional k s.direction] (p : P) : finite_dimensional k (vector_span k (insert p (s : set P))) := begin rw [←direction_affine_span, ←affine_span_insert_affine_span], rcases (s : set P).eq_empty_or_nonempty with hs | ⟨p₀, hp₀⟩, { rw coe_eq_bot_iff at hs, rw [hs, bot_coe, span_empty, bot_coe, direction_affine_span], convert finite_dimensional_bot _ _; simp }, { rw [affine_span_coe, direction_affine_span_insert hp₀], apply_instance } end /-- The direction of the affine span of adding a point to a finite-dimensional subspace is finite-dimensional. -/ instance finite_dimensional_direction_affine_span_insert (s : affine_subspace k P) [finite_dimensional k s.direction] (p : P) : finite_dimensional k (affine_span k (insert p (s : set P))).direction := (direction_affine_span k (insert p (s : set P))).symm ▸ finite_dimensional_vector_span_insert s p variables (k) /-- The `vector_span` of adding a point to a set with a finite-dimensional `vector_span` is finite-dimensional. -/ instance finite_dimensional_vector_span_insert_set (s : set P) [finite_dimensional k (vector_span k s)] (p : P) : finite_dimensional k (vector_span k (insert p s)) := begin haveI : finite_dimensional k (affine_span k s).direction := (direction_affine_span k s).symm ▸ infer_instance, rw [←direction_affine_span, ←affine_span_insert_affine_span, direction_affine_span], exact finite_dimensional_vector_span_insert (affine_span k s) p end /-- A set of points is collinear if their `vector_span` has dimension at most `1`. -/ def collinear (s : set P) : Prop := module.rank k (vector_span k s) ≤ 1 /-- The definition of `collinear`. -/ lemma collinear_iff_dim_le_one (s : set P) : collinear k s ↔ module.rank k (vector_span k s) ≤ 1 := iff.rfl variables {k} /-- A set of points, whose `vector_span` is finite-dimensional, is collinear if and only if their `vector_span` has dimension at most `1`. -/ lemma collinear_iff_finrank_le_one {s : set P} [finite_dimensional k (vector_span k s)] : collinear k s ↔ finrank k (vector_span k s) ≤ 1 := begin have h := collinear_iff_dim_le_one k s, rw ←finrank_eq_dim at h, exact_mod_cast h end alias collinear_iff_finrank_le_one ↔ collinear.finrank_le_one _ /-- A subset of a collinear set is collinear. -/ lemma collinear.subset {s₁ s₂ : set P} (hs : s₁ ⊆ s₂) (h : collinear k s₂) : collinear k s₁ := (dim_le_of_submodule (vector_span k s₁) (vector_span k s₂) (vector_span_mono k hs)).trans h /-- The `vector_span` of collinear points is finite-dimensional. -/ lemma collinear.finite_dimensional_vector_span {s : set P} (h : collinear k s) : finite_dimensional k (vector_span k s) := is_noetherian.iff_fg.1 (is_noetherian.iff_dim_lt_aleph_0.2 (lt_of_le_of_lt h cardinal.one_lt_aleph_0)) /-- The direction of the affine span of collinear points is finite-dimensional. -/ lemma collinear.finite_dimensional_direction_affine_span {s : set P} (h : collinear k s) : finite_dimensional k (affine_span k s).direction := (direction_affine_span k s).symm ▸ h.finite_dimensional_vector_span variables (k P) /-- The empty set is collinear. -/ lemma collinear_empty : collinear k (∅ : set P) := begin rw [collinear_iff_dim_le_one, vector_span_empty], simp end variables {P} /-- A single point is collinear. -/ lemma collinear_singleton (p : P) : collinear k ({p} : set P) := begin rw [collinear_iff_dim_le_one, vector_span_singleton], simp end variables {k} /-- Given a point `p₀` in a set of points, that set is collinear if and only if the points can all be expressed as multiples of the same vector, added to `p₀`. -/ lemma collinear_iff_of_mem {s : set P} {p₀ : P} (h : p₀ ∈ s) : collinear k s ↔ ∃ v : V, ∀ p ∈ s, ∃ r : k, p = r • v +ᵥ p₀ := begin simp_rw [collinear_iff_dim_le_one, dim_submodule_le_one_iff', submodule.le_span_singleton_iff], split, { rintro ⟨v₀, hv⟩, use v₀, intros p hp, obtain ⟨r, hr⟩ := hv (p -ᵥ p₀) (vsub_mem_vector_span k hp h), use r, rw eq_vadd_iff_vsub_eq, exact hr.symm }, { rintro ⟨v, hp₀v⟩, use v, intros w hw, have hs : vector_span k s ≤ k ∙ v, { rw [vector_span_eq_span_vsub_set_right k h, submodule.span_le, set.subset_def], intros x hx, rw [set_like.mem_coe, submodule.mem_span_singleton], rw set.mem_image at hx, rcases hx with ⟨p, hp, rfl⟩, rcases hp₀v p hp with ⟨r, rfl⟩, use r, simp }, have hw' := set_like.le_def.1 hs hw, rwa submodule.mem_span_singleton at hw' } end /-- A set of points is collinear if and only if they can all be expressed as multiples of the same vector, added to the same base point. -/ lemma collinear_iff_exists_forall_eq_smul_vadd (s : set P) : collinear k s ↔ ∃ (p₀ : P) (v : V), ∀ p ∈ s, ∃ r : k, p = r • v +ᵥ p₀ := begin rcases set.eq_empty_or_nonempty s with rfl | ⟨⟨p₁, hp₁⟩⟩, { simp [collinear_empty] }, { rw collinear_iff_of_mem hp₁, split, { exact λ h, ⟨p₁, h⟩ }, { rintros ⟨p, v, hv⟩, use v, intros p₂ hp₂, rcases hv p₂ hp₂ with ⟨r, rfl⟩, rcases hv p₁ hp₁ with ⟨r₁, rfl⟩, use r - r₁, simp [vadd_vadd, ←add_smul] } } end variables (k) /-- Two points are collinear. -/ lemma collinear_pair (p₁ p₂ : P) : collinear k ({p₁, p₂} : set P) := begin rw collinear_iff_exists_forall_eq_smul_vadd, use [p₁, p₂ -ᵥ p₁], intros p hp, rw [set.mem_insert_iff, set.mem_singleton_iff] at hp, cases hp, { use 0, simp [hp] }, { use 1, simp [hp] } end variables {k} /-- Three points are affinely independent if and only if they are not collinear. -/ lemma affine_independent_iff_not_collinear {p : fin 3 → P} : affine_independent k p ↔ ¬ collinear k (set.range p) := by rw [collinear_iff_finrank_le_one, affine_independent_iff_not_finrank_vector_span_le k p (fintype.card_fin 3)] /-- Three points are collinear if and only if they are not affinely independent. -/ lemma collinear_iff_not_affine_independent {p : fin 3 → P} : collinear k (set.range p) ↔ ¬ affine_independent k p := by rw [collinear_iff_finrank_le_one, finrank_vector_span_le_iff_not_affine_independent k p (fintype.card_fin 3)] /-- Three points are affinely independent if and only if they are not collinear. -/ lemma affine_independent_iff_not_collinear_set {p₁ p₂ p₃ : P} : affine_independent k ![p₁, p₂, p₃] ↔ ¬collinear k ({p₁, p₂, p₃} : set P) := by simp [affine_independent_iff_not_collinear, -set.union_singleton] /-- Three points are collinear if and only if they are not affinely independent. -/ lemma collinear_iff_not_affine_independent_set {p₁ p₂ p₃ : P} : collinear k ({p₁, p₂, p₃} : set P) ↔ ¬affine_independent k ![p₁, p₂, p₃] := affine_independent_iff_not_collinear_set.not_left.symm /-- Three points are affinely independent if and only if they are not collinear. -/ lemma affine_independent_iff_not_collinear_of_ne {p : fin 3 → P} {i₁ i₂ i₃ : fin 3} (h₁₂ : i₁ ≠ i₂) (h₁₃ : i₁ ≠ i₃) (h₂₃ : i₂ ≠ i₃) : affine_independent k p ↔ ¬collinear k ({p i₁, p i₂, p i₃} : set P) := begin have hu : (finset.univ : finset (fin 3)) = {i₁, i₂, i₃}, by dec_trivial!, rw [affine_independent_iff_not_collinear, ←set.image_univ, ←finset.coe_univ, hu, finset.coe_insert, finset.coe_insert, finset.coe_singleton, set.image_insert_eq, set.image_pair] end /-- Three points are collinear if and only if they are not affinely independent. -/ lemma collinear_iff_not_affine_independent_of_ne {p : fin 3 → P} {i₁ i₂ i₃ : fin 3} (h₁₂ : i₁ ≠ i₂) (h₁₃ : i₁ ≠ i₃) (h₂₃ : i₂ ≠ i₃) : collinear k ({p i₁, p i₂, p i₃} : set P) ↔ ¬affine_independent k p:= (affine_independent_iff_not_collinear_of_ne h₁₂ h₁₃ h₂₃).not_left.symm /-- If three points are not collinear, the first and second are different. -/ lemma ne₁₂_of_not_collinear {p₁ p₂ p₃ : P} (h : ¬collinear k ({p₁, p₂, p₃} : set P)) : p₁ ≠ p₂ := by { rintro rfl, simpa [collinear_pair] using h } /-- If three points are not collinear, the first and third are different. -/ lemma ne₁₃_of_not_collinear {p₁ p₂ p₃ : P} (h : ¬collinear k ({p₁, p₂, p₃} : set P)) : p₁ ≠ p₃ := by { rintro rfl, simpa [collinear_pair] using h } /-- If three points are not collinear, the second and third are different. -/ lemma ne₂₃_of_not_collinear {p₁ p₂ p₃ : P} (h : ¬collinear k ({p₁, p₂, p₃} : set P)) : p₂ ≠ p₃ := by { rintro rfl, simpa [collinear_pair] using h } /-- A point in a collinear set of points lies in the affine span of any two distinct points of that set. -/ lemma collinear.mem_affine_span_of_mem_of_ne {s : set P} (h : collinear k s) {p₁ p₂ p₃ : P} (hp₁ : p₁ ∈ s) (hp₂ : p₂ ∈ s) (hp₃ : p₃ ∈ s) (hp₁p₂ : p₁ ≠ p₂) : p₃ ∈ line[k, p₁, p₂] := begin rw collinear_iff_of_mem hp₁ at h, rcases h with ⟨v, h⟩, rcases h p₂ hp₂ with ⟨r₂, rfl⟩, rcases h p₃ hp₃ with ⟨r₃, rfl⟩, rw vadd_left_mem_affine_span_pair, refine ⟨r₃ / r₂, _⟩, have h₂ : r₂ ≠ 0, { rintro rfl, simpa using hp₁p₂ }, simp [smul_smul, h₂] end /-- The affine span of any two distinct points of a collinear set of points equals the affine span of the whole set. -/ lemma collinear.affine_span_eq_of_ne {s : set P} (h : collinear k s) {p₁ p₂ : P} (hp₁ : p₁ ∈ s) (hp₂ : p₂ ∈ s) (hp₁p₂ : p₁ ≠ p₂) : line[k, p₁, p₂] = affine_span k s := le_antisymm (affine_span_mono _ (set.insert_subset.2 ⟨hp₁, set.singleton_subset_iff.2 hp₂⟩)) (affine_span_le.2 (λ p hp, h.mem_affine_span_of_mem_of_ne hp₁ hp₂ hp hp₁p₂)) /-- Given a collinear set of points, and two distinct points `p₂` and `p₃` in it, a point `p₁` is collinear with the set if and only if it is collinear with `p₂` and `p₃`. -/ lemma collinear.collinear_insert_iff_of_ne {s : set P} (h : collinear k s) {p₁ p₂ p₃ : P} (hp₂ : p₂ ∈ s) (hp₃ : p₃ ∈ s) (hp₂p₃ : p₂ ≠ p₃) : collinear k (insert p₁ s) ↔ collinear k ({p₁, p₂, p₃} : set P) := begin have hv : vector_span k (insert p₁ s) = vector_span k ({p₁, p₂, p₃} : set P), { conv_lhs { rw [←direction_affine_span, ←affine_span_insert_affine_span] }, conv_rhs { rw [←direction_affine_span, ←affine_span_insert_affine_span] }, rw h.affine_span_eq_of_ne hp₂ hp₃ hp₂p₃ }, rw [collinear, collinear, hv] end /-- Adding a point in the affine span of a set does not change whether that set is collinear. -/ lemma collinear_insert_iff_of_mem_affine_span {s : set P} {p : P} (h : p ∈ affine_span k s) : collinear k (insert p s) ↔ collinear k s := by rw [collinear, collinear, vector_span_insert_eq_vector_span h] variables (k) /-- A set of points is coplanar if their `vector_span` has dimension at most `2`. -/ def coplanar (s : set P) : Prop := module.rank k (vector_span k s) ≤ 2 variables {k} /-- The `vector_span` of coplanar points is finite-dimensional. -/ lemma coplanar.finite_dimensional_vector_span {s : set P} (h : coplanar k s) : finite_dimensional k (vector_span k s) := begin refine is_noetherian.iff_fg.1 (is_noetherian.iff_dim_lt_aleph_0.2 (lt_of_le_of_lt h _)), simp, end /-- The direction of the affine span of coplanar points is finite-dimensional. -/ lemma coplanar.finite_dimensional_direction_affine_span {s : set P} (h : coplanar k s) : finite_dimensional k (affine_span k s).direction := (direction_affine_span k s).symm ▸ h.finite_dimensional_vector_span /-- A set of points, whose `vector_span` is finite-dimensional, is coplanar if and only if their `vector_span` has dimension at most `2`. -/ lemma coplanar_iff_finrank_le_two {s : set P} [finite_dimensional k (vector_span k s)] : coplanar k s ↔ finrank k (vector_span k s) ≤ 2 := begin have h : coplanar k s ↔ module.rank k (vector_span k s) ≤ 2 := iff.rfl, rw ←finrank_eq_dim at h, exact_mod_cast h end alias coplanar_iff_finrank_le_two ↔ coplanar.finrank_le_two _ /-- A subset of a coplanar set is coplanar. -/ lemma coplanar.subset {s₁ s₂ : set P} (hs : s₁ ⊆ s₂) (h : coplanar k s₂) : coplanar k s₁ := (dim_le_of_submodule (vector_span k s₁) (vector_span k s₂) (vector_span_mono k hs)).trans h /-- Collinear points are coplanar. -/ lemma collinear.coplanar {s : set P} (h : collinear k s) : coplanar k s := le_trans h one_le_two variables (k) (P) /-- The empty set is coplanar. -/ lemma coplanar_empty : coplanar k (∅ : set P) := (collinear_empty k P).coplanar variables {P} /-- A single point is coplanar. -/ lemma coplanar_singleton (p : P) : coplanar k ({p} : set P) := (collinear_singleton k p).coplanar /-- Two points are coplanar. -/ lemma coplanar_pair (p₁ p₂ : P) : coplanar k ({p₁, p₂} : set P) := (collinear_pair k p₁ p₂).coplanar variables {k} /-- Adding a point in the affine span of a set does not change whether that set is coplanar. -/ lemma coplanar_insert_iff_of_mem_affine_span {s : set P} {p : P} (h : p ∈ affine_span k s) : coplanar k (insert p s) ↔ coplanar k s := by rw [coplanar, coplanar, vector_span_insert_eq_vector_span h] end affine_space' section division_ring variables {k : Type*} {V : Type*} {P : Type*} include V open affine_subspace finite_dimensional module variables [division_ring k] [add_comm_group V] [module k V] [affine_space V P] /-- Adding a point to a finite-dimensional subspace increases the dimension by at most one. -/ lemma finrank_vector_span_insert_le (s : affine_subspace k P) (p : P) : finrank k (vector_span k (insert p (s : set P))) ≤ finrank k s.direction + 1 := begin by_cases hf : finite_dimensional k s.direction, swap, { have hf' : ¬finite_dimensional k (vector_span k (insert p (s : set P))), { intro h, have h' : s.direction ≤ vector_span k (insert p (s : set P)), { conv_lhs { rw [←affine_span_coe s, direction_affine_span] }, exact vector_span_mono k (set.subset_insert _ _) }, exactI hf (submodule.finite_dimensional_of_le h') }, rw [finrank_of_infinite_dimensional hf, finrank_of_infinite_dimensional hf', zero_add], exact zero_le_one }, haveI := hf, rw [←direction_affine_span, ←affine_span_insert_affine_span], rcases (s : set P).eq_empty_or_nonempty with hs | ⟨p₀, hp₀⟩, { rw coe_eq_bot_iff at hs, rw [hs, bot_coe, span_empty, bot_coe, direction_affine_span, direction_bot, finrank_bot, zero_add], convert zero_le_one' ℕ, rw ←finrank_bot k V, convert rfl; simp }, { rw [affine_span_coe, direction_affine_span_insert hp₀, add_comm], refine (submodule.dim_add_le_dim_add_dim _ _).trans (add_le_add_right _ _), refine finrank_le_one ⟨p -ᵥ p₀, submodule.mem_span_singleton_self _⟩ (λ v, _), have h := v.property, rw submodule.mem_span_singleton at h, rcases h with ⟨c, hc⟩, refine ⟨c, _⟩, ext, exact hc } end variables (k) /-- Adding a point to a set with a finite-dimensional span increases the dimension by at most one. -/ lemma finrank_vector_span_insert_le_set (s : set P) (p : P) : finrank k (vector_span k (insert p s)) ≤ finrank k (vector_span k s) + 1 := begin rw [←direction_affine_span, ←affine_span_insert_affine_span, direction_affine_span], refine (finrank_vector_span_insert_le _ _).trans (add_le_add_right _ _), rw direction_affine_span end variables {k} /-- Adding a point to a collinear set produces a coplanar set. -/ lemma collinear.coplanar_insert {s : set P} (h : collinear k s) (p : P) : coplanar k (insert p s) := begin haveI := h.finite_dimensional_vector_span, rw [coplanar_iff_finrank_le_two], exact (finrank_vector_span_insert_le_set k s p).trans (add_le_add_right h.finrank_le_one _) end /-- A set of points in a two-dimensional space is coplanar. -/ lemma coplanar_of_finrank_eq_two (s : set P) (h : finrank k V = 2) : coplanar k s := begin haveI := finite_dimensional_of_finrank_eq_succ h, rw [coplanar_iff_finrank_le_two, ←h], exact submodule.finrank_le _ end /-- A set of points in a two-dimensional space is coplanar. -/ lemma coplanar_of_fact_finrank_eq_two (s : set P) [h : fact (finrank k V = 2)] : coplanar k s := coplanar_of_finrank_eq_two s h.out variables (k) /-- Three points are coplanar. -/ lemma coplanar_triple (p₁ p₂ p₃ : P) : coplanar k ({p₁, p₂, p₃} : set P) := (collinear_pair k p₂ p₃).coplanar_insert p₁ end division_ring
6df78a4b3b461e9d43a2f601daf50356b04ba876
08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4
/src/Lean/Compiler/IR/LLVMBindings.lean
8e6a2aad53a20208738d97cbda8bdbd81b48e17e
[ "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", "Apache-2.0", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
gebner/lean4
d51c4922640a52a6f7426536ea669ef18a1d9af5
8cd9ce06843c9d42d6d6dc43d3e81e3b49dfc20f
refs/heads/master
1,685,732,780,391
1,672,962,627,000
1,673,459,398,000
373,307,283
0
0
Apache-2.0
1,691,316,730,000
1,622,669,271,000
Lean
UTF-8
Lean
false
false
14,502
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Siddharth Bhat -/ namespace LLVM /-! This file defines bindings for LLVM. The main mechanisms are to: - Mirror the values of C enumerations. - Create opaque values for LLVM's pointer based API - Write bindings that are `IO` based, which mutate the underlying in-memory data structures to build IR. -/ -- https://github.com/llvm/llvm-project/blob/c3e073bcbdc523b0f758d44a89a6333e38bff863/llvm/include/llvm-c/TargetMachine.h#L64 structure CodegenFileType where private mk :: val : UInt64 def CodegenFileType.AssemblyFile : CodegenFileType := { val := 0 } def CodegenFileType.ObjectFile : CodegenFileType := { val := 1 } -- https://github.com/llvm/llvm-project/blob/c3e073bcbdc523b0f758d44a89a6333e38bff863/llvm/include/llvm-c/Core.h#L290 structure IntPredicate where private mk :: val : UInt64 def IntPredicate.EQ : IntPredicate := { val := 32 } def IntPredicate.NE : IntPredicate := { val := IntPredicate.EQ.val + 1 } def IntPredicate.UGT : IntPredicate := { val := IntPredicate.NE.val + 1 } structure BasicBlock (ctx : Context) where private mk :: ptr : USize instance : Nonempty (BasicBlock ctx) := ⟨{ ptr := default }⟩ structure Builder (ctx : Context) where private mk :: ptr : USize instance : Nonempty (Builder ctx) := ⟨{ ptr := default }⟩ structure Context where private mk :: ptr : USize instance : Nonempty Context := ⟨{ ptr := default }⟩ structure LLVMType (ctx : Context) where private mk :: ptr : USize instance : Nonempty (LLVMType ctx) := ⟨{ ptr := default }⟩ structure MemoryBuffer (ctx : Context) where private mk :: ptr : USize instance : Nonempty (MemoryBuffer ctx) := ⟨{ ptr := default }⟩ structure Module (ctx : Context) where private mk :: ptr : USize instance : Nonempty (Module ctx) := ⟨{ ptr := default }⟩ structure PassManager (ctx : Context) where private mk :: ptr : USize instance : Nonempty (PassManager ctx) := ⟨{ ptr := default }⟩ structure PassManagerBuilder (ctx : Context) where private mk :: ptr : USize instance : Nonempty (PassManagerBuilder ctx) := ⟨{ ptr := default }⟩ structure Target (ctx : Context) where private mk :: ptr : USize instance : Nonempty (Target ctx) := ⟨{ ptr := default }⟩ structure TargetMachine (ctx : Context) where private mk :: ptr : USize instance : Nonempty (TargetMachine ctx) := ⟨{ ptr := default }⟩ structure Value (ctx : Context) where private mk :: ptr : USize instance : Nonempty (Value ctx) := ⟨{ ptr := default }⟩ @[extern "lean_llvm_initialize"] opaque llvmInitialize : BaseIO (Unit) @[extern "lean_llvm_create_context"] opaque createContext : BaseIO (Context) @[extern "lean_llvm_create_module"] opaque createModule (ctx : Context) (name : @&String) : BaseIO (Module ctx) @[extern "lean_llvm_module_to_string"] opaque moduleToString (m : Module ctx) : BaseIO String @[extern "lean_llvm_write_bitcode_to_file"] opaque writeBitcodeToFile (m : Module ctx) (path : @&String) : BaseIO Unit @[extern "lean_llvm_add_function"] opaque addFunction (m : Module ctx) (name : @&String) (type : LLVMType ctx) : BaseIO (Value ctx) @[extern "lean_llvm_get_named_function"] opaque getNamedFunction (m : Module ctx) (name : @&String) : BaseIO (Option (Value ctx)) @[extern "lean_llvm_add_global"] opaque addGlobal (m : Module ctx) (name : @&String) (type : LLVMType ctx) : BaseIO (Value ctx) @[extern "lean_llvm_get_named_global"] opaque getNamedGlobal (m : Module ctx) (name : @&String) : BaseIO (Option (Value ctx)) @[extern "lean_llvm_build_global_string"] opaque buildGlobalString (builder : Builder ctx) (value : @&String) (name : @&String := "") : BaseIO (Value ctx) @[extern "lean_llvm_set_initializer"] opaque setInitializer (glbl : Value ctx) (val : Value ctx) : BaseIO Unit @[extern "lean_llvm_function_type"] opaque functionType (retty : LLVMType ctx) (args : @&Array (LLVMType ctx)) (isVarArg : Bool := false) : BaseIO (LLVMType ctx) @[extern "lean_llvm_void_type_in_context"] opaque voidType (ctx : Context) : BaseIO (LLVMType ctx) @[extern "lean_llvm_int_type_in_context"] opaque intTypeInContext (ctx : Context) (width : UInt64) : BaseIO (LLVMType ctx) @[extern "lean_llvm_opaque_pointer_type_in_context"] opaque opaquePointerTypeInContext (ctx : Context) (addrspace: UInt64 := 0) : BaseIO (LLVMType ctx) @[extern "lean_llvm_float_type_in_context"] opaque floatTypeInContext (ctx : Context) : BaseIO (LLVMType ctx) @[extern "lean_llvm_double_type_in_context"] opaque doubleTypeInContext (ctx : Context) : BaseIO (LLVMType ctx) @[extern "lean_llvm_pointer_type"] opaque pointerType (elemty : LLVMType ctx) : BaseIO (LLVMType ctx) @[extern "lean_llvm_array_type"] opaque arrayType (elemty : LLVMType ctx) (nelem : UInt64) : BaseIO (LLVMType ctx) @[extern "lean_llvm_const_array"] opaque constArray (elemty : LLVMType ctx) (vals : @&Array (Value ctx)) : BaseIO (LLVMType ctx) -- `constString` provides a `String` as a constant array of element type `i8` @[extern "lean_llvm_const_string"] opaque constString (ctx : Context) (str : @&String) : BaseIO (Value ctx) @[extern "lean_llvm_const_pointer_null"] opaque constPointerNull (elemty : LLVMType ctx) : BaseIO (Value ctx) @[extern "lean_llvm_get_undef"] opaque getUndef (elemty : LLVMType ctx) : BaseIO (Value ctx) @[extern "lean_llvm_create_builder_in_context"] opaque createBuilderInContext (ctx : Context) : BaseIO (Builder ctx) @[extern "lean_llvm_append_basic_block_in_context"] opaque appendBasicBlockInContext (ctx : Context) (fn : Value ctx) (name : @&String) : BaseIO (BasicBlock ctx) @[extern "lean_llvm_position_builder_at_end"] opaque positionBuilderAtEnd (builder : Builder ctx) (bb : BasicBlock ctx) : BaseIO Unit @[extern "lean_llvm_build_call2"] opaque buildCall2 (builder : Builder ctx) (ty: LLVMType ctx) (fn : Value ctx) (args : @&Array (Value ctx)) (name : @&String := "") : BaseIO (Value ctx) @[extern "lean_llvm_set_tail_call"] opaque setTailCall (fn : Value ctx) (istail : Bool) : BaseIO Unit @[extern "lean_llvm_build_cond_br"] opaque buildCondBr (builder : Builder ctx) (if_ : Value ctx) (thenbb : BasicBlock ctx) (elsebb : BasicBlock ctx) : BaseIO (Value ctx) @[extern "lean_llvm_build_br"] opaque buildBr (builder : Builder ctx) (bb : BasicBlock ctx) : BaseIO (Value ctx) @[extern "lean_llvm_build_alloca"] opaque buildAlloca (builder : Builder ctx) (ty : LLVMType ctx) (name : @&String := "") : BaseIO (Value ctx) @[extern "lean_llvm_build_load2"] opaque buildLoad2 (builder : Builder ctx) (ty: LLVMType ctx) (val : Value ctx) (name : @&String := "") : BaseIO (Value ctx) @[extern "lean_llvm_build_store"] opaque buildStore (builder : Builder ctx) (val : Value ctx) (store_loc_ptr : Value ctx) : BaseIO Unit @[extern "lean_llvm_build_ret"] opaque buildRet (builder : Builder ctx) (val : Value ctx) : BaseIO (Value ctx) @[extern "lean_llvm_build_unreachable"] opaque buildUnreachable (builder : Builder ctx) : BaseIO (Value ctx) @[extern "lean_llvm_build_gep2"] opaque buildGEP2 (builder : Builder ctx) (ty: LLVMType ctx) (base : Value ctx) (ixs : @&Array (Value ctx)) (name : @&String := "") : BaseIO (Value ctx) @[extern "lean_llvm_build_inbounds_gep2"] opaque buildInBoundsGEP2 (builder : Builder ctx) (ty: LLVMType ctx) (base : Value ctx) (ixs : @&Array (Value ctx)) (name : @&String := "") : BaseIO (Value ctx) @[extern "lean_llvm_build_sext"] opaque buildSext (builder : Builder ctx) (val : Value ctx) (destTy : LLVMType ctx) (name : @&String := "") : BaseIO (Value ctx) @[extern "lean_llvm_build_zext"] opaque buildZext (builder : Builder ctx) (val : Value ctx) (destTy : LLVMType ctx) (name : @&String := "") : BaseIO (Value ctx) @[extern "lean_llvm_build_sext_or_trunc"] opaque buildSextOrTrunc (builder : Builder ctx) (val : Value ctx) (destTy : LLVMType ctx) (name : @&String := "") : BaseIO (Value ctx) @[extern "lean_llvm_build_switch"] opaque buildSwitch (builder : Builder ctx) (val : Value ctx) (elseBB : BasicBlock ctx) (numCasesHint : UInt64) : BaseIO (Value ctx) @[extern "lean_llvm_build_ptr_to_int"] opaque buildPtrToInt (builder : Builder ctx) (ptr : Value ctx) (destTy : LLVMType ctx) (name : @&String := "") : BaseIO (Value ctx) @[extern "lean_llvm_build_mul"] opaque buildMul (builder : Builder ctx) (x y : Value ctx) (name : @&String := "") : BaseIO (Value ctx) @[extern "lean_llvm_build_add"] opaque buildAdd (builder : Builder ctx) (x y : Value ctx) (name : @&String := "") : BaseIO (Value ctx) @[extern "lean_llvm_build_sub"] opaque buildSub (builder : Builder ctx) (x y : Value ctx) (name : @&String := "") : BaseIO (Value ctx) @[extern "lean_llvm_build_not"] opaque buildNot (builder : Builder ctx) (x : Value ctx) (name : @&String := "") : BaseIO (Value ctx) @[extern "lean_llvm_build_icmp"] opaque buildICmp (builder : Builder ctx) (predicate : IntPredicate) (x y : Value ctx) (name : @&String := "") : BaseIO (Value ctx) @[extern "lean_llvm_add_case"] opaque addCase (switch onVal : Value ctx) (destBB : BasicBlock ctx) : BaseIO Unit @[extern "lean_llvm_get_insert_block"] opaque getInsertBlock (builder : Builder ctx) : BaseIO (BasicBlock ctx) @[extern "lean_llvm_clear_insertion_position"] opaque clearInsertionPosition (builder : Builder ctx) : BaseIO Unit @[extern "lean_llvm_get_basic_block_parent"] opaque getBasicBlockParent (bb : BasicBlock ctx) : BaseIO (Value ctx) @[extern "lean_llvm_type_of"] opaque typeOf (val : Value ctx) : BaseIO (LLVMType ctx) @[extern "lean_llvm_const_int"] opaque constInt (intty : LLVMType ctx) (value : UInt64) (signExtend : @Bool := false) : BaseIO (Value ctx) @[extern "lean_llvm_print_module_to_string"] opaque printModuletoString (mod : Module ctx) : BaseIO (String) @[extern "lean_llvm_print_module_to_file"] opaque printModuletoFile (mod : Module ctx) (file : @&String) : BaseIO Unit @[extern "llvm_count_params"] opaque countParams (fn : Value ctx) : UInt64 @[extern "llvm_get_param"] opaque getParam (fn : Value ctx) (ix : UInt64) : BaseIO (Value ctx) @[extern "lean_llvm_create_memory_buffer_with_contents_of_file"] opaque createMemoryBufferWithContentsOfFile (path : @&String) : BaseIO (MemoryBuffer ctx) @[extern "lean_llvm_parse_bitcode"] opaque parseBitcode (ctx : Context) (membuf : MemoryBuffer ctx) : BaseIO (Module ctx) @[extern "lean_llvm_link_modules"] opaque linkModules (dest : Module ctx) (src : Module ctx) : BaseIO Unit @[extern "lean_llvm_get_default_target_triple"] opaque getDefaultTargetTriple : BaseIO String @[extern "lean_llvm_get_target_from_triple"] opaque getTargetFromTriple (triple : @&String) : BaseIO (Target ctx) @[extern "lean_llvm_create_target_machine"] opaque createTargetMachine (target : Target ctx) (tripleStr : @&String) (cpu : @&String) (features : @&String) : BaseIO (TargetMachine ctx) @[extern "lean_llvm_target_machine_emit_to_file"] opaque targetMachineEmitToFile (targetMachine : TargetMachine ctx) (module : Module ctx) (filepath : @&String) (codegenType : LLVM.CodegenFileType) : BaseIO Unit @[extern "lean_llvm_create_pass_manager"] opaque createPassManager : BaseIO (PassManager ctx) @[extern "lean_llvm_dispose_pass_manager"] opaque disposePassManager (pm : PassManager ctx) : BaseIO Unit @[extern "lean_llvm_run_pass_manager"] opaque runPassManager (pm : PassManager ctx) (mod : Module ctx): BaseIO Unit @[extern "lean_llvm_create_pass_manager_builder"] opaque createPassManagerBuilder : BaseIO (PassManagerBuilder ctx) @[extern "lean_llvm_dispose_pass_manager_builder"] opaque disposePassManagerBuilder (pmb : PassManagerBuilder ctx) : BaseIO Unit @[extern "lean_llvm_pass_manager_builder_set_opt_level"] opaque PassManagerBuilder.setOptLevel (pmb : PassManagerBuilder ctx) (optLevel : unsigned) : BaseIO Unit @[extern "lean_llvm_pass_manager_builder_populate_module_pass_manager"] opaque PassManagerBuilder.populateModulePassManager (pmb : PassManagerBuilder ctx) (pm : PassManager ctx): BaseIO Unit @[extern "lean_llvm_dispose_target_machine"] opaque disposeTargetMachine (tm : TargetMachine ctx) : BaseIO Unit @[extern "lean_llvm_dispose_module"] opaque disposeModule (m : Module ctx) : BaseIO Unit -- Helper to add a function if it does not exist, and to return the function handle if it does. def getOrAddFunction(m : Module ctx) (name : String) (type : LLVMType ctx) : BaseIO (Value ctx) := do match (← getNamedFunction m name) with | .some fn => return fn | .none => addFunction m name type def getOrAddGlobal(m : Module ctx) (name : String) (type : LLVMType ctx) : BaseIO (Value ctx) := do match (← getNamedGlobal m name) with | .some fn => return fn | .none => addGlobal m name type def i1Type (ctx : LLVM.Context) : BaseIO (LLVM.LLVMType ctx) := LLVM.intTypeInContext ctx 1 def i8Type (ctx : LLVM.Context) : BaseIO (LLVM.LLVMType ctx) := LLVM.intTypeInContext ctx 8 def i16Type (ctx : LLVM.Context) : BaseIO (LLVM.LLVMType ctx) := LLVM.intTypeInContext ctx 16 def i32Type (ctx : LLVM.Context) : BaseIO (LLVM.LLVMType ctx) := LLVM.intTypeInContext ctx 32 def i64Type (ctx : LLVM.Context) : BaseIO (LLVM.LLVMType ctx) := LLVM.intTypeInContext ctx 64 def voidPtrType (ctx : LLVM.Context) : BaseIO (LLVM.LLVMType ctx) := do LLVM.pointerType (← LLVM.intTypeInContext ctx 8) def i8PtrType (ctx : LLVM.Context) : BaseIO (LLVM.LLVMType ctx) := voidPtrType ctx def constTrue (ctx : Context) : BaseIO (Value ctx) := do constInt (← i1Type ctx) 1 (signExtend := false) def constFalse (ctx : Context) : BaseIO (Value ctx) := do constInt (← i1Type ctx) 0 (signExtend := false) def constInt' (ctx : Context) (width : UInt64) (value : UInt64) (signExtend : Bool := false) : BaseIO (Value ctx) := do constInt (← LLVM.intTypeInContext ctx width) value signExtend def constInt1 (ctx : Context) (value : UInt64) (signExtend : Bool := false) : BaseIO (Value ctx) := constInt' ctx 1 value signExtend def constInt8 (ctx : Context) (value : UInt64) (signExtend : Bool := false) : BaseIO (Value ctx) := constInt' ctx 8 value signExtend def constInt32 (ctx : Context) (value : UInt64) (signExtend : Bool := false) : BaseIO (Value ctx) := constInt' ctx 32 value signExtend def constInt64 (ctx : Context) (value : UInt64) (signExtend : Bool := false) : BaseIO (Value ctx) := constInt' ctx 64 value signExtend def constIntUnsigned (ctx : Context) (value : UInt64) (signExtend : Bool := false) : BaseIO (Value ctx) := constInt' ctx 64 value signExtend end LLVM
0abfb512109f4a7bfb9fe358f250c3237226cf01
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/reverts_tac.lean
33fb4b37315a730a40d148148738d7780fec9b49
[ "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
570
lean
import logic theorem tst {a b c : Prop} : a → b → c → a ∧ b := begin intros [Ha, Hb, Hc], reverts [Hb, Ha], intros [Hb2, Ha2], apply (and.intro Ha2 Hb2), end theorem foo1 {A : Type} (a b c : A) (P : A → Prop) : P a → a = b → P b := begin intros [Hp, Heq], reverts [Heq, Hp], intro Heq, eapply (eq.rec_on Heq), intro Pa, apply Pa end theorem foo2 {A : Type} (a b c : A) (P : A → Prop) : P a → a = b → P b := begin intros [Hp, Heq], apply (eq.rec_on Heq Hp) end reveal foo1 foo2 print definition foo1 print definition foo2
93425a63691de4e3f38b7820ea39002931dbd34f
d450724ba99f5b50b57d244eb41fef9f6789db81
/src/homework/hw1and2.lean
c68f4b494e220044a0f92d75b8c31dcdd973eef8
[]
no_license
jakekauff/CS2120F21
4f009adeb4ce4a148442b562196d66cc6c04530c
e69529ec6f5d47a554291c4241a3d8ec4fe8f5ad
refs/heads/main
1,693,841,880,030
1,637,604,848,000
1,637,604,848,000
399,946,698
0
0
null
null
null
null
UTF-8
Lean
false
false
6,247
lean
/- EQUALITY -/ /- #1 Suppose that x, y, z, and w are arbitrary objects of some type, T; and suppose further that we know (have proofs of the facts) that x = y, y = z, and w = z. Give a very, very short English proof of the conjecture that z = w. You can use not only the axioms of equality, but either of the theorems about properties of equality that we have proven. Hint: There's something about this question that makes it much easier to answer than it might at first appear. -/ /- #2 Give a formal statement of the conjecture (proposition) from #1 by filling in the "hole" in the following definition. The def is a keyword. The name you're binding to your proposition is prop_1. The type of the value is Prop (which is the type of all propositions in Lean). -/ def prop_1 : Prop := ∀ (T : Type) (x y z w : T), x = y → y = z → w = z → z = w /- #3 (extra credit) Give a formal proof of the proposition from #2 by filling in the hole in this next definition. Hint: Use Lean's versions of the axioms and basic theorems concerning equality. They are, again, called eq.refl, eq.subst, eq.symm, eq.trans. -/ theorem prop_1_proof : prop_1 := begin assume T x y z w, assume xy yz zw, exact eq.symm zw, end /- FOR ALL: ∀. -/ /- #4 Give a very brief explanation in English of the introduction rule for ∀. For example, suppose you need to prove (∀ x, P x); what do you do? (I'm being a little informal in leaving out the type of X.) -/ /- Assume you;re given an arbitrary but specific x, show that it satisfies P; because the choice was arbirtrary, P must be true of any x (you could have picked any of them!)-/ /- #5 Suppose you have a proof, let's call it pf, of the proposition, (∀ x, P x), and you need a proof of P t, for some particular t. Write an expression then uses the elimination rule for ∀ to get such a proof. Complete the answer by replacing the underscores in the following expression: ( _ _ ). -/ axioms (Ball : Type) (blue : Ball → Prop) (allBallsBlue : ∀ (b : Ball), blue b) (tomsBall : Ball) theorem tomsBallIsBlue : blue tomsBall := allBallsBlue tomsBall #check allBallsBlue example : ∀ (P Q : Prop), P ∧ Q → Q ∧ P := begin assume P Q h, have p : P := h.left, have q : Q := h.right, exact and.intro q p, end /- IMPLIES: → In the "code" that follows, we define two predicates, each taking one natural number as an argument. We call them ev and odd. When applied to any value, n, ev yields the proposition that n is even (n % 2 = 0), while odd yields the proposition that n is odd (n % 2 = 1). -/ def ev (n : ℕ) := n % 2 = 0 def odd (n : ℕ) := n % 2 = 1 /- #6 Write a formal version of the proposition that, for *any* natural number n, *if* n is even, *then* n + 1 is odd. Give your answer by filling the hole in the following definition. Hint: put parenthesis around "n + 1" in your answer. -/ def successor_of_even_is_odd : Prop := ∀ (n : ℕ), ev n → odd (n + 1) /- #7 Suppose that "its_raining" and "the_streets_are_wet" are propositions. (We formalize these assumptions as axioms in what follows. Then give a formal definition of the (larger) proposition, "if it's raining out then the streets are wet") by filling in the hole -/ axioms (raining streets_wet : Prop) axiom if_raining_then_streets_wet : raining → streets_wet /- #9 Now suppose that in addition, its_raining is true, and we have a proof of it, pf_its_raining. Again, we again give you this assumption formally as an axiom below. Finish the formal proof that the streets must be wet. Hint: here you are asked to use the elimination rule for →. -/ axiom pf_raining : raining example : streets_wet := if_raining_then_streets_wet pf_raining /- AND: ∧ -/ /- #10 In our last class, we proved that "∧ is *commutative*." That is, for any given *propositions*, P and Q, (P ∧ Q) → (Q ∧ P). The way we proved it was to *assume* that we're given such a P, Q, and proof, pq, of (P ∧ Q) -- applying the introduction rules for ∀ and →). In this context, we *use* the proof, pq, to derive separate proofs, let's call them p, a proof of P, and q, a proof of Q. With these in hand, we then apply the introduction rule for ∧ to put them back together into a proof of (Q ∧ P). We give you a formal version of this proof as a reminder, next. -/ theorem and_commutative : ∀ (P Q : Prop), P ∧ Q → Q ∧ P := begin assume P Q pq, apply and.intro _ _, exact (and.elim_right pq), exact (and.elim_left pq), end /- Your task now is to prove the theorem, "∧ is *associative*." What this means is that for arbitrary propositions, P, Q, and R, if (P ∧ (Q ∧ R)) is true, then ((P ∧ Q) ∧ R) is true, *and vice versa*. You just need to prove it in the first direction. Hint, if you have a proof, p_qr, of (P ∧ (Q ∧ R)), then the application of and.elim_left will give you a proof of P, and and.elim_right will give you a proof of (Q ∧ R). To help you along, we give you the first part of the proof, including an example of a new Lean tactic called have, which allows you to give a name to a new value in the middle of a proof script. -/ theorem and_associative : ∀ (P Q R : Prop), (P ∧ (Q ∧ R)) → ((P ∧ Q) ∧ R) := begin intros P Q R h, have p : P := and.elim_left h, have q : Q := (and.elim_right h).left end /- #11 Give an English language proof of the preceding theorem. Do it by finishing off the following partial "proof explanation." Proof. We assume that P, Q, and R are arbitrary but specific propositions, and that we have a proof, let's call it p_qr, of (P ∧ (Q ∧ R)) [by application of ∧ and → introduction.] What now remains to be proved is ((P ∧ Q) ∧ R). We can construct a proof of this proposition by applying _____ to a proof of (P ∧ Q) and a proof of R. What remains, then, is to obtain these proofs. But this is easily done by the application of ____ to ____. QED. -/ /- Note that Lean includes versions of these theorems (and many, many, many others) in its extensive library of formalized maths, as the following check commands reveal. Note the difference in naming relative to the definitions we give in this file. -/ #check @and.comm #check @and.assoc
a736eba7cf8561c3ffeb8b6e7e36b3becdad2b9d
59b654f4ee2fef898a3487dc03554a569051b63a
/src/old/twcube_graph.lean
484ca29bc3d42b482d9a725bb7bf24975a6bc6cd
[]
no_license
gunpinyo/twisted_cube_formalisation
180c9157478b66ec2b11ca47c8ff998a3e978a88
f78206ac495e84bd43a9b820fa10b6c94722e0ec
refs/heads/master
1,624,501,222,992
1,607,081,624,000
1,607,081,624,000
166,885,106
0
0
null
null
null
null
UTF-8
Lean
false
false
586
lean
import generic_cube_graph def twprism_graph : graph → graph := prism_graph tt def twcube_graph (n : ℕ) : graph := cube_graph tt n def twcube_graph_alt (n : ℕ) : graph := cube_graph_alt tt n section variable n : ℕ def twcg_to_twcg' : graph_cat.hom (twcube_graph n) (twcube_graph_alt n) := cg_to_cg' tt n def twcg'_to_twcg : graph_cat.hom (twcube_graph_alt n) (twcube_graph n) := cg'_to_cg tt n def twcg_iso_twcg' : graph_cat.iso (twcube_graph n) (twcube_graph_alt n) := cg_iso_cg' tt n end def twcube_graph_cat : category := cube_graph_cat tt
a2e4fb229f79313bbc0591ea1d45ff21a464de53
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/noncomp_thm.lean
d31bf82c759af8b6d97a16a3a217f4345d68d9a6
[ "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
44
lean
noncomputable theorem foo : true := trivial
2b1621db410daf28a02454e2c3b32b7f071cc0e2
43390109ab88557e6090f3245c47479c123ee500
/src/M3P14/Arithmetic_functions/mobius.lean
70c3c41d9fcfcf76eca7f8ce2def6797a6d14747
[ "Apache-2.0" ]
permissive
Ja1941/xena-UROP-2018
41f0956519f94d56b8bf6834a8d39473f4923200
b111fb87f343cf79eca3b886f99ee15c1dd9884b
refs/heads/master
1,662,355,955,139
1,590,577,325,000
1,590,577,325,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,233
lean
import data.nat.prime algebra.big_operators M3P14.Arithmetic_functions.sum_over_divisors open nat -- mobius function -- taken from M3P14 sheet 1 def square_free_int (n : ℕ) := ∀ p : ℕ, prime p ∧ (p ∣ n → ¬ (p^2 ∣ n)) -- number of prime divisors of n, not counting multiplicities def primes_div_nodup (n : ℕ) := n.factors.erase_dup.length local notation `ω` := primes_div_nodup --#eval ω 30 --number of prime divisors of n, counting multiplicities def primes_div_dup (n : ℕ) := n.factors.length local notation `Ω` := primes_div_dup --#eval Ω 300 local attribute [instance] classical.prop_decidable noncomputable def mobius (n : ℕ) : int := if square_free_int n ∧ (2 ∣ ω n) then 1 else if square_free_int n ∧ ¬(2 ∣ ω n) then -1 else 0 local notation `μ` := mobius theorem mob_mul (m n : ℕ) : μ (m*n) = (μ m ) * (μ n) := sorry lemma non_coprime (m n : ℕ) : (gcd m n) > 1 → μ (m * n) = 0 := sorry --theorem mob_sum (n d : ℕ) (hp : n ≠ 1) (hq: d ∣ n) : divisor_sum mobius n = 0 := sorry --def mertens_func (n k : ℕ) := sum k μ n --theorem mobius_inv (m n : ℕ) (f : ℕ → ℕ) (g : ℕ → ℕ) : (g n = sum f d) → (f n = sum (μ d) * g (n / d) ) := sorry
828e24f1a7837a4b2d10df241dea5535e292da10
8e381650eb2c1c5361be64ff97e47d956bf2ab9f
/src/Kenny/sites/lattice.lean
aded717b3dd5c7a31f8ea658aa50da388254e104
[]
no_license
alreadydone/lean-scheme
04c51ab08eca7ccf6c21344d45d202780fa667af
52d7624f57415eea27ed4dfa916cd94189221a1c
refs/heads/master
1,599,418,221,423
1,562,248,559,000
1,562,248,559,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,624
lean
import Kenny.sites.basic order.complete_lattice universes u v namespace lattice class Sup_lattice (X : Type u) extends lattice X, has_Sup X := (le_Sup : ∀ {s : set X} {a : X}, a ∈ s → a ≤ Sup s) (Sup_le : ∀ {s : set X} {a : X}, (∀ (b : X), b ∈ s → b ≤ a) → Sup s ≤ a) class Sup_distrib_lattice (X : Type u) extends Sup_lattice X := (inf_Sup_le {} : ∀ {x : X} {s : set X}, x ⊓ lattice.Sup s ≤ lattice.Sup ((⊓) x '' s)) section Sup_lattice instance complete_lattice.to_Sup_lattice {X : Type u} [complete_lattice X] : Sup_lattice X := { .. (infer_instance : complete_lattice X) } variables {X : Type u} [Sup_lattice X] theorem le_Sup' {s : set X} {a : X} : a ∈ s → a ≤ Sup s := Sup_lattice.le_Sup theorem Sup_le' {s : set X} {a : X} : (∀ (b : X), b ∈ s → b ≤ a) → Sup s ≤ a := Sup_lattice.Sup_le theorem Sup_singleton' (x : X) : Sup {x} = x := le_antisymm (Sup_le' $ λ b hb, set.eq_of_mem_singleton hb ▸ le_refl _) $ le_Sup' $ set.mem_singleton x end Sup_lattice section Sup_discrete_lattice instance complete_distrib_lattice.to_Sup_distrib_lattice {X : Type u} [complete_distrib_lattice X] : Sup_distrib_lattice X := { inf_Sup_le := λ x s, by rw [inf_Sup_eq, Sup_image], .. (infer_instance : complete_distrib_lattice X) } variables {X : Type u} [Sup_distrib_lattice X] theorem inf_Sup {x : X} {s : set X} : x ⊓ lattice.Sup s = lattice.Sup ((⊓) x '' s) := le_antisymm Sup_distrib_lattice.inf_Sup_le $ Sup_le' $ λ b ⟨c, hcs, hxcb⟩, hxcb ▸ inf_le_inf (le_refl x) (le_Sup' hcs) end Sup_discrete_lattice end lattice namespace category_theory open lattice variables {X : Type u} class is_univalent (X : Type u) [category.{v} X] : Prop := (univalent : ∀ x y : X, ∀ e : x ≅ y, x = y) theorem eq_of_iso [category.{v} X] [is_univalent X] {x y : X} (e : x ≅ y) : x = y := is_univalent.univalent x y e instance is_univalent_partial_order [partial_order X] : is_univalent X := ⟨λ x y e, le_antisymm e.1.1.1 e.2.1.1⟩ instance semilattice_inf.has_pullback [semilattice_inf X] : has_pullback X := λ F, { cone := { X := F.obj pullback_diagram.base_left ⊓ F.obj pullback_diagram.base_right, π := { app := λ p, pullback_diagram.rec_on p ⟨⟨inf_le_left⟩⟩ ⟨⟨inf_le_right⟩⟩ ⟨⟨le_trans inf_le_left (F.map pullback_diagram.hom.to_target_left).down.down⟩⟩, naturality' := by intros; ext } }, is_limit := { lift := λ c, ⟨⟨le_inf (c.π.app pullback_diagram.base_left).down.down (c.π.app pullback_diagram.base_right).down.down⟩⟩, fac' := by intros; ext, uniq' := by intros; ext } } instance Sup_lattice.has_site [Sup_distrib_lattice X] : has_site X := { cov := λ U, { c | U ≤ Sup (sigma.fst '' c) }, iso_mem := λ U V e, show U ≤ _, by rw [set.image_singleton, Sup_singleton']; exact e.2.1.1, comp_mem := λ U S HS F HF, le_trans HS $ Sup_le' $ λ x hx, let ⟨m, hmS, hmx⟩ := hx in hmx ▸ le_trans (HF m hmS) (Sup_le' $ λ y hy, let ⟨n, hnFS, hny⟩ := hy in le_Sup' ⟨⟨n.1, ⟨⟨le_trans n.2.1.1 m.2.1.1⟩⟩⟩, ⟨m, hmS, n, hnFS, rfl⟩, hny⟩), pullback_mem := λ U S HS V f, calc V ≤ V ⊓ Sup (sigma.fst '' S) : le_inf (le_refl V) (le_trans f.1.1 HS) ... = Sup ((⊓) V '' (sigma.fst '' S)) : inf_Sup ... = Sup ((⊓) V ∘ sigma.fst '' S) : congr_arg Sup (set.image_comp _ _ S).symm ... ≤ Sup (sigma.fst '' {m | ∃ t ∈ S, (⟨_, pullback.fst f t.2⟩ : Σ W, W ⟶ V) = m}) : Sup_le' (λ b ⟨c, hcs, hb⟩, le_Sup' ⟨⟨V ⊓ c.1, ⟨⟨inf_le_left⟩⟩⟩, ⟨c, hcs, rfl⟩, hb⟩) } end category_theory
ee2adab43b7a81267fa1937903bf81f66f214ffa
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/ring_theory/algebra_operations.lean
e727f0f9fd93d3c0f4a66bb3cad23a903ed8353a
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
8,918
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Multiplication and division of submodules of an algebra. -/ import ring_theory.algebra import ring_theory.ideals import algebra.pointwise universes u v open algebra local attribute [instance] set.pointwise_mul_semiring namespace submodule variables {R : Type u} [comm_ring R] section ring variables {A : Type v} [ring A] [algebra R A] variables (S T : set A) {M N P Q : submodule R A} {m n : A} instance : has_one (submodule R A) := ⟨submodule.map (of_id R A).to_linear_map (⊤ : ideal R)⟩ theorem one_eq_map_top : (1 : submodule R A) = submodule.map (of_id R A).to_linear_map (⊤ : ideal R) := rfl theorem one_eq_span : (1 : submodule R A) = span R {1} := begin apply submodule.ext, intro a, erw [mem_map, mem_span_singleton], apply exists_congr, intro r, simpa [smul_def], end theorem one_le : (1 : submodule R A) ≤ P ↔ (1 : A) ∈ P := by simpa only [one_eq_span, span_le, set.singleton_subset_iff] instance : has_mul (submodule R A) := ⟨λ M N, ⨆ s : M, N.map $ algebra.lmul R A s.1⟩ theorem mul_mem_mul (hm : m ∈ M) (hn : n ∈ N) : m * n ∈ M * N := (le_supr _ ⟨m, hm⟩ : _ ≤ M * N) ⟨n, hn, rfl⟩ theorem mul_le : M * N ≤ P ↔ ∀ (m ∈ M) (n ∈ N), m * n ∈ P := ⟨λ H m hm n hn, H $ mul_mem_mul hm hn, λ H, supr_le $ λ ⟨m, hm⟩, map_le_iff_le_comap.2 $ λ n hn, H m hm n hn⟩ @[elab_as_eliminator] protected theorem mul_induction_on {C : A → Prop} {r : A} (hr : r ∈ M * N) (hm : ∀ (m ∈ M) (n ∈ N), C (m * n)) (h0 : C 0) (ha : ∀ x y, C x → C y → C (x + y)) (hs : ∀ (r : R) x, C x → C (r • x)) : C r := (@mul_le _ _ _ _ _ _ _ ⟨C, h0, ha, hs⟩).2 hm hr variables R theorem span_mul_span : span R S * span R T = span R (S * T) := begin apply le_antisymm, { rw mul_le, intros a ha b hb, apply span_induction ha, work_on_goal 0 { intros, apply span_induction hb, work_on_goal 0 { intros, exact subset_span ⟨_, ‹_›, _, ‹_›, rfl⟩ } }, all_goals { intros, simp only [mul_zero, zero_mul, zero_mem, left_distrib, right_distrib, mul_smul_comm, smul_mul_assoc], try {apply add_mem _ _ _}, try {apply smul_mem _ _ _} }, assumption' }, { rw span_le, rintros _ ⟨a, ha, b, hb, rfl⟩, exact mul_mem_mul (subset_span ha) (subset_span hb) } end variables {R} variables (M N P Q) protected theorem mul_assoc : (M * N) * P = M * (N * P) := le_antisymm (mul_le.2 $ λ mn hmn p hp, suffices M * N ≤ (M * (N * P)).comap ((algebra.lmul R A).flip p), from this hmn, mul_le.2 $ λ m hm n hn, show m * n * p ∈ M * (N * P), from (mul_assoc m n p).symm ▸ mul_mem_mul hm (mul_mem_mul hn hp)) (mul_le.2 $ λ m hm np hnp, suffices N * P ≤ (M * N * P).comap (algebra.lmul R A m), from this hnp, mul_le.2 $ λ n hn p hp, show m * (n * p) ∈ M * N * P, from mul_assoc m n p ▸ mul_mem_mul (mul_mem_mul hm hn) hp) @[simp] theorem mul_bot : M * ⊥ = ⊥ := eq_bot_iff.2 $ mul_le.2 $ λ m hm n hn, by rw [submodule.mem_bot] at hn ⊢; rw [hn, mul_zero] @[simp] theorem bot_mul : ⊥ * M = ⊥ := eq_bot_iff.2 $ mul_le.2 $ λ m hm n hn, by rw [submodule.mem_bot] at hm ⊢; rw [hm, zero_mul] @[simp] protected theorem one_mul : (1 : submodule R A) * M = M := by { conv_lhs { rw [one_eq_span, ← span_eq M] }, erw [span_mul_span, one_mul, span_eq] } @[simp] protected theorem mul_one : M * 1 = M := by { conv_lhs { rw [one_eq_span, ← span_eq M] }, erw [span_mul_span, mul_one, span_eq] } variables {M N P Q} @[mono] theorem mul_le_mul (hmp : M ≤ P) (hnq : N ≤ Q) : M * N ≤ P * Q := mul_le.2 $ λ m hm n hn, mul_mem_mul (hmp hm) (hnq hn) theorem mul_le_mul_left (h : M ≤ N) : M * P ≤ N * P := mul_le_mul h (le_refl P) theorem mul_le_mul_right (h : N ≤ P) : M * N ≤ M * P := mul_le_mul (le_refl M) h variables (M N P) theorem mul_sup : M * (N ⊔ P) = M * N ⊔ M * P := le_antisymm (mul_le.2 $ λ m hm np hnp, let ⟨n, hn, p, hp, hnp⟩ := mem_sup.1 hnp in mem_sup.2 ⟨_, mul_mem_mul hm hn, _, mul_mem_mul hm hp, hnp ▸ (mul_add m n p).symm⟩) (sup_le (mul_le_mul_right le_sup_left) (mul_le_mul_right le_sup_right)) theorem sup_mul : (M ⊔ N) * P = M * P ⊔ N * P := le_antisymm (mul_le.2 $ λ mn hmn p hp, let ⟨m, hm, n, hn, hmn⟩ := mem_sup.1 hmn in mem_sup.2 ⟨_, mul_mem_mul hm hp, _, mul_mem_mul hn hp, hmn ▸ (add_mul m n p).symm⟩) (sup_le (mul_le_mul_left le_sup_left) (mul_le_mul_left le_sup_right)) lemma mul_subset_mul : (↑M : set A) * (↑N : set A) ⊆ (↑(M * N) : set A) := begin rintros _ ⟨i, hi, j, hj, rfl⟩, exact mul_mem_mul hi hj end variables {M N P} instance : semiring (submodule R A) := { one_mul := submodule.one_mul, mul_one := submodule.mul_one, mul_assoc := submodule.mul_assoc, zero_mul := bot_mul, mul_zero := mul_bot, left_distrib := mul_sup, right_distrib := sup_mul, ..submodule.add_comm_monoid, ..submodule.has_one, ..submodule.has_mul } variables (M) lemma pow_subset_pow {n : ℕ} : (↑M : set A)^n ⊆ ↑(M^n : submodule R A) := begin induction n with n ih, { erw [pow_zero, pow_zero, set.singleton_subset_iff], rw [mem_coe, ← one_le], exact le_refl _ }, { rw [pow_succ, pow_succ], refine set.subset.trans (set.pointwise_mul_subset_mul (set.subset.refl _) ih) _, apply mul_subset_mul } end instance span.is_semiring_hom : is_semiring_hom (submodule.span R : set A → submodule R A) := { map_zero := span_empty, map_one := show _ = map _ ⊤, by erw [← ideal.span_singleton_one, ← span_image, set.image_singleton, alg_hom.map_one]; refl, map_add := span_union, map_mul := λ s t, by erw [span_mul_span, set.pointwise_mul_eq_image] } end ring section comm_ring variables {A : Type v} [comm_ring A] [algebra R A] variables {M N : submodule R A} {m n : A} theorem mul_mem_mul_rev (hm : m ∈ M) (hn : n ∈ N) : n * m ∈ M * N := mul_comm m n ▸ mul_mem_mul hm hn variables (M N) protected theorem mul_comm : M * N = N * M := le_antisymm (mul_le.2 $ λ r hrm s hsn, mul_mem_mul_rev hsn hrm) (mul_le.2 $ λ r hrn s hsm, mul_mem_mul_rev hsm hrn) instance : comm_semiring (submodule R A) := { mul_comm := submodule.mul_comm, .. submodule.semiring } variables (R A) instance semimodule_set : semimodule (set A) (submodule R A) := { smul := λ s P, span R s * P, smul_add := λ _ _ _, mul_add _ _ _, add_smul := λ s t P, show span R (s ⊔ t) * P = _, by { erw [span_union, right_distrib] }, mul_smul := λ s t P, show _ = _ * (_ * _), by { rw [← mul_assoc, span_mul_span, set.pointwise_mul_eq_image] }, one_smul := λ P, show span R {(1 : A)} * P = _, by { conv_lhs {erw ← span_eq P}, erw [span_mul_span, one_mul, span_eq] }, zero_smul := λ P, show span R ∅ * P = ⊥, by erw [span_empty, bot_mul], smul_zero := λ _, mul_bot _ } variables {R A} lemma smul_def {s : set A} {P : submodule R A} : s • P = span R s * P := rfl lemma smul_le_smul {s t : set A} {M N : submodule R A} (h₁ : s ≤ t) (h₂ : M ≤ N) : s • M ≤ t • N := mul_le_mul (span_mono h₁) h₂ lemma smul_singleton (a : A) (M : submodule R A) : ({a} : set A) • M = M.map (lmul_left _ _ a) := begin conv_lhs {rw ← span_eq M}, change span _ _ * span _ _ = _, rw [span_mul_span], apply le_antisymm, { rw span_le, rintros _ ⟨b, hb, m, hm, rfl⟩, erw [mem_map, set.mem_singleton_iff.mp hb], exact ⟨m, hm, rfl⟩ }, { rintros _ ⟨m, hm, rfl⟩, exact subset_span ⟨a, set.mem_singleton a, m, hm, rfl⟩ } end section quotient local attribute [instance] set.smul_set_action /-- The elements of `I / J` are the `x` such that `x • J ⊆ I`. In fact, we define `x ∈ I / J` to be `∀ y ∈ J, x * y ∈ I` (see `mem_div_iff_forall_mul_mem`), which is equivalent to `x • J ⊆ I` (see `mem_div_iff_smul_subset`), but nicer to use in proofs. This is the general form of the ideal quotient, traditionally written $I : J$. -/ instance : has_div (submodule R A) := ⟨ λ I J, { carrier := { x | ∀ y ∈ J, x * y ∈ I }, zero := λ y hy, by { rw zero_mul, apply submodule.zero }, add := λ a b ha hb y hy, by { rw add_mul, exact submodule.add _ (ha _ hy) (hb _ hy) }, smul := λ r x hx y hy, by { rw algebra.smul_mul_assoc, exact submodule.smul _ _ (hx _ hy) } } ⟩ lemma mem_div_iff_forall_mul_mem {x : A} {I J : submodule R A} : x ∈ I / J ↔ ∀ y ∈ J, x * y ∈ I := iff.refl _ lemma mem_div_iff_smul_subset {x : A} {I J : submodule R A} : x ∈ I / J ↔ x • (J : set A) ⊆ I := ⟨ λ h y ⟨y', hy', y_eq_xy'⟩, by { rw y_eq_xy', apply h, assumption }, λ h y hy, h (set.smul_mem_smul_set _ hy)⟩ lemma le_div_iff {I J K : submodule R A} : I ≤ J / K ↔ ∀ (x ∈ I) (z ∈ K), x * z ∈ J := iff.refl _ end quotient end comm_ring end submodule
52ad7798749fb96067d1d5f209385ebef0f39008
7cef822f3b952965621309e88eadf618da0c8ae9
/src/tactic/ring.lean
9dbdd0dd188ae07fcfc36b711d266246ecf961c3
[ "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
21,105
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Evaluate expressions in the language of commutative (semi)rings. Based on <http://www.cs.ru.nl/~freek/courses/tt-2014/read/10.1.1.61.3041.pdf> . -/ import algebra.group_power tactic.norm_num import tactic.converter.interactive namespace tactic namespace ring def horner {α} [comm_semiring α] (a x : α) (n : ℕ) (b : α) := a * x ^ n + b meta structure cache := (α : expr) (univ : level) (comm_semiring_inst : expr) (red : transparency) meta def ring_m (α : Type) : Type := reader_t cache (state_t (buffer expr) tactic) α meta instance : monad ring_m := by dunfold ring_m; apply_instance meta instance : alternative ring_m := by dunfold ring_m; apply_instance meta def get_cache : ring_m cache := reader_t.read meta def get_atom (n : ℕ) : ring_m expr := reader_t.lift $ (λ es : buffer expr, es.read' n) <$> state_t.get meta def get_transparency : ring_m transparency := cache.red <$> get_cache meta def add_atom (e : expr) : ring_m ℕ := do red ← get_transparency, reader_t.lift ⟨λ es, (do n ← es.iterate failed (λ n e' t, t <|> (is_def_eq e e' red $> n)), return (n, es)) <|> return (es.size, es.push_back e)⟩ meta def lift {α} (m : tactic α) : ring_m α := reader_t.lift (state_t.lift m) meta def ring_m.run (red : transparency) (e : expr) {α} (m : ring_m α) : tactic α := do α ← infer_type e, c ← mk_app ``comm_semiring [α] >>= mk_instance, u ← mk_meta_univ, infer_type α >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, prod.fst <$> state_t.run (reader_t.run m ⟨α, u, c, red⟩) mk_buffer meta def cache.cs_app (c : cache) (n : name) : list expr → expr := (@expr.const tt n [c.univ] c.α c.comm_semiring_inst).mk_app meta def ring_m.mk_app (n inst : name) (l : list expr) : ring_m expr := do c ← get_cache, m ← lift $ mk_instance ((expr.const inst [c.univ] : expr) c.α), return $ (@expr.const tt n [c.univ] c.α m).mk_app l meta inductive horner_expr : Type | const (e : expr) : horner_expr | xadd (e : expr) (a : horner_expr) (x : expr × ℕ) (n : expr × ℕ) (b : horner_expr) : horner_expr meta def horner_expr.e : horner_expr → expr | (horner_expr.const e) := e | (horner_expr.xadd e _ _ _ _) := e meta instance : has_coe horner_expr expr := ⟨horner_expr.e⟩ meta def horner_expr.xadd' (c : cache) (a : horner_expr) (x : expr × ℕ) (n : expr × ℕ) (b : horner_expr) : horner_expr := horner_expr.xadd (c.cs_app ``horner [a, x.1, n.1, b]) a x n b open horner_expr meta def horner_expr.to_string : horner_expr → string | (const e) := to_string e | (xadd e a x (_, n) b) := "(" ++ a.to_string ++ ") * (" ++ to_string x ++ ")^" ++ to_string n ++ " + " ++ b.to_string meta def horner_expr.pp : horner_expr → tactic format | (const e) := pp e | (xadd e a x (_, n) b) := do pa ← a.pp, pb ← b.pp, px ← pp x, return $ "(" ++ pa ++ ") * (" ++ px ++ ")^" ++ to_string n ++ " + " ++ pb meta instance : has_to_tactic_format horner_expr := ⟨horner_expr.pp⟩ meta def horner_expr.refl_conv (e : horner_expr) : ring_m (horner_expr × expr) := do p ← lift $ mk_eq_refl e, return (e, p) theorem zero_horner {α} [comm_semiring α] (x n b) : @horner α _ 0 x n b = b := by simp [horner] theorem horner_horner {α} [comm_semiring α] (a₁ x n₁ n₂ b n') (h : n₁ + n₂ = n') : @horner α _ (horner a₁ x n₁ 0) x n₂ b = horner a₁ x n' b := by simp [h.symm, horner, pow_add, mul_assoc] meta def eval_horner : horner_expr → expr × ℕ → expr × ℕ → horner_expr → ring_m (horner_expr × expr) | ha@(const a) x n b := do c ← get_cache, if a.to_nat = some 0 then return (b, c.cs_app ``zero_horner [x.1, n.1, b]) else (xadd' c ha x n b).refl_conv | ha@(xadd a a₁ x₁ n₁ b₁) x n b := do c ← get_cache, if x₁.2 = x.2 ∧ b₁.e.to_nat = some 0 then do (n', h) ← lift $ mk_app ``has_add.add [n₁.1, n.1] >>= norm_num, return (xadd' c a₁ x (n', n₁.2 + n.2) b, c.cs_app ``horner_horner [a₁, x.1, n₁.1, n.1, b, n', h]) else (xadd' c ha x n b).refl_conv theorem const_add_horner {α} [comm_semiring α] (k a x n b b') (h : k + b = b') : k + @horner α _ a x n b = horner a x n b' := by simp [h.symm, horner] theorem horner_add_const {α} [comm_semiring α] (a x n b k b') (h : b + k = b') : @horner α _ a x n b + k = horner a x n b' := by simp [h.symm, horner] theorem horner_add_horner_lt {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ b₂ k a' b') (h₁ : n₁ + k = n₂) (h₂ : (a₁ + horner a₂ x k 0 : α) = a') (h₃ : b₁ + b₂ = b') : @horner α _ a₁ x n₁ b₁ + horner a₂ x n₂ b₂ = horner a' x n₁ b' := by simp [h₂.symm, h₃.symm, h₁.symm, horner, pow_add, mul_add, mul_comm, mul_left_comm] theorem horner_add_horner_gt {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ b₂ k a' b') (h₁ : n₂ + k = n₁) (h₂ : (horner a₁ x k 0 + a₂ : α) = a') (h₃ : b₁ + b₂ = b') : @horner α _ a₁ x n₁ b₁ + horner a₂ x n₂ b₂ = horner a' x n₂ b' := by simp [h₂.symm, h₃.symm, h₁.symm, horner, pow_add, mul_add, mul_comm, mul_left_comm] -- set_option trace.class_instances true -- set_option class.instance_max_depth 128 theorem horner_add_horner_eq {α} [comm_semiring α] (a₁ x n b₁ a₂ b₂ a' b' t) (h₁ : a₁ + a₂ = a') (h₂ : b₁ + b₂ = b') (h₃ : horner a' x n b' = t) : @horner α _ a₁ x n b₁ + horner a₂ x n b₂ = t := by simp [h₃.symm, h₂.symm, h₁.symm, horner, add_mul, mul_comm] meta def eval_add : horner_expr → horner_expr → ring_m (horner_expr × expr) | (const e₁) (const e₂) := do (e, p) ← lift $ mk_app ``has_add.add [e₁, e₂] >>= norm_num, return (const e, p) | he₁@(const e₁) he₂@(xadd e₂ a x n b) := do c ← get_cache, if e₁.to_nat = some 0 then do p ← lift $ mk_app ``zero_add [e₂], return (he₂, p) else do (b', h) ← eval_add he₁ b, return (xadd' c a x n b', c.cs_app ``const_add_horner [e₁, a, x.1, n.1, b, b', h]) | he₁@(xadd e₁ a x n b) he₂@(const e₂) := do c ← get_cache, if e₂.to_nat = some 0 then do p ← lift $ mk_app ``add_zero [e₁], return (he₁, p) else do (b', h) ← eval_add b he₂, return (xadd' c a x n b', c.cs_app ``horner_add_const [a, x.1, n.1, b, e₂, b', h]) | he₁@(xadd e₁ a₁ x₁ n₁ b₁) he₂@(xadd e₂ a₂ x₂ n₂ b₂) := do c ← get_cache, if x₁.2 < x₂.2 then do (b', h) ← eval_add b₁ he₂, return (xadd' c a₁ x₁ n₁ b', c.cs_app ``horner_add_const [a₁, x₁.1, n₁.1, b₁, e₂, b', h]) else if x₁.2 ≠ x₂.2 then do (b', h) ← eval_add he₁ b₂, return (xadd' c a₂ x₂ n₂ b', c.cs_app ``const_add_horner [e₁, a₂, x₂.1, n₂.1, b₂, b', h]) else if n₁.2 < n₂.2 then do let k := n₂.2 - n₁.2, ek ← lift $ expr.of_nat (expr.const `nat []) k, (_, h₁) ← lift $ mk_app ``has_add.add [n₁.1, ek] >>= norm_num, α0 ← lift $ expr.of_nat c.α 0, (a', h₂) ← eval_add a₁ (xadd' c a₂ x₁ (ek, k) (const α0)), (b', h₃) ← eval_add b₁ b₂, return (xadd' c a' x₁ n₁ b', c.cs_app ``horner_add_horner_lt [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, b₂, ek, a', b', h₁, h₂, h₃]) else if n₁.2 ≠ n₂.2 then do let k := n₁.2 - n₂.2, ek ← lift $ expr.of_nat (expr.const `nat []) k, (_, h₁) ← lift $ mk_app ``has_add.add [n₂.1, ek] >>= norm_num, α0 ← lift $ expr.of_nat c.α 0, (a', h₂) ← eval_add (xadd' c a₁ x₁ (ek, k) (const α0)) a₂, (b', h₃) ← eval_add b₁ b₂, return (xadd' c a' x₁ n₂ b', c.cs_app ``horner_add_horner_gt [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, b₂, ek, a', b', h₁, h₂, h₃]) else do (a', h₁) ← eval_add a₁ a₂, (b', h₂) ← eval_add b₁ b₂, (t, h₃) ← eval_horner a' x₁ n₁ b', return (t, c.cs_app ``horner_add_horner_eq [a₁, x₁.1, n₁.1, b₁, a₂, b₂, a', b', t, h₁, h₂, h₃]) theorem horner_neg {α} [comm_ring α] (a x n b a' b') (h₁ : -a = a') (h₂ : -b = b') : -@horner α _ a x n b = horner a' x n b' := by simp [h₂.symm, h₁.symm, horner] meta def eval_neg : horner_expr → ring_m (horner_expr × expr) | (const e) := do (e', p) ← lift $ mk_app ``has_neg.neg [e] >>= norm_num, return (const e', p) | (xadd e a x n b) := do c ← get_cache, (a', h₁) ← eval_neg a, (b', h₂) ← eval_neg b, p ← ring_m.mk_app ``horner_neg ``comm_ring [a, x.1, n.1, b, a', b', h₁, h₂], return (xadd' c a' x n b', p) theorem horner_const_mul {α} [comm_semiring α] (c a x n b a' b') (h₁ : c * a = a') (h₂ : c * b = b') : c * @horner α _ a x n b = horner a' x n b' := by simp [h₂.symm, h₁.symm, horner, mul_add, mul_assoc] theorem horner_mul_const {α} [comm_semiring α] (a x n b c a' b') (h₁ : a * c = a') (h₂ : b * c = b') : @horner α _ a x n b * c = horner a' x n b' := by simp [h₂.symm, h₁.symm, horner, add_mul, mul_right_comm] meta def eval_const_mul (k : expr) : horner_expr → ring_m (horner_expr × expr) | (const e) := do (e', p) ← lift $ mk_app ``has_mul.mul [k, e] >>= norm_num, return (const e', p) | (xadd e a x n b) := do c ← get_cache, (a', h₁) ← eval_const_mul a, (b', h₂) ← eval_const_mul b, return (xadd' c a' x n b', c.cs_app ``horner_const_mul [k, a, x.1, n.1, b, a', b', h₁, h₂]) theorem horner_mul_horner_zero {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ aa t) (h₁ : @horner α _ a₁ x n₁ b₁ * a₂ = aa) (h₂ : horner aa x n₂ 0 = t) : horner a₁ x n₁ b₁ * horner a₂ x n₂ 0 = t := by rw [← h₂, ← h₁]; simp [horner, mul_add, mul_comm, mul_left_comm, mul_assoc] theorem horner_mul_horner {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ b₂ aa haa ab bb t) (h₁ : @horner α _ a₁ x n₁ b₁ * a₂ = aa) (h₂ : horner aa x n₂ 0 = haa) (h₃ : a₁ * b₂ = ab) (h₄ : b₁ * b₂ = bb) (H : haa + horner ab x n₁ bb = t) : horner a₁ x n₁ b₁ * horner a₂ x n₂ b₂ = t := by rw [← H, ← h₂, ← h₁, ← h₃, ← h₄]; simp [horner, mul_add, mul_comm, mul_left_comm, mul_assoc] meta def eval_mul : horner_expr → horner_expr → ring_m (horner_expr × expr) | (const e₁) (const e₂) := do (e', p) ← lift $ mk_app ``has_mul.mul [e₁, e₂] >>= norm_num, return (const e', p) | (const e₁) e₂ := match e₁.to_nat with | (some 0) := do c ← get_cache, α0 ← lift $ expr.of_nat c.α 0, p ← lift $ mk_app ``zero_mul [e₂], return (const α0, p) | (some 1) := do p ← lift $ mk_app ``one_mul [e₂], return (e₂, p) | _ := eval_const_mul e₁ e₂ end | e₁ he₂@(const e₂) := do p₁ ← lift $ mk_app ``mul_comm [e₁, e₂], (e', p₂) ← eval_mul he₂ e₁, p ← lift $ mk_eq_trans p₁ p₂, return (e', p) | he₁@(xadd e₁ a₁ x₁ n₁ b₁) he₂@(xadd e₂ a₂ x₂ n₂ b₂) := do c ← get_cache, if x₁.2 < x₂.2 then do (a', h₁) ← eval_mul a₁ he₂, (b', h₂) ← eval_mul b₁ he₂, return (xadd' c a' x₁ n₁ b', c.cs_app ``horner_mul_const [a₁, x₁.1, n₁.1, b₁, e₂, a', b', h₁, h₂]) else if x₁.2 ≠ x₂.2 then do (a', h₁) ← eval_mul he₁ a₂, (b', h₂) ← eval_mul he₁ b₂, return (xadd' c a' x₂ n₂ b', c.cs_app ``horner_const_mul [e₁, a₂, x₂.1, n₂.1, b₂, a', b', h₁, h₂]) else do (aa, h₁) ← eval_mul he₁ a₂, α0 ← lift $ expr.of_nat c.α 0, (haa, h₂) ← eval_horner aa x₁ n₂ (const α0), if b₂.e.to_nat = some 0 then return (haa, c.cs_app ``horner_mul_horner_zero [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, aa, haa, h₁, h₂]) else do (ab, h₃) ← eval_mul a₁ b₂, (bb, h₄) ← eval_mul b₁ b₂, (t, H) ← eval_add haa (xadd' c ab x₁ n₁ bb), return (t, c.cs_app ``horner_mul_horner [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, b₂, aa, haa, ab, bb, t, h₁, h₂, h₃, h₄, H]) theorem horner_pow {α} [comm_semiring α] (a x n m n' a') (h₁ : n * m = n') (h₂ : a ^ m = a') : @horner α _ a x n 0 ^ m = horner a' x n' 0 := by simp [h₁.symm, h₂.symm, horner, mul_pow, pow_mul] meta def eval_pow : horner_expr → expr × ℕ → ring_m (horner_expr × expr) | e (_, 0) := do c ← get_cache, α1 ← lift $ expr.of_nat c.α 1, p ← lift $ mk_app ``pow_zero [e], return (const α1, p) | e (_, 1) := do p ← lift $ mk_app ``pow_one [e], return (e, p) | (const e) (e₂, m) := do (e', p) ← lift $ mk_app ``monoid.pow [e, e₂] >>= norm_num.derive, return (const e', p) | he@(xadd e a x n b) m := do c ← get_cache, let N : expr := expr.const `nat [], match b.e.to_nat with | some 0 := do (n', h₁) ← lift $ mk_app ``has_mul.mul [n.1, m.1] >>= norm_num, (a', h₂) ← eval_pow a m, α0 ← lift $ expr.of_nat c.α 0, return (xadd' c a' x (n', n.2 * m.2) (const α0), c.cs_app ``horner_pow [a, x.1, n.1, m.1, n', a', h₁, h₂]) | _ := do e₂ ← lift $ expr.of_nat N (m.2-1), l ← lift $ mk_app ``monoid.pow [e, e₂], (tl, hl) ← eval_pow he (e₂, m.2-1), (t, p₂) ← eval_mul tl he, hr ← lift $ mk_eq_refl e, p₂ ← ring_m.mk_app ``norm_num.subst_into_prod ``has_mul [l, e, tl, e, t, hl, hr, p₂], p₁ ← lift $ mk_app ``pow_succ' [e, e₂], p ← lift $ mk_eq_trans p₁ p₂, return (t, p) end theorem horner_atom {α} [comm_semiring α] (x : α) : x = horner 1 x 1 0 := by simp [horner] meta def eval_atom (e : expr) : ring_m (horner_expr × expr) := do c ← get_cache, i ← add_atom e, α0 ← lift $ expr.of_nat c.α 0, α1 ← lift $ expr.of_nat c.α 1, n1 ← lift $ expr.of_nat (expr.const `nat []) 1, return (xadd' c (const α1) (e, i) (n1, 1) (const α0), c.cs_app ``horner_atom [e]) lemma subst_into_pow {α} [monoid α] (l r tl tr t) (prl : (l : α) = tl) (prr : (r : ℕ) = tr) (prt : tl ^ tr = t) : l ^ r = t := by simp [prl, prr, prt] lemma unfold_sub {α} [add_group α] (a b c : α) (h : a + -b = c) : a - b = c := h lemma unfold_div {α} [division_ring α] (a b c : α) (h : a * b⁻¹ = c) : a / b = c := h meta def eval : expr → ring_m (horner_expr × expr) | `(%%e₁ + %%e₂) := do (e₁', p₁) ← eval e₁, (e₂', p₂) ← eval e₂, (e', p') ← eval_add e₁' e₂', p ← ring_m.mk_app ``norm_num.subst_into_sum ``has_add [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], return (e', p) | e@`(@has_sub.sub %%α %%P %%e₁ %%e₂) := mcond (succeeds (lift $ mk_app ``comm_ring [α] >>= mk_instance)) (do e₂' ← lift $ mk_app ``has_neg.neg [e₂], e ← lift $ mk_app ``has_add.add [e₁, e₂'], (e', p) ← eval e, p' ← ring_m.mk_app ``unfold_sub ``add_group [e₁, e₂, e', p], return (e', p')) (eval_atom e) | `(- %%e) := do (e₁, p₁) ← eval e, (e₂, p₂) ← eval_neg e₁, p ← ring_m.mk_app ``norm_num.subst_into_neg ``has_neg [e, e₁, e₂, p₁, p₂], return (e₂, p) | `(%%e₁ * %%e₂) := do (e₁', p₁) ← eval e₁, (e₂', p₂) ← eval e₂, (e', p') ← eval_mul e₁' e₂', p ← ring_m.mk_app ``norm_num.subst_into_prod ``has_mul [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], return (e', p) | e@`(has_inv.inv %%_) := (do (e', p) ← lift $ norm_num.derive e, lift $ e'.to_rat, return (const e', p)) <|> eval_atom e | `(%%e₁ / %%e₂) := do e₂' ← lift $ mk_app ``has_inv.inv [e₂], e ← lift $ mk_app ``has_mul.mul [e₁, e₂'], (e', p) ← eval e, p' ← ring_m.mk_app ``unfold_div ``division_ring [e₁, e₂, e', p], return (e', p') | e@`(@has_pow.pow _ _ %%P %%e₁ %%e₂) := do (e₂', p₂) ← eval e₂, match e₂'.e.to_nat, P with | some k, `(monoid.has_pow) := do (e₁', p₁) ← eval e₁, (e', p') ← eval_pow e₁' (e₂, k), p ← ring_m.mk_app ``subst_into_pow ``monoid [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], return (e', p) | some k, `(nat.has_pow) := do (e₁', p₁) ← eval e₁, (e', p') ← eval_pow e₁' (e₂, k), p₃ ← ring_m.mk_app ``subst_into_pow ``monoid [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], p₄ ← lift $ mk_app ``nat.pow_eq_pow [e₁, e₂] >>= mk_eq_symm, p ← lift $ mk_eq_trans p₄ p₃, return (e', p) | _, _ := eval_atom e end | e := match e.to_nat with | some n := (const e).refl_conv | none := eval_atom e end meta def eval' (red : transparency) (e : expr) : tactic (expr × expr) := ring_m.run red e $ do (e', p) ← eval e, return (e', p) theorem horner_def' {α} [comm_semiring α] (a x n b) : @horner α _ a x n b = x ^ n * a + b := by simp [horner, mul_comm] theorem mul_assoc_rev {α} [semigroup α] (a b c : α) : a * (b * c) = a * b * c := by simp [mul_assoc] theorem pow_add_rev {α} [monoid α] (a : α) (m n : ℕ) : a ^ m * a ^ n = a ^ (m + n) := by simp [pow_add] theorem pow_add_rev_right {α} [monoid α] (a b : α) (m n : ℕ) : b * a ^ m * a ^ n = b * a ^ (m + n) := by simp [pow_add, mul_assoc] theorem add_neg_eq_sub {α} [add_group α] (a b : α) : a + -b = a - b := rfl @[derive has_reflect] inductive normalize_mode | raw | SOP | horner meta def normalize (red : transparency) (mode := normalize_mode.horner) (e : expr) : tactic (expr × expr) := do pow_lemma ← simp_lemmas.mk.add_simp ``pow_one, let lemmas := match mode with | normalize_mode.SOP := [``horner_def', ``add_zero, ``mul_one, ``mul_add, ``mul_sub, ``mul_assoc_rev, ``pow_add_rev, ``pow_add_rev_right, ``mul_neg_eq_neg_mul_symm, ``add_neg_eq_sub] | normalize_mode.horner := [``horner.equations._eqn_1, ``add_zero, ``one_mul, ``pow_one, ``neg_mul_eq_neg_mul_symm, ``add_neg_eq_sub] | _ := [] end, lemmas ← lemmas.mfoldl simp_lemmas.add_simp simp_lemmas.mk, (_, e', pr) ← ext_simplify_core () {} simp_lemmas.mk (λ _, failed) (λ _ _ _ _ e, do (new_e, pr) ← match mode with | normalize_mode.raw := eval' red | normalize_mode.horner := trans_conv (eval' red) (simplify lemmas []) | normalize_mode.SOP := trans_conv (eval' red) $ trans_conv (simplify lemmas []) $ simp_bottom_up' (λ e, norm_num e <|> pow_lemma.rewrite e) end e, guard (¬ new_e =ₐ e), return ((), new_e, some pr, ff)) (λ _ _ _ _ _, failed) `eq e, return (e', pr) end ring namespace interactive open interactive interactive.types lean.parser open tactic.ring local postfix `?`:9001 := optional /-- Tactic for solving equations in the language of *commutative* (semi)rings. This version of `ring` fails if the target is not an equality that is provable by the axioms of commutative (semi)rings. -/ meta def ring1 (red : parse (tk "!")?) : tactic unit := let transp := if red.is_some then semireducible else reducible in do `(%%e₁ = %%e₂) ← target, ((e₁', p₁), (e₂', p₂)) ← ring_m.run transp e₁ $ prod.mk <$> eval e₁ <*> eval e₂, is_def_eq e₁' e₂', p ← mk_eq_symm p₂ >>= mk_eq_trans p₁, tactic.exact p meta def ring.mode : lean.parser ring.normalize_mode := with_desc "(SOP|raw|horner)?" $ do mode ← ident?, match mode with | none := return ring.normalize_mode.horner | some `horner := return ring.normalize_mode.horner | some `SOP := return ring.normalize_mode.SOP | some `raw := return ring.normalize_mode.raw | _ := failed end /-- Tactic for solving equations in the language of *commutative* (semi)rings. Attempts to prove the goal outright if there is no `at` specifier and the target is an equality, but if this fails it falls back to rewriting all ring expressions into a normal form. When writing a normal form, `ring SOP` will use sum-of-products form instead of horner form. `ring!` will use a more aggressive reducibility setting to identify atoms. -/ meta def ring (red : parse (tk "!")?) (SOP : parse ring.mode) (loc : parse location) : tactic unit := match loc with | interactive.loc.ns [none] := instantiate_mvars_in_target >> ring1 red | _ := failed end <|> do ns ← loc.get_locals, let transp := if red.is_some then semireducible else reducible, tt ← tactic.replace_at (normalize transp SOP) ns loc.include_goal | fail "ring failed to simplify", when loc.include_goal $ try tactic.reflexivity end interactive end tactic namespace conv.interactive open conv interactive open tactic tactic.interactive (ring.mode ring1) open tactic.ring (normalize) local postfix `?`:9001 := optional meta def ring (red : parse (lean.parser.tk "!")?) (SOP : parse ring.mode) : conv unit := let transp := if red.is_some then semireducible else reducible in discharge_eq_lhs (ring1 red) <|> replace_lhs (normalize transp SOP) <|> fail "ring failed to simplify" end conv.interactive
33bda3aa4c5799f480978bb17296b62e90891dd5
59b654f4ee2fef898a3487dc03554a569051b63a
/src/graph.lean
9fb1b94ea649dc3d45bac6163676280c08393d8e
[]
no_license
gunpinyo/twisted_cube_formalisation
180c9157478b66ec2b11ca47c8ff998a3e978a88
f78206ac495e84bd43a9b820fa10b6c94722e0ec
refs/heads/master
1,624,501,222,992
1,607,081,624,000
1,607,081,624,000
166,885,106
0
0
null
null
null
null
UTF-8
Lean
false
false
3,421
lean
import utils structure graph : Type 1 := (node : Type) (edge : Type) (src : edge → node) (trg : edge → node) namespace graph protected def ext (G G' : graph) (node : G.node = G'.node) (edge : G.edge = G'.edge) (src : G.src == G'.src) (trg : G.trg == G'.trg) : G = G' := begin cases G with v e s t, cases G' with v' e' s' t', cases node, cases edge, cases src, cases trg, refl end protected def srctrg (G : graph) : bool → G.edge → G.node | ff := G.src | tt := G.trg protected def make (node : Type) (edge : Type) (srctrg : bool → edge → node) : graph := { node := node, edge := edge, src := srctrg ff, trg := srctrg tt } def has_srctrg_as (G : graph) (e : G.edge) (s t : G.node) : Prop := G.src e = s ∧ G.trg e = t def composable (G : graph) (e e' : G.edge) : Prop := G.trg e = G.src e' @[class] def has_deceq_node (G : graph) : Type := decidable_eq G.node @[class] def reflexive_struct (G : graph) : Type := Π v : G.node, subtype.mk ⟨G.edge, _⟩ #check subtype def reflexive_closure (G : graph) : graph := graph.make G.node (G.edge ⊕ G.node) (λ b, sum.elim (cond b G.trg G.src) id) instance reflexive_closure_is_reflexive_struct (G : graph) : reflexive_struct (reflexive_closure G) := begin dsimp [reflexive_struct, reflexive_closure, graph.make, has_srctrg_as], intro v, fapply subtype.mk, exact sum.inr v, simp, end @[class] def symmetric_struct (G : graph) : Type := Π e : G.edge, {e' : G.edge // G.has_srctrg_as e' (G.trg e) (G.src e)} def symmetric_closure (G : graph) : graph := graph.make G.node (G.edge ⊕ G.edge) (λ b, sum.elim (G.srctrg b) (G.srctrg (bnot b))) instance symmetric_closure_is_symmetric_struct (G : graph) : symmetric_struct (symmetric_closure G) := begin dsimp [symmetric_struct, symmetric_closure, graph.make], intro e, cases e, {fapply subtype.mk, exact sum.inr e, simp [has_srctrg_as]}, {fapply subtype.mk, exact sum.inl e, simp [has_srctrg_as]} end inductive nonempty_path (G : graph) : G.node → G.node → Type | from_edge : Π e : G.edge, nonempty_path (G.src e) (G.trg e) | compose : Π {v v' v'' : G.node} (p : nonempty_path v v') (p' : nonempty_path v' v''), nonempty_path v v'' structure nonempty_path_with_srctrg (G : graph) : Type := (src trg : G.node) (p : nonempty_path G src trg) @[class] def transitive_struct (G : graph) : Type := Π e e' : G.edge, G.composable e e' → {e'': G.edge // G.has_srctrg_as e'' (G.src e) (G.trg e')} def transitive_closure (G : graph) : graph := graph.make G.node (nonempty_path_with_srctrg G) (λ b e, cond b e.src e.trg) instance transitive_closure_is_transitive_struct (G : graph) : transitive_struct (transitive_closure G) := begin dsimp [transitive_struct, transitive_closure, graph.make], intro v, fapply subtype.mk, exact sum.inr v, simp, end end graph structure graph_hom (G H : graph) : Type := (node : G.node → H.node) (edge : G.edge → H.edge) (scr : ∀ e : G.edge, node (G.src e) = H.src (edge e)) (trg : ∀ e : G.edge, node (G.trg e) = H.trg (edge e))
f4c1fa83065dc594e98b8f59162003efe705edbd
9dc8cecdf3c4634764a18254e94d43da07142918
/src/measure_theory/covering/vitali.lean
7836842778ca8ad9b8ebb1176a3ea51ee2218ff0
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
29,621
lean
/- Copyright (c) 2021 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.metric_space.basic import measure_theory.constructions.borel_space import measure_theory.covering.vitali_family /-! # Vitali covering theorems The topological Vitali covering theorem, in its most classical version, states the following. Consider a family of balls `(B (x_i, r_i))_{i ∈ I}` in a metric space, with uniformly bounded radii. Then one can extract a disjoint subfamily indexed by `J ⊆ I`, such that any `B (x_i, r_i)` is included in a ball `B (x_j, 5 r_j)`. We prove this theorem in `vitali.exists_disjoint_subfamily_covering_enlargment_closed_ball`. It is deduced from a more general version, called `vitali.exists_disjoint_subfamily_covering_enlargment`, which applies to any family of sets together with a size function `δ` (think "radius" or "diameter"). We deduce the measurable Vitali covering theorem. Assume one is given a family `t` of closed sets with nonempty interior, such that each `a ∈ t` is included in a ball `B (x, r)` and covers a definite proportion of the ball `B (x, 6 r)` for a given measure `μ` (think of the situation where `μ` is a doubling measure and `t` is a family of balls). Consider a set `s` at which the family is fine, i.e., every point of `s` belongs to arbitrarily small elements of `t`. Then one can extract from `t` a disjoint subfamily that covers almost all `s`. It is proved in `vitali.exists_disjoint_covering_ae`. A way to restate this theorem is to say that the set of closed sets `a` with nonempty interior covering a fixed proportion `1/C` of the ball `closed_ball x (3 * diam a)` forms a Vitali family. This version is given in `vitali.vitali_family`. -/ variables {α : Type*} open set metric measure_theory topological_space filter open_locale nnreal classical ennreal topological_space namespace vitali /-- Vitali covering theorem: given a set `t` of subsets of a type, one may extract a disjoint subfamily `u` such that the `τ`-enlargment of this family covers all elements of `t`, where `τ > 1` is any fixed number. When `t` is a family of balls, the `τ`-enlargment of `ball x r` is `ball x ((1+2τ) r)`. In general, it is expressed in terms of a function `δ` (think "radius" or "diameter"), positive and bounded on all elements of `t`. The condition is that every element `a` of `t` should intersect an element `b` of `u` of size larger than that of `a` up to `τ`, i.e., `δ b ≥ δ a / τ`. -/ theorem exists_disjoint_subfamily_covering_enlargment (t : set (set α)) (δ : set α → ℝ) (τ : ℝ) (hτ : 1 < τ) (δnonneg : ∀ a ∈ t, 0 ≤ δ a) (R : ℝ) (δle : ∀ a ∈ t, δ a ≤ R) (hne : ∀ a ∈ t, set.nonempty a) : ∃ u ⊆ t, u.pairwise_disjoint id ∧ ∀ a ∈ t, ∃ b ∈ u, set.nonempty (a ∩ b) ∧ δ a ≤ τ * δ b := begin /- The proof could be formulated as a transfinite induction. First pick an element of `t` with `δ` as large as possible (up to a factor of `τ`). Then among the remaining elements not intersecting the already chosen one, pick another element with large `δ`. Go on forever (transfinitely) until there is nothing left. Instead, we give a direct Zorn-based argument. Consider a maximal family `u` of disjoint sets with the following property: if an element `a` of `t` intersects some element `b` of `u`, then it intersects some `b' ∈ u` with `δ b' ≥ δ a / τ`. Such a maximal family exists by Zorn. If this family did not intersect some element `a ∈ t`, then take an element `a' ∈ t` which does not intersect any element of `u`, with `δ a'` almost as large as possible. One checks easily that `u ∪ {a'}` still has this property, contradicting the maximality. Therefore, `u` intersects all elements of `t`, and by definition it satisfies all the desired properties. -/ let T : set (set (set α)) := {u | u ⊆ t ∧ u.pairwise_disjoint id ∧ ∀ a ∈ t, ∀ b ∈ u, set.nonempty (a ∩ b) → ∃ c ∈ u, (a ∩ c).nonempty ∧ δ a ≤ τ * δ c}, -- By Zorn, choose a maximal family in the good set `T` of disjoint families. obtain ⟨u, uT, hu⟩ : ∃ u ∈ T, ∀ v ∈ T, u ⊆ v → v = u, { refine zorn_subset _ (λ U UT hU, _), refine ⟨⋃₀ U, _, λ s hs, subset_sUnion_of_mem hs⟩, simp only [set.sUnion_subset_iff, and_imp, exists_prop, forall_exists_index, mem_sUnion, set.mem_set_of_eq], refine ⟨λ u hu, (UT hu).1, (pairwise_disjoint_sUnion hU.directed_on).2 (λ u hu, (UT hu).2.1), λ a hat b u uU hbu hab, _⟩, obtain ⟨c, cu, ac, hc⟩ : ∃ (c : set α) (H : c ∈ u), (a ∩ c).nonempty ∧ δ a ≤ τ * δ c := (UT uU).2.2 a hat b hbu hab, exact ⟨c, ⟨u, uU, cu⟩, ac, hc⟩ }, -- the only nontrivial bit is to check that every `a ∈ t` intersects an element `b ∈ u` with -- comparatively large `δ b`. Assume this is not the case, then we will contradict the maximality. refine ⟨u, uT.1, uT.2.1, λ a hat, _⟩, contrapose! hu, have a_disj : ∀ c ∈ u, disjoint a c, { assume c hc, by_contra, rw not_disjoint_iff_nonempty_inter at h, obtain ⟨d, du, ad, hd⟩ : ∃ (d : set α) (H : d ∈ u), (a ∩ d).nonempty ∧ δ a ≤ τ * δ d := uT.2.2 a hat c hc h, exact lt_irrefl _ ((hu d du ad).trans_le hd) }, -- Let `A` be all the elements of `t` which do not intersect the family `u`. It is nonempty as it -- contains `a`. We will pick an element `a'` of `A` with `δ a'` almost as large as possible. let A := {a' | a' ∈ t ∧ ∀ c ∈ u, disjoint a' c}, have Anonempty : A.nonempty := ⟨a, hat, a_disj⟩, let m := Sup (δ '' A), have bddA : bdd_above (δ '' A), { refine ⟨R, λ x xA, _⟩, rcases (mem_image _ _ _).1 xA with ⟨a', ha', rfl⟩, exact δle a' ha'.1 }, obtain ⟨a', a'A, ha'⟩ : ∃ a' ∈ A, m / τ ≤ δ a', { have : 0 ≤ m := (δnonneg a hat).trans (le_cSup bddA (mem_image_of_mem _ ⟨hat, a_disj⟩)), rcases eq_or_lt_of_le this with mzero|mpos, { refine ⟨a, ⟨hat, a_disj⟩, _⟩, simpa only [← mzero, zero_div] using δnonneg a hat }, { have I : m / τ < m, { rw div_lt_iff (zero_lt_one.trans hτ), conv_lhs { rw ← mul_one m }, exact (mul_lt_mul_left mpos).2 hτ }, rcases exists_lt_of_lt_cSup (nonempty_image_iff.2 Anonempty) I with ⟨x, xA, hx⟩, rcases (mem_image _ _ _).1 xA with ⟨a', ha', rfl⟩, exact ⟨a', ha', hx.le⟩, } }, clear hat hu a_disj a, have a'_ne_u : a' ∉ u := λ H, (hne _ a'A.1).ne_empty (disjoint_self.1 (a'A.2 _ H)), -- we claim that `u ∪ {a'}` still belongs to `T`, contradicting the maximality of `u`. refine ⟨insert a' u, ⟨_, _, _⟩, subset_insert _ _, (ne_insert_of_not_mem _ a'_ne_u).symm⟩, -- check that `u ∪ {a'}` is made of elements of `t`. { rw insert_subset, exact ⟨a'A.1, uT.1⟩ }, -- check that `u ∪ {a'}` is a disjoint family. This follows from the fact that `a'` does not -- intersect `u`. { exact uT.2.1.insert (λ b bu ba', a'A.2 b bu) }, -- check that every element `c` of `t` intersecting `u ∪ {a'}` intersects an element of this -- family with large `δ`. { assume c ct b ba'u hcb, -- if `c` already intersects an element of `u`, then it intersects an element of `u` with -- large `δ` by the assumption on `u`, and there is nothing left to do. by_cases H : ∃ d ∈ u, set.nonempty (c ∩ d), { rcases H with ⟨d, du, hd⟩, rcases uT.2.2 c ct d du hd with ⟨d', d'u, hd'⟩, exact ⟨d', mem_insert_of_mem _ d'u, hd'⟩ }, -- otherwise, `c` belongs to `A`. The element of `u ∪ {a'}` that it intersects has to be `a'`. -- moreover, `δ c` is smaller than the maximum `m` of `δ` over `A`, which is `≤ δ a' / τ` -- thanks to the good choice of `a'`. This is the desired inequality. { push_neg at H, simp only [← not_disjoint_iff_nonempty_inter, not_not] at H, rcases mem_insert_iff.1 ba'u with rfl|H', { refine ⟨b, mem_insert _ _, hcb, _⟩, calc δ c ≤ m : le_cSup bddA (mem_image_of_mem _ ⟨ct, H⟩) ... = τ * (m / τ) : by { field_simp [(zero_lt_one.trans hτ).ne'], ring } ... ≤ τ * δ b : mul_le_mul_of_nonneg_left ha' (zero_le_one.trans hτ.le) }, { rw ← not_disjoint_iff_nonempty_inter at hcb, exact (hcb (H _ H')).elim } } } end /-- Vitali covering theorem, closed balls version: given a family `t` of closed balls, one can extract a disjoint subfamily `u ⊆ t` so that all balls in `t` are covered by the 5-times dilations of balls in `u`. -/ theorem exists_disjoint_subfamily_covering_enlargment_closed_ball [metric_space α] (t : set (set α)) (R : ℝ) (ht : ∀ s ∈ t, ∃ x r, s = closed_ball x r ∧ r ≤ R) : ∃ u ⊆ t, u.pairwise_disjoint id ∧ ∀ a ∈ t, ∃ x r, closed_ball x r ∈ u ∧ a ⊆ closed_ball x (5 * r) := begin rcases eq_empty_or_nonempty t with rfl|tnonempty, { exact ⟨∅, subset.refl _, pairwise_disjoint_empty, by simp⟩ }, haveI : inhabited α, { choose s hst using tnonempty, choose x r hxr using ht s hst, exact ⟨x⟩ }, -- Exclude the trivial case where `t` is reduced to the empty set. rcases eq_or_ne t {∅} with rfl|t_ne_empty, { refine ⟨{∅}, subset.refl _, _⟩, simp only [true_and, closed_ball_eq_empty, mem_singleton_iff, and_true, empty_subset, forall_eq, pairwise_disjoint_singleton, exists_const], exact ⟨-1, by simp only [right.neg_neg_iff, zero_lt_one]⟩ }, -- The real proof starts now. Since the center or the radius of a ball is not uniquely defined -- in a general metric space, we just choose one for definiteness. choose! x r hxr using ht, have r_nonneg : ∀ (a : set α), a ∈ t → a.nonempty → 0 ≤ r a, { assume a hat a_nonempty, rw (hxr a hat).1 at a_nonempty, simpa only [nonempty_closed_ball] using a_nonempty }, -- The difference with the generic version is that we are not excluding empty sets in our family -- (which would correspond to `r a < 0`). To compensate for this, we apply the generic version -- to the subfamily `t'` made of nonempty sets, and we use `δ = r` there. This gives a disjointed -- subfamily `u'`. let t' := {a ∈ t | 0 ≤ r a}, obtain ⟨u', u't', u'_disj, hu'⟩ : ∃ u' ⊆ t', u'.pairwise_disjoint id ∧ ∀ a ∈ t', ∃ b ∈ u', set.nonempty (a ∩ b) ∧ r a ≤ 2 * r b, { refine exists_disjoint_subfamily_covering_enlargment t' r 2 one_lt_two (λ a ha, ha.2) R (λ a ha, (hxr a ha.1).2) (λ a ha, _), rw [(hxr a ha.1).1], simp only [ha.2, nonempty_closed_ball] }, -- this subfamily is nonempty, as we have excluded the situation `t = {∅}`. have u'_nonempty : u'.nonempty, { have : ∃ a ∈ t, a ≠ ∅, { contrapose! t_ne_empty, apply subset.antisymm, { simpa only using t_ne_empty }, { rcases tnonempty with ⟨a, hat⟩, have := t_ne_empty a hat, simpa only [this, singleton_subset_iff] using hat } }, rcases this with ⟨a, hat, a_nonempty⟩, have ranonneg : 0 ≤ r a := r_nonneg a hat (ne_empty_iff_nonempty.1 a_nonempty), rcases hu' a ⟨hat, ranonneg⟩ with ⟨b, bu', hb⟩, exact ⟨b, bu'⟩ }, -- check that the family `u'` gives the desired disjoint covering. refine ⟨u', λ a ha, (u't' ha).1, u'_disj, λ a hat, _⟩, -- it remains to check that any ball in `t` is contained in the 5-dilation of a ball -- in `u'`. This depends on whether the ball is empty of not. rcases eq_empty_or_nonempty a with rfl|a_nonempty, -- if the ball is empty, use any element of `u'` (since we know that `u'` is nonempty). { rcases u'_nonempty with ⟨b, hb⟩, refine ⟨x b, r b, _, empty_subset _⟩, rwa ← (hxr b (u't' hb).1).1 }, -- if the ball is not empty, it belongs to `t'`. Then it intersects a ball `a'` in `u'` with -- controlled radius, by definition of `u'`. It is straightforward to check that this ball -- satisfies all the desired properties. { have hat' : a ∈ t' := ⟨hat, r_nonneg a hat a_nonempty⟩, obtain ⟨a', a'u', aa', raa'⟩ : (∃ (a' : set α) (H : a' ∈ u'), (a ∩ a').nonempty ∧ r a ≤ 2 * r a') := hu' a hat', refine ⟨x a', r a', _, _⟩, { convert a'u', exact (hxr a' (u't' a'u').1).1.symm }, { rw (hxr a hat'.1).1 at aa' ⊢, rw (hxr a' (u't' a'u').1).1 at aa', have : dist (x a) (x a') ≤ r a + r a' := dist_le_add_of_nonempty_closed_ball_inter_closed_ball aa', apply closed_ball_subset_closed_ball', linarith } } end /-- The measurable Vitali covering theorem. Assume one is given a family `t` of closed sets with nonempty interior, such that each `a ∈ t` is included in a ball `B (x, r)` and covers a definite proportion of the ball `B (x, 6 r)` for a given measure `μ` (think of the situation where `μ` is a doubling measure and `t` is a family of balls). Consider a (possible non-measurable) set `s` at which the family is fine, i.e., every point of `s` belongs to arbitrarily small elements of `t`. Then one can extract from `t` a disjoint subfamily that covers almost all `s`. -/ theorem exists_disjoint_covering_ae [metric_space α] [measurable_space α] [opens_measurable_space α] [second_countable_topology α] (μ : measure α) [is_locally_finite_measure μ] (s : set α) (t : set (set α)) (hf : ∀ x ∈ s, ∀ (ε > (0 : ℝ)), ∃ a ∈ t, x ∈ a ∧ a ⊆ closed_ball x ε) (ht : ∀ a ∈ t, (interior a).nonempty) (h't : ∀ a ∈ t, is_closed a) (C : ℝ≥0) (h : ∀ a ∈ t, ∃ x ∈ a, μ (closed_ball x (3 * diam a)) ≤ C * μ a) : ∃ u ⊆ t, u.countable ∧ u.pairwise_disjoint id ∧ μ (s \ ⋃ (a ∈ u), a) = 0 := begin /- The idea of the proof is the following. Assume for simplicity that `μ` is finite. Applying the abstract Vitali covering theorem with `δ = diam`, one obtains a disjoint subfamily `u`, such that any element of `t` intersects an element of `u` with comparable diameter. Fix `ε > 0`. Since the elements of `u` have summable measure, one can remove finitely elements `w_1, ..., w_n`. so that the measure of the remaining elements is `< ε`. Consider now a point `z` not in the `w_i`. There is a small ball around `z` not intersecting the `w_i` (as they are closed), an element `a ∈ t` contained in this small ball (as the family `t` is fine at `z`) and an element `b ∈ u` intersecting `a`, with comparable diameter (by definition of `u`). Then `z` belongs to the enlargement of `b`. This shows that `s \ (w_1 ∪ ... ∪ w_n)` is contained in `⋃ (b ∈ u \ {w_1, ... w_n}) (enlargement of b)`. The measure of the latter set is bounded by `∑ (b ∈ u \ {w_1, ... w_n}) C * μ b` (by the doubling property of the measure), which is at most `C ε`. Letting `ε` tend to `0` shows that `s` is almost everywhere covered by the family `u`. For the real argument, the measure is only locally finite. Therefore, we implement the same strategy, but locally restricted to balls on which the measure is finite. For this, we do not use the whole family `t`, but a subfamily `t'` supported on small balls (which is possible since the family is assumed to be fine at every point of `s`). -/ rcases eq_empty_or_nonempty s with rfl|nonempty, { refine ⟨∅, empty_subset _, countable_empty, pairwise_disjoint_empty, by simp only [measure_empty, Union_false, Union_empty, diff_self]⟩ }, haveI : inhabited α, { choose x hx using nonempty, exact ⟨x⟩ }, -- choose around each `x` a small ball on which the measure is finite have : ∀ x, ∃ r, 0 < r ∧ r ≤ 1 ∧ μ (closed_ball x (20 * r)) < ∞, { assume x, obtain ⟨R, Rpos, μR⟩ : ∃ (R : ℝ) (hR : 0 < R), μ (closed_ball x R) < ∞ := (μ.finite_at_nhds x).exists_mem_basis nhds_basis_closed_ball, refine ⟨min 1 (R/20), _, min_le_left _ _, _⟩, { simp only [true_and, lt_min_iff, zero_lt_one], linarith }, { apply lt_of_le_of_lt (measure_mono _) μR, apply closed_ball_subset_closed_ball, calc 20 * min 1 (R / 20) ≤ 20 * (R/20) : mul_le_mul_of_nonneg_left (min_le_right _ _) (by norm_num) ... = R : by ring } }, choose r hr0 hr1 hrμ, -- we restrict to a subfamily `t'` of `t`, made of elements small enough to ensure that -- they only see a finite part of the measure. let t' := {a ∈ t | ∃ x, a ⊆ closed_ball x (r x)}, -- extract a disjoint subfamily `u` of `t'` thanks to the abstract Vitali covering theorem. obtain ⟨u, ut', u_disj, hu⟩ : ∃ u ⊆ t', u.pairwise_disjoint id ∧ ∀ a ∈ t', ∃ b ∈ u, set.nonempty (a ∩ b) ∧ diam a ≤ 2 * diam b, { have A : ∀ (a : set α), a ∈ t' → diam a ≤ 2, { rintros a ⟨hat, ⟨x, hax⟩⟩, calc diam a ≤ 2 * 1 : diam_le_of_subset_closed_ball zero_le_one (hax.trans $ closed_ball_subset_closed_ball $ hr1 x) ... = 2 : mul_one _ }, have B : ∀ (a : set α), a ∈ t' → a.nonempty := λ a hat', set.nonempty.mono interior_subset (ht a hat'.1), exact exists_disjoint_subfamily_covering_enlargment t' diam 2 one_lt_two (λ a ha, diam_nonneg) 2 A B }, have ut : u ⊆ t := λ a hau, (ut' hau).1, -- As the space is second countable, the family is countable since all its sets have nonempty -- interior. have u_count : u.countable := u_disj.countable_of_nonempty_interior (λ a ha, ht a (ut ha)), -- the family `u` will be the desired family refine ⟨u, λ a hat', (ut' hat').1, u_count, u_disj, _⟩, -- it suffices to show that it covers almost all `s` locally around each point `x`. refine null_of_locally_null _ (λ x hx, _), -- let `v` be the subfamily of `u` made of those sets intersecting the small ball `ball x (r x)` let v := {a ∈ u | (a ∩ ball x (r x)).nonempty }, have vu : v ⊆ u := λ a ha, ha.1, -- they are all contained in a fixed ball of finite measure, thanks to our choice of `t'` obtain ⟨R, μR, hR⟩ : ∃ R, μ (closed_ball x R) < ∞ ∧ ∀ a ∈ u, (a ∩ ball x (r x)).nonempty → a ⊆ closed_ball x R, { have : ∀ a ∈ u, ∃ y, a ⊆ closed_ball y (r y) := λ a hau, (ut' hau).2, choose! y hy using this, have Idist_v : ∀ a ∈ v, dist (y a) x ≤ r (y a) + r x, { assume a hav, apply dist_le_add_of_nonempty_closed_ball_inter_closed_ball, exact hav.2.mono (inter_subset_inter (hy a hav.1) ball_subset_closed_ball) }, set R0 := Sup ((λ a, r (y a)) '' v) with hR0, have R0_bdd : bdd_above ((λ a, r (y a)) '' v), { refine ⟨1, λ r' hr', _⟩, rcases (mem_image _ _ _).1 hr' with ⟨b, hb, rfl⟩, exact hr1 _ }, rcases le_total R0 (r x) with H|H, { refine ⟨20 * r x, hrμ x, λ a au hax, _⟩, refine (hy a au).trans _, apply closed_ball_subset_closed_ball', have : r (y a) ≤ R0 := le_cSup R0_bdd (mem_image_of_mem _ ⟨au, hax⟩), linarith [(hr0 (y a)).le, (hr0 x).le, Idist_v a ⟨au, hax⟩] }, { have R0pos : 0 < R0 := (hr0 x).trans_le H, have vnonempty : v.nonempty, { by_contra, rw [← ne_empty_iff_nonempty, not_not] at h, simp only [h, real.Sup_empty, image_empty] at hR0, exact lt_irrefl _ (R0pos.trans_le (le_of_eq hR0)) }, obtain ⟨a, hav, R0a⟩ : ∃ a ∈ v, R0/2 < r (y a), { obtain ⟨r', r'mem, hr'⟩ : ∃ r' ∈ ((λ a, r (y a)) '' v), R0 / 2 < r' := exists_lt_of_lt_cSup (nonempty_image_iff.2 vnonempty) (half_lt_self R0pos), rcases (mem_image _ _ _).1 r'mem with ⟨a, hav, rfl⟩, exact ⟨a, hav, hr'⟩ }, refine ⟨8 * R0, _, _⟩, { apply lt_of_le_of_lt (measure_mono _) (hrμ (y a)), apply closed_ball_subset_closed_ball', rw dist_comm, linarith [Idist_v a hav] }, { assume b bu hbx, refine (hy b bu).trans _, apply closed_ball_subset_closed_ball', have : r (y b) ≤ R0 := le_cSup R0_bdd (mem_image_of_mem _ ⟨bu, hbx⟩), linarith [Idist_v b ⟨bu, hbx⟩] } } }, -- we will show that, in `ball x (r x)`, almost all `s` is covered by the family `u`. refine ⟨_ ∩ ball x (r x), inter_mem_nhds_within _ (ball_mem_nhds _ (hr0 _)), nonpos_iff_eq_zero.mp (le_of_forall_le_of_dense (λ ε εpos, _))⟩, -- the elements of `v` are disjoint and all contained in a finite volume ball, hence the sum -- of their measures is finite. have I : ∑' (a : v), μ (↑a) < ∞, { calc ∑' (a : v), μ (↑a) = μ (⋃ (a ∈ v), a) : begin rw measure_bUnion (u_count.mono vu) _ (λ a ha, (h't _ (vu.trans ut ha)).measurable_set), exact u_disj.subset vu end ... ≤ μ (closed_ball x R) : measure_mono (Union₂_subset (λ a ha, hR a (vu ha) ha.2)) ... < ∞ : μR }, -- we can obtain a finite subfamily of `v`, such that the measures of the remaining elements -- add up to an arbitrarily small number, say `ε / C`. obtain ⟨w, hw⟩ : ∃ (w : finset ↥v), ∑' (a : {a // a ∉ w}), μ (↑a) < ε / C, { haveI : ne_bot (at_top : filter (finset v)) := at_top_ne_bot, have : 0 < ε / C, by simp only [ennreal.div_pos_iff, εpos.ne', ennreal.coe_ne_top, ne.def, not_false_iff, and_self], exact ((tendsto_order.1 (ennreal.tendsto_tsum_compl_at_top_zero I.ne)).2 _ this).exists }, choose! y hy using h, -- main property: the points `z` of `s` which are not covered by `u` are contained in the -- enlargements of the elements not in `w`. have M : (s \ ⋃ (a : set α) (H : a ∈ u), a) ∩ ball x (r x) ⊆ ⋃ (a : {a // a ∉ w}), closed_ball (y a) (3 * diam (a : set α)), { assume z hz, set k := ⋃ (a : v) (ha : a ∈ w), (↑a : set α) with hk, have k_closed : is_closed k := is_closed_bUnion w.finite_to_set (λ i hi, h't _ (ut (vu i.2))), have z_notmem_k : z ∉ k, { simp only [not_exists, exists_prop, mem_Union, mem_sep_eq, forall_exists_index, set_coe.exists, not_and, exists_and_distrib_right, subtype.coe_mk], assume b hbv h'b h'z, have : z ∈ (s \ ⋃ (a : set α) (H : a ∈ u), a) ∩ (⋃ (a : set α) (H : a ∈ u), a) := mem_inter (mem_of_mem_inter_left hz) (mem_bUnion (vu hbv) h'z), simpa only [diff_inter_self] }, -- since the elements of `w` are closed and finitely many, one can find a small ball around `z` -- not intersecting them have : ball x (r x) \ k ∈ 𝓝 z, { apply is_open.mem_nhds (is_open_ball.sdiff k_closed) _, exact (mem_diff _).2 ⟨mem_of_mem_inter_right hz, z_notmem_k⟩ }, obtain ⟨d, dpos, hd⟩ : ∃ (d : ℝ) (dpos : 0 < d), closed_ball z d ⊆ ball x (r x) \ k := nhds_basis_closed_ball.mem_iff.1 this, -- choose an element `a` of the family `t` contained in this small ball obtain ⟨a, hat, za, ad⟩ : ∃ a ∈ t, z ∈ a ∧ a ⊆ closed_ball z d := hf z ((mem_diff _).1 (mem_of_mem_inter_left hz)).1 d dpos, have ax : a ⊆ ball x (r x) := ad.trans (hd.trans (diff_subset (ball x (r x)) k)), -- it intersects an element `b` of `u` with comparable diameter, by definition of `u` obtain ⟨b, bu, ab, bdiam⟩ : ∃ (b : set α) (H : b ∈ u), (a ∩ b).nonempty ∧ diam a ≤ 2 * diam b := hu a ⟨hat, ⟨x, ax.trans ball_subset_closed_ball⟩⟩, have bv : b ∈ v, { refine ⟨bu, ab.mono _⟩, rw inter_comm, exact inter_subset_inter_right _ ax }, let b' : v := ⟨b, bv⟩, -- `b` can not belong to `w`, as the elements of `w` do not intersect `closed_ball z d`, -- contrary to `b` have b'_notmem_w : b' ∉ w, { assume b'w, have b'k : (↑b' : set α) ⊆ k := finset.subset_set_bUnion_of_mem b'w, have : ((ball x (r x) \ k) ∩ k).nonempty := ab.mono (inter_subset_inter (ad.trans hd) b'k), simpa only [diff_inter_self, not_nonempty_empty] }, let b'' : {a // a ∉ w} := ⟨b', b'_notmem_w⟩, -- since `a` and `b` have comparable diameters, it follows that `z` belongs to the -- enlargement of `b` have zb : z ∈ closed_ball (y b) (3 * diam b), { rcases ab with ⟨e, ⟨ea, eb⟩⟩, have A : dist z e ≤ diam a := dist_le_diam_of_mem (bounded_closed_ball.mono ad) za ea, have B : dist e (y b) ≤ diam b, { rcases (ut' bu).2 with ⟨c, hc⟩, apply dist_le_diam_of_mem (bounded_closed_ball.mono hc) eb (hy b (ut bu)).1 }, simp only [mem_closed_ball], linarith [dist_triangle z e (y b)] }, suffices H : closed_ball (y (↑b'')) (3 * diam (↑b'' : set α)) ⊆ ⋃ (a : {a // a ∉ w}), closed_ball (y (↑a)) (3 * diam (↑a : set α)), from H zb, exact subset_Union (λ (a : {a // a ∉ w}), closed_ball (y (↑a)) (3 * diam (↑a : set α))) b'' }, -- now that we have proved our main inclusion, we can use it to estimate the measure of the points -- in `ball x (r x)` not covered by `u`. haveI : encodable v := (u_count.mono vu).to_encodable, calc μ ((s \ ⋃ (a : set α) (H : a ∈ u), a) ∩ ball x (r x)) ≤ μ (⋃ (a : {a // a ∉ w}), closed_ball (y (↑a)) (3 * diam (↑a : set α))) : measure_mono M ... ≤ ∑' (a : {a // a ∉ w}), μ (closed_ball (y (↑a)) (3 * diam (↑a : set α))) : measure_Union_le _ ... ≤ ∑' (a : {a // a ∉ w}), C * μ (↑a) : ennreal.tsum_le_tsum (λ a, (hy a (ut (vu a.1.2))).2) ... = C * ∑' (a : {a // a ∉ w}), μ (↑a) : ennreal.tsum_mul_left ... ≤ C * (ε / C) : ennreal.mul_le_mul le_rfl hw.le ... ≤ ε : ennreal.mul_div_le end /-- Assume that around every point there are arbitrarily small scales at which the measure is doubling. Then the set of closed sets `a` with nonempty interior covering a fixed proportion `1/C` of the ball `closed_ball x (3 * diam a)` forms a Vitali family. This is essentially a restatement of the measurable Vitali theorem. -/ protected def vitali_family [metric_space α] [measurable_space α] [opens_measurable_space α] [second_countable_topology α] (μ : measure α) [is_locally_finite_measure μ] (C : ℝ≥0) (h : ∀ x (ε > 0), ∃ r ∈ Ioc (0 : ℝ) ε, μ (closed_ball x (6 * r)) ≤ C * μ (closed_ball x r)) : vitali_family μ := { sets_at := λ x, {a | x ∈ a ∧ is_closed a ∧ (interior a).nonempty ∧ μ (closed_ball x (3 * diam a)) ≤ C * μ a}, measurable_set' := λ x a ha, ha.2.1.measurable_set, nonempty_interior := λ x a ha, ha.2.2.1, nontrivial := λ x ε εpos, begin obtain ⟨r, ⟨rpos, rε⟩, μr⟩ : ∃ r ∈ Ioc (0 : ℝ) ε, μ (closed_ball x (6 * r)) ≤ C * μ (closed_ball x r) := h x ε εpos, refine ⟨closed_ball x r, ⟨_, is_closed_ball, _, _⟩, closed_ball_subset_closed_ball rε⟩, { simp only [rpos.le, mem_closed_ball, dist_self] }, { exact (nonempty_ball.2 rpos).mono (ball_subset_interior_closed_ball) }, { apply le_trans (measure_mono (closed_ball_subset_closed_ball _)) μr, have : diam (closed_ball x r) ≤ 2 * r := diam_closed_ball rpos.le, linarith } end, covering := begin assume s f fsubset ffine, rcases eq_empty_or_nonempty s with rfl|H, { exact ⟨∅, λ _, ∅, by simp, by simp⟩ }, haveI : inhabited α, { choose x hx using H, exact ⟨x⟩ }, let t := ⋃ (x ∈ s), f x, have A₁ : ∀ x ∈ s, ∀ (ε : ℝ), 0 < ε → (∃ a ∈ t, x ∈ a ∧ a ⊆ closed_ball x ε), { assume x xs ε εpos, rcases ffine x xs ε εpos with ⟨a, xa, hax⟩, exact ⟨a, mem_bUnion xs xa, (fsubset x xs xa).1, hax⟩ }, have A₂ : ∀ a ∈ t, (interior a).nonempty, { rintros a ha, rcases mem_Union₂.1 ha with ⟨x, xs, xa⟩, exact (fsubset x xs xa).2.2.1 }, have A₃ : ∀ a ∈ t, is_closed a, { rintros a ha, rcases mem_Union₂.1 ha with ⟨x, xs, xa⟩, exact (fsubset x xs xa).2.1 }, have A₄ : ∀ a ∈ t, ∃ x ∈ a, μ (closed_ball x (3 * diam a)) ≤ C * μ a, { rintros a ha, rcases mem_Union₂.1 ha with ⟨x, xs, xa⟩, exact ⟨x, (fsubset x xs xa).1, (fsubset x xs xa).2.2.2⟩ }, obtain ⟨u, ut, u_count, u_disj, μu⟩ : ∃ u ⊆ t, u.countable ∧ u.pairwise disjoint ∧ μ (s \ ⋃ a ∈ u, a) = 0 := exists_disjoint_covering_ae μ s t A₁ A₂ A₃ C A₄, have : ∀ a ∈ u, ∃ x ∈ s, a ∈ f x := λ a ha, mem_Union₂.1 (ut ha), choose! x hx using this, have inj_on_x : inj_on x u, { assume a ha b hb hab, have A : (a ∩ b).nonempty, { refine ⟨x a, mem_inter ((fsubset _ (hx a ha).1 (hx a ha).2).1) _⟩, rw hab, exact (fsubset _ (hx b hb).1 (hx b hb).2).1 }, contrapose A, have : disjoint a b := u_disj ha hb A, simpa only [← not_disjoint_iff_nonempty_inter] }, refine ⟨x '' u, function.inv_fun_on x u, _, _, _, _⟩, { assume y hy, rcases (mem_image _ _ _).1 hy with ⟨a, au, rfl⟩, exact (hx a au).1 }, { rw [inj_on_x.pairwise_disjoint_image], assume a ha b hb hab, simp only [function.on_fun, inj_on_x.left_inv_on_inv_fun_on ha, inj_on_x.left_inv_on_inv_fun_on hb, (∘)], exact u_disj ha hb hab }, { assume y hy, rcases (mem_image _ _ _).1 hy with ⟨a, ha, rfl⟩, rw inj_on_x.left_inv_on_inv_fun_on ha, exact (hx a ha).2 }, { rw [bUnion_image], convert μu using 3, exact Union₂_congr (λ a ha, inj_on_x.left_inv_on_inv_fun_on ha) } end } end vitali
8db86d29c13fa10d2dd88953a3c1969bfd5f8803
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/elab13.lean
810d83813a06b63ae7d5487357466edf6872ab01
[ "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
255
lean
open tactic list #check assume c : name, ( do { env ← get_env, decl ← returnex (environment.get env c), num ← return (length (declaration.univ_params decl)), ls ← mk_num_meta_univs 2, return (expr.const c ls) } : tactic expr)
814765cbff6734a59663c72d81602d221f819b68
63abd62053d479eae5abf4951554e1064a4c45b4
/src/measure_theory/bochner_integration.lean
f36a5e6966bb0a71591e51e5704b33326f39672e
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
64,770
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Yury Kudryashov -/ import measure_theory.simple_func_dense import analysis.normed_space.bounded_linear_maps import topology.sequences /-! # Bochner integral The Bochner integral extends the definition of the Lebesgue integral to functions that map from a measure space into a Banach space (complete normed vector space). It is constructed here by extending the integral on simple functions. ## Main definitions The Bochner integral is defined following these steps: 1. Define the integral on simple functions of the type `simple_func α E` (notation : `α →ₛ E`) where `E` is a real normed space. (See `simple_func.bintegral` and section `bintegral` for details. Also see `simple_func.integral` for the integral on simple functions of the type `simple_func α ennreal`.) 2. Use `α →ₛ E` to cut out the simple functions from L1 functions, and define integral on these. The type of simple functions in L1 space is written as `α →₁ₛ[μ] E`. 3. Show that the embedding of `α →₁ₛ[μ] E` into L1 is a dense and uniform one. 4. Show that the integral defined on `α →₁ₛ[μ] E` is a continuous linear map. 5. Define the Bochner integral on L1 functions by extending the integral on integrable simple functions `α →₁ₛ[μ] E` using `continuous_linear_map.extend`. Define the Bochner integral on functions as the Bochner integral of its equivalence class in L1 space. ## Main statements 1. Basic properties of the Bochner integral on functions of type `α → E`, where `α` is a measure space and `E` is a real normed space. * `integral_zero` : `∫ 0 ∂μ = 0` * `integral_add` : `∫ x, f x + g x ∂μ = ∫ x, f ∂μ + ∫ x, g x ∂μ` * `integral_neg` : `∫ x, - f x ∂μ = - ∫ x, f x ∂μ` * `integral_sub` : `∫ x, f x - g x ∂μ = ∫ x, f x ∂μ - ∫ x, g x ∂μ` * `integral_smul` : `∫ x, r • f x ∂μ = r • ∫ x, f x ∂μ` * `integral_congr_ae` : `f =ᵐ[μ] g → ∫ x, f x ∂μ = ∫ x, g x ∂μ` * `norm_integral_le_integral_norm` : `∥∫ x, f x ∂μ∥ ≤ ∫ x, ∥f x∥ ∂μ` 2. Basic properties of the Bochner integral on functions of type `α → ℝ`, where `α` is a measure space. * `integral_nonneg_of_ae` : `0 ≤ᵐ[μ] f → 0 ≤ ∫ x, f x ∂μ` * `integral_nonpos_of_ae` : `f ≤ᵐ[μ] 0 → ∫ x, f x ∂μ ≤ 0` * `integral_mono_ae` : `f ≤ᵐ[μ] g → ∫ x, f x ∂μ ≤ ∫ x, g x ∂μ` * `integral_nonneg` : `0 ≤ f → 0 ≤ ∫ x, f x ∂μ` * `integral_nonpos` : `f ≤ 0 → ∫ x, f x ∂μ ≤ 0` * `integral_mono` : `f ≤ᵐ[μ] g → ∫ x, f x ∂μ ≤ ∫ x, g x ∂μ` 3. Propositions connecting the Bochner integral with the integral on `ennreal`-valued functions, which is called `lintegral` and has the notation `∫⁻`. * `integral_eq_lintegral_max_sub_lintegral_min` : `∫ x, f x ∂μ = ∫⁻ x, f⁺ x ∂μ - ∫⁻ x, f⁻ x ∂μ`, where `f⁺` is the positive part of `f` and `f⁻` is the negative part of `f`. * `integral_eq_lintegral_of_nonneg_ae` : `0 ≤ᵐ[μ] f → ∫ x, f x ∂μ = ∫⁻ x, f x ∂μ` 4. `tendsto_integral_of_dominated_convergence` : the Lebesgue dominated convergence theorem ## Notes Some tips on how to prove a proposition if the API for the Bochner integral is not enough so that you need to unfold the definition of the Bochner integral and go back to simple functions. One method is to use the theorem `integrable.induction` in the file `set_integral`, which allows you to prove something for an arbitrary measurable + integrable function. Another method is using the following steps. See `integral_eq_lintegral_max_sub_lintegral_min` for a complicated example, which proves that `∫ f = ∫⁻ f⁺ - ∫⁻ f⁻`, with the first integral sign being the Bochner integral of a real-valued function `f : α → ℝ`, and second and third integral sign being the integral on ennreal-valued functions (called `lintegral`). The proof of `integral_eq_lintegral_max_sub_lintegral_min` is scattered in sections with the name `pos_part`. Here are the usual steps of proving that a property `p`, say `∫ f = ∫⁻ f⁺ - ∫⁻ f⁻`, holds for all functions : 1. First go to the `L¹` space. For example, if you see `ennreal.to_real (∫⁻ a, ennreal.of_real $ ∥f a∥)`, that is the norm of `f` in `L¹` space. Rewrite using `l1.norm_of_fun_eq_lintegral_norm`. 2. Show that the set `{f ∈ L¹ | ∫ f = ∫⁻ f⁺ - ∫⁻ f⁻}` is closed in `L¹` using `is_closed_eq`. 3. Show that the property holds for all simple functions `s` in `L¹` space. Typically, you need to convert various notions to their `simple_func` counterpart, using lemmas like `l1.integral_coe_eq_integral`. 4. Since simple functions are dense in `L¹`, ``` univ = closure {s simple} = closure {s simple | ∫ s = ∫⁻ s⁺ - ∫⁻ s⁻} : the property holds for all simple functions ⊆ closure {f | ∫ f = ∫⁻ f⁺ - ∫⁻ f⁻} = {f | ∫ f = ∫⁻ f⁺ - ∫⁻ f⁻} : closure of a closed set is itself ``` Use `is_closed_property` or `dense_range.induction_on` for this argument. ## Notations * `α →ₛ E` : simple functions (defined in `measure_theory/integration`) * `α →₁[μ] E` : functions in L1 space, i.e., equivalence classes of integrable functions (defined in `measure_theory/l1_space`) * `α →₁ₛ[μ] E` : simple functions in L1 space, i.e., equivalence classes of integrable simple functions Note : `ₛ` is typed using `\_s`. Sometimes it shows as a box if font is missing. ## Tags Bochner integral, simple function, function space, Lebesgue dominated convergence theorem -/ noncomputable theory open_locale classical topological_space big_operators namespace measure_theory variables {α E : Type*} [measurable_space α] [linear_order E] [has_zero E] local infixr ` →ₛ `:25 := simple_func namespace simple_func section pos_part /-- Positive part of a simple function. -/ def pos_part (f : α →ₛ E) : α →ₛ E := f.map (λb, max b 0) /-- Negative part of a simple function. -/ def neg_part [has_neg E] (f : α →ₛ E) : α →ₛ E := pos_part (-f) lemma pos_part_map_norm (f : α →ₛ ℝ) : (pos_part f).map norm = pos_part f := begin ext, rw [map_apply, real.norm_eq_abs, abs_of_nonneg], rw [pos_part, map_apply], exact le_max_right _ _ end lemma neg_part_map_norm (f : α →ₛ ℝ) : (neg_part f).map norm = neg_part f := by { rw neg_part, exact pos_part_map_norm _ } lemma pos_part_sub_neg_part (f : α →ₛ ℝ) : f.pos_part - f.neg_part = f := begin simp only [pos_part, neg_part], ext, exact max_zero_sub_eq_self (f a) end end pos_part end simple_func end measure_theory namespace measure_theory open set filter topological_space ennreal emetric variables {α E F : Type*} [measurable_space α] local infixr ` →ₛ `:25 := simple_func namespace simple_func section integral /-! ### The Bochner integral of simple functions Define the Bochner integral of simple functions of the type `α →ₛ β` where `β` is a normed group, and prove basic property of this integral. -/ open finset variables [normed_group E] [measurable_space E] [normed_group F] variables {μ : measure α} /-- For simple functions with a `normed_group` as codomain, being integrable is the same as having finite volume support. -/ lemma integrable_iff_fin_meas_supp {f : α →ₛ E} {μ : measure α} : integrable f μ ↔ f.fin_meas_supp μ := calc integrable f μ ↔ ∫⁻ x, f.map (coe ∘ nnnorm : E → ennreal) x ∂μ < ⊤ : and_iff_right f.measurable ... ↔ (f.map (coe ∘ nnnorm : E → ennreal)).lintegral μ < ⊤ : by rw lintegral_eq_lintegral ... ↔ (f.map (coe ∘ nnnorm : E → ennreal)).fin_meas_supp μ : iff.symm $ fin_meas_supp.iff_lintegral_lt_top $ eventually_of_forall $ λ x, coe_lt_top ... ↔ _ : fin_meas_supp.map_iff $ λ b, coe_eq_zero.trans nnnorm_eq_zero lemma fin_meas_supp.integrable {f : α →ₛ E} (h : f.fin_meas_supp μ) : integrable f μ := integrable_iff_fin_meas_supp.2 h lemma integrable_pair [measurable_space F] {f : α →ₛ E} {g : α →ₛ F} : integrable f μ → integrable g μ → integrable (pair f g) μ := by simpa only [integrable_iff_fin_meas_supp] using fin_meas_supp.pair variables [normed_space ℝ F] /-- Bochner integral of simple functions whose codomain is a real `normed_space`. -/ def integral (μ : measure α) (f : α →ₛ F) : F := ∑ x in f.range, (ennreal.to_real (μ (f ⁻¹' {x}))) • x lemma integral_eq_sum_filter (f : α →ₛ F) (μ) : f.integral μ = ∑ x in f.range.filter (λ x, x ≠ 0), (ennreal.to_real (μ (f ⁻¹' {x}))) • x := eq.symm $ sum_filter_of_ne $ λ x _, mt $ λ h0, h0.symm ▸ smul_zero _ /-- The Bochner integral is equal to a sum over any set that includes `f.range` (except `0`). -/ lemma integral_eq_sum_of_subset {f : α →ₛ F} {μ : measure α} {s : finset F} (hs : f.range.filter (λ x, x ≠ 0) ⊆ s) : f.integral μ = ∑ x in s, (μ (f ⁻¹' {x})).to_real • x := begin rw [simple_func.integral_eq_sum_filter, finset.sum_subset hs], rintro x - hx, rw [finset.mem_filter, not_and_distrib, ne.def, not_not] at hx, rcases hx with hx|rfl; [skip, simp], rw [simple_func.mem_range] at hx, rw [preimage_eq_empty]; simp [disjoint_singleton_left, hx] end /-- Calculate the integral of `g ∘ f : α →ₛ F`, where `f` is an integrable function from `α` to `E` and `g` is a function from `E` to `F`. We require `g 0 = 0` so that `g ∘ f` is integrable. -/ lemma map_integral (f : α →ₛ E) (g : E → F) (hf : integrable f μ) (hg : g 0 = 0) : (f.map g).integral μ = ∑ x in f.range, (ennreal.to_real (μ (f ⁻¹' {x}))) • (g x) := begin -- We start as in the proof of `map_lintegral` simp only [integral, range_map], refine finset.sum_image' _ (assume b hb, _), rcases mem_range.1 hb with ⟨a, rfl⟩, rw [map_preimage_singleton, ← sum_measure_preimage_singleton _ (λ _ _, f.is_measurable_preimage _)], -- Now we use `hf : integrable f μ` to show that `ennreal.to_real` is additive. by_cases ha : g (f a) = 0, { simp only [ha, smul_zero], refine (sum_eq_zero $ λ x hx, _).symm, simp only [mem_filter] at hx, simp [hx.2] }, { rw [to_real_sum, sum_smul], { refine sum_congr rfl (λ x hx, _), simp only [mem_filter] at hx, rw [hx.2] }, { intros x hx, simp only [mem_filter] at hx, refine (integrable_iff_fin_meas_supp.1 hf).meas_preimage_singleton_ne_zero _, exact λ h0, ha (hx.2 ▸ h0.symm ▸ hg) } }, end /-- `simple_func.integral` and `simple_func.lintegral` agree when the integrand has type `α →ₛ ennreal`. But since `ennreal` is not a `normed_space`, we need some form of coercion. See `integral_eq_lintegral` for a simpler version. -/ lemma integral_eq_lintegral' {f : α →ₛ E} {g : E → ennreal} (hf : integrable f μ) (hg0 : g 0 = 0) (hgt : ∀b, g b < ⊤): (f.map (ennreal.to_real ∘ g)).integral μ = ennreal.to_real (∫⁻ a, g (f a) ∂μ) := begin have hf' : f.fin_meas_supp μ := integrable_iff_fin_meas_supp.1 hf, simp only [← map_apply g f, lintegral_eq_lintegral], rw [map_integral f _ hf, map_lintegral, ennreal.to_real_sum], { refine finset.sum_congr rfl (λb hb, _), rw [smul_eq_mul, to_real_mul_to_real, mul_comm] }, { assume a ha, by_cases a0 : a = 0, { rw [a0, hg0, zero_mul], exact with_top.zero_lt_top }, { apply mul_lt_top (hgt a) (hf'.meas_preimage_singleton_ne_zero a0) } }, { simp [hg0] } end variables [normed_space ℝ E] lemma integral_congr {f g : α →ₛ E} (hf : integrable f μ) (h : f =ᵐ[μ] g): f.integral μ = g.integral μ := show ((pair f g).map prod.fst).integral μ = ((pair f g).map prod.snd).integral μ, from begin have inte := integrable_pair hf (hf.congr g.measurable h), rw [map_integral (pair f g) _ inte prod.fst_zero, map_integral (pair f g) _ inte prod.snd_zero], refine finset.sum_congr rfl (assume p hp, _), rcases mem_range.1 hp with ⟨a, rfl⟩, by_cases eq : f a = g a, { dsimp only [pair_apply], rw eq }, { have : μ ((pair f g) ⁻¹' {(f a, g a)}) = 0, { refine measure_mono_null (assume a' ha', _) h, simp only [set.mem_preimage, mem_singleton_iff, pair_apply, prod.mk.inj_iff] at ha', show f a' ≠ g a', rwa [ha'.1, ha'.2] }, simp only [this, pair_apply, zero_smul, ennreal.zero_to_real] }, end /-- `simple_func.bintegral` and `simple_func.integral` agree when the integrand has type `α →ₛ ennreal`. But since `ennreal` is not a `normed_space`, we need some form of coercion. -/ lemma integral_eq_lintegral {f : α →ₛ ℝ} (hf : integrable f μ) (h_pos : 0 ≤ᵐ[μ] f) : f.integral μ = ennreal.to_real (∫⁻ a, ennreal.of_real (f a) ∂μ) := begin have : f =ᵐ[μ] f.map (ennreal.to_real ∘ ennreal.of_real) := h_pos.mono (λ a h, (ennreal.to_real_of_real h).symm), rw [← integral_eq_lintegral' hf], { exact integral_congr hf this }, { exact ennreal.of_real_zero }, { assume b, rw ennreal.lt_top_iff_ne_top, exact ennreal.of_real_ne_top } end lemma integral_add {f g : α →ₛ E} (hf : integrable f μ) (hg : integrable g μ) : integral μ (f + g) = integral μ f + integral μ g := calc integral μ (f + g) = ∑ x in (pair f g).range, ennreal.to_real (μ ((pair f g) ⁻¹' {x})) • (x.fst + x.snd) : begin rw [add_eq_map₂, map_integral (pair f g)], { exact integrable_pair hf hg }, { simp only [add_zero, prod.fst_zero, prod.snd_zero] } end ... = ∑ x in (pair f g).range, (ennreal.to_real (μ ((pair f g) ⁻¹' {x})) • x.fst + ennreal.to_real (μ ((pair f g) ⁻¹' {x})) • x.snd) : finset.sum_congr rfl $ assume a ha, smul_add _ _ _ ... = ∑ x in (pair f g).range, ennreal.to_real (μ ((pair f g) ⁻¹' {x})) • x.fst + ∑ x in (pair f g).range, ennreal.to_real (μ ((pair f g) ⁻¹' {x})) • x.snd : by rw finset.sum_add_distrib ... = ((pair f g).map prod.fst).integral μ + ((pair f g).map prod.snd).integral μ : begin rw [map_integral (pair f g), map_integral (pair f g)], { exact integrable_pair hf hg }, { refl }, { exact integrable_pair hf hg }, { refl } end ... = integral μ f + integral μ g : rfl lemma integral_neg {f : α →ₛ E} (hf : integrable f μ) : integral μ (-f) = - integral μ f := calc integral μ (-f) = integral μ (f.map (has_neg.neg)) : rfl ... = - integral μ f : begin rw [map_integral f _ hf neg_zero, integral, ← sum_neg_distrib], refine finset.sum_congr rfl (λx h, smul_neg _ _), end lemma integral_sub [borel_space E] {f g : α →ₛ E} (hf : integrable f μ) (hg : integrable g μ) : integral μ (f - g) = integral μ f - integral μ g := begin rw [sub_eq_add_neg, integral_add hf, integral_neg hg, sub_eq_add_neg], exact hg.neg end lemma integral_smul (r : ℝ) {f : α →ₛ E} (hf : integrable f μ) : integral μ (r • f) = r • integral μ f := calc integral μ (r • f) = ∑ x in f.range, ennreal.to_real (μ (f ⁻¹' {x})) • r • x : by rw [smul_eq_map r f, map_integral f _ hf (smul_zero _)] ... = ∑ x in f.range, ((ennreal.to_real (μ (f ⁻¹' {x}))) * r) • x : finset.sum_congr rfl $ λb hb, by apply smul_smul ... = r • integral μ f : by simp only [integral, smul_sum, smul_smul, mul_comm] lemma norm_integral_le_integral_norm (f : α →ₛ E) (hf : integrable f μ) : ∥f.integral μ∥ ≤ (f.map norm).integral μ := begin rw [map_integral f norm hf norm_zero, integral], calc ∥∑ x in f.range, ennreal.to_real (μ (f ⁻¹' {x})) • x∥ ≤ ∑ x in f.range, ∥ennreal.to_real (μ (f ⁻¹' {x})) • x∥ : norm_sum_le _ _ ... = ∑ x in f.range, ennreal.to_real (μ (f ⁻¹' {x})) • ∥x∥ : begin refine finset.sum_congr rfl (λb hb, _), rw [norm_smul, smul_eq_mul, real.norm_eq_abs, abs_of_nonneg to_real_nonneg] end end lemma integral_add_measure {ν} (f : α →ₛ E) (hf : integrable f (μ + ν)) : f.integral (μ + ν) = f.integral μ + f.integral ν := begin simp only [integral_eq_sum_filter, ← sum_add_distrib, ← add_smul, measure.add_apply], refine sum_congr rfl (λ x hx, _), rw [to_real_add]; refine ne_of_lt ((integrable_iff_fin_meas_supp.1 _).meas_preimage_singleton_ne_zero (mem_filter.1 hx).2), exacts [hf.left_of_add_measure, hf.right_of_add_measure] end end integral end simple_func namespace l1 open ae_eq_fun variables [normed_group E] [second_countable_topology E] [measurable_space E] [borel_space E] [normed_group F] [second_countable_topology F] [measurable_space F] [borel_space F] {μ : measure α} variables (α E μ) -- We use `Type*` instead of `add_subgroup` because otherwise we loose dot notation. /-- `l1.simple_func` is a subspace of L1 consisting of equivalence classes of an integrable simple function. -/ def simple_func : Type* := ↥({ carrier := {f : α →₁[μ] E | ∃ (s : α →ₛ E), (ae_eq_fun.mk s s.measurable : α →ₘ[μ] E) = f}, zero_mem' := ⟨0, rfl⟩, add_mem' := λ f g ⟨s, hs⟩ ⟨t, ht⟩, ⟨s + t, by simp only [coe_add, ← hs, ← ht, mk_add_mk, ← simple_func.coe_add]⟩, neg_mem' := λ f ⟨s, hs⟩, ⟨-s, by simp only [coe_neg, ← hs, neg_mk, ← simple_func.coe_neg]⟩ } : add_subgroup (α →₁[μ] E)) variables {α E μ} notation α ` →₁ₛ[`:25 μ `] ` E := measure_theory.l1.simple_func α E μ namespace simple_func section instances /-! Simple functions in L1 space form a `normed_space`. -/ instance : has_coe (α →₁ₛ[μ] E) (α →₁[μ] E) := coe_subtype instance : has_coe_to_fun (α →₁ₛ[μ] E) := ⟨λ f, α → E, λ f, ⇑(f : α →₁[μ] E)⟩ @[simp, norm_cast] lemma coe_coe (f : α →₁ₛ[μ] E) : ⇑(f : α →₁[μ] E) = f := rfl protected lemma eq {f g : α →₁ₛ[μ] E} : (f : α →₁[μ] E) = (g : α →₁[μ] E) → f = g := subtype.eq protected lemma eq' {f g : α →₁ₛ[μ] E} : (f : α →ₘ[μ] E) = (g : α →ₘ[μ] E) → f = g := subtype.eq ∘ subtype.eq @[norm_cast] protected lemma eq_iff {f g : α →₁ₛ[μ] E} : (f : α →₁[μ] E) = g ↔ f = g := subtype.ext_iff.symm @[norm_cast] protected lemma eq_iff' {f g : α →₁ₛ[μ] E} : (f : α →ₘ[μ] E) = g ↔ f = g := iff.intro (simple_func.eq') (congr_arg _) /-- L1 simple functions forms a `emetric_space`, with the emetric being inherited from L1 space, i.e., `edist f g = ∫⁻ a, edist (f a) (g a)`. Not declared as an instance as `α →₁ₛ[μ] β` will only be useful in the construction of the Bochner integral. -/ protected def emetric_space : emetric_space (α →₁ₛ[μ] E) := subtype.emetric_space /-- L1 simple functions forms a `metric_space`, with the metric being inherited from L1 space, i.e., `dist f g = ennreal.to_real (∫⁻ a, edist (f a) (g a)`). Not declared as an instance as `α →₁ₛ[μ] β` will only be useful in the construction of the Bochner integral. -/ protected def metric_space : metric_space (α →₁ₛ[μ] E) := subtype.metric_space local attribute [instance] simple_func.metric_space simple_func.emetric_space /-- Functions `α →₁ₛ[μ] E` form an additive commutative group. -/ local attribute [instance, priority 10000] protected def add_comm_group : add_comm_group (α →₁ₛ[μ] E) := add_subgroup.to_add_comm_group _ instance : inhabited (α →₁ₛ[μ] E) := ⟨0⟩ @[simp, norm_cast] lemma coe_zero : ((0 : α →₁ₛ[μ] E) : α →₁[μ] E) = 0 := rfl @[simp, norm_cast] lemma coe_add (f g : α →₁ₛ[μ] E) : ((f + g : α →₁ₛ[μ] E) : α →₁[μ] E) = f + g := rfl @[simp, norm_cast] lemma coe_neg (f : α →₁ₛ[μ] E) : ((-f : α →₁ₛ[μ] E) : α →₁[μ] E) = -f := rfl @[simp, norm_cast] lemma coe_sub (f g : α →₁ₛ[μ] E) : ((f - g : α →₁ₛ[μ] E) : α →₁[μ] E) = f - g := rfl @[simp] lemma edist_eq (f g : α →₁ₛ[μ] E) : edist f g = edist (f : α →₁[μ] E) (g : α →₁[μ] E) := rfl @[simp] lemma dist_eq (f g : α →₁ₛ[μ] E) : dist f g = dist (f : α →₁[μ] E) (g : α →₁[μ] E) := rfl /-- The norm on `α →₁ₛ[μ] E` is inherited from L1 space. That is, `∥f∥ = ∫⁻ a, edist (f a) 0`. Not declared as an instance as `α →₁ₛ[μ] E` will only be useful in the construction of the Bochner integral. -/ protected def has_norm : has_norm (α →₁ₛ[μ] E) := ⟨λf, ∥(f : α →₁[μ] E)∥⟩ local attribute [instance] simple_func.has_norm lemma norm_eq (f : α →₁ₛ[μ] E) : ∥f∥ = ∥(f : α →₁[μ] E)∥ := rfl lemma norm_eq' (f : α →₁ₛ[μ] E) : ∥f∥ = ennreal.to_real (edist (f : α →ₘ[μ] E) 0) := rfl /-- Not declared as an instance as `α →₁ₛ[μ] E` will only be useful in the construction of the Bochner integral. -/ protected def normed_group : normed_group (α →₁ₛ[μ] E) := normed_group.of_add_dist (λ x, rfl) $ by { intros, simp only [dist_eq, coe_add, l1.dist_eq, l1.coe_add], rw edist_add_right } variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E] /-- Not declared as an instance as `α →₁ₛ[μ] E` will only be useful in the construction of the Bochner integral. -/ protected def has_scalar : has_scalar 𝕜 (α →₁ₛ[μ] E) := ⟨λk f, ⟨k • f, begin rcases f with ⟨f, ⟨s, hs⟩⟩, use k • s, rw [coe_smul, subtype.coe_mk, ← hs], refl end ⟩⟩ local attribute [instance, priority 10000] simple_func.has_scalar @[simp, norm_cast] lemma coe_smul (c : 𝕜) (f : α →₁ₛ[μ] E) : ((c • f : α →₁ₛ[μ] E) : α →₁[μ] E) = c • (f : α →₁[μ] E) := rfl /-- Not declared as an instance as `α →₁ₛ[μ] E` will only be useful in the construction of the Bochner integral. -/ protected def semimodule : semimodule 𝕜 (α →₁ₛ[μ] E) := { one_smul := λf, simple_func.eq (by { simp only [coe_smul], exact one_smul _ _ }), mul_smul := λx y f, simple_func.eq (by { simp only [coe_smul], exact mul_smul _ _ _ }), smul_add := λx f g, simple_func.eq (by { simp only [coe_smul, coe_add], exact smul_add _ _ _ }), smul_zero := λx, simple_func.eq (by { simp only [coe_zero, coe_smul], exact smul_zero _ }), add_smul := λx y f, simple_func.eq (by { simp only [coe_smul], exact add_smul _ _ _ }), zero_smul := λf, simple_func.eq (by { simp only [coe_smul], exact zero_smul _ _ }) } local attribute [instance] simple_func.normed_group simple_func.semimodule /-- Not declared as an instance as `α →₁ₛ[μ] E` will only be useful in the construction of the Bochner integral. -/ protected def normed_space : normed_space 𝕜 (α →₁ₛ[μ] E) := ⟨ λc f, by { rw [norm_eq, norm_eq, coe_smul, norm_smul] } ⟩ end instances local attribute [instance] simple_func.normed_group simple_func.normed_space section of_simple_func /-- Construct the equivalence class `[f]` of an integrable simple function `f`. -/ @[reducible] def of_simple_func (f : α →ₛ E) (hf : integrable f μ) : (α →₁ₛ[μ] E) := ⟨l1.of_fun f hf, ⟨f, rfl⟩⟩ lemma of_simple_func_eq_of_fun (f : α →ₛ E) (hf : integrable f μ) : (of_simple_func f hf : α →₁[μ] E) = l1.of_fun f hf := rfl lemma of_simple_func_eq_mk (f : α →ₛ E) (hf : integrable f μ) : (of_simple_func f hf : α →ₘ[μ] E) = ae_eq_fun.mk f f.measurable := rfl lemma of_simple_func_zero : of_simple_func (0 : α →ₛ E) (integrable_zero α E μ) = 0 := rfl lemma of_simple_func_add (f g : α →ₛ E) (hf : integrable f μ) (hg : integrable g μ) : of_simple_func (f + g) (hf.add hg) = of_simple_func f hf + of_simple_func g hg := rfl lemma of_simple_func_neg (f : α →ₛ E) (hf : integrable f μ) : of_simple_func (-f) hf.neg = -of_simple_func f hf := rfl lemma of_simple_func_sub (f g : α →ₛ E) (hf : integrable f μ) (hg : integrable g μ) : of_simple_func (f - g) (hf.sub hg) = of_simple_func f hf - of_simple_func g hg := rfl variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E] lemma of_simple_func_smul (f : α →ₛ E) (hf : integrable f μ) (c : 𝕜) : of_simple_func (c • f) (hf.smul c) = c • of_simple_func f hf := rfl lemma norm_of_simple_func (f : α →ₛ E) (hf : integrable f μ) : ∥of_simple_func f hf∥ = ennreal.to_real (∫⁻ a, edist (f a) 0 ∂μ) := rfl end of_simple_func section to_simple_func /-- Find a representative of a `l1.simple_func`. -/ def to_simple_func (f : α →₁ₛ[μ] E) : α →ₛ E := classical.some f.2 /-- `f.to_simple_func` is measurable. -/ protected lemma measurable (f : α →₁ₛ[μ] E) : measurable f.to_simple_func := f.to_simple_func.measurable /-- `f.to_simple_func` is integrable. -/ protected lemma integrable (f : α →₁ₛ[μ] E) : integrable f.to_simple_func μ := let h := classical.some_spec f.2 in (integrable_mk f.measurable).1 $ h.symm ▸ (f : α →₁[μ] E).2 lemma of_simple_func_to_simple_func (f : α →₁ₛ[μ] E) : of_simple_func (f.to_simple_func) f.integrable = f := by { rw ← simple_func.eq_iff', exact classical.some_spec f.2 } lemma to_simple_func_of_simple_func (f : α →ₛ E) (hfi : integrable f μ) : (of_simple_func f hfi).to_simple_func =ᵐ[μ] f := by { rw ← mk_eq_mk, exact classical.some_spec (of_simple_func f hfi).2 } lemma to_simple_func_eq_to_fun (f : α →₁ₛ[μ] E) : f.to_simple_func =ᵐ[μ] f := begin rw [← of_fun_eq_of_fun f.to_simple_func f f.integrable (f : α →₁[μ] E).integrable, ← l1.eq_iff], simp only [of_fun_eq_mk, ← coe_coe, mk_to_fun], exact classical.some_spec f.coe_prop end variables (α E) lemma zero_to_simple_func : (0 : α →₁ₛ[μ] E).to_simple_func =ᵐ[μ] 0 := begin filter_upwards [to_simple_func_eq_to_fun (0 : α →₁ₛ[μ] E), l1.zero_to_fun α E], assume a h₁ h₂, rwa h₁, end variables {α E} lemma add_to_simple_func (f g : α →₁ₛ[μ] E) : (f + g).to_simple_func =ᵐ[μ] f.to_simple_func + g.to_simple_func := begin filter_upwards [to_simple_func_eq_to_fun (f + g), to_simple_func_eq_to_fun f, to_simple_func_eq_to_fun g, l1.add_to_fun (f : α →₁[μ] E) g], assume a, simp only [← coe_coe, coe_add, pi.add_apply], iterate 4 { assume h, rw h } end lemma neg_to_simple_func (f : α →₁ₛ[μ] E) : (-f).to_simple_func =ᵐ[μ] - f.to_simple_func := begin filter_upwards [to_simple_func_eq_to_fun (-f), to_simple_func_eq_to_fun f, l1.neg_to_fun (f : α →₁[μ] E)], assume a, simp only [pi.neg_apply, coe_neg, ← coe_coe], repeat { assume h, rw h } end lemma sub_to_simple_func (f g : α →₁ₛ[μ] E) : (f - g).to_simple_func =ᵐ[μ] f.to_simple_func - g.to_simple_func := begin filter_upwards [to_simple_func_eq_to_fun (f - g), to_simple_func_eq_to_fun f, to_simple_func_eq_to_fun g, l1.sub_to_fun (f : α →₁[μ] E) g], assume a, simp only [coe_sub, pi.sub_apply, ← coe_coe], repeat { assume h, rw h } end variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E] lemma smul_to_simple_func (k : 𝕜) (f : α →₁ₛ[μ] E) : (k • f).to_simple_func =ᵐ[μ] k • f.to_simple_func := begin filter_upwards [to_simple_func_eq_to_fun (k • f), to_simple_func_eq_to_fun f, l1.smul_to_fun k (f : α →₁[μ] E)], assume a, simp only [pi.smul_apply, coe_smul, ← coe_coe], repeat { assume h, rw h } end lemma lintegral_edist_to_simple_func_lt_top (f g : α →₁ₛ[μ] E) : ∫⁻ (x : α), edist ((to_simple_func f) x) ((to_simple_func g) x) ∂μ < ⊤ := begin rw lintegral_rw₂ (to_simple_func_eq_to_fun f) (to_simple_func_eq_to_fun g), exact lintegral_edist_to_fun_lt_top _ _ end lemma dist_to_simple_func (f g : α →₁ₛ[μ] E) : dist f g = ennreal.to_real (∫⁻ x, edist (f.to_simple_func x) (g.to_simple_func x) ∂μ) := begin rw [dist_eq, l1.dist_to_fun, ennreal.to_real_eq_to_real], { rw lintegral_rw₂, repeat { exact ae_eq_symm (to_simple_func_eq_to_fun _) } }, { exact l1.lintegral_edist_to_fun_lt_top _ _ }, { exact lintegral_edist_to_simple_func_lt_top _ _ } end lemma norm_to_simple_func (f : α →₁ₛ[μ] E) : ∥f∥ = ennreal.to_real (∫⁻ (a : α), nnnorm ((to_simple_func f) a) ∂μ) := calc ∥f∥ = ennreal.to_real (∫⁻x, edist (f.to_simple_func x) ((0 : α →₁ₛ[μ] E).to_simple_func x) ∂μ) : begin rw [← dist_zero_right, dist_to_simple_func] end ... = ennreal.to_real (∫⁻ (x : α), (coe ∘ nnnorm) (f.to_simple_func x) ∂μ) : begin rw lintegral_nnnorm_eq_lintegral_edist, have : ∫⁻ x, edist ((to_simple_func f) x) ((to_simple_func (0 : α →₁ₛ[μ] E)) x) ∂μ = ∫⁻ x, edist ((to_simple_func f) x) 0 ∂μ, { refine lintegral_congr_ae ((zero_to_simple_func α E).mono (λ a h, _)), rw [h, pi.zero_apply] }, rw [ennreal.to_real_eq_to_real], { exact this }, { exact lintegral_edist_to_simple_func_lt_top _ _ }, { rw ← this, exact lintegral_edist_to_simple_func_lt_top _ _ } end lemma norm_eq_integral (f : α →₁ₛ[μ] E) : ∥f∥ = (f.to_simple_func.map norm).integral μ := -- calc ∥f∥ = ennreal.to_real (∫⁻ (x : α), (coe ∘ nnnorm) (f.to_simple_func x) ∂μ) : -- by { rw norm_to_simple_func } -- ... = (f.to_simple_func.map norm).integral μ : begin rw [norm_to_simple_func, simple_func.integral_eq_lintegral], { simp only [simple_func.map_apply, of_real_norm_eq_coe_nnnorm] }, { exact f.integrable.norm }, { exact eventually_of_forall (λ x, norm_nonneg _) } end end to_simple_func section coe_to_l1 protected lemma uniform_continuous : uniform_continuous (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)) := uniform_continuous_comap protected lemma uniform_embedding : uniform_embedding (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)) := uniform_embedding_comap subtype.val_injective protected lemma uniform_inducing : uniform_inducing (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)) := simple_func.uniform_embedding.to_uniform_inducing protected lemma dense_embedding : dense_embedding (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)) := begin apply simple_func.uniform_embedding.dense_embedding, rintros ⟨⟨f, hfm⟩, hfi⟩, rw mem_closure_iff_seq_limit, have hfi' := (integrable_mk hfm).1 hfi, refine ⟨λ n, ↑(of_simple_func (simple_func.approx_on f hfm univ 0 trivial n) (simple_func.integrable_approx_on_univ hfi' n)), λ n, mem_range_self _, _⟩, rw tendsto_iff_edist_tendsto_0, simpa [edist_mk_mk] using simple_func.tendsto_approx_on_univ_l1_edist hfi' end protected lemma dense_inducing : dense_inducing (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)) := simple_func.dense_embedding.to_dense_inducing protected lemma dense_range : dense_range (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)) := simple_func.dense_inducing.dense variables (𝕜 : Type*) [normed_field 𝕜] [normed_space 𝕜 E] variables (α E) /-- The uniform and dense embedding of L1 simple functions into L1 functions. -/ def coe_to_l1 : (α →₁ₛ[μ] E) →L[𝕜] (α →₁[μ] E) := { to_fun := (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)), map_add' := λf g, rfl, map_smul' := λk f, rfl, cont := l1.simple_func.uniform_continuous.continuous, } variables {α E 𝕜} end coe_to_l1 section pos_part /-- Positive part of a simple function in L1 space. -/ def pos_part (f : α →₁ₛ[μ] ℝ) : α →₁ₛ[μ] ℝ := ⟨l1.pos_part (f : α →₁[μ] ℝ), begin rcases f with ⟨f, s, hsf⟩, use s.pos_part, simp only [subtype.coe_mk, l1.coe_pos_part, ← hsf, ae_eq_fun.pos_part_mk, simple_func.pos_part, simple_func.coe_map] end ⟩ /-- Negative part of a simple function in L1 space. -/ def neg_part (f : α →₁ₛ[μ] ℝ) : α →₁ₛ[μ] ℝ := pos_part (-f) @[norm_cast] lemma coe_pos_part (f : α →₁ₛ[μ] ℝ) : (f.pos_part : α →₁[μ] ℝ) = (f : α →₁[μ] ℝ).pos_part := rfl @[norm_cast] lemma coe_neg_part (f : α →₁ₛ[μ] ℝ) : (f.neg_part : α →₁[μ] ℝ) = (f : α →₁[μ] ℝ).neg_part := rfl end pos_part section simple_func_integral /-! Define the Bochner integral on `α →₁ₛ[μ] E` and prove basic properties of this integral. -/ variables [normed_space ℝ E] /-- The Bochner integral over simple functions in l1 space. -/ def integral (f : α →₁ₛ[μ] E) : E := (f.to_simple_func).integral μ lemma integral_eq_integral (f : α →₁ₛ[μ] E) : integral f = (f.to_simple_func).integral μ := rfl lemma integral_eq_lintegral {f : α →₁ₛ[μ] ℝ} (h_pos : 0 ≤ᵐ[μ] f.to_simple_func) : integral f = ennreal.to_real (∫⁻ a, ennreal.of_real (f.to_simple_func a) ∂μ) := by rw [integral, simple_func.integral_eq_lintegral f.integrable h_pos] lemma integral_congr {f g : α →₁ₛ[μ] E} (h : f.to_simple_func =ᵐ[μ] g.to_simple_func) : integral f = integral g := simple_func.integral_congr f.integrable h lemma integral_add (f g : α →₁ₛ[μ] E) : integral (f + g) = integral f + integral g := begin simp only [integral], rw ← simple_func.integral_add f.integrable g.integrable, apply measure_theory.simple_func.integral_congr (f + g).integrable, apply add_to_simple_func end lemma integral_smul (r : ℝ) (f : α →₁ₛ[μ] E) : integral (r • f) = r • integral f := begin simp only [integral], rw ← simple_func.integral_smul _ f.integrable, apply measure_theory.simple_func.integral_congr (r • f).integrable, apply smul_to_simple_func end lemma norm_integral_le_norm (f : α →₁ₛ[μ] E) : ∥ integral f ∥ ≤ ∥f∥ := begin rw [integral, norm_eq_integral], exact f.to_simple_func.norm_integral_le_integral_norm f.integrable end /-- The Bochner integral over simple functions in l1 space as a continuous linear map. -/ def integral_clm : (α →₁ₛ[μ] E) →L[ℝ] E := linear_map.mk_continuous ⟨integral, integral_add, integral_smul⟩ 1 (λf, le_trans (norm_integral_le_norm _) $ by rw one_mul) local notation `Integral` := @integral_clm α E _ _ _ _ _ μ _ open continuous_linear_map lemma norm_Integral_le_one : ∥Integral∥ ≤ 1 := linear_map.mk_continuous_norm_le _ (zero_le_one) _ section pos_part lemma pos_part_to_simple_func (f : α →₁ₛ[μ] ℝ) : f.pos_part.to_simple_func =ᵐ[μ] f.to_simple_func.pos_part := begin have eq : ∀ a, f.to_simple_func.pos_part a = max (f.to_simple_func a) 0 := λa, rfl, have ae_eq : ∀ᵐ a ∂μ, f.pos_part.to_simple_func a = max (f.to_simple_func a) 0, { filter_upwards [to_simple_func_eq_to_fun f.pos_part, pos_part_to_fun (f : α →₁[μ] ℝ), to_simple_func_eq_to_fun f], assume a h₁ h₂ h₃, rw [h₁, ← coe_coe, coe_pos_part, h₂, coe_coe, ← h₃] }, refine ae_eq.mono (assume a h, _), rw [h, eq] end lemma neg_part_to_simple_func (f : α →₁ₛ[μ] ℝ) : f.neg_part.to_simple_func =ᵐ[μ] f.to_simple_func.neg_part := begin rw [simple_func.neg_part, measure_theory.simple_func.neg_part], filter_upwards [pos_part_to_simple_func (-f), neg_to_simple_func f], assume a h₁ h₂, rw h₁, show max _ _ = max _ _, rw h₂, refl end lemma integral_eq_norm_pos_part_sub (f : α →₁ₛ[μ] ℝ) : f.integral = ∥f.pos_part∥ - ∥f.neg_part∥ := begin -- Convert things in `L¹` to their `simple_func` counterpart have ae_eq₁ : f.to_simple_func.pos_part =ᵐ[μ] (f.pos_part).to_simple_func.map norm, { filter_upwards [pos_part_to_simple_func f], assume a h, rw [simple_func.map_apply, h], conv_lhs { rw [← simple_func.pos_part_map_norm, simple_func.map_apply] } }, -- Convert things in `L¹` to their `simple_func` counterpart have ae_eq₂ : f.to_simple_func.neg_part =ᵐ[μ] (f.neg_part).to_simple_func.map norm, { filter_upwards [neg_part_to_simple_func f], assume a h, rw [simple_func.map_apply, h], conv_lhs { rw [← simple_func.neg_part_map_norm, simple_func.map_apply] } }, -- Convert things in `L¹` to their `simple_func` counterpart have ae_eq : ∀ᵐ a ∂μ, f.to_simple_func.pos_part a - f.to_simple_func.neg_part a = (f.pos_part).to_simple_func.map norm a - (f.neg_part).to_simple_func.map norm a, { filter_upwards [ae_eq₁, ae_eq₂], assume a h₁ h₂, rw [h₁, h₂] }, rw [integral, norm_eq_integral, norm_eq_integral, ← simple_func.integral_sub], { show f.to_simple_func.integral μ = ((f.pos_part.to_simple_func).map norm - f.neg_part.to_simple_func.map norm).integral μ, apply measure_theory.simple_func.integral_congr f.integrable, filter_upwards [ae_eq₁, ae_eq₂], assume a h₁ h₂, show _ = _ - _, rw [← h₁, ← h₂], have := f.to_simple_func.pos_part_sub_neg_part, conv_lhs {rw ← this}, refl }, { exact f.integrable.max_zero.congr (measure_theory.simple_func.measurable _) ae_eq₁ }, { exact f.integrable.neg.max_zero.congr (measure_theory.simple_func.measurable _) ae_eq₂ } end end pos_part end simple_func_integral end simple_func open simple_func variables [normed_space ℝ E] [normed_space ℝ F] [complete_space E] section integration_in_l1 local notation `to_l1` := coe_to_l1 α E ℝ local attribute [instance] simple_func.normed_group simple_func.normed_space open continuous_linear_map /-- The Bochner integral in l1 space as a continuous linear map. -/ def integral_clm : (α →₁[μ] E) →L[ℝ] E := integral_clm.extend to_l1 simple_func.dense_range simple_func.uniform_inducing /-- The Bochner integral in l1 space -/ def integral (f : α →₁[μ] E) : E := integral_clm f lemma integral_eq (f : α →₁[μ] E) : integral f = integral_clm f := rfl @[norm_cast] lemma simple_func.integral_l1_eq_integral (f : α →₁ₛ[μ] E) : integral (f : α →₁[μ] E) = f.integral := uniformly_extend_of_ind simple_func.uniform_inducing simple_func.dense_range simple_func.integral_clm.uniform_continuous _ variables (α E) @[simp] lemma integral_zero : integral (0 : α →₁[μ] E) = 0 := map_zero integral_clm variables {α E} lemma integral_add (f g : α →₁[μ] E) : integral (f + g) = integral f + integral g := map_add integral_clm f g lemma integral_neg (f : α →₁[μ] E) : integral (-f) = - integral f := map_neg integral_clm f lemma integral_sub (f g : α →₁[μ] E) : integral (f - g) = integral f - integral g := map_sub integral_clm f g lemma integral_smul (r : ℝ) (f : α →₁[μ] E) : integral (r • f) = r • integral f := map_smul r integral_clm f local notation `Integral` := @integral_clm α E _ _ _ _ _ μ _ _ local notation `sIntegral` := @simple_func.integral_clm α E _ _ _ _ _ μ _ lemma norm_Integral_le_one : ∥Integral∥ ≤ 1 := calc ∥Integral∥ ≤ (1 : nnreal) * ∥sIntegral∥ : op_norm_extend_le _ _ _ $ λs, by {rw [nnreal.coe_one, one_mul], refl} ... = ∥sIntegral∥ : one_mul _ ... ≤ 1 : norm_Integral_le_one lemma norm_integral_le (f : α →₁[μ] E) : ∥integral f∥ ≤ ∥f∥ := calc ∥integral f∥ = ∥Integral f∥ : rfl ... ≤ ∥Integral∥ * ∥f∥ : le_op_norm _ _ ... ≤ 1 * ∥f∥ : mul_le_mul_of_nonneg_right norm_Integral_le_one $ norm_nonneg _ ... = ∥f∥ : one_mul _ @[continuity] lemma continuous_integral : continuous (λ (f : α →₁[μ] E), f.integral) := by simp [l1.integral, l1.integral_clm.continuous] section pos_part lemma integral_eq_norm_pos_part_sub (f : α →₁[μ] ℝ) : integral f = ∥pos_part f∥ - ∥neg_part f∥ := begin -- Use `is_closed_property` and `is_closed_eq` refine @is_closed_property _ _ _ (coe : (α →₁ₛ[μ] ℝ) → (α →₁[μ] ℝ)) (λ f : α →₁[μ] ℝ, integral f = ∥pos_part f∥ - ∥neg_part f∥) l1.simple_func.dense_range (is_closed_eq _ _) _ f, { exact cont _ }, { refine continuous.sub (continuous_norm.comp l1.continuous_pos_part) (continuous_norm.comp l1.continuous_neg_part) }, -- Show that the property holds for all simple functions in the `L¹` space. { assume s, norm_cast, rw [← simple_func.norm_eq, ← simple_func.norm_eq], exact simple_func.integral_eq_norm_pos_part_sub _} end end pos_part end integration_in_l1 end l1 variables [normed_group E] [second_countable_topology E] [normed_space ℝ E] [complete_space E] [measurable_space E] [borel_space E] [normed_group F] [second_countable_topology F] [normed_space ℝ F] [complete_space F] [measurable_space F] [borel_space F] /-- The Bochner integral -/ def integral (μ : measure α) (f : α → E) : E := if hf : integrable f μ then (l1.of_fun f hf).integral else 0 /-! In the notation for integrals, an expression like `∫ x, g ∥x∥ ∂μ` will not be parsed correctly, and needs parentheses. We do not set the binding power of `r` to `0`, because then `∫ x, f x = 0` will be parsed incorrectly. -/ notation `∫` binders `, ` r:(scoped:60 f, f) ` ∂` μ:70 := integral μ r notation `∫` binders `, ` r:(scoped:60 f, integral volume f) := r notation `∫` binders ` in ` s `, ` r:(scoped:60 f, f) ` ∂` μ:70 := integral (measure.restrict μ s) r notation `∫` binders ` in ` s `, ` r:(scoped:60 f, integral (measure.restrict volume s) f) := r section properties open continuous_linear_map measure_theory.simple_func variables {f g : α → E} {μ : measure α} lemma integral_eq (f : α → E) (hf : integrable f μ) : ∫ a, f a ∂μ = (l1.of_fun f hf).integral := dif_pos hf lemma l1.integral_eq_integral (f : α →₁[μ] E) : f.integral = ∫ a, f a ∂μ := by rw [integral_eq, l1.of_fun_to_fun] lemma integral_undef (h : ¬ integrable f μ) : ∫ a, f a ∂μ = 0 := dif_neg h lemma integral_non_measurable (h : ¬ measurable f) : ∫ a, f a ∂μ = 0 := integral_undef $ not_and_of_not_left _ h variables (α E) lemma integral_zero : ∫ a : α, (0:E) ∂μ = 0 := by rw [integral_eq, l1.of_fun_zero, l1.integral_zero] @[simp] lemma integral_zero' : integral μ (0 : α → E) = 0 := integral_zero α E variables {α E} lemma integral_add (hf : integrable f μ) (hg : integrable g μ) : ∫ a, f a + g a ∂μ = ∫ a, f a ∂μ + ∫ a, g a ∂μ := by { rw [integral_eq, integral_eq f hf, integral_eq g hg, ← l1.integral_add, ← l1.of_fun_add], refl } lemma integral_add' (hf : integrable f μ) (hg : integrable g μ) : ∫ a, (f + g) a ∂μ = ∫ a, f a ∂μ + ∫ a, g a ∂μ := integral_add hf hg lemma integral_neg (f : α → E) : ∫ a, -f a ∂μ = - ∫ a, f a ∂μ := begin by_cases hf : integrable f μ, { rw [integral_eq f hf, integral_eq (λa, - f a) hf.neg, ← l1.integral_neg, ← l1.of_fun_neg], refl }, { rw [integral_undef hf, integral_undef, neg_zero], rwa [← integrable_neg_iff] at hf } end lemma integral_neg' (f : α → E) : ∫ a, (-f) a ∂μ = - ∫ a, f a ∂μ := integral_neg f lemma integral_sub (hf : integrable f μ) (hg : integrable g μ) : ∫ a, f a - g a ∂μ = ∫ a, f a ∂μ - ∫ a, g a ∂μ := by { rw [sub_eq_add_neg, ← integral_neg], exact integral_add hf hg.neg } lemma integral_sub' (hf : integrable f μ) (hg : integrable g μ) : ∫ a, (f - g) a ∂μ = ∫ a, f a ∂μ - ∫ a, g a ∂μ := integral_sub hf hg lemma integral_smul (r : ℝ) (f : α → E) : ∫ a, r • (f a) ∂μ = r • ∫ a, f a ∂μ := begin by_cases hf : integrable f μ, { rw [integral_eq f hf, integral_eq (λa, r • (f a)), l1.of_fun_smul, l1.integral_smul] }, { by_cases hr : r = 0, { simp only [hr, measure_theory.integral_zero, zero_smul] }, have hf' : ¬ integrable (λ x, r • f x) μ, { change ¬ integrable (r • f) μ, rwa [integrable_smul_iff hr f] }, rw [integral_undef hf, integral_undef hf', smul_zero] } end lemma integral_mul_left (r : ℝ) (f : α → ℝ) : ∫ a, r * (f a) ∂μ = r * ∫ a, f a ∂μ := integral_smul r f lemma integral_mul_right (r : ℝ) (f : α → ℝ) : ∫ a, (f a) * r ∂μ = ∫ a, f a ∂μ * r := by { simp only [mul_comm], exact integral_mul_left r f } lemma integral_div (r : ℝ) (f : α → ℝ) : ∫ a, (f a) / r ∂μ = ∫ a, f a ∂μ / r := integral_mul_right r⁻¹ f lemma integral_congr_ae (hfm : measurable f) (hgm : measurable g) (h : f =ᵐ[μ] g) : ∫ a, f a ∂μ = ∫ a, g a ∂μ := begin by_cases hfi : integrable f μ, { have hgi : integrable g μ := hfi.congr hgm h, rw [integral_eq f hfi, integral_eq g hgi, (l1.of_fun_eq_of_fun f g hfi hgi).2 h] }, { have hgi : ¬ integrable g μ, { rw integrable_congr hfm hgm h at hfi, exact hfi }, rw [integral_undef hfi, integral_undef hgi] }, end @[simp] lemma l1.integral_of_fun_eq_integral {f : α → E} (hf : integrable f μ) : ∫ a, (l1.of_fun f hf) a ∂μ = ∫ a, f a ∂μ := integral_congr_ae (l1.measurable _) hf.measurable (l1.to_fun_of_fun f hf) @[continuity] lemma continuous_integral : continuous (λ (f : α →₁[μ] E), ∫ a, f a ∂μ) := by { simp only [← l1.integral_eq_integral], exact l1.continuous_integral } lemma norm_integral_le_lintegral_norm (f : α → E) : ∥∫ a, f a ∂μ∥ ≤ ennreal.to_real (∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ) := begin by_cases hf : integrable f μ, { rw [integral_eq f hf, ← l1.norm_of_fun_eq_lintegral_norm f hf], exact l1.norm_integral_le _ }, { rw [integral_undef hf, norm_zero], exact to_real_nonneg } end lemma ennnorm_integral_le_lintegral_ennnorm (f : α → E) : (nnnorm (∫ a, f a ∂μ) : ennreal) ≤ ∫⁻ a, (nnnorm (f a)) ∂μ := by { simp_rw [← of_real_norm_eq_coe_nnnorm], apply ennreal.of_real_le_of_le_to_real, exact norm_integral_le_lintegral_norm f } lemma integral_eq_zero_of_ae {f : α → E} (hf : f =ᵐ[μ] 0) : ∫ a, f a ∂μ = 0 := if hfm : measurable f then by simp [integral_congr_ae hfm measurable_zero hf, integral_zero] else integral_non_measurable hfm /-- If `F i → f` in `L1`, then `∫ x, F i x ∂μ → ∫ x, f x∂μ`. -/ lemma tendsto_integral_of_l1 {ι} (f : α → E) (hfi : integrable f μ) {F : ι → α → E} {l : filter ι} (hFi : ∀ᶠ i in l, integrable (F i) μ) (hF : tendsto (λ i, ∫⁻ x, edist (F i x) (f x) ∂μ) l (𝓝 0)) : tendsto (λ i, ∫ x, F i x ∂μ) l (𝓝 $ ∫ x, f x ∂μ) := begin rw [tendsto_iff_norm_tendsto_zero], replace hF : tendsto (λ i, ennreal.to_real $ ∫⁻ x, edist (F i x) (f x) ∂μ) l (𝓝 0) := (ennreal.tendsto_to_real zero_ne_top).comp hF, refine squeeze_zero_norm' (hFi.mp $ hFi.mono $ λ i hFi hFm, _) hF, simp only [norm_norm, ← integral_sub hFi hfi, edist_dist, dist_eq_norm], apply norm_integral_le_lintegral_norm end /-- Lebesgue dominated convergence theorem provides sufficient conditions under which almost everywhere convergence of a sequence of functions implies the convergence of their integrals. -/ theorem tendsto_integral_of_dominated_convergence {F : ℕ → α → E} {f : α → E} (bound : α → ℝ) (F_measurable : ∀ n, measurable (F n)) (f_measurable : measurable f) (bound_integrable : integrable bound μ) (h_bound : ∀ n, ∀ᵐ a ∂μ, ∥F n a∥ ≤ bound a) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) : tendsto (λn, ∫ a, F n a ∂μ) at_top (𝓝 $ ∫ a, f a ∂μ) := begin /- To show `(∫ a, F n a) --> (∫ f)`, suffices to show `∥∫ a, F n a - ∫ f∥ --> 0` -/ rw tendsto_iff_norm_tendsto_zero, /- But `0 ≤ ∥∫ a, F n a - ∫ f∥ = ∥∫ a, (F n a - f a) ∥ ≤ ∫ a, ∥F n a - f a∥, and thus we apply the sandwich theorem and prove that `∫ a, ∥F n a - f a∥ --> 0` -/ have lintegral_norm_tendsto_zero : tendsto (λn, ennreal.to_real $ ∫⁻ a, (ennreal.of_real ∥F n a - f a∥) ∂μ) at_top (𝓝 0) := (tendsto_to_real zero_ne_top).comp (tendsto_lintegral_norm_of_dominated_convergence F_measurable f_measurable bound_integrable.has_finite_integral h_bound h_lim), -- Use the sandwich theorem refine squeeze_zero (λ n, norm_nonneg _) _ lintegral_norm_tendsto_zero, -- Show `∥∫ a, F n a - ∫ f∥ ≤ ∫ a, ∥F n a - f a∥` for all `n` { assume n, have h₁ : integrable (F n) μ := bound_integrable.mono' (F_measurable n) (h_bound _), have h₂ : integrable f μ := ⟨f_measurable, has_finite_integral_of_dominated_convergence bound_integrable.has_finite_integral h_bound h_lim⟩, rw ← integral_sub h₁ h₂, exact norm_integral_le_lintegral_norm _ } end /-- Lebesgue dominated convergence theorem for filters with a countable basis -/ lemma tendsto_integral_filter_of_dominated_convergence {ι} {l : filter ι} {F : ι → α → E} {f : α → E} (bound : α → ℝ) (hl_cb : l.is_countably_generated) (hF_meas : ∀ᶠ n in l, measurable (F n)) (f_measurable : measurable f) (h_bound : ∀ᶠ n in l, ∀ᵐ a ∂μ, ∥F n a∥ ≤ bound a) (bound_integrable : integrable bound μ) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) l (𝓝 (f a))) : tendsto (λn, ∫ a, F n a ∂μ) l (𝓝 $ ∫ a, f a ∂μ) := begin rw hl_cb.tendsto_iff_seq_tendsto, { intros x xl, have hxl, { rw tendsto_at_top' at xl, exact xl }, have h := inter_mem_sets hF_meas h_bound, replace h := hxl _ h, rcases h with ⟨k, h⟩, rw ← tendsto_add_at_top_iff_nat k, refine tendsto_integral_of_dominated_convergence _ _ _ _ _ _, { exact bound }, { intro, refine (h _ _).1, exact nat.le_add_left _ _ }, { assumption }, { assumption }, { intro, refine (h _ _).2, exact nat.le_add_left _ _ }, { filter_upwards [h_lim], assume a h_lim, apply @tendsto.comp _ _ _ (λn, x (n + k)) (λn, F n a), { assumption }, rw tendsto_add_at_top_iff_nat, assumption } }, end /-- The Bochner integral of a real-valued function `f : α → ℝ` is the difference between the integral of the positive part of `f` and the integral of the negative part of `f`. -/ lemma integral_eq_lintegral_max_sub_lintegral_min {f : α → ℝ} (hf : integrable f μ) : ∫ a, f a ∂μ = ennreal.to_real (∫⁻ a, (ennreal.of_real $ max (f a) 0) ∂μ) - ennreal.to_real (∫⁻ a, (ennreal.of_real $ - min (f a) 0) ∂μ) := let f₁ : α →₁[μ] ℝ := l1.of_fun f hf in -- Go to the `L¹` space have eq₁ : ennreal.to_real (∫⁻ a, (ennreal.of_real $ max (f a) 0) ∂μ) = ∥l1.pos_part f₁∥ := begin rw l1.norm_eq_norm_to_fun, congr' 1, apply lintegral_congr_ae, filter_upwards [l1.pos_part_to_fun f₁, l1.to_fun_of_fun f hf], assume a h₁ h₂, rw [h₁, h₂, real.norm_eq_abs, abs_of_nonneg], exact le_max_right _ _ end, -- Go to the `L¹` space have eq₂ : ennreal.to_real (∫⁻ a, (ennreal.of_real $ -min (f a) 0) ∂μ) = ∥l1.neg_part f₁∥ := begin rw l1.norm_eq_norm_to_fun, congr' 1, apply lintegral_congr_ae, filter_upwards [l1.neg_part_to_fun_eq_min f₁, l1.to_fun_of_fun f hf], assume a h₁ h₂, rw [h₁, h₂, real.norm_eq_abs, abs_of_nonneg], rw [neg_nonneg], exact min_le_right _ _ end, begin rw [eq₁, eq₂, integral, dif_pos], exact l1.integral_eq_norm_pos_part_sub _ end lemma integral_eq_lintegral_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ] f) (hfm : measurable f) : ∫ a, f a ∂μ = ennreal.to_real (∫⁻ a, (ennreal.of_real $ f a) ∂μ) := begin by_cases hfi : integrable f μ, { rw integral_eq_lintegral_max_sub_lintegral_min hfi, have h_min : ∫⁻ a, ennreal.of_real (-min (f a) 0) ∂μ = 0, { rw lintegral_eq_zero_iff, { refine hf.mono _, simp only [pi.zero_apply], assume a h, simp only [min_eq_right h, neg_zero, ennreal.of_real_zero] }, { exact measurable_of_real.comp (measurable_id.neg.comp $ hfm.min measurable_const) } }, have h_max : ∫⁻ a, ennreal.of_real (max (f a) 0) ∂μ = ∫⁻ a, ennreal.of_real (f a) ∂μ, { refine lintegral_congr_ae (hf.mono (λ a h, _)), rw [pi.zero_apply] at h, rw max_eq_left h }, rw [h_min, h_max, zero_to_real, _root_.sub_zero] }, { rw integral_undef hfi, simp_rw [integrable, hfm, has_finite_integral_iff_norm, lt_top_iff_ne_top, ne.def, true_and, not_not] at hfi, have : ∫⁻ (a : α), ennreal.of_real (f a) ∂μ = ∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ, { refine lintegral_congr_ae (hf.mono $ assume a h, _), rw [real.norm_eq_abs, abs_of_nonneg h] }, rw [this, hfi], refl } end lemma integral_nonneg_of_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ] f) : 0 ≤ ∫ a, f a ∂μ := begin by_cases hfm : measurable f, { rw integral_eq_lintegral_of_nonneg_ae hf hfm, exact to_real_nonneg }, { rw integral_non_measurable hfm } end lemma lintegral_coe_eq_integral (f : α → nnreal) (hfi : integrable (λ x, (f x : real)) μ) : ∫⁻ a, f a ∂μ = ennreal.of_real ∫ a, f a ∂μ := begin simp_rw [integral_eq_lintegral_of_nonneg_ae (eventually_of_forall (λ x, (f x).coe_nonneg)) hfi.measurable, ← ennreal.coe_nnreal_eq], rw [ennreal.of_real_to_real], rw [← lt_top_iff_ne_top], convert hfi.has_finite_integral, ext1 x, rw [real.nnnorm_coe_eq_self] end lemma integral_to_real {f : α → ennreal} (hfm : measurable f) (hf : ∀ᵐ x ∂μ, f x < ⊤) : ∫ a, (f a).to_real ∂μ = (∫⁻ a, f a ∂μ).to_real := begin rw [integral_eq_lintegral_of_nonneg_ae _ hfm.to_real], { rw lintegral_congr_ae, refine hf.mp (eventually_of_forall _), intros x hx, rw [lt_top_iff_ne_top] at hx, simp [hx] }, { exact (eventually_of_forall $ λ x, ennreal.to_real_nonneg) } end lemma integral_nonneg {f : α → ℝ} (hf : 0 ≤ f) : 0 ≤ ∫ a, f a ∂μ := integral_nonneg_of_ae $ eventually_of_forall hf lemma integral_nonpos_of_ae {f : α → ℝ} (hf : f ≤ᵐ[μ] 0) : ∫ a, f a ∂μ ≤ 0 := begin have hf : 0 ≤ᵐ[μ] (-f) := hf.mono (assume a h, by rwa [pi.neg_apply, pi.zero_apply, neg_nonneg]), have : 0 ≤ ∫ a, -f a ∂μ := integral_nonneg_of_ae hf, rwa [integral_neg, neg_nonneg] at this, end lemma integral_nonpos {f : α → ℝ} (hf : f ≤ 0) : ∫ a, f a ∂μ ≤ 0 := integral_nonpos_of_ae $ eventually_of_forall hf lemma integral_eq_zero_iff_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ] f) (hfi : integrable f μ) : ∫ x, f x ∂μ = 0 ↔ f =ᵐ[μ] 0 := by simp_rw [integral_eq_lintegral_of_nonneg_ae hf hfi.1, ennreal.to_real_eq_zero_iff, lintegral_eq_zero_iff (ennreal.measurable_of_real.comp hfi.1), ← ennreal.not_lt_top, ← has_finite_integral_iff_of_real hf, hfi.2, not_true, or_false, ← hf.le_iff_eq, filter.eventually_eq, filter.eventually_le, (∘), pi.zero_apply, ennreal.of_real_eq_zero] lemma integral_eq_zero_iff_of_nonneg {f : α → ℝ} (hf : 0 ≤ f) (hfi : integrable f μ) : ∫ x, f x ∂μ = 0 ↔ f =ᵐ[μ] 0 := integral_eq_zero_iff_of_nonneg_ae (eventually_of_forall hf) hfi lemma integral_pos_iff_support_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ] f) (hfi : integrable f μ) : (0 < ∫ x, f x ∂μ) ↔ 0 < μ (function.support f) := by simp_rw [(integral_nonneg_of_ae hf).lt_iff_ne, zero_lt_iff_ne_zero, ne.def, @eq_comm ℝ 0, integral_eq_zero_iff_of_nonneg_ae hf hfi, filter.eventually_eq, ae_iff, pi.zero_apply, function.support] lemma integral_pos_iff_support_of_nonneg {f : α → ℝ} (hf : 0 ≤ f) (hfi : integrable f μ) : (0 < ∫ x, f x ∂μ) ↔ 0 < μ (function.support f) := integral_pos_iff_support_of_nonneg_ae (eventually_of_forall hf) hfi section normed_group variables {H : Type*} [normed_group H] [second_countable_topology H] [measurable_space H] [borel_space H] lemma l1.norm_eq_integral_norm (f : α →₁[μ] H) : ∥f∥ = ∫ a, ∥f a∥ ∂μ := by rw [l1.norm_eq_norm_to_fun, integral_eq_lintegral_of_nonneg_ae (eventually_of_forall $ by simp [norm_nonneg]) (continuous_norm.measurable.comp f.measurable)] lemma l1.norm_of_fun_eq_integral_norm {f : α → H} (hf : integrable f μ) : ∥ l1.of_fun f hf ∥ = ∫ a, ∥f a∥ ∂μ := begin rw l1.norm_eq_integral_norm, refine integral_congr_ae (l1.measurable_norm _) hf.measurable.norm _, apply (l1.to_fun_of_fun f hf).mono, intros a ha, simp [ha] end end normed_group lemma integral_mono_ae {f g : α → ℝ} (hf : integrable f μ) (hg : integrable g μ) (h : f ≤ᵐ[μ] g) : ∫ a, f a ∂μ ≤ ∫ a, g a ∂μ := le_of_sub_nonneg $ integral_sub hg hf ▸ integral_nonneg_of_ae $ h.mono (λ a, sub_nonneg_of_le) lemma integral_mono {f g : α → ℝ} (hf : integrable f μ) (hg : integrable g μ) (h : f ≤ g) : ∫ a, f a ∂μ ≤ ∫ a, g a ∂μ := integral_mono_ae hf hg $ eventually_of_forall h lemma integral_mono_of_nonneg {f g : α → ℝ} (hf : 0 ≤ᵐ[μ] f) (hgi : integrable g μ) (h : f ≤ᵐ[μ] g) : ∫ a, f a ∂μ ≤ ∫ a, g a ∂μ := begin by_cases hfm : measurable f, { refine integral_mono_ae ⟨hfm, _⟩ hgi h, refine (hgi.has_finite_integral.mono $ h.mp $ hf.mono $ λ x hf hfg, _), simpa [real.norm_eq_abs, abs_of_nonneg hf, abs_of_nonneg (le_trans hf hfg)] }, { rw [integral_non_measurable hfm], exact integral_nonneg_of_ae (hf.trans h) } end lemma norm_integral_le_integral_norm (f : α → E) : ∥(∫ a, f a ∂μ)∥ ≤ ∫ a, ∥f a∥ ∂μ := have le_ae : ∀ᵐ a ∂μ, 0 ≤ ∥f a∥ := eventually_of_forall (λa, norm_nonneg _), classical.by_cases ( λh : measurable f, calc ∥∫ a, f a ∂μ∥ ≤ ennreal.to_real (∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ) : norm_integral_le_lintegral_norm _ ... = ∫ a, ∥f a∥ ∂μ : (integral_eq_lintegral_of_nonneg_ae le_ae $ measurable.norm h).symm ) ( λh : ¬measurable f, begin rw [integral_non_measurable h, norm_zero], exact integral_nonneg_of_ae le_ae end ) lemma norm_integral_le_of_norm_le {f : α → E} {g : α → ℝ} (hg : integrable g μ) (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ g x) : ∥∫ x, f x ∂μ∥ ≤ ∫ x, g x ∂μ := calc ∥∫ x, f x ∂μ∥ ≤ ∫ x, ∥f x∥ ∂μ : norm_integral_le_integral_norm f ... ≤ ∫ x, g x ∂μ : integral_mono_of_nonneg (eventually_of_forall $ λ x, norm_nonneg _) hg h lemma integral_finset_sum {ι} (s : finset ι) {f : ι → α → E} (hf : ∀ i, integrable (f i) μ) : ∫ a, ∑ i in s, f i a ∂μ = ∑ i in s, ∫ a, f i a ∂μ := begin refine finset.induction_on s _ _, { simp only [integral_zero, finset.sum_empty] }, { assume i s his ih, simp only [his, finset.sum_insert, not_false_iff], rw [integral_add (hf _) (integrable_finset_sum s hf), ih] } end lemma simple_func.integral_eq_integral (f : α →ₛ E) (hfi : integrable f μ) : f.integral μ = ∫ x, f x ∂μ := begin rw [integral_eq f hfi, ← l1.simple_func.of_simple_func_eq_of_fun, l1.simple_func.integral_l1_eq_integral, l1.simple_func.integral_eq_integral], exact simple_func.integral_congr hfi (l1.simple_func.to_simple_func_of_simple_func _ _).symm end @[simp] lemma integral_const (c : E) : ∫ x : α, c ∂μ = (μ univ).to_real • c := begin by_cases hμ : μ univ < ⊤, { haveI : finite_measure μ := ⟨hμ⟩, calc ∫ x : α, c ∂μ = (simple_func.const α c).integral μ : ((simple_func.const α c).integral_eq_integral (integrable_const _)).symm ... = _ : _, rw [simple_func.integral], by_cases ha : nonempty α, { resetI, simp [preimage_const_of_mem] }, { simp [μ.eq_zero_of_not_nonempty ha] } }, { by_cases hc : c = 0, { simp [hc, integral_zero] }, { have : ¬integrable (λ x : α, c) μ, { simp only [integrable_const_iff, not_or_distrib], exact ⟨hc, hμ⟩ }, simp only [not_lt, top_le_iff] at hμ, simp [integral_undef, *] } } end lemma norm_integral_le_of_norm_le_const [finite_measure μ] {f : α → E} {C : ℝ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ C) : ∥∫ x, f x ∂μ∥ ≤ C * (μ univ).to_real := calc ∥∫ x, f x ∂μ∥ ≤ ∫ x, C ∂μ : norm_integral_le_of_norm_le (integrable_const C) h ... = C * (μ univ).to_real : by rw [integral_const, smul_eq_mul, mul_comm] lemma tendsto_integral_approx_on_univ {f : α → E} (hf : integrable f μ) : tendsto (λ n, (simple_func.approx_on f hf.1 univ 0 trivial n).integral μ) at_top (𝓝 $ ∫ x, f x ∂μ) := begin have : tendsto (λ n, ∫ x, simple_func.approx_on f hf.1 univ 0 trivial n x ∂μ) at_top (𝓝 $ ∫ x, f x ∂μ) := tendsto_integral_of_l1 _ hf (eventually_of_forall $ simple_func.integrable_approx_on_univ hf) (simple_func.tendsto_approx_on_univ_l1_edist hf), simpa only [simple_func.integral_eq_integral, simple_func.integrable_approx_on_univ hf] end variable {ν : measure α} lemma integral_add_measure {f : α → E} (hμ : integrable f μ) (hν : integrable f ν) : ∫ x, f x ∂(μ + ν) = ∫ x, f x ∂μ + ∫ x, f x ∂ν := begin have hfi := hμ.add_measure hν, refine tendsto_nhds_unique (tendsto_integral_approx_on_univ hfi) _, simpa only [simple_func.integral_add_measure _ (simple_func.integrable_approx_on_univ hfi _)] using (tendsto_integral_approx_on_univ hμ).add (tendsto_integral_approx_on_univ hν) end lemma integral_add_measure' {f : α → E} (hμ : has_finite_integral f μ) (hν : has_finite_integral f ν) : ∫ x, f x ∂(μ + ν) = ∫ x, f x ∂μ + ∫ x, f x ∂ν := begin by_cases hfm : measurable f, { exact integral_add_measure ⟨hfm, hμ⟩ ⟨hfm, hν⟩ }, { simp only [integral_non_measurable hfm, zero_add] } end @[simp] lemma integral_zero_measure (f : α → E) : ∫ x, f x ∂0 = 0 := norm_le_zero_iff.1 $ le_trans (norm_integral_le_lintegral_norm f) $ by simp @[simp] lemma integral_smul_measure (f : α → E) (c : ennreal) : ∫ x, f x ∂(c • μ) = c.to_real • ∫ x, f x ∂μ := begin -- First we consider “degenerate” cases: -- `f` is not measurable by_cases hfm : measurable f, swap, { simp [integral_non_measurable hfm] }, -- `c = 0` rcases (zero_le c).eq_or_lt with rfl|h0, { simp }, -- `c = ⊤` rcases (le_top : c ≤ ⊤).eq_or_lt with rfl|hc, { rw [ennreal.top_to_real, zero_smul], by_cases hf : f =ᵐ[μ] 0, { have : f =ᵐ[⊤ • μ] 0 := ae_smul_measure hf ⊤, exact integral_eq_zero_of_ae this }, { apply integral_undef, rw [integrable, has_finite_integral, iff_true_intro hfm, true_and, lintegral_smul_measure, top_mul, if_neg], { apply lt_irrefl }, { rw [lintegral_eq_zero_iff hfm.ennnorm], refine λ h, hf (h.mono $ λ x, _), simp } } }, -- `f` is not integrable and `0 < c < ⊤` by_cases hfi : integrable f μ, swap, { rw [integral_undef hfi, smul_zero], refine integral_undef (mt (λ h, _) hfi), convert h.smul_measure (ennreal.inv_lt_top.2 h0), rw [smul_smul, ennreal.inv_mul_cancel (ne_of_gt h0) (ne_of_lt hc), one_smul] }, -- Main case: `0 < c < ⊤`, `f` is measurable and integrable refine tendsto_nhds_unique _ (tendsto_const_nhds.smul (tendsto_integral_approx_on_univ hfi)), convert tendsto_integral_approx_on_univ (hfi.smul_measure hc), simp only [simple_func.integral, measure.smul_apply, finset.smul_sum, smul_smul, ennreal.to_real_mul_to_real] end lemma integral_map {β} [measurable_space β] {φ : α → β} (hφ : measurable φ) {f : β → E} (hfm : measurable f) : ∫ y, f y ∂(measure.map φ μ) = ∫ x, f (φ x) ∂μ := begin by_cases hfi : integrable f (measure.map φ μ), swap, { rw [integral_undef hfi, integral_undef], rwa [← integrable_map_measure hφ hfm] }, refine tendsto_nhds_unique (tendsto_integral_approx_on_univ hfi) _, convert tendsto_integral_approx_on_univ ((integrable_map_measure hφ hfm).1 hfi), ext1 i, simp only [simple_func.approx_on_comp, simple_func.integral, measure.map_apply, hφ, simple_func.is_measurable_preimage, ← preimage_comp, simple_func.coe_comp], refine (finset.sum_subset (simple_func.range_comp_subset_range _ hφ) (λ y _ hy, _)).symm, rw [simple_func.mem_range, ← set.preimage_singleton_eq_empty, simple_func.coe_comp] at hy, simp [hy] end lemma integral_dirac (f : α → E) (a : α) (hfm : measurable f) : ∫ x, f x ∂(measure.dirac a) = f a := calc ∫ x, f x ∂(measure.dirac a) = ∫ x, f a ∂(measure.dirac a) : integral_congr_ae hfm measurable_const $ eventually_eq_dirac hfm ... = f a : by simp [measure.dirac_apply_of_mem] end properties mk_simp_attribute integral_simps "Simp set for integral rules." attribute [integral_simps] integral_neg integral_smul l1.integral_add l1.integral_sub l1.integral_smul l1.integral_neg attribute [irreducible] integral l1.integral end measure_theory
ec1e8524f4331ec94a4af26cc7ca592c865fef8b
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/adjoin/fg.lean
bcc8bfa719413dc7a2e40673fa50d2f1587ae80b
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
6,902
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import ring_theory.polynomial.basic import ring_theory.principal_ideal_domain import data.mv_polynomial.basic /-! # Adjoining elements to form subalgebras This file develops the basic theory of finitely-generated subalgebras. ## Definitions * `fg (S : subalgebra R A)` : A predicate saying that the subalgebra is finitely-generated as an A-algebra ## Tags adjoin, algebra, finitely-generated algebra -/ universes u v w open subsemiring ring submodule open_locale pointwise namespace algebra variables {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [comm_semiring A] [algebra R A] {s t : set A} theorem fg_trans (h1 : (adjoin R s).to_submodule.fg) (h2 : (adjoin (adjoin R s) t).to_submodule.fg) : (adjoin R (s ∪ t)).to_submodule.fg := begin rcases fg_def.1 h1 with ⟨p, hp, hp'⟩, rcases fg_def.1 h2 with ⟨q, hq, hq'⟩, refine fg_def.2 ⟨p * q, hp.mul hq, le_antisymm _ _⟩, { rw [span_le], rintros _ ⟨x, y, hx, hy, rfl⟩, change x * y ∈ _, refine subalgebra.mul_mem _ _ _, { have : x ∈ (adjoin R s).to_submodule, { rw ← hp', exact subset_span hx }, exact adjoin_mono (set.subset_union_left _ _) this }, have : y ∈ (adjoin (adjoin R s) t).to_submodule, { rw ← hq', exact subset_span hy }, change y ∈ adjoin R (s ∪ t), rwa adjoin_union_eq_adjoin_adjoin }, { intros r hr, change r ∈ adjoin R (s ∪ t) at hr, rw adjoin_union_eq_adjoin_adjoin at hr, change r ∈ (adjoin (adjoin R s) t).to_submodule at hr, rw [← hq', ← set.image_id q, finsupp.mem_span_image_iff_total (adjoin R s)] at hr, rcases hr with ⟨l, hlq, rfl⟩, have := @finsupp.total_apply A A (adjoin R s), rw [this, finsupp.sum], refine sum_mem _, intros z hz, change (l z).1 * _ ∈ _, have : (l z).1 ∈ (adjoin R s).to_submodule := (l z).2, rw [← hp', ← set.image_id p, finsupp.mem_span_image_iff_total R] at this, rcases this with ⟨l2, hlp, hl⟩, have := @finsupp.total_apply A A R, rw this at hl, rw [←hl, finsupp.sum_mul], refine sum_mem _, intros t ht, change _ * _ ∈ _, rw smul_mul_assoc, refine smul_mem _ _ _, exact subset_span ⟨t, z, hlp ht, hlq hz, rfl⟩ } end end algebra namespace subalgebra variables {R : Type u} {A : Type v} {B : Type w} variables [comm_semiring R] [semiring A] [algebra R A] [semiring B] [algebra R B] /-- A subalgebra `S` is finitely generated if there exists `t : finset A` such that `algebra.adjoin R t = S`. -/ def fg (S : subalgebra R A) : Prop := ∃ t : finset A, algebra.adjoin R ↑t = S lemma fg_adjoin_finset (s : finset A) : (algebra.adjoin R (↑s : set A)).fg := ⟨s, rfl⟩ theorem fg_def {S : subalgebra R A} : S.fg ↔ ∃ t : set A, set.finite t ∧ algebra.adjoin R t = S := iff.symm set.exists_finite_iff_finset theorem fg_bot : (⊥ : subalgebra R A).fg := ⟨∅, algebra.adjoin_empty R A⟩ theorem fg_of_fg_to_submodule {S : subalgebra R A} : S.to_submodule.fg → S.fg := λ ⟨t, ht⟩, ⟨t, le_antisymm (algebra.adjoin_le (λ x hx, show x ∈ S.to_submodule, from ht ▸ subset_span hx)) $ show S.to_submodule ≤ (algebra.adjoin R ↑t).to_submodule, from (λ x hx, span_le.mpr (λ x hx, algebra.subset_adjoin hx) (show x ∈ span R ↑t, by { rw ht, exact hx }))⟩ theorem fg_of_noetherian [is_noetherian R A] (S : subalgebra R A) : S.fg := fg_of_fg_to_submodule (is_noetherian.noetherian S.to_submodule) lemma fg_of_submodule_fg (h : (⊤ : submodule R A).fg) : (⊤ : subalgebra R A).fg := let ⟨s, hs⟩ := h in ⟨s, to_submodule.injective $ by { rw [algebra.top_to_submodule, eq_top_iff, ← hs, span_le], exact algebra.subset_adjoin }⟩ lemma fg.prod {S : subalgebra R A} {T : subalgebra R B} (hS : S.fg) (hT : T.fg) : (S.prod T).fg := begin obtain ⟨s, hs⟩ := fg_def.1 hS, obtain ⟨t, ht⟩ := fg_def.1 hT, rw [← hs.2, ← ht.2], exact fg_def.2 ⟨(linear_map.inl R A B '' (s ∪ {1})) ∪ (linear_map.inr R A B '' (t ∪ {1})), set.finite.union (set.finite.image _ (set.finite.union hs.1 (set.finite_singleton _))) (set.finite.image _ (set.finite.union ht.1 (set.finite_singleton _))), algebra.adjoin_inl_union_inr_eq_prod R s t⟩ end section open_locale classical lemma fg.map {S : subalgebra R A} (f : A →ₐ[R] B) (hs : S.fg) : (S.map f).fg := let ⟨s, hs⟩ := hs in ⟨s.image f, by rw [finset.coe_image, algebra.adjoin_image, hs]⟩ end lemma fg_of_fg_map (S : subalgebra R A) (f : A →ₐ[R] B) (hf : function.injective f) (hs : (S.map f).fg) : S.fg := let ⟨s, hs⟩ := hs in ⟨s.preimage f $ λ _ _ _ _ h, hf h, map_injective hf $ by { rw [← algebra.adjoin_image, finset.coe_preimage, set.image_preimage_eq_of_subset, hs], rw [← alg_hom.coe_range, ← algebra.adjoin_le_iff, hs, ← algebra.map_top], exact map_mono le_top }⟩ lemma fg_top (S : subalgebra R A) : (⊤ : subalgebra R S).fg ↔ S.fg := ⟨λ h, by { rw [← S.range_val, ← algebra.map_top], exact fg.map _ h }, λ h, fg_of_fg_map _ S.val subtype.val_injective $ by { rw [algebra.map_top, range_val], exact h }⟩ lemma induction_on_adjoin [is_noetherian R A] (P : subalgebra R A → Prop) (base : P ⊥) (ih : ∀ (S : subalgebra R A) (x : A), P S → P (algebra.adjoin R (insert x S))) (S : subalgebra R A) : P S := begin classical, obtain ⟨t, rfl⟩ := S.fg_of_noetherian, refine finset.induction_on t _ _, { simpa using base }, intros x t hxt h, rw [finset.coe_insert], simpa only [algebra.adjoin_insert_adjoin] using ih _ x h, end end subalgebra section semiring variables {R : Type u} {A : Type v} {B : Type w} variables [comm_semiring R] [comm_ring A] [comm_ring B] [algebra R A] [algebra R B] /-- The image of a Noetherian R-algebra under an R-algebra map is a Noetherian ring. -/ instance alg_hom.is_noetherian_ring_range (f : A →ₐ[R] B) [is_noetherian_ring A] : is_noetherian_ring f.range := is_noetherian_ring_range f.to_ring_hom end semiring section ring variables {R : Type u} {A : Type v} {B : Type w} variables [comm_ring R] [comm_ring A] [comm_ring B] [algebra R A] [algebra R B] theorem is_noetherian_ring_of_fg {S : subalgebra R A} (HS : S.fg) [is_noetherian_ring R] : is_noetherian_ring S := let ⟨t, ht⟩ := HS in ht ▸ (algebra.adjoin_eq_range R (↑t : set A)).symm ▸ by haveI : is_noetherian_ring (mv_polynomial (↑t : set A) R) := mv_polynomial.is_noetherian_ring; convert alg_hom.is_noetherian_ring_range _; apply_instance theorem is_noetherian_subring_closure (s : set R) (hs : s.finite) : is_noetherian_ring (subring.closure s) := show is_noetherian_ring (subalgebra_of_subring (subring.closure s)), from algebra.adjoin_int s ▸ is_noetherian_ring_of_fg (subalgebra.fg_def.2 ⟨s, hs, rfl⟩) end ring
ee9a784a6fb7b68d98e36453fbaef5655f8de19a
dc15192b741b5d1c22cea8d65d6eb38bce3d838d
/src/finset.lean
007c14d9f4ed76027f8ec182d2c187ee27717c52
[]
no_license
VArtem/lean-matroids
86910241ac8d1a5ec7b35adb77c1cc9969480fb9
a8969b1cb2456820ccbdce65e2e168c48c30d9bf
refs/heads/main
1,678,556,999,525
1,614,537,008,000
1,614,537,008,000
338,915,729
0
1
null
null
null
null
UTF-8
Lean
false
false
2,668
lean
import data.finset.basic import tactic variables {X : Type*} [fintype X] [decidable_eq X] namespace finset open finset lemma card_erase_of_mem' {A : finset X} {x} (h : x ∈ A) : (A.erase x).card + 1 = A.card := begin rw [card_erase_of_mem h, nat.add_one, nat.succ_pred_eq_of_pos], rw [gt_iff_lt, pos_iff_ne_zero], exact card_ne_zero_of_mem h, end lemma sdiff_subset_erase_of_mem {A B : finset X} {x} : x ∈ B → A \ B ⊆ A.erase x := begin intros xB, rw [← sdiff_singleton_eq_erase x A], apply sdiff_subset_sdiff (subset.refl _) _, rwa singleton_subset_iff, end lemma eq_or_ssubset_of_subset {A B : finset X} (h : A ⊆ B) : A = B ∨ A ⊂ B := begin rwa [← le_iff_subset, le_iff_eq_or_lt] at h, end lemma union_singleton {A : finset X} {x : X} : {x} ∪ A = insert x A := begin exact (insert_eq x A).symm, end lemma card_succ_iff_erase_mem {A B : finset X} (h : A ⊆ B) : B.card = A.card + 1 ↔ ∃ x ∈ B, A = B.erase x := begin split, { intro h_card, have hC : (B \ A).card = 1, from by { rw [card_sdiff h], exact nat.sub_eq_of_eq_add h_card, }, obtain ⟨x, h_sing⟩ := card_eq_one.1 hC, use x, have hx : x ∈ B \ A, by simp only [h_sing, mem_singleton], rw mem_sdiff at hx, use hx.1, rw [←sdiff_union_of_subset h, h_sing, ←insert_eq, erase_insert hx.2], }, { rintro ⟨x, xB, rfl⟩, exact (card_erase_of_mem' xB).symm, } end lemma very_important_lemma {A B S : finset X} : (A ∩ B) ⊆ S → S ⊆ (A ∪ B) → (A ∪ B).card = S.card + 1 → (A ⊆ S ∨ B ⊆ S) := begin intros ABS SAB Scard, obtain ⟨x, xUnion, rfl⟩ := (card_succ_iff_erase_mem SAB).1 Scard, rw mem_union at xUnion, wlog xA : x ∈ A := xUnion using [A B, B A], right, have xInter : x ∉ A ∩ B := λ h, not_mem_erase _ _ (ABS h), have xB : x ∉ B := λ h, xInter $ mem_inter_of_mem xA h, nth_rewrite 0 ← (erase_eq_of_not_mem xB), exact erase_subset_erase _ (subset_union_right _ _), end lemma eq_or_eq_succ_of_le_and_le_succ {x y : ℕ}: x ≤ y → y ≤ x + 1 → x = y ∨ x + 1 = y := begin intros hxy hyx1, cases le_iff_lt_or_eq.1 hxy, { right, linarith, }, { left, exact h, } end lemma not_mem_sdiff_iff {x : X} {A B : finset X} : x ∉ A \ B ↔ x ∉ A ∨ x ∈ B := begin rw not_iff_comm, push_neg, simp only [mem_sdiff, iff_self], end lemma card_sdiff_ℤ {A B : finset X} (hAB : A ⊆ B) : ((B \ A).card : ℤ) = (B.card : ℤ) - (A.card : ℤ) := begin suffices h : (B \ A).card + A.card = B.card, { linarith, }, rw [card_sdiff hAB, nat.sub_add_cancel (card_le_of_subset hAB)], end end finset
0ba6da62480a2a7bb8da632dd81e1b34065b433f
e4d500be102d7cc2cf7c341f360db71d9125c19b
/src/data/zmod/basic.lean
bb5d3c068516507ed203c09cb818ba746d34b6b9
[ "Apache-2.0" ]
permissive
mgrabovsky/mathlib
3cbc6c54dab5f277f0abf4195a1b0e6e39b9971f
e397b4c1266ee241e9412e17b1dd8724f56fba09
refs/heads/master
1,664,687,987,155
1,591,255,329,000
1,591,255,329,000
269,361,264
0
0
Apache-2.0
1,591,275,784,000
1,591,275,783,000
null
UTF-8
Lean
false
false
25,974
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Chris Hughes -/ import data.int.modeq import algebra.char_p import data.nat.totient /-! # Integers mod `n` Definition of the integers mod n, and the field structure on the integers mod p. ## Definitions * `zmod n`, which is for integers modulo a nat `n : ℕ` * `val a` is defined as a natural number: - for `a : zmod 0` it is the absolute value of `a` - for `a : zmod n` with `0 < n` it is the least natural number in the equivalence class * `val_min_abs` returns the integer closest to zero in the equivalence class. * A coercion `cast` is defined from `zmod n` into any ring. This is a ring hom if the ring has characteristic dividing `n` -/ namespace fin /-! ## Ring structure on `fin n` We define a commutative ring structure on `fin n`, but we do not register it as instance. Afterwords, when we define `zmod n` in terms of `fin n`, we use these definitions to register the ring structure on `zmod n` as type class instance. -/ open nat nat.modeq int /-- Negation on `fin n` -/ def has_neg (n : ℕ) : has_neg (fin n) := ⟨λ a, ⟨nat_mod (-(a.1 : ℤ)) n, begin have npos : 0 < n := lt_of_le_of_lt (nat.zero_le _) a.2, have h : (n : ℤ) ≠ 0 := int.coe_nat_ne_zero_iff_pos.2 npos, have := int.mod_lt (-(a.1 : ℤ)) h, rw [(abs_of_nonneg (int.coe_nat_nonneg n))] at this, rwa [← int.coe_nat_lt, nat_mod, to_nat_of_nonneg (int.mod_nonneg _ h)] end⟩⟩ /-- Additive commutative semigroup structure on `fin (n+1)`. -/ def add_comm_semigroup (n : ℕ) : add_comm_semigroup (fin (n+1)) := { add_assoc := λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq (show ((a + b) % (n+1) + c) ≡ (a + (b + c) % (n+1)) [MOD (n+1)], from calc ((a + b) % (n+1) + c) ≡ a + b + c [MOD (n+1)] : modeq_add (nat.mod_mod _ _) rfl ... ≡ a + (b + c) [MOD (n+1)] : by rw add_assoc ... ≡ (a + (b + c) % (n+1)) [MOD (n+1)] : modeq_add rfl (nat.mod_mod _ _).symm), add_comm := λ ⟨a, _⟩ ⟨b, _⟩, fin.eq_of_veq (show (a + b) % (n+1) = (b + a) % (n+1), by rw add_comm), ..fin.has_add } /-- Multiplicative commutative semigroup structure on `fin (n+1)`. -/ def comm_semigroup (n : ℕ) : comm_semigroup (fin (n+1)) := { mul_assoc := λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq (calc ((a * b) % (n+1) * c) ≡ a * b * c [MOD (n+1)] : modeq_mul (nat.mod_mod _ _) rfl ... ≡ a * (b * c) [MOD (n+1)] : by rw mul_assoc ... ≡ a * (b * c % (n+1)) [MOD (n+1)] : modeq_mul rfl (nat.mod_mod _ _).symm), mul_comm := λ ⟨a, _⟩ ⟨b, _⟩, fin.eq_of_veq (show (a * b) % (n+1) = (b * a) % (n+1), by rw mul_comm), ..fin.has_mul } local attribute [instance] fin.add_comm_semigroup fin.comm_semigroup private lemma one_mul_aux (n : ℕ) (a : fin (n+1)) : (1 : fin (n+1)) * a = a := begin cases n with n, { exact subsingleton.elim _ _ }, { have h₁ : a.1 % n.succ.succ = a.1 := nat.mod_eq_of_lt a.2, have h₂ : 1 % n.succ.succ = 1 := nat.mod_eq_of_lt dec_trivial, refine fin.eq_of_veq _, simp [val_mul, one_val, h₁, h₂] } end private lemma left_distrib_aux (n : ℕ) : ∀ a b c : fin (n+1), a * (b + c) = a * b + a * c := λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq (calc a * ((b + c) % (n+1)) ≡ a * (b + c) [MOD (n+1)] : modeq_mul rfl (nat.mod_mod _ _) ... ≡ a * b + a * c [MOD (n+1)] : by rw mul_add ... ≡ (a * b) % (n+1) + (a * c) % (n+1) [MOD (n+1)] : modeq_add (nat.mod_mod _ _).symm (nat.mod_mod _ _).symm) /-- Commutative ring structure on `fin (n+1)`. -/ def comm_ring (n : ℕ) : comm_ring (fin (n+1)) := { zero_add := λ ⟨a, ha⟩, fin.eq_of_veq (show (0 + a) % (n+1) = a, by rw zero_add; exact nat.mod_eq_of_lt ha), add_zero := λ ⟨a, ha⟩, fin.eq_of_veq (nat.mod_eq_of_lt ha), add_left_neg := λ ⟨a, ha⟩, fin.eq_of_veq (show (((-a : ℤ) % (n+1)).to_nat + a) % (n+1) = 0, from int.coe_nat_inj begin have npos : 0 < n+1 := lt_of_le_of_lt (nat.zero_le _) ha, have hn : ((n+1) : ℤ) ≠ 0 := (ne_of_lt (int.coe_nat_lt.2 npos)).symm, rw [int.coe_nat_mod, int.coe_nat_add, to_nat_of_nonneg (int.mod_nonneg _ hn), add_comm], simp, end), one_mul := one_mul_aux n, mul_one := λ a, by rw mul_comm; exact one_mul_aux n a, left_distrib := left_distrib_aux n, right_distrib := λ a b c, by rw [mul_comm, left_distrib_aux, mul_comm _ b, mul_comm]; refl, ..fin.has_zero, ..fin.has_one, ..fin.has_neg (n+1), ..fin.add_comm_semigroup n, ..fin.comm_semigroup n } end fin /-- The integers modulo `n : ℕ`. -/ def zmod : ℕ → Type | 0 := ℤ | (n+1) := fin (n+1) namespace zmod instance fintype : Π (n : ℕ) [fact (0 < n)], fintype (zmod n) | 0 _ := false.elim $ nat.not_lt_zero 0 ‹0 < 0› | (n+1) _ := fin.fintype (n+1) lemma card (n : ℕ) [fact (0 < n)] : fintype.card (zmod n) = n := begin unfreezeI, cases n, { exfalso, exact nat.not_lt_zero 0 ‹0 < 0› }, { exact fintype.card_fin (n+1) } end instance decidable_eq : Π (n : ℕ), decidable_eq (zmod n) | 0 := int.decidable_eq | (n+1) := fin.decidable_eq _ instance has_repr : Π (n : ℕ), has_repr (zmod n) | 0 := int.has_repr | (n+1) := fin.has_repr _ instance comm_ring : Π (n : ℕ), comm_ring (zmod n) | 0 := int.comm_ring | (n+1) := fin.comm_ring n instance inhabited (n : ℕ) : inhabited (zmod n) := ⟨0⟩ /-- `val a` is a natural number defined as: - for `a : zmod 0` it is the absolute value of `a` - for `a : zmod n` with `0 < n` it is the least natural number in the equivalence class See `zmod.val_min_abs` for a variant that takes values in the integers. -/ def val : Π {n : ℕ}, zmod n → ℕ | 0 := int.nat_abs | (n+1) := fin.val lemma val_lt {n : ℕ} [fact (0 < n)] (a : zmod n) : a.val < n := begin unfreezeI, cases n, { exfalso, exact nat.not_lt_zero 0 ‹0 < 0› }, exact fin.is_lt a end @[simp] lemma val_zero : ∀ {n}, (0 : zmod n).val = 0 | 0 := rfl | (n+1) := rfl lemma val_cast_nat {n : ℕ} (a : ℕ) : (a : zmod n).val = a % n := begin unfreezeI, cases n, { rw [nat.mod_zero, int.nat_cast_eq_coe_nat], exact int.nat_abs_of_nat a, }, rw ← fin.of_nat_eq_coe, refl end instance (n : ℕ) : char_p (zmod n) n := { cast_eq_zero_iff := begin intro k, cases n, { simp only [int.nat_cast_eq_coe_nat, zero_dvd_iff, int.coe_nat_eq_zero], }, rw [fin.eq_iff_veq], show (k : zmod (n+1)).val = (0 : zmod (n+1)).val ↔ _, rw [val_cast_nat, val_zero, nat.dvd_iff_mod_eq_zero], end } @[simp] lemma cast_self (n : ℕ) : (n : zmod n) = 0 := char_p.cast_eq_zero (zmod n) n @[simp] lemma cast_self' (n : ℕ) : (n + 1 : zmod (n + 1)) = 0 := by rw [← nat.cast_add_one, cast_self (n + 1)] section universal_property variables {n : ℕ} {R : Type*} section variables [has_zero R] [has_one R] [has_add R] [has_neg R] /-- Cast an integer modulo `n` to another semiring. This function is a morphism if the characteristic of `R` divides `n`. See `zmod.cast_hom` for a bundled version. -/ def cast : Π {n : ℕ}, zmod n → R | 0 := int.cast | (n+1) := λ i, i.val -- see Note [coercion into rings] @[priority 900] instance (n : ℕ) : has_coe_t (zmod n) R := ⟨cast⟩ @[simp] lemma cast_zero : ((0 : zmod n) : R) = 0 := by { cases n; refl } end lemma nat_cast_surjective [fact (0 < n)] : function.surjective (coe : ℕ → zmod n) := begin assume i, unfreezeI, cases n, { exfalso, exact nat.not_lt_zero 0 ‹0 < 0› }, { refine ⟨i.val, _⟩, cases i with i hi, induction i with i IH, { ext, refl }, show (i+1 : zmod (n+1)) = _, specialize IH (lt_of_le_of_lt i.le_succ hi), ext, erw [fin.val_add, IH], suffices : fin.val (1 : zmod (n+1)) = 1, { rw this, apply nat.mod_eq_of_lt hi }, show 1 % (n+1) = 1, apply nat.mod_eq_of_lt, apply lt_of_le_of_lt _ hi, exact le_of_inf_eq rfl } end lemma int_cast_surjective : function.surjective (coe : ℤ → zmod n) := begin assume i, cases n, { exact ⟨i, int.cast_id i⟩ }, { rcases nat_cast_surjective i with ⟨k, rfl⟩, refine ⟨k, _⟩, norm_cast } end lemma cast_val {n : ℕ} [fact (0 < n)] (a : zmod n) : (a.val : zmod n) = a := begin rcases nat_cast_surjective a with ⟨k, rfl⟩, symmetry, rw [val_cast_nat, ← sub_eq_zero, ← nat.cast_sub, char_p.cast_eq_zero_iff (zmod n) n], { apply nat.dvd_sub_mod }, { apply nat.mod_le } end @[simp, norm_cast] lemma cast_id : ∀ n (i : zmod n), ↑i = i | 0 i := int.cast_id i | (n+1) i := cast_val i variables [ring R] @[simp] lemma nat_cast_val [fact (0 < n)] (i : zmod n) : (i.val : R) = i := begin unfreezeI, cases n, { exfalso, exact nat.not_lt_zero 0 ‹0 < 0› }, refl end variable [char_p R n] @[simp] lemma cast_one : ((1 : zmod n) : R) = 1 := begin unfreezeI, cases n, { exact int.cast_one }, show ((1 % (n+1) : ℕ) : R) = 1, cases n, { apply subsingleton.elim }, rw nat.mod_eq_of_lt, { exact nat.cast_one }, exact nat.lt_of_sub_eq_succ rfl end @[simp] lemma cast_add (a b : zmod n) : ((a + b : zmod n) : R) = a + b := begin unfreezeI, cases n, { apply int.cast_add }, show ((fin.val (a + b) : ℕ) : R) = fin.val a + fin.val b, symmetry, resetI, rw [fin.val_add, ← nat.cast_add, ← sub_eq_zero, ← nat.cast_sub, @char_p.cast_eq_zero_iff R _ n.succ], { apply nat.dvd_sub_mod }, { apply nat.mod_le } end @[simp] lemma cast_mul (a b : zmod n) : ((a * b : zmod n) : R) = a * b := begin unfreezeI, cases n, { apply int.cast_mul }, show ((fin.val (a * b) : ℕ) : R) = fin.val a * fin.val b, symmetry, resetI, rw [fin.val_mul, ← nat.cast_mul, ← sub_eq_zero, ← nat.cast_sub, @char_p.cast_eq_zero_iff R _ n.succ], { apply nat.dvd_sub_mod }, { apply nat.mod_le } end /-- The canonical ring homomorphism from `zmod n` to a ring of characteristic `n`. -/ def cast_hom (n : ℕ) (R : Type*) [ring R] [char_p R n] : zmod n →+* R := { to_fun := coe, map_zero' := cast_zero, map_one' := cast_one, map_add' := cast_add, map_mul' := cast_mul } @[simp] lemma cast_hom_apply (i : zmod n) : cast_hom n R i = i := rfl @[simp, norm_cast] lemma cast_nat_cast (k : ℕ) : ((k : zmod n) : R) = k := (cast_hom n R).map_nat_cast k @[simp, norm_cast] lemma cast_int_cast (k : ℤ) : ((k : zmod n) : R) = k := (cast_hom n R).map_int_cast k end universal_property lemma int_coe_eq_int_coe_iff (a b : ℤ) (c : ℕ) : (a : zmod c) = (b : zmod c) ↔ a ≡ b [ZMOD c] := char_p.int_coe_eq_int_coe_iff (zmod c) c a b lemma nat_coe_eq_nat_coe_iff (a b c : ℕ) : (a : zmod c) = (b : zmod c) ↔ a ≡ b [MOD c] := begin convert zmod.int_coe_eq_int_coe_iff a b c, simp [nat.modeq.modeq_iff_dvd, int.modeq.modeq_iff_dvd], end lemma int_coe_zmod_eq_zero_iff_dvd (a : ℤ) (b : ℕ) : (a : zmod b) = 0 ↔ (b : ℤ) ∣ a := begin change (a : zmod b) = ((0 : ℤ) : zmod b) ↔ (b : ℤ) ∣ a, rw [zmod.int_coe_eq_int_coe_iff, int.modeq.modeq_zero_iff], end lemma nat_coe_zmod_eq_zero_iff_dvd (a b : ℕ) : (a : zmod b) = 0 ↔ b ∣ a := begin change (a : zmod b) = ((0 : ℕ) : zmod b) ↔ b ∣ a, rw [zmod.nat_coe_eq_nat_coe_iff, nat.modeq.modeq_zero_iff], end @[push_cast] lemma cast_mod_int (a : ℤ) (b : ℕ) : ((a % b : ℤ) : zmod b) = (a : zmod b) := begin rw zmod.int_coe_eq_int_coe_iff, apply int.modeq.mod_modeq, end lemma val_injective (n : ℕ) [fact (0 < n)] : function.injective (zmod.val : zmod n → ℕ) := begin unfreezeI, cases n, { exfalso, exact nat.not_lt_zero 0 ‹_› }, assume a b h, ext, exact h end lemma val_one_eq_one_mod (n : ℕ) : (1 : zmod n).val = 1 % n := by rw [← nat.cast_one, val_cast_nat] lemma val_one (n : ℕ) [fact (1 < n)] : (1 : zmod n).val = 1 := by { rw val_one_eq_one_mod, exact nat.mod_eq_of_lt ‹1 < n› } lemma val_add {n : ℕ} [fact (0 < n)] (a b : zmod n) : (a + b).val = (a.val + b.val) % n := begin unfreezeI, cases n, { exfalso, exact nat.not_lt_zero 0 ‹0 < 0› }, { apply fin.val_add } end lemma val_mul {n : ℕ} (a b : zmod n) : (a * b).val = (a.val * b.val) % n := begin cases n, { rw nat.mod_zero, apply int.nat_abs_mul }, { apply fin.val_mul } end instance nonzero (n : ℕ) [fact (1 < n)] : nonzero (zmod n) := { zero_ne_one := assume h, zero_ne_one $ calc 0 = (0 : zmod n).val : by rw val_zero ... = (1 : zmod n).val : congr_arg zmod.val h ... = 1 : val_one n } /-- The inversion on `zmod n`. It is setup in such a way that `a * a⁻¹` is equal to `gcd a.val n`. In particular, if `a` is coprime to `n`, and hence a unit, `a * a⁻¹ = 1`. -/ def inv : Π (n : ℕ), zmod n → zmod n | 0 i := int.sign i | (n+1) i := nat.gcd_a i.val (n+1) instance (n : ℕ) : has_inv (zmod n) := ⟨inv n⟩ lemma inv_zero : ∀ (n : ℕ), (0 : zmod n)⁻¹ = 0 | 0 := int.sign_zero | (n+1) := show (nat.gcd_a _ (n+1) : zmod (n+1)) = 0, by { rw val_zero, unfold nat.gcd_a nat.xgcd nat.xgcd_aux, refl } lemma mul_inv_eq_gcd {n : ℕ} (a : zmod n) : a * a⁻¹ = nat.gcd a.val n := begin cases n, { calc a * a⁻¹ = a * int.sign a : rfl ... = a.nat_abs : by rw [int.mul_sign, int.nat_cast_eq_coe_nat] ... = a.val.gcd 0 : by rw nat.gcd_zero_right; refl }, { set k := n.succ, calc a * a⁻¹ = a * a⁻¹ + k * nat.gcd_b (val a) k : by rw [cast_self, zero_mul, add_zero] ... = ↑(↑a.val * nat.gcd_a (val a) k + k * nat.gcd_b (val a) k) : by { push_cast, rw cast_val, refl } ... = nat.gcd a.val k : (congr_arg coe (nat.gcd_eq_gcd_ab a.val k)).symm, } end @[simp] lemma cast_mod_nat (n : ℕ) (a : ℕ) : ((a % n : ℕ) : zmod n) = a := by conv {to_rhs, rw ← nat.mod_add_div a n}; simp lemma eq_iff_modeq_nat (n : ℕ) {a b : ℕ} : (a : zmod n) = b ↔ a ≡ b [MOD n] := begin cases n, { simp only [nat.modeq, int.coe_nat_inj', nat.mod_zero, int.nat_cast_eq_coe_nat], }, { rw [fin.ext_iff, nat.modeq, ← val_cast_nat, ← val_cast_nat], exact iff.rfl, } end lemma coe_mul_inv_eq_one {n : ℕ} (x : ℕ) (h : nat.coprime x n) : (x * x⁻¹ : zmod n) = 1 := begin rw [nat.coprime, nat.gcd_comm, nat.gcd_rec] at h, rw [mul_inv_eq_gcd, val_cast_nat, h, nat.cast_one], end /-- `unit_of_coprime` makes an element of `units (zmod n)` given a natural number `x` and a proof that `x` is coprime to `n` -/ def unit_of_coprime {n : ℕ} (x : ℕ) (h : nat.coprime x n) : units (zmod n) := ⟨x, x⁻¹, coe_mul_inv_eq_one x h, by rw [mul_comm, coe_mul_inv_eq_one x h]⟩ @[simp] lemma cast_unit_of_coprime {n : ℕ} (x : ℕ) (h : nat.coprime x n) : (unit_of_coprime x h : zmod n) = x := rfl lemma val_coe_unit_coprime {n : ℕ} (u : units (zmod n)) : nat.coprime (u : zmod n).val n := begin cases n, { rcases int.units_eq_one_or u with rfl|rfl; exact dec_trivial }, apply nat.modeq.coprime_of_mul_modeq_one ((u⁻¹ : units (zmod (n+1))) : zmod (n+1)).val, have := units.ext_iff.1 (mul_right_inv u), rw [units.coe_one] at this, rw [← eq_iff_modeq_nat, nat.cast_one, ← this], clear this, rw [← cast_val ((u * u⁻¹ : units (zmod (n+1))) : zmod (n+1))], rw [units.coe_mul, val_mul, cast_mod_nat], end @[simp] lemma inv_coe_unit {n : ℕ} (u : units (zmod n)) : (u : zmod n)⁻¹ = (u⁻¹ : units (zmod n)) := begin have := congr_arg (coe : ℕ → zmod n) (val_coe_unit_coprime u), rw [← mul_inv_eq_gcd, nat.cast_one] at this, let u' : units (zmod n) := ⟨u, (u : zmod n)⁻¹, this, by rwa mul_comm⟩, have h : u = u', { apply units.ext, refl }, rw h, refl end lemma mul_inv_of_unit {n : ℕ} (a : zmod n) (h : is_unit a) : a * a⁻¹ = 1 := begin rcases h with ⟨u, rfl⟩, rw [inv_coe_unit, u.mul_inv], end lemma inv_mul_of_unit {n : ℕ} (a : zmod n) (h : is_unit a) : a⁻¹ * a = 1 := by rw [mul_comm, mul_inv_of_unit a h] /-- Equivalence between the units of `zmod n` and the subtype of terms `x : zmod n` for which `x.val` is comprime to `n` -/ def units_equiv_coprime {n : ℕ} [fact (0 < n)] : units (zmod n) ≃ {x : zmod n // nat.coprime x.val n} := { to_fun := λ x, ⟨x, val_coe_unit_coprime x⟩, inv_fun := λ x, unit_of_coprime x.1.val x.2, left_inv := λ ⟨_, _, _, _⟩, units.ext (cast_val _), right_inv := λ ⟨_, _⟩, by simp } section totient open_locale nat @[simp] lemma card_units_eq_totient (n : ℕ) [fact (0 < n)] : fintype.card (units (zmod n)) = φ n := calc fintype.card (units (zmod n)) = fintype.card {x : zmod n // x.val.coprime n} : fintype.card_congr zmod.units_equiv_coprime ... = φ n : begin apply finset.card_congr (λ (a : {x : zmod n // x.val.coprime n}) _, a.1.val), { intro a, simp [a.1.val_lt, a.2.symm] {contextual := tt}, }, { intros _ _ _ _ h, rw subtype.ext, apply val_injective, exact h, }, { intros b hb, rw [finset.mem_filter, finset.mem_range] at hb, refine ⟨⟨b, _⟩, finset.mem_univ _, _⟩, { let u := unit_of_coprime b hb.2.symm, exact val_coe_unit_coprime u }, { show zmod.val (b : zmod n) = b, rw [val_cast_nat, nat.mod_eq_of_lt hb.1], } } end end totient instance subsingleton_units : subsingleton (units (zmod 2)) := ⟨λ x y, begin cases x with x xi, cases y with y yi, revert x y xi yi, exact dec_trivial end⟩ lemma le_div_two_iff_lt_neg (n : ℕ) [hn : fact ((n : ℕ) % 2 = 1)] {x : zmod n} (hx0 : x ≠ 0) : x.val ≤ (n / 2 : ℕ) ↔ (n / 2 : ℕ) < (-x).val := begin haveI npos : fact (0 < n) := by { apply (nat.eq_zero_or_pos n).resolve_left, resetI, rintro rfl, simpa [fact] using hn, }, have hn2 : (n : ℕ) / 2 < n := nat.div_lt_of_lt_mul ((lt_mul_iff_one_lt_left npos).2 dec_trivial), have hn2' : (n : ℕ) - n / 2 = n / 2 + 1, { conv {to_lhs, congr, rw [← nat.succ_sub_one n, nat.succ_sub npos]}, rw [← nat.two_mul_odd_div_two hn, two_mul, ← nat.succ_add, nat.add_sub_cancel], }, have hxn : (n : ℕ) - x.val < n, { rw [nat.sub_lt_iff (le_of_lt x.val_lt) (le_refl _), nat.sub_self], rw ← zmod.cast_val x at hx0, exact nat.pos_of_ne_zero (λ h, by simpa [h] using hx0) }, by conv {to_rhs, rw [← nat.succ_le_iff, nat.succ_eq_add_one, ← hn2', ← zero_add (- x), ← zmod.cast_self, ← sub_eq_add_neg, ← zmod.cast_val x, ← nat.cast_sub (le_of_lt x.val_lt), zmod.val_cast_nat, nat.mod_eq_of_lt hxn, nat.sub_le_sub_left_iff (le_of_lt x.val_lt)] } end lemma ne_neg_self (n : ℕ) [hn : fact ((n : ℕ) % 2 = 1)] {a : zmod n} (ha : a ≠ 0) : a ≠ -a := λ h, have a.val ≤ n / 2 ↔ (n : ℕ) / 2 < (-a).val := le_div_two_iff_lt_neg n ha, by rwa [← h, ← not_lt, not_iff_self] at this lemma neg_one_ne_one {n : ℕ} [fact (2 < n)] : (-1 : zmod n) ≠ 1 := char_p.neg_one_ne_one (zmod n) n @[simp] lemma neg_eq_self_mod_two : ∀ (a : zmod 2), -a = a := dec_trivial @[simp] lemma nat_abs_mod_two (a : ℤ) : (a.nat_abs : zmod 2) = a := begin cases a, { simp only [int.nat_abs_of_nat, int.cast_coe_nat, int.of_nat_eq_coe] }, { simp only [neg_eq_self_mod_two, nat.cast_succ, int.nat_abs, int.cast_neg_succ_of_nat] } end @[simp] lemma val_eq_zero : ∀ {n : ℕ} (a : zmod n), a.val = 0 ↔ a = 0 | 0 a := int.nat_abs_eq_zero | (n+1) a := by { rw fin.ext_iff, exact iff.rfl } lemma val_cast_of_lt {n : ℕ} {a : ℕ} (h : a < n) : (a : zmod n).val = a := by rw [val_cast_nat, nat.mod_eq_of_lt h] lemma neg_val' {n : ℕ} [fact (0 < n)] (a : zmod n) : (-a).val = (n - a.val) % n := begin have : ((-a).val + a.val) % n = (n - a.val + a.val) % n, { rw [←val_add, add_left_neg, nat.sub_add_cancel (le_of_lt a.val_lt), nat.mod_self, val_zero], }, calc (-a).val = val (-a) % n : by rw nat.mod_eq_of_lt ((-a).val_lt) ... = (n - val a) % n : nat.modeq.modeq_add_cancel_right rfl this end lemma neg_val {n : ℕ} [fact (0 < n)] (a : zmod n) : (-a).val = if a = 0 then 0 else n - a.val := begin rw neg_val', by_cases h : a = 0, { rw [if_pos h, h, val_zero, nat.sub_zero, nat.mod_self] }, rw if_neg h, apply nat.mod_eq_of_lt, apply nat.sub_lt ‹0 < n›, contrapose! h, rwa [nat.le_zero_iff, val_eq_zero] at h, end /-- `val_min_abs x` returns the integer in the same equivalence class as `x` that is closest to `0`, The result will be in the interval `(-n/2, n/2]`. -/ def val_min_abs : Π {n : ℕ}, zmod n → ℤ | 0 x := x | n@(_+1) x := if x.val ≤ n / 2 then x.val else (x.val : ℤ) - n @[simp] lemma val_min_abs_def_zero (x : zmod 0) : val_min_abs x = x := rfl lemma val_min_abs_def_pos {n : ℕ} [fact (0 < n)] (x : zmod n) : val_min_abs x = if x.val ≤ n / 2 then x.val else x.val - n := begin unfreezeI, cases n, { exfalso, exact nat.not_lt_zero 0 ‹0 < 0› }, { refl } end @[simp] lemma coe_val_min_abs : ∀ {n : ℕ} (x : zmod n), (x.val_min_abs : zmod n) = x | 0 x := int.cast_id x | k@(n+1) x := begin rw val_min_abs_def_pos, split_ifs, { rw [int.cast_coe_nat, cast_val] }, { rw [int.cast_sub, int.cast_coe_nat, cast_val, int.cast_coe_nat, cast_self, sub_zero], } end lemma nat_abs_val_min_abs_le {n : ℕ} [fact (0 < n)] (x : zmod n) : x.val_min_abs.nat_abs ≤ n / 2 := begin rw zmod.val_min_abs_def_pos, split_ifs with h, { exact h }, have : (x.val - n : ℤ) ≤ 0, { rw [sub_nonpos, int.coe_nat_le], exact le_of_lt x.val_lt, }, rw [← int.coe_nat_le, int.of_nat_nat_abs_of_nonpos this, neg_sub], conv_lhs { congr, rw [← nat.mod_add_div n 2, int.coe_nat_add, int.coe_nat_mul, int.coe_nat_bit0, int.coe_nat_one] }, suffices : ((n % 2 : ℕ) + (n / 2) : ℤ) ≤ (val x), { rw ← sub_nonneg at this ⊢, apply le_trans this (le_of_eq _), ring }, norm_cast, calc (n : ℕ) % 2 + n / 2 ≤ 1 + n / 2 : nat.add_le_add_right (nat.le_of_lt_succ (nat.mod_lt _ dec_trivial)) _ ... ≤ x.val : by { rw add_comm, exact nat.succ_le_of_lt (lt_of_not_ge h) } end @[simp] lemma val_min_abs_zero : ∀ n, (0 : zmod n).val_min_abs = 0 | 0 := by simp only [val_min_abs_def_zero] | (n+1) := by simp only [val_min_abs_def_pos, if_true, int.coe_nat_zero, zero_le, val_zero] @[simp] lemma val_min_abs_eq_zero {n : ℕ} (x : zmod n) : x.val_min_abs = 0 ↔ x = 0 := begin cases n, { simp }, split, { simp only [val_min_abs_def_pos, int.coe_nat_succ], split_ifs with h h; assume h0, { apply val_injective, rwa [int.coe_nat_eq_zero] at h0, }, { apply absurd h0, rw sub_eq_zero, apply ne_of_lt, exact_mod_cast x.val_lt } }, { rintro rfl, rw val_min_abs_zero } end lemma cast_nat_abs_val_min_abs {n : ℕ} [fact (0 < n)] (a : zmod n) : (a.val_min_abs.nat_abs : zmod n) = if a.val ≤ (n : ℕ) / 2 then a else -a := begin have : (a.val : ℤ) - n ≤ 0, by { erw [sub_nonpos, int.coe_nat_le], exact le_of_lt a.val_lt, }, rw [zmod.val_min_abs_def_pos], split_ifs, { rw [int.nat_abs_of_nat, cast_val] }, { rw [← int.cast_coe_nat, int.of_nat_nat_abs_of_nonpos this, int.cast_neg, int.cast_sub], rw [int.cast_coe_nat, int.cast_coe_nat, cast_self, sub_zero, cast_val], } end @[simp] lemma nat_abs_val_min_abs_neg {n : ℕ} (a : zmod n) : (-a).val_min_abs.nat_abs = a.val_min_abs.nat_abs := begin cases n, { simp only [int.nat_abs_neg, val_min_abs_def_zero], }, by_cases ha0 : a = 0, { rw [ha0, neg_zero] }, by_cases haa : -a = a, { rw [haa] }, suffices hpa : (n+1 : ℕ) - a.val ≤ (n+1) / 2 ↔ (n+1 : ℕ) / 2 < a.val, { rw [val_min_abs_def_pos, val_min_abs_def_pos], rw ← not_le at hpa, simp only [if_neg ha0, neg_val, hpa, int.coe_nat_sub (le_of_lt a.val_lt)], split_ifs, all_goals { rw [← int.nat_abs_neg], congr' 1, ring } }, suffices : (((n+1 : ℕ) % 2) + 2 * ((n + 1) / 2)) - a.val ≤ (n+1) / 2 ↔ (n+1 : ℕ) / 2 < a.val, by rwa [nat.mod_add_div] at this, suffices : (n + 1) % 2 + (n + 1) / 2 ≤ val a ↔ (n + 1) / 2 < val a, by rw [nat.sub_le_iff, two_mul, ← add_assoc, nat.add_sub_cancel, this], cases (n + 1 : ℕ).mod_two_eq_zero_or_one with hn0 hn1, { split, { assume h, apply lt_of_le_of_ne (le_trans (nat.le_add_left _ _) h), contrapose! haa, rw [← zmod.cast_val a, ← haa, neg_eq_iff_add_eq_zero, ← nat.cast_add], rw [char_p.cast_eq_zero_iff (zmod (n+1)) (n+1)], rw [← two_mul, ← zero_add (2 * _), ← hn0, nat.mod_add_div] }, { rw [hn0, zero_add], exact le_of_lt } }, { rw [hn1, add_comm, nat.succ_le_iff] } end lemma val_eq_ite_val_min_abs {n : ℕ} [fact (0 < n)] (a : zmod n) : (a.val : ℤ) = a.val_min_abs + if a.val ≤ n / 2 then 0 else n := by { rw [zmod.val_min_abs_def_pos], split_ifs; simp only [add_zero, sub_add_cancel] } lemma prime_ne_zero (p q : ℕ) [hp : fact p.prime] [hq : fact q.prime] (hpq : p ≠ q) : (q : zmod p) ≠ 0 := by rwa [← nat.cast_zero, ne.def, eq_iff_modeq_nat, nat.modeq.modeq_zero_iff, ← hp.coprime_iff_not_dvd, nat.coprime_primes hp hq] end zmod namespace zmod variables (p : ℕ) [fact p.prime] private lemma mul_inv_cancel_aux (a : zmod p) (h : a ≠ 0) : a * a⁻¹ = 1 := begin obtain ⟨k, rfl⟩ := nat_cast_surjective a, apply coe_mul_inv_eq_one, apply nat.coprime.symm, rwa [nat.prime.coprime_iff_not_dvd ‹p.prime›, ← char_p.cast_eq_zero_iff (zmod p)] end /-- Field structure on `zmod p` if `p` is prime. -/ instance : field (zmod p) := { mul_inv_cancel := mul_inv_cancel_aux p, inv_zero := inv_zero p, .. zmod.comm_ring p, .. zmod.nonzero p, .. zmod.has_inv p } end zmod lemma ring_hom.ext_zmod {n : ℕ} {R : Type*} [semiring R] (f g : (zmod n) →+* R) : f = g := begin ext a, obtain ⟨k, rfl⟩ := zmod.int_cast_surjective a, let φ : ℤ →+* R := f.comp (int.cast_ring_hom (zmod n)), let ψ : ℤ →+* R := g.comp (int.cast_ring_hom (zmod n)), show φ k = ψ k, rw φ.ext_int ψ, end instance zmod.subsingleton_ring_hom {n : ℕ} {R : Type*} [semiring R] : subsingleton ((zmod n) →+* R) := ⟨ring_hom.ext_zmod⟩
4ad2bf845bc181a8617ce787391b8f472753c5e7
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch4/ex0409.lean
ad29cd97e8558f91354b1f5b10a4c8874cd61057
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
420
lean
def is_even (a : ℕ) := ∃ b, a = 2 * b theorem even_plus_even {a b : ℕ} (h1 : is_even a) (h2 : is_even b) : is_even (a + b) := exists.elim h1 (assume w1, assume hw1, exists.elim h2 (assume w2, assume hw2, exists.intro (w1 + w2) (calc a + b = 2 * w1 + 2 * w2 : by rw [hw1, hw2] ... = 2 * (w1 + w2) : by rw mul_add)))
200d9b4e7cdb6052fcb98928b0a6179087b4a31b
ba4794a0deca1d2aaa68914cd285d77880907b5c
/src/game/world10/level1.lean
f066829c7d24c4eda50562cf146cd2c384eca015
[ "Apache-2.0" ]
permissive
ChrisHughes24/natural_number_game
c7c00aa1f6a95004286fd456ed13cf6e113159ce
9d09925424da9f6275e6cfe427c8bcf12bb0944f
refs/heads/master
1,600,715,773,528
1,573,910,462,000
1,573,910,462,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,381
lean
import mynat.le -- import definition of ≤ import game.world9.level4 import game.world4.level8 namespace mynat -- hide /- Axiom : le_iff_exists_add (a b : mynat) a ≤ b ↔ ∃ (c : mynat), b = a + c -/ /- Tactic : use ## Summary `use` works on the goal. If your goal is `⊢ ∃ c : mynat, 1 + x = x + c` then `use 1` will turn the goal into `⊢ 1 + x = x + 1`, and the rather more unwise `use 0` will turn it into the impossible-to-prove `⊢ 1 + x = x + 0`. ## Details `use` is a tactic which works on goals of the form `⊢ ∃ c, P(c)` where `P(c)` is some proposition which depends on `c`. With a goal of this form, `use 0` will turn the goal into `⊢ P(0)`, `use x + y` (assuming `x` and `y` are natural numbers in your local context) will turn the goal into `P(x + y)` and so on. -/ -- World name : Inequality world /- # Inequality world. A new import, giving us a new definition. If `a` and `b` are naturals, `a ≤ b` is *defined* to mean `∃ (c : mynat), b = a + c` The upside-down E means "there exists". So in words, $a\le b$ if and only if there exists a natural $c$ such that $b=a+c$. If you really want to change an `a ≤ b` to `∃ c, b = a + c` then you can do so with `rw le_iff_exists_add`: ``` le_iff_exists_add (a b : mynat) : a ≤ b ↔ ∃ (c : mynat), b = a + c ``` But because `a ≤ b` is *defined as* `∃ (c : mynat), b = a + c`, you do not need to `rw le_iff_exists_add`, you can just pretend when you see `a ≤ b` that it says `∃ (c : mynat), b = a + c`. You will see a concrete example of this below. A new construction like `∃` means that we need to learn how to manipulate it. There are two situations. Firstly we need to know how to solve a goal of the form `⊢ ∃ c, ...`, and secondly we need to know how to use a hypothesi of the form `∃ c, ...`. ## Level 1: the `use` tactic. The goal below is to prove $x\le 1+x$ for any natural number $x$. First let's turn the goal explicitly into an existence problem with `rw le_iff_exists_add,` and now the goal has become `∃ c : mynat, 1 + x = x + c`. Clearly this statement is true, and the proof is that $c=1$ will work (we also need the fact that addition is commutative, but we proved that a long time ago). How do we make progress with this goal? The `use` tactic can be used on goals of the form `∃ c, ...`. The idea is that we choose which natural number we want to use, and then we use it. So try `use 1,` and now the goal becomes `⊢ 1 + x = x + 1`. You can solve this by `exact add_comm 1 x`, or if you are lazy you can just use the `ring` tactic, which is a powerful AI which will solve any equality in algebra which can be proved using the standard rules of addition and multiplication. Now look at your proof. We're going to remove a line. ## Important An important time-saver here is to note that because `a ≤ b` is *defined* as `∃ c : mynat, b = a + c`, you *do not need to write `rw le_iff_exists_add`*. The `use` tactic will work directly on a goal of the form `a ≤ b`. Just use the difference `b - a` (note that we have not defined subtraction so this does not formally make sense, but you can do the calculation in your head). -/ /- Lemma : no-side-bar If $x$ is a natural number, then $x\le 1+x$. -/ lemma one_add_le_self (x : mynat) : x ≤ 1 + x := begin rw le_iff_exists_add, use 1, ring, end end mynat -- hide
eeb4961972d4d08ee82431cf593e9725b917f237
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/comma.lean
c78fa975d0b0ab7cb1be15934e97ce8c9f2560c7
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
8,904
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Johan Commelin, Bhavik Mehta -/ import category_theory.isomorphism import category_theory.functor.category import category_theory.eq_to_hom /-! # Comma categories > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. A comma category is a construction in category theory, which builds a category out of two functors with a common codomain. Specifically, for functors `L : A ⥤ T` and `R : B ⥤ T`, an object in `comma L R` is a morphism `hom : L.obj left ⟶ R.obj right` for some objects `left : A` and `right : B`, and a morphism in `comma L R` between `hom : L.obj left ⟶ R.obj right` and `hom' : L.obj left' ⟶ R.obj right'` is a commutative square ``` L.obj left ⟶ L.obj left' | | hom | | hom' ↓ ↓ R.obj right ⟶ R.obj right', ``` where the top and bottom morphism come from morphisms `left ⟶ left'` and `right ⟶ right'`, respectively. ## Main definitions * `comma L R`: the comma category of the functors `L` and `R`. * `over X`: the over category of the object `X` (developed in `over.lean`). * `under X`: the under category of the object `X` (also developed in `over.lean`). * `arrow T`: the arrow category of the category `T` (developed in `arrow.lean`). ## References * <https://ncatlab.org/nlab/show/comma+category> ## Tags comma, slice, coslice, over, under, arrow -/ namespace category_theory -- declare the `v`'s first; see `category_theory.category` for an explanation universes v₁ v₂ v₃ v₄ v₅ u₁ u₂ u₃ u₄ u₅ variables {A : Type u₁} [category.{v₁} A] variables {B : Type u₂} [category.{v₂} B] variables {T : Type u₃} [category.{v₃} T] /-- The objects of the comma category are triples of an object `left : A`, an object `right : B` and a morphism `hom : L.obj left ⟶ R.obj right`. -/ structure comma (L : A ⥤ T) (R : B ⥤ T) : Type (max u₁ u₂ v₃) := (left : A) (right : B) (hom : L.obj left ⟶ R.obj right) -- Satisfying the inhabited linter instance comma.inhabited [inhabited T] : inhabited (comma (𝟭 T) (𝟭 T)) := { default := { left := default, right := default, hom := 𝟙 default } } variables {L : A ⥤ T} {R : B ⥤ T} /-- A morphism between two objects in the comma category is a commutative square connecting the morphisms coming from the two objects using morphisms in the image of the functors `L` and `R`. -/ @[ext] structure comma_morphism (X Y : comma L R) := (left : X.left ⟶ Y.left) (right : X.right ⟶ Y.right) (w' : L.map left ≫ Y.hom = X.hom ≫ R.map right . obviously) -- Satisfying the inhabited linter instance comma_morphism.inhabited [inhabited (comma L R)] : inhabited (comma_morphism (default : comma L R) default) := ⟨⟨𝟙 _, 𝟙 _⟩⟩ restate_axiom comma_morphism.w' attribute [simp, reassoc] comma_morphism.w instance comma_category : category (comma L R) := { hom := comma_morphism, id := λ X, { left := 𝟙 X.left, right := 𝟙 X.right }, comp := λ X Y Z f g, { left := f.left ≫ g.left, right := f.right ≫ g.right } } namespace comma section variables {X Y Z : comma L R} {f : X ⟶ Y} {g : Y ⟶ Z} @[simp] lemma id_left : ((𝟙 X) : comma_morphism X X).left = 𝟙 X.left := rfl @[simp] lemma id_right : ((𝟙 X) : comma_morphism X X).right = 𝟙 X.right := rfl @[simp] lemma comp_left : (f ≫ g).left = f.left ≫ g.left := rfl @[simp] lemma comp_right : (f ≫ g).right = f.right ≫ g.right := rfl end variables (L) (R) /-- The functor sending an object `X` in the comma category to `X.left`. -/ @[simps] def fst : comma L R ⥤ A := { obj := λ X, X.left, map := λ _ _ f, f.left } /-- The functor sending an object `X` in the comma category to `X.right`. -/ @[simps] def snd : comma L R ⥤ B := { obj := λ X, X.right, map := λ _ _ f, f.right } /-- We can interpret the commutative square constituting a morphism in the comma category as a natural transformation between the functors `fst ⋙ L` and `snd ⋙ R` from the comma category to `T`, where the components are given by the morphism that constitutes an object of the comma category. -/ @[simps] def nat_trans : fst L R ⋙ L ⟶ snd L R ⋙ R := { app := λ X, X.hom } @[simp] lemma eq_to_hom_left (X Y : comma L R) (H : X = Y) : comma_morphism.left (eq_to_hom H) = eq_to_hom (by { cases H, refl }) := by { cases H, refl } @[simp] lemma eq_to_hom_right (X Y : comma L R) (H : X = Y) : comma_morphism.right (eq_to_hom H) = eq_to_hom (by { cases H, refl }) := by { cases H, refl } section variables {L₁ L₂ L₃ : A ⥤ T} {R₁ R₂ R₃ : B ⥤ T} /-- Construct an isomorphism in the comma category given isomorphisms of the objects whose forward directions give a commutative square. -/ @[simps] def iso_mk {X Y : comma L₁ R₁} (l : X.left ≅ Y.left) (r : X.right ≅ Y.right) (h : L₁.map l.hom ≫ Y.hom = X.hom ≫ R₁.map r.hom) : X ≅ Y := { hom := { left := l.hom, right := r.hom }, inv := { left := l.inv, right := r.inv, w' := begin rw [←L₁.map_iso_inv l, iso.inv_comp_eq, L₁.map_iso_hom, reassoc_of h, ← R₁.map_comp], simp end, } } /-- A natural transformation `L₁ ⟶ L₂` induces a functor `comma L₂ R ⥤ comma L₁ R`. -/ @[simps] def map_left (l : L₁ ⟶ L₂) : comma L₂ R ⥤ comma L₁ R := { obj := λ X, { left := X.left, right := X.right, hom := l.app X.left ≫ X.hom }, map := λ X Y f, { left := f.left, right := f.right } } /-- The functor `comma L R ⥤ comma L R` induced by the identity natural transformation on `L` is naturally isomorphic to the identity functor. -/ @[simps] def map_left_id : map_left R (𝟙 L) ≅ 𝟭 _ := { hom := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } }, inv := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } } } /-- The functor `comma L₁ R ⥤ comma L₃ R` induced by the composition of two natural transformations `l : L₁ ⟶ L₂` and `l' : L₂ ⟶ L₃` is naturally isomorphic to the composition of the two functors induced by these natural transformations. -/ @[simps] def map_left_comp (l : L₁ ⟶ L₂) (l' : L₂ ⟶ L₃) : (map_left R (l ≫ l')) ≅ (map_left R l') ⋙ (map_left R l) := { hom := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } }, inv := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } } } /-- A natural transformation `R₁ ⟶ R₂` induces a functor `comma L R₁ ⥤ comma L R₂`. -/ @[simps] def map_right (r : R₁ ⟶ R₂) : comma L R₁ ⥤ comma L R₂ := { obj := λ X, { left := X.left, right := X.right, hom := X.hom ≫ r.app X.right }, map := λ X Y f, { left := f.left, right := f.right } } /-- The functor `comma L R ⥤ comma L R` induced by the identity natural transformation on `R` is naturally isomorphic to the identity functor. -/ @[simps] def map_right_id : map_right L (𝟙 R) ≅ 𝟭 _ := { hom := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } }, inv := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } } } /-- The functor `comma L R₁ ⥤ comma L R₃` induced by the composition of the natural transformations `r : R₁ ⟶ R₂` and `r' : R₂ ⟶ R₃` is naturally isomorphic to the composition of the functors induced by these natural transformations. -/ @[simps] def map_right_comp (r : R₁ ⟶ R₂) (r' : R₂ ⟶ R₃) : (map_right L (r ≫ r')) ≅ (map_right L r) ⋙ (map_right L r') := { hom := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } }, inv := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } } } end section variables {C : Type u₄} [category.{v₄} C] {D : Type u₅} [category.{v₅} D] /-- The functor `(F ⋙ L, R) ⥤ (L, R)` -/ @[simps] def pre_left (F: C ⥤ A) (L : A ⥤ T) (R : B ⥤ T) : comma (F ⋙ L) R ⥤ comma L R := { obj := λ X, { left := F.obj X.left, right := X.right, hom := X.hom }, map := λ X Y f, { left := F.map f.left, right := f.right, w' := by simpa using f.w } } /-- The functor `(F ⋙ L, R) ⥤ (L, R)` -/ @[simps] def pre_right (L : A ⥤ T) (F: C ⥤ B) (R : B ⥤ T) : comma L (F ⋙ R) ⥤ comma L R := { obj := λ X, { left := X.left, right := F.obj X.right, hom := X.hom }, map := λ X Y f, { left := f.left, right := F.map f.right, w' := by simp } } /-- The functor `(L, R) ⥤ (L ⋙ F, R ⋙ F)` -/ @[simps] def post (L : A ⥤ T) (R : B ⥤ T) (F: T ⥤ C) : comma L R ⥤ comma (L ⋙ F) (R ⋙ F) := { obj := λ X, { left := X.left, right := X.right, hom := F.map X.hom }, map := λ X Y f, { left := f.left, right := f.right, w' := by { simp only [functor.comp_map, ←F.map_comp, f.w] } } } end end comma end category_theory
0c0ac92a57f63ae7ea1b3965db5fd507fb85b1fb
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/set_theory/ordinal/basic.lean
6c36f67c2e29f8cd90085f474fcb6a71fbb882fa
[ "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
49,516
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Floris van Doorn -/ import data.sum.order import order.initial_seg import set_theory.cardinal.basic /-! # Ordinals Ordinals are defined as equivalences of well-ordered sets under order isomorphism. They are endowed with a total order, where an ordinal is smaller than another one if it embeds into it as an initial segment (or, equivalently, in any way). This total order is well founded. ## Main definitions * `ordinal`: the type of ordinals (in a given universe) * `ordinal.type r`: given a well-founded order `r`, this is the corresponding ordinal * `ordinal.typein r a`: given a well-founded order `r` on a type `α`, and `a : α`, the ordinal corresponding to all elements smaller than `a`. * `enum r o h`: given a well-order `r` on a type `α`, and an ordinal `o` strictly smaller than the ordinal corresponding to `r` (this is the assumption `h`), returns the `o`-th element of `α`. In other words, the elements of `α` can be enumerated using ordinals up to `type r`. * `ordinal.card o`: the cardinality of an ordinal `o`. * `ordinal.lift` lifts an ordinal in universe `u` to an ordinal in universe `max u v`. For a version registering additionally that this is an initial segment embedding, see `ordinal.lift.initial_seg`. For a version regiserting that it is a principal segment embedding if `u < v`, see `ordinal.lift.principal_seg`. * `ordinal.omega` or `ω` is the order type of `ℕ`. This definition is universe polymorphic: `ordinal.omega.{u} : ordinal.{u}` (contrast with `ℕ : Type`, which lives in a specific universe). In some cases the universe level has to be given explicitly. * `o₁ + o₂` is the order on the disjoint union of `o₁` and `o₂` obtained by declaring that every element of `o₁` is smaller than every element of `o₂`. The main properties of addition (and the other operations on ordinals) are stated and proved in `ordinal_arithmetic.lean`. Here, we only introduce it and prove its basic properties to deduce the fact that the order on ordinals is total (and well founded). * `succ o` is the successor of the ordinal `o`. * `cardinal.ord c`: when `c` is a cardinal, `ord c` is the smallest ordinal with this cardinality. It is the canonical way to represent a cardinal with an ordinal. A conditionally complete linear order with bot structure is registered on ordinals, where `⊥` is `0`, the ordinal corresponding to the empty type, and `Inf` is the minimum for nonempty sets and `0` for the empty set by convention. ## Notations * `ω` is a notation for the first infinite ordinal in the locale `ordinal`. -/ noncomputable theory open function cardinal set equiv order open_locale classical cardinal initial_seg universes u v w variables {α : Type*} {β : Type*} {γ : Type*} {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} /-! ### Well order on an arbitrary type -/ section well_ordering_thm parameter {σ : Type u} open function theorem nonempty_embedding_to_cardinal : nonempty (σ ↪ cardinal.{u}) := (embedding.total _ _).resolve_left $ λ ⟨⟨f, hf⟩⟩, let g : σ → cardinal.{u} := inv_fun f in let ⟨x, (hx : g x = 2 ^ sum g)⟩ := inv_fun_surjective hf (2 ^ sum g) in have g x ≤ sum g, from le_sum.{u u} g x, not_le_of_gt (by rw hx; exact cantor _) this /-- An embedding of any type to the set of cardinals. -/ def embedding_to_cardinal : σ ↪ cardinal.{u} := classical.choice nonempty_embedding_to_cardinal /-- Any type can be endowed with a well order, obtained by pulling back the well order over cardinals by some embedding. -/ def well_ordering_rel : σ → σ → Prop := embedding_to_cardinal ⁻¹'o (<) instance well_ordering_rel.is_well_order : is_well_order σ well_ordering_rel := (rel_embedding.preimage _ _).is_well_order instance is_well_order.subtype_nonempty : nonempty {r // is_well_order σ r} := ⟨⟨well_ordering_rel, infer_instance⟩⟩ end well_ordering_thm /-! ### Definition of ordinals -/ /-- Bundled structure registering a well order on a type. Ordinals will be defined as a quotient of this type. -/ structure Well_order : Type (u+1) := (α : Type u) (r : α → α → Prop) (wo : is_well_order α r) attribute [instance] Well_order.wo namespace Well_order instance : inhabited Well_order := ⟨⟨pempty, _, empty_relation.is_well_order⟩⟩ @[simp] lemma eta (o : Well_order) : mk o.α o.r o.wo = o := by { cases o, refl } end Well_order /-- Equivalence relation on well orders on arbitrary types in universe `u`, given by order isomorphism. -/ instance ordinal.is_equivalent : setoid Well_order := { r := λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, nonempty (r ≃r s), iseqv := ⟨λ ⟨α, r, _⟩, ⟨rel_iso.refl _⟩, λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨e⟩, ⟨e.symm⟩, λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨e₁⟩ ⟨e₂⟩, ⟨e₁.trans e₂⟩⟩ } /-- `ordinal.{u}` is the type of well orders in `Type u`, up to order isomorphism. -/ def ordinal : Type (u + 1) := quotient ordinal.is_equivalent instance has_well_founded_out (o : ordinal) : has_well_founded o.out.α := ⟨o.out.r, o.out.wo.wf⟩ instance linear_order_out (o : ordinal) : linear_order o.out.α := is_well_order.linear_order o.out.r instance is_well_order_out_lt (o : ordinal) : is_well_order o.out.α (<) := o.out.wo namespace ordinal /- ### Basic properties of the order type -/ /-- The order type of a well order is an ordinal. -/ def type (r : α → α → Prop) [wo : is_well_order α r] : ordinal := ⟦⟨α, r, wo⟩⟧ instance : has_zero ordinal := ⟨type $ @empty_relation pempty⟩ instance : inhabited ordinal := ⟨0⟩ instance : has_one ordinal := ⟨type $ @empty_relation punit⟩ /-- The order type of an element inside a well order. For the embedding as a principal segment, see `typein.principal_seg`. -/ def typein (r : α → α → Prop) [is_well_order α r] (a : α) : ordinal := type (subrel r {b | r b a}) @[simp] theorem type_def' (w : Well_order) : ⟦w⟧ = type w.r := by { cases w, refl } @[simp] theorem type_def (r) [wo : is_well_order α r] : (⟦⟨α, r, wo⟩⟧ : ordinal) = type r := rfl @[simp] lemma type_out (o : ordinal) : ordinal.type o.out.r = o := by rw [ordinal.type, Well_order.eta, quotient.out_eq] theorem type_eq {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] : type r = type s ↔ nonempty (r ≃r s) := quotient.eq theorem _root_.rel_iso.ordinal_type_eq {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] (h : r ≃r s) : type r = type s := type_eq.2 ⟨h⟩ @[simp] theorem type_lt (o : ordinal) : type ((<) : o.out.α → o.out.α → Prop) = o := (type_def' _).symm.trans $ quotient.out_eq o theorem type_eq_zero_of_empty (r) [is_well_order α r] [is_empty α] : type r = 0 := (rel_iso.rel_iso_of_is_empty r _).ordinal_type_eq @[simp] theorem type_eq_zero_iff_is_empty [is_well_order α r] : type r = 0 ↔ is_empty α := ⟨λ h, let ⟨s⟩ := type_eq.1 h in s.to_equiv.is_empty, @type_eq_zero_of_empty α r _⟩ theorem type_ne_zero_iff_nonempty [is_well_order α r] : type r ≠ 0 ↔ nonempty α := by simp theorem type_ne_zero_of_nonempty (r) [is_well_order α r] [h : nonempty α] : type r ≠ 0 := type_ne_zero_iff_nonempty.2 h theorem type_pempty : type (@empty_relation pempty) = 0 := rfl theorem type_empty : type (@empty_relation empty) = 0 := type_eq_zero_of_empty _ theorem type_eq_one_of_unique (r) [is_well_order α r] [unique α] : type r = 1 := (rel_iso.rel_iso_of_unique_of_irrefl r _).ordinal_type_eq @[simp] theorem type_eq_one_iff_unique [is_well_order α r] : type r = 1 ↔ nonempty (unique α) := ⟨λ h, let ⟨s⟩ := type_eq.1 h in ⟨s.to_equiv.unique⟩, λ ⟨h⟩, @type_eq_one_of_unique α r _ h⟩ theorem type_punit : type (@empty_relation punit) = 1 := rfl theorem type_unit : type (@empty_relation unit) = 1 := rfl @[simp] theorem out_empty_iff_eq_zero {o : ordinal} : is_empty o.out.α ↔ o = 0 := by rw [←@type_eq_zero_iff_is_empty o.out.α (<), type_lt] lemma eq_zero_of_out_empty (o : ordinal) [h : is_empty o.out.α] : o = 0 := out_empty_iff_eq_zero.1 h instance is_empty_out_zero : is_empty (0 : ordinal).out.α := out_empty_iff_eq_zero.2 rfl @[simp] theorem out_nonempty_iff_ne_zero {o : ordinal} : nonempty o.out.α ↔ o ≠ 0 := by rw [←@type_ne_zero_iff_nonempty o.out.α (<), type_lt] lemma ne_zero_of_out_nonempty (o : ordinal) [h : nonempty o.out.α] : o ≠ 0 := out_nonempty_iff_ne_zero.1 h protected lemma one_ne_zero : (1 : ordinal) ≠ 0 := type_ne_zero_of_nonempty _ instance : nontrivial ordinal.{u} := ⟨⟨1, 0, ordinal.one_ne_zero⟩⟩ @[simp] theorem type_preimage {α β : Type u} (r : α → α → Prop) [is_well_order α r] (f : β ≃ α) : type (f ⁻¹'o r) = type r := (rel_iso.preimage f r).ordinal_type_eq @[elab_as_eliminator] theorem induction_on {C : ordinal → Prop} (o : ordinal) (H : ∀ α r [is_well_order α r], by exactI C (type r)) : C o := quot.induction_on o $ λ ⟨α, r, wo⟩, @H α r wo /-! ### The order on ordinals -/ instance : partial_order ordinal := { le := λ a b, quotient.lift_on₂ a b (λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, nonempty (r ≼i s)) $ λ ⟨α₁, r₁, o₁⟩ ⟨α₂, r₂, o₂⟩ ⟨β₁, s₁, p₁⟩ ⟨β₂, s₂, p₂⟩ ⟨f⟩ ⟨g⟩, propext ⟨ λ ⟨h⟩, ⟨(initial_seg.of_iso f.symm).trans $ h.trans (initial_seg.of_iso g)⟩, λ ⟨h⟩, ⟨(initial_seg.of_iso f).trans $ h.trans (initial_seg.of_iso g.symm)⟩⟩, lt := λ a b, quotient.lift_on₂ a b (λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, nonempty (r ≺i s)) $ λ ⟨α₁, r₁, o₁⟩ ⟨α₂, r₂, o₂⟩ ⟨β₁, s₁, p₁⟩ ⟨β₂, s₂, p₂⟩ ⟨f⟩ ⟨g⟩, by exactI propext ⟨ λ ⟨h⟩, ⟨principal_seg.equiv_lt f.symm $ h.lt_le (initial_seg.of_iso g)⟩, λ ⟨h⟩, ⟨principal_seg.equiv_lt f $ h.lt_le (initial_seg.of_iso g.symm)⟩⟩, le_refl := quot.ind $ by exact λ ⟨α, r, wo⟩, ⟨initial_seg.refl _⟩, le_trans := λ a b c, quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩ ⟨g⟩, ⟨f.trans g⟩, lt_iff_le_not_le := λ a b, quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩, by exactI ⟨λ ⟨f⟩, ⟨⟨f⟩, λ ⟨g⟩, (f.lt_le g).irrefl⟩, λ ⟨⟨f⟩, h⟩, sum.rec_on f.lt_or_eq (λ g, ⟨g⟩) (λ g, (h ⟨initial_seg.of_iso g.symm⟩).elim)⟩, le_antisymm := λ a b, quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨h₁⟩ ⟨h₂⟩, by exactI quot.sound ⟨initial_seg.antisymm h₁ h₂⟩ } /-- Ordinal less-equal is defined such that well orders `r` and `s` satisfy `type r ≤ type s` if there exists a function embedding `r` as an initial segment of `s`. -/ add_decl_doc ordinal.partial_order.le /-- Ordinal less-than is defined such that well orders `r` and `s` satisfy `type r < type s` if there exists a function embedding `r` as a principal segment of `s`. -/ add_decl_doc ordinal.partial_order.lt theorem type_le_iff {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] : type r ≤ type s ↔ nonempty (r ≼i s) := iff.rfl theorem type_le_iff' {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] : type r ≤ type s ↔ nonempty (r ↪r s) := ⟨λ ⟨f⟩, ⟨f⟩, λ ⟨f⟩, ⟨f.collapse⟩⟩ theorem _root_.initial_seg.ordinal_type_le {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] (h : r ≼i s) : type r ≤ type s := ⟨h⟩ theorem _root_.rel_embedding.ordinal_type_le {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] (h : r ↪r s) : type r ≤ type s := ⟨h.collapse⟩ @[simp] theorem type_lt_iff {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] : type r < type s ↔ nonempty (r ≺i s) := iff.rfl theorem _root_.principal_seg.ordinal_type_lt {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] (h : r ≺i s) : type r < type s := ⟨h⟩ protected theorem zero_le (o : ordinal) : 0 ≤ o := induction_on o $ λ α r _, by exactI (initial_seg.of_is_empty _ r).ordinal_type_le instance : order_bot ordinal := ⟨0, ordinal.zero_le⟩ @[simp] lemma bot_eq_zero : (⊥ : ordinal) = 0 := rfl @[simp] protected theorem le_zero {o : ordinal} : o ≤ 0 ↔ o = 0 := le_bot_iff protected theorem pos_iff_ne_zero {o : ordinal} : 0 < o ↔ o ≠ 0 := bot_lt_iff_ne_bot protected theorem not_lt_zero (o : ordinal) : ¬ o < 0 := not_lt_bot theorem eq_zero_or_pos : ∀ a : ordinal, a = 0 ∨ 0 < a := eq_bot_or_bot_lt instance : zero_le_one_class ordinal := ⟨ordinal.zero_le _⟩ instance ne_zero.one : ne_zero (1 : ordinal) := ⟨ordinal.one_ne_zero⟩ /-- Given two ordinals `α ≤ β`, then `initial_seg_out α β` is the initial segment embedding of `α` to `β`, as map from a model type for `α` to a model type for `β`. -/ def initial_seg_out {α β : ordinal} (h : α ≤ β) : initial_seg ((<) : α.out.α → α.out.α → Prop) ((<) : β.out.α → β.out.α → Prop) := begin change α.out.r ≼i β.out.r, rw [←quotient.out_eq α, ←quotient.out_eq β] at h, revert h, cases quotient.out α, cases quotient.out β, exact classical.choice end /-- Given two ordinals `α < β`, then `principal_seg_out α β` is the principal segment embedding of `α` to `β`, as map from a model type for `α` to a model type for `β`. -/ def principal_seg_out {α β : ordinal} (h : α < β) : principal_seg ((<) : α.out.α → α.out.α → Prop) ((<) : β.out.α → β.out.α → Prop) := begin change α.out.r ≺i β.out.r, rw [←quotient.out_eq α, ←quotient.out_eq β] at h, revert h, cases quotient.out α, cases quotient.out β, exact classical.choice end theorem typein_lt_type (r : α → α → Prop) [is_well_order α r] (a : α) : typein r a < type r := ⟨principal_seg.of_element _ _⟩ theorem typein_lt_self {o : ordinal} (i : o.out.α) : typein (<) i < o := by { simp_rw ←type_lt o, apply typein_lt_type } @[simp] theorem typein_top {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] (f : r ≺i s) : typein s f.top = type r := eq.symm $ quot.sound ⟨rel_iso.of_surjective (rel_embedding.cod_restrict _ f f.lt_top) (λ ⟨a, h⟩, by rcases f.down.1 h with ⟨b, rfl⟩; exact ⟨b, rfl⟩)⟩ @[simp] theorem typein_apply {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] (f : r ≼i s) (a : α) : ordinal.typein s (f a) = ordinal.typein r a := eq.symm $ quotient.sound ⟨rel_iso.of_surjective (rel_embedding.cod_restrict _ ((subrel.rel_embedding _ _).trans f) (λ ⟨x, h⟩, by rw [rel_embedding.trans_apply]; exact f.to_rel_embedding.map_rel_iff.2 h)) (λ ⟨y, h⟩, by rcases f.init' h with ⟨a, rfl⟩; exact ⟨⟨a, f.to_rel_embedding.map_rel_iff.1 h⟩, subtype.eq $ rel_embedding.trans_apply _ _ _⟩)⟩ @[simp] theorem typein_lt_typein (r : α → α → Prop) [is_well_order α r] {a b : α} : typein r a < typein r b ↔ r a b := ⟨λ ⟨f⟩, begin have : f.top.1 = a, { let f' := principal_seg.of_element r a, let g' := f.trans (principal_seg.of_element r b), have : g'.top = f'.top, {rw subsingleton.elim f' g'}, exact this }, rw ← this, exact f.top.2 end, λ h, ⟨principal_seg.cod_restrict _ (principal_seg.of_element r a) (λ x, @trans _ r _ _ _ _ x.2 h) h⟩⟩ theorem typein_surj (r : α → α → Prop) [is_well_order α r] {o} (h : o < type r) : ∃ a, typein r a = o := induction_on o (λ β s _ ⟨f⟩, by exactI ⟨f.top, typein_top _⟩) h lemma typein_injective (r : α → α → Prop) [is_well_order α r] : injective (typein r) := injective_of_increasing r (<) (typein r) (λ x y, (typein_lt_typein r).2) @[simp] theorem typein_inj (r : α → α → Prop) [is_well_order α r] {a b} : typein r a = typein r b ↔ a = b := (typein_injective r).eq_iff /-! ### Enumerating elements in a well-order with ordinals. -/ /-- `enum r o h` is the `o`-th element of `α` ordered by `r`. That is, `enum` maps an initial segment of the ordinals, those less than the order type of `r`, to the elements of `α`. -/ def enum (r : α → α → Prop) [is_well_order α r] (o) : o < type r → α := quot.rec_on o (λ ⟨β, s, _⟩ h, (classical.choice h).top) $ λ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨h⟩, begin resetI, refine funext (λ (H₂ : type t < type r), _), have H₁ : type s < type r, {rwa type_eq.2 ⟨h⟩}, have : ∀ {o e} (H : o < type r), @@eq.rec (λ (o : ordinal), o < type r → α) (λ (h : type s < type r), (classical.choice h).top) e H = (classical.choice H₁).top, {intros, subst e}, exact (this H₂).trans (principal_seg.top_eq h (classical.choice H₁) (classical.choice H₂)) end theorem enum_type {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] (f : s ≺i r) {h : type s < type r} : enum r (type s) h = f.top := principal_seg.top_eq (rel_iso.refl _) _ _ @[simp] theorem enum_typein (r : α → α → Prop) [is_well_order α r] (a : α) : enum r (typein r a) (typein_lt_type r a) = a := enum_type (principal_seg.of_element r a) @[simp] theorem typein_enum (r : α → α → Prop) [is_well_order α r] {o} (h : o < type r) : typein r (enum r o h) = o := let ⟨a, e⟩ := typein_surj r h in by clear _let_match; subst e; rw enum_typein theorem enum_lt_enum {r : α → α → Prop} [is_well_order α r] {o₁ o₂ : ordinal} (h₁ : o₁ < type r) (h₂ : o₂ < type r) : r (enum r o₁ h₁) (enum r o₂ h₂) ↔ o₁ < o₂ := by rw [← typein_lt_typein r, typein_enum, typein_enum] lemma rel_iso_enum' {α β : Type u} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] (f : r ≃r s) (o : ordinal) : ∀(hr : o < type r) (hs : o < type s), f (enum r o hr) = enum s o hs := begin refine induction_on o _, rintros γ t wo ⟨g⟩ ⟨h⟩, resetI, rw [enum_type g, enum_type (principal_seg.lt_equiv g f)], refl end lemma rel_iso_enum {α β : Type u} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] (f : r ≃r s) (o : ordinal) (hr : o < type r) : f (enum r o hr) = enum s o (by {convert hr using 1, apply quotient.sound, exact ⟨f.symm⟩ }) := rel_iso_enum' _ _ _ _ theorem lt_wf : @well_founded ordinal (<) := ⟨λ a, induction_on a $ λ α r wo, by exactI suffices ∀ a, acc (<) (typein r a), from ⟨_, λ o h, let ⟨a, e⟩ := typein_surj r h in e ▸ this a⟩, λ a, acc.rec_on (wo.wf.apply a) $ λ x H IH, ⟨_, λ o h, begin rcases typein_surj r (lt_trans h (typein_lt_type r _)) with ⟨b, rfl⟩, exact IH _ ((typein_lt_typein r).1 h) end⟩⟩ instance : has_well_founded ordinal := ⟨(<), lt_wf⟩ /-- Reformulation of well founded induction on ordinals as a lemma that works with the `induction` tactic, as in `induction i using ordinal.induction with i IH`. -/ lemma induction {p : ordinal.{u} → Prop} (i : ordinal.{u}) (h : ∀ j, (∀ k, k < j → p k) → p j) : p i := lt_wf.induction i h /-- Principal segment version of the `typein` function, embedding a well order into ordinals as a principal segment. -/ def typein.principal_seg {α : Type u} (r : α → α → Prop) [is_well_order α r] : @principal_seg α ordinal.{u} r (<) := ⟨rel_embedding.of_monotone (typein r) (λ a b, (typein_lt_typein r).2), type r, λ b, ⟨λ h, ⟨enum r _ h, typein_enum r h⟩, λ ⟨a, e⟩, e ▸ typein_lt_type _ _⟩⟩ @[simp] theorem typein.principal_seg_coe (r : α → α → Prop) [is_well_order α r] : (typein.principal_seg r : α → ordinal) = typein r := rfl /-! ### Cardinality of ordinals -/ /-- The cardinal of an ordinal is the cardinality of any type on which a relation with that order type is defined. -/ def card : ordinal → cardinal := quotient.map Well_order.α $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨e⟩, ⟨e.to_equiv⟩ @[simp] theorem card_type (r : α → α → Prop) [is_well_order α r] : card (type r) = #α := rfl @[simp] lemma card_typein {r : α → α → Prop} [wo : is_well_order α r] (x : α) : #{y // r y x} = (typein r x).card := rfl theorem card_le_card {o₁ o₂ : ordinal} : o₁ ≤ o₂ → card o₁ ≤ card o₂ := induction_on o₁ $ λ α r _, induction_on o₂ $ λ β s _ ⟨⟨⟨f, _⟩, _⟩⟩, ⟨f⟩ @[simp] theorem card_zero : card 0 = 0 := rfl @[simp] theorem card_eq_zero {o} : card o = 0 ↔ o = 0 := ⟨induction_on o $ λ α r _ h, begin haveI := cardinal.mk_eq_zero_iff.1 h, apply type_eq_zero_of_empty end, λ e, by simp only [e, card_zero]⟩ @[simp] theorem card_one : card 1 = 1 := rfl /-! ### Lifting ordinals to a higher universe -/ /-- The universe lift operation for ordinals, which embeds `ordinal.{u}` as a proper initial segment of `ordinal.{v}` for `v > u`. For the initial segment version, see `lift.initial_seg`. -/ def lift (o : ordinal.{v}) : ordinal.{max v u} := quotient.lift_on o (λ w, type $ ulift.down ⁻¹'o w.r) $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨f⟩, quot.sound ⟨(rel_iso.preimage equiv.ulift r).trans $ f.trans (rel_iso.preimage equiv.ulift s).symm⟩ @[simp] theorem type_ulift (r : α → α → Prop) [is_well_order α r] : type (ulift.down ⁻¹'o r) = lift.{v} (type r) := rfl theorem _root_.rel_iso.ordinal_lift_type_eq {α : Type u} {β : Type v} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] (f : r ≃r s) : lift.{v} (type r) = lift.{u} (type s) := ((rel_iso.preimage equiv.ulift r).trans $ f.trans (rel_iso.preimage equiv.ulift s).symm).ordinal_type_eq @[simp] theorem type_lift_preimage {α : Type u} {β : Type v} (r : α → α → Prop) [is_well_order α r] (f : β ≃ α) : lift.{u} (type (f ⁻¹'o r)) = lift.{v} (type r) := (rel_iso.preimage f r).ordinal_lift_type_eq /-- `lift.{(max u v) u}` equals `lift.{v u}`. Using `set_option pp.universes true` will make it much easier to understand what's happening when using this lemma. -/ @[simp] theorem lift_umax : lift.{(max u v) u} = lift.{v u} := funext $ λ a, induction_on a $ λ α r _, quotient.sound ⟨(rel_iso.preimage equiv.ulift r).trans (rel_iso.preimage equiv.ulift r).symm⟩ /-- `lift.{(max v u) u}` equals `lift.{v u}`. Using `set_option pp.universes true` will make it much easier to understand what's happening when using this lemma. -/ @[simp] theorem lift_umax' : lift.{(max v u) u} = lift.{v u} := lift_umax /-- An ordinal lifted to a lower or equal universe equals itself. -/ @[simp] theorem lift_id' (a : ordinal) : lift a = a := induction_on a $ λ α r _, quotient.sound ⟨rel_iso.preimage equiv.ulift r⟩ /-- An ordinal lifted to the same universe equals itself. -/ @[simp] theorem lift_id : ∀ a, lift.{u u} a = a := lift_id'.{u u} /-- An ordinal lifted to the zero universe equals itself. -/ @[simp] theorem lift_uzero (a : ordinal.{u}) : lift.{0} a = a := lift_id'.{0 u} a @[simp] theorem lift_lift (a : ordinal) : lift.{w} (lift.{v} a) = lift.{max v w} a := induction_on a $ λ α r _, quotient.sound ⟨(rel_iso.preimage equiv.ulift _).trans $ (rel_iso.preimage equiv.ulift _).trans (rel_iso.preimage equiv.ulift _).symm⟩ theorem lift_type_le {α : Type u} {β : Type v} {r s} [is_well_order α r] [is_well_order β s] : lift.{max v w} (type r) ≤ lift.{max u w} (type s) ↔ nonempty (r ≼i s) := ⟨λ ⟨f⟩, ⟨(initial_seg.of_iso (rel_iso.preimage equiv.ulift r).symm).trans $ f.trans (initial_seg.of_iso (rel_iso.preimage equiv.ulift s))⟩, λ ⟨f⟩, ⟨(initial_seg.of_iso (rel_iso.preimage equiv.ulift r)).trans $ f.trans (initial_seg.of_iso (rel_iso.preimage equiv.ulift s).symm)⟩⟩ theorem lift_type_eq {α : Type u} {β : Type v} {r s} [is_well_order α r] [is_well_order β s] : lift.{max v w} (type r) = lift.{max u w} (type s) ↔ nonempty (r ≃r s) := quotient.eq.trans ⟨λ ⟨f⟩, ⟨(rel_iso.preimage equiv.ulift r).symm.trans $ f.trans (rel_iso.preimage equiv.ulift s)⟩, λ ⟨f⟩, ⟨(rel_iso.preimage equiv.ulift r).trans $ f.trans (rel_iso.preimage equiv.ulift s).symm⟩⟩ theorem lift_type_lt {α : Type u} {β : Type v} {r s} [is_well_order α r] [is_well_order β s] : lift.{max v w} (type r) < lift.{max u w} (type s) ↔ nonempty (r ≺i s) := by haveI := @rel_embedding.is_well_order _ _ (@equiv.ulift.{max v w} α ⁻¹'o r) r (rel_iso.preimage equiv.ulift.{max v w} r) _; haveI := @rel_embedding.is_well_order _ _ (@equiv.ulift.{max u w} β ⁻¹'o s) s (rel_iso.preimage equiv.ulift.{max u w} s) _; exact ⟨λ ⟨f⟩, ⟨(f.equiv_lt (rel_iso.preimage equiv.ulift r).symm).lt_le (initial_seg.of_iso (rel_iso.preimage equiv.ulift s))⟩, λ ⟨f⟩, ⟨(f.equiv_lt (rel_iso.preimage equiv.ulift r)).lt_le (initial_seg.of_iso (rel_iso.preimage equiv.ulift s).symm)⟩⟩ @[simp] theorem lift_le {a b : ordinal} : lift.{u v} a ≤ lift b ↔ a ≤ b := induction_on a $ λ α r _, induction_on b $ λ β s _, by { rw ← lift_umax, exactI lift_type_le } @[simp] theorem lift_inj {a b : ordinal} : lift a = lift b ↔ a = b := by simp only [le_antisymm_iff, lift_le] @[simp] theorem lift_lt {a b : ordinal} : lift a < lift b ↔ a < b := by simp only [lt_iff_le_not_le, lift_le] @[simp] theorem lift_zero : lift 0 = 0 := type_eq_zero_of_empty _ @[simp] theorem lift_one : lift 1 = 1 := type_eq_one_of_unique _ @[simp] theorem lift_card (a) : (card a).lift = card (lift a) := induction_on a $ λ α r _, rfl theorem lift_down' {a : cardinal.{u}} {b : ordinal.{max u v}} (h : card b ≤ a.lift) : ∃ a', lift a' = b := let ⟨c, e⟩ := cardinal.lift_down h in cardinal.induction_on c (λ α, induction_on b $ λ β s _ e', begin resetI, rw [card_type, ← cardinal.lift_id'.{(max u v) u} (#β), ← cardinal.lift_umax.{u v}, lift_mk_eq.{u (max u v) (max u v)}] at e', cases e' with f, have g := rel_iso.preimage f s, haveI := (g : ⇑f ⁻¹'o s ↪r s).is_well_order, have := lift_type_eq.{u (max u v) (max u v)}.2 ⟨g⟩, rw [lift_id, lift_umax.{u v}] at this, exact ⟨_, this⟩ end) e theorem lift_down {a : ordinal.{u}} {b : ordinal.{max u v}} (h : b ≤ lift a) : ∃ a', lift a' = b := @lift_down' (card a) _ (by rw lift_card; exact card_le_card h) theorem le_lift_iff {a : ordinal.{u}} {b : ordinal.{max u v}} : b ≤ lift a ↔ ∃ a', lift a' = b ∧ a' ≤ a := ⟨λ h, let ⟨a', e⟩ := lift_down h in ⟨a', e, lift_le.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_le.2 h⟩ theorem lt_lift_iff {a : ordinal.{u}} {b : ordinal.{max u v}} : b < lift a ↔ ∃ a', lift a' = b ∧ a' < a := ⟨λ h, let ⟨a', e⟩ := lift_down (le_of_lt h) in ⟨a', e, lift_lt.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_lt.2 h⟩ /-- Initial segment version of the lift operation on ordinals, embedding `ordinal.{u}` in `ordinal.{v}` as an initial segment when `u ≤ v`. -/ def lift.initial_seg : @initial_seg ordinal.{u} ordinal.{max u v} (<) (<) := ⟨⟨⟨lift.{v}, λ a b, lift_inj.1⟩, λ a b, lift_lt⟩, λ a b h, lift_down (le_of_lt h)⟩ @[simp] theorem lift.initial_seg_coe : (lift.initial_seg : ordinal → ordinal) = lift := rfl /-! ### The first infinite ordinal `omega` -/ /-- `ω` is the first infinite ordinal, defined as the order type of `ℕ`. -/ def omega : ordinal.{u} := lift $ @type ℕ (<) _ localized "notation (name := ordinal.omega) `ω` := ordinal.omega" in ordinal /-- Note that the presence of this lemma makes `simp [omega]` form a loop. -/ @[simp] theorem type_nat_lt : @type ℕ (<) _ = ω := (lift_id _).symm @[simp] theorem card_omega : card ω = ℵ₀ := rfl @[simp] theorem lift_omega : lift ω = ω := lift_lift _ /-! ### Definition and first properties of addition on ordinals In this paragraph, we introduce the addition on ordinals, and prove just enough properties to deduce that the order on ordinals is total (and therefore well-founded). Further properties of the addition, together with properties of the other operations, are proved in `ordinal_arithmetic.lean`. -/ /-- `o₁ + o₂` is the order on the disjoint union of `o₁` and `o₂` obtained by declaring that every element of `o₁` is smaller than every element of `o₂`. -/ instance : has_add ordinal.{u} := ⟨λ o₁ o₂, quotient.lift_on₂ o₁ o₂ (λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, by exactI type (sum.lex r s)) $ λ ⟨α₁, r₁, o₁⟩ ⟨α₂, r₂, o₂⟩ ⟨β₁, s₁, p₁⟩ ⟨β₂, s₂, p₂⟩ ⟨f⟩ ⟨g⟩, quot.sound ⟨rel_iso.sum_lex_congr f g⟩⟩ instance : add_monoid_with_one ordinal.{u} := { add := (+), zero := 0, one := 1, zero_add := λ o, induction_on o $ λ α r _, eq.symm $ quotient.sound ⟨⟨(empty_sum pempty α).symm, λ a b, sum.lex_inr_inr⟩⟩, add_zero := λ o, induction_on o $ λ α r _, eq.symm $ quotient.sound ⟨⟨(sum_empty α pempty).symm, λ a b, sum.lex_inl_inl⟩⟩, add_assoc := λ o₁ o₂ o₃, quotient.induction_on₃ o₁ o₂ o₃ $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩, quot.sound ⟨⟨sum_assoc _ _ _, λ a b, begin rcases a with ⟨a|a⟩|a; rcases b with ⟨b|b⟩|b; simp only [sum_assoc_apply_inl_inl, sum_assoc_apply_inl_inr, sum_assoc_apply_inr, sum.lex_inl_inl, sum.lex_inr_inr, sum.lex.sep, sum.lex_inr_inl] end⟩⟩ } @[simp] theorem card_add (o₁ o₂ : ordinal) : card (o₁ + o₂) = card o₁ + card o₂ := induction_on o₁ $ λ α r _, induction_on o₂ $ λ β s _, rfl @[simp] theorem type_sum_lex {α β : Type u} (r : α → α → Prop) (s : β → β → Prop) [is_well_order α r] [is_well_order β s] : type (sum.lex r s) = type r + type s := rfl @[simp] theorem card_nat (n : ℕ) : card.{u} n = n := by induction n; [refl, simp only [card_add, card_one, nat.cast_succ, *]] instance add_covariant_class_le : covariant_class ordinal.{u} ordinal.{u} (+) (≤) := ⟨λ c a b h, begin revert h c, exact ( induction_on a $ λ α₁ r₁ _, induction_on b $ λ α₂ r₂ _ ⟨⟨⟨f, fo⟩, fi⟩⟩ c, induction_on c $ λ β s _, ⟨⟨⟨(embedding.refl _).sum_map f, λ a b, match a, b with | sum.inl a, sum.inl b := sum.lex_inl_inl.trans sum.lex_inl_inl.symm | sum.inl a, sum.inr b := by apply iff_of_true; apply sum.lex.sep | sum.inr a, sum.inl b := by apply iff_of_false; exact sum.lex_inr_inl | sum.inr a, sum.inr b := sum.lex_inr_inr.trans $ fo.trans sum.lex_inr_inr.symm end⟩, λ a b H, match a, b, H with | _, sum.inl b, _ := ⟨sum.inl b, rfl⟩ | sum.inl a, sum.inr b, H := (sum.lex_inr_inl H).elim | sum.inr a, sum.inr b, H := let ⟨w, h⟩ := fi _ _ (sum.lex_inr_inr.1 H) in ⟨sum.inr w, congr_arg sum.inr h⟩ end⟩⟩) end⟩ instance add_swap_covariant_class_le : covariant_class ordinal.{u} ordinal.{u} (swap (+)) (≤) := ⟨λ c a b h, begin revert h c, exact ( induction_on a $ λ α₁ r₁ hr₁, induction_on b $ λ α₂ r₂ hr₂ ⟨⟨⟨f, fo⟩, fi⟩⟩ c, induction_on c $ λ β s hs, by exactI @rel_embedding.ordinal_type_le _ _ (sum.lex r₁ s) (sum.lex r₂ s) _ _ ⟨f.sum_map (embedding.refl _), λ a b, begin split; intro H, { cases a with a a; cases b with b b; cases H; constructor; [rwa ← fo, assumption] }, { cases H; constructor; [rwa fo, assumption] } end⟩) end⟩ theorem le_add_right (a b : ordinal) : a ≤ a + b := by simpa only [add_zero] using add_le_add_left (ordinal.zero_le b) a theorem le_add_left (a b : ordinal) : a ≤ b + a := by simpa only [zero_add] using add_le_add_right (ordinal.zero_le b) a instance : linear_order ordinal := { le_total := λ a b, match lt_or_eq_of_le (le_add_left b a), lt_or_eq_of_le (le_add_right a b) with | or.inr h, _ := by rw h; exact or.inl (le_add_right _ _) | _, or.inr h := by rw h; exact or.inr (le_add_left _ _) | or.inl h₁, or.inl h₂ := induction_on a (λ α₁ r₁ _, induction_on b $ λ α₂ r₂ _ ⟨f⟩ ⟨g⟩, begin resetI, rw [← typein_top f, ← typein_top g, le_iff_lt_or_eq, le_iff_lt_or_eq, typein_lt_typein, typein_lt_typein], rcases trichotomous_of (sum.lex r₁ r₂) g.top f.top with h|h|h; [exact or.inl (or.inl h), {left, right, rw h}, exact or.inr (or.inl h)] end) h₁ h₂ end, decidable_le := classical.dec_rel _, ..ordinal.partial_order } instance : well_founded_lt ordinal := ⟨lt_wf⟩ instance : is_well_order ordinal (<) := { } instance : conditionally_complete_linear_order_bot ordinal := is_well_order.conditionally_complete_linear_order_bot _ @[simp] lemma max_zero_left : ∀ a : ordinal, max 0 a = a := max_bot_left @[simp] lemma max_zero_right : ∀ a : ordinal, max a 0 = a := max_bot_right @[simp] lemma max_eq_zero {a b : ordinal} : max a b = 0 ↔ a = 0 ∧ b = 0 := max_eq_bot @[simp] theorem Inf_empty : Inf (∅ : set ordinal) = 0 := dif_neg not_nonempty_empty /- ### Successor order properties -/ private theorem succ_le_iff' {a b : ordinal} : a + 1 ≤ b ↔ a < b := ⟨lt_of_lt_of_le (induction_on a $ λ α r _, ⟨⟨⟨⟨λ x, sum.inl x, λ _ _, sum.inl.inj⟩, λ _ _, sum.lex_inl_inl⟩, sum.inr punit.star, λ b, sum.rec_on b (λ x, ⟨λ _, ⟨x, rfl⟩, λ _, sum.lex.sep _ _⟩) (λ x, sum.lex_inr_inr.trans ⟨false.elim, λ ⟨x, H⟩, sum.inl_ne_inr H⟩)⟩⟩), induction_on a $ λ α r hr, induction_on b $ λ β s hs ⟨⟨f, t, hf⟩⟩, begin haveI := hs, refine ⟨⟨@rel_embedding.of_monotone (α ⊕ punit) β _ _ _ _ (sum.rec _ _) (λ a b, _), λ a b, _⟩⟩, { exact f }, { exact λ _, t }, { rcases a with a|_; rcases b with b|_, { simpa only [sum.lex_inl_inl] using f.map_rel_iff.2 }, { intro _, rw hf, exact ⟨_, rfl⟩ }, { exact false.elim ∘ sum.lex_inr_inl }, { exact false.elim ∘ sum.lex_inr_inr.1 } }, { rcases a with a|_, { intro h, have := @principal_seg.init _ _ _ _ _ ⟨f, t, hf⟩ _ _ h, cases this with w h, exact ⟨sum.inl w, h⟩ }, { intro h, cases (hf b).1 h with w h, exact ⟨sum.inl w, h⟩ } } end⟩ instance : no_max_order ordinal := ⟨λ a, ⟨_, succ_le_iff'.1 le_rfl⟩⟩ instance : succ_order ordinal.{u} := succ_order.of_succ_le_iff (λ o, o + 1) (λ a b, succ_le_iff') @[simp] theorem add_one_eq_succ (o : ordinal) : o + 1 = succ o := rfl @[simp] theorem succ_zero : succ (0 : ordinal) = 1 := zero_add 1 @[simp] theorem succ_one : succ (1 : ordinal) = 2 := rfl theorem add_succ (o₁ o₂ : ordinal) : o₁ + succ o₂ = succ (o₁ + o₂) := (add_assoc _ _ _).symm theorem one_le_iff_pos {o : ordinal} : 1 ≤ o ↔ 0 < o := by rw [← succ_zero, succ_le_iff] theorem one_le_iff_ne_zero {o : ordinal} : 1 ≤ o ↔ o ≠ 0 := by rw [one_le_iff_pos, ordinal.pos_iff_ne_zero] theorem succ_pos (o : ordinal) : 0 < succ o := bot_lt_succ o theorem succ_ne_zero (o : ordinal) : succ o ≠ 0 := ne_of_gt $ succ_pos o theorem lt_one_iff_zero {a : ordinal} : a < 1 ↔ a = 0 := by simpa using @lt_succ_bot_iff _ _ _ a _ _ theorem le_one_iff {a : ordinal} : a ≤ 1 ↔ a = 0 ∨ a = 1 := by simpa using @le_succ_bot_iff _ _ _ a _ @[simp] theorem card_succ (o : ordinal) : card (succ o) = card o + 1 := by simp only [←add_one_eq_succ, card_add, card_one] theorem nat_cast_succ (n : ℕ) : ↑n.succ = succ (n : ordinal) := rfl instance unique_Iio_one : unique (Iio (1 : ordinal)) := { default := ⟨0, zero_lt_one⟩, uniq := λ a, subtype.ext $ lt_one_iff_zero.1 a.prop } instance unique_out_one : unique (1 : ordinal).out.α := { default := enum (<) 0 (by simp), uniq := λ a, begin rw ←enum_typein (<) a, unfold default, congr, rw ←lt_one_iff_zero, apply typein_lt_self end } theorem one_out_eq (x : (1 : ordinal).out.α) : x = enum (<) 0 (by simp) := unique.eq_default x /-! ### Extra properties of typein and enum -/ @[simp] theorem typein_one_out (x : (1 : ordinal).out.α) : typein (<) x = 0 := by rw [one_out_eq x, typein_enum] @[simp] lemma typein_le_typein (r : α → α → Prop) [is_well_order α r] {x x' : α} : typein r x ≤ typein r x' ↔ ¬r x' x := by rw [←not_lt, typein_lt_typein] @[simp] lemma typein_le_typein' (o : ordinal) {x x' : o.out.α} : typein (<) x ≤ typein (<) x' ↔ x ≤ x' := by { rw typein_le_typein, exact not_lt } @[simp] lemma enum_le_enum (r : α → α → Prop) [is_well_order α r] {o o' : ordinal} (ho : o < type r) (ho' : o' < type r) : ¬r (enum r o' ho') (enum r o ho) ↔ o ≤ o' := by rw [←@not_lt _ _ o' o, enum_lt_enum ho'] @[simp] lemma enum_le_enum' (a : ordinal) {o o' : ordinal} (ho : o < type (<)) (ho' : o' < type (<)) : enum (<) o ho ≤ @enum a.out.α (<) _ o' ho' ↔ o ≤ o' := by rw [←enum_le_enum (<), ←not_lt] theorem enum_zero_le {r : α → α → Prop} [is_well_order α r] (h0 : 0 < type r) (a : α) : ¬ r a (enum r 0 h0) := by { rw [←enum_typein r a, enum_le_enum r], apply ordinal.zero_le } theorem enum_zero_le' {o : ordinal} (h0 : 0 < o) (a : o.out.α) : @enum o.out.α (<) _ 0 (by rwa type_lt) ≤ a := by { rw ←not_lt, apply enum_zero_le } theorem le_enum_succ {o : ordinal} (a : (succ o).out.α) : a ≤ @enum (succ o).out.α (<) _ o (by { rw type_lt, exact lt_succ o }) := by { rw [←enum_typein (<) a, enum_le_enum', ←lt_succ_iff], apply typein_lt_self } @[simp] theorem enum_inj {r : α → α → Prop} [is_well_order α r] {o₁ o₂ : ordinal} (h₁ : o₁ < type r) (h₂ : o₂ < type r) : enum r o₁ h₁ = enum r o₂ h₂ ↔ o₁ = o₂ := ⟨λ h, begin by_contra hne, cases lt_or_gt_of_ne hne with hlt hlt; apply (is_well_order.is_irrefl r).1, { rwa [←@enum_lt_enum α r _ o₁ o₂ h₁ h₂, h] at hlt }, { change _ < _ at hlt, rwa [←@enum_lt_enum α r _ o₂ o₁ h₂ h₁, h] at hlt } end, λ h, by simp_rw h⟩ /-- A well order `r` is order isomorphic to the set of ordinals smaller than `type r`. -/ @[simps] def enum_iso (r : α → α → Prop) [is_well_order α r] : subrel (<) (< type r) ≃r r := { to_fun := λ x, enum r x.1 x.2, inv_fun := λ x, ⟨typein r x, typein_lt_type r x⟩, left_inv := λ ⟨o, h⟩, subtype.ext_val (typein_enum _ _), right_inv := λ h, enum_typein _ _, map_rel_iff' := by { rintros ⟨a, _⟩ ⟨b, _⟩, apply enum_lt_enum } } /-- The order isomorphism between ordinals less than `o` and `o.out.α`. -/ @[simps] noncomputable def enum_iso_out (o : ordinal) : set.Iio o ≃o o.out.α := { to_fun := λ x, enum (<) x.1 $ by { rw type_lt, exact x.2 }, inv_fun := λ x, ⟨typein (<) x, typein_lt_self x⟩, left_inv := λ ⟨o', h⟩, subtype.ext_val (typein_enum _ _), right_inv := λ h, enum_typein _ _, map_rel_iff' := by { rintros ⟨a, _⟩ ⟨b, _⟩, apply enum_le_enum' } } /-- `o.out.α` is an `order_bot` whenever `0 < o`. -/ def out_order_bot_of_pos {o : ordinal} (ho : 0 < o) : order_bot o.out.α := ⟨_, enum_zero_le' ho⟩ theorem enum_zero_eq_bot {o : ordinal} (ho : 0 < o) : enum (<) 0 (by rwa type_lt) = by { haveI H := out_order_bot_of_pos ho, exact ⊥ } := rfl /-! ### Universal ordinal -/ /-- `univ.{u v}` is the order type of the ordinals of `Type u` as a member of `ordinal.{v}` (when `u < v`). It is an inaccessible cardinal. -/ @[nolint check_univs] -- intended to be used with explicit universe parameters def univ : ordinal.{max (u + 1) v} := lift.{v (u+1)} (@type ordinal (<) _) theorem univ_id : univ.{u (u+1)} = @type ordinal (<) _ := lift_id _ @[simp] theorem lift_univ : lift.{w} univ.{u v} = univ.{u (max v w)} := lift_lift _ theorem univ_umax : univ.{u (max (u+1) v)} = univ.{u v} := congr_fun lift_umax _ /-- Principal segment version of the lift operation on ordinals, embedding `ordinal.{u}` in `ordinal.{v}` as a principal segment when `u < v`. -/ def lift.principal_seg : @principal_seg ordinal.{u} ordinal.{max (u+1) v} (<) (<) := ⟨↑lift.initial_seg.{u (max (u+1) v)}, univ.{u v}, begin refine λ b, induction_on b _, introsI β s _, rw [univ, ← lift_umax], split; intro h, { rw ← lift_id (type s) at h ⊢, cases lift_type_lt.1 h with f, cases f with f a hf, existsi a, revert hf, apply induction_on a, introsI α r _ hf, refine lift_type_eq.{u (max (u+1) v) (max (u+1) v)}.2 ⟨(rel_iso.of_surjective (rel_embedding.of_monotone _ _) _).symm⟩, { exact λ b, enum r (f b) ((hf _).2 ⟨_, rfl⟩) }, { refine λ a b h, (typein_lt_typein r).1 _, rw [typein_enum, typein_enum], exact f.map_rel_iff.2 h }, { intro a', cases (hf _).1 (typein_lt_type _ a') with b e, existsi b, simp, simp [e] } }, { cases h with a e, rw [← e], apply induction_on a, introsI α r _, exact lift_type_lt.{u (u+1) (max (u+1) v)}.2 ⟨typein.principal_seg r⟩ } end⟩ @[simp] theorem lift.principal_seg_coe : (lift.principal_seg.{u v} : ordinal → ordinal) = lift.{max (u+1) v} := rfl @[simp] theorem lift.principal_seg_top : lift.principal_seg.top = univ := rfl theorem lift.principal_seg_top' : lift.principal_seg.{u (u+1)}.top = @type ordinal (<) _ := by simp only [lift.principal_seg_top, univ_id] end ordinal /-! ### Representing a cardinal with an ordinal -/ namespace cardinal open ordinal @[simp] theorem mk_ordinal_out (o : ordinal) : #(o.out.α) = o.card := (ordinal.card_type _).symm.trans $ by rw ordinal.type_lt /-- The ordinal corresponding to a cardinal `c` is the least ordinal whose cardinal is `c`. For the order-embedding version, see `ord.order_embedding`. -/ def ord (c : cardinal) : ordinal := let F := λ α : Type u, ⨅ r : {r // is_well_order α r}, @type α r.1 r.2 in quot.lift_on c F begin suffices : ∀ {α β}, α ≈ β → F α ≤ F β, from λ α β h, (this h).antisymm (this (setoid.symm h)), rintros α β ⟨f⟩, refine le_cinfi_iff'.2 (λ i, _), haveI := @rel_embedding.is_well_order _ _ (f ⁻¹'o i.1) _ ↑(rel_iso.preimage f i.1) i.2, exact (cinfi_le' _ (subtype.mk (⇑f ⁻¹'o i.val) (@rel_embedding.is_well_order _ _ _ _ ↑(rel_iso.preimage f i.1) i.2))).trans_eq (quot.sound ⟨rel_iso.preimage f i.1⟩) end lemma ord_eq_Inf (α : Type u) : ord (#α) = ⨅ r : {r // is_well_order α r}, @type α r.1 r.2 := rfl theorem ord_eq (α) : ∃ (r : α → α → Prop) [wo : is_well_order α r], ord (#α) = @type α r wo := let ⟨r, wo⟩ := infi_mem (λ r : {r // is_well_order α r}, @type α r.1 r.2) in ⟨r.1, r.2, wo.symm⟩ theorem ord_le_type (r : α → α → Prop) [h : is_well_order α r] : ord (#α) ≤ type r := cinfi_le' _ (subtype.mk r h) theorem ord_le {c o} : ord c ≤ o ↔ c ≤ o.card := induction_on c $ λ α, ordinal.induction_on o $ λ β s _, let ⟨r, _, e⟩ := ord_eq α in begin resetI, simp only [card_type], split; intro h, { rw e at h, exact let ⟨f⟩ := h in ⟨f.to_embedding⟩ }, { cases h with f, have g := rel_embedding.preimage f s, haveI := rel_embedding.is_well_order g, exact le_trans (ord_le_type _) g.ordinal_type_le } end theorem gc_ord_card : galois_connection ord card := λ _ _, ord_le theorem lt_ord {c o} : o < ord c ↔ o.card < c := gc_ord_card.lt_iff_lt @[simp] theorem card_ord (c) : (ord c).card = c := quotient.induction_on c $ λ α, let ⟨r, _, e⟩ := ord_eq α in by simp only [mk_def, e, card_type] /-- Galois coinsertion between `cardinal.ord` and `ordinal.card`. -/ def gci_ord_card : galois_coinsertion ord card := gc_ord_card.to_galois_coinsertion $ λ c, c.card_ord.le theorem ord_card_le (o : ordinal) : o.card.ord ≤ o := gc_ord_card.l_u_le _ lemma lt_ord_succ_card (o : ordinal) : o < (succ o.card).ord := lt_ord.2 $ lt_succ _ @[mono] theorem ord_strict_mono : strict_mono ord := gci_ord_card.strict_mono_l @[mono] theorem ord_mono : monotone ord := gc_ord_card.monotone_l @[simp] theorem ord_le_ord {c₁ c₂} : ord c₁ ≤ ord c₂ ↔ c₁ ≤ c₂ := gci_ord_card.l_le_l_iff @[simp] theorem ord_lt_ord {c₁ c₂} : ord c₁ < ord c₂ ↔ c₁ < c₂ := ord_strict_mono.lt_iff_lt @[simp] theorem ord_zero : ord 0 = 0 := gc_ord_card.l_bot @[simp] theorem ord_nat (n : ℕ) : ord n = n := (ord_le.2 (card_nat n).ge).antisymm begin induction n with n IH, { apply ordinal.zero_le }, { exact succ_le_of_lt (IH.trans_lt $ ord_lt_ord.2 $ nat_cast_lt.2 (nat.lt_succ_self n)) } end @[simp] theorem ord_one : ord 1 = 1 := by simpa using ord_nat 1 @[simp] theorem lift_ord (c) : (ord c).lift = ord (lift c) := begin refine le_antisymm (le_of_forall_lt (λ a ha, _)) _, { rcases ordinal.lt_lift_iff.1 ha with ⟨a, rfl, h⟩, rwa [lt_ord, ← lift_card, lift_lt, ← lt_ord, ← ordinal.lift_lt] }, { rw [ord_le, ← lift_card, card_ord] } end lemma mk_ord_out (c : cardinal) : #c.ord.out.α = c := by simp lemma card_typein_lt (r : α → α → Prop) [is_well_order α r] (x : α) (h : ord (#α) = type r) : card (typein r x) < #α := by { rw [←lt_ord, h], apply typein_lt_type } lemma card_typein_out_lt (c : cardinal) (x : c.ord.out.α) : card (typein (<) x) < c := by { rw ←lt_ord, apply typein_lt_self } lemma ord_injective : injective ord := by { intros c c' h, rw [←card_ord c, ←card_ord c', h] } /-- The ordinal corresponding to a cardinal `c` is the least ordinal whose cardinal is `c`. This is the order-embedding version. For the regular function, see `ord`. -/ def ord.order_embedding : cardinal ↪o ordinal := rel_embedding.order_embedding_of_lt_embedding (rel_embedding.of_monotone cardinal.ord $ λ a b, cardinal.ord_lt_ord.2) @[simp] theorem ord.order_embedding_coe : (ord.order_embedding : cardinal → ordinal) = ord := rfl /-- The cardinal `univ` is the cardinality of ordinal `univ`, or equivalently the cardinal of `ordinal.{u}`, or `cardinal.{u}`, as an element of `cardinal.{v}` (when `u < v`). -/ @[nolint check_univs] -- intended to be used with explicit universe parameters def univ := lift.{v (u+1)} (#ordinal) theorem univ_id : univ.{u (u+1)} = #ordinal := lift_id _ @[simp] theorem lift_univ : lift.{w} univ.{u v} = univ.{u (max v w)} := lift_lift _ theorem univ_umax : univ.{u (max (u+1) v)} = univ.{u v} := congr_fun lift_umax _ theorem lift_lt_univ (c : cardinal) : lift.{(u+1) u} c < univ.{u (u+1)} := by simpa only [lift.principal_seg_coe, lift_ord, lift_succ, ord_le, succ_le_iff] using le_of_lt (lift.principal_seg.{u (u+1)}.lt_top (succ c).ord) theorem lift_lt_univ' (c : cardinal) : lift.{(max (u+1) v) u} c < univ.{u v} := by simpa only [lift_lift, lift_univ, univ_umax] using lift_lt.{_ (max (u+1) v)}.2 (lift_lt_univ c) @[simp] theorem ord_univ : ord univ.{u v} = ordinal.univ.{u v} := le_antisymm (ord_card_le _) $ le_of_forall_lt $ λ o h, lt_ord.2 begin rcases lift.principal_seg.{u v}.down.1 (by simpa only [lift.principal_seg_coe] using h) with ⟨o', rfl⟩, simp only [lift.principal_seg_coe], rw [← lift_card], apply lift_lt_univ' end theorem lt_univ {c} : c < univ.{u (u+1)} ↔ ∃ c', c = lift.{(u+1) u} c' := ⟨λ h, begin have := ord_lt_ord.2 h, rw ord_univ at this, cases lift.principal_seg.{u (u+1)}.down.1 (by simpa only [lift.principal_seg_top]) with o e, have := card_ord c, rw [← e, lift.principal_seg_coe, ← lift_card] at this, exact ⟨_, this.symm⟩ end, λ ⟨c', e⟩, e.symm ▸ lift_lt_univ _⟩ theorem lt_univ' {c} : c < univ.{u v} ↔ ∃ c', c = lift.{(max (u+1) v) u} c' := ⟨λ h, let ⟨a, e, h'⟩ := lt_lift_iff.1 h in begin rw [← univ_id] at h', rcases lt_univ.{u}.1 h' with ⟨c', rfl⟩, exact ⟨c', by simp only [e.symm, lift_lift]⟩ end, λ ⟨c', e⟩, e.symm ▸ lift_lt_univ' _⟩ theorem small_iff_lift_mk_lt_univ {α : Type u} : small.{v} α ↔ cardinal.lift (#α) < univ.{v (max u (v + 1))} := begin rw lt_univ', split, { rintro ⟨β, e⟩, exact ⟨#β, lift_mk_eq.{u _ (v + 1)}.2 e⟩ }, { rintro ⟨c, hc⟩, exact ⟨⟨c.out, lift_mk_eq.{u _ (v + 1)}.1 (hc.trans (congr rfl c.mk_out.symm))⟩⟩ } end end cardinal namespace ordinal @[simp] theorem card_univ : card univ = cardinal.univ := rfl @[simp] theorem nat_le_card {o} {n : ℕ} : (n : cardinal) ≤ card o ↔ (n : ordinal) ≤ o := by rw [← cardinal.ord_le, cardinal.ord_nat] @[simp] theorem nat_lt_card {o} {n : ℕ} : (n : cardinal) < card o ↔ (n : ordinal) < o := by { rw [←succ_le_iff, ←succ_le_iff, ←nat_succ, nat_le_card], refl } @[simp] theorem card_lt_nat {o} {n : ℕ} : card o < n ↔ o < n := lt_iff_lt_of_le_iff_le nat_le_card @[simp] theorem card_le_nat {o} {n : ℕ} : card o ≤ n ↔ o ≤ n := le_iff_le_iff_lt_iff_lt.2 nat_lt_card @[simp] theorem card_eq_nat {o} {n : ℕ} : card o = n ↔ o = n := by simp only [le_antisymm_iff, card_le_nat, nat_le_card] @[simp] theorem type_fintype (r : α → α → Prop) [is_well_order α r] [fintype α] : type r = fintype.card α := by rw [←card_eq_nat, card_type, mk_fintype] theorem type_fin (n : ℕ) : @type (fin n) (<) _ = n := by simp end ordinal
6ad83b803559698942571c4c92bd5661a90142c8
dc15192b741b5d1c22cea8d65d6eb38bce3d838d
/src/base_of.lean
a610672b3286799423343b24053a759eb0e5275c
[]
no_license
VArtem/lean-matroids
86910241ac8d1a5ec7b35adb77c1cc9969480fb9
a8969b1cb2456820ccbdce65e2e168c48c30d9bf
refs/heads/main
1,678,556,999,525
1,614,537,008,000
1,614,537,008,000
338,915,729
0
1
null
null
null
null
UTF-8
Lean
false
false
2,088
lean
import data.fintype.basic import tactic import matroid import finset variables {α : Type*} [fintype α] [decidable_eq α] {m : matroid α} {A B X: finset α} open finset namespace matroid lemma base_of_refl_iff_ind : m.ind A ↔ m.base_of A A := begin split, { intro Aind, refine ⟨subset.refl _, Aind, λ x hnx hx, absurd hx hnx⟩, }, { exact λ hb, hb.2.1, } end lemma base_of_eq_card (hA : m.base_of X A) (hB : m.base_of X B) : A.card = B.card := begin by_contradiction, wlog : A.card ≤ B.card := le_total A.card B.card using [A B, B A], replace h := nat.lt_of_le_and_ne case h, obtain ⟨w, wB, wA, winsert⟩ := m.ind_exchange _ _ (base_of_ind hA) (base_of_ind hB) h, refine hA.2.2 w wA (base_of_subset hB wB) winsert, end lemma ind_subset_base_of : A ⊆ X → m.ind A → ∃ B, A ⊆ B ∧ m.base_of X B := begin intros hAX hA, by_contradiction, push_neg at h, suffices ind_unbounded : ∀ k ≥ A.card, ∃ B, A ⊆ B ∧ B ⊆ X ∧ m.ind B ∧ B.card = k, { rcases ind_unbounded (X.card + 1) _ with ⟨B, hAB, hBX, Bind, Bcard⟩, replace hBX := card_le_of_subset hBX, linarith, replace hAX := card_le_of_subset hAX, linarith, }, apply nat.le_induction, { use [A, subset.refl A, hAX, hA], }, { rintro n Acard ⟨B, hAB, hBX, Bind, rfl⟩, specialize h B hAB, rw base_of at h, push_neg at h, rcases h hBX Bind with ⟨w, wB, wX, w_insert⟩, use [insert w B], use [subset.trans hAB (subset_insert _ _)], use [insert_subset.2 ⟨wX, hBX⟩], use [w_insert, card_insert_of_not_mem wB], } end theorem exists_base_of (m : matroid α) (X : finset α): ∃ A, m.base_of X A := begin obtain ⟨B, _, Bbase⟩ := ind_subset_base_of (empty_subset X) m.ind_empty, exact ⟨B, Bbase⟩, end lemma ind_card_le_base_of_card : (A ⊆ X) → m.ind A → m.base_of X B → A.card ≤ B.card := begin intros hAX Aind Bbase, obtain ⟨T, hAT, Tbase⟩ := ind_subset_base_of hAX Aind, rw base_of_eq_card Bbase Tbase, exact card_le_of_subset hAT, end end matroid
b8be488407b5924aa669f8a23602d46ddbc46c77
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/number_theory/bertrand.lean
27480499ca9b31167d3bc4c1f46653343101bc1f
[ "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
11,236
lean
/- Copyright (c) 2020 Patrick Stevens. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Stevens, Bolton Bailey -/ import data.nat.choose.factorization import number_theory.primorial import analysis.convex.specific_functions /-! # Bertrand's Postulate This file contains a proof of Bertrand's postulate: That between any positive number and its double there is a prime. The proof follows the outline of the Erdős proof presented in "Proofs from THE BOOK": One considers the prime factorization of `(2 * n).choose n`, and splits the constituent primes up into various groups, then upper bounds the contribution of each group. This upper bounds the central binomial coefficient, and if the postulate does not hold, this upper bound conflicts with a simple lower bound for large enough `n`. This proves the result holds for large enough `n`, and for smaller `n` an explicit list of primes is provided which covers the remaining cases. As in the [Metamath implementation](carneiro2015arithmetic), we rely on some optimizations from [Shigenori Tochiori](tochiori_bertrand). In particular we use the cleaner bound on the central binomial coefficient given in `nat.four_pow_lt_mul_central_binom`. ## References * [M. Aigner and G. M. Ziegler _Proofs from THE BOOK_][aigner1999proofs] * [S. Tochiori, _Considering the Proof of “There is a Prime between n and 2n”_][tochiori_bertrand] * [M. Carneiro, _Arithmetic in Metamath, Case Study: Bertrand's Postulate_][carneiro2015arithmetic] ## Tags Bertrand, prime, binomial coefficients -/ open_locale big_operators section real open real namespace bertrand /-- A reified version of the `bertrand.main_inequality` below. This is not best possible: it actually holds for 464 ≤ x. -/ lemma real_main_inequality {x : ℝ} (n_large : (512 : ℝ) ≤ x) : x * (2 * x) ^ (sqrt (2 * x)) * 4 ^ (2 * x / 3) ≤ 4 ^ x := begin let f : ℝ → ℝ := λ x, log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x, have hf' : ∀ x, 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3) := λ x h, div_pos (mul_pos h (rpow_pos_of_pos (mul_pos two_pos h) _)) (rpow_pos_of_pos four_pos _), have hf : ∀ x, 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)), { intros x h5, have h6 := mul_pos two_pos h5, have h7 := rpow_pos_of_pos h6 (sqrt (2 * x)), rw [log_div (mul_pos h5 h7).ne' (rpow_pos_of_pos four_pos _).ne', log_mul h5.ne' h7.ne', log_rpow h6, log_rpow zero_lt_four, ← mul_div_right_comm, ← mul_div, mul_comm x] }, have h5 : 0 < x := lt_of_lt_of_le (by norm_num1) n_large, rw [← div_le_one (rpow_pos_of_pos four_pos x), ← div_div_eq_mul_div, ← rpow_sub four_pos, ← mul_div 2 x, mul_div_left_comm, ← mul_one_sub, (by norm_num1 : (1 : ℝ) - 2 / 3 = 1 / 3), mul_one_div, ← log_nonpos_iff (hf' x h5), ← hf x h5], have h : concave_on ℝ (set.Ioi 0.5) f, { refine ((strict_concave_on_log_Ioi.concave_on.subset (set.Ioi_subset_Ioi _) (convex_Ioi 0.5)).add ((strict_concave_on_sqrt_mul_log_Ioi.concave_on.comp_linear_map ((2 : ℝ) • linear_map.id)).subset (λ a ha, lt_of_eq_of_lt _ ((mul_lt_mul_left two_pos).mpr ha)) (convex_Ioi 0.5))).sub ((convex_on_id (convex_Ioi 0.5)).smul (div_nonneg (log_nonneg _) _)); norm_num1 }, suffices : ∃ x1 x2, 0.5 < x1 ∧ x1 < x2 ∧ x2 ≤ x ∧ 0 ≤ f x1 ∧ f x2 ≤ 0, { obtain ⟨x1, x2, h1, h2, h0, h3, h4⟩ := this, exact (h.right_le_of_le_left'' h1 ((h1.trans h2).trans_le h0) h2 h0 (h4.trans h3)).trans h4 }, refine ⟨18, 512, by norm_num1, by norm_num1, le_trans (by norm_num1) n_large, _, _⟩, { have : sqrt (2 * 18) = 6 := (sqrt_eq_iff_mul_self_eq_of_pos (by norm_num1)).mpr (by norm_num1), rw [hf, log_nonneg_iff (hf' 18 _), this]; norm_num1 }, { have : sqrt (2 * 512) = 32, { exact (sqrt_eq_iff_mul_self_eq_of_pos (by norm_num1)).mpr (by norm_num1) }, rw [hf, log_nonpos_iff (hf' _ _), this, div_le_one (rpow_pos_of_pos four_pos _), ← rpow_le_rpow_iff _ (rpow_pos_of_pos four_pos _).le three_pos, ← rpow_mul]; norm_num1 }, end end bertrand end real section nat open nat /-- The inequality which contradicts Bertrand's postulate, for large enough `n`. -/ lemma bertrand_main_inequality {n : ℕ} (n_large : 512 ≤ n) : n * (2 * n) ^ sqrt (2 * n) * 4 ^ (2 * n / 3) ≤ 4 ^ n := begin rw ← @cast_le ℝ, simp only [cast_bit0, cast_add, cast_one, cast_mul, cast_pow, ← real.rpow_nat_cast], have n_pos : 0 < n := (dec_trivial : 0 < 512).trans_le n_large, have n2_pos : 1 ≤ 2 * n := mul_pos dec_trivial n_pos, refine trans (mul_le_mul _ _ _ _) (bertrand.real_main_inequality (by exact_mod_cast n_large)), { refine mul_le_mul_of_nonneg_left _ (nat.cast_nonneg _), refine real.rpow_le_rpow_of_exponent_le (by exact_mod_cast n2_pos) _, exact_mod_cast real.nat_sqrt_le_real_sqrt }, { exact real.rpow_le_rpow_of_exponent_le (by norm_num1) (cast_div_le.trans (by norm_cast)) }, { exact real.rpow_nonneg_of_nonneg (by norm_num1) _ }, { refine mul_nonneg (nat.cast_nonneg _) _, exact real.rpow_nonneg_of_nonneg (mul_nonneg zero_le_two (nat.cast_nonneg _)) _, }, end /-- A lemma that tells us that, in the case where Bertrand's postulate does not hold, the prime factorization of the central binomial coefficent only has factors at most `2 * n / 3 + 1`. -/ lemma central_binom_factorization_small (n : ℕ) (n_large : 2 < n) (no_prime: ¬∃ (p : ℕ), p.prime ∧ n < p ∧ p ≤ 2 * n) : central_binom n = ∏ p in finset.range (2 * n / 3 + 1), p ^ ((central_binom n).factorization p) := begin refine (eq.trans _ n.prod_pow_factorization_central_binom).symm, apply finset.prod_subset, { exact finset.range_subset.2 (add_le_add_right (nat.div_le_self _ _) _) }, intros x hx h2x, rw [finset.mem_range, lt_succ_iff] at hx h2x, rw [not_le, div_lt_iff_lt_mul' three_pos, mul_comm x] at h2x, replace no_prime := not_exists.mp no_prime x, rw [←and_assoc, not_and', not_and_distrib, not_lt] at no_prime, cases no_prime hx with h h, { rw [factorization_eq_zero_of_non_prime n.central_binom h, pow_zero] }, { rw [factorization_central_binom_of_two_mul_self_lt_three_mul n_large h h2x, pow_zero] }, end /-- An upper bound on the central binomial coefficient used in the proof of Bertrand's postulate. The bound splits the prime factors of `central_binom n` into those 1. At most `sqrt (2 * n)`, which contribute at most `2 * n` for each such prime. 2. Between `sqrt (2 * n)` and `2 * n / 3`, which contribute at most `4^(2 * n / 3)` in total. 3. Between `2 * n / 3` and `n`, which do not exist. 4. Between `n` and `2 * n`, which would not exist in the case where Bertrand's postulate is false. 5. Above `2 * n`, which do not exist. -/ lemma central_binom_le_of_no_bertrand_prime (n : ℕ) (n_big : 2 < n) (no_prime : ¬∃ (p : ℕ), nat.prime p ∧ n < p ∧ p ≤ 2 * n) : central_binom n ≤ (2 * n) ^ sqrt (2 * n) * 4 ^ (2 * n / 3) := begin have n_pos : 0 < n := (nat.zero_le _).trans_lt n_big, have n2_pos : 1 ≤ 2 * n := mul_pos two_pos n_pos, let S := (finset.range (2 * n / 3 + 1)).filter nat.prime, let f := λ x, x ^ n.central_binom.factorization x, have : ∏ (x : ℕ) in S, f x = ∏ (x : ℕ) in finset.range (2 * n / 3 + 1), f x, { refine finset.prod_filter_of_ne (λ p hp h, _), contrapose! h, dsimp only [f], rw [factorization_eq_zero_of_non_prime n.central_binom h, pow_zero] }, rw [central_binom_factorization_small n n_big no_prime, ← this, ← finset.prod_filter_mul_prod_filter_not S (≤ sqrt (2 * n))], apply mul_le_mul', { refine (finset.prod_le_prod'' (λ p hp, (_ : f p ≤ 2 * n))).trans _, { exact pow_factorization_choose_le (mul_pos two_pos n_pos) }, have : (finset.Icc 1 (sqrt (2 * n))).card = sqrt (2 * n), { rw [card_Icc, nat.add_sub_cancel] }, rw finset.prod_const, refine pow_le_pow n2_pos ((finset.card_le_of_subset (λ x hx, _)).trans this.le), obtain ⟨h1, h2⟩ := finset.mem_filter.1 hx, exact finset.mem_Icc.mpr ⟨(finset.mem_filter.1 h1).2.one_lt.le, h2⟩ }, { refine le_trans _ (primorial_le_4_pow (2 * n / 3)), refine (finset.prod_le_prod' (λ p hp, (_ : f p ≤ p))).trans _, { obtain ⟨h1, h2⟩ := finset.mem_filter.1 hp, refine (pow_le_pow (finset.mem_filter.1 h1).2.one_lt.le _).trans (pow_one p).le, exact nat.factorization_choose_le_one (sqrt_lt'.mp $ not_le.1 h2) }, refine finset.prod_le_prod_of_subset_of_one_le' (finset.filter_subset _ _) _, exact λ p hp _, (finset.mem_filter.1 hp).2.one_lt.le } end namespace nat /-- Proves that Bertrand's postulate holds for all sufficiently large `n`. -/ lemma exists_prime_lt_and_le_two_mul_eventually (n : ℕ) (n_big : 512 ≤ n) : ∃ (p : ℕ), p.prime ∧ n < p ∧ p ≤ 2 * n := begin -- Assume there is no prime in the range. by_contradiction no_prime, -- Then we have the above sub-exponential bound on the size of this central binomial coefficient. -- We now couple this bound with an exponential lower bound on the central binomial coefficient, -- yielding an inequality which we have seen is false for large enough n. have H1 : n * (2 * n) ^ sqrt (2 * n) * 4 ^ (2 * n / 3) ≤ 4 ^ n := bertrand_main_inequality n_big, have H2 : 4 ^ n < n * n.central_binom := nat.four_pow_lt_mul_central_binom n (le_trans (by norm_num1) n_big), have H3 : n.central_binom ≤ (2 * n) ^ sqrt (2 * n) * 4 ^ (2 * n / 3) := central_binom_le_of_no_bertrand_prime n (lt_of_lt_of_le (by norm_num1) n_big) no_prime, rw mul_assoc at H1, exact not_le.2 H2 ((mul_le_mul_left' H3 n).trans H1), end /-- Proves that Bertrand's postulate holds over all positive naturals less than n by identifying a descending list of primes, each no more than twice the next, such that the list contains a witness for each number ≤ n. -/ lemma exists_prime_lt_and_le_two_mul_succ {n} (q) {p : ℕ} (prime_p : nat.prime p) (covering : p ≤ 2 * q) (H : n < q → ∃ (p : ℕ), p.prime ∧ n < p ∧ p ≤ 2 * n) (hn : n < p) : ∃ (p : ℕ), p.prime ∧ n < p ∧ p ≤ 2 * n := begin by_cases p ≤ 2 * n, { exact ⟨p, prime_p, hn, h⟩ }, exact H (lt_of_mul_lt_mul_left' (lt_of_lt_of_le (not_le.1 h) covering)) end /-- **Bertrand's Postulate**: For any positive natural number, there is a prime which is greater than it, but no more than twice as large. -/ theorem exists_prime_lt_and_le_two_mul (n : ℕ) (hn0 : n ≠ 0) : ∃ p, nat.prime p ∧ n < p ∧ p ≤ 2 * n := begin -- Split into cases whether `n` is large or small cases lt_or_le 511 n, -- If `n` is large, apply the lemma derived from the inequalities on the central binomial -- coefficient. { exact exists_prime_lt_and_le_two_mul_eventually n h, }, replace h : n < 521 := h.trans_lt (by norm_num1), revert h, -- For small `n`, supply a list of primes to cover the initial cases. ([317, 163, 83, 43, 23, 13, 7, 5, 3, 2].mmap' $ λ n, `[refine exists_prime_lt_and_le_two_mul_succ %%(reflect n) (by norm_num1) (by norm_num1) _]), exact λ h2, ⟨2, prime_two, h2, nat.mul_le_mul_left 2 (nat.pos_of_ne_zero hn0)⟩, end alias nat.exists_prime_lt_and_le_two_mul ← bertrand end nat end nat
f3df667beca57c02780479ed2e9f50dde5a435d5
c09f5945267fd905e23a77be83d9a78580e04a4a
/src/analysis/normed_space/deriv.lean
436e522e7b4aa82ff93308a96fcce982af8a1fb0
[ "Apache-2.0" ]
permissive
OHIHIYA20/mathlib
023a6df35355b5b6eb931c404f7dd7535dccfa89
1ec0a1f49db97d45e8666a3bf33217ff79ca1d87
refs/heads/master
1,587,964,529,965
1,551,819,319,000
1,551,819,319,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,858
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad The Fréchet derivative. Let `E` and `F` be normed spaces, and `f : E → F`. Then `has_fderiv_at_within f f' x s` says that the function `f' : E → F` is a bounded linear map and `f` has derivative `f'` at `x`, where the domain of interest is restricted to `s`. We also have `has_fderiv_at f f' x := has_fderiv_at_within f f' x univ` The derivative is defined in terms of the `is_o` relation, but also characterized in terms of the `tendsto` relation. -/ import topology.basic analysis.normed_space.bounded_linear_maps ..asymptotics tactic.abel open filter asymptotics section variables {K : Type*} [normed_field K] variables {E : Type*} [normed_space K E] variables {F : Type*} [normed_space K F] variables {G : Type*} [normed_space K G] include K def has_fderiv_at_filter (f : E → F) (f' : E → F) (x : E) (L : filter E) := is_bounded_linear_map f' ∧ is_o (λ x', f x' - f x - f' (x' - x)) (λ x', x' - x) L def has_fderiv_at_within (f : E → F) (f' : E → F) (x : E) (s : set E) := has_fderiv_at_filter f f' x (nhds_within x s) def has_fderiv_at (f : E → F) (f' : E → F) (x : E) := has_fderiv_at_filter f f' x (nhds x) theorem has_fderiv_at_filter.is_o {f : E → F} {f' : E → F} {x L} (h : has_fderiv_at_filter f f' x L) : is_o (λ x', f x' - f x - f' (x' - x)) (λ x', x' - x) L := h.right theorem has_fderiv_at.is_o {f : E → F} {f' : E → F} {x : E} (h : has_fderiv_at f f' x) : is_o (λ x', f x' - f x - f' (x' - x)) (λ x', x' - x) (nhds x) := h.is_o theorem has_fderiv_at_filter_iff_tendsto {f : E → F} {f' : E → F} {x : E} {L : filter E} : has_fderiv_at_filter f f' x L ↔ is_bounded_linear_map f' ∧ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) L (nhds 0) := and.congr_right_iff.mpr $ assume bf' : is_bounded_linear_map f', have f'0 : f' 0 = 0 := (bf'.to_linear_map _).map_zero, have h : ∀ x', ∥x' - x∥ = 0 → ∥f x' - f x - f' (x' - x)∥ = 0, from assume x' hx', have x' = x, from eq_of_sub_eq_zero ((norm_eq_zero _).mp hx'), by rw this; simp [f'0], begin rw [←is_o_norm_left, ←is_o_norm_right, is_o_iff_tendsto h], exact tendsto.congr'r (λ x', mul_comm _ _) end theorem has_fderiv_at_within_iff_tendsto {f : E → F} {f' : E → F} {x : E} {s : set E} : has_fderiv_at_within f f' x s ↔ is_bounded_linear_map f' ∧ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) (nhds_within x s) (nhds 0) := has_fderiv_at_filter_iff_tendsto theorem has_fderiv_at_iff_tendsto {f : E → F} {f' : E → F} {x : E} : has_fderiv_at f f' x ↔ is_bounded_linear_map f' ∧ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) (nhds x) (nhds 0) := has_fderiv_at_filter_iff_tendsto theorem has_fderiv_at_filter.mono {f : E → F} {f' : E → F} {x : E} {L₁ L₂ : filter E} (hst : L₁ ≤ L₂) : has_fderiv_at_filter f f' x L₂ → has_fderiv_at_filter f f' x L₁ := and.imp_right (is_o.mono hst) theorem has_fderiv_at_within.mono {f : E → F} {f' : E → F} {x : E} {s t : set E} (hst : s ⊆ t) : has_fderiv_at_within f f' x t → has_fderiv_at_within f f' x s := has_fderiv_at_filter.mono (nhds_within_mono _ hst) theorem has_fderiv_at_filter_of_has_fderiv_at {f : E → F} {f' : E → F} {x : E} {L : filter E} (hL : L ≤ nhds x) (h : has_fderiv_at f f' x) : has_fderiv_at_filter f f' x L := h.mono hL theorem has_fderiv_at_within_of_has_fderiv_at {f : E → F} {f' : E → F} {x : E} {s : set E} : has_fderiv_at f f' x → has_fderiv_at_within f f' x s := has_fderiv_at_filter_of_has_fderiv_at lattice.inf_le_left theorem has_fderiv_at_filter_congr' {f₀ f₁ : E → F} {f₀' f₁' : E → F} {x : E} {L : filter E} (hx : f₀ x = f₁ x) (h₀ : {x | f₀ x = f₁ x} ∈ L.sets) (h₁ : ∀ x, f₀' x = f₁' x) : has_fderiv_at_filter f₀ f₀' x L ↔ has_fderiv_at_filter f₁ f₁' x L := by rw (funext h₁ : f₀' = f₁'); exact and_congr_right (λ _, is_o_congr (by filter_upwards [h₀] λ x' (h:_=_), by simp [h, hx]) (univ_mem_sets' $ λ _, rfl)) theorem has_fderiv_at_filter_congr {f₀ f₁ : E → F} {f₀' f₁' : E → F} {x : E} {L : filter E} (h₀ : ∀ x, f₀ x = f₁ x) (h₁ : ∀ x, f₀' x = f₁' x) : has_fderiv_at_filter f₀ f₀' x L ↔ has_fderiv_at_filter f₁ f₁' x L := has_fderiv_at_filter_congr' (h₀ _) (univ_mem_sets' h₀) h₁ theorem has_fderiv_at_filter.congr {f₀ f₁ : E → F} {f₀' f₁' : E → F} {x : E} {L : filter E} (h₀ : ∀ x, f₀ x = f₁ x) (h₁ : ∀ x, f₀' x = f₁' x) : has_fderiv_at_filter f₀ f₀' x L → has_fderiv_at_filter f₁ f₁' x L := (has_fderiv_at_filter_congr h₀ h₁).1 theorem has_fderiv_at_within_congr {f₀ f₁ : E → F} {f₀' f₁' : E → F} {x : E} {s : set E} (h₀ : ∀ x, f₀ x = f₁ x) (h₁ : ∀ x, f₀' x = f₁' x) : has_fderiv_at_within f₀ f₀' x s ↔ has_fderiv_at_within f₁ f₁' x s := has_fderiv_at_filter_congr h₀ h₁ theorem has_fderiv_at_within.congr {f₀ f₁ : E → F} {f₀' f₁' : E → F} {x : E} {s : set E} (h₀ : ∀ x, f₀ x = f₁ x) (h₁ : ∀ x, f₀' x = f₁' x) : has_fderiv_at_within f₀ f₀' x s → has_fderiv_at_within f₁ f₁' x s := (has_fderiv_at_within_congr h₀ h₁).1 theorem has_fderiv_at_congr {f₀ f₁ : E → F} {f₀' f₁' : E → F} {x : E} (h₀ : ∀ x, f₀ x = f₁ x) (h₁ : ∀ x, f₀' x = f₁' x) : has_fderiv_at f₀ f₀' x ↔ has_fderiv_at f₁ f₁' x := has_fderiv_at_filter_congr h₀ h₁ theorem has_fderiv_at.congr {f₀ f₁ : E → F} {f₀' f₁' : E → F} {x : E} (h₀ : ∀ x, f₀ x = f₁ x) (h₁ : ∀ x, f₀' x = f₁' x) : has_fderiv_at f₀ f₀' x → has_fderiv_at f₁ f₁' x := (has_fderiv_at_congr h₀ h₁).1 theorem has_fderiv_at_filter_id (x : E) (L : filter E) : has_fderiv_at_filter id id x L := ⟨is_bounded_linear_map.id, (is_o_zero _ _).congr_left (by simp)⟩ theorem has_fderiv_at_within_id (x : E) (s : set E) : has_fderiv_at_within id id x s := has_fderiv_at_filter_id _ _ theorem has_fderiv_at_id (x : E) : has_fderiv_at id id x := has_fderiv_at_filter_id _ _ theorem has_fderiv_at_filter_const (c : F) (x : E) (L : filter E) : has_fderiv_at_filter (λ x, c) (λ y, 0) x L := ⟨is_bounded_linear_map.zero, (is_o_zero _ _).congr_left (by simp)⟩ theorem has_fderiv_at_within_const (c : F) (x : E) (s : set E) : has_fderiv_at_within (λ x, c) (λ y, 0) x s := has_fderiv_at_filter_const _ _ _ theorem has_fderiv_at_const (c : F) (x : E) : has_fderiv_at (λ x, c) (λ y, 0) x := has_fderiv_at_filter_const _ _ _ theorem has_fderiv_at_filter_smul {f : E → F} {f' : E → F} {x : E} {L : filter E} (c : K) (h : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (λ x, c • f x) (λ x, c • f' x) x L := ⟨is_bounded_linear_map.smul c h.left, (is_o_const_smul_left h.right c).congr_left $ λ x, by simp [smul_neg, smul_add]⟩ theorem has_fderiv_at_within_smul {f : E → F} {f' : E → F} {x : E} {s : set E} (c : K) : has_fderiv_at_within f f' x s → has_fderiv_at_within (λ x, c • f x) (λ x, c • f' x) x s := has_fderiv_at_filter_smul _ theorem has_fderiv_at_smul {f : E → F} {f' : E → F} {x : E} (c : K) : has_fderiv_at f f' x → has_fderiv_at (λ x, c • f x) (λ x, c • f' x) x := has_fderiv_at_filter_smul _ theorem has_fderiv_at_filter_add {f g : E → F} {f' g' : E → F} {x : E} {L : filter E} (hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' x L) : has_fderiv_at_filter (λ x, f x + g x) (λ x, f' x + g' x) x L := ⟨is_bounded_linear_map.add hf.left hg.left, (hf.right.add hg.right).congr_left (by simp)⟩ theorem has_fderiv_at_within_add {f g : E → F} {f' g' : E → F} {x : E} {s : set E} : has_fderiv_at_within f f' x s → has_fderiv_at_within g g' x s → has_fderiv_at_within (λ x, f x + g x) (λ x, f' x + g' x) x s := has_fderiv_at_filter_add theorem has_fderiv_at_add {f g : E → F} {f' g' : E → F} {x : E} : has_fderiv_at f f' x → has_fderiv_at g g' x → has_fderiv_at (λ x, f x + g x) (λ x, f' x + g' x) x := has_fderiv_at_filter_add theorem has_fderiv_at_filter_neg {f : E → F} {f' : E → F} {x : E} {L : filter E} (h : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (λ x, -f x) (λ x, -f' x) x L := (has_fderiv_at_filter_smul (-1 : K) h).congr (by simp) (by simp) theorem has_fderiv_at_within_neg {f : E → F} {f' : E → F} {x : E} {s : set E} : has_fderiv_at_within f f' x s → has_fderiv_at_within (λ x, -f x) (λ x, -f' x) x s := has_fderiv_at_filter_neg theorem has_fderiv_at_neg {f : E → F} {f' : E → F} {x : E} : has_fderiv_at f f' x → has_fderiv_at (λ x, -f x) (λ x, -f' x) x := has_fderiv_at_filter_neg theorem has_fderiv_at_filter_sub {f g : E → F} {f' g' : E → F} {x : E} {L : filter E} (hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' x L) : has_fderiv_at_filter (λ x, f x - g x) (λ x, f' x - g' x) x L := has_fderiv_at_filter_add hf (has_fderiv_at_filter_neg hg) theorem has_fderiv_at_within_sub {f g : E → F} {f' g' : E → F} {x : E} {s : set E} : has_fderiv_at_within f f' x s → has_fderiv_at_within g g' x s → has_fderiv_at_within (λ x, f x - g x) (λ x, f' x - g' x) x s := has_fderiv_at_filter_sub theorem has_fderiv_at_sub {f g : E → F} {f' g' : E → F} {x : E} : has_fderiv_at f f' x → has_fderiv_at g g' x → has_fderiv_at (λ x, f x - g x) (λ x, f' x - g' x) x := has_fderiv_at_filter_sub theorem has_fderiv_at_filter.is_O_sub {f : E → F} {f' : E → F} {x : E} {L : filter E} (h : has_fderiv_at_filter f f' x L) : is_O (λ x', f x' - f x) (λ x', x' - x) L := h.2.to_is_O.congr_of_sub.2 (h.1.is_O_sub _ _) theorem has_fderiv_at_filter.tendsto_nhds {f : E → F} {f' : E → F} {x : E} {L : filter E} (hL : L ≤ nhds x) (h : has_fderiv_at_filter f f' x L) : tendsto f L (nhds (f x)) := begin have : tendsto (λ x', f x' - f x) L (nhds 0), { refine h.is_O_sub.trans_tendsto (tendsto_le_left hL _), rw ← sub_self x, exact tendsto_sub tendsto_id tendsto_const_nhds }, have := tendsto_add this tendsto_const_nhds, rw zero_add (f x) at this, exact this.congr (by simp) end theorem has_fderiv_at_within.continuous_at_within {f : E → F} {f' : E → F} {x : E} {s : set E} : has_fderiv_at_within f f' x s → continuous_at_within f x s := has_fderiv_at_filter.tendsto_nhds lattice.inf_le_left theorem has_fderiv_at.continuous_at {f : E → F} {f' : E → F} {x : E} : has_fderiv_at f f' x → continuous_at f x := has_fderiv_at_filter.tendsto_nhds (le_refl _) theorem has_fderiv_at_filter.comp {g g' : F → G} {f f' : E → F} {L : filter E} {x : E} (hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' (f x) (L.map f)) : has_fderiv_at_filter (g ∘ f) (g' ∘ f') x L := ⟨hg.1.comp hf.1, begin have eq₁ := (hg.1.is_O_comp _).trans_is_o hf.2, have eq₂ := ((hg.2.comp f).mono le_comap_map).trans_is_O hf.is_O_sub, refine eq₂.tri (eq₁.congr_left (λ x', _)), rw [show g' (_-_) = g' _ - g' _, from (hg.1.to_linear_map _).map_sub _ _] end⟩ /- A readable version of the previous theorem, a general form of the chain rule. -/ example {g g' : F → G} {f f' : E → F} {L : filter E} {x : E} (hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' (f x) (L.map f)) : has_fderiv_at_filter (g ∘ f) (g' ∘ f') x L := ⟨hg.1.comp hf.1, begin have : is_o (λ x', g (f x') - g (f x) - g' (f x' - f x)) (λ x', f x' - f x) L, from (hg.2.comp f).mono le_comap_map, have eq₁ : is_o (λ x', g (f x') - g (f x) - g' (f x' - f x)) (λ x', x' - x) L, from this.trans_is_O hf.is_O_sub, have eq₂ : is_o (λ x', f x' - f x - f' (x' - x)) (λ x', x' - x) L, from hf.2, have : is_O (λ x', g' (f x' - f x - f' (x' - x))) (λ x', f x' - f x - f' (x' - x)) L, from hg.1.is_O_comp _, have : is_o (λ x', g' (f x' - f x - f' (x' - x))) (λ x', x' - x) L, from this.trans_is_o eq₂, have eq₃ : is_o (λ x', g' (f x' - f x) - (g' (f' (x' - x)))) (λ x', x' - x) L, by { refine this.congr_left (λ x', _), rw [show g' (_-_) = g' _ - g' _, from (hg.1.to_linear_map _).map_sub _ _] }, exact eq₁.tri eq₃ end⟩ theorem has_fderiv_at_within.comp {g g' : F → G} {f f' : E → F} {s : set E} {x : E} (hf : has_fderiv_at_within f f' x s) (hg : has_fderiv_at_within g g' (f x) (f '' s)) : has_fderiv_at_within (g ∘ f) (g' ∘ f') x s := hf.comp (has_fderiv_at_filter.mono hf.continuous_at_within.tendsto_nhds_within_image hg) /-- The chain rule. -/ theorem has_fderiv_at.comp {g g' : F → G} {f f' : E → F} {x : E} (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' (f x)) : has_fderiv_at (g ∘ f) (g' ∘ f') x := hf.comp (hg.mono hf.continuous_at) end /- In the special case of a normed space over the reals, we can use scalar multiplication in the `tendsto` characterization of the Fréchet derivative. -/ section variables {E : Type*} [normed_space ℝ E] variables {F : Type*} [normed_space ℝ F] variables {G : Type*} [normed_space ℝ G] theorem has_fderiv_at_filter_real_equiv {f : E → F} {f' : E → F} {x : E} {L : filter E} (bf' : is_bounded_linear_map f') : tendsto (λ x' : E, ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) L (nhds 0) ↔ tendsto (λ x' : E, ∥x' - x∥⁻¹ • (f x' - f x - f' (x' - x))) L (nhds 0) := begin have f'0 : f' 0 = 0 := (bf'.to_linear_map _).map_zero, symmetry, rw [tendsto_iff_norm_tendsto_zero], refine tendsto.congr'r (λ x', _), have : ∥x' + -x∥⁻¹ ≥ 0, from inv_nonneg.mpr (norm_nonneg _), simp [norm_smul, real.norm_eq_abs, abs_of_nonneg this] end end
5132e469f60d074934a139c19bd6a345d0c1283d
fe84e287c662151bb313504482b218a503b972f3
/src/combinatorics/graph.lean
7e0dd66981b90f1906e7bce3ea12b1a25d890daa
[]
no_license
NeilStrickland/lean_lib
91e163f514b829c42fe75636407138b5c75cba83
6a9563de93748ace509d9db4302db6cd77d8f92c
refs/heads/master
1,653,408,198,261
1,652,996,419,000
1,652,996,419,000
181,006,067
4
1
null
null
null
null
UTF-8
Lean
false
false
3,452
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland This file gives some basic definitions for graph theory. It supports only graphs with no loops or multiple edges. It should be refactored to use definitions and results from data/pos_list.lean -/ import data.pos_list import tactic.interactive namespace combinatorics class graph (V : Type) : Type := (edge : V → V → Prop) (symm : ∀ {u v : V}, edge u v → edge v u) (asymm : ∀ v : V, ¬ edge v v) namespace graph variables {V : Type} [graph V] def is_path : pos_list V → Prop | (pos_list.const _) := true | (pos_list.cons v p) := (edge v p.head) ∧ is_path p lemma is_path_append (p q : pos_list V) : is_path (pos_list.append p q) ↔ is_path p ∧ edge p.foot q.head ∧ is_path q := begin induction p with a a p ih, {dsimp[is_path,pos_list.foot,pos_list.append,is_path], rw[true_and] }, {dsimp[pos_list.append,pos_list.foot,is_path], rw[pos_list.head_append,ih,and_assoc], } end lemma is_path_reverse : ∀ {p : pos_list V}, is_path p → is_path p.reverse | (pos_list.const a) _ := by {dsimp[pos_list.reverse,is_path],trivial} | (pos_list.cons a p) h := begin dsimp[pos_list.reverse,is_path], dsimp[is_path] at h, rw[is_path_append,pos_list.head,pos_list.foot_reverse,is_path,and_true], exact ⟨is_path_reverse h.right,symm h.left⟩, end variable (V) def path : Type := { p : pos_list V // is_path p } variable {V} def path_between (a b : V) : Type := { p : pos_list V // is_path p ∧ p.head = a ∧ p.foot = b } namespace path def head (p : path V) : V := p.val.head def foot (p : path V) : V := p.val.foot def length (p : path V) : ℕ := p.val.length def cons (v : V) (p : path V) (h : edge v p.head) : path V := ⟨pos_list.cons v p.val,⟨h,p.property⟩⟩ def const (v : V) : path_between v v := ⟨pos_list.const v,⟨trivial,rfl,rfl⟩⟩ def reverse {u v : V} : ∀ (p : path_between u v), path_between v u | ⟨p,⟨p_path,p_head,p_foot⟩⟩ := ⟨p.reverse,⟨is_path_reverse p_path, (pos_list.head_reverse p).trans p_foot, (pos_list.foot_reverse p).trans p_head⟩⟩ def splice {u v w : V} : ∀ (p : path_between u v) (q : path_between v w), path_between u w | ⟨p,⟨p_path,p_head,p_foot⟩⟩ ⟨pos_list.const x,⟨q_path,q_head,q_foot⟩⟩ := ⟨p,begin change x = v at q_head, change x = w at q_foot, replace p_foot := p_foot.trans (q_head.symm.trans q_foot), exact ⟨p_path,p_head,p_foot⟩ end⟩ | ⟨p,⟨p_path,p_head,p_foot⟩⟩ ⟨pos_list.cons x q,⟨q_path,q_head,q_foot⟩⟩ := ⟨pos_list.append p q, begin change x = v at q_head, change q.foot = w at q_foot, rw[pos_list.head_append,p_head,pos_list.foot_append,q_foot], split, {dsimp[is_path] at q_path,rw[is_path_append,p_foot,← q_head], exact ⟨p_path,q_path⟩}, {split;refl,} end ⟩ instance are_connected : setoid V := { r := λ a b, nonempty (path_between a b), iseqv := ⟨ λ a, nonempty.intro (const a), λ a b ⟨p⟩, nonempty.intro (reverse p), λ a b c ⟨p⟩ ⟨q⟩, nonempty.intro (splice p q) ⟩ } /- For finite graphs with decidable equality: define valence, prove that there are two vertices with the same valence. -/ end path end graph end combinatorics
400e59d40898f7ce13a368ba4ab1eabda9c4dbfe
037dba89703a79cd4a4aec5e959818147f97635d
/src/2020/problem_sheets/Part_II/sheet1_q3.lean
4fbc3867c4ce32459313b2d5fdd02ba7e1febe4a
[]
no_license
ImperialCollegeLondon/M40001_lean
3a6a09298da395ab51bc220a535035d45bbe919b
62a76fa92654c855af2b2fc2bef8e60acd16ccec
refs/heads/master
1,666,750,403,259
1,665,771,117,000
1,665,771,117,000
209,141,835
115
12
null
1,640,270,596,000
1,568,749,174,000
Lean
UTF-8
Lean
false
false
775
lean
import tactic variables (x y : ℕ) open nat -- Q3 def def is_pred (x y : ℕ) := x.succ = y theorem Q3a : ¬ ∃ x : ℕ, is_pred x 0 := begin sorry end theorem Q3b : y ≠ 0 → ∃! x, is_pred x y := begin sorry end def aux : 0 < y → ∃ x, is_pred x y := begin sorry end -- definition of pred' is "choose a random d such that succ(d) = n" noncomputable def pred' : ℕ+ → ℕ := λ nhn, classical.some (aux nhn nhn.2) theorem pred'_def : ∀ np : ℕ+, is_pred (pred' np) np := λ nhn, classical.some_spec (aux nhn nhn.2) def succ' : ℕ → ℕ+ := λ n, ⟨n.succ, zero_lt_succ n⟩ noncomputable definition Q3c : ℕ+ ≃ ℕ := { to_fun := pred', inv_fun := succ', left_inv := begin sorry end, right_inv := begin sorry end }
fc1b94fe82c783f6fa5f2f1c4eda999f36e026c4
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/algebra/big_operators/basic.lean
c1bfa596b492759e86bc47cd453da5b741c24e1f
[ "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
60,250
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import data.finset.fold import data.equiv.mul_add import tactic.abel /-! # Big operators In this file we define products and sums indexed by finite sets (specifically, `finset`). ## Notation We introduce the following notation, localized in `big_operators`. To enable the notation, use `open_locale big_operators`. Let `s` be a `finset α`, and `f : α → β` a function. * `∏ x in s, f x` is notation for `finset.prod s f` (assuming `β` is a `comm_monoid`) * `∑ x in s, f x` is notation for `finset.sum s f` (assuming `β` is an `add_comm_monoid`) * `∏ x, f x` is notation for `finset.prod finset.univ f` (assuming `α` is a `fintype` and `β` is a `comm_monoid`) * `∑ x, f x` is notation for `finset.sum finset.univ f` (assuming `α` is a `fintype` and `β` is an `add_comm_monoid`) -/ universes u v w variables {α : Type u} {β : Type v} {γ : Type w} namespace finset /-- `∏ x in s, f x` is the product of `f x` as `x` ranges over the elements of the finite set `s`. -/ @[to_additive "`∑ x in s, f` is the sum of `f x` as `x` ranges over the elements of the finite set `s`."] protected def prod [comm_monoid β] (s : finset α) (f : α → β) : β := (s.1.map f).prod @[simp, to_additive] lemma prod_mk [comm_monoid β] (s : multiset α) (hs) (f : α → β) : (⟨s, hs⟩ : finset α).prod f = (s.map f).prod := rfl end finset /-- There is no established mathematical convention for the operator precedence of big operators like `∏` and `∑`. We will have to make a choice. Online discussions, such as https://math.stackexchange.com/q/185538/30839 seem to suggest that `∏` and `∑` should have the same precedence, and that this should be somewhere between `*` and `+`. The latter have precedence levels `70` and `65` respectively, and we therefore choose the level `67`. In practice, this means that parentheses should be placed as follows: ```lean ∑ k in K, (a k + b k) = ∑ k in K, a k + ∑ k in K, b k → ∏ k in K, a k * b k = (∏ k in K, a k) * (∏ k in K, b k) ``` (Example taken from page 490 of Knuth's *Concrete Mathematics*.) -/ library_note "operator precedence of big operators" localized "notation `∑` binders `, ` r:(scoped:67 f, finset.sum finset.univ f) := r" in big_operators localized "notation `∏` binders `, ` r:(scoped:67 f, finset.prod finset.univ f) := r" in big_operators localized "notation `∑` binders ` in ` s `, ` r:(scoped:67 f, finset.sum s f) := r" in big_operators localized "notation `∏` binders ` in ` s `, ` r:(scoped:67 f, finset.prod s f) := r" in big_operators open_locale big_operators namespace finset variables {s s₁ s₂ : finset α} {a : α} {f g : α → β} @[to_additive] lemma prod_eq_multiset_prod [comm_monoid β] (s : finset α) (f : α → β) : ∏ x in s, f x = (s.1.map f).prod := rfl @[to_additive] theorem prod_eq_fold [comm_monoid β] (s : finset α) (f : α → β) : (∏ x in s, f x) = s.fold (*) 1 f := rfl @[simp] lemma sum_multiset_singleton (s : finset α) : s.sum (λ x, x ::ₘ 0) = s.val := by simp [sum_eq_multiset_sum] end finset @[to_additive] lemma monoid_hom.map_prod [comm_monoid β] [comm_monoid γ] (g : β →* γ) (f : α → β) (s : finset α) : g (∏ x in s, f x) = ∏ x in s, g (f x) := by simp only [finset.prod_eq_multiset_prod, g.map_multiset_prod, multiset.map_map] @[to_additive] lemma mul_equiv.map_prod [comm_monoid β] [comm_monoid γ] (g : β ≃* γ) (f : α → β) (s : finset α) : g (∏ x in s, f x) = ∏ x in s, g (f x) := g.to_monoid_hom.map_prod f s lemma ring_hom.map_list_prod [semiring β] [semiring γ] (f : β →+* γ) (l : list β) : f l.prod = (l.map f).prod := f.to_monoid_hom.map_list_prod l lemma ring_hom.map_list_sum [semiring β] [semiring γ] (f : β →+* γ) (l : list β) : f l.sum = (l.map f).sum := f.to_add_monoid_hom.map_list_sum l lemma ring_hom.map_multiset_prod [comm_semiring β] [comm_semiring γ] (f : β →+* γ) (s : multiset β) : f s.prod = (s.map f).prod := f.to_monoid_hom.map_multiset_prod s lemma ring_hom.map_multiset_sum [semiring β] [semiring γ] (f : β →+* γ) (s : multiset β) : f s.sum = (s.map f).sum := f.to_add_monoid_hom.map_multiset_sum s lemma ring_hom.map_prod [comm_semiring β] [comm_semiring γ] (g : β →+* γ) (f : α → β) (s : finset α) : g (∏ x in s, f x) = ∏ x in s, g (f x) := g.to_monoid_hom.map_prod f s lemma ring_hom.map_sum [semiring β] [semiring γ] (g : β →+* γ) (f : α → β) (s : finset α) : g (∑ x in s, f x) = ∑ x in s, g (f x) := g.to_add_monoid_hom.map_sum f s @[to_additive] lemma monoid_hom.coe_prod [mul_one_class β] [comm_monoid γ] (f : α → β →* γ) (s : finset α) : ⇑(∏ x in s, f x) = ∏ x in s, f x := (monoid_hom.coe_fn β γ).map_prod _ _ -- See also `finset.prod_apply`, with the same conclusion -- but with the weaker hypothesis `f : α → β → γ`. @[simp, to_additive] lemma monoid_hom.finset_prod_apply [mul_one_class β] [comm_monoid γ] (f : α → β →* γ) (s : finset α) (b : β) : (∏ x in s, f x) b = ∏ x in s, f x b := (monoid_hom.eval b).map_prod _ _ variables {s s₁ s₂ : finset α} {a : α} {f g : α → β} namespace finset section comm_monoid variables [comm_monoid β] @[simp, to_additive] lemma prod_empty {α : Type u} {f : α → β} : (∏ x in (∅:finset α), f x) = 1 := rfl @[simp, to_additive] lemma prod_insert [decidable_eq α] : a ∉ s → (∏ x in (insert a s), f x) = f a * ∏ x in s, f x := fold_insert /-- The product of `f` over `insert a s` is the same as the product over `s`, as long as `a` is in `s` or `f a = 1`. -/ @[simp, to_additive "The sum of `f` over `insert a s` is the same as the sum over `s`, as long as `a` is in `s` or `f a = 0`."] lemma prod_insert_of_eq_one_if_not_mem [decidable_eq α] (h : a ∉ s → f a = 1) : ∏ x in insert a s, f x = ∏ x in s, f x := begin by_cases hm : a ∈ s, { simp_rw insert_eq_of_mem hm }, { rw [prod_insert hm, h hm, one_mul] }, end /-- The product of `f` over `insert a s` is the same as the product over `s`, as long as `f a = 1`. -/ @[simp, to_additive "The sum of `f` over `insert a s` is the same as the sum over `s`, as long as `f a = 0`."] lemma prod_insert_one [decidable_eq α] (h : f a = 1) : ∏ x in insert a s, f x = ∏ x in s, f x := prod_insert_of_eq_one_if_not_mem (λ _, h) @[simp, to_additive] lemma prod_singleton : (∏ x in (singleton a), f x) = f a := eq.trans fold_singleton $ mul_one _ @[to_additive] lemma prod_pair [decidable_eq α] {a b : α} (h : a ≠ b) : (∏ x in ({a, b} : finset α), f x) = f a * f b := by rw [prod_insert (not_mem_singleton.2 h), prod_singleton] @[simp, priority 1100] lemma prod_const_one : (∏ x in s, (1 : β)) = 1 := by simp only [finset.prod, multiset.map_const, multiset.prod_repeat, one_pow] @[simp, priority 1100] lemma sum_const_zero {β} {s : finset α} [add_comm_monoid β] : (∑ x in s, (0 : β)) = 0 := @prod_const_one _ (multiplicative β) _ _ attribute [to_additive] prod_const_one @[simp, to_additive] lemma prod_image [decidable_eq α] {s : finset γ} {g : γ → α} : (∀x∈s, ∀y∈s, g x = g y → x = y) → (∏ x in (s.image g), f x) = ∏ x in s, f (g x) := fold_image @[simp, to_additive] lemma prod_map (s : finset α) (e : α ↪ γ) (f : γ → β) : (∏ x in (s.map e), f x) = ∏ x in s, f (e x) := by rw [finset.prod, finset.map_val, multiset.map_map]; refl @[congr, to_additive] lemma prod_congr (h : s₁ = s₂) : (∀x∈s₂, f x = g x) → s₁.prod f = s₂.prod g := by rw [h]; exact fold_congr attribute [congr] finset.sum_congr @[to_additive] lemma prod_union_inter [decidable_eq α] : (∏ x in (s₁ ∪ s₂), f x) * (∏ x in (s₁ ∩ s₂), f x) = (∏ x in s₁, f x) * (∏ x in s₂, f x) := fold_union_inter @[to_additive] lemma prod_union [decidable_eq α] (h : disjoint s₁ s₂) : (∏ x in (s₁ ∪ s₂), f x) = (∏ x in s₁, f x) * (∏ x in s₂, f x) := by rw [←prod_union_inter, (disjoint_iff_inter_eq_empty.mp h)]; exact (mul_one _).symm end comm_monoid end finset section open finset variables [fintype α] [decidable_eq α] [comm_monoid β] @[to_additive] lemma is_compl.prod_mul_prod {s t : finset α} (h : is_compl s t) (f : α → β) : (∏ i in s, f i) * (∏ i in t, f i) = ∏ i, f i := (finset.prod_union h.disjoint).symm.trans $ by rw [← finset.sup_eq_union, h.sup_eq_top]; refl end namespace finset section comm_monoid variables [comm_monoid β] @[to_additive] lemma prod_mul_prod_compl [fintype α] [decidable_eq α] (s : finset α) (f : α → β) : (∏ i in s, f i) * (∏ i in sᶜ, f i) = ∏ i, f i := is_compl_compl.prod_mul_prod f @[to_additive] lemma prod_compl_mul_prod [fintype α] [decidable_eq α] (s : finset α) (f : α → β) : (∏ i in sᶜ, f i) * (∏ i in s, f i) = ∏ i, f i := is_compl_compl.symm.prod_mul_prod f @[to_additive] lemma prod_sdiff [decidable_eq α] (h : s₁ ⊆ s₂) : (∏ x in (s₂ \ s₁), f x) * (∏ x in s₁, f x) = (∏ x in s₂, f x) := by rw [←prod_union sdiff_disjoint, sdiff_union_of_subset h] @[simp, to_additive] lemma prod_sum_elim [decidable_eq (α ⊕ γ)] (s : finset α) (t : finset γ) (f : α → β) (g : γ → β) : ∏ x in s.map function.embedding.inl ∪ t.map function.embedding.inr, sum.elim f g x = (∏ x in s, f x) * (∏ x in t, g x) := begin rw [prod_union, prod_map, prod_map], { simp only [sum.elim_inl, function.embedding.inl_apply, function.embedding.inr_apply, sum.elim_inr] }, { simp only [disjoint_left, finset.mem_map, finset.mem_map], rintros _ ⟨i, hi, rfl⟩ ⟨j, hj, H⟩, cases H } end @[to_additive] lemma prod_bUnion [decidable_eq α] {s : finset γ} {t : γ → finset α} : (∀ x ∈ s, ∀ y ∈ s, x ≠ y → disjoint (t x) (t y)) → (∏ x in (s.bUnion t), f x) = ∏ x in s, ∏ i in t x, f i := by haveI := classical.dec_eq γ; exact finset.induction_on s (λ _, by simp only [bUnion_empty, prod_empty]) (assume x s hxs ih hd, have hd' : ∀x∈s, ∀y∈s, x ≠ y → disjoint (t x) (t y), from assume _ hx _ hy, hd _ (mem_insert_of_mem hx) _ (mem_insert_of_mem hy), have ∀y∈s, x ≠ y, from assume _ hy h, by rw [←h] at hy; contradiction, have ∀y∈s, disjoint (t x) (t y), from assume _ hy, hd _ (mem_insert_self _ _) _ (mem_insert_of_mem hy) (this _ hy), have disjoint (t x) (finset.bUnion s t), from (disjoint_bUnion_right _ _ _).mpr this, by simp only [bUnion_insert, prod_insert hxs, prod_union this, ih hd']) @[to_additive] lemma prod_product {s : finset γ} {t : finset α} {f : γ×α → β} : (∏ x in s.product t, f x) = ∏ x in s, ∏ y in t, f (x, y) := begin haveI := classical.dec_eq α, haveI := classical.dec_eq γ, rw [product_eq_bUnion, prod_bUnion], { congr, funext, exact prod_image (λ _ _ _ _ H, (prod.mk.inj H).2) }, simp only [disjoint_iff_ne, mem_image], rintros _ _ _ _ h ⟨_, _⟩ ⟨_, _, ⟨_, _⟩⟩ ⟨_, _⟩ ⟨_, _, ⟨_, _⟩⟩ _, apply h, cc end /-- An uncurried version of `finset.prod_product`. -/ @[to_additive "An uncurried version of `finset.sum_product`"] lemma prod_product' {s : finset γ} {t : finset α} {f : γ → α → β} : (∏ x in s.product t, f x.1 x.2) = ∏ x in s, ∏ y in t, f x y := prod_product /-- Product over a sigma type equals the product of fiberwise products. For rewriting in the reverse direction, use `finset.prod_sigma'`. -/ @[to_additive "Sum over a sigma type equals the sum of fiberwise sums. For rewriting in the reverse direction, use `finset.sum_sigma'`"] lemma prod_sigma {σ : α → Type*} (s : finset α) (t : Πa, finset (σ a)) (f : sigma σ → β) : (∏ x in s.sigma t, f x) = ∏ a in s, ∏ s in (t a), f ⟨a, s⟩ := by classical; calc (∏ x in s.sigma t, f x) = ∏ x in s.bUnion (λa, (t a).map (function.embedding.sigma_mk a)), f x : by rw sigma_eq_bUnion ... = ∏ a in s, ∏ x in (t a).map (function.embedding.sigma_mk a), f x : prod_bUnion $ assume a₁ ha a₂ ha₂ h x hx, by { simp only [inf_eq_inter, mem_inter, mem_map, function.embedding.sigma_mk_apply] at hx, rcases hx with ⟨⟨y, hy, rfl⟩, ⟨z, hz, hz'⟩⟩, cc } ... = ∏ a in s, ∏ s in t a, f ⟨a, s⟩ : prod_congr rfl $ λ _ _, prod_map _ _ _ @[to_additive] lemma prod_sigma' {σ : α → Type*} (s : finset α) (t : Πa, finset (σ a)) (f : Πa, σ a → β) : (∏ a in s, ∏ s in (t a), f a s) = ∏ x in s.sigma t, f x.1 x.2 := eq.symm $ prod_sigma s t (λ x, f x.1 x.2) @[to_additive] lemma prod_fiberwise_of_maps_to [decidable_eq γ] {s : finset α} {t : finset γ} {g : α → γ} (h : ∀ x ∈ s, g x ∈ t) (f : α → β) : (∏ y in t, ∏ x in s.filter (λ x, g x = y), f x) = ∏ x in s, f x := begin letI := classical.dec_eq α, rw [← bUnion_filter_eq_of_maps_to h] {occs := occurrences.pos [2]}, refine (prod_bUnion $ λ x' hx y' hy hne, _).symm, rw [disjoint_filter], rintros x hx rfl, exact hne end @[to_additive] lemma prod_image' [decidable_eq α] {s : finset γ} {g : γ → α} (h : γ → β) (eq : ∀c∈s, f (g c) = ∏ x in s.filter (λc', g c' = g c), h x) : (∏ x in s.image g, f x) = ∏ x in s, h x := calc (∏ x in s.image g, f x) = ∏ x in s.image g, ∏ x in s.filter (λ c', g c' = x), h x : prod_congr rfl $ λ x hx, let ⟨c, hcs, hc⟩ := mem_image.1 hx in hc ▸ (eq c hcs) ... = ∏ x in s, h x : prod_fiberwise_of_maps_to (λ x, mem_image_of_mem g) _ @[to_additive] lemma prod_mul_distrib : ∏ x in s, (f x * g x) = (∏ x in s, f x) * (∏ x in s, g x) := eq.trans (by rw one_mul; refl) fold_op_distrib @[to_additive] lemma prod_comm {s : finset γ} {t : finset α} {f : γ → α → β} : (∏ x in s, ∏ y in t, f x y) = (∏ y in t, ∏ x in s, f x y) := begin classical, apply finset.induction_on s, { simp only [prod_empty, prod_const_one] }, { intros _ _ H ih, simp only [prod_insert H, prod_mul_distrib, ih] } end @[to_additive] lemma prod_hom [comm_monoid γ] (s : finset α) {f : α → β} (g : β → γ) [is_monoid_hom g] : (∏ x in s, g (f x)) = g (∏ x in s, f x) := ((monoid_hom.of g).map_prod f s).symm @[to_additive] lemma prod_hom_rel [comm_monoid γ] {r : β → γ → Prop} {f : α → β} {g : α → γ} {s : finset α} (h₁ : r 1 1) (h₂ : ∀a b c, r b c → r (f a * b) (g a * c)) : r (∏ x in s, f x) (∏ x in s, g x) := by { delta finset.prod, apply multiset.prod_hom_rel; assumption } @[to_additive] lemma prod_subset (h : s₁ ⊆ s₂) (hf : ∀ x ∈ s₂, x ∉ s₁ → f x = 1) : (∏ x in s₁, f x) = ∏ x in s₂, f x := by haveI := classical.dec_eq α; exact have ∏ x in s₂ \ s₁, f x = ∏ x in s₂ \ s₁, 1, from prod_congr rfl $ by simpa only [mem_sdiff, and_imp], by rw [←prod_sdiff h]; simp only [this, prod_const_one, one_mul] @[to_additive] lemma prod_filter_of_ne {p : α → Prop} [decidable_pred p] (hp : ∀ x ∈ s, f x ≠ 1 → p x) : (∏ x in (s.filter p), f x) = (∏ x in s, f x) := prod_subset (filter_subset _ _) $ λ x, by { classical, rw [not_imp_comm, mem_filter], exact λ h₁ h₂, ⟨h₁, hp _ h₁ h₂⟩ } -- If we use `[decidable_eq β]` here, some rewrites fail because they find a wrong `decidable` -- instance first; `{∀x, decidable (f x ≠ 1)}` doesn't work with `rw ← prod_filter_ne_one` @[to_additive] lemma prod_filter_ne_one [∀ x, decidable (f x ≠ 1)] : (∏ x in (s.filter $ λx, f x ≠ 1), f x) = (∏ x in s, f x) := prod_filter_of_ne $ λ _ _, id @[to_additive] lemma prod_filter (p : α → Prop) [decidable_pred p] (f : α → β) : (∏ a in s.filter p, f a) = (∏ a in s, if p a then f a else 1) := calc (∏ a in s.filter p, f a) = ∏ a in s.filter p, if p a then f a else 1 : prod_congr rfl (assume a h, by rw [if_pos (mem_filter.1 h).2]) ... = ∏ a in s, if p a then f a else 1 : begin refine prod_subset (filter_subset _ s) (assume x hs h, _), rw [mem_filter, not_and] at h, exact if_neg (h hs) end @[to_additive] lemma prod_eq_single_of_mem {s : finset α} {f : α → β} (a : α) (h : a ∈ s) (h₀ : ∀ b ∈ s, b ≠ a → f b = 1) : (∏ x in s, f x) = f a := begin haveI := classical.dec_eq α, calc (∏ x in s, f x) = ∏ x in {a}, f x : begin refine (prod_subset _ _).symm, { intros _ H, rwa mem_singleton.1 H }, { simpa only [mem_singleton] } end ... = f a : prod_singleton end @[to_additive] lemma prod_eq_single {s : finset α} {f : α → β} (a : α) (h₀ : ∀b∈s, b ≠ a → f b = 1) (h₁ : a ∉ s → f a = 1) : (∏ x in s, f x) = f a := by haveI := classical.dec_eq α; from classical.by_cases (assume : a ∈ s, prod_eq_single_of_mem a this h₀) (assume : a ∉ s, (prod_congr rfl $ λ b hb, h₀ b hb $ by rintro rfl; cc).trans $ prod_const_one.trans (h₁ this).symm) @[to_additive] lemma prod_eq_mul_of_mem {s : finset α} {f : α → β} (a b : α) (ha : a ∈ s) (hb : b ∈ s) (hn : a ≠ b) (h₀ : ∀ c ∈ s, c ≠ a ∧ c ≠ b → f c = 1) : (∏ x in s, f x) = (f a) * (f b) := begin haveI := classical.dec_eq α; let s' := ({a, b} : finset α), have hu : s' ⊆ s, { refine insert_subset.mpr _, apply and.intro ha, apply singleton_subset_iff.mpr hb }, have hf : ∀ c ∈ s, c ∉ s' → f c = 1, { intros c hc hcs, apply h₀ c hc, apply not_or_distrib.mp, intro hab, apply hcs, apply mem_insert.mpr, rw mem_singleton, exact hab }, rw ←prod_subset hu hf, exact finset.prod_pair hn end @[to_additive] lemma prod_eq_mul {s : finset α} {f : α → β} (a b : α) (hn : a ≠ b) (h₀ : ∀ c ∈ s, c ≠ a ∧ c ≠ b → f c = 1) (ha : a ∉ s → f a = 1) (hb : b ∉ s → f b = 1) : (∏ x in s, f x) = (f a) * (f b) := begin haveI := classical.dec_eq α; by_cases h₁ : a ∈ s; by_cases h₂ : b ∈ s, { exact prod_eq_mul_of_mem a b h₁ h₂ hn h₀ }, { rw [hb h₂, mul_one], apply prod_eq_single_of_mem a h₁, exact λ c hc hca, h₀ c hc ⟨hca, ne_of_mem_of_not_mem hc h₂⟩ }, { rw [ha h₁, one_mul], apply prod_eq_single_of_mem b h₂, exact λ c hc hcb, h₀ c hc ⟨ne_of_mem_of_not_mem hc h₁, hcb⟩ }, { rw [ha h₁, hb h₂, mul_one], exact trans (prod_congr rfl (λ c hc, h₀ c hc ⟨ne_of_mem_of_not_mem hc h₁, ne_of_mem_of_not_mem hc h₂⟩)) prod_const_one } end @[to_additive] lemma prod_attach {f : α → β} : (∏ x in s.attach, f x) = (∏ x in s, f x) := by haveI := classical.dec_eq α; exact calc (∏ x in s.attach, f x.val) = (∏ x in (s.attach).image subtype.val, f x) : by rw [prod_image]; exact assume x _ y _, subtype.eq ... = _ : by rw [attach_image_val] /-- A product over `s.subtype p` equals one over `s.filter p`. -/ @[simp, to_additive "A sum over `s.subtype p` equals one over `s.filter p`."] lemma prod_subtype_eq_prod_filter (f : α → β) {p : α → Prop} [decidable_pred p] : ∏ x in s.subtype p, f x = ∏ x in s.filter p, f x := begin conv_lhs { erw ←prod_map (s.subtype p) (function.embedding.subtype _) f }, exact prod_congr (subtype_map _) (λ x hx, rfl) end /-- If all elements of a `finset` satisfy the predicate `p`, a product over `s.subtype p` equals that product over `s`. -/ @[to_additive "If all elements of a `finset` satisfy the predicate `p`, a sum over `s.subtype p` equals that sum over `s`."] lemma prod_subtype_of_mem (f : α → β) {p : α → Prop} [decidable_pred p] (h : ∀ x ∈ s, p x) : ∏ x in s.subtype p, f x = ∏ x in s, f x := by simp_rw [prod_subtype_eq_prod_filter, filter_true_of_mem h] /-- A product of a function over a `finset` in a subtype equals a product in the main type of a function that agrees with the first function on that `finset`. -/ @[to_additive "A sum of a function over a `finset` in a subtype equals a sum in the main type of a function that agrees with the first function on that `finset`."] lemma prod_subtype_map_embedding {p : α → Prop} {s : finset {x // p x}} {f : {x // p x} → β} {g : α → β} (h : ∀ x : {x // p x}, x ∈ s → g x = f x) : ∏ x in s.map (function.embedding.subtype _), g x = ∏ x in s, f x := begin rw finset.prod_map, exact finset.prod_congr rfl h end @[to_additive] lemma prod_finset_coe (f : α → β) (s : finset α) : ∏ (i : (s : set α)), f i = ∏ i in s, f i := prod_attach @[to_additive] lemma prod_subtype {p : α → Prop} {F : fintype (subtype p)} (s : finset α) (h : ∀ x, x ∈ s ↔ p x) (f : α → β) : ∏ a in s, f a = ∏ a : subtype p, f a := have (∈ s) = p, from set.ext h, by { substI p, rw [←prod_finset_coe], congr } @[to_additive] lemma prod_eq_one {f : α → β} {s : finset α} (h : ∀x∈s, f x = 1) : (∏ x in s, f x) = 1 := calc (∏ x in s, f x) = ∏ x in s, 1 : finset.prod_congr rfl h ... = 1 : finset.prod_const_one @[to_additive] lemma prod_apply_dite {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f : Π (x : α), p x → γ) (g : Π (x : α), ¬p x → γ) (h : γ → β) : (∏ x in s, h (if hx : p x then f x hx else g x hx)) = (∏ x in (s.filter p).attach, h (f x.1 (mem_filter.mp x.2).2)) * (∏ x in (s.filter (λ x, ¬ p x)).attach, h (g x.1 (mem_filter.mp x.2).2)) := by letI := classical.dec_eq α; exact calc ∏ x in s, h (if hx : p x then f x hx else g x hx) = ∏ x in s.filter p ∪ s.filter (λ x, ¬ p x), h (if hx : p x then f x hx else g x hx) : by rw [filter_union_filter_neg_eq] ... = (∏ x in s.filter p, h (if hx : p x then f x hx else g x hx)) * (∏ x in s.filter (λ x, ¬ p x), h (if hx : p x then f x hx else g x hx)) : prod_union (by simp [disjoint_right] {contextual := tt}) ... = (∏ x in (s.filter p).attach, h (if hx : p x.1 then f x.1 hx else g x.1 hx)) * (∏ x in (s.filter (λ x, ¬ p x)).attach, h (if hx : p x.1 then f x.1 hx else g x.1 hx)) : congr_arg2 _ prod_attach.symm prod_attach.symm ... = (∏ x in (s.filter p).attach, h (f x.1 (mem_filter.mp x.2).2)) * (∏ x in (s.filter (λ x, ¬ p x)).attach, h (g x.1 (mem_filter.mp x.2).2)) : congr_arg2 _ (prod_congr rfl (λ x hx, congr_arg h (dif_pos (mem_filter.mp x.2).2))) (prod_congr rfl (λ x hx, congr_arg h (dif_neg (mem_filter.mp x.2).2))) @[to_additive] lemma prod_apply_ite {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f g : α → γ) (h : γ → β) : (∏ x in s, h (if p x then f x else g x)) = (∏ x in s.filter p, h (f x)) * (∏ x in s.filter (λ x, ¬ p x), h (g x)) := trans (prod_apply_dite _ _ _) (congr_arg2 _ (@prod_attach _ _ _ _ (h ∘ f)) (@prod_attach _ _ _ _ (h ∘ g))) @[to_additive] lemma prod_dite {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f : Π (x : α), p x → β) (g : Π (x : α), ¬p x → β) : (∏ x in s, if hx : p x then f x hx else g x hx) = (∏ x in (s.filter p).attach, f x.1 (mem_filter.mp x.2).2) * (∏ x in (s.filter (λ x, ¬ p x)).attach, g x.1 (mem_filter.mp x.2).2) := by simp [prod_apply_dite _ _ (λ x, x)] @[to_additive] lemma prod_ite {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f g : α → β) : (∏ x in s, if p x then f x else g x) = (∏ x in s.filter p, f x) * (∏ x in s.filter (λ x, ¬ p x), g x) := by simp [prod_apply_ite _ _ (λ x, x)] @[to_additive] lemma prod_ite_of_false {p : α → Prop} {hp : decidable_pred p} (f g : α → β) (h : ∀ x ∈ s, ¬p x) : (∏ x in s, if p x then f x else g x) = (∏ x in s, g x) := by { rw prod_ite, simp [filter_false_of_mem h, filter_true_of_mem h] } @[to_additive] lemma prod_ite_of_true {p : α → Prop} {hp : decidable_pred p} (f g : α → β) (h : ∀ x ∈ s, p x) : (∏ x in s, if p x then f x else g x) = (∏ x in s, f x) := by { simp_rw ←(ite_not (p _)), apply prod_ite_of_false, simpa } @[to_additive] lemma prod_apply_ite_of_false {p : α → Prop} {hp : decidable_pred p} (f g : α → γ) (k : γ → β) (h : ∀ x ∈ s, ¬p x) : (∏ x in s, k (if p x then f x else g x)) = (∏ x in s, k (g x)) := by { simp_rw apply_ite k, exact prod_ite_of_false _ _ h } @[to_additive] lemma prod_apply_ite_of_true {p : α → Prop} {hp : decidable_pred p} (f g : α → γ) (k : γ → β) (h : ∀ x ∈ s, p x) : (∏ x in s, k (if p x then f x else g x)) = (∏ x in s, k (f x)) := by { simp_rw apply_ite k, exact prod_ite_of_true _ _ h } @[to_additive] lemma prod_extend_by_one [decidable_eq α] (s : finset α) (f : α → β) : ∏ i in s, (if i ∈ s then f i else 1) = ∏ i in s, f i := prod_congr rfl $ λ i hi, if_pos hi @[simp, to_additive] lemma prod_dite_eq [decidable_eq α] (s : finset α) (a : α) (b : Π x : α, a = x → β) : (∏ x in s, (if h : a = x then b x h else 1)) = ite (a ∈ s) (b a rfl) 1 := begin split_ifs with h, { rw [finset.prod_eq_single a, dif_pos rfl], { intros, rw dif_neg, cc }, { cc } }, { rw finset.prod_eq_one, intros, rw dif_neg, intro, cc } end @[simp, to_additive] lemma prod_dite_eq' [decidable_eq α] (s : finset α) (a : α) (b : Π x : α, x = a → β) : (∏ x in s, (if h : x = a then b x h else 1)) = ite (a ∈ s) (b a rfl) 1 := begin split_ifs with h, { rw [finset.prod_eq_single a, dif_pos rfl], { intros, rw dif_neg, cc }, { cc } }, { rw finset.prod_eq_one, intros, rw dif_neg, intro, cc } end @[simp, to_additive] lemma prod_ite_eq [decidable_eq α] (s : finset α) (a : α) (b : α → β) : (∏ x in s, (ite (a = x) (b x) 1)) = ite (a ∈ s) (b a) 1 := prod_dite_eq s a (λ x _, b x) /-- When a product is taken over a conditional whose condition is an equality test on the index and whose alternative is 1, then the product's value is either the term at that index or `1`. The difference with `prod_ite_eq` is that the arguments to `eq` are swapped. -/ @[simp, to_additive] lemma prod_ite_eq' [decidable_eq α] (s : finset α) (a : α) (b : α → β) : (∏ x in s, (ite (x = a) (b x) 1)) = ite (a ∈ s) (b a) 1 := prod_dite_eq' s a (λ x _, b x) @[to_additive] lemma prod_ite_index (p : Prop) [decidable p] (s t : finset α) (f : α → β) : (∏ x in if p then s else t, f x) = if p then ∏ x in s, f x else ∏ x in t, f x := apply_ite (λ s, ∏ x in s, f x) _ _ _ @[simp, to_additive] lemma prod_dite_irrel (p : Prop) [decidable p] (s : finset α) (f : p → α → β) (g : ¬p → α → β): (∏ x in s, if h : p then f h x else g h x) = if h : p then ∏ x in s, f h x else ∏ x in s, g h x := by { split_ifs with h; refl } @[simp] lemma sum_pi_single' {ι M : Type*} [decidable_eq ι] [add_comm_monoid M] (i : ι) (x : M) (s : finset ι) : ∑ j in s, pi.single i x j = if i ∈ s then x else 0 := sum_dite_eq' _ _ _ @[simp] lemma sum_pi_single {ι : Type*} {M : ι → Type*} [decidable_eq ι] [Π i, add_comm_monoid (M i)] (i : ι) (f : Π i, M i) (s : finset ι) : ∑ j in s, pi.single j (f j) i = if i ∈ s then f i else 0 := sum_dite_eq _ _ _ /-- Reorder a product. The difference with `prod_bij'` is that the bijection is specified as a surjective injection, rather than by an inverse function. -/ @[to_additive " Reorder a sum. The difference with `sum_bij'` is that the bijection is specified as a surjective injection, rather than by an inverse function. "] lemma prod_bij {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Πa∈s, γ) (hi : ∀a ha, i a ha ∈ t) (h : ∀a ha, f a = g (i a ha)) (i_inj : ∀a₁ a₂ ha₁ ha₂, i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂) (i_surj : ∀b∈t, ∃a ha, b = i a ha) : (∏ x in s, f x) = (∏ x in t, g x) := congr_arg multiset.prod (multiset.map_eq_map_of_bij_of_nodup f g s.2 t.2 i hi h i_inj i_surj) /-- Reorder a product. The difference with `prod_bij` is that the bijection is specified with an inverse, rather than as a surjective injection. -/ @[to_additive " Reorder a sum. The difference with `sum_bij` is that the bijection is specified with an inverse, rather than as a surjective injection. "] lemma prod_bij' {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Πa∈s, γ) (hi : ∀a ha, i a ha ∈ t) (h : ∀a ha, f a = g (i a ha)) (j : Πa∈t, α) (hj : ∀a ha, j a ha ∈ s) (left_inv : ∀ a ha, j (i a ha) (hi a ha) = a) (right_inv : ∀ a ha, i (j a ha) (hj a ha) = a) : (∏ x in s, f x) = (∏ x in t, g x) := begin refine prod_bij i hi h _ _, {intros a1 a2 h1 h2 eq, rw [←left_inv a1 h1, ←left_inv a2 h2], cc,}, {intros b hb, use j b hb, use hj b hb, exact (right_inv b hb).symm,}, end @[to_additive] lemma prod_bij_ne_one {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Πa∈s, f a ≠ 1 → γ) (hi : ∀a h₁ h₂, i a h₁ h₂ ∈ t) (i_inj : ∀a₁ a₂ h₁₁ h₁₂ h₂₁ h₂₂, i a₁ h₁₁ h₁₂ = i a₂ h₂₁ h₂₂ → a₁ = a₂) (i_surj : ∀b∈t, g b ≠ 1 → ∃a h₁ h₂, b = i a h₁ h₂) (h : ∀a h₁ h₂, f a = g (i a h₁ h₂)) : (∏ x in s, f x) = (∏ x in t, g x) := by classical; exact calc (∏ x in s, f x) = ∏ x in (s.filter $ λx, f x ≠ 1), f x : prod_filter_ne_one.symm ... = ∏ x in (t.filter $ λx, g x ≠ 1), g x : prod_bij (assume a ha, i a (mem_filter.mp ha).1 (mem_filter.mp ha).2) (assume a ha, (mem_filter.mp ha).elim $ λh₁ h₂, mem_filter.mpr ⟨hi a h₁ h₂, λ hg, h₂ (hg ▸ h a h₁ h₂)⟩) (assume a ha, (mem_filter.mp ha).elim $ h a) (assume a₁ a₂ ha₁ ha₂, (mem_filter.mp ha₁).elim $ λ ha₁₁ ha₁₂, (mem_filter.mp ha₂).elim $ λ ha₂₁ ha₂₂, i_inj a₁ a₂ _ _ _ _) (assume b hb, (mem_filter.mp hb).elim $ λh₁ h₂, let ⟨a, ha₁, ha₂, eq⟩ := i_surj b h₁ h₂ in ⟨a, mem_filter.mpr ⟨ha₁, ha₂⟩, eq⟩) ... = (∏ x in t, g x) : prod_filter_ne_one @[to_additive] lemma nonempty_of_prod_ne_one (h : (∏ x in s, f x) ≠ 1) : s.nonempty := s.eq_empty_or_nonempty.elim (λ H, false.elim $ h $ H.symm ▸ prod_empty) id @[to_additive] lemma exists_ne_one_of_prod_ne_one (h : (∏ x in s, f x) ≠ 1) : ∃a∈s, f a ≠ 1 := begin classical, rw ← prod_filter_ne_one at h, rcases nonempty_of_prod_ne_one h with ⟨x, hx⟩, exact ⟨x, (mem_filter.1 hx).1, (mem_filter.1 hx).2⟩ end @[to_additive] lemma prod_subset_one_on_sdiff [decidable_eq α] (h : s₁ ⊆ s₂) (hg : ∀ x ∈ (s₂ \ s₁), g x = 1) (hfg : ∀ x ∈ s₁, f x = g x) : ∏ i in s₁, f i = ∏ i in s₂, g i := begin rw [← prod_sdiff h, prod_eq_one hg, one_mul], exact prod_congr rfl hfg end lemma sum_range_succ_comm {β} [add_comm_monoid β] (f : ℕ → β) (n : ℕ) : ∑ x in range (n + 1), f x = f n + ∑ x in range n, f x := by rw [range_succ, sum_insert not_mem_range_self] lemma sum_range_succ {β} [add_comm_monoid β] (f : ℕ → β) (n : ℕ) : ∑ x in range (n + 1), f x = ∑ x in range n, f x + f n := by simp only [add_comm, sum_range_succ_comm] @[to_additive] lemma prod_range_succ_comm (f : ℕ → β) (n : ℕ) : ∏ x in range (n + 1), f x = f n * ∏ x in range n, f x := by rw [range_succ, prod_insert not_mem_range_self] @[to_additive] lemma prod_range_succ (f : ℕ → β) (n : ℕ) : ∏ x in range (n + 1), f x = (∏ x in range n, f x) * f n := by simp only [mul_comm, prod_range_succ_comm] lemma prod_range_succ' (f : ℕ → β) : ∀ n : ℕ, (∏ k in range (n + 1), f k) = (∏ k in range n, f (k+1)) * f 0 | 0 := prod_range_succ _ _ | (n + 1) := by rw [prod_range_succ _ n, mul_right_comm, ← prod_range_succ', prod_range_succ] lemma prod_range_add (f : ℕ → β) (n m : ℕ) : ∏ x in range (n + m), f x = (∏ x in range n, f x) * (∏ x in range m, f (n + x)) := begin induction m with m hm, { simp }, { rw [nat.add_succ, prod_range_succ, hm, prod_range_succ, mul_assoc], }, end @[to_additive] lemma prod_range_zero (f : ℕ → β) : ∏ k in range 0, f k = 1 := by rw [range_zero, prod_empty] lemma prod_range_one (f : ℕ → β) : ∏ k in range 1, f k = f 0 := by { rw [range_one], apply @prod_singleton ℕ β 0 f } lemma sum_range_one {δ : Type*} [add_comm_monoid δ] (f : ℕ → δ) : ∑ k in range 1, f k = f 0 := @prod_range_one (multiplicative δ) _ f attribute [to_additive finset.sum_range_one] prod_range_one open multiset lemma prod_multiset_map_count [decidable_eq α] (s : multiset α) {M : Type*} [comm_monoid M] (f : α → M) : (s.map f).prod = ∏ m in s.to_finset, (f m) ^ (s.count m) := begin apply s.induction_on, { simp only [prod_const_one, count_zero, prod_zero, pow_zero, map_zero] }, intros a s ih, simp only [prod_cons, map_cons, to_finset_cons, ih], by_cases has : a ∈ s.to_finset, { rw [insert_eq_of_mem has, ← insert_erase has, prod_insert (not_mem_erase _ _), prod_insert (not_mem_erase _ _), ← mul_assoc, count_cons_self, pow_succ], congr' 1, refine prod_congr rfl (λ x hx, _), rw [count_cons_of_ne (ne_of_mem_erase hx)] }, rw [prod_insert has, count_cons_self, count_eq_zero_of_not_mem (mt mem_to_finset.2 has), pow_one], congr' 1, refine prod_congr rfl (λ x hx, _), rw count_cons_of_ne, rintro rfl, exact has hx end lemma sum_multiset_map_count [decidable_eq α] (s : multiset α) {M : Type*} [add_comm_monoid M] (f : α → M) : (s.map f).sum = ∑ m in s.to_finset, s.count m • f m := @prod_multiset_map_count _ _ _ (multiplicative M) _ f attribute [to_additive] prod_multiset_map_count lemma prod_multiset_count [decidable_eq α] [comm_monoid α] (s : multiset α) : s.prod = ∏ m in s.to_finset, m ^ (s.count m) := by { convert prod_multiset_map_count s id, rw map_id } lemma sum_multiset_count [decidable_eq α] [add_comm_monoid α] (s : multiset α) : s.sum = ∑ m in s.to_finset, s.count m • m := @prod_multiset_count (multiplicative α) _ _ s attribute [to_additive] prod_multiset_count /-- To prove a property of a product, it suffices to prove that the property is multiplicative and holds on factors. -/ @[to_additive "To prove a property of a sum, it suffices to prove that the property is additive and holds on summands."] lemma prod_induction {M : Type*} [comm_monoid M] (f : α → M) (p : M → Prop) (p_mul : ∀ a b, p a → p b → p (a * b)) (p_one : p 1) (p_s : ∀ x ∈ s, p $ f x) : p $ ∏ x in s, f x := multiset.prod_induction _ _ p_mul p_one (multiset.forall_mem_map_iff.mpr p_s) /-- To prove a property of a product, it suffices to prove that the property is multiplicative and holds on factors. -/ @[to_additive "To prove a property of a sum, it suffices to prove that the property is additive and holds on summands."] lemma prod_induction_nonempty {M : Type*} [comm_monoid M] (f : α → M) (p : M → Prop) (p_mul : ∀ a b, p a → p b → p (a * b)) (hs_nonempty : s.nonempty) (p_s : ∀ x ∈ s, p $ f x) : p $ ∏ x in s, f x := multiset.prod_induction_nonempty p p_mul (by simp [nonempty_iff_ne_empty.mp hs_nonempty]) (multiset.forall_mem_map_iff.mpr p_s) /-- For any product along `{0, ..., n-1}` of a commutative-monoid-valued function, we can verify that it's equal to a different function just by checking ratios of adjacent terms. This is a multiplicative discrete analogue of the fundamental theorem of calculus. -/ lemma prod_range_induction {M : Type*} [comm_monoid M] (f s : ℕ → M) (h0 : s 0 = 1) (h : ∀ n, s (n + 1) = s n * f n) (n : ℕ) : ∏ k in finset.range n, f k = s n := begin induction n with k hk, { simp only [h0, finset.prod_range_zero] }, { simp only [hk, finset.prod_range_succ, h, mul_comm] } end /-- For any sum along `{0, ..., n-1}` of a commutative-monoid-valued function, we can verify that it's equal to a different function just by checking differences of adjacent terms. This is a discrete analogue of the fundamental theorem of calculus. -/ lemma sum_range_induction {M : Type*} [add_comm_monoid M] (f s : ℕ → M) (h0 : s 0 = 0) (h : ∀ n, s (n + 1) = s n + f n) (n : ℕ) : ∑ k in finset.range n, f k = s n := @prod_range_induction (multiplicative M) _ f s h0 h n /-- A telescoping sum along `{0, ..., n-1}` of an additive commutative group valued function reduces to the difference of the last and first terms.-/ lemma sum_range_sub {G : Type*} [add_comm_group G] (f : ℕ → G) (n : ℕ) : ∑ i in range n, (f (i+1) - f i) = f n - f 0 := by { apply sum_range_induction; abel, simp } lemma sum_range_sub' {G : Type*} [add_comm_group G] (f : ℕ → G) (n : ℕ) : ∑ i in range n, (f i - f (i+1)) = f 0 - f n := by { apply sum_range_induction; abel, simp } /-- A telescoping product along `{0, ..., n-1}` of a commutative group valued function reduces to the ratio of the last and first factors.-/ @[to_additive] lemma prod_range_div {M : Type*} [comm_group M] (f : ℕ → M) (n : ℕ) : ∏ i in range n, (f (i+1) * (f i)⁻¹) = f n * (f 0)⁻¹ := by simpa only [← div_eq_mul_inv] using @sum_range_sub (additive M) _ f n @[to_additive] lemma prod_range_div' {M : Type*} [comm_group M] (f : ℕ → M) (n : ℕ) : ∏ i in range n, (f i * (f (i+1))⁻¹) = (f 0) * (f n)⁻¹ := by simpa only [← div_eq_mul_inv] using @sum_range_sub' (additive M) _ f n /-- A telescoping sum along `{0, ..., n-1}` of an `ℕ`-valued function reduces to the difference of the last and first terms when the function we are summing is monotone. -/ lemma sum_range_sub_of_monotone {f : ℕ → ℕ} (h : monotone f) (n : ℕ) : ∑ i in range n, (f (i+1) - f i) = f n - f 0 := begin refine sum_range_induction _ _ (nat.sub_self _) (λ n, _) _, have h₁ : f n ≤ f (n+1) := h (nat.le_succ _), have h₂ : f 0 ≤ f n := h (nat.zero_le _), rw [←nat.sub_add_comm h₂, nat.add_sub_cancel' h₁], end @[simp] lemma prod_const (b : β) : (∏ x in s, b) = b ^ s.card := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (λ a s has ih, by rw [prod_insert has, card_insert_of_not_mem has, pow_succ, ih]) lemma pow_eq_prod_const (b : β) : ∀ n, b ^ n = ∏ k in range n, b | 0 := by simp | (n+1) := by simp lemma prod_pow (s : finset α) (n : ℕ) (f : α → β) : ∏ x in s, f x ^ n = (∏ x in s, f x) ^ n := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (by simp [mul_pow] {contextual := tt}) -- `to_additive` fails on this lemma, so we prove it manually below lemma prod_flip {n : ℕ} (f : ℕ → β) : ∏ r in range (n + 1), f (n - r) = ∏ k in range (n + 1), f k := begin induction n with n ih, { rw [prod_range_one, prod_range_one] }, { rw [prod_range_succ', prod_range_succ _ (nat.succ n)], simp [← ih] } end @[to_additive] lemma prod_involution {s : finset α} {f : α → β} : ∀ (g : Π a ∈ s, α) (h : ∀ a ha, f a * f (g a ha) = 1) (g_ne : ∀ a ha, f a ≠ 1 → g a ha ≠ a) (g_mem : ∀ a ha, g a ha ∈ s) (g_inv : ∀ a ha, g (g a ha) (g_mem a ha) = a), (∏ x in s, f x) = 1 := by haveI := classical.dec_eq α; haveI := classical.dec_eq β; exact finset.strong_induction_on s (λ s ih g h g_ne g_mem g_inv, s.eq_empty_or_nonempty.elim (λ hs, hs.symm ▸ rfl) (λ ⟨x, hx⟩, have hmem : ∀ y ∈ (s.erase x).erase (g x hx), y ∈ s, from λ y hy, (mem_of_mem_erase (mem_of_mem_erase hy)), have g_inj : ∀ {x hx y hy}, g x hx = g y hy → x = y, from λ x hx y hy h, by rw [← g_inv x hx, ← g_inv y hy]; simp [h], have ih': ∏ y in erase (erase s x) (g x hx), f y = (1 : β) := ih ((s.erase x).erase (g x hx)) ⟨subset.trans (erase_subset _ _) (erase_subset _ _), λ h, not_mem_erase (g x hx) (s.erase x) (h (g_mem x hx))⟩ (λ y hy, g y (hmem y hy)) (λ y hy, h y (hmem y hy)) (λ y hy, g_ne y (hmem y hy)) (λ y hy, mem_erase.2 ⟨λ (h : g y _ = g x hx), by simpa [g_inj h] using hy, mem_erase.2 ⟨λ (h : g y _ = x), have y = g x hx, from g_inv y (hmem y hy) ▸ by simp [h], by simpa [this] using hy, g_mem y (hmem y hy)⟩⟩) (λ y hy, g_inv y (hmem y hy)), if hx1 : f x = 1 then ih' ▸ eq.symm (prod_subset hmem (λ y hy hy₁, have y = x ∨ y = g x hx, by simp [hy] at hy₁; tauto, this.elim (λ hy, hy.symm ▸ hx1) (λ hy, h x hx ▸ hy ▸ hx1.symm ▸ (one_mul _).symm))) else by rw [← insert_erase hx, prod_insert (not_mem_erase _ _), ← insert_erase (mem_erase.2 ⟨g_ne x hx hx1, g_mem x hx⟩), prod_insert (not_mem_erase _ _), ih', mul_one, h x hx])) /-- The product of the composition of functions `f` and `g`, is the product over `b ∈ s.image g` of `f b` to the power of the cardinality of the fibre of `b` -/ lemma prod_comp [decidable_eq γ] {s : finset α} (f : γ → β) (g : α → γ) : ∏ a in s, f (g a) = ∏ b in s.image g, f b ^ (s.filter (λ a, g a = b)).card := calc ∏ a in s, f (g a) = ∏ x in (s.image g).sigma (λ b : γ, s.filter (λ a, g a = b)), f (g x.2) : prod_bij (λ a ha, ⟨g a, a⟩) (by simp; tauto) (λ _ _, rfl) (by simp) (by finish) ... = ∏ b in s.image g, ∏ a in s.filter (λ a, g a = b), f (g a) : prod_sigma _ _ _ ... = ∏ b in s.image g, ∏ a in s.filter (λ a, g a = b), f b : prod_congr rfl (λ b hb, prod_congr rfl (by simp {contextual := tt})) ... = ∏ b in s.image g, f b ^ (s.filter (λ a, g a = b)).card : prod_congr rfl (λ _ _, prod_const _) @[to_additive] lemma prod_piecewise [decidable_eq α] (s t : finset α) (f g : α → β) : (∏ x in s, (t.piecewise f g) x) = (∏ x in s ∩ t, f x) * (∏ x in s \ t, g x) := by { rw [piecewise, prod_ite, filter_mem_eq_inter, ← sdiff_eq_filter], } @[to_additive] lemma prod_inter_mul_prod_diff [decidable_eq α] (s t : finset α) (f : α → β) : (∏ x in s ∩ t, f x) * (∏ x in s \ t, f x) = (∏ x in s, f x) := by { convert (s.prod_piecewise t f f).symm, simp [finset.piecewise] } @[to_additive] lemma prod_eq_mul_prod_diff_singleton [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s) (f : α → β) : ∏ x in s, f x = f i * ∏ x in s \ {i}, f x := by { convert (s.prod_inter_mul_prod_diff {i} f).symm, simp [h] } @[to_additive] lemma prod_eq_prod_diff_singleton_mul [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s) (f : α → β) : ∏ x in s, f x = (∏ x in s \ {i}, f x) * f i := by { rw [prod_eq_mul_prod_diff_singleton h, mul_comm] } @[to_additive] lemma _root_.fintype.prod_eq_mul_prod_compl [decidable_eq α] [fintype α] (a : α) (f : α → β) : ∏ i, f i = (f a) * ∏ i in {a}ᶜ, f i := prod_eq_mul_prod_diff_singleton (mem_univ a) f @[to_additive] lemma _root_.fintype.prod_eq_prod_compl_mul [decidable_eq α] [fintype α] (a : α) (f : α → β) : ∏ i, f i = (∏ i in {a}ᶜ, f i) * f a := prod_eq_prod_diff_singleton_mul (mem_univ a) f /-- A product can be partitioned into a product of products, each equivalent under a setoid. -/ @[to_additive "A sum can be partitioned into a sum of sums, each equivalent under a setoid."] lemma prod_partition (R : setoid α) [decidable_rel R.r] : (∏ x in s, f x) = ∏ xbar in s.image quotient.mk, ∏ y in s.filter (λ y, ⟦y⟧ = xbar), f y := begin refine (finset.prod_image' f (λ x hx, _)).symm, refl, end /-- If we can partition a product into subsets that cancel out, then the whole product cancels. -/ @[to_additive "If we can partition a sum into subsets that cancel out, then the whole sum cancels."] lemma prod_cancels_of_partition_cancels (R : setoid α) [decidable_rel R.r] (h : ∀ x ∈ s, (∏ a in s.filter (λ y, y ≈ x), f a) = 1) : (∏ x in s, f x) = 1 := begin rw [prod_partition R, ←finset.prod_eq_one], intros xbar xbar_in_s, obtain ⟨x, x_in_s, xbar_eq_x⟩ := mem_image.mp xbar_in_s, rw [←xbar_eq_x, filter_congr (λ y _, @quotient.eq _ R y x)], apply h x x_in_s, end @[to_additive] lemma prod_update_of_not_mem [decidable_eq α] {s : finset α} {i : α} (h : i ∉ s) (f : α → β) (b : β) : (∏ x in s, function.update f i b x) = (∏ x in s, f x) := begin apply prod_congr rfl (λj hj, _), have : j ≠ i, by { assume eq, rw eq at hj, exact h hj }, simp [this] end lemma prod_update_of_mem [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s) (f : α → β) (b : β) : (∏ x in s, function.update f i b x) = b * (∏ x in s \ (singleton i), f x) := by { rw [update_eq_piecewise, prod_piecewise], simp [h] } /-- If a product of a `finset` of size at most 1 has a given value, so do the terms in that product. -/ lemma eq_of_card_le_one_of_prod_eq {s : finset α} (hc : s.card ≤ 1) {f : α → β} {b : β} (h : ∏ x in s, f x = b) : ∀ x ∈ s, f x = b := begin intros x hx, by_cases hc0 : s.card = 0, { exact false.elim (card_ne_zero_of_mem hx hc0) }, { have h1 : s.card = 1 := le_antisymm hc (nat.one_le_of_lt (nat.pos_of_ne_zero hc0)), rw card_eq_one at h1, cases h1 with x2 hx2, rw [hx2, mem_singleton] at hx, simp_rw hx2 at h, rw hx, rw prod_singleton at h, exact h } end /-- If a sum of a `finset` of size at most 1 has a given value, so do the terms in that sum. -/ lemma eq_of_card_le_one_of_sum_eq [add_comm_monoid γ] {s : finset α} (hc : s.card ≤ 1) {f : α → γ} {b : γ} (h : ∑ x in s, f x = b) : ∀ x ∈ s, f x = b := begin intros x hx, by_cases hc0 : s.card = 0, { exact false.elim (card_ne_zero_of_mem hx hc0) }, { have h1 : s.card = 1 := le_antisymm hc (nat.one_le_of_lt (nat.pos_of_ne_zero hc0)), rw card_eq_one at h1, cases h1 with x2 hx2, rw [hx2, mem_singleton] at hx, simp_rw hx2 at h, rw hx, rw sum_singleton at h, exact h } end attribute [to_additive eq_of_card_le_one_of_sum_eq] eq_of_card_le_one_of_prod_eq /-- If a function applied at a point is 1, a product is unchanged by removing that point, if present, from a `finset`. -/ @[to_additive "If a function applied at a point is 0, a sum is unchanged by removing that point, if present, from a `finset`."] lemma prod_erase [decidable_eq α] (s : finset α) {f : α → β} {a : α} (h : f a = 1) : ∏ x in s.erase a, f x = ∏ x in s, f x := begin rw ←sdiff_singleton_eq_erase, refine prod_subset (sdiff_subset _ _) (λ x hx hnx, _), rw sdiff_singleton_eq_erase at hnx, rwa eq_of_mem_of_not_mem_erase hx hnx end /-- If a product is 1 and the function is 1 except possibly at one point, it is 1 everywhere on the `finset`. -/ @[to_additive "If a sum is 0 and the function is 0 except possibly at one point, it is 0 everywhere on the `finset`."] lemma eq_one_of_prod_eq_one {s : finset α} {f : α → β} {a : α} (hp : ∏ x in s, f x = 1) (h1 : ∀ x ∈ s, x ≠ a → f x = 1) : ∀ x ∈ s, f x = 1 := begin intros x hx, classical, by_cases h : x = a, { rw h, rw h at hx, rw [←prod_subset (singleton_subset_iff.2 hx) (λ t ht ha, h1 t ht (not_mem_singleton.1 ha)), prod_singleton] at hp, exact hp }, { exact h1 x hx h } end lemma prod_pow_boole [decidable_eq α] (s : finset α) (f : α → β) (a : α) : (∏ x in s, (f x)^(ite (a = x) 1 0)) = ite (a ∈ s) (f a) 1 := by simp end comm_monoid /-- If `f = g = h` everywhere but at `i`, where `f i = g i + h i`, then the product of `f` over `s` is the sum of the products of `g` and `h`. -/ lemma prod_add_prod_eq [comm_semiring β] {s : finset α} {i : α} {f g h : α → β} (hi : i ∈ s) (h1 : g i + h i = f i) (h2 : ∀ j ∈ s, j ≠ i → g j = f j) (h3 : ∀ j ∈ s, j ≠ i → h j = f j) : ∏ i in s, g i + ∏ i in s, h i = ∏ i in s, f i := by { classical, simp_rw [prod_eq_mul_prod_diff_singleton hi, ← h1, right_distrib], congr' 2; apply prod_congr rfl; simpa } lemma sum_update_of_mem [add_comm_monoid β] [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s) (f : α → β) (b : β) : (∑ x in s, function.update f i b x) = b + (∑ x in s \ (singleton i), f x) := by { rw [update_eq_piecewise, sum_piecewise], simp [h] } attribute [to_additive] prod_update_of_mem lemma sum_nsmul [add_comm_monoid β] (s : finset α) (n : ℕ) (f : α → β) : (∑ x in s, n • (f x)) = n • ((∑ x in s, f x)) := @prod_pow _ (multiplicative β) _ _ _ _ attribute [to_additive sum_nsmul] prod_pow @[simp] lemma sum_const [add_comm_monoid β] (b : β) : (∑ x in s, b) = s.card • b := @prod_const _ (multiplicative β) _ _ _ attribute [to_additive] prod_const lemma card_eq_sum_ones (s : finset α) : s.card = ∑ _ in s, 1 := by simp lemma sum_const_nat {m : ℕ} {f : α → ℕ} (h₁ : ∀x ∈ s, f x = m) : (∑ x in s, f x) = card s * m := begin rw [← nat.nsmul_eq_mul, ← sum_const], apply sum_congr rfl h₁ end @[simp] lemma sum_boole {s : finset α} {p : α → Prop} [semiring β] {hp : decidable_pred p} : (∑ x in s, if p x then (1 : β) else (0 : β)) = (s.filter p).card := by simp [sum_ite] @[norm_cast] lemma sum_nat_cast [add_comm_monoid β] [has_one β] (s : finset α) (f : α → ℕ) : ↑(∑ x in s, f x : ℕ) = (∑ x in s, (f x : β)) := (nat.cast_add_monoid_hom β).map_sum f s @[norm_cast] lemma sum_int_cast [add_comm_group β] [has_one β] (s : finset α) (f : α → ℤ) : ↑(∑ x in s, f x : ℤ) = (∑ x in s, (f x : β)) := (int.cast_add_hom β).map_sum f s lemma sum_comp [add_comm_monoid β] [decidable_eq γ] {s : finset α} (f : γ → β) (g : α → γ) : ∑ a in s, f (g a) = ∑ b in s.image g, (s.filter (λ a, g a = b)).card • (f b) := @prod_comp _ (multiplicative β) _ _ _ _ _ _ attribute [to_additive "The sum of the composition of functions `f` and `g`, is the sum over `b ∈ s.image g` of `f b` times of the cardinality of the fibre of `b`"] prod_comp lemma sum_range_succ' [add_comm_monoid β] (f : ℕ → β) : ∀ n : ℕ, (∑ i in range (n + 1), f i) = (∑ i in range n, f (i + 1)) + f 0 := @prod_range_succ' (multiplicative β) _ _ attribute [to_additive] prod_range_succ' lemma eq_sum_range_sub [add_comm_group β] (f : ℕ → β) (n : ℕ) : f n = f 0 + ∑ i in range n, (f (i+1) - f i) := by { rw finset.sum_range_sub, abel } lemma eq_sum_range_sub' [add_comm_group β] (f : ℕ → β) (n : ℕ) : f n = ∑ i in range (n + 1), if i = 0 then f 0 else f i - f (i - 1) := begin conv_lhs { rw [finset.eq_sum_range_sub f] }, simp [finset.sum_range_succ', add_comm] end lemma sum_range_add {β} [add_comm_monoid β] (f : ℕ → β) (n : ℕ) (m : ℕ) : (∑ x in range (n + m), f x) = (∑ x in range n, f x) + (∑ x in range m, f (n + x)) := @prod_range_add (multiplicative β) _ _ _ _ attribute [to_additive] prod_range_add lemma sum_flip [add_comm_monoid β] {n : ℕ} (f : ℕ → β) : (∑ i in range (n + 1), f (n - i)) = (∑ i in range (n + 1), f i) := @prod_flip (multiplicative β) _ _ _ attribute [to_additive] prod_flip section opposite open opposite /-- Moving to the opposite additive commutative monoid commutes with summing. -/ @[simp] lemma op_sum [add_comm_monoid β] {s : finset α} (f : α → β) : op (∑ x in s, f x) = ∑ x in s, op (f x) := (op_add_equiv : β ≃+ βᵒᵖ).map_sum _ _ @[simp] lemma unop_sum [add_comm_monoid β] {s : finset α} (f : α → βᵒᵖ) : unop (∑ x in s, f x) = ∑ x in s, unop (f x) := (op_add_equiv : β ≃+ βᵒᵖ).symm.map_sum _ _ end opposite section comm_group variables [comm_group β] @[simp, to_additive] lemma prod_inv_distrib : (∏ x in s, (f x)⁻¹) = (∏ x in s, f x)⁻¹ := s.prod_hom has_inv.inv end comm_group @[simp] theorem card_sigma {σ : α → Type*} (s : finset α) (t : Π a, finset (σ a)) : card (s.sigma t) = ∑ a in s, card (t a) := multiset.card_sigma _ _ lemma card_bUnion [decidable_eq β] {s : finset α} {t : α → finset β} (h : ∀ x ∈ s, ∀ y ∈ s, x ≠ y → disjoint (t x) (t y)) : (s.bUnion t).card = ∑ u in s, card (t u) := calc (s.bUnion t).card = ∑ i in s.bUnion t, 1 : by simp ... = ∑ a in s, ∑ i in t a, 1 : finset.sum_bUnion h ... = ∑ u in s, card (t u) : by simp lemma card_bUnion_le [decidable_eq β] {s : finset α} {t : α → finset β} : (s.bUnion t).card ≤ ∑ a in s, (t a).card := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (λ a s has ih, calc ((insert a s).bUnion t).card ≤ (t a).card + (s.bUnion t).card : by rw bUnion_insert; exact finset.card_union_le _ _ ... ≤ ∑ a in insert a s, card (t a) : by rw sum_insert has; exact add_le_add_left ih _) theorem card_eq_sum_card_fiberwise [decidable_eq β] {f : α → β} {s : finset α} {t : finset β} (H : ∀ x ∈ s, f x ∈ t) : s.card = ∑ a in t, (s.filter (λ x, f x = a)).card := by simp only [card_eq_sum_ones, sum_fiberwise_of_maps_to H] theorem card_eq_sum_card_image [decidable_eq β] (f : α → β) (s : finset α) : s.card = ∑ a in s.image f, (s.filter (λ x, f x = a)).card := card_eq_sum_card_fiberwise (λ _, mem_image_of_mem _) lemma gsmul_sum [add_comm_group β] {f : α → β} {s : finset α} (z : ℤ) : gsmul z (∑ a in s, f a) = ∑ a in s, gsmul z (f a) := (s.sum_hom (gsmul z)).symm @[simp] lemma sum_sub_distrib [add_comm_group β] : ∑ x in s, (f x - g x) = (∑ x in s, f x) - (∑ x in s, g x) := by simpa only [sub_eq_add_neg] using sum_add_distrib.trans (congr_arg _ sum_neg_distrib) section prod_eq_zero variables [comm_monoid_with_zero β] lemma prod_eq_zero (ha : a ∈ s) (h : f a = 0) : (∏ x in s, f x) = 0 := by haveI := classical.dec_eq α; calc (∏ x in s, f x) = ∏ x in insert a (erase s a), f x : by rw insert_erase ha ... = 0 : by rw [prod_insert (not_mem_erase _ _), h, zero_mul] lemma prod_boole {s : finset α} {p : α → Prop} [decidable_pred p] : ∏ i in s, ite (p i) (1 : β) (0 : β) = ite (∀ i ∈ s, p i) 1 0 := begin split_ifs, { apply prod_eq_one, intros i hi, rw if_pos (h i hi) }, { push_neg at h, rcases h with ⟨i, hi, hq⟩, apply prod_eq_zero hi, rw [if_neg hq] }, end variables [nontrivial β] [no_zero_divisors β] lemma prod_eq_zero_iff : (∏ x in s, f x) = 0 ↔ (∃a∈s, f a = 0) := begin classical, apply finset.induction_on s, exact ⟨not.elim one_ne_zero, λ ⟨_, H, _⟩, H.elim⟩, assume a s ha ih, rw [prod_insert ha, mul_eq_zero, bex_def, exists_mem_insert, ih, ← bex_def] end theorem prod_ne_zero_iff : (∏ x in s, f x) ≠ 0 ↔ (∀ a ∈ s, f a ≠ 0) := by { rw [ne, prod_eq_zero_iff], push_neg } end prod_eq_zero section comm_group_with_zero variables [comm_group_with_zero β] @[simp] lemma prod_inv_distrib' : (∏ x in s, (f x)⁻¹) = (∏ x in s, f x)⁻¹ := begin classical, by_cases h : ∃ x ∈ s, f x = 0, { simpa [prod_eq_zero_iff.mpr h, prod_eq_zero_iff] using h }, { push_neg at h, have h' := prod_ne_zero_iff.mpr h, have hf : ∀ x ∈ s, (f x)⁻¹ * f x = 1 := λ x hx, inv_mul_cancel (h x hx), apply mul_right_cancel' h', simp [h, h', ← finset.prod_mul_distrib, prod_congr rfl hf] } end end comm_group_with_zero end finset namespace fintype open finset /-- `fintype.prod_bijective` is a variant of `finset.prod_bij` that accepts `function.bijective`. See `function.bijective.prod_comp` for a version without `h`. -/ @[to_additive "`fintype.sum_equiv` is a variant of `finset.sum_bij` that accepts `function.bijective`. See `function.bijective.sum_comp` for a version without `h`. "] lemma prod_bijective {α β M : Type*} [fintype α] [fintype β] [comm_monoid M] (e : α → β) (he : function.bijective e) (f : α → M) (g : β → M) (h : ∀ x, f x = g (e x)) : ∏ x : α, f x = ∏ x : β, g x := prod_bij (λ x _, e x) (λ x _, mem_univ (e x)) (λ x _, h x) (λ x x' _ _ h, he.injective h) (λ y _, (he.surjective y).imp $ λ a h, ⟨mem_univ _, h.symm⟩) /-- `fintype.prod_equiv` is a specialization of `finset.prod_bij` that automatically fills in most arguments. See `equiv.prod_comp` for a version without `h`. -/ @[to_additive "`fintype.sum_equiv` is a specialization of `finset.sum_bij` that automatically fills in most arguments. See `equiv.sum_comp` for a version without `h`. "] lemma prod_equiv {α β M : Type*} [fintype α] [fintype β] [comm_monoid M] (e : α ≃ β) (f : α → M) (g : β → M) (h : ∀ x, f x = g (e x)) : ∏ x : α, f x = ∏ x : β, g x := prod_bijective e e.bijective f g h @[to_additive] lemma prod_finset_coe [comm_monoid β] : ∏ (i : (s : set α)), f i = ∏ i in s, f i := (finset.prod_subtype s (λ _, iff.rfl) f).symm end fintype namespace list @[to_additive] lemma prod_to_finset {M : Type*} [decidable_eq α] [comm_monoid M] (f : α → M) : ∀ {l : list α} (hl : l.nodup), l.to_finset.prod f = (l.map f).prod | [] _ := by simp | (a :: l) hl := let ⟨not_mem, hl⟩ := list.nodup_cons.mp hl in by simp [finset.prod_insert (mt list.mem_to_finset.mp not_mem), prod_to_finset hl] end list namespace multiset variables [decidable_eq α] @[simp] lemma to_finset_sum_count_eq (s : multiset α) : (∑ a in s.to_finset, s.count a) = s.card := multiset.induction_on s rfl (assume a s ih, calc (∑ x in to_finset (a ::ₘ s), count x (a ::ₘ s)) = ∑ x in to_finset (a ::ₘ s), ((if x = a then 1 else 0) + count x s) : finset.sum_congr rfl $ λ _ _, by split_ifs; [simp only [h, count_cons_self, nat.one_add], simp only [count_cons_of_ne h, zero_add]] ... = card (a ::ₘ s) : begin by_cases a ∈ s.to_finset, { have : ∑ x in s.to_finset, ite (x = a) 1 0 = ∑ x in {a}, ite (x = a) 1 0, { rw [finset.sum_ite_eq', if_pos h, finset.sum_singleton, if_pos rfl], }, rw [to_finset_cons, finset.insert_eq_of_mem h, finset.sum_add_distrib, ih, this, finset.sum_singleton, if_pos rfl, add_comm, card_cons] }, { have ha : a ∉ s, by rwa mem_to_finset at h, have : ∑ x in to_finset s, ite (x = a) 1 0 = ∑ x in to_finset s, 0, from finset.sum_congr rfl (λ x hx, if_neg $ by rintro rfl; cc), rw [to_finset_cons, finset.sum_insert h, if_pos rfl, finset.sum_add_distrib, this, finset.sum_const_zero, ih, count_eq_zero_of_not_mem ha, zero_add, add_comm, card_cons] } end) lemma count_sum' {s : finset β} {a : α} {f : β → multiset α} : count a (∑ x in s, f x) = ∑ x in s, count a (f x) := by { dunfold finset.sum, rw count_sum } @[simp] lemma to_finset_sum_count_nsmul_eq (s : multiset α) : (∑ a in s.to_finset, s.count a • (a ::ₘ 0)) = s := begin apply ext', intro b, rw count_sum', have h : count b s = count b (count b s • (b ::ₘ 0)), { rw [singleton_coe, count_nsmul, ← singleton_coe, count_singleton, mul_one] }, rw h, clear h, apply finset.sum_eq_single b, { intros c h hcb, rw count_nsmul, convert mul_zero (count c s), apply count_eq_zero.mpr, exact finset.not_mem_singleton.mpr (ne.symm hcb) }, { intro hb, rw [count_eq_zero_of_not_mem (mt mem_to_finset.2 hb), count_nsmul, zero_mul]} end theorem exists_smul_of_dvd_count (s : multiset α) {k : ℕ} (h : ∀ (a : α), k ∣ multiset.count a s) : ∃ (u : multiset α), s = k • u := begin use ∑ a in s.to_finset, (s.count a / k) • (a ::ₘ 0), have h₂ : ∑ (x : α) in s.to_finset, k • (count x s / k) • (x ::ₘ 0) = ∑ (x : α) in s.to_finset, count x s • (x ::ₘ 0), { refine congr_arg s.to_finset.sum _, apply funext, intro x, rw [← mul_nsmul, nat.mul_div_cancel' (h x)] }, rw [← finset.sum_nsmul, h₂, to_finset_sum_count_nsmul_eq] end end multiset @[simp, norm_cast] lemma nat.coe_prod {R : Type*} [comm_semiring R] (f : α → ℕ) (s : finset α) : (↑∏ i in s, f i : R) = ∏ i in s, f i := (nat.cast_ring_hom R).map_prod _ _ @[simp, norm_cast] lemma int.coe_prod {R : Type*} [comm_ring R] (f : α → ℤ) (s : finset α) : (↑∏ i in s, f i : R) = ∏ i in s, f i := (int.cast_ring_hom R).map_prod _ _ @[simp, norm_cast] lemma units.coe_prod {M : Type*} [comm_monoid M] (f : α → units M) (s : finset α) : (↑∏ i in s, f i : M) = ∏ i in s, f i := (units.coe_hom M).map_prod _ _
b8ab3293a1d54a2ecd4d5d9df795a84a4c797e16
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/stage0/src/Init/Data/List/Basic.lean
5ed43828dec619a1cf675bad31e7e8f01beec324
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,725
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import Init.Core import Init.Data.Nat.Basic open Decidable List universes u v w instance (α : Type u) : Inhabited (List α) := ⟨List.nil⟩ variables {α : Type u} {β : Type v} {γ : Type w} namespace List def reverseAux : List α → List α → List α | [], r => r | a::l, r => reverseAux l (a::r) def reverse (as : List α) :List α := reverseAux as [] protected def append (as bs : List α) : List α := reverseAux as.reverse bs instance : Append (List α) := ⟨List.append⟩ theorem reverseAuxReverseAuxNil : ∀ (as bs : List α), reverseAux (reverseAux as bs) [] = reverseAux bs as | [], bs => rfl | a::as, bs => show reverseAux (reverseAux as (a::bs)) [] = reverseAux bs (a::as) from reverseAuxReverseAuxNil as (a::bs) theorem nilAppend (as : List α) : [] ++ as = as := rfl theorem appendNil (as : List α) : as ++ [] = as := show reverseAux (reverseAux as []) [] = as from reverseAuxReverseAuxNil as [] theorem reverseAuxReverseAux : ∀ (as bs cs : List α), reverseAux (reverseAux as bs) cs = reverseAux bs (reverseAux (reverseAux as []) cs) | [], bs, cs => rfl | a::as, bs, cs => by rw [reverseAuxReverseAux as (a::bs) cs, reverseAuxReverseAux as [a] cs] exact rfl theorem consAppend (a : α) (as bs : List α) : (a::as) ++ bs = a::(as ++ bs) := reverseAuxReverseAux as [a] bs theorem appendAssoc : ∀ (as bs cs : List α), (as ++ bs) ++ cs = as ++ (bs ++ cs) | [], bs, cs => rfl | a::as, bs, cs => by show ((a::as) ++ bs) ++ cs = (a::as) ++ (bs ++ cs) rw [consAppend, consAppend, appendAssoc, consAppend] exact rfl instance : EmptyCollection (List α) := ⟨List.nil⟩ protected def erase {α} [BEq α] : List α → α → List α | [], b => [] | a::as, b => match a == b with | true => as | false => a :: List.erase as b def eraseIdx : List α → Nat → List α | [], _ => [] | a::as, 0 => as | a::as, n+1 => a :: eraseIdx as n def lengthAux : List α → Nat → Nat | [], n => n | a::as, n => lengthAux as (n+1) def length (as : List α) : Nat := lengthAux as 0 def isEmpty : List α → Bool | [] => true | _ :: _ => false def set : List α → Nat → α → List α | a::as, 0, b => b::as | a::as, n+1, b => a::(set as n b) | [], _, _ => [] @[specialize] def map (f : α → β) : List α → List β | [] => [] | a::as => f a :: map f as @[specialize] def map₂ (f : α → β → γ) : List α → List β → List γ | [], _ => [] | _, [] => [] | a::as, b::bs => f a b :: map₂ f as bs def join : List (List α) → List α | [] => [] | a :: as => a ++ join as @[specialize] def filterMap (f : α → Option β) : List α → List β | [] => [] | a::as => match f a with | none => filterMap f as | some b => b :: filterMap f as @[specialize] def filterAux (p : α → Bool) : List α → List α → List α | [], rs => rs.reverse | a::as, rs => match p a with | true => filterAux p as (a::rs) | false => filterAux p as rs @[inline] def filter (p : α → Bool) (as : List α) : List α := filterAux p as [] @[specialize] def partitionAux (p : α → Bool) : List α → List α × List α → List α × List α | [], (bs, cs) => (bs.reverse, cs.reverse) | a::as, (bs, cs) => match p a with | true => partitionAux p as (a::bs, cs) | false => partitionAux p as (bs, a::cs) @[inline] def partition (p : α → Bool) (as : List α) : List α × List α := partitionAux p as ([], []) def dropWhile (p : α → Bool) : List α → List α | [] => [] | a::l => match p a with | true => dropWhile p l | false => a::l def find? (p : α → Bool) : List α → Option α | [] => none | a::as => match p a with | true => some a | false => find? p as def findSome? (f : α → Option β) : List α → Option β | [] => none | a::as => match f a with | some b => some b | none => findSome? f as def replace [BEq α] : List α → α → α → List α | [], _, _ => [] | a::as, b, c => match a == b with | true => c::as | flase => a :: (replace as b c) def elem [BEq α] (a : α) : List α → Bool | [] => false | b::bs => match a == b with | true => true | false => elem a bs def notElem [BEq α] (a : α) (as : List α) : Bool := !(as.elem a) abbrev contains [BEq α] (as : List α) (a : α) : Bool := elem a as def eraseDupsAux {α} [BEq α] : List α → List α → List α | [], bs => bs.reverse | a::as, bs => match bs.elem a with | true => eraseDupsAux as bs | false => eraseDupsAux as (a::bs) def eraseDups {α} [BEq α] (as : List α) : List α := eraseDupsAux as [] def eraseRepsAux {α} [BEq α] : α → List α → List α → List α | a, [], rs => (a::rs).reverse | a, a'::as, rs => match a == a' with | true => eraseRepsAux a as rs | false => eraseRepsAux a' as (a::rs) /-- Erase repeated adjacent elements. -/ def eraseReps {α} [BEq α] : List α → List α | [] => [] | a::as => eraseRepsAux a as [] @[specialize] def spanAux (p : α → Bool) : List α → List α → List α × List α | [], rs => (rs.reverse, []) | a::as, rs => match p a with | true => spanAux p as (a::rs) | false => (rs.reverse, a::as) @[inline] def span (p : α → Bool) (as : List α) : List α × List α := spanAux p as [] @[specialize] def groupByAux (eq : α → α → Bool) : List α → List (List α) → List (List α) | a::as, (ag::g)::gs => match eq a ag with | true => groupByAux eq as ((a::ag::g)::gs) | false => groupByAux eq as ([a]::(ag::g).reverse::gs) | _, gs => gs.reverse @[specialize] def groupBy (p : α → α → Bool) : List α → List (List α) | [] => [] | a::as => groupByAux p as [[a]] def lookup [BEq α] : α → List (α × β) → Option β | _, [] => none | a, (k,b)::es => match a == k with | true => some b | false => lookup a es def removeAll [BEq α] (xs ys : List α) : List α := xs.filter (fun x => ys.notElem x) def drop : Nat → List α → List α | 0, a => a | n+1, [] => [] | n+1, a::as => drop n as def take : Nat → List α → List α | 0, a => [] | n+1, [] => [] | n+1, a::as => a :: take n as @[specialize] def foldr (f : α → β → β) (init : β) : List α → β | [] => init | a :: l => f a (foldr f init l) @[inline] def any (l : List α) (p : α → Bool) : Bool := foldr (fun a r => p a || r) false l @[inline] def all (l : List α) (p : α → Bool) : Bool := foldr (fun a r => p a && r) true l def or (bs : List Bool) : Bool := bs.any id def and (bs : List Bool) : Bool := bs.all id def zipWith (f : α → β → γ) : List α → List β → List γ | x::xs, y::ys => f x y :: zipWith f xs ys | _, _ => [] def zip : List α → List β → List (Prod α β) := zipWith Prod.mk def unzip : List (α × β) → List α × List β | [] => ([], []) | (a, b) :: t => match unzip t with | (al, bl) => (a::al, b::bl) def replicate (n : Nat) (a : α) : List α := n.repeat (fun xs => a :: xs) [] def rangeAux : Nat → List Nat → List Nat | 0, ns => ns | n+1, ns => rangeAux n (n::ns) def range (n : Nat) : List Nat := rangeAux n [] def iota : Nat → List Nat | 0 => [] | m@(n+1) => m :: iota n def enumFrom : Nat → List α → List (Nat × α) | n, [] => nil | n, x :: xs => (n, x) :: enumFrom (n + 1) xs def enum : List α → List (Nat × α) := enumFrom 0 def init : List α → List α | [] => [] | [a] => [] | a::l => a::init l def intersperse (sep : α) : List α → List α | [] => [] | [x] => [x] | x::xs => x :: sep :: intersperse sep xs def intercalate (sep : List α) (xs : List (List α)) : List α := join (intersperse sep xs) @[inline] protected def bind {α : Type u} {β : Type v} (a : List α) (b : α → List β) : List β := join (map b a) @[inline] protected def pure {α : Type u} (a : α) : List α := [a] inductive List.Less [HasLess α] : List α → List α → Prop | nil (b : α) (bs : List α) : Less [] (b::bs) | head {a : α} (as : List α) {b : α} (bs : List α) : a < b → Less (a::as) (b::bs) | tail {a : α} {as : List α} {b : α} {bs : List α} : ¬ a < b → ¬ b < a → Less as bs → Less (a::as) (b::bs) instance less [HasLess α] : HasLess (List α) := ⟨List.Less⟩ instance hasDecidableLt [HasLess α] [h : DecidableRel (α:=α) (·<·)] : (l₁ l₂ : List α) → Decidable (l₁ < l₂) | [], [] => isFalse (fun h => nomatch h) | [], b::bs => isTrue (List.Less.nil _ _) | a::as, [] => isFalse (fun h => nomatch h) | a::as, b::bs => match h a b with | isTrue h₁ => isTrue (List.Less.head _ _ h₁) | isFalse h₁ => match h b a with | isTrue h₂ => isFalse (fun h => match h with | List.Less.head _ _ h₁' => absurd h₁' h₁ | List.Less.tail _ h₂' _ => absurd h₂ h₂') | isFalse h₂ => match hasDecidableLt as bs with | isTrue h₃ => isTrue (List.Less.tail h₁ h₂ h₃) | isFalse h₃ => isFalse (fun h => match h with | List.Less.head _ _ h₁' => absurd h₁' h₁ | List.Less.tail _ _ h₃' => absurd h₃' h₃) @[reducible] protected def LessEq [HasLess α] (a b : List α) : Prop := ¬ b < a instance lessEq [HasLess α] : HasLessEq (List α) := ⟨List.LessEq⟩ instance [HasLess α] [h : DecidableRel ((· < ·) : α → α → Prop)] : (l₁ l₂ : List α) → Decidable (l₁ ≤ l₂) := fun a b => inferInstanceAs (Decidable (Not _)) /-- `isPrefixOf l₁ l₂` returns `true` Iff `l₁` is a prefix of `l₂`. -/ def isPrefixOf [BEq α] : List α → List α → Bool | [], _ => true | _, [] => false | a::as, b::bs => a == b && isPrefixOf as bs /-- `isSuffixOf l₁ l₂` returns `true` Iff `l₁` is a suffix of `l₂`. -/ def isSuffixOf [BEq α] (l₁ l₂ : List α) : Bool := isPrefixOf l₁.reverse l₂.reverse @[specialize] def isEqv : List α → List α → (α → α → Bool) → Bool | [], [], _ => true | a::as, b::bs, eqv => eqv a b && isEqv as bs eqv | _, _, eqv => false protected def beq [BEq α] : List α → List α → Bool | [], [] => true | a::as, b::bs => a == b && List.beq as bs | _, _ => false instance [BEq α] : BEq (List α) := ⟨List.beq⟩ end List
cc2da761007c8e4befe36820e649fcc1c2aa4716
6094e25ea0b7699e642463b48e51b2ead6ddc23f
/library/data/set/finite.lean
b5a791cff4f1639147a215466006c94db0c20448
[ "Apache-2.0" ]
permissive
gbaz/lean
a7835c4e3006fbbb079e8f8ffe18aacc45adebfb
a501c308be3acaa50a2c0610ce2e0d71becf8032
refs/heads/master
1,611,198,791,433
1,451,339,111,000
1,451,339,111,000
48,713,797
0
0
null
1,451,338,939,000
1,451,338,939,000
null
UTF-8
Lean
false
false
7,029
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad The notion of "finiteness" for sets. This approach is not computational: for example, just because an element s : set A satsifies finite s doesn't mean that we can compute the cardinality. For a computational representation, use the finset type. -/ import data.set.function data.finset.to_set open nat classical variable {A : Type} namespace set definition finite [class] (s : set A) : Prop := ∃ (s' : finset A), s = finset.to_set s' theorem finite_finset [instance] (s : finset A) : finite (finset.to_set s) := exists.intro s rfl /- to finset: casts every set to a finite set -/ noncomputable definition to_finset (s : set A) : finset A := if fins : finite s then some fins else finset.empty theorem to_finset_of_not_finite {s : set A} (nfins : ¬ finite s) : to_finset s = (#finset ∅) := by rewrite [↑to_finset, dif_neg nfins] theorem to_set_to_finset (s : set A) [fins : finite s] : finset.to_set (to_finset s) = s := by rewrite [↑to_finset, dif_pos fins]; exact eq.symm (some_spec fins) theorem mem_to_finset_eq (a : A) (s : set A) [finite s] : (#finset a ∈ to_finset s) = (a ∈ s) := by rewrite [-to_set_to_finset at {2}] theorem to_set_to_finset_of_not_finite {s : set A} (nfins : ¬ finite s) : finset.to_set (to_finset s) = ∅ := by rewrite [to_finset_of_not_finite nfins] theorem to_finset_to_set (s : finset A) : to_finset (finset.to_set s) = s := by rewrite [finset.eq_eq_to_set_eq, to_set_to_finset (finset.to_set s)] theorem to_finset_eq_of_to_set_eq {s : set A} {t : finset A} (H : finset.to_set t = s) : to_finset s = t := finset.eq_of_to_set_eq_to_set (by subst [s]; rewrite to_finset_to_set) /- finiteness -/ theorem finite_of_to_set_to_finset_eq {s : set A} (H : finset.to_set (to_finset s) = s) : finite s := by rewrite -H; apply finite_finset theorem finite_empty [instance] : finite (∅ : set A) := by rewrite [-finset.to_set_empty]; apply finite_finset theorem to_finset_empty : to_finset (∅ : set A) = (#finset ∅) := to_finset_eq_of_to_set_eq !finset.to_set_empty theorem finite_insert [instance] (a : A) (s : set A) [finite s] : finite (insert a s) := exists.intro (finset.insert a (to_finset s)) (by rewrite [finset.to_set_insert, to_set_to_finset]) theorem to_finset_insert (a : A) (s : set A) [finite s] : to_finset (insert a s) = finset.insert a (to_finset s) := by apply to_finset_eq_of_to_set_eq; rewrite [finset.to_set_insert, to_set_to_finset] theorem finite_union [instance] (s t : set A) [finite s] [finite t] : finite (s ∪ t) := exists.intro (#finset to_finset s ∪ to_finset t) (by rewrite [finset.to_set_union, *to_set_to_finset]) theorem to_finset_union (s t : set A) [finite s] [finite t] : to_finset (s ∪ t) = (#finset to_finset s ∪ to_finset t) := by apply to_finset_eq_of_to_set_eq; rewrite [finset.to_set_union, *to_set_to_finset] theorem finite_inter [instance] (s t : set A) [finite s] [finite t] : finite (s ∩ t) := exists.intro (#finset to_finset s ∩ to_finset t) (by rewrite [finset.to_set_inter, *to_set_to_finset]) theorem to_finset_inter (s t : set A) [finite s] [finite t] : to_finset (s ∩ t) = (#finset to_finset s ∩ to_finset t) := by apply to_finset_eq_of_to_set_eq; rewrite [finset.to_set_inter, *to_set_to_finset] theorem finite_sep [instance] (s : set A) (p : A → Prop) [decidable_pred p] [finite s] : finite {x ∈ s | p x} := exists.intro (finset.sep p (to_finset s)) (by rewrite [finset.to_set_sep, *to_set_to_finset]) theorem to_finset_sep (s : set A) (p : A → Prop) [decidable_pred p] [finite s] : to_finset {x ∈ s | p x} = (#finset {x ∈ to_finset s | p x}) := by apply to_finset_eq_of_to_set_eq; rewrite [finset.to_set_sep, to_set_to_finset] theorem finite_image [instance] {B : Type} [decidable_eq B] (f : A → B) (s : set A) [finite s] : finite (f '[s]) := exists.intro (finset.image f (to_finset s)) (by rewrite [finset.to_set_image, *to_set_to_finset]) theorem to_finset_image {B : Type} [decidable_eq B] (f : A → B) (s : set A) [fins : finite s] : to_finset (f '[s]) = (#finset f '[to_finset s]) := by apply to_finset_eq_of_to_set_eq; rewrite [finset.to_set_image, to_set_to_finset] theorem finite_diff [instance] (s t : set A) [finite s] : finite (s \ t) := !finite_sep theorem to_finset_diff (s t : set A) [finite s] [finite t] : to_finset (s \ t) = (#finset to_finset s \ to_finset t) := by apply to_finset_eq_of_to_set_eq; rewrite [finset.to_set_diff, *to_set_to_finset] theorem finite_subset {s t : set A} [finite t] (ssubt : s ⊆ t) : finite s := by rewrite (eq_sep_of_subset ssubt); apply finite_sep theorem to_finset_subset_to_finset_eq (s t : set A) [finite s] [finite t] : (#finset to_finset s ⊆ to_finset t) = (s ⊆ t) := by rewrite [finset.subset_eq_to_set_subset, *to_set_to_finset] theorem finite_of_finite_insert {s : set A} {a : A} (finias : finite (insert a s)) : finite s := finite_subset (subset_insert a s) theorem finite_upto [instance] (n : ℕ) : finite {i | i < n} := by rewrite [-finset.to_set_upto n]; apply finite_finset theorem to_finset_upto (n : ℕ) : to_finset {i | i < n} = finset.upto n := by apply (to_finset_eq_of_to_set_eq !finset.to_set_upto) theorem finite_powerset (s : set A) [finite s] : finite 𝒫 s := assert H : 𝒫 s = finset.to_set '[finset.to_set (#finset 𝒫 (to_finset s))], from ext (take t, iff.intro (suppose t ∈ 𝒫 s, assert t ⊆ s, from this, assert finite t, from finite_subset this, assert (#finset to_finset t ∈ 𝒫 (to_finset s)), by rewrite [finset.mem_powerset_iff_subset, to_finset_subset_to_finset_eq]; apply `t ⊆ s`, assert to_finset t ∈ (finset.to_set (finset.powerset (to_finset s))), from this, mem_image this (by rewrite to_set_to_finset)) (assume H', obtain t' [(tmem : (#finset t' ∈ 𝒫 (to_finset s))) (teq : finset.to_set t' = t)], from H', show t ⊆ s, begin rewrite [-teq, finset.mem_powerset_iff_subset at tmem, -to_set_to_finset s], rewrite -finset.subset_eq_to_set_subset, assumption end)), by rewrite H; apply finite_image /- induction for finite sets -/ theorem induction_finite [recursor 6] {P : set A → Prop} (H1 : P ∅) (H2 : ∀ ⦃a : A⦄, ∀ {s : set A} [finite s], a ∉ s → P s → P (insert a s)) : ∀ (s : set A) [finite s], P s := begin intro s fins, rewrite [-to_set_to_finset s], generalize to_finset s, intro s', induction s' using finset.induction with a s' nains ih, {rewrite finset.to_set_empty, apply H1}, rewrite [finset.to_set_insert], apply H2, {rewrite -finset.mem_eq_mem_to_set, assumption}, exact ih end theorem induction_on_finite {P : set A → Prop} (s : set A) [finite s] (H1 : P ∅) (H2 : ∀ ⦃a : A⦄, ∀ {s : set A} [finite s], a ∉ s → P s → P (insert a s)) : P s := induction_finite H1 H2 s end set
6923c4bff8c0f8a50eaad5b2308547a7742c31b8
359199d7253811b032ab92108191da7336eba86e
/src/mywork/mid-term_review/hw-2_practice.lean
fab99013e2fb2f95938bf8d80a154453b5273b1c
[]
no_license
arte-et-marte/my_cs2120f21
0bc6215cb5018a3b7c90d9d399a173233f587064
91609c3609ad81fda895bee8b97cc76813241e17
refs/heads/main
1,693,298,928,348
1,634,931,202,000
1,634,931,202,000
399,946,705
0
0
null
null
null
null
UTF-8
Lean
false
false
1,693
lean
-- 14 example : ∀ (P : Prop), P ∧ false ↔ false := begin assume P, apply iff.intro _ _, -- forwards implication proof assume p_and_false, exact and.elim_right p_and_false, -- backwards implication proof assume f, exact false.elim f, -- **How does the false elim rule work?** end -- 12 example : ∀ (P : Prop), P ∨ false ↔ P := begin assume P, apply iff.intro _ _, -- forwards implication proof assume p_or_false, /- solution 1 apply or.elim p_or_false, ---- case 1 assume p, exact p, -- alternatively, 'assumption' ---- case 2 assume f, exact false.elim f, solution 2 -/ cases p_or_false with p f, -- **What does 'cases' do?** assumption, exact false.elim f, -- backwards implication proof assume p, exact or.intro_left false p, end -- 10 example : ∀ (P Q : Prop), P ∨ (P ∧ Q) ↔ P := begin assume P Q, apply iff.intro _ _, -- forwards implication proof assume p_or_pandq, /- solution 1 apply or.elim p_or_pandq, ---- case 1 assume p, exact p, -- alternatively, 'assumption' ---- case 2 assume pandq, exact and.elim_left pandq, solution 2 -/ cases p_or_pandq with p pandq, assumption, exact and.elim_left pandq, -- backwards implication proof assume p, apply or.intro_left (P ∧ Q) p, -- **The 'or' intro rules take a proposition argument first, second a proof of a proposition.** end -- 9 example : ∀ (P Q : Prop), P ∧ (P ∨ Q) ↔ P := begin assume P Q, apply iff.intro _ _, -- forwards implication proof assume p_and_porq, exact and.elim_left p_and_porq, -- backwards implication proof assume p, apply and.intro p _, exact or.intro_left Q p, end
963ce5e19d55885213d8e972a771a57378b77610
b561a44b48979a98df50ade0789a21c79ee31288
/stage0/src/Lean/PrettyPrinter/Formatter.lean
df2370c170b70d3904828f4bb891e94e30e9cb5e
[ "Apache-2.0" ]
permissive
3401ijk/lean4
97659c475ebd33a034fed515cb83a85f75ccfb06
a5b1b8de4f4b038ff752b9e607b721f15a9a4351
refs/heads/master
1,693,933,007,651
1,636,424,845,000
1,636,424,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
21,953
lean
/- Copyright (c) 2020 Sebastian Ullrich. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ import Lean.CoreM import Lean.Parser.Extension import Lean.KeyedDeclsAttribute import Lean.ParserCompiler.Attribute import Lean.PrettyPrinter.Basic /-! The formatter turns a `Syntax` tree into a `Format` object, inserting both mandatory whitespace (to separate adjacent tokens) as well as "pretty" optional whitespace. The basic approach works much like the parenthesizer: A right-to-left traversal over the syntax tree, driven by parser-specific handlers registered via attributes. The traversal is right-to-left so that when emitting a token, we already know the text following it and can decide whether or not whitespace between the two is necessary. -/ namespace Lean namespace PrettyPrinter namespace Formatter structure Context where options : Options table : Parser.TokenTable structure State where stxTrav : Syntax.Traverser -- Textual content of `stack` up to the first whitespace (not enclosed in an escaped ident). We assume that the textual -- content of `stack` is modified only by `pushText` and `pushLine`, so `leadWord` is adjusted there accordingly. leadWord : String := "" -- Stack of generated Format objects, analogous to the Syntax stack in the parser. -- Note, however, that the stack is reversed because of the right-to-left traversal. stack : Array Format := #[] end Formatter abbrev FormatterM := ReaderT Formatter.Context $ StateRefT Formatter.State CoreM @[inline] def FormatterM.orElse {α} (p₁ : FormatterM α) (p₂ : Unit → FormatterM α) : FormatterM α := do let s ← get catchInternalId backtrackExceptionId p₁ (fun _ => do set s; p₂ ()) instance {α} : OrElse (FormatterM α) := ⟨FormatterM.orElse⟩ abbrev Formatter := FormatterM Unit unsafe def mkFormatterAttribute : IO (KeyedDeclsAttribute Formatter) := KeyedDeclsAttribute.init { builtinName := `builtinFormatter, name := `formatter, descr := "Register a formatter for a parser. [formatter k] registers a declaration of type `Lean.PrettyPrinter.Formatter` for the `SyntaxNodeKind` `k`.", valueTypeName := `Lean.PrettyPrinter.Formatter, evalKey := fun builtin stx => do let env ← getEnv let id ← Attribute.Builtin.getId stx -- `isValidSyntaxNodeKind` is updated only in the next stage for new `[builtin*Parser]`s, but we try to -- synthesize a formatter for it immediately, so we just check for a declaration in this case if (builtin && (env.find? id).isSome) || Parser.isValidSyntaxNodeKind env id then pure id else throwError "invalid [formatter] argument, unknown syntax kind '{id}'" } `Lean.PrettyPrinter.formatterAttribute @[builtinInit mkFormatterAttribute] constant formatterAttribute : KeyedDeclsAttribute Formatter unsafe def mkCombinatorFormatterAttribute : IO ParserCompiler.CombinatorAttribute := ParserCompiler.registerCombinatorAttribute `combinatorFormatter "Register a formatter for a parser combinator. [combinatorFormatter c] registers a declaration of type `Lean.PrettyPrinter.Formatter` for the `Parser` declaration `c`. Note that, unlike with [formatter], this is not a node kind since combinators usually do not introduce their own node kinds. The tagged declaration may optionally accept parameters corresponding to (a prefix of) those of `c`, where `Parser` is replaced with `Formatter` in the parameter types." @[builtinInit mkCombinatorFormatterAttribute] constant combinatorFormatterAttribute : ParserCompiler.CombinatorAttribute namespace Formatter open Lean.Core open Lean.Parser def throwBacktrack {α} : FormatterM α := throw $ Exception.internal backtrackExceptionId instance : Syntax.MonadTraverser FormatterM := ⟨{ get := State.stxTrav <$> get, set := fun t => modify (fun st => { st with stxTrav := t }), modifyGet := fun f => modifyGet (fun st => let (a, t) := f st.stxTrav; (a, { st with stxTrav := t })) }⟩ open Syntax.MonadTraverser def getStack : FormatterM (Array Format) := do let st ← get pure st.stack def getStackSize : FormatterM Nat := do let stack ← getStack; pure stack.size def setStack (stack : Array Format) : FormatterM Unit := modify fun st => { st with stack := stack } def push (f : Format) : FormatterM Unit := modify fun st => { st with stack := st.stack.push f } def pushLine : FormatterM Unit := do push Format.line; modify fun st => { st with leadWord := "" } /-- Execute `x` at the right-most child of the current node, if any, then advance to the left. -/ def visitArgs (x : FormatterM Unit) : FormatterM Unit := do let stx ← getCur if stx.getArgs.size > 0 then goDown (stx.getArgs.size - 1) *> x <* goUp goLeft /-- Execute `x`, pass array of generated Format objects to `fn`, and push result. -/ def fold (fn : Array Format → Format) (x : FormatterM Unit) : FormatterM Unit := do let sp ← getStackSize x let stack ← getStack let f := fn $ stack.extract sp stack.size setStack $ (stack.shrink sp).push f /-- Execute `x` and concatenate generated Format objects. -/ def concat (x : FormatterM Unit) : FormatterM Unit := do fold (Array.foldl (fun acc f => if acc.isNil then f else f ++ acc) Format.nil) x def indent (x : Formatter) (indent : Option Int := none) : Formatter := do concat x let ctx ← read let indent := indent.getD $ Std.Format.getIndent ctx.options modify fun st => { st with stack := st.stack.modify (st.stack.size - 1) (Format.nest indent) } def group (x : Formatter) : Formatter := do concat x modify fun st => { st with stack := st.stack.modify (st.stack.size - 1) Format.fill } /-- If `pos?` has a position, run `x` and tag its results with that position. Otherwise just run `x`. -/ def withMaybeTag (pos? : Option String.Pos) (x : FormatterM Unit) : Formatter := do if let some p := pos? then concat x modify fun st => { st with stack := st.stack.modify (st.stack.size - 1) (Format.tag p) } else x @[combinatorFormatter Lean.Parser.orelse] def orelse.formatter (p1 p2 : Formatter) : Formatter := -- HACK: We have no (immediate) information on which side of the orelse could have produced the current node, so try -- them in turn. Uses the syntax traverser non-linearly! p1 <|> p2 -- `mkAntiquot` is quite complex, so we'd rather have its formatter synthesized below the actual parser definition. -- Note that there is a mutual recursion -- `categoryParser -> mkAntiquot -> termParser -> categoryParser`, so we need to introduce an indirection somewhere -- anyway. @[extern "lean_mk_antiquot_formatter"] constant mkAntiquot.formatter' (name : String) (kind : Option SyntaxNodeKind) (anonymous := true) : Formatter -- break up big mutual recursion @[extern "lean_pretty_printer_formatter_interpret_parser_descr"] constant interpretParserDescr' : ParserDescr → CoreM Formatter private def SourceInfo.getExprPos? : SourceInfo → Option Nat | SourceInfo.synthetic pos _ => pos | _ => none private def getExprPos? : Syntax → Option Nat | Syntax.node info _ _ => SourceInfo.getExprPos? info | Syntax.atom info _ => SourceInfo.getExprPos? info | Syntax.ident info _ _ _ => SourceInfo.getExprPos? info | Syntax.missing => none unsafe def formatterForKindUnsafe (k : SyntaxNodeKind) : Formatter := do if k == `missing then push "<missing>" goLeft else let stx ← getCur let f ← runForNodeKind formatterAttribute k interpretParserDescr' withMaybeTag (getExprPos? stx) f @[implementedBy formatterForKindUnsafe] constant formatterForKind (k : SyntaxNodeKind) : Formatter @[combinatorFormatter Lean.Parser.withAntiquot] def withAntiquot.formatter (antiP p : Formatter) : Formatter := -- TODO: could be optimized using `isAntiquot` (which would have to be moved), but I'd rather -- fix the backtracking hack outright. orelse.formatter antiP p @[combinatorFormatter Lean.Parser.withAntiquotSuffixSplice] def withAntiquotSuffixSplice.formatter (k : SyntaxNodeKind) (p suffix : Formatter) : Formatter := do if (← getCur).isAntiquotSuffixSplice then visitArgs <| suffix *> p else p @[combinatorFormatter Lean.Parser.tokenWithAntiquot] def tokenWithAntiquot.formatter (p : Formatter) : Formatter := do if (← getCur).isTokenAntiquot then visitArgs p else p @[combinatorFormatter Lean.Parser.categoryParser] def categoryParser.formatter (cat : Name) : Formatter := group $ indent do let stx ← getCur trace[PrettyPrinter.format] "formatting {indentD (format stx)}" if stx.getKind == `choice then visitArgs do -- format only last choice -- TODO: We could use elaborator data here to format the chosen child when available formatterForKind (← getCur).getKind else withAntiquot.formatter (mkAntiquot.formatter' cat.toString none) (formatterForKind stx.getKind) @[combinatorFormatter Lean.Parser.categoryParserOfStack] def categoryParserOfStack.formatter (offset : Nat) : Formatter := do let st ← get let stx := st.stxTrav.parents.back.getArg (st.stxTrav.idxs.back - offset) categoryParser.formatter stx.getId @[combinatorFormatter Lean.Parser.parserOfStack] def parserOfStack.formatter (offset : Nat) (prec : Nat := 0) : Formatter := do let st ← get let stx := st.stxTrav.parents.back.getArg (st.stxTrav.idxs.back - offset) formatterForKind stx.getKind @[combinatorFormatter Lean.Parser.error] def error.formatter (msg : String) : Formatter := pure () @[combinatorFormatter Lean.Parser.errorAtSavedPos] def errorAtSavedPos.formatter (msg : String) (delta : Bool) : Formatter := pure () @[combinatorFormatter Lean.Parser.atomic] def atomic.formatter (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.lookahead] def lookahead.formatter (p : Formatter) : Formatter := pure () @[combinatorFormatter Lean.Parser.notFollowedBy] def notFollowedBy.formatter (p : Formatter) : Formatter := pure () @[combinatorFormatter Lean.Parser.andthen] def andthen.formatter (p1 p2 : Formatter) : Formatter := p2 *> p1 def checkKind (k : SyntaxNodeKind) : FormatterM Unit := do let stx ← getCur if k != stx.getKind then trace[PrettyPrinter.format.backtrack] "unexpected node kind '{stx.getKind}', expected '{k}'" throwBacktrack @[combinatorFormatter Lean.Parser.node] def node.formatter (k : SyntaxNodeKind) (p : Formatter) : Formatter := do checkKind k; visitArgs p @[combinatorFormatter Lean.Parser.trailingNode] def trailingNode.formatter (k : SyntaxNodeKind) (_ _ : Nat) (p : Formatter) : Formatter := do checkKind k visitArgs do p; -- leading term, not actually produced by `p` categoryParser.formatter `foo def parseToken (s : String) : FormatterM ParserState := do -- include comment tokens, e.g. when formatting `- -0` (Parser.andthenFn Parser.whitespace (Parser.tokenFn [])) { input := s, fileName := "", fileMap := FileMap.ofString "", prec := 0, env := ← getEnv, options := ← getOptions, tokens := (← read).table } (Parser.mkParserState s) def pushTokenCore (tk : String) : FormatterM Unit := do if tk.toSubstring.dropRightWhile (fun s => s == ' ') == tk.toSubstring then push tk else pushLine push tk.trimRight def pushToken (info : SourceInfo) (tk : String) : FormatterM Unit := do match info with | SourceInfo.original _ _ ss _ => -- preserve non-whitespace content (i.e. comments) let ss' := ss.trim if !ss'.isEmpty then let ws := { ss with startPos := ss'.stopPos } if ws.contains '\n' then push s!"\n{ss'}" else push s!" {ss'}" modify fun st => { st with leadWord := "" } | _ => pure () let st ← get -- If there is no space between `tk` and the next word, see if we would parse more than `tk` as a single token if st.leadWord != "" && tk.trimRight == tk then let tk' := tk.trimLeft let t ← parseToken $ tk' ++ st.leadWord if t.pos <= tk'.bsize then -- stopped within `tk` => use it as is, extend `leadWord` if not prefixed by whitespace pushTokenCore tk modify fun st => { st with leadWord := if tk.trimLeft == tk then tk ++ st.leadWord else "" } else -- stopped after `tk` => add space pushTokenCore $ tk ++ " " modify fun st => { st with leadWord := if tk.trimLeft == tk then tk else "" } else -- already separated => use `tk` as is pushTokenCore tk modify fun st => { st with leadWord := if tk.trimLeft == tk then tk else "" } match info with | SourceInfo.original ss _ _ _ => -- preserve non-whitespace content (i.e. comments) let ss' := ss.trim if !ss'.isEmpty then let ws := { ss with startPos := ss'.stopPos } if ws.contains '\n' then do -- Indentation is automatically increased when entering a category, but comments should be aligned -- with the actual token, so dedent indent (push s!"{ss'}\n") (some ((0:Int) - Std.Format.getIndent (← getOptions))) else push s!"{ss'} " modify fun st => { st with leadWord := "" } | _ => pure () @[combinatorFormatter Lean.Parser.symbolNoAntiquot] def symbolNoAntiquot.formatter (sym : String) : Formatter := do let stx ← getCur if stx.isToken sym then do let (Syntax.atom info _) ← pure stx | unreachable! pushToken info sym goLeft else do trace[PrettyPrinter.format.backtrack] "unexpected syntax '{format stx}', expected symbol '{sym}'" throwBacktrack @[combinatorFormatter Lean.Parser.nonReservedSymbolNoAntiquot] def nonReservedSymbolNoAntiquot.formatter := symbolNoAntiquot.formatter @[combinatorFormatter Lean.Parser.rawCh] def rawCh.formatter (ch : Char) := symbolNoAntiquot.formatter ch.toString @[combinatorFormatter Lean.Parser.unicodeSymbolNoAntiquot] def unicodeSymbolNoAntiquot.formatter (sym asciiSym : String) : Formatter := do let Syntax.atom info val ← getCur | throwError m!"not an atom: {← getCur}" if val == sym.trim then pushToken info sym else pushToken info asciiSym; goLeft @[combinatorFormatter Lean.Parser.identNoAntiquot] def identNoAntiquot.formatter : Formatter := do checkKind identKind let Syntax.ident info _ id _ ← getCur | throwError m!"not an ident: {← getCur}" let id := id.simpMacroScopes pushToken info id.toString goLeft @[combinatorFormatter Lean.Parser.rawIdentNoAntiquot] def rawIdentNoAntiquot.formatter : Formatter := do checkKind identKind let Syntax.ident info _ id _ ← getCur | throwError m!"not an ident: {← getCur}" pushToken info id.toString goLeft @[combinatorFormatter Lean.Parser.identEq] def identEq.formatter (id : Name) := rawIdentNoAntiquot.formatter def visitAtom (k : SyntaxNodeKind) : Formatter := do let stx ← getCur if k != Name.anonymous then checkKind k let Syntax.atom info val ← pure $ stx.ifNode (fun n => n.getArg 0) (fun _ => stx) | throwError m!"not an atom: {stx}" pushToken info val goLeft @[combinatorFormatter Lean.Parser.charLitNoAntiquot] def charLitNoAntiquot.formatter := visitAtom charLitKind @[combinatorFormatter Lean.Parser.strLitNoAntiquot] def strLitNoAntiquot.formatter := visitAtom strLitKind @[combinatorFormatter Lean.Parser.nameLitNoAntiquot] def nameLitNoAntiquot.formatter := visitAtom nameLitKind @[combinatorFormatter Lean.Parser.numLitNoAntiquot] def numLitNoAntiquot.formatter := visitAtom numLitKind @[combinatorFormatter Lean.Parser.scientificLitNoAntiquot] def scientificLitNoAntiquot.formatter := visitAtom scientificLitKind @[combinatorFormatter Lean.Parser.fieldIdx] def fieldIdx.formatter := visitAtom fieldIdxKind @[combinatorFormatter Lean.Parser.manyNoAntiquot] def manyNoAntiquot.formatter (p : Formatter) : Formatter := do let stx ← getCur visitArgs $ stx.getArgs.size.forM fun _ => p @[combinatorFormatter Lean.Parser.many1NoAntiquot] def many1NoAntiquot.formatter (p : Formatter) : Formatter := manyNoAntiquot.formatter p @[combinatorFormatter Lean.Parser.optionalNoAntiquot] def optionalNoAntiquot.formatter (p : Formatter) : Formatter := visitArgs p @[combinatorFormatter Lean.Parser.many1Unbox] def many1Unbox.formatter (p : Formatter) : Formatter := do let stx ← getCur if stx.getKind == nullKind then do manyNoAntiquot.formatter p else p @[combinatorFormatter Lean.Parser.sepByNoAntiquot] def sepByNoAntiquot.formatter (p pSep : Formatter) : Formatter := do let stx ← getCur visitArgs $ (List.range stx.getArgs.size).reverse.forM $ fun i => if i % 2 == 0 then p else pSep @[combinatorFormatter Lean.Parser.sepBy1NoAntiquot] def sepBy1NoAntiquot.formatter := sepByNoAntiquot.formatter @[combinatorFormatter Lean.Parser.withPosition] def withPosition.formatter (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.withoutPosition] def withoutPosition.formatter (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.withForbidden] def withForbidden.formatter (tk : Token) (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.withoutForbidden] def withoutForbidden.formatter (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.withoutInfo] def withoutInfo.formatter (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.setExpected] def setExpected.formatter (expected : List String) (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.incQuotDepth] def incQuotDepth.formatter (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.decQuotDepth] def decQuotDepth.formatter (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.suppressInsideQuot] def suppressInsideQuot.formatter (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.evalInsideQuot] def evalInsideQuot.formatter (declName : Name) (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.checkWsBefore] def checkWsBefore.formatter : Formatter := do let st ← get if st.leadWord != "" then pushLine @[combinatorFormatter Lean.Parser.checkPrec] def checkPrec.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkLhsPrec] def checkLhsPrec.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.setLhsPrec] def setLhsPrec.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkStackTop] def checkStackTop.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkNoWsBefore] def checkNoWsBefore.formatter : Formatter := -- prevent automatic whitespace insertion modify fun st => { st with leadWord := "" } @[combinatorFormatter Lean.Parser.checkLinebreakBefore] def checkLinebreakBefore.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkTailWs] def checkTailWs.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkColGe] def checkColGe.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkColGt] def checkColGt.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkLineEq] def checkLineEq.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.eoi] def eoi.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.notFollowedByCategoryToken] def notFollowedByCategoryToken.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkNoImmediateColon] def checkNoImmediateColon.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkInsideQuot] def checkInsideQuot.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkOutsideQuot] def checkOutsideQuot.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.skip] def skip.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.pushNone] def pushNone.formatter : Formatter := goLeft @[combinatorFormatter Lean.Parser.withOpenDecl] def withOpenDecl.formatter (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.withOpen] def withOpen.formatter (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.interpolatedStr] def interpolatedStr.formatter (p : Formatter) : Formatter := do visitArgs $ (← getCur).getArgs.reverse.forM fun chunk => match chunk.isLit? interpolatedStrLitKind with | some str => push str *> goLeft | none => p @[combinatorFormatter Lean.Parser.dbgTraceState] def dbgTraceState.formatter (label : String) (p : Formatter) : Formatter := p @[combinatorFormatter ite, macroInline] def ite {α : Type} (c : Prop) [h : Decidable c] (t e : Formatter) : Formatter := if c then t else e abbrev FormatterAliasValue := AliasValue Formatter builtin_initialize formatterAliasesRef : IO.Ref (NameMap FormatterAliasValue) ← IO.mkRef {} def registerAlias (aliasName : Name) (v : FormatterAliasValue) : IO Unit := do Parser.registerAliasCore formatterAliasesRef aliasName v instance : Coe Formatter FormatterAliasValue := { coe := AliasValue.const } instance : Coe (Formatter → Formatter) FormatterAliasValue := { coe := AliasValue.unary } instance : Coe (Formatter → Formatter → Formatter) FormatterAliasValue := { coe := AliasValue.binary } end Formatter open Formatter def format (formatter : Formatter) (stx : Syntax) : CoreM Format := do trace[PrettyPrinter.format.input] "{Std.format stx}" let options ← getOptions let table ← Parser.builtinTokenTable.get catchInternalId backtrackExceptionId (do let (_, st) ← (concat formatter { table := table, options := options }).run { stxTrav := Syntax.Traverser.fromSyntax stx }; pure $ Format.fill $ st.stack.get! 0) (fun _ => throwError "format: uncaught backtrack exception") def formatTerm := format $ categoryParser.formatter `term def formatTactic := format $ categoryParser.formatter `tactic def formatCommand := format $ categoryParser.formatter `command builtin_initialize registerTraceClass `PrettyPrinter.format; end PrettyPrinter end Lean
b8743e3ddafa394a83aa3382cffcdf629062a1ec
6094e25ea0b7699e642463b48e51b2ead6ddc23f
/library/algebra/group.lean
10d6fbe31e6214918cfc6a407bd9d99333ad56c2
[ "Apache-2.0" ]
permissive
gbaz/lean
a7835c4e3006fbbb079e8f8ffe18aacc45adebfb
a501c308be3acaa50a2c0610ce2e0d71becf8032
refs/heads/master
1,611,198,791,433
1,451,339,111,000
1,451,339,111,000
48,713,797
0
0
null
1,451,338,939,000
1,451,338,939,000
null
UTF-8
Lean
false
false
24,820
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura Various multiplicative and additive structures. Partially modeled on Isabelle's library. -/ import logic.eq data.unit data.sigma data.prod import algebra.binary algebra.priority open eq eq.ops -- note: ⁻¹ will be overloaded open binary variable {A : Type} /- semigroup -/ structure semigroup [class] (A : Type) extends has_mul A := (mul_assoc : ∀a b c, mul (mul a b) c = mul a (mul b c)) theorem mul.assoc [semigroup A] (a b c : A) : a * b * c = a * (b * c) := !semigroup.mul_assoc structure comm_semigroup [class] (A : Type) extends semigroup A := (mul_comm : ∀a b, mul a b = mul b a) theorem mul.comm [comm_semigroup A] (a b : A) : a * b = b * a := !comm_semigroup.mul_comm theorem mul.left_comm [comm_semigroup A] (a b c : A) : a * (b * c) = b * (a * c) := binary.left_comm (@mul.comm A _) (@mul.assoc A _) a b c theorem mul.right_comm [comm_semigroup A] (a b c : A) : (a * b) * c = (a * c) * b := binary.right_comm (@mul.comm A _) (@mul.assoc A _) a b c structure left_cancel_semigroup [class] (A : Type) extends semigroup A := (mul_left_cancel : ∀a b c, mul a b = mul a c → b = c) theorem mul.left_cancel [left_cancel_semigroup A] {a b c : A} : a * b = a * c → b = c := !left_cancel_semigroup.mul_left_cancel abbreviation eq_of_mul_eq_mul_left' := @mul.left_cancel structure right_cancel_semigroup [class] (A : Type) extends semigroup A := (mul_right_cancel : ∀a b c, mul a b = mul c b → a = c) theorem mul.right_cancel [right_cancel_semigroup A] {a b c : A} : a * b = c * b → a = c := !right_cancel_semigroup.mul_right_cancel abbreviation eq_of_mul_eq_mul_right' := @mul.right_cancel /- additive semigroup -/ structure add_semigroup [class] (A : Type) extends has_add A := (add_assoc : ∀a b c, add (add a b) c = add a (add b c)) theorem add.assoc [add_semigroup A] (a b c : A) : a + b + c = a + (b + c) := !add_semigroup.add_assoc structure add_comm_semigroup [class] (A : Type) extends add_semigroup A := (add_comm : ∀a b, add a b = add b a) theorem add.comm [add_comm_semigroup A] (a b : A) : a + b = b + a := !add_comm_semigroup.add_comm theorem add.left_comm [add_comm_semigroup A] (a b c : A) : a + (b + c) = b + (a + c) := binary.left_comm (@add.comm A _) (@add.assoc A _) a b c theorem add.right_comm [add_comm_semigroup A] (a b c : A) : (a + b) + c = (a + c) + b := binary.right_comm (@add.comm A _) (@add.assoc A _) a b c structure add_left_cancel_semigroup [class] (A : Type) extends add_semigroup A := (add_left_cancel : ∀a b c, add a b = add a c → b = c) theorem add.left_cancel [add_left_cancel_semigroup A] {a b c : A} : a + b = a + c → b = c := !add_left_cancel_semigroup.add_left_cancel abbreviation eq_of_add_eq_add_left := @add.left_cancel structure add_right_cancel_semigroup [class] (A : Type) extends add_semigroup A := (add_right_cancel : ∀a b c, add a b = add c b → a = c) theorem add.right_cancel [add_right_cancel_semigroup A] {a b c : A} : a + b = c + b → a = c := !add_right_cancel_semigroup.add_right_cancel abbreviation eq_of_add_eq_add_right := @add.right_cancel /- monoid -/ structure monoid [class] (A : Type) extends semigroup A, has_one A := (one_mul : ∀a, mul one a = a) (mul_one : ∀a, mul a one = a) theorem one_mul [monoid A] (a : A) : 1 * a = a := !monoid.one_mul theorem mul_one [monoid A] (a : A) : a * 1 = a := !monoid.mul_one structure comm_monoid [class] (A : Type) extends monoid A, comm_semigroup A /- additive monoid -/ structure add_monoid [class] (A : Type) extends add_semigroup A, has_zero A := (zero_add : ∀a, add zero a = a) (add_zero : ∀a, add a zero = a) theorem zero_add [add_monoid A] (a : A) : 0 + a = a := !add_monoid.zero_add theorem add_zero [add_monoid A] (a : A) : a + 0 = a := !add_monoid.add_zero structure add_comm_monoid [class] (A : Type) extends add_monoid A, add_comm_semigroup A definition add_monoid.to_monoid {A : Type} [add_monoid A] : monoid A := ⦃ monoid, mul := add_monoid.add, mul_assoc := add_monoid.add_assoc, one := add_monoid.zero A, mul_one := add_monoid.add_zero, one_mul := add_monoid.zero_add ⦄ definition add_comm_monoid.to_comm_monoid {A : Type} [add_comm_monoid A] : comm_monoid A := ⦃ comm_monoid, add_monoid.to_monoid, mul_comm := add_comm_monoid.add_comm ⦄ section add_comm_monoid variables [add_comm_monoid A] theorem add_comm_three (a b c : A) : a + b + c = c + b + a := by rewrite [{a + _}add.comm, {_ + c}add.comm, -*add.assoc] theorem add.comm4 : ∀ (n m k l : A), n + m + (k + l) = n + k + (m + l) := comm4 add.comm add.assoc end add_comm_monoid /- group -/ structure group [class] (A : Type) extends monoid A, has_inv A := (mul_left_inv : ∀a, mul (inv a) a = one) -- Note: with more work, we could derive the axiom one_mul section group variable [group A] theorem mul.left_inv (a : A) : a⁻¹ * a = 1 := !group.mul_left_inv theorem inv_mul_cancel_left (a b : A) : a⁻¹ * (a * b) = b := by rewrite [-mul.assoc, mul.left_inv, one_mul] theorem inv_mul_cancel_right (a b : A) : a * b⁻¹ * b = a := by rewrite [mul.assoc, mul.left_inv, mul_one] theorem inv_eq_of_mul_eq_one {a b : A} (H : a * b = 1) : a⁻¹ = b := by rewrite [-mul_one a⁻¹, -H, inv_mul_cancel_left] theorem one_inv : 1⁻¹ = (1 : A) := inv_eq_of_mul_eq_one (one_mul 1) theorem inv_inv (a : A) : (a⁻¹)⁻¹ = a := inv_eq_of_mul_eq_one (mul.left_inv a) theorem inv.inj {a b : A} (H : a⁻¹ = b⁻¹) : a = b := by rewrite [-inv_inv a, H, inv_inv b] theorem inv_eq_inv_iff_eq (a b : A) : a⁻¹ = b⁻¹ ↔ a = b := iff.intro (assume H, inv.inj H) (assume H, congr_arg _ H) theorem inv_eq_one_iff_eq_one (a : A) : a⁻¹ = 1 ↔ a = 1 := one_inv ▸ inv_eq_inv_iff_eq a 1 theorem eq_one_of_inv_eq_one (a : A) : a⁻¹ = 1 → a = 1 := iff.mp !inv_eq_one_iff_eq_one theorem eq_inv_of_eq_inv {a b : A} (H : a = b⁻¹) : b = a⁻¹ := by rewrite [H, inv_inv] theorem eq_inv_iff_eq_inv (a b : A) : a = b⁻¹ ↔ b = a⁻¹ := iff.intro !eq_inv_of_eq_inv !eq_inv_of_eq_inv theorem eq_inv_of_mul_eq_one {a b : A} (H : a * b = 1) : a = b⁻¹ := begin apply eq_inv_of_eq_inv, symmetry, exact inv_eq_of_mul_eq_one H end theorem mul.right_inv (a : A) : a * a⁻¹ = 1 := calc a * a⁻¹ = (a⁻¹)⁻¹ * a⁻¹ : inv_inv ... = 1 : mul.left_inv theorem mul_inv_cancel_left (a b : A) : a * (a⁻¹ * b) = b := calc a * (a⁻¹ * b) = a * a⁻¹ * b : by rewrite mul.assoc ... = 1 * b : mul.right_inv ... = b : one_mul theorem mul_inv_cancel_right (a b : A) : a * b * b⁻¹ = a := calc a * b * b⁻¹ = a * (b * b⁻¹) : mul.assoc ... = a * 1 : mul.right_inv ... = a : mul_one theorem mul_inv (a b : A) : (a * b)⁻¹ = b⁻¹ * a⁻¹ := inv_eq_of_mul_eq_one (calc a * b * (b⁻¹ * a⁻¹) = a * (b * (b⁻¹ * a⁻¹)) : mul.assoc ... = a * a⁻¹ : mul_inv_cancel_left ... = 1 : mul.right_inv) theorem eq_of_mul_inv_eq_one {a b : A} (H : a * b⁻¹ = 1) : a = b := calc a = a * b⁻¹ * b : by rewrite inv_mul_cancel_right ... = 1 * b : H ... = b : one_mul theorem eq_mul_inv_of_mul_eq {a b c : A} (H : a * c = b) : a = b * c⁻¹ := by rewrite [-H, mul_inv_cancel_right] theorem eq_inv_mul_of_mul_eq {a b c : A} (H : b * a = c) : a = b⁻¹ * c := by rewrite [-H, inv_mul_cancel_left] theorem inv_mul_eq_of_eq_mul {a b c : A} (H : b = a * c) : a⁻¹ * b = c := by rewrite [H, inv_mul_cancel_left] theorem mul_inv_eq_of_eq_mul {a b c : A} (H : a = c * b) : a * b⁻¹ = c := by rewrite [H, mul_inv_cancel_right] theorem eq_mul_of_mul_inv_eq {a b c : A} (H : a * c⁻¹ = b) : a = b * c := !inv_inv ▸ (eq_mul_inv_of_mul_eq H) theorem eq_mul_of_inv_mul_eq {a b c : A} (H : b⁻¹ * a = c) : a = b * c := !inv_inv ▸ (eq_inv_mul_of_mul_eq H) theorem mul_eq_of_eq_inv_mul {a b c : A} (H : b = a⁻¹ * c) : a * b = c := !inv_inv ▸ (inv_mul_eq_of_eq_mul H) theorem mul_eq_of_eq_mul_inv {a b c : A} (H : a = c * b⁻¹) : a * b = c := !inv_inv ▸ (mul_inv_eq_of_eq_mul H) theorem mul_eq_iff_eq_inv_mul (a b c : A) : a * b = c ↔ b = a⁻¹ * c := iff.intro eq_inv_mul_of_mul_eq mul_eq_of_eq_inv_mul theorem mul_eq_iff_eq_mul_inv (a b c : A) : a * b = c ↔ a = c * b⁻¹ := iff.intro eq_mul_inv_of_mul_eq mul_eq_of_eq_mul_inv theorem mul_left_cancel {a b c : A} (H : a * b = a * c) : b = c := by rewrite [-inv_mul_cancel_left a b, H, inv_mul_cancel_left] theorem mul_right_cancel {a b c : A} (H : a * b = c * b) : a = c := by rewrite [-mul_inv_cancel_right a b, H, mul_inv_cancel_right] theorem mul_eq_one_of_mul_eq_one {a b : A} (H : b * a = 1) : a * b = 1 := by rewrite [-inv_eq_of_mul_eq_one H, mul.left_inv] theorem mul_eq_one_iff_mul_eq_one (a b : A) : a * b = 1 ↔ b * a = 1 := iff.intro !mul_eq_one_of_mul_eq_one !mul_eq_one_of_mul_eq_one definition conj_by (g a : A) := g * a * g⁻¹ definition is_conjugate (a b : A) := ∃ x, conj_by x b = a local infixl ` ~ ` := is_conjugate local infixr ` ∘c `:55 := conj_by lemma conj_compose (f g a : A) : f ∘c g ∘c a = f*g ∘c a := calc f ∘c g ∘c a = f * (g * a * g⁻¹) * f⁻¹ : rfl ... = f * (g * a) * g⁻¹ * f⁻¹ : mul.assoc ... = f * g * a * g⁻¹ * f⁻¹ : mul.assoc ... = f * g * a * (g⁻¹ * f⁻¹) : mul.assoc ... = f * g * a * (f * g)⁻¹ : mul_inv lemma conj_id (a : A) : 1 ∘c a = a := calc 1 * a * 1⁻¹ = a * 1⁻¹ : one_mul ... = a * 1 : one_inv ... = a : mul_one lemma conj_one (g : A) : g ∘c 1 = 1 := calc g * 1 * g⁻¹ = g * g⁻¹ : mul_one ... = 1 : mul.right_inv lemma conj_inv_cancel (g : A) : ∀ a, g⁻¹ ∘c g ∘c a = a := assume a, calc g⁻¹ ∘c g ∘c a = g⁻¹*g ∘c a : conj_compose ... = 1 ∘c a : mul.left_inv ... = a : conj_id lemma conj_inv (g : A) : ∀ a, (g ∘c a)⁻¹ = g ∘c a⁻¹ := take a, calc (g * a * g⁻¹)⁻¹ = g⁻¹⁻¹ * (g * a)⁻¹ : mul_inv ... = g⁻¹⁻¹ * (a⁻¹ * g⁻¹) : mul_inv ... = g⁻¹⁻¹ * a⁻¹ * g⁻¹ : mul.assoc ... = g * a⁻¹ * g⁻¹ : inv_inv lemma is_conj.refl (a : A) : a ~ a := exists.intro 1 (conj_id a) lemma is_conj.symm (a b : A) : a ~ b → b ~ a := assume Pab, obtain x (Pconj : x ∘c b = a), from Pab, assert Pxinv : x⁻¹ ∘c x ∘c b = x⁻¹ ∘c a, begin congruence, assumption end, exists.intro x⁻¹ (eq.symm (conj_inv_cancel x b ▸ Pxinv)) lemma is_conj.trans (a b c : A) : a ~ b → b ~ c → a ~ c := assume Pab, assume Pbc, obtain x (Px : x ∘c b = a), from Pab, obtain y (Py : y ∘c c = b), from Pbc, exists.intro (x*y) (calc x*y ∘c c = x ∘c y ∘c c : conj_compose ... = x ∘c b : Py ... = a : Px) end group definition group.to_left_cancel_semigroup [trans_instance] [reducible] [s : group A] : left_cancel_semigroup A := ⦃ left_cancel_semigroup, s, mul_left_cancel := @mul_left_cancel A s ⦄ definition group.to_right_cancel_semigroup [trans_instance] [reducible] [s : group A] : right_cancel_semigroup A := ⦃ right_cancel_semigroup, s, mul_right_cancel := @mul_right_cancel A s ⦄ structure comm_group [class] (A : Type) extends group A, comm_monoid A /- additive group -/ structure add_group [class] (A : Type) extends add_monoid A, has_neg A := (add_left_inv : ∀a, add (neg a) a = zero) definition add_group.to_group {A : Type} [add_group A] : group A := ⦃ group, add_monoid.to_monoid, mul_left_inv := add_group.add_left_inv ⦄ section add_group variables [s : add_group A] include s theorem add.left_inv (a : A) : -a + a = 0 := !add_group.add_left_inv theorem neg_add_cancel_left (a b : A) : -a + (a + b) = b := by rewrite [-add.assoc, add.left_inv, zero_add] theorem neg_add_cancel_right (a b : A) : a + -b + b = a := by rewrite [add.assoc, add.left_inv, add_zero] theorem neg_eq_of_add_eq_zero {a b : A} (H : a + b = 0) : -a = b := by rewrite [-add_zero, -H, neg_add_cancel_left] theorem neg_zero : -0 = (0 : A) := neg_eq_of_add_eq_zero (zero_add 0) theorem neg_neg (a : A) : -(-a) = a := neg_eq_of_add_eq_zero (add.left_inv a) theorem eq_neg_of_add_eq_zero {a b : A} (H : a + b = 0) : a = -b := by rewrite [-neg_eq_of_add_eq_zero H, neg_neg] theorem neg.inj {a b : A} (H : -a = -b) : a = b := calc a = -(-a) : neg_neg ... = b : neg_eq_of_add_eq_zero (H⁻¹ ▸ (add.left_inv _)) theorem neg_eq_neg_iff_eq (a b : A) : -a = -b ↔ a = b := iff.intro (assume H, neg.inj H) (assume H, congr_arg _ H) theorem eq_of_neg_eq_neg {a b : A} : -a = -b → a = b := iff.mp !neg_eq_neg_iff_eq theorem neg_eq_zero_iff_eq_zero (a : A) : -a = 0 ↔ a = 0 := neg_zero ▸ !neg_eq_neg_iff_eq theorem eq_zero_of_neg_eq_zero {a : A} : -a = 0 → a = 0 := iff.mp !neg_eq_zero_iff_eq_zero theorem eq_neg_of_eq_neg {a b : A} (H : a = -b) : b = -a := H⁻¹ ▸ (neg_neg b)⁻¹ theorem eq_neg_iff_eq_neg (a b : A) : a = -b ↔ b = -a := iff.intro !eq_neg_of_eq_neg !eq_neg_of_eq_neg theorem add.right_inv (a : A) : a + -a = 0 := calc a + -a = -(-a) + -a : neg_neg ... = 0 : add.left_inv theorem add_neg_cancel_left (a b : A) : a + (-a + b) = b := by rewrite [-add.assoc, add.right_inv, zero_add] theorem add_neg_cancel_right (a b : A) : a + b + -b = a := by rewrite [add.assoc, add.right_inv, add_zero] theorem neg_add_rev (a b : A) : -(a + b) = -b + -a := neg_eq_of_add_eq_zero begin rewrite [add.assoc, add_neg_cancel_left, add.right_inv] end -- TODO: delete these in favor of sub rules? theorem eq_add_neg_of_add_eq {a b c : A} (H : a + c = b) : a = b + -c := H ▸ !add_neg_cancel_right⁻¹ theorem eq_neg_add_of_add_eq {a b c : A} (H : b + a = c) : a = -b + c := H ▸ !neg_add_cancel_left⁻¹ theorem neg_add_eq_of_eq_add {a b c : A} (H : b = a + c) : -a + b = c := H⁻¹ ▸ !neg_add_cancel_left theorem add_neg_eq_of_eq_add {a b c : A} (H : a = c + b) : a + -b = c := H⁻¹ ▸ !add_neg_cancel_right theorem eq_add_of_add_neg_eq {a b c : A} (H : a + -c = b) : a = b + c := !neg_neg ▸ (eq_add_neg_of_add_eq H) theorem eq_add_of_neg_add_eq {a b c : A} (H : -b + a = c) : a = b + c := !neg_neg ▸ (eq_neg_add_of_add_eq H) theorem add_eq_of_eq_neg_add {a b c : A} (H : b = -a + c) : a + b = c := !neg_neg ▸ (neg_add_eq_of_eq_add H) theorem add_eq_of_eq_add_neg {a b c : A} (H : a = c + -b) : a + b = c := !neg_neg ▸ (add_neg_eq_of_eq_add H) theorem add_eq_iff_eq_neg_add (a b c : A) : a + b = c ↔ b = -a + c := iff.intro eq_neg_add_of_add_eq add_eq_of_eq_neg_add theorem add_eq_iff_eq_add_neg (a b c : A) : a + b = c ↔ a = c + -b := iff.intro eq_add_neg_of_add_eq add_eq_of_eq_add_neg theorem add_left_cancel {a b c : A} (H : a + b = a + c) : b = c := calc b = -a + (a + b) : !neg_add_cancel_left⁻¹ ... = -a + (a + c) : H ... = c : neg_add_cancel_left theorem add_right_cancel {a b c : A} (H : a + b = c + b) : a = c := calc a = (a + b) + -b : !add_neg_cancel_right⁻¹ ... = (c + b) + -b : H ... = c : add_neg_cancel_right definition add_group.to_left_cancel_semigroup [trans_instance] [reducible] : add_left_cancel_semigroup A := ⦃ add_left_cancel_semigroup, s, add_left_cancel := @add_left_cancel A s ⦄ definition add_group.to_add_right_cancel_semigroup [trans_instance] [reducible] : add_right_cancel_semigroup A := ⦃ add_right_cancel_semigroup, s, add_right_cancel := @add_right_cancel A s ⦄ theorem add_neg_eq_neg_add_rev {a b : A} : a + -b = -(b + -a) := by rewrite [neg_add_rev, neg_neg] /- sub -/ -- TODO: derive corresponding facts for div in a field protected definition algebra.sub [reducible] (a b : A) : A := a + -b definition add_group_has_sub [reducible] [instance] : has_sub A := has_sub.mk algebra.sub theorem sub_eq_add_neg (a b : A) : a - b = a + -b := rfl theorem sub_self (a : A) : a - a = 0 := !add.right_inv theorem sub_add_cancel (a b : A) : a - b + b = a := !neg_add_cancel_right theorem add_sub_cancel (a b : A) : a + b - b = a := !add_neg_cancel_right theorem eq_of_sub_eq_zero {a b : A} (H : a - b = 0) : a = b := calc a = (a - b) + b : !sub_add_cancel⁻¹ ... = 0 + b : H ... = b : zero_add theorem eq_iff_sub_eq_zero (a b : A) : a = b ↔ a - b = 0 := iff.intro (assume H, H ▸ !sub_self) (assume H, eq_of_sub_eq_zero H) theorem zero_sub (a : A) : 0 - a = -a := !zero_add theorem sub_zero (a : A) : a - 0 = a := by rewrite [sub_eq_add_neg, neg_zero, add_zero] theorem sub_neg_eq_add (a b : A) : a - (-b) = a + b := by change a + -(-b) = a + b; rewrite neg_neg theorem neg_sub (a b : A) : -(a - b) = b - a := neg_eq_of_add_eq_zero (calc a - b + (b - a) = a - b + b - a : by krewrite -add.assoc ... = a - a : sub_add_cancel ... = 0 : sub_self) theorem add_sub (a b c : A) : a + (b - c) = a + b - c := !add.assoc⁻¹ theorem sub_add_eq_sub_sub_swap (a b c : A) : a - (b + c) = a - c - b := calc a - (b + c) = a + (-c - b) : by rewrite [sub_eq_add_neg, neg_add_rev] ... = a - c - b : by krewrite -add.assoc theorem sub_eq_iff_eq_add (a b c : A) : a - b = c ↔ a = c + b := iff.intro (assume H, eq_add_of_add_neg_eq H) (assume H, add_neg_eq_of_eq_add H) theorem eq_sub_iff_add_eq (a b c : A) : a = b - c ↔ a + c = b := iff.intro (assume H, add_eq_of_eq_add_neg H) (assume H, eq_add_neg_of_add_eq H) theorem eq_iff_eq_of_sub_eq_sub {a b c d : A} (H : a - b = c - d) : a = b ↔ c = d := calc a = b ↔ a - b = 0 : eq_iff_sub_eq_zero ... = (c - d = 0) : H ... ↔ c = d : iff.symm (eq_iff_sub_eq_zero c d) theorem eq_sub_of_add_eq {a b c : A} (H : a + c = b) : a = b - c := !eq_add_neg_of_add_eq H theorem sub_eq_of_eq_add {a b c : A} (H : a = c + b) : a - b = c := !add_neg_eq_of_eq_add H theorem eq_add_of_sub_eq {a b c : A} (H : a - c = b) : a = b + c := eq_add_of_add_neg_eq H theorem add_eq_of_eq_sub {a b c : A} (H : a = c - b) : a + b = c := add_eq_of_eq_add_neg H end add_group structure add_comm_group [class] (A : Type) extends add_group A, add_comm_monoid A section add_comm_group variable [s : add_comm_group A] include s theorem sub_add_eq_sub_sub (a b c : A) : a - (b + c) = a - b - c := !add.comm ▸ !sub_add_eq_sub_sub_swap theorem neg_add_eq_sub (a b : A) : -a + b = b - a := !add.comm theorem neg_add (a b : A) : -(a + b) = -a + -b := add.comm (-b) (-a) ▸ neg_add_rev a b theorem sub_add_eq_add_sub (a b c : A) : a - b + c = a + c - b := !add.right_comm theorem sub_sub (a b c : A) : a - b - c = a - (b + c) := by rewrite [▸ a + -b + -c = _, add.assoc, -neg_add] theorem add_sub_add_left_eq_sub (a b c : A) : (c + a) - (c + b) = a - b := by rewrite [sub_add_eq_sub_sub, (add.comm c a), add_sub_cancel] theorem eq_sub_of_add_eq' {a b c : A} (H : c + a = b) : a = b - c := !eq_sub_of_add_eq (!add.comm ▸ H) theorem sub_eq_of_eq_add' {a b c : A} (H : a = b + c) : a - b = c := !sub_eq_of_eq_add (!add.comm ▸ H) theorem eq_add_of_sub_eq' {a b c : A} (H : a - b = c) : a = b + c := !add.comm ▸ eq_add_of_sub_eq H theorem add_eq_of_eq_sub' {a b c : A} (H : b = c - a) : a + b = c := !add.comm ▸ add_eq_of_eq_sub H theorem sub_sub_self (a b : A) : a - (a - b) = b := by rewrite [sub_eq_add_neg, neg_sub, add.comm, sub_add_cancel] theorem add_sub_comm (a b c d : A) : a + b - (c + d) = (a - c) + (b - d) := by rewrite [sub_add_eq_sub_sub, -sub_add_eq_add_sub a c b, add_sub] theorem sub_eq_sub_add_sub (a b c : A) : a - b = c - b + (a - c) := by rewrite [add_sub, sub_add_cancel] ⬝ !add.comm theorem neg_neg_sub_neg (a b : A) : - (-a - -b) = a - b := by rewrite [neg_sub, sub_neg_eq_add, neg_add_eq_sub] end add_comm_group definition group_of_add_group (A : Type) [G : add_group A] : group A := ⦃group, mul := has_add.add, mul_assoc := add.assoc, one := !has_zero.zero, one_mul := zero_add, mul_one := add_zero, inv := has_neg.neg, mul_left_inv := add.left_inv⦄ namespace norm_num reveal add.assoc definition add1 [has_add A] [has_one A] (a : A) : A := add a one theorem add_comm_four [add_comm_semigroup A] (a b : A) : a + a + (b + b) = (a + b) + (a + b) := by rewrite [-add.assoc at {1}, add.comm, {a + b}add.comm at {1}, *add.assoc] theorem add_comm_middle [add_comm_semigroup A] (a b c : A) : a + b + c = a + c + b := by rewrite [add.assoc, add.comm b, -add.assoc] theorem bit0_add_bit0 [add_comm_semigroup A] (a b : A) : bit0 a + bit0 b = bit0 (a + b) := !add_comm_four theorem bit0_add_bit0_helper [add_comm_semigroup A] (a b t : A) (H : a + b = t) : bit0 a + bit0 b = bit0 t := by rewrite -H; apply bit0_add_bit0 theorem bit1_add_bit0 [add_comm_semigroup A] [has_one A] (a b : A) : bit1 a + bit0 b = bit1 (a + b) := begin rewrite [↑bit0, ↑bit1, add_comm_middle], congruence, apply add_comm_four end theorem bit1_add_bit0_helper [add_comm_semigroup A] [has_one A] (a b t : A) (H : a + b = t) : bit1 a + bit0 b = bit1 t := by rewrite -H; apply bit1_add_bit0 theorem bit0_add_bit1 [add_comm_semigroup A] [has_one A] (a b : A) : bit0 a + bit1 b = bit1 (a + b) := by rewrite [{bit0 a + bit1 b}add.comm,{a + b}add.comm]; exact bit1_add_bit0 b a theorem bit0_add_bit1_helper [add_comm_semigroup A] [has_one A] (a b t : A) (H : a + b = t) : bit0 a + bit1 b = bit1 t := by rewrite -H; apply bit0_add_bit1 theorem bit1_add_bit1 [add_comm_semigroup A] [has_one A] (a b : A) : bit1 a + bit1 b = bit0 (add1 (a + b)) := begin rewrite ↑[bit0, bit1, add1], rewrite [*add.assoc, {_ + (b + 1)}add.comm, {_ + (b + 1 + _)}add.comm, {_ + (b + 1 + _ + _)}add.comm, *add.assoc, {1 + a}add.comm, -{b + (a + 1)}add.assoc, {b + a}add.comm, *add.assoc] end theorem bit1_add_bit1_helper [add_comm_semigroup A] [has_one A] (a b t s: A) (H : (a + b) = t) (H2 : add1 t = s) : bit1 a + bit1 b = bit0 s := begin rewrite [-H2, -H], apply bit1_add_bit1 end theorem bin_add_zero [add_monoid A] (a : A) : a + zero = a := !add_zero theorem bin_zero_add [add_monoid A] (a : A) : zero + a = a := !zero_add theorem one_add_bit0 [add_comm_semigroup A] [has_one A] (a : A) : one + bit0 a = bit1 a := begin rewrite ↑[bit0, bit1], rewrite add.comm end theorem bit0_add_one [has_add A] [has_one A] (a : A) : bit0 a + one = bit1 a := rfl theorem bit1_add_one [has_add A] [has_one A] (a : A) : bit1 a + one = add1 (bit1 a) := rfl theorem bit1_add_one_helper [has_add A] [has_one A] (a t : A) (H : add1 (bit1 a) = t) : bit1 a + one = t := by rewrite -H theorem one_add_bit1 [add_comm_semigroup A] [has_one A] (a : A) : one + bit1 a = add1 (bit1 a) := !add.comm theorem one_add_bit1_helper [add_comm_semigroup A] [has_one A] (a t : A) (H : add1 (bit1 a) = t) : one + bit1 a = t := by rewrite -H; apply one_add_bit1 theorem add1_bit0 [has_add A] [has_one A] (a : A) : add1 (bit0 a) = bit1 a := rfl theorem add1_bit1 [add_comm_semigroup A] [has_one A] (a : A) : add1 (bit1 a) = bit0 (add1 a) := begin rewrite ↑[add1, bit1, bit0], rewrite [add.assoc, add_comm_four] end theorem add1_bit1_helper [add_comm_semigroup A] [has_one A] (a t : A) (H : add1 a = t) : add1 (bit1 a) = bit0 t := by rewrite -H; apply add1_bit1 theorem add1_one [has_add A] [has_one A] : add1 (one : A) = bit0 one := rfl theorem add1_zero [add_monoid A] [has_one A] : add1 (zero : A) = one := begin rewrite [↑add1, zero_add] end theorem one_add_one [has_add A] [has_one A] : (one : A) + one = bit0 one := rfl theorem subst_into_sum [has_add A] (l r tl tr t : A) (prl : l = tl) (prr : r = tr) (prt : tl + tr = t) : l + r = t := by rewrite [prl, prr, prt] theorem neg_zero_helper [add_group A] (a : A) (H : a = 0) : - a = 0 := by rewrite [H, neg_zero] end norm_num attribute [simp] zero_add add_zero one_mul mul_one at simplifier.unit attribute [simp] neg_neg sub_eq_add_neg at simplifier.neg attribute [simp] add.assoc add.comm add.left_comm mul.left_comm mul.comm mul.assoc at simplifier.ac
ba6be3e69d7bff09a2c0528ab24b25970c007b62
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/meta/smt/congruence_closure_auto.lean
017886d49d67a0685c88e295149e3175669138be
[]
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
574
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.meta.interactive_base import Mathlib.Lean3Lib.init.meta.tactic import Mathlib.Lean3Lib.init.meta.set_get_option_tactics universes l namespace Mathlib /- If tt, congruence closure will treat implicit instance arguments as constants. -/ structure cc_config where ignore_instances : Bool ac : Bool ho_fns : Option (List name) em : Bool end Mathlib
bb741376f6e8613c95c5cc105e67f2506124cbd5
9dc8cecdf3c4634764a18254e94d43da07142918
/src/analysis/special_functions/trigonometric/inverse_deriv.lean
c449c042d7303e4012186a50a564acee69b8a821
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
7,723
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Benjamin Davidson -/ import analysis.special_functions.trigonometric.inverse import analysis.special_functions.trigonometric.deriv /-! # derivatives of the inverse trigonometric functions Derivatives of `arcsin` and `arccos`. -/ noncomputable theory open_locale classical topological_space filter open set filter open_locale real namespace real section arcsin lemma deriv_arcsin_aux {x : ℝ} (h₁ : x ≠ -1) (h₂ : x ≠ 1) : has_strict_deriv_at arcsin (1 / sqrt (1 - x ^ 2)) x ∧ cont_diff_at ℝ ⊤ arcsin x := begin cases h₁.lt_or_lt with h₁ h₁, { have : 1 - x ^ 2 < 0, by nlinarith [h₁], rw [sqrt_eq_zero'.2 this.le, div_zero], have : arcsin =ᶠ[𝓝 x] λ _, -(π / 2) := (gt_mem_nhds h₁).mono (λ y hy, arcsin_of_le_neg_one hy.le), exact ⟨(has_strict_deriv_at_const _ _).congr_of_eventually_eq this.symm, cont_diff_at_const.congr_of_eventually_eq this⟩ }, cases h₂.lt_or_lt with h₂ h₂, { have : 0 < sqrt (1 - x ^ 2) := sqrt_pos.2 (by nlinarith [h₁, h₂]), simp only [← cos_arcsin h₁.le h₂.le, one_div] at this ⊢, exact ⟨sin_local_homeomorph.has_strict_deriv_at_symm ⟨h₁, h₂⟩ this.ne' (has_strict_deriv_at_sin _), sin_local_homeomorph.cont_diff_at_symm_deriv this.ne' ⟨h₁, h₂⟩ (has_deriv_at_sin _) cont_diff_sin.cont_diff_at⟩ }, { have : 1 - x ^ 2 < 0, by nlinarith [h₂], rw [sqrt_eq_zero'.2 this.le, div_zero], have : arcsin =ᶠ[𝓝 x] λ _, π / 2 := (lt_mem_nhds h₂).mono (λ y hy, arcsin_of_one_le hy.le), exact ⟨(has_strict_deriv_at_const _ _).congr_of_eventually_eq this.symm, cont_diff_at_const.congr_of_eventually_eq this⟩ } end lemma has_strict_deriv_at_arcsin {x : ℝ} (h₁ : x ≠ -1) (h₂ : x ≠ 1) : has_strict_deriv_at arcsin (1 / sqrt (1 - x ^ 2)) x := (deriv_arcsin_aux h₁ h₂).1 lemma has_deriv_at_arcsin {x : ℝ} (h₁ : x ≠ -1) (h₂ : x ≠ 1) : has_deriv_at arcsin (1 / sqrt (1 - x ^ 2)) x := (has_strict_deriv_at_arcsin h₁ h₂).has_deriv_at lemma cont_diff_at_arcsin {x : ℝ} (h₁ : x ≠ -1) (h₂ : x ≠ 1) {n : ℕ∞} : cont_diff_at ℝ n arcsin x := (deriv_arcsin_aux h₁ h₂).2.of_le le_top lemma has_deriv_within_at_arcsin_Ici {x : ℝ} (h : x ≠ -1) : has_deriv_within_at arcsin (1 / sqrt (1 - x ^ 2)) (Ici x) x := begin rcases em (x = 1) with (rfl|h'), { convert (has_deriv_within_at_const _ _ (π / 2)).congr _ _; simp [arcsin_of_one_le] { contextual := tt } }, { exact (has_deriv_at_arcsin h h').has_deriv_within_at } end lemma has_deriv_within_at_arcsin_Iic {x : ℝ} (h : x ≠ 1) : has_deriv_within_at arcsin (1 / sqrt (1 - x ^ 2)) (Iic x) x := begin rcases em (x = -1) with (rfl|h'), { convert (has_deriv_within_at_const _ _ (-(π / 2))).congr _ _; simp [arcsin_of_le_neg_one] { contextual := tt } }, { exact (has_deriv_at_arcsin h' h).has_deriv_within_at } end lemma differentiable_within_at_arcsin_Ici {x : ℝ} : differentiable_within_at ℝ arcsin (Ici x) x ↔ x ≠ -1 := begin refine ⟨_, λ h, (has_deriv_within_at_arcsin_Ici h).differentiable_within_at⟩, rintro h rfl, have : sin ∘ arcsin =ᶠ[𝓝[≥] (-1 : ℝ)] id, { filter_upwards [Icc_mem_nhds_within_Ici ⟨le_rfl, neg_lt_self (@zero_lt_one ℝ _ _)⟩] with x using sin_arcsin', }, have := h.has_deriv_within_at.sin.congr_of_eventually_eq this.symm (by simp), simpa using (unique_diff_on_Ici _ _ left_mem_Ici).eq_deriv _ this (has_deriv_within_at_id _ _) end lemma differentiable_within_at_arcsin_Iic {x : ℝ} : differentiable_within_at ℝ arcsin (Iic x) x ↔ x ≠ 1 := begin refine ⟨λ h, _, λ h, (has_deriv_within_at_arcsin_Iic h).differentiable_within_at⟩, rw [← neg_neg x, ← image_neg_Ici] at h, have := (h.comp (-x) differentiable_within_at_id.neg (maps_to_image _ _)).neg, simpa [(∘), differentiable_within_at_arcsin_Ici] using this end lemma differentiable_at_arcsin {x : ℝ} : differentiable_at ℝ arcsin x ↔ x ≠ -1 ∧ x ≠ 1 := ⟨λ h, ⟨differentiable_within_at_arcsin_Ici.1 h.differentiable_within_at, differentiable_within_at_arcsin_Iic.1 h.differentiable_within_at⟩, λ h, (has_deriv_at_arcsin h.1 h.2).differentiable_at⟩ @[simp] lemma deriv_arcsin : deriv arcsin = λ x, 1 / sqrt (1 - x ^ 2) := begin funext x, by_cases h : x ≠ -1 ∧ x ≠ 1, { exact (has_deriv_at_arcsin h.1 h.2).deriv }, { rw [deriv_zero_of_not_differentiable_at (mt differentiable_at_arcsin.1 h)], simp only [not_and_distrib, ne.def, not_not] at h, rcases h with (rfl|rfl); simp } end lemma differentiable_on_arcsin : differentiable_on ℝ arcsin {-1, 1}ᶜ := λ x hx, (differentiable_at_arcsin.2 ⟨λ h, hx (or.inl h), λ h, hx (or.inr h)⟩).differentiable_within_at lemma cont_diff_on_arcsin {n : ℕ∞} : cont_diff_on ℝ n arcsin {-1, 1}ᶜ := λ x hx, (cont_diff_at_arcsin (mt or.inl hx) (mt or.inr hx)).cont_diff_within_at lemma cont_diff_at_arcsin_iff {x : ℝ} {n : ℕ∞} : cont_diff_at ℝ n arcsin x ↔ n = 0 ∨ (x ≠ -1 ∧ x ≠ 1) := ⟨λ h, or_iff_not_imp_left.2 $ λ hn, differentiable_at_arcsin.1 $ h.differentiable_at $ enat.one_le_iff_ne_zero.2 hn, λ h, h.elim (λ hn, hn.symm ▸ (cont_diff_zero.2 continuous_arcsin).cont_diff_at) $ λ hx, cont_diff_at_arcsin hx.1 hx.2⟩ end arcsin section arccos lemma has_strict_deriv_at_arccos {x : ℝ} (h₁ : x ≠ -1) (h₂ : x ≠ 1) : has_strict_deriv_at arccos (-(1 / sqrt (1 - x ^ 2))) x := (has_strict_deriv_at_arcsin h₁ h₂).const_sub (π / 2) lemma has_deriv_at_arccos {x : ℝ} (h₁ : x ≠ -1) (h₂ : x ≠ 1) : has_deriv_at arccos (-(1 / sqrt (1 - x ^ 2))) x := (has_deriv_at_arcsin h₁ h₂).const_sub (π / 2) lemma cont_diff_at_arccos {x : ℝ} (h₁ : x ≠ -1) (h₂ : x ≠ 1) {n : ℕ∞} : cont_diff_at ℝ n arccos x := cont_diff_at_const.sub (cont_diff_at_arcsin h₁ h₂) lemma has_deriv_within_at_arccos_Ici {x : ℝ} (h : x ≠ -1) : has_deriv_within_at arccos (-(1 / sqrt (1 - x ^ 2))) (Ici x) x := (has_deriv_within_at_arcsin_Ici h).const_sub _ lemma has_deriv_within_at_arccos_Iic {x : ℝ} (h : x ≠ 1) : has_deriv_within_at arccos (-(1 / sqrt (1 - x ^ 2))) (Iic x) x := (has_deriv_within_at_arcsin_Iic h).const_sub _ lemma differentiable_within_at_arccos_Ici {x : ℝ} : differentiable_within_at ℝ arccos (Ici x) x ↔ x ≠ -1 := (differentiable_within_at_const_sub_iff _).trans differentiable_within_at_arcsin_Ici lemma differentiable_within_at_arccos_Iic {x : ℝ} : differentiable_within_at ℝ arccos (Iic x) x ↔ x ≠ 1 := (differentiable_within_at_const_sub_iff _).trans differentiable_within_at_arcsin_Iic lemma differentiable_at_arccos {x : ℝ} : differentiable_at ℝ arccos x ↔ x ≠ -1 ∧ x ≠ 1 := (differentiable_at_const_sub_iff _).trans differentiable_at_arcsin @[simp] lemma deriv_arccos : deriv arccos = λ x, -(1 / sqrt (1 - x ^ 2)) := funext $ λ x, (deriv_const_sub _).trans $ by simp only [deriv_arcsin] lemma differentiable_on_arccos : differentiable_on ℝ arccos {-1, 1}ᶜ := differentiable_on_arcsin.const_sub _ lemma cont_diff_on_arccos {n : ℕ∞} : cont_diff_on ℝ n arccos {-1, 1}ᶜ := cont_diff_on_const.sub cont_diff_on_arcsin lemma cont_diff_at_arccos_iff {x : ℝ} {n : ℕ∞} : cont_diff_at ℝ n arccos x ↔ n = 0 ∨ (x ≠ -1 ∧ x ≠ 1) := by refine iff.trans ⟨λ h, _, λ h, _⟩ cont_diff_at_arcsin_iff; simpa [arccos] using (@cont_diff_at_const _ _ _ _ _ _ _ _ _ _ (π / 2)).sub h end arccos end real
de5059573504dd6c5219eb6b71defcadac5f9d04
9dc8cecdf3c4634764a18254e94d43da07142918
/src/analysis/special_functions/bernstein.lean
f7532b07c6960ca607c1c844c4c19c21150f5578
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
12,756
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.order.field import ring_theory.polynomial.bernstein import topology.continuous_function.polynomial /-! # Bernstein approximations and Weierstrass' theorem We prove that the Bernstein approximations ``` ∑ k : fin (n+1), f (k/n : ℝ) * n.choose k * x^k * (1-x)^(n-k) ``` for a continuous function `f : C([0,1], ℝ)` converge uniformly to `f` as `n` tends to infinity. Our proof follows [Richard Beals' *Analysis, an introduction*][beals-analysis], §7D. The original proof, due to [Bernstein](bernstein1912) in 1912, is probabilistic, and relies on Bernoulli's theorem, which gives bounds for how quickly the observed frequencies in a Bernoulli trial approach the underlying probability. The proof here does not directly rely on Bernoulli's theorem, but can also be given a probabilistic account. * Consider a weighted coin which with probability `x` produces heads, and with probability `1-x` produces tails. * The value of `bernstein n k x` is the probability that such a coin gives exactly `k` heads in a sequence of `n` tosses. * If such an appearance of `k` heads results in a payoff of `f(k / n)`, the `n`-th Bernstein approximation for `f` evaluated at `x` is the expected payoff. * The main estimate in the proof bounds the probability that the observed frequency of heads differs from `x` by more than some `δ`, obtaining a bound of `(4 * n * δ^2)⁻¹`, irrespective of `x`. * This ensures that for `n` large, the Bernstein approximation is (uniformly) close to the payoff function `f`. (You don't need to think in these terms to follow the proof below: it's a giant `calc` block!) This result proves Weierstrass' theorem that polynomials are dense in `C([0,1], ℝ)`, although we defer an abstract statement of this until later. -/ noncomputable theory open_locale classical open_locale big_operators open_locale bounded_continuous_function open_locale unit_interval /-- The Bernstein polynomials, as continuous functions on `[0,1]`. -/ def bernstein (n ν : ℕ) : C(I, ℝ) := (bernstein_polynomial ℝ n ν).to_continuous_map_on I @[simp] lemma bernstein_apply (n ν : ℕ) (x : I) : bernstein n ν x = n.choose ν * x^ν * (1-x)^(n-ν) := begin dsimp [bernstein, polynomial.to_continuous_map_on, polynomial.to_continuous_map, bernstein_polynomial], simp, end lemma bernstein_nonneg {n ν : ℕ} {x : I} : 0 ≤ bernstein n ν x := begin simp only [bernstein_apply], exact mul_nonneg (mul_nonneg (nat.cast_nonneg _) (pow_nonneg (by unit_interval) _)) (pow_nonneg (by unit_interval) _), end /-! We now give a slight reformulation of `bernstein_polynomial.variance`. -/ namespace bernstein /-- Send `k : fin (n+1)` to the equally spaced points `k/n` in the unit interval. -/ def z {n : ℕ} (k : fin (n+1)) : I := ⟨(k : ℝ) / n, begin cases n, { norm_num }, { have h₁ : 0 < (n.succ : ℝ) := by exact_mod_cast (nat.succ_pos _), have h₂ : ↑k ≤ n.succ := by exact_mod_cast (fin.le_last k), rw [set.mem_Icc, le_div_iff h₁, div_le_iff h₁], norm_cast, simp [h₂], }, end⟩ local postfix `/ₙ`:90 := z lemma probability (n : ℕ) (x : I) : ∑ k : fin (n+1), bernstein n k x = 1 := begin have := bernstein_polynomial.sum ℝ n, apply_fun (λ p, polynomial.aeval (x : ℝ) p) at this, simp [alg_hom.map_sum, finset.sum_range] at this, exact this, end lemma variance {n : ℕ} (h : 0 < (n : ℝ)) (x : I) : ∑ k : fin (n+1), (x - k/ₙ : ℝ)^2 * bernstein n k x = x * (1-x) / n := begin have h' : (n : ℝ) ≠ 0 := ne_of_gt h, apply_fun (λ x : ℝ, x * n) using group_with_zero.mul_right_injective h', apply_fun (λ x : ℝ, x * n) using group_with_zero.mul_right_injective h', dsimp, conv_lhs { simp only [finset.sum_mul, z], }, conv_rhs { rw div_mul_cancel _ h', }, have := bernstein_polynomial.variance ℝ n, apply_fun (λ p, polynomial.aeval (x : ℝ) p) at this, simp [alg_hom.map_sum, finset.sum_range, ←polynomial.nat_cast_mul] at this, convert this using 1, { congr' 1, funext k, rw [mul_comm _ (n : ℝ), mul_comm _ (n : ℝ), ←mul_assoc, ←mul_assoc], congr' 1, field_simp [h], ring, }, { ring, }, end end bernstein open bernstein local postfix `/ₙ`:2000 := z /-- The `n`-th approximation of a continuous function on `[0,1]` by Bernstein polynomials, given by `∑ k, f (k/n) * bernstein n k x`. -/ def bernstein_approximation (n : ℕ) (f : C(I, ℝ)) : C(I, ℝ) := ∑ k : fin (n+1), f k/ₙ • bernstein n k /-! We now set up some of the basic machinery of the proof that the Bernstein approximations converge uniformly. A key player is the set `S f ε h n x`, for some function `f : C(I, ℝ)`, `h : 0 < ε`, `n : ℕ` and `x : I`. This is the set of points `k` in `fin (n+1)` such that `k/n` is within `δ` of `x`, where `δ` is the modulus of uniform continuity for `f`, chosen so `|f x - f y| < ε/2` when `|x - y| < δ`. We show that if `k ∉ S`, then `1 ≤ δ^-2 * (x - k/n)^2`. -/ namespace bernstein_approximation @[simp] lemma apply (n : ℕ) (f : C(I, ℝ)) (x : I) : bernstein_approximation n f x = ∑ k : fin (n+1), f k/ₙ * bernstein n k x := by simp [bernstein_approximation] /-- The modulus of (uniform) continuity for `f`, chosen so `|f x - f y| < ε/2` when `|x - y| < δ`. -/ def δ (f : C(I, ℝ)) (ε : ℝ) (h : 0 < ε) : ℝ := f.modulus (ε/2) (half_pos h) lemma δ_pos {f : C(I, ℝ)} {ε : ℝ} {h : 0 < ε} : 0 < δ f ε h := f.modulus_pos /-- The set of points `k` so `k/n` is within `δ` of `x`. -/ def S (f : C(I, ℝ)) (ε : ℝ) (h : 0 < ε) (n : ℕ) (x : I) : finset (fin (n+1)) := { k : fin (n+1) | dist k/ₙ x < δ f ε h }.to_finset /-- If `k ∈ S`, then `f(k/n)` is close to `f x`. -/ lemma lt_of_mem_S {f : C(I, ℝ)} {ε : ℝ} {h : 0 < ε} {n : ℕ} {x : I} {k : fin (n+1)} (m : k ∈ S f ε h n x) : |f k/ₙ - f x| < ε/2 := begin apply f.dist_lt_of_dist_lt_modulus (ε/2) (half_pos h), simpa [S] using m, end /-- If `k ∉ S`, then as `δ ≤ |x - k/n|`, we have the inequality `1 ≤ δ^-2 * (x - k/n)^2`. This particular formulation will be helpful later. -/ lemma le_of_mem_S_compl {f : C(I, ℝ)} {ε : ℝ} {h : 0 < ε} {n : ℕ} {x : I} {k : fin (n+1)} (m : k ∈ (S f ε h n x)ᶜ) : (1 : ℝ) ≤ (δ f ε h)^(-2 : ℤ) * (x - k/ₙ) ^ 2 := begin simp only [finset.mem_compl, not_lt, set.mem_to_finset, set.mem_set_of_eq, S] at m, erw [zpow_neg, ← div_eq_inv_mul, one_le_div (pow_pos δ_pos 2), sq_le_sq, abs_of_pos δ_pos], rwa [dist_comm] at m end end bernstein_approximation open bernstein_approximation open bounded_continuous_function open filter open_locale topological_space /-- The Bernstein approximations ``` ∑ k : fin (n+1), f (k/n : ℝ) * n.choose k * x^k * (1-x)^(n-k) ``` for a continuous function `f : C([0,1], ℝ)` converge uniformly to `f` as `n` tends to infinity. This is the proof given in [Richard Beals' *Analysis, an introduction*][beals-analysis], §7D, and reproduced on wikipedia. -/ theorem bernstein_approximation_uniform (f : C(I, ℝ)) : tendsto (λ n : ℕ, bernstein_approximation n f) at_top (𝓝 f) := begin simp only [metric.nhds_basis_ball.tendsto_right_iff, metric.mem_ball, dist_eq_norm], intros ε h, let δ := δ f ε h, have nhds_zero := tendsto_const_div_at_top_nhds_0_nat (2 * ∥f∥ * δ ^ (-2 : ℤ)), filter_upwards [nhds_zero.eventually (gt_mem_nhds (half_pos h)), eventually_gt_at_top 0] with n nh npos', have npos : 0 < (n:ℝ) := by exact_mod_cast npos', -- Two easy inequalities we'll need later: have w₁ : 0 ≤ 2 * ∥f∥ := mul_nonneg (by norm_num) (norm_nonneg f), have w₂ : 0 ≤ 2 * ∥f∥ * δ^(-2 : ℤ) := mul_nonneg w₁ pow_minus_two_nonneg, -- As `[0,1]` is compact, it suffices to check the inequality pointwise. rw (continuous_map.norm_lt_iff _ h), intro x, -- The idea is to split up the sum over `k` into two sets, -- `S`, where `x - k/n < δ`, and its complement. let S := S f ε h n x, calc |(bernstein_approximation n f - f) x| = |bernstein_approximation n f x - f x| : rfl ... = |bernstein_approximation n f x - f x * 1| : by rw mul_one ... = |bernstein_approximation n f x - f x * (∑ k : fin (n+1), bernstein n k x)| : by rw bernstein.probability ... = |∑ k : fin (n+1), (f k/ₙ - f x) * bernstein n k x| : by simp [bernstein_approximation, finset.mul_sum, sub_mul] ... ≤ ∑ k : fin (n+1), |(f k/ₙ - f x) * bernstein n k x| : finset.abs_sum_le_sum_abs _ _ ... = ∑ k : fin (n+1), |f k/ₙ - f x| * bernstein n k x : by simp_rw [abs_mul, abs_eq_self.mpr bernstein_nonneg] ... = ∑ k in S, |f k/ₙ - f x| * bernstein n k x + ∑ k in Sᶜ, |f k/ₙ - f x| * bernstein n k x : (S.sum_add_sum_compl _).symm -- We'll now deal with the terms in `S` and the terms in `Sᶜ` in separate calc blocks. ... < ε/2 + ε/2 : add_lt_add_of_le_of_lt _ _ ... = ε : add_halves ε, { -- We now work on the terms in `S`: uniform continuity and `bernstein.probability` -- quickly give us a bound. calc ∑ k in S, |f k/ₙ - f x| * bernstein n k x ≤ ∑ k in S, ε/2 * bernstein n k x : finset.sum_le_sum (λ k m, (mul_le_mul_of_nonneg_right (le_of_lt (lt_of_mem_S m)) bernstein_nonneg)) ... = ε/2 * ∑ k in S, bernstein n k x : by rw finset.mul_sum -- In this step we increase the sum over `S` back to a sum over all of `fin (n+1)`, -- so that we can use `bernstein.probability`. ... ≤ ε/2 * ∑ k : fin (n+1), bernstein n k x : mul_le_mul_of_nonneg_left (finset.sum_le_univ_sum_of_nonneg (λ k, bernstein_nonneg)) (le_of_lt (half_pos h)) ... = ε/2 : by rw [bernstein.probability, mul_one] }, { -- We now turn to working on `Sᶜ`: we control the difference term just using `∥f∥`, -- and then insert a `δ^(-2) * (x - k/n)^2` factor -- (which is at least one because we are not in `S`). calc ∑ k in Sᶜ, |f k/ₙ - f x| * bernstein n k x ≤ ∑ k in Sᶜ, (2 * ∥f∥) * bernstein n k x : finset.sum_le_sum (λ k m, mul_le_mul_of_nonneg_right (f.dist_le_two_norm _ _) bernstein_nonneg) ... = (2 * ∥f∥) * ∑ k in Sᶜ, bernstein n k x : by rw finset.mul_sum ... ≤ (2 * ∥f∥) * ∑ k in Sᶜ, δ^(-2 : ℤ) * (x - k/ₙ)^2 * bernstein n k x : mul_le_mul_of_nonneg_left (finset.sum_le_sum (λ k m, begin conv_lhs { rw ←one_mul (bernstein _ _ _), }, exact mul_le_mul_of_nonneg_right (le_of_mem_S_compl m) bernstein_nonneg, end)) w₁ -- Again enlarging the sum from `Sᶜ` to all of `fin (n+1)` ... ≤ (2 * ∥f∥) * ∑ k : fin (n+1), δ^(-2 : ℤ) * (x - k/ₙ)^2 * bernstein n k x : mul_le_mul_of_nonneg_left (finset.sum_le_univ_sum_of_nonneg (λ k, mul_nonneg (mul_nonneg pow_minus_two_nonneg (sq_nonneg _)) bernstein_nonneg)) w₁ ... = (2 * ∥f∥) * δ^(-2 : ℤ) * ∑ k : fin (n+1), (x - k/ₙ)^2 * bernstein n k x : by conv_rhs { rw [mul_assoc, finset.mul_sum], simp only [←mul_assoc], } -- `bernstein.variance` and `x ∈ [0,1]` gives the uniform bound ... = (2 * ∥f∥) * δ^(-2 : ℤ) * x * (1-x) / n : by { rw variance npos, ring, } ... ≤ (2 * ∥f∥) * δ^(-2 : ℤ) / n : (div_le_div_right npos).mpr $ by refine mul_le_of_le_of_le_one' (mul_le_of_le_one_right w₂ _) _ _ w₂; unit_interval ... < ε/2 : nh, } end
a0911498fb4e5577d52b6c0858f4f4267135eb3c
ac1c2a2f522b0fdf854095ba00f882ca849669e7
/leanpkg/leanpkg/toml.lean
b622b933fe029a23ea5549346e826ecb30694179
[ "Apache-2.0" ]
permissive
abliss/lean
b8b336abc8d50dbb0726dcff9dd16793c23bfbe1
fb24cc99573c153f97a1951ee94bbbdda300b6be
refs/heads/master
1,611,536,584,520
1,497,811,981,000
1,497,811,981,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,823
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Gabriel Ebner -/ import data.buffer.parser -- I'd like to contribute a new naming convention: -- CamelCase for non-terminals. def join (sep : string) : list string → string | [x] := x | [] := "" | (x::xs) := x ++ sep ++ join xs namespace toml inductive value : Type | str : string → value | nat : ℕ → value | bool : bool → value | table : list (string × value) → value namespace value private def escapec : char → string | '\"' := "\\\"" | '\t' := "\\t" | '\n' := "\\n" | '\\' := "\\\\" | c := string.singleton c private def escape (s : string) : string := s.fold "" (λ s c, s ++ escapec c) private mutual def to_string_core, to_string_pairs with to_string_core : value → string | (value.str s) := "\"" ++ escape s ++ "\"" | (value.nat n) := to_string n | (value.bool tt) := "true" | (value.bool ff) := "false" | (value.table cs) := "{" ++ to_string_pairs cs ++ "}" with to_string_pairs : list (string × value) → string | [] := "" | [(k, v)] := k ++ " = " ++ to_string_core v | ((k, v)::kvs) := k ++ " = " ++ to_string_core v ++ ", " ++ to_string_pairs kvs protected def to_string : ∀ (v : value), string | (table cs) := join "\n" $ do (h, c) ← cs, match c with | table ds := ["[" ++ h ++ "]\n" ++ join "" (do (k, v) ← ds, [k ++ " = " ++ to_string_core v ++ "\n"])] | _ := ["<error> " ++ to_string_core c] end | v := to_string_core v instance : has_to_string value := ⟨value.to_string⟩ def lookup : value → string → option value | (value.table cs) k := match cs.filter (λ c : string × value, c.fst = k) with | [] := none | (k,v) ::_ := some v end | _ _ := none end value open parser def Comment : parser unit := ch '#' >> many' (sat (≠ '#')) >> optional (ch '\n') >> eps def Ws : parser unit := decorate_error "<whitespace>" $ many' $ one_of' " \t\n".to_list <|> Comment def tok (s : string) := str s >> Ws def StringChar : parser char := sat (λc, c ≠ '\"' ∧ c ≠ '\\' ∧ c.val > 0x1f) <|> (do str "\\", (str "t" >> return '\t') <|> (str "n" >> return '\n') <|> (str "\\" >> return '\\') <|> (str "\"" >> return '\"')) def BasicString : parser string := str "\"" *> (many_char StringChar) <* str "\"" <* Ws def String := BasicString def Nat : parser nat := do s ← many_char1 (one_of "0123456789".to_list), Ws, return s.to_nat def Boolean : parser bool := (tok "true" >> return tt) <|> (tok "false" >> return ff) def BareKey : parser string := do cs ← many_char1 $ sat $ λ c, c.is_alpha ∨ c.is_digit ∨ c = '_' ∨ c = '-', Ws, return cs def Key := BareKey <|> BasicString section parameter Val : parser value def KeyVal : parser (string × value) := do k ← Key, tok "=", v ← Val, return (k, v) def StdTable : parser (string × value) := do tok "[", n ← Key, tok "]", cs ← many KeyVal, return (n, value.table cs) def Table : parser (string × value) := StdTable def StrVal : parser value := value.str <$> String def NatVal : parser value := value.nat <$> Nat def BoolVal : parser value := value.bool <$> Boolean def InlineTable : parser value := tok "{" *> (value.table <$> sep_by (tok ",") KeyVal) <* tok "}" end def Val : parser value := fix $ λ Val, StrVal <|> NatVal <|> BoolVal <|> InlineTable Val def Expression := Table Val def File : parser value := Ws *> (value.table <$> many Expression) /- #eval run_string File $ "[package]\n" ++ "name = \"sss\"\n" ++ "version = \"0.1\"\n" ++ "timeout = 10\n" ++ "\n" ++ "[dependencies]\n" ++ "library_dev = { git = \"https://github.com/leanprover/library_dev\", rev = \"master\" }" -/ end toml
3c8f1ee7c070fcbe24ba9339d39a1b23f141f25e
f5f7e6fae601a5fe3cac7cc3ed353ed781d62419
/src/data/seq/seq.lean
9a57ae3229da87ec57a98faa7cf47d9992ab72d7
[ "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
25,101
lean
import data.stream data.lazy_list data.seq.computation logic.basic tactic.interactive universes u v w /- coinductive seq (α : Type u) : Type u | nil : seq α | cons : α → seq α → seq α -/ /-- `seq α` is the type of possibly infinite lists (referred here as sequences). It is encoded as an infinite stream of options such that if `f n = none`, then `f m = none` for all `m ≥ n`. -/ def seq (α : Type u) : Type u := { f : stream (option α) // ∀ {n}, f n = none → f (n+1) = none } /-- `seq1 α` is the type of nonempty sequences. -/ def seq1 (α) := α × seq α namespace seq variables {α : Type u} {β : Type v} {γ : Type w} /-- The empty sequence -/ def nil : seq α := ⟨stream.const none, λn h, rfl⟩ /-- Prepend an element to a sequence -/ def cons (a : α) : seq α → seq α | ⟨f, al⟩ := ⟨some a :: f, λn h, by {cases n with n, contradiction, exact al h}⟩ /-- Get the nth element of a sequence (if it exists) -/ def nth : seq α → ℕ → option α := subtype.val /-- Functorial action of the functor `option (α × _)` -/ @[simp] def omap (f : β → γ) : option (α × β) → option (α × γ) | none := none | (some (a, b)) := some (a, f b) /-- Get the first element of a sequence -/ def head (s : seq α) : option α := nth s 0 /-- Get the tail of a sequence (or `nil` if the sequence is `nil`) -/ def tail : seq α → seq α | ⟨f, al⟩ := ⟨f.tail, λ n, al⟩ protected def mem (a : α) (s : seq α) := some a ∈ s.1 instance : has_mem α (seq α) := ⟨seq.mem⟩ theorem le_stable (s : seq α) {m n} (h : m ≤ n) : s.1 m = none → s.1 n = none := by {cases s with f al, induction h with n h IH, exacts [id, λ h2, al (IH h2)]} theorem not_mem_nil (a : α) : a ∉ @nil α := λ ⟨n, (h : some a = none)⟩, by injection h theorem mem_cons (a : α) : ∀ (s : seq α), a ∈ cons a s | ⟨f, al⟩ := stream.mem_cons (some a) _ theorem mem_cons_of_mem (y : α) {a : α} : ∀ {s : seq α}, a ∈ s → a ∈ cons y s | ⟨f, al⟩ := stream.mem_cons_of_mem (some y) theorem eq_or_mem_of_mem_cons {a b : α} : ∀ {s : seq α}, a ∈ cons b s → a = b ∨ a ∈ s | ⟨f, al⟩ h := (stream.eq_or_mem_of_mem_cons h).imp_left (λh, by injection h) @[simp] theorem mem_cons_iff {a b : α} {s : seq α} : a ∈ cons b s ↔ a = b ∨ a ∈ s := ⟨eq_or_mem_of_mem_cons, λo, by cases o with e m; [{rw e, apply mem_cons}, exact mem_cons_of_mem _ m]⟩ /-- Destructor for a sequence, resulting in either `none` (for `nil`) or `some (a, s)` (for `cons a s`). -/ def destruct (s : seq α) : option (seq1 α) := (λa', (a', s.tail)) <$> nth s 0 theorem destruct_eq_nil {s : seq α} : destruct s = none → s = nil := begin dsimp [destruct], induction f0 : nth s 0; intro h, { apply subtype.eq, funext n, induction n with n IH, exacts [f0, s.2 IH] }, { contradiction } end theorem destruct_eq_cons {s : seq α} {a s'} : destruct s = some (a, s') → s = cons a s' := begin dsimp [destruct], induction f0 : nth s 0 with a'; intro h, { contradiction }, { unfold functor.map at h, dsimp at h, cases s with f al, injections with _ h1 h2, rw ←h2, apply subtype.eq, dsimp [tail, cons], rw h1 at f0, rw ←f0, exact (stream.eta f).symm } end @[simp] theorem destruct_nil : destruct (nil : seq α) = none := rfl @[simp] theorem destruct_cons (a : α) : ∀ s, destruct (cons a s) = some (a, s) | ⟨f, al⟩ := begin unfold cons destruct functor.map, apply congr_arg (λ s, some (a, s)), apply subtype.eq, dsimp [tail], rw [stream.tail_cons] end theorem head_eq_destruct (s : seq α) : head s = prod.fst <$> destruct s := by unfold destruct head; cases nth s 0; refl @[simp] theorem head_nil : head (nil : seq α) = none := rfl @[simp] theorem head_cons (a : α) (s) : head (cons a s) = some a := by rw [head_eq_destruct, destruct_cons]; refl @[simp] theorem tail_nil : tail (nil : seq α) = nil := rfl @[simp] theorem tail_cons (a : α) (s) : tail (cons a s) = s := by cases s with f al; apply subtype.eq; dsimp [tail, cons]; rw [stream.tail_cons] def cases_on {C : seq α → Sort v} (s : seq α) (h1 : C nil) (h2 : ∀ x s, C (cons x s)) : C s := begin induction H : destruct s with v v, { rw destruct_eq_nil H, apply h1 }, { cases v with a s', rw destruct_eq_cons H, apply h2 } end theorem mem_rec_on {C : seq α → Prop} {a s} (M : a ∈ s) (h1 : ∀ b s', (a = b ∨ C s') → C (cons b s')) : C s := begin cases M with k e, unfold stream.nth at e, induction k with k IH generalizing s, { have TH : s = cons a (tail s), { apply destruct_eq_cons, unfold destruct nth functor.map, rw ←e, refl }, rw TH, apply h1 _ _ (or.inl rfl) }, revert e, apply s.cases_on _ (λ b s', _); intro e, { injection e }, { have h_eq : (cons b s').val (nat.succ k) = s'.val k, { cases s'; refl }, rw [h_eq] at e, apply h1 _ _ (or.inr (IH e)) } end def corec.F (f : β → option (α × β)) : option β → option α × option β | none := (none, none) | (some b) := match f b with none := (none, none) | some (a, b') := (some a, some b') end /-- Corecursor for `seq α` as a coinductive type. Iterates `f` to produce new elements of the sequence until `none` is obtained. -/ def corec (f : β → option (α × β)) (b : β) : seq α := begin refine ⟨stream.corec' (corec.F f) (some b), λn h, _⟩, rw stream.corec'_eq, change stream.corec' (corec.F f) (corec.F f (some b)).2 n = none, revert h, generalize : some b = o, revert o, induction n with n IH; intro o, { change (corec.F f o).1 = none → (corec.F f (corec.F f o).2).1 = none, cases o with b; intro h, { refl }, dsimp [corec.F] at h, dsimp [corec.F], cases f b with s, { refl }, { cases s with a b', contradiction } }, { rw [stream.corec'_eq (corec.F f) (corec.F f o).2, stream.corec'_eq (corec.F f) o], exact IH (corec.F f o).2 } end @[simp] theorem corec_eq (f : β → option (α × β)) (b : β) : destruct (corec f b) = omap (corec f) (f b) := begin dsimp [corec, destruct, nth], change stream.corec' (corec.F f) (some b) 0 with (corec.F f (some b)).1, unfold functor.map, dsimp [corec.F], induction h : f b with s, { refl }, cases s with a b', dsimp [corec.F], apply congr_arg (λ b', some (a, b')), apply subtype.eq, dsimp [corec, tail], rw [stream.corec'_eq, stream.tail_cons], dsimp [corec.F], rw h, refl end /-- Embed a list as a sequence -/ def of_list (l : list α) : seq α := ⟨list.nth l, λn h, begin induction l with a l IH generalizing n, refl, dsimp [list.nth], cases n with n; dsimp [list.nth] at h, { contradiction }, { apply IH _ h } end⟩ instance coe_list : has_coe (list α) (seq α) := ⟨of_list⟩ section bisim variable (R : seq α → seq α → Prop) local infix ~ := R def bisim_o : option (seq1 α) → option (seq1 α) → Prop | none none := true | (some (a, s)) (some (a', s')) := a = a' ∧ R s s' | _ _ := false attribute [simp] bisim_o def is_bisimulation := ∀ ⦃s₁ s₂⦄, s₁ ~ s₂ → bisim_o R (destruct s₁) (destruct s₂) -- If two streams are bisimilar, then they are equal theorem eq_of_bisim (bisim : is_bisimulation R) {s₁ s₂} (r : s₁ ~ s₂) : s₁ = s₂ := begin apply subtype.eq, apply stream.eq_of_bisim (λx y, ∃ s s' : seq α, s.1 = x ∧ s'.1 = y ∧ R s s'), dsimp [stream.is_bisimulation], intros t₁ t₂ e, exact match t₁, t₂, e with ._, ._, ⟨s, s', rfl, rfl, r⟩ := suffices head s = head s' ∧ R (tail s) (tail s'), from and.imp id (λr, ⟨tail s, tail s', by cases s; refl, by cases s'; refl, r⟩) this, begin have := bisim r, revert r this, apply cases_on s _ _; intros; apply cases_on s' _ _; intros; intros r this, { constructor, refl, assumption }, { rw [destruct_nil, destruct_cons] at this, exact false.elim this }, { rw [destruct_nil, destruct_cons] at this, exact false.elim this }, { rw [destruct_cons, destruct_cons] at this, rw [head_cons, head_cons, tail_cons, tail_cons], cases this with h1 h2, constructor, rw h1, exact h2 } end end, exact ⟨s₁, s₂, rfl, rfl, r⟩ end end bisim theorem coinduction : ∀ {s₁ s₂ : seq α}, head s₁ = head s₂ → (∀ (β : Type u) (fr : seq α → β), fr s₁ = fr s₂ → fr (tail s₁) = fr (tail s₂)) → s₁ = s₂ | ⟨f₁, a₁⟩ ⟨f₂, a₂⟩ hh ht := subtype.eq (stream.coinduction hh (λ β fr, ht β (λs, fr s.1))) theorem coinduction2 (s) (f g : seq α → seq β) (H : ∀ s, bisim_o (λ (s1 s2 : seq β), ∃ (s : seq α), s1 = f s ∧ s2 = g s) (destruct (f s)) (destruct (g s))) : f s = g s := begin refine eq_of_bisim (λ s1 s2, ∃ s, s1 = f s ∧ s2 = g s) _ ⟨s, rfl, rfl⟩, intros s1 s2 h, rcases h with ⟨s, h1, h2⟩, rw [h1, h2], apply H end /-- Embed an infinite stream as a sequence -/ def of_stream (s : stream α) : seq α := ⟨s.map some, λn h, by contradiction⟩ instance coe_stream : has_coe (stream α) (seq α) := ⟨of_stream⟩ /-- Embed a `lazy_list α` as a sequence. Note that even though this is non-meta, it will produce infinite sequences if used with cyclic `lazy_list`s created by meta constructions. -/ def of_lazy_list : lazy_list α → seq α := corec (λl, match l with | lazy_list.nil := none | lazy_list.cons a l' := some (a, l' ()) end) instance coe_lazy_list : has_coe (lazy_list α) (seq α) := ⟨of_lazy_list⟩ /-- Translate a sequence into a `lazy_list`. Since `lazy_list` and `list` are isomorphic as non-meta types, this function is necessarily meta. -/ meta def to_lazy_list : seq α → lazy_list α | s := match destruct s with | none := lazy_list.nil | some (a, s') := lazy_list.cons a (to_lazy_list s') end /-- Translate a sequence to a list. This function will run forever if run on an infinite sequence. -/ meta def force_to_list (s : seq α) : list α := (to_lazy_list s).to_list /-- Append two sequences. If `s₁` is infinite, then `s₁ ++ s₂ = s₁`, otherwise it puts `s₂` at the location of the `nil` in `s₁`. -/ def append (s₁ s₂ : seq α) : seq α := @corec α (seq α × seq α) (λ⟨s₁, s₂⟩, match destruct s₁ with | none := omap (λs₂, (nil, s₂)) (destruct s₂) | some (a, s₁') := some (a, s₁', s₂) end) (s₁, s₂) /-- Map a function over a sequence. -/ def map (f : α → β) : seq α → seq β | ⟨s, al⟩ := ⟨s.map (option.map f), λn, begin dsimp [stream.map, stream.nth], induction e : s n; intro, { rw al e, assumption }, { contradiction } end⟩ /-- Flatten a sequence of sequences. (It is required that the sequences be nonempty to ensure productivity; in the case of an infinite sequence of `nil`, the first element is never generated.) -/ def join : seq (seq1 α) → seq α := corec (λS, match destruct S with | none := none | some ((a, s), S') := some (a, match destruct s with | none := S' | some s' := cons s' S' end) end) /-- Remove the first `n` elements from the sequence. -/ def drop (s : seq α) : ℕ → seq α | 0 := s | (n+1) := tail (drop n) attribute [simp] drop /-- Take the first `n` elements of the sequence (producing a list) -/ def take : ℕ → seq α → list α | 0 s := [] | (n+1) s := match destruct s with | none := [] | some (x, r) := list.cons x (take n r) end /-- Split a sequence at `n`, producing a finite initial segment and an infinite tail. -/ def split_at : ℕ → seq α → list α × seq α | 0 s := ([], s) | (n+1) s := match destruct s with | none := ([], nil) | some (x, s') := let (l, r) := split_at n s' in (list.cons x l, r) end /-- Combine two sequences with a function -/ def zip_with (f : α → β → γ) : seq α → seq β → seq γ | ⟨f₁, a₁⟩ ⟨f₂, a₂⟩ := ⟨λn, match f₁ n, f₂ n with | some a, some b := some (f a b) | _, _ := none end, λn, begin induction h1 : f₁ n, { intro H, rw a₁ h1, refl }, induction h2 : f₂ n; dsimp [seq.zip_with._match_1]; intro H, { rw a₂ h2, cases f₁ (n + 1); refl }, { contradiction } end⟩ /-- Pair two sequences into a sequence of pairs -/ def zip : seq α → seq β → seq (α × β) := zip_with prod.mk /-- Separate a sequence of pairs into two sequences -/ def unzip (s : seq (α × β)) : seq α × seq β := (map prod.fst s, map prod.snd s) /-- Convert a sequence which is known to terminate into a list -/ def to_list (s : seq α) (h : ∃ n, ¬ (nth s n).is_some) : list α := take (nat.find h) s /-- Convert a sequence which is known not to terminate into a stream -/ def to_stream (s : seq α) (h : ∀ n, (nth s n).is_some) : stream α := λn, option.get (h n) /-- Convert a sequence into either a list or a stream depending on whether it is finite or infinite. (Without decidability of the infiniteness predicate, this is not constructively possible.) -/ def to_list_or_stream (s : seq α) [decidable (∃ n, ¬ (nth s n).is_some)] : list α ⊕ stream α := if h : ∃ n, ¬ (nth s n).is_some then sum.inl (to_list s h) else sum.inr (to_stream s (λn, decidable.by_contradiction (λ hn, h ⟨n, hn⟩))) @[simp] theorem nil_append (s : seq α) : append nil s = s := begin apply coinduction2, intro s, dsimp [append], rw [corec_eq], dsimp [append], apply cases_on s _ _, { trivial }, { intros x s, rw [destruct_cons], dsimp, exact ⟨rfl, s, rfl, rfl⟩ } end @[simp] theorem cons_append (a : α) (s t) : append (cons a s) t = cons a (append s t) := destruct_eq_cons $ begin dsimp [append], rw [corec_eq], dsimp [append], rw [destruct_cons], dsimp [append], refl end @[simp] theorem append_nil (s : seq α) : append s nil = s := begin apply coinduction2 s, intro s, apply cases_on s _ _, { trivial }, { intros x s, rw [cons_append, destruct_cons, destruct_cons], dsimp, exact ⟨rfl, s, rfl, rfl⟩ } end @[simp] theorem append_assoc (s t u : seq α) : append (append s t) u = append s (append t u) := begin apply eq_of_bisim (λs1 s2, ∃ s t u, s1 = append (append s t) u ∧ s2 = append s (append t u)), { intros s1 s2 h, exact match s1, s2, h with ._, ._, ⟨s, t, u, rfl, rfl⟩ := begin apply cases_on s; simp, { apply cases_on t; simp, { apply cases_on u; simp, { intros x u, refine ⟨nil, nil, u, _, _⟩; simp } }, { intros x t, refine ⟨nil, t, u, _, _⟩; simp } }, { intros x s, exact ⟨s, t, u, rfl, rfl⟩ } end end }, { exact ⟨s, t, u, rfl, rfl⟩ } end @[simp] theorem map_nil (f : α → β) : map f nil = nil := rfl @[simp] theorem map_cons (f : α → β) (a) : ∀ s, map f (cons a s) = cons (f a) (map f s) | ⟨s, al⟩ := by apply subtype.eq; dsimp [cons, map]; rw stream.map_cons; refl @[simp] theorem map_id : ∀ (s : seq α), map id s = s | ⟨s, al⟩ := begin apply subtype.eq; dsimp [map], rw [option.map_id, stream.map_id]; refl end @[simp] theorem map_tail (f : α → β) : ∀ s, map f (tail s) = tail (map f s) | ⟨s, al⟩ := by apply subtype.eq; dsimp [tail, map]; rw stream.map_tail; refl theorem map_comp (f : α → β) (g : β → γ) : ∀ (s : seq α), map (g ∘ f) s = map g (map f s) | ⟨s, al⟩ := begin apply subtype.eq; dsimp [map], rw stream.map_map, apply congr_arg (λ f : _ → option γ, stream.map f s), funext x, cases x with x; refl end @[simp] theorem map_append (f : α → β) (s t) : map f (append s t) = append (map f s) (map f t) := begin apply eq_of_bisim (λs1 s2, ∃ s t, s1 = map f (append s t) ∧ s2 = append (map f s) (map f t)) _ ⟨s, t, rfl, rfl⟩, intros s1 s2 h, exact match s1, s2, h with ._, ._, ⟨s, t, rfl, rfl⟩ := begin apply cases_on s; simp, { apply cases_on t; simp, { intros x t, refine ⟨nil, t, _, _⟩; simp } }, { intros x s, refine ⟨s, t, rfl, rfl⟩ } end end end @[simp] theorem map_nth (f : α → β) : ∀ s n, nth (map f s) n = (nth s n).map f | ⟨s, al⟩ n := rfl instance : functor seq := {map := @map} instance : is_lawful_functor seq := { id_map := @map_id, comp_map := @map_comp } @[simp] theorem join_nil : join nil = (nil : seq α) := destruct_eq_nil rfl @[simp] theorem join_cons_nil (a : α) (S) : join (cons (a, nil) S) = cons a (join S) := destruct_eq_cons $ by simp [join] @[simp] theorem join_cons_cons (a b : α) (s S) : join (cons (a, cons b s) S) = cons a (join (cons (b, s) S)) := destruct_eq_cons $ by simp [join] @[simp] theorem join_cons (a : α) (s S) : join (cons (a, s) S) = cons a (append s (join S)) := begin apply eq_of_bisim (λs1 s2, s1 = s2 ∨ ∃ a s S, s1 = join (cons (a, s) S) ∧ s2 = cons a (append s (join S))) _ (or.inr ⟨a, s, S, rfl, rfl⟩), intros s1 s2 h, exact match s1, s2, h with | _, _, (or.inl $ eq.refl s) := begin apply cases_on s, { trivial }, { intros x s, rw [destruct_cons], exact ⟨rfl, or.inl rfl⟩ } end | ._, ._, (or.inr ⟨a, s, S, rfl, rfl⟩) := begin apply cases_on s, { simp }, { intros x s, simp, refine or.inr ⟨x, s, S, rfl, rfl⟩ } end end end @[simp] theorem join_append (S T : seq (seq1 α)) : join (append S T) = append (join S) (join T) := begin apply eq_of_bisim (λs1 s2, ∃ s S T, s1 = append s (join (append S T)) ∧ s2 = append s (append (join S) (join T))), { intros s1 s2 h, exact match s1, s2, h with ._, ._, ⟨s, S, T, rfl, rfl⟩ := begin apply cases_on s; simp, { apply cases_on S; simp, { apply cases_on T, { simp }, { intros s T, cases s with a s; simp, refine ⟨s, nil, T, _, _⟩; simp } }, { intros s S, cases s with a s; simp, exact ⟨s, S, T, rfl, rfl⟩ } }, { intros x s, exact ⟨s, S, T, rfl, rfl⟩ } end end }, { refine ⟨nil, S, T, _, _⟩; simp } end @[simp] theorem of_list_nil : of_list [] = (nil : seq α) := rfl @[simp] theorem of_list_cons (a : α) (l) : of_list (a :: l) = cons a (of_list l) := begin apply subtype.eq, simp [of_list, cons], funext n, cases n; simp [list.nth, stream.cons] end @[simp] theorem of_stream_cons (a : α) (s) : of_stream (a :: s) = cons a (of_stream s) := by apply subtype.eq; simp [of_stream, cons]; rw stream.map_cons @[simp] theorem of_list_append (l l' : list α) : of_list (l ++ l') = append (of_list l) (of_list l') := by induction l; simp [*] @[simp] theorem of_stream_append (l : list α) (s : stream α) : of_stream (l ++ₛ s) = append (of_list l) (of_stream s) := by induction l; simp [*, stream.nil_append_stream, stream.cons_append_stream] /-- Convert a sequence into a list, embedded in a computation to allow for the possibility of infinite sequences (in which case the computation never returns anything). -/ def to_list' {α} (s : seq α) : computation (list α) := @computation.corec (list α) (list α × seq α) (λ⟨l, s⟩, match destruct s with | none := sum.inl l.reverse | some (a, s') := sum.inr (a::l, s') end) ([], s) theorem dropn_add (s : seq α) (m) : ∀ n, drop s (m + n) = drop (drop s m) n | 0 := rfl | (n+1) := congr_arg tail (dropn_add n) theorem dropn_tail (s : seq α) (n) : drop (tail s) n = drop s (n + 1) := by rw add_comm; symmetry; apply dropn_add theorem nth_tail : ∀ (s : seq α) n, nth (tail s) n = nth s (n + 1) | ⟨f, al⟩ n := rfl @[simp] theorem head_dropn (s : seq α) (n) : head (drop s n) = nth s n := begin induction n with n IH generalizing s, { refl }, rw [nat.succ_eq_add_one, ←nth_tail, ←dropn_tail], apply IH end theorem mem_map (f : α → β) {a : α} : ∀ {s : seq α}, a ∈ s → f a ∈ map f s | ⟨g, al⟩ := stream.mem_map (option.map f) theorem exists_of_mem_map {f} {b : β} : ∀ {s : seq α}, b ∈ map f s → ∃ a, a ∈ s ∧ f a = b | ⟨g, al⟩ h := let ⟨o, om, oe⟩ := stream.exists_of_mem_map h in by cases o with a; injection oe with h'; exact ⟨a, om, h'⟩ theorem of_mem_append {s₁ s₂ : seq α} {a : α} (h : a ∈ append s₁ s₂) : a ∈ s₁ ∨ a ∈ s₂ := begin have := h, revert this, generalize e : append s₁ s₂ = ss, intro h, revert s₁, apply mem_rec_on h _, intros b s' o s₁, apply s₁.cases_on _ (λ c t₁, _); intros m e; have := congr_arg destruct e, { apply or.inr, simpa using m }, { cases (show a = c ∨ a ∈ append t₁ s₂, by simpa using m) with e' m, { rw e', exact or.inl (mem_cons _ _) }, { cases (show c = b ∧ append t₁ s₂ = s', by simpa) with i1 i2, cases o with e' IH, { simp [i1, e'] }, { exact or.imp_left (mem_cons_of_mem _) (IH m i2) } } } end theorem mem_append_left {s₁ s₂ : seq α} {a : α} (h : a ∈ s₁) : a ∈ append s₁ s₂ := by apply mem_rec_on h; intros; simp [*] end seq namespace seq1 variables {α : Type u} {β : Type v} {γ : Type w} open seq /-- Convert a `seq1` to a sequence. -/ def to_seq : seq1 α → seq α | (a, s) := cons a s instance coe_seq : has_coe (seq1 α) (seq α) := ⟨to_seq⟩ /-- Map a function on a `seq1` -/ def map (f : α → β) : seq1 α → seq1 β | (a, s) := (f a, seq.map f s) theorem map_id : ∀ (s : seq1 α), map id s = s | ⟨a, s⟩ := by simp [map] /-- Flatten a nonempty sequence of nonempty sequences -/ def join : seq1 (seq1 α) → seq1 α | ((a, s), S) := match destruct s with | none := (a, seq.join S) | some s' := (a, seq.join (cons s' S)) end @[simp] theorem join_nil (a : α) (S) : join ((a, nil), S) = (a, seq.join S) := rfl @[simp] theorem join_cons (a b : α) (s S) : join ((a, cons b s), S) = (a, seq.join (cons (b, s) S)) := by dsimp [join]; rw [destruct_cons]; refl /-- The `return` operator for the `seq1` monad, which produces a singleton sequence. -/ def ret (a : α) : seq1 α := (a, nil) /-- The `bind` operator for the `seq1` monad, which maps `f` on each element of `s` and appends the results together. (Not all of `s` may be evaluated, because the first few elements of `s` may already produce an infinite result.) -/ def bind (s : seq1 α) (f : α → seq1 β) : seq1 β := join (map f s) @[simp] theorem join_map_ret (s : seq α) : seq.join (seq.map ret s) = s := by apply coinduction2 s; intro s; apply cases_on s; simp [ret] @[simp] theorem bind_ret (f : α → β) : ∀ s, bind s (ret ∘ f) = map f s | ⟨a, s⟩ := begin dsimp [bind, map], change (λx, ret (f x)) with (ret ∘ f), rw [map_comp], simp [function.comp, ret] end @[simp] theorem ret_bind (a : α) (f : α → seq1 β) : bind (ret a) f = f a := begin simp [ret, bind, map], cases f a with a s, apply cases_on s; intros; simp end @[simp] theorem map_join' (f : α → β) (S) : seq.map f (seq.join S) = seq.join (seq.map (map f) S) := begin apply eq_of_bisim (λs1 s2, ∃ s S, s1 = append s (seq.map f (seq.join S)) ∧ s2 = append s (seq.join (seq.map (map f) S))), { intros s1 s2 h, exact match s1, s2, h with ._, ._, ⟨s, S, rfl, rfl⟩ := begin apply cases_on s; simp, { apply cases_on S; simp, { intros x S, cases x with a s; simp [map], exact ⟨_, _, rfl, rfl⟩ } }, { intros x s, refine ⟨s, S, rfl, rfl⟩ } end end }, { refine ⟨nil, S, _, _⟩; simp } end @[simp] theorem map_join (f : α → β) : ∀ S, map f (join S) = join (map (map f) S) | ((a, s), S) := by apply cases_on s; intros; simp [map] @[simp] theorem join_join (SS : seq (seq1 (seq1 α))) : seq.join (seq.join SS) = seq.join (seq.map join SS) := begin apply eq_of_bisim (λs1 s2, ∃ s SS, s1 = seq.append s (seq.join (seq.join SS)) ∧ s2 = seq.append s (seq.join (seq.map join SS))), { intros s1 s2 h, exact match s1, s2, h with ._, ._, ⟨s, SS, rfl, rfl⟩ := begin apply cases_on s; simp, { apply cases_on SS; simp, { intros S SS, cases S with s S; cases s with x s; simp [map], apply cases_on s; simp, { exact ⟨_, _, rfl, rfl⟩ }, { intros x s, refine ⟨cons x (append s (seq.join S)), SS, _, _⟩; simp } } }, { intros x s, exact ⟨s, SS, rfl, rfl⟩ } end end }, { refine ⟨nil, SS, _, _⟩; simp } end @[simp] theorem bind_assoc (s : seq1 α) (f : α → seq1 β) (g : β → seq1 γ) : bind (bind s f) g = bind s (λ (x : α), bind (f x) g) := begin cases s with a s, simp [bind, map], rw [←map_comp], change (λ x, join (map g (f x))) with (join ∘ ((map g) ∘ f)), rw [map_comp _ join], generalize : seq.map (map g ∘ f) s = SS, rcases map g (f a) with ⟨⟨a, s⟩, S⟩, apply cases_on s; intros; apply cases_on S; intros; simp, { cases x with x t, apply cases_on t; intros; simp }, { cases x_1 with y t; simp } end instance : monad seq1 := { map := @map, pure := @ret, bind := @bind } instance : is_lawful_monad seq1 := { id_map := @map_id, bind_pure_comp_eq_map := @bind_ret, pure_bind := @ret_bind, bind_assoc := @bind_assoc } end seq1
a853931f203d57908c16f1c38d5fc496c528ea16
26ac254ecb57ffcb886ff709cf018390161a9225
/src/linear_algebra/tensor_product.lean
20bfd0b53177f98e3fcb7fe94e1823068865b9f2
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
25,348
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro -/ import group_theory.congruence import group_theory.free_abelian_group import linear_algebra.direct_sum_module /-! # Tensor product of semimodules over commutative semirings. This file constructs the tensor product of semimodules over commutative semirings. Given a semiring `R` and semimodules over it `M` and `N`, the standard construction of the tensor product is `tensor_product R M N`. It is also a semimodule over `R`. It comes with a canonical bilinear map `M → N → tensor_product R M N`. Given any bilinear map `M → N → P`, there is a unique linear map `tensor_product R M N → P` whose composition with the canonical bilinear map `M → N → tensor_product R M N` is the given bilinear map `M → N → P`. We start by proving basic lemmas about bilinear maps. ## Notations This file uses the localized notation `M ⊗ N` and `M ⊗[R] N` for `tensor_product R M N`, as well as `m ⊗ₜ n` and `m ⊗ₜ[R] n` for `tensor_product.tmul R m n`. ## Tags bilinear, tensor, tensor product -/ namespace linear_map variables {R : Type*} [comm_semiring R] variables {M : Type*} {N : Type*} {P : Type*} {Q : Type*} {S : Type*} variables [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q] [add_comm_monoid S] variables [semimodule R M] [semimodule R N] [semimodule R P] [semimodule R Q] [semimodule R S] include R variables (R) /-- Create a bilinear map from a function that is linear in each component. -/ def mk₂ (f : M → N → P) (H1 : ∀ m₁ m₂ n, f (m₁ + m₂) n = f m₁ n + f m₂ n) (H2 : ∀ (c:R) m n, f (c • m) n = c • f m n) (H3 : ∀ m n₁ n₂, f m (n₁ + n₂) = f m n₁ + f m n₂) (H4 : ∀ (c:R) m n, f m (c • n) = c • f m n) : M →ₗ N →ₗ P := ⟨λ m, ⟨f m, H3 m, λ c, H4 c m⟩, λ m₁ m₂, linear_map.ext $ H1 m₁ m₂, λ c m, linear_map.ext $ H2 c m⟩ variables {R} @[simp] theorem mk₂_apply (f : M → N → P) {H1 H2 H3 H4} (m : M) (n : N) : (mk₂ R f H1 H2 H3 H4 : M →ₗ[R] N →ₗ P) m n = f m n := rfl theorem ext₂ {f g : M →ₗ[R] N →ₗ[R] P} (H : ∀ m n, f m n = g m n) : f = g := linear_map.ext (λ m, linear_map.ext $ λ n, H m n) /-- Given a linear map from `M` to linear maps from `N` to `P`, i.e., a bilinear map from `M × N` to `P`, change the order of variables and get a linear map from `N` to linear maps from `M` to `P`. -/ def flip (f : M →ₗ[R] N →ₗ[R] P) : N →ₗ M →ₗ P := mk₂ R (λ n m, f m n) (λ n₁ n₂ m, (f m).map_add _ _) (λ c n m, (f m).map_smul _ _) (λ n m₁ m₂, by rw f.map_add; refl) (λ c n m, by rw f.map_smul; refl) variable (f : M →ₗ[R] N →ₗ[R] P) @[simp] theorem flip_apply (m : M) (n : N) : flip f n m = f m n := rfl variables {R} theorem flip_inj {f g : M →ₗ[R] N →ₗ P} (H : flip f = flip g) : f = g := ext₂ $ λ m n, show flip f n m = flip g n m, by rw H variables (R M N P) /-- Given a linear map from `M` to linear maps from `N` to `P`, i.e., a bilinear map `M → N → P`, change the order of variables and get a linear map from `N` to linear maps from `M` to `P`. -/ def lflip : (M →ₗ[R] N →ₗ P) →ₗ[R] N →ₗ M →ₗ P := ⟨flip, λ _ _, rfl, λ _ _, rfl⟩ variables {R M N P} @[simp] theorem lflip_apply (m : M) (n : N) : lflip R M N P f n m = f m n := rfl theorem map_zero₂ (y) : f 0 y = 0 := (flip f y).map_zero theorem map_neg₂ {R : Type*} [comm_ring R] {M N P : Type*} [add_comm_group M] [add_comm_group N] [add_comm_group P] [module R M] [module R N] [module R P] (f : M →ₗ[R] N →ₗ[R] P) (x y) : f (-x) y = -f x y := (flip f y).map_neg _ theorem map_add₂ (x₁ x₂ y) : f (x₁ + x₂) y = f x₁ y + f x₂ y := (flip f y).map_add _ _ theorem map_smul₂ (r:R) (x y) : f (r • x) y = r • f x y := (flip f y).map_smul _ _ variables (R P) /-- Composing a linear map `M → N` and a linear map `N → P` to form a linear map `M → P`. -/ def lcomp (f : M →ₗ[R] N) : (N →ₗ[R] P) →ₗ[R] M →ₗ[R] P := flip $ linear_map.comp (flip id) f variables {R P} @[simp] theorem lcomp_apply (f : M →ₗ[R] N) (g : N →ₗ P) (x : M) : lcomp R P f g x = g (f x) := rfl variables (R M N P) /-- Composing a linear map `M → N` and a linear map `N → P` to form a linear map `M → P`. -/ def llcomp : (N →ₗ[R] P) →ₗ[R] (M →ₗ[R] N) →ₗ M →ₗ P := flip ⟨lcomp R P, λ f f', ext₂ $ λ g x, g.map_add _ _, λ c f, ext₂ $ λ g x, g.map_smul _ _⟩ variables {R M N P} section @[simp] theorem llcomp_apply (f : N →ₗ[R] P) (g : M →ₗ[R] N) (x : M) : llcomp R M N P f g x = f (g x) := rfl end /-- Composing a linear map `Q → N` and a bilinear map `M → N → P` to form a bilinear map `M → Q → P`. -/ def compl₂ (g : Q →ₗ N) : M →ₗ Q →ₗ P := (lcomp R _ g).comp f @[simp] theorem compl₂_apply (g : Q →ₗ[R] N) (m : M) (q : Q) : f.compl₂ g m q = f m (g q) := rfl /-- Composing a linear map `P → Q` and a bilinear map `M × N → P` to form a bilinear map `M → N → Q`. -/ def compr₂ (g : P →ₗ Q) : M →ₗ N →ₗ Q := linear_map.comp (llcomp R N P Q g) f @[simp] theorem compr₂_apply (g : P →ₗ[R] Q) (m : M) (n : N) : f.compr₂ g m n = g (f m n) := rfl variables (R M) /-- Scalar multiplication as a bilinear map `R → M → M`. -/ def lsmul : R →ₗ M →ₗ M := mk₂ R (•) add_smul (λ _ _ _, mul_smul _ _ _) smul_add (λ r s m, by simp only [smul_smul, smul_eq_mul, mul_comm]) variables {R M} @[simp] theorem lsmul_apply (r : R) (m : M) : lsmul R M r m = r • m := rfl end linear_map section semiring variables {R : Type*} [comm_semiring R] variables {M : Type*} {N : Type*} {P : Type*} {Q : Type*} {S : Type*} variables [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q] [add_comm_monoid S] variables [semimodule R M] [semimodule R N] [semimodule R P] [semimodule R Q] [semimodule R S] include R variables (M N) namespace tensor_product section -- open free_add_monoid variables (R) /-- The relation on `free_add_monoid (M × N)` that generates a congruence whose quotient is the tensor product. -/ inductive eqv : free_add_monoid (M × N) → free_add_monoid (M × N) → Prop | of_zero_left : ∀ n : N, eqv (free_add_monoid.of (0, n)) 0 | of_zero_right : ∀ m : M, eqv (free_add_monoid.of (m, 0)) 0 | of_add_left : ∀ (m₁ m₂ : M) (n : N), eqv (free_add_monoid.of (m₁, n) + free_add_monoid.of (m₂, n)) (free_add_monoid.of (m₁ + m₂, n)) | of_add_right : ∀ (m : M) (n₁ n₂ : N), eqv (free_add_monoid.of (m, n₁) + free_add_monoid.of (m, n₂)) (free_add_monoid.of (m, n₁ + n₂)) | of_smul : ∀ (r : R) (m : M) (n : N), eqv (free_add_monoid.of (r • m, n)) (free_add_monoid.of (m, r • n)) | add_comm : ∀ x y, eqv (x + y) (y + x) end end tensor_product variables (R) /-- The tensor product of two semimodules `M` and `N` over the same commutative semiring `R`. The localized notations are `M ⊗ N` and `M ⊗[R] N`, accessed by `open_locale tensor_product`. -/ def tensor_product : Type* := (add_con_gen (tensor_product.eqv R M N)).quotient variables {R} localized "infix ` ⊗ `:100 := tensor_product _" in tensor_product localized "notation M ` ⊗[`:100 R `] ` N:100 := tensor_product R M N" in tensor_product namespace tensor_product section module instance : add_comm_monoid (M ⊗[R] N) := { add_comm := λ x y, add_con.induction_on₂ x y $ λ x y, quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.add_comm _ _, .. (add_con_gen (tensor_product.eqv R M N)).add_monoid } instance : inhabited (M ⊗[R] N) := ⟨0⟩ variables (R) {M N} /-- The canonical function `M → N → M ⊗ N`. The localized notations are `m ⊗ₜ n` and `m ⊗ₜ[R] n`, accessed by `open_locale tensor_product`. -/ def tmul (m : M) (n : N) : M ⊗[R] N := add_con.mk' _ $ free_add_monoid.of (m, n) variables {R} infix ` ⊗ₜ `:100 := tmul _ notation x ` ⊗ₜ[`:100 R `] ` y := tmul R x y @[elab_as_eliminator] protected theorem induction_on {C : (M ⊗[R] N) → Prop} (z : M ⊗[R] N) (C0 : C 0) (C1 : ∀ {x y}, C $ x ⊗ₜ[R] y) (Cp : ∀ {x y}, C x → C y → C (x + y)) : C z := add_con.induction_on z $ λ x, free_add_monoid.rec_on x C0 $ λ ⟨m, n⟩ y ih, by { rw add_con.coe_add, exact Cp C1 ih } variables (M) @[simp] lemma zero_tmul (n : N) : (0 ⊗ₜ n : M ⊗[R] N) = 0 := quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_zero_left _ variables {M} lemma add_tmul (m₁ m₂ : M) (n : N) : (m₁ + m₂) ⊗ₜ n = m₁ ⊗ₜ n + m₂ ⊗ₜ[R] n := eq.symm $ quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_add_left _ _ _ variables (N) @[simp] lemma tmul_zero (m : M) : (m ⊗ₜ 0 : M ⊗[R] N) = 0 := quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_zero_right _ variables {N} lemma tmul_add (m : M) (n₁ n₂ : N) : m ⊗ₜ (n₁ + n₂) = m ⊗ₜ n₁ + m ⊗ₜ[R] n₂ := eq.symm $ quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_add_right _ _ _ lemma smul_tmul (r : R) (m : M) (n : N) : (r • m) ⊗ₜ n = m ⊗ₜ[R] (r • n) := quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_smul _ _ _ /-- Auxiliary function to defining scalar multiplication on tensor product. -/ def smul.aux (r : R) : free_add_monoid (M × N) →+ M ⊗[R] N := free_add_monoid.lift $ λ p : M × N, (r • p.1) ⊗ₜ p.2 theorem smul.aux_of (r : R) (m : M) (n : N) : smul.aux r (free_add_monoid.of (m, n)) = (r • m) ⊗ₜ n := rfl instance : has_scalar R (M ⊗[R] N) := ⟨λ r, (add_con_gen (tensor_product.eqv R M N)).lift (smul.aux r) $ add_con.add_con_gen_le $ λ x y hxy, match x, y, hxy with | _, _, (eqv.of_zero_left n) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_zero, smul.aux_of, smul_zero, zero_tmul] | _, _, (eqv.of_zero_right m) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_zero, smul.aux_of, tmul_zero] | _, _, (eqv.of_add_left m₁ m₂ n) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, smul.aux_of, smul_add, add_tmul] | _, _, (eqv.of_add_right m n₁ n₂) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, smul.aux_of, tmul_add] | _, _, (eqv.of_smul s m n) := (add_con.ker_rel _).2 $ by simp_rw [smul.aux_of, smul_tmul, smul_smul, mul_comm] | _, _, (eqv.add_comm x y) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, add_comm] end⟩ protected theorem smul_zero (r : R) : (r • 0 : M ⊗[R] N) = 0 := add_monoid_hom.map_zero _ protected theorem smul_add (r : R) (x y : M ⊗[R] N) : r • (x + y) = r • x + r • y := add_monoid_hom.map_add _ _ _ theorem smul_tmul' (r : R) (m : M) (n : N) : r • (m ⊗ₜ n : M ⊗[R] N) = (r • m) ⊗ₜ n := rfl instance : semimodule R (M ⊗[R] N) := { smul := (•), smul_add := λ r x y, tensor_product.smul_add r x y, mul_smul := λ r s x, tensor_product.induction_on x (by simp_rw tensor_product.smul_zero) (λ m n, by simp_rw [smul_tmul', mul_smul]) (λ x y ihx ihy, by { simp_rw tensor_product.smul_add, rw [ihx, ihy] }), one_smul := λ x, tensor_product.induction_on x (by rw tensor_product.smul_zero) (λ m n, by rw [smul_tmul', one_smul]) (λ x y ihx ihy, by rw [tensor_product.smul_add, ihx, ihy]), add_smul := λ r s x, tensor_product.induction_on x (by simp_rw [tensor_product.smul_zero, add_zero]) (λ m n, by simp_rw [smul_tmul', add_smul, add_tmul]) (λ x y ihx ihy, by { simp_rw tensor_product.smul_add, rw [ihx, ihy, add_add_add_comm] }), smul_zero := λ r, tensor_product.smul_zero r, zero_smul := λ x, tensor_product.induction_on x (by rw tensor_product.smul_zero) (λ m n, by rw [smul_tmul', zero_smul, zero_tmul]) (λ x y ihx ihy, by rw [tensor_product.smul_add, ihx, ihy, add_zero]) } @[simp] lemma tmul_smul (r : R) (x : M) (y : N) : x ⊗ₜ (r • y) = r • (x ⊗ₜ[R] y) := (smul_tmul _ _ _).symm variables (R M N) /-- The canonical bilinear map `M → N → M ⊗[R] N`. -/ def mk : M →ₗ N →ₗ M ⊗[R] N := linear_map.mk₂ R (⊗ₜ) add_tmul (λ c m n, by rw [smul_tmul, tmul_smul]) tmul_add tmul_smul variables {R M N} @[simp] lemma mk_apply (m : M) (n : N) : mk R M N m n = m ⊗ₜ n := rfl lemma ite_tmul (x₁ : M) (x₂ : N) (P : Prop) [decidable P] : ((if P then x₁ else 0) ⊗ₜ[R] x₂) = if P then (x₁ ⊗ₜ x₂) else 0 := by { split_ifs; simp } lemma tmul_ite (x₁ : M) (x₂ : N) (P : Prop) [decidable P] : (x₁ ⊗ₜ[R] (if P then x₂ else 0)) = if P then (x₁ ⊗ₜ x₂) else 0 := by { split_ifs; simp } section open_locale big_operators lemma sum_tmul {α : Type*} (s : finset α) (m : α → M) (n : N) : ((∑ a in s, m a) ⊗ₜ[R] n) = ∑ a in s, m a ⊗ₜ[R] n := begin classical, induction s using finset.induction with a s has ih h, { simp, }, { simp [finset.sum_insert has, add_tmul, ih], }, end lemma tmul_sum (m : M) {α : Type*} (s : finset α) (n : α → N) : (m ⊗ₜ[R] (∑ a in s, n a)) = ∑ a in s, m ⊗ₜ[R] n a := begin classical, induction s using finset.induction with a s has ih h, { simp, }, { simp [finset.sum_insert has, tmul_add, ih], }, end end end module section UMP variables {M N P Q} variables (f : M →ₗ[R] N →ₗ[R] P) /-- Auxiliary function to constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P` with the property that its composition with the canonical bilinear map `M → N → M ⊗ N` is the given bilinear map `M → N → P`. -/ def lift_aux : (M ⊗[R] N) →+ P := (add_con_gen (tensor_product.eqv R M N)).lift (free_add_monoid.lift $ λ p : M × N, f p.1 p.2) $ add_con.add_con_gen_le $ λ x y hxy, match x, y, hxy with | _, _, (eqv.of_zero_left n) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_zero, free_add_monoid.lift_eval_of, f.map_zero₂] | _, _, (eqv.of_zero_right m) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_zero, free_add_monoid.lift_eval_of, (f m).map_zero] | _, _, (eqv.of_add_left m₁ m₂ n) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, free_add_monoid.lift_eval_of, f.map_add₂] | _, _, (eqv.of_add_right m n₁ n₂) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, free_add_monoid.lift_eval_of, (f m).map_add] | _, _, (eqv.of_smul r m n) := (add_con.ker_rel _).2 $ by simp_rw [free_add_monoid.lift_eval_of, f.map_smul₂, (f m).map_smul] | _, _, (eqv.add_comm x y) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, add_comm] end lemma lift_aux_tmul (m n) : lift_aux f (m ⊗ₜ n) = f m n := zero_add _ variable {f} @[simp] lemma lift_aux.smul (r : R) (x) : lift_aux f (r • x) = r • lift_aux f x := tensor_product.induction_on x (smul_zero _).symm (λ p q, by rw [← tmul_smul, lift_aux_tmul, lift_aux_tmul, (f p).map_smul]) (λ p q ih1 ih2, by rw [smul_add, (lift_aux f).map_add, ih1, ih2, (lift_aux f).map_add, smul_add]) variable (f) /-- Constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P` with the property that its composition with the canonical bilinear map `M → N → M ⊗ N` is the given bilinear map `M → N → P`. -/ def lift : M ⊗ N →ₗ P := { map_smul' := lift_aux.smul, .. lift_aux f } variable {f} @[simp] lemma lift.tmul (x y) : lift f (x ⊗ₜ y) = f x y := zero_add _ @[simp] lemma lift.tmul' (x y) : (lift f).1 (x ⊗ₜ y) = f x y := lift.tmul _ _ @[ext] theorem ext {g h : (M ⊗[R] N) →ₗ[R] P} (H : ∀ x y, g (x ⊗ₜ y) = h (x ⊗ₜ y)) : g = h := linear_map.ext $ λ z, tensor_product.induction_on z (by simp_rw linear_map.map_zero) H $ λ x y ihx ihy, by rw [g.map_add, h.map_add, ihx, ihy] theorem lift.unique {g : (M ⊗[R] N) →ₗ[R] P} (H : ∀ x y, g (x ⊗ₜ y) = f x y) : g = lift f := ext $ λ m n, by rw [H, lift.tmul] theorem lift_mk : lift (mk R M N) = linear_map.id := eq.symm $ lift.unique $ λ x y, rfl theorem lift_compr₂ (g : P →ₗ Q) : lift (f.compr₂ g) = g.comp (lift f) := eq.symm $ lift.unique $ λ x y, by simp theorem lift_mk_compr₂ (f : M ⊗ N →ₗ P) : lift ((mk R M N).compr₂ f) = f := by rw [lift_compr₂ f, lift_mk, linear_map.comp_id] theorem mk_compr₂_inj {g h : M ⊗ N →ₗ P} (H : (mk R M N).compr₂ g = (mk R M N).compr₂ h) : g = h := by rw [← lift_mk_compr₂ g, H, lift_mk_compr₂] example : M → N → (M → N → P) → P := λ m, flip $ λ f, f m variables (R M N P) /-- Linearly constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P` with the property that its composition with the canonical bilinear map `M → N → M ⊗ N` is the given bilinear map `M → N → P`. -/ def uncurry : (M →ₗ[R] N →ₗ[R] P) →ₗ[R] M ⊗[R] N →ₗ[R] P := linear_map.flip $ lift $ (linear_map.lflip _ _ _ _).comp (linear_map.flip linear_map.id) variables {R M N P} @[simp] theorem uncurry_apply (f : M →ₗ[R] N →ₗ[R] P) (m : M) (n : N) : uncurry R M N P f (m ⊗ₜ n) = f m n := by rw [uncurry, linear_map.flip_apply, lift.tmul]; refl variables (R M N P) /-- A linear equivalence constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P` with the property that its composition with the canonical bilinear map `M → N → M ⊗ N` is the given bilinear map `M → N → P`. -/ def lift.equiv : (M →ₗ N →ₗ P) ≃ₗ (M ⊗ N →ₗ P) := { inv_fun := λ f, (mk R M N).compr₂ f, left_inv := λ f, linear_map.ext₂ $ λ m n, lift.tmul _ _, right_inv := λ f, ext $ λ m n, lift.tmul _ _, .. uncurry R M N P } /-- Given a linear map `M ⊗ N → P`, compose it with the canonical bilinear map `M → N → M ⊗ N` to form a bilinear map `M → N → P`. -/ def lcurry : (M ⊗[R] N →ₗ[R] P) →ₗ[R] M →ₗ[R] N →ₗ[R] P := (lift.equiv R M N P).symm variables {R M N P} @[simp] theorem lcurry_apply (f : M ⊗[R] N →ₗ[R] P) (m : M) (n : N) : lcurry R M N P f m n = f (m ⊗ₜ n) := rfl /-- Given a linear map `M ⊗ N → P`, compose it with the canonical bilinear map `M → N → M ⊗ N` to form a bilinear map `M → N → P`. -/ def curry (f : M ⊗ N →ₗ P) : M →ₗ N →ₗ P := lcurry R M N P f @[simp] theorem curry_apply (f : M ⊗ N →ₗ[R] P) (m : M) (n : N) : curry f m n = f (m ⊗ₜ n) := rfl theorem ext_threefold {g h : (M ⊗[R] N) ⊗[R] P →ₗ[R] Q} (H : ∀ x y z, g ((x ⊗ₜ y) ⊗ₜ z) = h ((x ⊗ₜ y) ⊗ₜ z)) : g = h := begin let e := linear_equiv.to_equiv (lift.equiv R (M ⊗[R] N) P Q), apply e.symm.injective, refine ext _, intros x y, ext z, exact H x y z end -- We'll need this one for checking the pentagon identity! theorem ext_fourfold {g h : ((M ⊗[R] N) ⊗[R] P) ⊗[R] Q →ₗ[R] S} (H : ∀ w x y z, g (((w ⊗ₜ x) ⊗ₜ y) ⊗ₜ z) = h (((w ⊗ₜ x) ⊗ₜ y) ⊗ₜ z)) : g = h := begin let e := linear_equiv.to_equiv (lift.equiv R ((M ⊗[R] N) ⊗[R] P) Q S), apply e.symm.injective, refine ext_threefold _, intros x y z, ext w, exact H x y z w, end end UMP variables {M N} section variables (R M) /-- The base ring is a left identity for the tensor product of modules, up to linear equivalence. -/ protected def lid : R ⊗ M ≃ₗ M := linear_equiv.of_linear (lift $ linear_map.lsmul R M) (mk R R M 1) (linear_map.ext $ λ _, by simp) (ext $ λ r m, by simp; rw [← tmul_smul, ← smul_tmul, smul_eq_mul, mul_one]) end @[simp] theorem lid_tmul (m : M) (r : R) : ((tensor_product.lid R M) : (R ⊗ M → M)) (r ⊗ₜ m) = r • m := begin dsimp [tensor_product.lid], simp, end section variables (R M N) /-- The tensor product of modules is commutative, up to linear equivalence. -/ protected def comm : M ⊗ N ≃ₗ N ⊗ M := linear_equiv.of_linear (lift (mk R N M).flip) (lift (mk R M N).flip) (ext $ λ m n, rfl) (ext $ λ m n, rfl) @[simp] theorem comm_tmul (m : M) (n : N) : ((tensor_product.comm R M N) : (M ⊗ N → N ⊗ M)) (m ⊗ₜ n) = n ⊗ₜ m := begin dsimp [tensor_product.comm], simp, end end section variables (R M) /-- The base ring is a right identity for the tensor product of modules, up to linear equivalence. -/ protected def rid : M ⊗[R] R ≃ₗ M := linear_equiv.trans (tensor_product.comm R M R) (tensor_product.lid R M) end @[simp] theorem rid_tmul (m : M) (r : R) : ((tensor_product.rid R M) : (M ⊗ R → M)) (m ⊗ₜ r) = r • m := begin dsimp [tensor_product.rid, tensor_product.comm, tensor_product.lid], simp, end open linear_map section variables (R M N P) /-- The associator for tensor product of R-modules, as a linear equivalence. -/ protected def assoc : (M ⊗[R] N) ⊗[R] P ≃ₗ[R] M ⊗[R] (N ⊗[R] P) := begin refine linear_equiv.of_linear (lift $ lift $ comp (lcurry R _ _ _) $ mk _ _ _) (lift $ comp (uncurry R _ _ _) $ curry $ mk _ _ _) (mk_compr₂_inj $ linear_map.ext $ λ m, ext $ λ n p, _) (mk_compr₂_inj $ flip_inj $ linear_map.ext $ λ p, ext $ λ m n, _); repeat { rw lift.tmul <|> rw compr₂_apply <|> rw comp_apply <|> rw mk_apply <|> rw flip_apply <|> rw lcurry_apply <|> rw uncurry_apply <|> rw curry_apply <|> rw id_apply } end end @[simp] theorem assoc_tmul (m : M) (n : N) (p : P) : ((tensor_product.assoc R M N P) : (M ⊗[R] N) ⊗[R] P → M ⊗[R] (N ⊗[R] P)) ((m ⊗ₜ n) ⊗ₜ p) = m ⊗ₜ (n ⊗ₜ p) := rfl /-- The tensor product of a pair of linear maps between modules. -/ def map (f : M →ₗ[R] P) (g : N →ₗ Q) : M ⊗ N →ₗ[R] P ⊗ Q := lift $ comp (compl₂ (mk _ _ _) g) f @[simp] theorem map_tmul (f : M →ₗ[R] P) (g : N →ₗ[R] Q) (m : M) (n : N) : map f g (m ⊗ₜ n) = f m ⊗ₜ g n := rfl /-- If M and P are linearly equivalent and N and Q are linearly equivalent then M ⊗ N and P ⊗ Q are linearly equivalent. -/ def congr (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) : M ⊗ N ≃ₗ[R] P ⊗ Q := linear_equiv.of_linear (map f g) (map f.symm g.symm) (ext $ λ m n, by simp; simp only [linear_equiv.apply_symm_apply]) (ext $ λ m n, by simp; simp only [linear_equiv.symm_apply_apply]) @[simp] theorem congr_tmul (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) (m : M) (n : N) : congr f g (m ⊗ₜ n) = f m ⊗ₜ g n := rfl end tensor_product end semiring section ring namespace tensor_product variables {R : Type*} [comm_ring R] variables {M : Type*} {N : Type*} {P : Type*} {Q : Type*} {S : Type*} variables [add_comm_group M] [add_comm_group N] [add_comm_group P] [add_comm_group Q] [add_comm_group S] variables [module R M] [module R N] [module R P] [module R Q] [module R S] open_locale tensor_product open linear_map instance : add_comm_group (M ⊗[R] N) := { neg := tensor_product.lift $ (mk R M N).comp $ (-1 : R) • linear_map.id, add_left_neg := λ x, suffices (tensor_product.lift $ (mk R M N).comp $ (-1 : R) • linear_map.id) + linear_map.id = 0, from linear_map.ext_iff.1 this x, ext $ λ m n, by rw [add_apply, lift.tmul, comp_apply, mk_apply, smul_apply, neg_one_smul, id_apply, id_apply, ← add_tmul, neg_add_self, zero_tmul, zero_apply], .. tensor_product.add_comm_monoid M N } lemma neg_tmul (m : M) (n : N) : (-m) ⊗ₜ n = -(m ⊗ₜ[R] n) := (mk R M N).map_neg₂ _ _ lemma tmul_neg (m : M) (n : N) : m ⊗ₜ (-n) = -(m ⊗ₜ[R] n) := (mk R M N _).map_neg _ variables (R) (ι₁ : Type*) (ι₂ : Type*) variables [decidable_eq ι₁] [decidable_eq ι₂] variables (M₁ : ι₁ → Type*) (M₂ : ι₂ → Type*) variables [Π i₁, add_comm_group (M₁ i₁)] [Π i₂, add_comm_group (M₂ i₂)] variables [Π i₁, module R (M₁ i₁)] [Π i₂, module R (M₂ i₂)] /-- The linear equivalence `(⊕ i₁, M₁ i₁) ⊗ (⊕ i₂, M₂ i₂) ≃ (⊕ i₁, ⊕ i₂, M₁ i₁ ⊗ M₂ i₂)`, i.e. "tensor product distributes over direct sum". -/ def direct_sum : direct_sum ι₁ M₁ ⊗[R] direct_sum ι₂ M₂ ≃ₗ[R] direct_sum (ι₁ × ι₂) (λ i, M₁ i.1 ⊗[R] M₂ i.2) := begin refine linear_equiv.of_linear (lift $ direct_sum.to_module R _ _ $ λ i₁, flip $ direct_sum.to_module R _ _ $ λ i₂, flip $ curry $ direct_sum.lof R (ι₁ × ι₂) (λ i, M₁ i.1 ⊗[R] M₂ i.2) (i₁, i₂)) (direct_sum.to_module R _ _ $ λ i, map (direct_sum.lof R _ _ _) (direct_sum.lof R _ _ _)) (linear_map.ext $ direct_sum.to_module.ext _ $ λ i, mk_compr₂_inj $ linear_map.ext $ λ x₁, linear_map.ext $ λ x₂, _) (mk_compr₂_inj $ linear_map.ext $ direct_sum.to_module.ext _ $ λ i₁, linear_map.ext $ λ x₁, linear_map.ext $ direct_sum.to_module.ext _ $ λ i₂, linear_map.ext $ λ x₂, _); repeat { rw compr₂_apply <|> rw comp_apply <|> rw id_apply <|> rw mk_apply <|> rw direct_sum.to_module_lof <|> rw map_tmul <|> rw lift.tmul <|> rw flip_apply <|> rw curry_apply }, cases i; refl end @[simp] theorem direct_sum_lof_tmul_lof (i₁ : ι₁) (m₁ : M₁ i₁) (i₂ : ι₂) (m₂ : M₂ i₂) : direct_sum R ι₁ ι₂ M₁ M₂ (direct_sum.lof R ι₁ M₁ i₁ m₁ ⊗ₜ direct_sum.lof R ι₂ M₂ i₂ m₂) = direct_sum.lof R (ι₁ × ι₂) (λ i, M₁ i.1 ⊗[R] M₂ i.2) (i₁, i₂) (m₁ ⊗ₜ m₂) := by simp [direct_sum] end tensor_product end ring
056dc99503ad6d3a9ae9bf04dde74fd6a7ad7848
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/measure_theory/arithmetic.lean
158072c5ffd782661f1706bfd1da465b55d60262
[ "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
25,052
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import measure_theory.measure_space /-! # Typeclasses for measurability of operations In this file we define classes `has_measurable_mul` etc and prove dot-style lemmas (`measurable.mul`, `ae_measurable.mul` etc). For binary operations we define two typeclasses: - `has_measurable_mul` says that both left and right multiplication are measurable; - `has_measurable_mul₂` says that `λ p : α × α, p.1 * p.2` is measurable, and similarly for other binary operations. The reason for introducing these classes is that in case of topological space `α` equipped with the Borel `σ`-algebra, instances for `has_measurable_mul₂` etc require `α` to have a second countable topology. We define separate classes for `has_measurable_div`/`has_measurable_sub` because on some types (e.g., `ℕ`, `ℝ≥0∞`) division and/or subtraction are not defined as `a * b⁻¹` / `a + (-b)`. For instances relating, e.g., `has_continuous_mul` to `has_measurable_mul` see file `measure_theory.borel_space`. ## Tags measurable function, arithmetic operator -/ universes u v open_locale big_operators open measure_theory variables {α : Type*} [measurable_space α] /-! ### Binary operations: `(+)`, `(*)`, `(-)`, `(/)` -/ /-- We say that a type `has_measurable_add` if `((+) c)` and `(+ c)` are measurable functions. For a typeclass assuming measurability of `uncurry (+)` see `has_measurable_add₂`. -/ class has_measurable_add (M : Type*) [measurable_space M] [has_add M] : Prop := (measurable_const_add : ∀ c : M, measurable ((+) c)) (measurable_add_const : ∀ c : M, measurable (+ c)) /-- We say that a type `has_measurable_add` if `uncurry (+)` is a measurable functions. For a typeclass assuming measurability of `((+) c)` and `(+ c)` see `has_measurable_add`. -/ class has_measurable_add₂ (M : Type*) [measurable_space M] [has_add M] : Prop := (measurable_add : measurable (λ p : M × M, p.1 + p.2)) export has_measurable_add₂ (measurable_add) has_measurable_add (measurable_const_add measurable_add_const) /-- We say that a type `has_measurable_mul` if `((*) c)` and `(* c)` are measurable functions. For a typeclass assuming measurability of `uncurry (*)` see `has_measurable_mul₂`. -/ @[to_additive] class has_measurable_mul (M : Type*) [measurable_space M] [has_mul M] : Prop := (measurable_const_mul : ∀ c : M, measurable ((*) c)) (measurable_mul_const : ∀ c : M, measurable (* c)) /-- We say that a type `has_measurable_mul` if `uncurry (*)` is a measurable functions. For a typeclass assuming measurability of `((*) c)` and `(* c)` see `has_measurable_mul`. -/ @[to_additive has_measurable_add₂] class has_measurable_mul₂ (M : Type*) [measurable_space M] [has_mul M] : Prop := (measurable_mul : measurable (λ p : M × M, p.1 * p.2)) export has_measurable_mul₂ (measurable_mul) has_measurable_mul (measurable_const_mul measurable_mul_const) section mul variables {M : Type*} [measurable_space M] [has_mul M] @[to_additive, measurability] lemma measurable.const_mul [has_measurable_mul M] {f : α → M} (hf : measurable f) (c : M) : measurable (λ x, c * f x) := (measurable_const_mul c).comp hf @[to_additive, measurability] lemma ae_measurable.const_mul [has_measurable_mul M] {f : α → M} {μ : measure α} (hf : ae_measurable f μ) (c : M) : ae_measurable (λ x, c * f x) μ := (has_measurable_mul.measurable_const_mul c).comp_ae_measurable hf @[to_additive, measurability] lemma measurable.mul_const [has_measurable_mul M] {f : α → M} (hf : measurable f) (c : M) : measurable (λ x, f x * c) := (measurable_mul_const c).comp hf @[to_additive, measurability] lemma ae_measurable.mul_const [has_measurable_mul M] {f : α → M} {μ : measure α} (hf : ae_measurable f μ) (c : M) : ae_measurable (λ x, f x * c) μ := (measurable_mul_const c).comp_ae_measurable hf @[to_additive, measurability] lemma measurable.mul' [has_measurable_mul₂ M] {f g : α → M} (hf : measurable f) (hg : measurable g) : measurable (f * g) := measurable_mul.comp (hf.prod_mk hg) @[to_additive, measurability] lemma measurable.mul [has_measurable_mul₂ M] {f g : α → M} (hf : measurable f) (hg : measurable g) : measurable (λ a, f a * g a) := measurable_mul.comp (hf.prod_mk hg) @[to_additive, measurability] lemma ae_measurable.mul' [has_measurable_mul₂ M] {μ : measure α} {f g : α → M} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (f * g) μ := measurable_mul.comp_ae_measurable (hf.prod_mk hg) @[to_additive, measurability] lemma ae_measurable.mul [has_measurable_mul₂ M] {μ : measure α} {f g : α → M} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ a, f a * g a) μ := measurable_mul.comp_ae_measurable (hf.prod_mk hg) @[priority 100, to_additive] instance has_measurable_mul₂.to_has_measurable_mul [has_measurable_mul₂ M] : has_measurable_mul M := ⟨λ c, measurable_const.mul measurable_id, λ c, measurable_id.mul measurable_const⟩ attribute [measurability] measurable.add' measurable.add ae_measurable.add ae_measurable.add' measurable.const_add ae_measurable.const_add measurable.add_const ae_measurable.add_const end mul /-- This class assumes that the map `β × γ → β` given by `(x, y) ↦ x ^ y` is measurable. -/ class has_measurable_pow (β γ : Type*) [measurable_space β] [measurable_space γ] [has_pow β γ] := (measurable_pow : measurable (λ p : β × γ, p.1 ^ p.2)) export has_measurable_pow (measurable_pow) instance has_measurable_mul.has_measurable_pow (M : Type*) [monoid M] [measurable_space M] [has_measurable_mul₂ M] : has_measurable_pow M ℕ := ⟨begin haveI : measurable_singleton_class ℕ := ⟨λ _, trivial⟩, refine measurable_from_prod_encodable (λ n, _), induction n with n ih, { simp [pow_zero, measurable_one] }, { simp only [pow_succ], exact measurable_id.mul ih } end⟩ section pow variables {β γ : Type*} [measurable_space β] [measurable_space γ] [has_pow β γ] [has_measurable_pow β γ] @[measurability] lemma measurable.pow {f : α → β} {g : α → γ} (hf : measurable f) (hg : measurable g) : measurable (λ x, f x ^ g x) := measurable_pow.comp (hf.prod_mk hg) @[measurability] lemma ae_measurable.pow {μ : measure α} {f : α → β} {g : α → γ} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ x, f x ^ g x) μ := measurable_pow.comp_ae_measurable (hf.prod_mk hg) @[measurability] lemma measurable.pow_const {f : α → β} (hf : measurable f) (c : γ) : measurable (λ x, f x ^ c) := hf.pow measurable_const @[measurability] lemma ae_measurable.pow_const {μ : measure α} {f : α → β} (hf : ae_measurable f μ) (c : γ) : ae_measurable (λ x, f x ^ c) μ := hf.pow ae_measurable_const @[measurability] lemma measurable.const_pow {f : α → γ} (hf : measurable f) (c : β) : measurable (λ x, c ^ f x) := measurable_const.pow hf @[measurability] lemma ae_measurable.const_pow {μ : measure α} {f : α → γ} (hf : ae_measurable f μ) (c : β) : ae_measurable (λ x, c ^ f x) μ := ae_measurable_const.pow hf end pow /-- We say that a type `has_measurable_sub` if `(λ x, c - x)` and `(λ x, x - c)` are measurable functions. For a typeclass assuming measurability of `uncurry (-)` see `has_measurable_sub₂`. -/ class has_measurable_sub (G : Type*) [measurable_space G] [has_sub G] : Prop := (measurable_const_sub : ∀ c : G, measurable (λ x, c - x)) (measurable_sub_const : ∀ c : G, measurable (λ x, x - c)) /-- We say that a type `has_measurable_sub` if `uncurry (-)` is a measurable functions. For a typeclass assuming measurability of `((-) c)` and `(- c)` see `has_measurable_sub`. -/ class has_measurable_sub₂ (G : Type*) [measurable_space G] [has_sub G] : Prop := (measurable_sub : measurable (λ p : G × G, p.1 - p.2)) export has_measurable_sub₂ (measurable_sub) /-- We say that a type `has_measurable_div` if `((/) c)` and `(/ c)` are measurable functions. For a typeclass assuming measurability of `uncurry (/)` see `has_measurable_div₂`. -/ @[to_additive] class has_measurable_div (G₀: Type*) [measurable_space G₀] [has_div G₀] : Prop := (measurable_const_div : ∀ c : G₀, measurable ((/) c)) (measurable_div_const : ∀ c : G₀, measurable (/ c)) /-- We say that a type `has_measurable_div` if `uncurry (/)` is a measurable functions. For a typeclass assuming measurability of `((/) c)` and `(/ c)` see `has_measurable_div`. -/ @[to_additive has_measurable_sub₂] class has_measurable_div₂ (G₀: Type*) [measurable_space G₀] [has_div G₀] : Prop := (measurable_div : measurable (λ p : G₀× G₀, p.1 / p.2)) export has_measurable_div₂ (measurable_div) section div variables {G : Type*} [measurable_space G] [has_div G] @[to_additive, measurability] lemma measurable.const_div [has_measurable_div G] {f : α → G} (hf : measurable f) (c : G) : measurable (λ x, c / f x) := (has_measurable_div.measurable_const_div c).comp hf @[to_additive, measurability] lemma ae_measurable.const_div [has_measurable_div G] {f : α → G} {μ : measure α} (hf : ae_measurable f μ) (c : G) : ae_measurable (λ x, c / f x) μ := (has_measurable_div.measurable_const_div c).comp_ae_measurable hf @[to_additive, measurability] lemma measurable.div_const [has_measurable_div G] {f : α → G} (hf : measurable f) (c : G) : measurable (λ x, f x / c) := (has_measurable_div.measurable_div_const c).comp hf @[to_additive, measurability] lemma ae_measurable.div_const [has_measurable_div G] {f : α → G} {μ : measure α} (hf : ae_measurable f μ) (c : G) : ae_measurable (λ x, f x / c) μ := (has_measurable_div.measurable_div_const c).comp_ae_measurable hf @[to_additive, measurability] lemma measurable.div' [has_measurable_div₂ G] {f g : α → G} (hf : measurable f) (hg : measurable g) : measurable (f / g) := measurable_div.comp (hf.prod_mk hg) @[to_additive, measurability] lemma measurable.div [has_measurable_div₂ G] {f g : α → G} (hf : measurable f) (hg : measurable g) : measurable (λ a, f a / g a) := measurable_div.comp (hf.prod_mk hg) @[to_additive, measurability] lemma ae_measurable.div' [has_measurable_div₂ G] {f g : α → G} {μ : measure α} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (f / g) μ := measurable_div.comp_ae_measurable (hf.prod_mk hg) @[to_additive, measurability] lemma ae_measurable.div [has_measurable_div₂ G] {f g : α → G} {μ : measure α} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ a, f a / g a) μ := measurable_div.comp_ae_measurable (hf.prod_mk hg) @[priority 100, to_additive] instance has_measurable_div₂.to_has_measurable_div [has_measurable_div₂ G] : has_measurable_div G := ⟨λ c, measurable_const.div measurable_id, λ c, measurable_id.div measurable_const⟩ attribute [measurability] measurable.sub measurable.sub' ae_measurable.sub ae_measurable.sub' measurable.const_sub ae_measurable.const_sub measurable.sub_const ae_measurable.sub_const lemma measurable_set_eq_fun {E} [measurable_space E] [add_group E] [measurable_singleton_class E] [has_measurable_sub₂ E] {f g : α → E} (hf : measurable f) (hg : measurable g) : measurable_set {x | f x = g x} := begin suffices h_set_eq : {x : α | f x = g x} = {x | (f-g) x = (0 : E)}, { rw h_set_eq, exact (hf.sub hg) measurable_set_eq, }, ext, simp_rw [set.mem_set_of_eq, pi.sub_apply, sub_eq_zero], end end div /-- We say that a type `has_measurable_neg` if `x ↦ -x` is a measurable function. -/ class has_measurable_neg (G : Type*) [has_neg G] [measurable_space G] : Prop := (measurable_neg : measurable (has_neg.neg : G → G)) /-- We say that a type `has_measurable_inv` if `x ↦ x⁻¹` is a measurable function. -/ @[to_additive] class has_measurable_inv (G : Type*) [has_inv G] [measurable_space G] : Prop := (measurable_inv : measurable (has_inv.inv : G → G)) export has_measurable_inv (measurable_inv) has_measurable_neg (measurable_neg) @[priority 100, to_additive] instance has_measurable_div_of_mul_inv (G : Type*) [measurable_space G] [div_inv_monoid G] [has_measurable_mul G] [has_measurable_inv G] : has_measurable_div G := { measurable_const_div := λ c, by { convert (measurable_inv.const_mul c), ext1, apply div_eq_mul_inv }, measurable_div_const := λ c, by { convert (measurable_id.mul_const c⁻¹), ext1, apply div_eq_mul_inv } } section inv variables {G : Type*} [has_inv G] [measurable_space G] [has_measurable_inv G] @[to_additive, measurability] lemma measurable.inv {f : α → G} (hf : measurable f) : measurable (λ x, (f x)⁻¹) := measurable_inv.comp hf @[to_additive, measurability] lemma ae_measurable.inv {f : α → G} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x)⁻¹) μ := measurable_inv.comp_ae_measurable hf attribute [measurability] measurable.neg ae_measurable.neg @[simp, to_additive] lemma measurable_inv_iff {G : Type*} [group G] [measurable_space G] [has_measurable_inv G] {f : α → G} : measurable (λ x, (f x)⁻¹) ↔ measurable f := ⟨λ h, by simpa only [inv_inv] using h.inv, λ h, h.inv⟩ @[simp, to_additive] lemma ae_measurable_inv_iff {G : Type*} [group G] [measurable_space G] [has_measurable_inv G] {f : α → G} {μ : measure α} : ae_measurable (λ x, (f x)⁻¹) μ ↔ ae_measurable f μ := ⟨λ h, by simpa only [inv_inv] using h.inv, λ h, h.inv⟩ @[simp] lemma measurable_inv_iff' {G₀ : Type*} [group_with_zero G₀] [measurable_space G₀] [has_measurable_inv G₀] {f : α → G₀} : measurable (λ x, (f x)⁻¹) ↔ measurable f := ⟨λ h, by simpa only [inv_inv'] using h.inv, λ h, h.inv⟩ @[simp] lemma ae_measurable_inv_iff' {G₀ : Type*} [group_with_zero G₀] [measurable_space G₀] [has_measurable_inv G₀] {f : α → G₀} {μ : measure α} : ae_measurable (λ x, (f x)⁻¹) μ ↔ ae_measurable f μ := ⟨λ h, by simpa only [inv_inv'] using h.inv, λ h, h.inv⟩ end inv /- There is something extremely strange here: copy-pasting the proof of this lemma in the proof of `has_measurable_gpow` fails, while `pp.all` does not show any difference in the goal. Keep it as a separate lemmas as a workaround. -/ private lemma has_measurable_gpow_aux (G : Type u) [div_inv_monoid G] [measurable_space G] [has_measurable_mul₂ G] [has_measurable_inv G] (k : ℕ) : measurable (λ (x : G), x ^(-[1+ k])) := begin simp_rw [gpow_neg_succ_of_nat], exact (measurable_id.pow_const (k + 1)).inv end instance has_measurable_gpow (G : Type u) [div_inv_monoid G] [measurable_space G] [has_measurable_mul₂ G] [has_measurable_inv G] : has_measurable_pow G ℤ := begin letI : measurable_singleton_class ℤ := ⟨λ _, trivial⟩, constructor, refine measurable_from_prod_encodable (λ n, _), dsimp, apply int.cases_on n, { simpa using measurable_id.pow_const }, { exact has_measurable_gpow_aux G } end @[priority 100, to_additive] instance has_measurable_div₂_of_mul_inv (G : Type*) [measurable_space G] [div_inv_monoid G] [has_measurable_mul₂ G] [has_measurable_inv G] : has_measurable_div₂ G := ⟨by { simp only [div_eq_mul_inv], exact measurable_fst.mul measurable_snd.inv }⟩ /-- We say that the action of `M` on `α` `has_measurable_smul` if for each `c` the map `x ↦ c • x` is a measurable function and for each `x` the map `c ↦ c • x` is a measurable function. -/ class has_measurable_smul (M α : Type*) [has_scalar M α] [measurable_space M] [measurable_space α] : Prop := (measurable_const_smul : ∀ c : M, measurable ((•) c : α → α)) (measurable_smul_const : ∀ x : α, measurable (λ c : M, c • x)) /-- We say that the action of `M` on `α` `has_measurable_smul` if the map `(c, x) ↦ c • x` is a measurable function. -/ class has_measurable_smul₂ (M α : Type*) [has_scalar M α] [measurable_space M] [measurable_space α] : Prop := (measurable_smul : measurable (function.uncurry (•) : M × α → α)) export has_measurable_smul (measurable_const_smul measurable_smul_const) has_measurable_smul₂ (measurable_smul) instance has_measurable_smul_of_mul (M : Type*) [monoid M] [measurable_space M] [has_measurable_mul M] : has_measurable_smul M M := ⟨measurable_id.const_mul, measurable_id.mul_const⟩ instance has_measurable_smul₂_of_mul (M : Type*) [monoid M] [measurable_space M] [has_measurable_mul₂ M] : has_measurable_smul₂ M M := ⟨measurable_mul⟩ section smul variables {M β : Type*} [measurable_space M] [measurable_space β] [has_scalar M β] @[measurability] lemma measurable.smul [has_measurable_smul₂ M β] {f : α → M} {g : α → β} (hf : measurable f) (hg : measurable g) : measurable (λ x, f x • g x) := measurable_smul.comp (hf.prod_mk hg) @[measurability] lemma ae_measurable.smul [has_measurable_smul₂ M β] {f : α → M} {g : α → β} {μ : measure α} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ x, f x • g x) μ := has_measurable_smul₂.measurable_smul.comp_ae_measurable (hf.prod_mk hg) @[priority 100] instance has_measurable_smul₂.to_has_measurable_smul [has_measurable_smul₂ M β] : has_measurable_smul M β := ⟨λ c, measurable_const.smul measurable_id, λ y, measurable_id.smul measurable_const⟩ variables [has_measurable_smul M β] {μ : measure α} @[measurability] lemma measurable.smul_const {f : α → M} (hf : measurable f) (y : β) : measurable (λ x, f x • y) := (has_measurable_smul.measurable_smul_const y).comp hf @[measurability] lemma ae_measurable.smul_const {f : α → M} (hf : ae_measurable f μ) (y : β) : ae_measurable (λ x, f x • y) μ := (has_measurable_smul.measurable_smul_const y).comp_ae_measurable hf @[measurability] lemma measurable.const_smul' {f : α → β} (hf : measurable f) (c : M) : measurable (λ x, c • f x) := (has_measurable_smul.measurable_const_smul c).comp hf @[measurability] lemma measurable.const_smul {f : α → β} (hf : measurable f) (c : M) : measurable (c • f) := hf.const_smul' c @[measurability] lemma ae_measurable.const_smul' {f : α → β} (hf : ae_measurable f μ) (c : M) : ae_measurable (λ x, c • f x) μ := (has_measurable_smul.measurable_const_smul c).comp_ae_measurable hf @[measurability] lemma ae_measurable.const_smul {f : α → β} (hf : ae_measurable f μ) (c : M) : ae_measurable (c • f) μ := hf.const_smul' c end smul section mul_action variables {M β : Type*} [measurable_space M] [measurable_space β] [monoid M] [mul_action M β] [has_measurable_smul M β] {f : α → β} {μ : measure α} variables {G : Type*} [group G] [measurable_space G] [mul_action G β] [has_measurable_smul G β] lemma measurable_const_smul_iff (c : G) : measurable (λ x, c • f x) ↔ measurable f := ⟨λ h, by simpa only [inv_smul_smul] using h.const_smul' c⁻¹, λ h, h.const_smul c⟩ lemma ae_measurable_const_smul_iff (c : G) : ae_measurable (λ x, c • f x) μ ↔ ae_measurable f μ := ⟨λ h, by simpa only [inv_smul_smul] using h.const_smul' c⁻¹, λ h, h.const_smul c⟩ instance : measurable_space (units M) := measurable_space.comap (coe : units M → M) ‹_› instance units.has_measurable_smul : has_measurable_smul (units M) β := { measurable_const_smul := λ c, (measurable_const_smul (c : M) : _), measurable_smul_const := λ x, (measurable_smul_const x : measurable (λ c : M, c • x)).comp measurable_space.le_map_comap, } lemma is_unit.measurable_const_smul_iff {c : M} (hc : is_unit c) : measurable (λ x, c • f x) ↔ measurable f := let ⟨u, hu⟩ := hc in hu ▸ measurable_const_smul_iff u lemma is_unit.ae_measurable_const_smul_iff {c : M} (hc : is_unit c) : ae_measurable (λ x, c • f x) μ ↔ ae_measurable f μ := let ⟨u, hu⟩ := hc in hu ▸ ae_measurable_const_smul_iff u variables {G₀ : Type*} [group_with_zero G₀] [measurable_space G₀] [mul_action G₀ β] [has_measurable_smul G₀ β] lemma measurable_const_smul_iff' {c : G₀} (hc : c ≠ 0) : measurable (λ x, c • f x) ↔ measurable f := (is_unit.mk0 c hc).measurable_const_smul_iff lemma ae_measurable_const_smul_iff' {c : G₀} (hc : c ≠ 0) : ae_measurable (λ x, c • f x) μ ↔ ae_measurable f μ := (is_unit.mk0 c hc).ae_measurable_const_smul_iff end mul_action /-! ### Big operators: `∏` and `∑` -/ @[to_additive, measurability] lemma list.measurable_prod' {M : Type*} [monoid M] [measurable_space M] [has_measurable_mul₂ M] (l : list (α → M)) (hl : ∀ f ∈ l, measurable f) : measurable l.prod := begin induction l with f l ihl, { exact measurable_one }, rw [list.forall_mem_cons] at hl, rw [list.prod_cons], exact hl.1.mul (ihl hl.2) end @[to_additive, measurability] lemma list.ae_measurable_prod' {M : Type*} [monoid M] [measurable_space M] [has_measurable_mul₂ M] {μ : measure α} (l : list (α → M)) (hl : ∀ f ∈ l, ae_measurable f μ) : ae_measurable l.prod μ := begin induction l with f l ihl, { exact ae_measurable_one }, rw [list.forall_mem_cons] at hl, rw [list.prod_cons], exact hl.1.mul (ihl hl.2) end @[to_additive, measurability] lemma list.measurable_prod {M : Type*} [monoid M] [measurable_space M] [has_measurable_mul₂ M] (l : list (α → M)) (hl : ∀ f ∈ l, measurable f) : measurable (λ x, (l.map (λ f : α → M, f x)).prod) := by simpa only [← pi.list_prod_apply] using l.measurable_prod' hl @[to_additive, measurability] lemma list.ae_measurable_prod {M : Type*} [monoid M] [measurable_space M] [has_measurable_mul₂ M] {μ : measure α} (l : list (α → M)) (hl : ∀ f ∈ l, ae_measurable f μ) : ae_measurable (λ x, (l.map (λ f : α → M, f x)).prod) μ := by simpa only [← pi.list_prod_apply] using l.ae_measurable_prod' hl @[to_additive, measurability] lemma multiset.measurable_prod' {M : Type*} [comm_monoid M] [measurable_space M] [has_measurable_mul₂ M] (l : multiset (α → M)) (hl : ∀ f ∈ l, measurable f) : measurable l.prod := by { rcases l with ⟨l⟩, simpa using l.measurable_prod' (by simpa using hl) } @[to_additive, measurability] lemma multiset.ae_measurable_prod' {M : Type*} [comm_monoid M] [measurable_space M] [has_measurable_mul₂ M] {μ : measure α} (l : multiset (α → M)) (hl : ∀ f ∈ l, ae_measurable f μ) : ae_measurable l.prod μ := by { rcases l with ⟨l⟩, simpa using l.ae_measurable_prod' (by simpa using hl) } @[to_additive, measurability] lemma multiset.measurable_prod {M : Type*} [comm_monoid M] [measurable_space M] [has_measurable_mul₂ M] (s : multiset (α → M)) (hs : ∀ f ∈ s, measurable f) : measurable (λ x, (s.map (λ f : α → M, f x)).prod) := by simpa only [← pi.multiset_prod_apply] using s.measurable_prod' hs @[to_additive, measurability] lemma multiset.ae_measurable_prod {M : Type*} [comm_monoid M] [measurable_space M] [has_measurable_mul₂ M] {μ : measure α} (s : multiset (α → M)) (hs : ∀ f ∈ s, ae_measurable f μ) : ae_measurable (λ x, (s.map (λ f : α → M, f x)).prod) μ := by simpa only [← pi.multiset_prod_apply] using s.ae_measurable_prod' hs @[to_additive, measurability] lemma finset.measurable_prod' {ι M : Type*} [comm_monoid M] [measurable_space M] [has_measurable_mul₂ M] {f : ι → α → M} (s : finset ι) (hf : ∀i ∈ s, measurable (f i)) : measurable (∏ i in s, f i) := finset.prod_induction _ _ (λ _ _, measurable.mul) (@measurable_one M _ _ _ _) hf @[to_additive, measurability] lemma finset.measurable_prod {ι M : Type*} [comm_monoid M] [measurable_space M] [has_measurable_mul₂ M] {f : ι → α → M} (s : finset ι) (hf : ∀i ∈ s, measurable (f i)) : measurable (λ a, ∏ i in s, f i a) := by simpa only [← finset.prod_apply] using s.measurable_prod' hf @[to_additive, measurability] lemma finset.ae_measurable_prod' {ι M : Type*} [comm_monoid M] [measurable_space M] [has_measurable_mul₂ M] {μ : measure α} {f : ι → α → M} (s : finset ι) (hf : ∀i ∈ s, ae_measurable (f i) μ) : ae_measurable (∏ i in s, f i) μ := multiset.ae_measurable_prod' _ $ λ g hg, let ⟨i, hi, hg⟩ := multiset.mem_map.1 hg in (hg ▸ hf _ hi) @[to_additive, measurability] lemma finset.ae_measurable_prod {ι M : Type*} [comm_monoid M] [measurable_space M] [has_measurable_mul₂ M] {f : ι → α → M} {μ : measure α} (s : finset ι) (hf : ∀i ∈ s, ae_measurable (f i) μ) : ae_measurable (λ a, ∏ i in s, f i a) μ := by simpa only [← finset.prod_apply] using s.ae_measurable_prod' hf attribute [measurability] list.measurable_sum' list.ae_measurable_sum' list.measurable_sum list.ae_measurable_sum multiset.measurable_sum' multiset.ae_measurable_sum' multiset.measurable_sum multiset.ae_measurable_sum finset.measurable_sum' finset.ae_measurable_sum' finset.measurable_sum finset.ae_measurable_sum
c81c699f41db5fe77998b5ae465a13bb03bde42f
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/linear_algebra/free_module/pid.lean
468d3090f9ad85b5e05b88d34f9f2e05f7e79d05
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
36,355
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import linear_algebra.basis import linear_algebra.finsupp_vector_space import ring_theory.principal_ideal_domain import ring_theory.finiteness /-! # Free modules over PID A free `R`-module `M` is a module with a basis over `R`, equivalently it is an `R`-module linearly equivalent to `ι →₀ R` for some `ι`. This file proves a submodule of a free `R`-module of finite rank is also a free `R`-module of finite rank, if `R` is a principal ideal domain (PID), i.e. we have instances `[integral_domain R] [is_principal_ideal_ring R]`. We express "free `R`-module of finite rank" as a module `M` which has a basis `b : ι → R`, where `ι` is a `fintype`. We call the cardinality of `ι` the rank of `M` in this file; it would be equal to `finrank R M` if `R` is a field and `M` is a vector space. ## Main results In this section, `M` is a free and finitely generated `R`-module, and `N` is a submodule of `M`. - `submodule.induction_on_rank`: if `P` holds for `⊥ : submodule R M` and if `P N` follows from `P N'` for all `N'` that are of lower rank, then `P` holds on all submodules - `submodule.exists_basis_of_pid`: if `R` is a PID, then `N : submodule R M` is free and finitely generated. This is the first part of the structure theorem for modules. - `submodule.smith_normal_form`: if `R` is a PID, then `M` has a basis `bM` and `N` has a basis `bN` such that `bN i = a i • bM i`. Equivalently, a linear map `f : M →ₗ M` with `range f = N` can be written as a matrix in Smith normal form, a diagonal matrix with the coefficients `a i` along the diagonal. ## Tags free module, finitely generated module, rank, structure theorem -/ open_locale big_operators section comm_ring universes u v variables {R : Type u} {M : Type v} [comm_ring R] [add_comm_group M] [module R M] variables {ι : Type*} (b : basis ι R M) open submodule.is_principal lemma eq_bot_of_rank_eq_zero [no_zero_divisors R] (b : basis ι R M) (N : submodule R M) (rank_eq : ∀ {m : ℕ} (v : fin m → N), linear_independent R (coe ∘ v : fin m → M) → m = 0) : N = ⊥ := begin rw submodule.eq_bot_iff, intros x hx, contrapose! rank_eq with x_ne, refine ⟨1, λ _, ⟨x, hx⟩, _, one_ne_zero⟩, rw fintype.linear_independent_iff, rintros g sum_eq i, fin_cases i, simp only [function.const_apply, fin.default_eq_zero, submodule.coe_mk, univ_unique, function.comp_const, finset.sum_singleton] at sum_eq, exact (b.smul_eq_zero.mp sum_eq).resolve_right x_ne end open submodule lemma eq_bot_of_generator_maximal_map_eq_zero (b : basis ι R M) {N : submodule R M} {ϕ : M →ₗ[R] R} (hϕ : ∀ (ψ : M →ₗ[R] R), N.map ϕ ≤ N.map ψ → N.map ψ = N.map ϕ) [(N.map ϕ).is_principal] (hgen : generator (N.map ϕ) = 0) : N = ⊥ := begin rw submodule.eq_bot_iff, intros x hx, refine b.ext_elem (λ i, _), rw (eq_bot_iff_generator_eq_zero _).mpr hgen at hϕ, rw [linear_equiv.map_zero, finsupp.zero_apply], exact (submodule.eq_bot_iff _).mp (hϕ ((finsupp.lapply i) ∘ₗ ↑b.repr) bot_le) _ ⟨x, hx, rfl⟩ end /-- `(ϕ : O →ₗ M').submodule_image N` is `ϕ(N)` as a submodule of `M'` -/ def linear_map.submodule_image {M' : Type*} [add_comm_group M'] [module R M'] {O : submodule R M} (ϕ : O →ₗ[R] M') (N : submodule R M) : submodule R M' := (N.comap O.subtype).map ϕ @[simp] lemma linear_map.mem_submodule_image {M' : Type*} [add_comm_group M'] [module R M'] {O : submodule R M} {ϕ : O →ₗ[R] M'} {N : submodule R M} {x : M'} : x ∈ ϕ.submodule_image N ↔ ∃ y (yO : y ∈ O) (yN : y ∈ N), ϕ ⟨y, yO⟩ = x := begin refine submodule.mem_map.trans ⟨_, _⟩; simp_rw submodule.mem_comap, { rintro ⟨⟨y, yO⟩, (yN : y ∈ N), h⟩, exact ⟨y, yO, yN, h⟩ }, { rintro ⟨y, yO, yN, h⟩, exact ⟨⟨y, yO⟩, yN, h⟩ } end lemma linear_map.mem_submodule_image_of_le {M' : Type*} [add_comm_group M'] [module R M'] {O : submodule R M} {ϕ : O →ₗ[R] M'} {N : submodule R M} (hNO : N ≤ O) {x : M'} : x ∈ ϕ.submodule_image N ↔ ∃ y (yN : y ∈ N), ϕ ⟨y, hNO yN⟩ = x := begin refine linear_map.mem_submodule_image.trans ⟨_, _⟩, { rintro ⟨y, yO, yN, h⟩, exact ⟨y, yN, h⟩ }, { rintro ⟨y, yN, h⟩, exact ⟨y, hNO yN, yN, h⟩ } end lemma linear_map.submodule_image_apply_of_le {M' : Type*} [add_comm_group M'] [module R M'] {O : submodule R M} (ϕ : O →ₗ[R] M') (N : submodule R M) (hNO : N ≤ O) : ϕ.submodule_image N = (ϕ.comp (of_le hNO)).range := by rw [linear_map.submodule_image, linear_map.range_comp, range_of_le] lemma eq_bot_of_generator_maximal_submodule_image_eq_zero {N O : submodule R M} (b : basis ι R O) (hNO : N ≤ O) {ϕ : O →ₗ[R] R} (hϕ : ∀ (ψ : O →ₗ[R] R), ϕ.submodule_image N ≤ ψ.submodule_image N → ψ.submodule_image N = ϕ.submodule_image N) [(ϕ.submodule_image N).is_principal] (hgen : generator (ϕ.submodule_image N) = 0) : N = ⊥ := begin rw submodule.eq_bot_iff, intros x hx, refine congr_arg coe (show (⟨x, hNO hx⟩ : O) = 0, from b.ext_elem (λ i, _)), rw (eq_bot_iff_generator_eq_zero _).mpr hgen at hϕ, rw [linear_equiv.map_zero, finsupp.zero_apply], refine (submodule.eq_bot_iff _).mp (hϕ ((finsupp.lapply i) ∘ₗ ↑b.repr) bot_le) _ _, exact (linear_map.mem_submodule_image_of_le hNO).mpr ⟨x, hx, rfl⟩ end -- Note that the converse may not hold if `ϕ` is not injective. lemma generator_map_dvd_of_mem {N : submodule R M} (ϕ : M →ₗ[R] R) [(N.map ϕ).is_principal] {x : M} (hx : x ∈ N) : generator (N.map ϕ) ∣ ϕ x := by { rw [← mem_iff_generator_dvd, submodule.mem_map], exact ⟨x, hx, rfl⟩ } -- Note that the converse may not hold if `ϕ` is not injective. lemma generator_submodule_image_dvd_of_mem {N O : submodule R M} (hNO : N ≤ O) (ϕ : O →ₗ[R] R) [(ϕ.submodule_image N).is_principal] {x : M} (hx : x ∈ N) : generator (ϕ.submodule_image N) ∣ ϕ ⟨x, hNO hx⟩ := by { rw [← mem_iff_generator_dvd, linear_map.mem_submodule_image_of_le hNO], exact ⟨x, hx, rfl⟩ } end comm_ring section integral_domain variables {ι : Type*} {R : Type*} [comm_ring R] [integral_domain R] variables {M : Type*} [add_comm_group M] [module R M] {b : ι → M} lemma not_mem_of_ortho {x : M} {N : submodule R M} (ortho : ∀ (c : R) (y ∈ N), c • x + y = (0 : M) → c = 0) : x ∉ N := by { intro hx, simpa using ortho (-1) x hx } lemma ne_zero_of_ortho {x : M} {N : submodule R M} (ortho : ∀ (c : R) (y ∈ N), c • x + y = (0 : M) → c = 0) : x ≠ 0 := mt (λ h, show x ∈ N, from h.symm ▸ N.zero_mem) (not_mem_of_ortho ortho) /-- If `N` is a submodule with finite rank, do induction on adjoining a linear independent element to a submodule. -/ def submodule.induction_on_rank_aux (b : basis ι R M) (P : submodule R M → Sort*) (ih : ∀ (N : submodule R M), (∀ (N' ≤ N) (x ∈ N), (∀ (c : R) (y ∈ N'), c • x + y = (0 : M) → c = 0) → P N') → P N) (n : ℕ) (N : submodule R M) (rank_le : ∀ {m : ℕ} (v : fin m → N), linear_independent R (coe ∘ v : fin m → M) → m ≤ n) : P N := begin haveI : decidable_eq M := classical.dec_eq M, have Pbot : P ⊥, { apply ih, intros N N_le x x_mem x_ortho, exfalso, simpa using x_ortho 1 0 N.zero_mem }, induction n with n rank_ih generalizing N, { suffices : N = ⊥, { rwa this }, apply eq_bot_of_rank_eq_zero b _ (λ m v hv, nat.le_zero_iff.mp (rank_le v hv)) }, apply ih, intros N' N'_le x x_mem x_ortho, apply rank_ih, intros m v hli, refine nat.succ_le_succ_iff.mp (rank_le (fin.cons ⟨x, x_mem⟩ (λ i, ⟨v i, N'_le (v i).2⟩)) _), convert hli.fin_cons' x _ _, { ext i, refine fin.cases _ _ i; simp }, { intros c y hcy, refine x_ortho c y (submodule.span_le.mpr _ y.2) hcy, rintros _ ⟨z, rfl⟩, exact (v z).2 } end /-- In an `n`-dimensional space, the rank is at most `m`. -/ lemma basis.card_le_card_of_linear_independent_aux {R : Type*} [comm_ring R] [integral_domain R] (n : ℕ) {m : ℕ} (v : fin m → fin n → R) : linear_independent R v → m ≤ n := begin revert m, refine nat.rec_on n _ _, { intros m v hv, cases m, { refl }, exfalso, have : v 0 = 0, { ext i, exact fin_zero_elim i }, have := hv.ne_zero 0, contradiction }, intros n ih m v hv, cases m, { exact nat.zero_le _ }, -- Induction: try deleting a dimension and a vector. suffices : ∃ (v' : fin m → fin n → R), linear_independent R v', { obtain ⟨v', hv'⟩ := this, exact nat.succ_le_succ (ih v' hv') }, -- Either the `0`th dimension is irrelevant... by_cases this : linear_independent R (λ i, v i ∘ fin.succ), { exact ⟨_, this.comp fin.succ (fin.succ_injective _)⟩ }, -- ... or we can write (x, 0, 0, ...) = ∑ i, c i • v i where c i ≠ 0 for some i. simp only [fintype.linear_independent_iff, not_forall, not_imp] at this, obtain ⟨c, hc, i, hi⟩ := this, have hc : ∀ (j : fin n), ∑ (i : fin m.succ), c i * v i j.succ = 0, { intro j, convert congr_fun hc j, rw [@finset.sum_apply (fin n) (λ _, R) _ _ _], simp }, set x := ∑ i', c i' * v i' 0 with x_eq, -- We'll show each equation of the form (y, 0, 0, ...) = ∑ i', c' i' • v i' must have c' i ≠ 0. use λ i' j', v (i.succ_above i') j'.succ, rw fintype.linear_independent_iff at ⊢ hv, -- Assume that ∑ i, c' i • v i = (y, 0, 0, ...). intros c' hc' i', set y := ∑ i', c' i' * v (i.succ_above i') 0 with y_eq, have hc' : ∀ (j : fin n), (∑ (i' : fin m), c' i' * v (i.succ_above i') j.succ) = 0, { intro j, convert congr_fun hc' j, rw [@finset.sum_apply (fin n) (λ _, R) _ _ _], simp }, -- Combine these equations to get a linear dependence on the full space. have : ∑ i', (y * c i' - x * (@fin.insert_nth _ (λ _, R) i 0 c') i') • v i' = 0, { simp only [sub_smul, mul_smul, finset.sum_sub_distrib, ← finset.smul_sum], ext j, rw [pi.zero_apply, @pi.sub_apply (fin n.succ) (λ _, R) _ _ _ _], simp only [finset.sum_apply, pi.smul_apply, smul_eq_mul, sub_eq_zero], symmetry, rw [fin.sum_univ_succ_above _ i, fin.insert_nth_apply_same, zero_mul, zero_add, mul_comm], simp only [fin.insert_nth_apply_succ_above], refine fin.cases _ _ j, { simp }, { intro j, rw [hc', hc, zero_mul, mul_zero] } }, have hyc := hv _ this i, simp only [fin.insert_nth_apply_same, mul_zero, sub_zero, mul_eq_zero] at hyc, -- Therefore, either `c i = 0` (which contradicts the assumption on `i`) or `y = 0`. have hy := hyc.resolve_right hi, -- If `y = 0`, then we can extend `c'` to a linear dependence on the full space, -- which implies `c'` is trivial. convert hv (@fin.insert_nth _ (λ _, R) i 0 c') _ (i.succ_above i'), { rw fin.insert_nth_apply_succ_above }, ext j, -- After a bit of calculation, we find that `∑ i, c' i • v i = (y, 0, 0, ...) = 0` as promised. rw [@finset.sum_apply (fin n.succ) (λ _, R) _ _ _, pi.zero_apply], simp only [pi.smul_apply, smul_eq_mul], rw [fin.sum_univ_succ_above _ i, fin.insert_nth_apply_same, zero_mul, zero_add], simp only [fin.insert_nth_apply_succ_above], refine fin.cases _ _ j, { rw [← y_eq, hy] }, { exact hc' }, end lemma basis.card_le_card_of_linear_independent {R : Type*} [comm_ring R] [integral_domain R] [module R M] {ι : Type*} [fintype ι] (b : basis ι R M) {ι' : Type*} [fintype ι'] {v : ι' → M} (hv : linear_independent R v) : fintype.card ι' ≤ fintype.card ι := begin haveI := classical.dec_eq ι, haveI := classical.dec_eq ι', let e := fintype.equiv_fin ι, let e' := fintype.equiv_fin ι', let b := b.reindex e, have hv := (linear_independent_equiv e'.symm).mpr hv, have hv := hv.map' _ b.equiv_fun.ker, exact basis.card_le_card_of_linear_independent_aux (fintype.card ι) _ hv, end lemma basis.card_le_card_of_submodule {R : Type*} [comm_ring R] [integral_domain R] [module R M] (N : submodule R M) {ι : Type*} [fintype ι] (b : basis ι R M) {ι' : Type*} [fintype ι'] (b' : basis ι' R N) : fintype.card ι' ≤ fintype.card ι := b.card_le_card_of_linear_independent (b'.linear_independent.map' N.subtype N.ker_subtype) lemma basis.card_le_card_of_le {R : Type*} [comm_ring R] [integral_domain R] [module R M] {N O : submodule R M} (hNO : N ≤ O) {ι : Type*} [fintype ι] (b : basis ι R O) {ι' : Type*} [fintype ι'] (b' : basis ι' R N) : fintype.card ι' ≤ fintype.card ι := b.card_le_card_of_linear_independent (b'.linear_independent.map' (submodule.of_le hNO) (N.ker_of_le O _)) /-- If `N` is a submodule in a free, finitely generated module, do induction on adjoining a linear independent element to a submodule. -/ def submodule.induction_on_rank [fintype ι] (b : basis ι R M) (P : submodule R M → Sort*) (ih : ∀ (N : submodule R M), (∀ (N' ≤ N) (x ∈ N), (∀ (c : R) (y ∈ N'), c • x + y = (0 : M) → c = 0) → P N') → P N) (N : submodule R M) : P N := submodule.induction_on_rank_aux b P ih (fintype.card ι) N (λ s hs hli, by simpa using b.card_le_card_of_linear_independent hli) open submodule.is_principal set submodule lemma dvd_generator_iff {I : ideal R} [I.is_principal] {x : R} (hx : x ∈ I) : x ∣ generator I ↔ I = ideal.span {x} := begin conv_rhs { rw [← span_singleton_generator I] }, erw [ideal.span_singleton_eq_span_singleton, ← dvd_dvd_iff_associated, ← mem_iff_generator_dvd], exact ⟨λ h, ⟨hx, h⟩, λ h, h.2⟩ end /-- If `S` a finite-dimensional ring extension of `R` which is free as an `R`-module, then the rank of an ideal `I` of `S` over `R` is the same as the rank of `S`. -/ lemma ideal.rank_eq {S : Type*} [ring S] [domain S] [algebra R S] {n m : Type*} [fintype n] [fintype m] (b : basis n R S) {I : ideal S} (hI : I ≠ ⊥) (c : basis m R I) : fintype.card m = fintype.card n := begin obtain ⟨a, ha⟩ := submodule.nonzero_mem_of_bot_lt (bot_lt_iff_ne_bot.mpr hI), have : linear_independent R (λ i, b i • a), { have hb := b.linear_independent, rw fintype.linear_independent_iff at ⊢ hb, intros g hg, apply hb g, simp only [← smul_assoc, ← finset.sum_smul, smul_eq_zero] at hg, exact hg.resolve_right ha }, exact le_antisymm (b.card_le_card_of_linear_independent (c.linear_independent.map' (submodule.subtype I) (linear_map.ker_eq_bot.mpr subtype.coe_injective))) (c.card_le_card_of_linear_independent this), end end integral_domain section principal_ideal_domain open submodule.is_principal set submodule variables {ι : Type*} {R : Type*} [comm_ring R] [integral_domain R] [is_principal_ideal_ring R] variables {M : Type*} [add_comm_group M] [module R M] {b : ι → M} open submodule.is_principal lemma generator_maximal_submodule_image_dvd {N O : submodule R M} (hNO : N ≤ O) {ϕ : O →ₗ[R] R} (hϕ : ∀ (ψ : O →ₗ[R] R), ϕ.submodule_image N ≤ ψ.submodule_image N → ψ.submodule_image N = ϕ.submodule_image N) [(ϕ.submodule_image N).is_principal] (y : M) (yN : y ∈ N) (ϕy_eq : ϕ ⟨y, hNO yN⟩ = generator (ϕ.submodule_image N)) (ψ : O →ₗ[R] R) : generator (ϕ.submodule_image N) ∣ ψ ⟨y, hNO yN⟩ := begin let a : R := generator (ϕ.submodule_image N), let d : R := is_principal.generator (submodule.span R {a, ψ ⟨y, hNO yN⟩}), have d_dvd_left : d ∣ a := (mem_iff_generator_dvd _).mp (subset_span (mem_insert _ _)), have d_dvd_right : d ∣ ψ ⟨y, hNO yN⟩ := (mem_iff_generator_dvd _).mp (subset_span (mem_insert_of_mem _ (mem_singleton _))), refine dvd_trans _ d_dvd_right, rw [dvd_generator_iff, ideal.span, ← span_singleton_generator (submodule.span R {a, ψ ⟨y, hNO yN⟩})], obtain ⟨r₁, r₂, d_eq⟩ : ∃ r₁ r₂ : R, d = r₁ * a + r₂ * ψ ⟨y, hNO yN⟩, { obtain ⟨r₁, r₂', hr₂', hr₁⟩ := mem_span_insert.mp (is_principal.generator_mem (submodule.span R {a, ψ ⟨y, hNO yN⟩})), obtain ⟨r₂, rfl⟩ := mem_span_singleton.mp hr₂', exact ⟨r₁, r₂, hr₁⟩ }, let ψ' : O →ₗ[R] R := r₁ • ϕ + r₂ • ψ, have : span R {d} ≤ ψ'.submodule_image N, { rw [span_le, singleton_subset_iff, set_like.mem_coe, linear_map.mem_submodule_image_of_le hNO], refine ⟨y, yN, _⟩, change r₁ * ϕ ⟨y, hNO yN⟩ + r₂ * ψ ⟨y, hNO yN⟩ = d, rw [d_eq, ϕy_eq] }, refine le_antisymm (this.trans (le_of_eq _)) (ideal.span_singleton_le_span_singleton.mpr d_dvd_left), rw span_singleton_generator, refine hϕ ψ' (le_trans _ this), rw [← span_singleton_generator (ϕ.submodule_image N)], exact ideal.span_singleton_le_span_singleton.mpr d_dvd_left, { exact subset_span (mem_insert _ _) } end /-- The induction hypothesis of `submodule.basis_of_pid` and `submodule.smith_normal_form`. Basically, it says: let `N ≤ M` be a pair of submodules, then we can find a pair of submodules `N' ≤ M'` of strictly smaller rank, whose basis we can extend to get a basis of `N` and `M`. Moreover, if the basis for `M'` is up to scalars a basis for `N'`, then the basis we find for `M` is up to scalars a basis for `N`. For `basis_of_pid` we only need the first half and can fix `M = ⊤`, for `smith_normal_form` we need the full statement, but must also feed in a basis for `M` using `basis_of_pid` to keep the induction going. -/ lemma submodule.basis_of_pid_aux [fintype ι] {O : Type*} [add_comm_group O] [module R O] (M N : submodule R O) (b'M : basis ι R M) (N_bot : N ≠ ⊥) (N_le_M : N ≤ M) : ∃ (y ∈ M) (a : R) (hay : a • y ∈ N) (M' ≤ M) (N' ≤ N) (N'_le_M' : N' ≤ M') (y_ortho_M' : ∀ (c : R) (z : O), z ∈ M' → c • y + z = 0 → c = 0) (ay_ortho_N' : ∀ (c : R) (z : O), z ∈ N' → c • a • y + z = 0 → c = 0), ∀ (n') (bN' : basis (fin n') R N'), ∃ (bN : basis (fin (n' + 1)) R N), ∀ (m') (hn'm' : n' ≤ m') (bM' : basis (fin m') R M'), ∃ (hnm : (n' + 1) ≤ (m' + 1)) (bM : basis (fin (m' + 1)) R M), ∀ (as : fin n' → R) (h : ∀ (i : fin n'), (bN' i : O) = as i • (bM' (fin.cast_le hn'm' i) : O)), ∃ (as' : fin (n' + 1) → R), ∀ (i : fin (n' + 1)), (bN i : O) = as' i • (bM (fin.cast_le hnm i) : O) := begin -- Let `ϕ` be a maximal projection of `M` onto `R`, in the sense that there is -- no `ψ` whose image of `N` is larger than `ϕ`'s image of `N`. have : ∃ ϕ : M →ₗ[R] R, ∀ (ψ : M →ₗ[R] R), ϕ.submodule_image N ≤ ψ.submodule_image N → ψ.submodule_image N = ϕ.submodule_image N, { obtain ⟨P, P_eq, P_max⟩ := set_has_maximal_iff_noetherian.mpr (infer_instance : is_noetherian R R) _ (show (set.range (λ ψ : M →ₗ[R] R, ψ.submodule_image N)).nonempty, from ⟨_, set.mem_range.mpr ⟨0, rfl⟩⟩), obtain ⟨ϕ, rfl⟩ := set.mem_range.mp P_eq, exact ⟨ϕ, λ ψ hψ, P_max _ ⟨_, rfl⟩ hψ⟩ }, let ϕ := this.some, have ϕ_max := this.some_spec, -- Since `ϕ(N)` is a `R`-submodule of the PID `R`, -- it is principal and generated by some `a`. let a := generator (ϕ.submodule_image N), have a_mem : a ∈ ϕ.submodule_image N := generator_mem _, -- If `a` is zero, then the submodule is trivial. So let's assume `a ≠ 0`, `N ≠ ⊥`. by_cases a_zero : a = 0, { have := eq_bot_of_generator_maximal_submodule_image_eq_zero b'M N_le_M ϕ_max a_zero, contradiction }, -- We claim that `ϕ⁻¹ a = y` can be taken as basis element of `N`. obtain ⟨y, yN, ϕy_eq⟩ := (linear_map.mem_submodule_image_of_le N_le_M).mp a_mem, have ϕy_ne_zero : ϕ ⟨y, N_le_M yN⟩ ≠ 0 := λ h, a_zero (ϕy_eq.symm.trans h), -- Write `y` as `a • y'` for some `y'`. have hdvd : ∀ i, a ∣ b'M.coord i ⟨y, N_le_M yN⟩ := λ i, generator_maximal_submodule_image_dvd N_le_M ϕ_max y yN ϕy_eq (b'M.coord i), choose c hc using hdvd, let y' : O := ∑ i, c i • b'M i, have y'M : y' ∈ M := M.sum_mem (λ i _, M.smul_mem (c i) (b'M i).2), have mk_y' : (⟨y', y'M⟩ : M) = ∑ i, c i • b'M i := subtype.ext (show y' = M.subtype _, by { simp only [linear_map.map_sum, linear_map.map_smul], refl }), have a_smul_y' : a • y' = y, { refine congr_arg coe (show (a • ⟨y', y'M⟩ : M) = ⟨y, N_le_M yN⟩, from _), rw [← b'M.sum_repr ⟨y, N_le_M yN⟩, mk_y', finset.smul_sum], refine finset.sum_congr rfl (λ i _, _), rw [← mul_smul, ← hc], refl }, -- We found an `y` and an `a`! refine ⟨y', y'M, a, a_smul_y'.symm ▸ yN, _⟩, have ϕy'_eq : ϕ ⟨y', y'M⟩ = 1 := mul_left_cancel₀ a_zero (calc a • ϕ ⟨y', y'M⟩ = ϕ ⟨a • y', _⟩ : (ϕ.map_smul a ⟨y', y'M⟩).symm ... = ϕ ⟨y, N_le_M yN⟩ : by simp only [a_smul_y'] ... = a : ϕy_eq ... = a * 1 : (mul_one a).symm), have ϕy'_ne_zero : ϕ ⟨y', y'M⟩ ≠ 0 := by simpa only [ϕy'_eq] using one_ne_zero, -- `M' := ker (ϕ : M → R)` is smaller than `M` and `N' := ker (ϕ : N → R)` is smaller than `N`. let M' : submodule R O := ϕ.ker.map M.subtype, let N' : submodule R O := (ϕ.comp (of_le N_le_M)).ker.map N.subtype, have M'_le_M : M' ≤ M := M.map_subtype_le ϕ.ker, have N'_le_M' : N' ≤ M', { intros x hx, simp only [mem_map, linear_map.mem_ker] at hx ⊢, obtain ⟨⟨x, xN⟩, hx, rfl⟩ := hx, exact ⟨⟨x, N_le_M xN⟩, hx, rfl⟩ }, have N'_le_N : N' ≤ N := N.map_subtype_le (ϕ.comp (of_le N_le_M)).ker, -- So fill in those results as well. refine ⟨M', M'_le_M, N', N'_le_N, N'_le_M', _⟩, -- Note that `y'` is orthogonal to `M'`. have y'_ortho_M' : ∀ (c : R) z ∈ M', c • y' + z = 0 → c = 0, { intros c x xM' hc, obtain ⟨⟨x, xM⟩, hx', rfl⟩ := submodule.mem_map.mp xM', rw linear_map.mem_ker at hx', have hc' : (c • ⟨y', y'M⟩ + ⟨x, xM⟩ : M) = 0 := subtype.coe_injective hc, simpa only [linear_map.map_add, linear_map.map_zero, linear_map.map_smul, smul_eq_mul, add_zero, mul_eq_zero, ϕy'_ne_zero, hx', or_false] using congr_arg ϕ hc' }, -- And `a • y'` is orthogonal to `N'`. have ay'_ortho_N' : ∀ (c : R) z ∈ N', c • a • y' + z = 0 → c = 0, { intros c z zN' hc, refine (mul_eq_zero.mp (y'_ortho_M' (a * c) z (N'_le_M' zN') _)).resolve_left a_zero, rw [mul_comm, mul_smul, hc] }, -- So we can extend a basis for `N'` with `y` refine ⟨y'_ortho_M', ay'_ortho_N', λ n' bN', ⟨_, _⟩⟩, { refine basis.mk_fin_cons_of_le y yN bN' N'_le_N _ _, { intros c z zN' hc, refine ay'_ortho_N' c z zN' _, rwa ← a_smul_y' at hc }, { intros z zN, obtain ⟨b, hb⟩ : _ ∣ ϕ ⟨z, N_le_M zN⟩ := generator_submodule_image_dvd_of_mem N_le_M ϕ zN, refine ⟨-b, submodule.mem_map.mpr ⟨⟨_, N.sub_mem zN (N.smul_mem b yN)⟩, _, _⟩⟩, { refine linear_map.mem_ker.mpr (show ϕ (⟨z, N_le_M zN⟩ - b • ⟨y, N_le_M yN⟩) = 0, from _), rw [linear_map.map_sub, linear_map.map_smul, hb, ϕy_eq, smul_eq_mul, mul_comm, sub_self] }, { simp only [sub_eq_add_neg, neg_smul], refl } } }, -- And extend a basis for `M'` with `y'` intros m' hn'm' bM', refine ⟨nat.succ_le_succ hn'm', _, _⟩, { refine basis.mk_fin_cons_of_le y' y'M bM' M'_le_M y'_ortho_M' _, intros z zM, refine ⟨-ϕ ⟨z, zM⟩, ⟨⟨z, zM⟩ - (ϕ ⟨z, zM⟩) • ⟨y', y'M⟩, linear_map.mem_ker.mpr _, _⟩⟩, { rw [linear_map.map_sub, linear_map.map_smul, ϕy'_eq, smul_eq_mul, mul_one, sub_self] }, { rw [linear_map.map_sub, linear_map.map_smul, sub_eq_add_neg, neg_smul], refl } }, -- It remains to show the extended bases are compatible with each other. intros as h, refine ⟨fin.cons a as, _⟩, intro i, rw [basis.coe_mk_fin_cons_of_le, basis.coe_mk_fin_cons_of_le], refine fin.cases _ (λ i, _) i, { simp only [fin.cons_zero, fin.cast_le_zero], exact a_smul_y'.symm }, { rw fin.cast_le_succ, simp only [fin.cons_succ, coe_of_le, h i] } end /-- A submodule of a free `R`-module of finite rank is also a free `R`-module of finite rank, if `R` is a principal ideal domain. This is a `lemma` to make the induction a bit easier. To actually access the basis, see `submodule.basis_of_pid`. See also the stronger version `submodule.smith_normal_form`. -/ lemma submodule.nonempty_basis_of_pid {ι : Type*} [fintype ι] (b : basis ι R M) (N : submodule R M) : ∃ (n : ℕ), nonempty (basis (fin n) R N) := begin haveI := classical.dec_eq M, refine N.induction_on_rank b _ _, intros N ih, let b' := (b.reindex (fintype.equiv_fin ι)).map (linear_equiv.of_top _ rfl).symm, by_cases N_bot : N = ⊥, { subst N_bot, exact ⟨0, ⟨basis.empty _⟩⟩ }, obtain ⟨y, -, a, hay, M', -, N', N'_le_N, -, -, ay_ortho, h'⟩ := submodule.basis_of_pid_aux ⊤ N b' N_bot le_top, obtain ⟨n', ⟨bN'⟩⟩ := ih N' N'_le_N _ hay ay_ortho, obtain ⟨bN, hbN⟩ := h' n' bN', exact ⟨n' + 1, ⟨bN⟩⟩ end /-- A submodule of a free `R`-module of finite rank is also a free `R`-module of finite rank, if `R` is a principal ideal domain. See also the stronger version `submodule.smith_normal_form`. -/ noncomputable def submodule.basis_of_pid {ι : Type*} [fintype ι] (b : basis ι R M) (N : submodule R M) : Σ (n : ℕ), (basis (fin n) R N) := ⟨_, (N.nonempty_basis_of_pid b).some_spec.some⟩ lemma submodule.basis_of_pid_bot {ι : Type*} [fintype ι] (b : basis ι R M) : submodule.basis_of_pid b ⊥ = ⟨0, basis.empty _⟩ := begin obtain ⟨n, b'⟩ := submodule.basis_of_pid b ⊥, let e : fin n ≃ fin 0 := b'.index_equiv (basis.empty _ : basis (fin 0) R (⊥ : submodule R M)), have : n = 0 := by simpa using fintype.card_eq.mpr ⟨e⟩, subst this, exact sigma.eq rfl (basis.eq_of_apply_eq $ fin_zero_elim) end /-- A submodule inside a free `R`-submodule of finite rank is also a free `R`-module of finite rank, if `R` is a principal ideal domain. See also the stronger version `submodule.smith_normal_form_of_le`. -/ noncomputable def submodule.basis_of_pid_of_le {ι : Type*} [fintype ι] {N O : submodule R M} (hNO : N ≤ O) (b : basis ι R O) : Σ (n : ℕ), basis (fin n) R N := let ⟨n, bN'⟩ := submodule.basis_of_pid b (N.comap O.subtype) in ⟨n, bN'.map (submodule.comap_subtype_equiv_of_le hNO)⟩ /-- A submodule inside the span of a linear independent family is a free `R`-module of finite rank, if `R` is a principal ideal domain. -/ noncomputable def submodule.basis_of_pid_of_le_span {ι : Type*} [fintype ι] {b : ι → M} (hb : linear_independent R b) {N : submodule R M} (le : N ≤ submodule.span R (set.range b)) : Σ (n : ℕ), basis (fin n) R N := submodule.basis_of_pid_of_le le (basis.span hb) variable {M} /-- A finite type torsion free module over a PID is free. -/ noncomputable def module.free_of_finite_type_torsion_free [fintype ι] {s : ι → M} (hs : span R (range s) = ⊤) [no_zero_smul_divisors R M] : Σ (n : ℕ), basis (fin n) R M := begin classical, -- We define `N` as the submodule spanned by a maximal linear independent subfamily of `s` have := exists_maximal_independent R s, let I : set ι := this.some, obtain ⟨indepI : linear_independent R (s ∘ coe : I → M), hI : ∀ i ∉ I, ∃ a : R, a ≠ 0 ∧ a • s i ∈ span R (s '' I)⟩ := this.some_spec, let N := span R (range $ (s ∘ coe : I → M)), -- same as `span R (s '' I)` but more convenient let sI : I → N := λ i, ⟨s i.1, subset_span (mem_range_self i)⟩, -- `s` restricted to `I` let sI_basis : basis I R N, -- `s` restricted to `I` is a basis of `N` from basis.span indepI, -- Our first goal is to build `A ≠ 0` such that `A • M ⊆ N` have exists_a : ∀ i : ι, ∃ a : R, a ≠ 0 ∧ a • s i ∈ N, { intro i, by_cases hi : i ∈ I, { use [1, zero_ne_one.symm], rw one_smul, exact subset_span (mem_range_self (⟨i, hi⟩ : I)) }, { simpa [image_eq_range s I] using hI i hi } }, choose a ha ha' using exists_a, let A := ∏ i, a i, have hA : A ≠ 0, { rw finset.prod_ne_zero_iff, simpa using ha }, -- `M ≃ A • M` because `M` is torsion free and `A ≠ 0` let φ : M →ₗ[R] M := linear_map.lsmul R M A, have : φ.ker = ⊥, from linear_map.ker_lsmul hA, let ψ : M ≃ₗ[R] φ.range := linear_equiv.of_injective φ (linear_map.ker_eq_bot.mp this), have : φ.range ≤ N, -- as announced, `A • M ⊆ N` { suffices : ∀ i, φ (s i) ∈ N, { rw [linear_map.range_eq_map, ← hs, φ.map_span_le], rintros _ ⟨i, rfl⟩, apply this }, intro i, calc (∏ j, a j) • s i = (∏ j in {i}ᶜ, a j) • a i • s i : by rw [fintype.prod_eq_prod_compl_mul i, mul_smul] ... ∈ N : N.smul_mem _ (ha' i) }, -- Since a submodule of a free `R`-module is free, we get that `A • M` is free obtain ⟨n, b : basis (fin n) R φ.range⟩ := submodule.basis_of_pid_of_le this sI_basis, -- hence `M` is free. exact ⟨n, b.map ψ.symm⟩ end /-- A finite type torsion free module over a PID is free. -/ noncomputable def module.free_of_finite_type_torsion_free' [module.finite R M] [no_zero_smul_divisors R M] : Σ (n : ℕ), basis (fin n) R M := module.free_of_finite_type_torsion_free module.finite.exists_fin.some_spec.some_spec section smith_normal /-- A Smith normal form basis for a submodule `N` of a module `M` consists of bases for `M` and `N` such that the inclusion map `N → M` can be written as a (rectangular) matrix with `a` along the diagonal: in Smith normal form. -/ @[nolint has_inhabited_instance] structure basis.smith_normal_form (N : submodule R M) (ι : Type*) (n : ℕ) := (bM : basis ι R M) (bN : basis (fin n) R N) (f : fin n ↪ ι) (a : fin n → R) (snf : ∀ i, (bN i : M) = a i • bM (f i)) /-- If `M` is finite free over a PID `R`, then any submodule `N` is free and we can find a basis for `M` and `N` such that the inclusion map is a diagonal matrix in Smith normal form. See `submodule.smith_normal_form_of_le` for a version of this theorem that returns a `basis.smith_normal_form`. This is a strengthening of `submodule.basis_of_pid_of_le`. -/ theorem submodule.exists_smith_normal_form_of_le [fintype ι] (b : basis ι R M) (N O : submodule R M) (N_le_O : N ≤ O) : ∃ (n o : ℕ) (hno : n ≤ o) (bO : basis (fin o) R O) (bN : basis (fin n) R N) (a : fin n → R), ∀ i, (bN i : M) = a i • bO (fin.cast_le hno i) := begin revert N, refine induction_on_rank b _ _ O, intros M ih N N_le_M, obtain ⟨m, b'M⟩ := M.basis_of_pid b, by_cases N_bot : N = ⊥, { subst N_bot, exact ⟨0, m, nat.zero_le _, b'M, basis.empty _, fin_zero_elim, fin_zero_elim⟩ }, obtain ⟨y, hy, a, hay, M', M'_le_M, N', N'_le_N, N'_le_M', y_ortho, ay_ortho, h⟩ := submodule.basis_of_pid_aux M N b'M N_bot N_le_M, obtain ⟨n', m', hn'm', bM', bN', as', has'⟩ := ih M' M'_le_M y hy y_ortho N' N'_le_M', obtain ⟨bN, h'⟩ := h n' bN', obtain ⟨hmn, bM, h''⟩ := h' m' hn'm' bM', obtain ⟨as, has⟩ := h'' as' has', exact ⟨_, _, hmn, bM, bN, as, has⟩ end /-- If `M` is finite free over a PID `R`, then any submodule `N` is free and we can find a basis for `M` and `N` such that the inclusion map is a diagonal matrix in Smith normal form. See `submodule.exists_smith_normal_form_of_le` for a version of this theorem that doesn't need to map `N` into a submodule of `O`. This is a strengthening of `submodule.basis_of_pid_of_le`. -/ noncomputable def submodule.smith_normal_form_of_le [fintype ι] (b : basis ι R M) (N O : submodule R M) (N_le_O : N ≤ O) : Σ (o n : ℕ), basis.smith_normal_form (N.comap O.subtype) (fin o) n := begin choose n o hno bO bN a snf using N.exists_smith_normal_form_of_le b O N_le_O, refine ⟨o, n, bO, bN.map (comap_subtype_equiv_of_le N_le_O).symm, (fin.cast_le hno).to_embedding, a, λ i, _⟩, ext, simp only [snf, basis.map_apply, submodule.comap_subtype_equiv_of_le_symm_apply_coe_coe, submodule.coe_smul_of_tower, rel_embedding.coe_fn_to_embedding] end /-- If `M` is finite free over a PID `R`, then any submodule `N` is free and we can find a basis for `M` and `N` such that the inclusion map is a diagonal matrix in Smith normal form. This is a strengthening of `submodule.basis_of_pid`. See also `ideal.smith_normal_form`, which moreover proves that the dimension of an ideal is the same as the dimension of the whole ring. -/ noncomputable def submodule.smith_normal_form [fintype ι] (b : basis ι R M) (N : submodule R M) : Σ (n : ℕ), basis.smith_normal_form N ι n := let ⟨m, n, bM, bN, f, a, snf⟩ := N.smith_normal_form_of_le b ⊤ le_top, bM' := bM.map (linear_equiv.of_top _ rfl), e := bM'.index_equiv b in ⟨n, bM'.reindex e, bN.map (comap_subtype_equiv_of_le le_top), f.trans e.to_embedding, a, λ i, by simp only [snf, basis.map_apply, linear_equiv.of_top_apply, submodule.coe_smul_of_tower, submodule.comap_subtype_equiv_of_le_apply_coe, coe_coe, basis.reindex_apply, equiv.to_embedding_apply, function.embedding.trans_apply, equiv.symm_apply_apply]⟩ /-- If `S` a finite-dimensional ring extension of a PID `R` which is free as an `R`-module, then any nonzero `S`-ideal `I` is free as an `R`-submodule of `S`, and we can find a basis for `S` and `I` such that the inclusion map is a square diagonal matrix. See `ideal.exists_smith_normal_form` for a version of this theorem that doesn't need to map `I` into a submodule of `R`. This is a strengthening of `submodule.basis_of_pid`. -/ noncomputable def ideal.smith_normal_form [fintype ι] {S : Type*} [comm_ring S] [integral_domain S] [algebra R S] (b : basis ι R S) (I : ideal S) (hI : I ≠ ⊥) : basis.smith_normal_form (I.restrict_scalars R) ι (fintype.card ι) := let ⟨n, bS, bI, f, a, snf⟩ := (I.restrict_scalars R).smith_normal_form b in have eq : _ := ideal.rank_eq bS hI (bI.map ((restrict_scalars_equiv R S S I).restrict_scalars _)), let e : fin n ≃ fin (fintype.card ι) := fintype.equiv_of_card_eq (by rw [eq, fintype.card_fin]) in ⟨bS, bI.reindex e, e.symm.to_embedding.trans f, a ∘ e.symm, λ i, by simp only [snf, basis.coe_reindex, function.embedding.trans_apply, equiv.to_embedding_apply]⟩ /-- If `S` a finite-dimensional ring extension of a PID `R` which is free as an `R`-module, then any nonzero `S`-ideal `I` is free as an `R`-submodule of `S`, and we can find a basis for `S` and `I` such that the inclusion map is a square diagonal matrix. See also `ideal.smith_normal_form` for a version of this theorem that returns a `basis.smith_normal_form`. -/ theorem ideal.exists_smith_normal_form [fintype ι] {S : Type*} [comm_ring S] [integral_domain S] [algebra R S] (b : basis ι R S) (I : ideal S) (hI : I ≠ ⊥) : ∃ (b' : basis ι R S) (a : ι → R) (ab' : basis ι R I), ∀ i, (ab' i : S) = a i • b' i := let ⟨bS, bI, f, a, snf⟩ := I.smith_normal_form b hI, e : fin (fintype.card ι) ≃ ι := equiv.of_bijective f ((fintype.bijective_iff_injective_and_card f).mpr ⟨f.injective, fintype.card_fin _⟩) in have fe : ∀ i, f (e.symm i) = i := e.apply_symm_apply, ⟨bS, a ∘ e.symm, (bI.reindex e).map ((restrict_scalars_equiv _ _ _ _).restrict_scalars R), λ i, by simp only [snf, fe, basis.map_apply, linear_equiv.restrict_scalars_apply, submodule.restrict_scalars_equiv_apply, basis.coe_reindex]⟩ end smith_normal end principal_ideal_domain /-- A set of linearly independent vectors in a module `M` over a semiring `S` is also linearly independent over a subring `R` of `K`. -/ lemma linear_independent.restrict_scalars_algebras {R S M ι : Type*} [comm_semiring R] [semiring S] [add_comm_monoid M] [algebra R S] [module R M] [module S M] [is_scalar_tower R S M] (hinj : function.injective (algebra_map R S)) {v : ι → M} (li : linear_independent S v) : linear_independent R v := linear_independent.restrict_scalars (by rwa algebra.algebra_map_eq_smul_one' at hinj) li
9fca317d0e12800cf4527f57ddc9864a7b79045c
a19a4fce1e5677f4d20cbfdf60c04b6386ab8210
/hott/init/tactic.hlean
b5ca7b6e369893404f6a142ff8e365bb1a5928ac
[ "Apache-2.0" ]
permissive
nthomas103/lean
9c341a316e7d9faa00546462f90a8aa402e17eac
04eaf184a92606a56e54d0d6c8d59437557263fc
refs/heads/master
1,586,061,106,806
1,454,640,115,000
1,454,641,279,000
51,127,143
0
0
null
1,454,648,683,000
1,454,648,683,000
null
UTF-8
Lean
false
false
7,084
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura This is just a trick to embed the 'tactic language' as a Lean expression. We should view 'tactic' as automation that when execute produces a term. tactic.builtin is just a "dummy" for creating the definitions that are actually implemented in C++ -/ prelude import init.datatypes init.reserved_notation init.num inductive tactic : Type := builtin : tactic namespace tactic -- Remark the following names are not arbitrary, the tactic module -- uses them when converting Lean expressions into actual tactic objects. -- The bultin 'by' construct triggers the process of converting a -- a term of type 'tactic' into a tactic that sythesizes a term definition and_then (t1 t2 : tactic) : tactic := builtin definition or_else (t1 t2 : tactic) : tactic := builtin definition append (t1 t2 : tactic) : tactic := builtin definition interleave (t1 t2 : tactic) : tactic := builtin definition par (t1 t2 : tactic) : tactic := builtin definition fixpoint (f : tactic → tactic) : tactic := builtin definition repeat (t : tactic) : tactic := builtin definition at_most (t : tactic) (k : num) : tactic := builtin definition discard (t : tactic) (k : num) : tactic := builtin definition focus_at (t : tactic) (i : num) : tactic := builtin definition try_for (t : tactic) (ms : num) : tactic := builtin definition all_goals (t : tactic) : tactic := builtin definition now : tactic := builtin definition assumption : tactic := builtin definition eassumption : tactic := builtin definition state : tactic := builtin definition fail : tactic := builtin definition id : tactic := builtin definition beta : tactic := builtin definition info : tactic := builtin definition whnf : tactic := builtin definition contradiction : tactic := builtin definition exfalso : tactic := builtin definition congruence : tactic := builtin definition rotate_left (k : num) := builtin definition rotate_right (k : num) := builtin definition rotate (k : num) := rotate_left k -- This is just a trick to embed expressions into tactics. -- The nested expressions are "raw". They tactic should -- elaborate them when it is executed. inductive expr : Type := builtin : expr inductive expr_list : Type := | nil : expr_list | cons : expr → expr_list → expr_list -- auxiliary type used to mark optional list of arguments definition opt_expr_list := expr_list -- auxiliary types used to mark that the expression is suppose to be an identifier, optional, or a list. definition identifier := expr definition identifier_list := expr_list definition opt_identifier_list := expr_list -- Remark: the parser has special support for tactics containing `location` parameters. -- It will parse the optional `at ...` modifier. definition location := expr -- Marker for instructing the parser to parse it as 'with <expr>' definition with_expr := expr -- Marker for instructing the parser to parse it as '?(using <expr>)' definition using_expr := expr -- Constant used to denote the case were no expression was provided definition none_expr : expr := expr.builtin definition apply (e : expr) : tactic := builtin definition eapply (e : expr) : tactic := builtin definition fapply (e : expr) : tactic := builtin definition rename (a b : identifier) : tactic := builtin definition intro (e : opt_identifier_list) : tactic := builtin definition generalize_tac (e : expr) (id : identifier) : tactic := builtin definition clear (e : identifier_list) : tactic := builtin definition revert (e : identifier_list) : tactic := builtin definition refine (e : expr) : tactic := builtin definition exact (e : expr) : tactic := builtin -- Relaxed version of exact that does not enforce goal type definition rexact (e : expr) : tactic := builtin definition check_expr (e : expr) : tactic := builtin definition trace (s : string) : tactic := builtin -- rewrite_tac is just a marker for the builtin 'rewrite' notation -- used to create instances of this tactic. definition rewrite_tac (e : expr_list) : tactic := builtin definition xrewrite_tac (e : expr_list) : tactic := builtin definition krewrite_tac (e : expr_list) : tactic := builtin -- Arguments: -- - ls : lemmas to be used (if not provided, then blast will choose them) -- - ds : definitions that can be unfolded (if not provided, then blast will choose them) definition blast (ls : opt_identifier_list) (ds : opt_identifier_list) : tactic := builtin -- with_options_tac is just a marker for the builtin 'with_options' notation definition with_options_tac (o : expr) (t : tactic) : tactic := builtin -- with_options_tac is just a marker for the builtin 'with_attributes' notation definition with_attributes_tac (o : expr) (n : identifier_list) (t : tactic) : tactic := builtin definition cases (h : expr) (ids : opt_identifier_list) : tactic := builtin definition induction (h : expr) (rec : using_expr) (ids : opt_identifier_list) : tactic := builtin definition intros (ids : opt_identifier_list) : tactic := builtin definition generalizes (es : expr_list) : tactic := builtin definition clears (ids : identifier_list) : tactic := builtin definition reverts (ids : identifier_list) : tactic := builtin definition change (e : expr) : tactic := builtin definition assert_hypothesis (id : identifier) (e : expr) : tactic := builtin definition note_tac (id : identifier) (e : expr) : tactic := builtin definition constructor (k : option num) : tactic := builtin definition fconstructor (k : option num) : tactic := builtin definition existsi (e : expr) : tactic := builtin definition split : tactic := builtin definition left : tactic := builtin definition right : tactic := builtin definition injection (e : expr) (ids : opt_identifier_list) : tactic := builtin definition subst (ids : identifier_list) : tactic := builtin definition substvars : tactic := builtin definition reflexivity : tactic := builtin definition symmetry : tactic := builtin definition transitivity (e : expr) : tactic := builtin definition try (t : tactic) : tactic := or_else t id definition repeat1 (t : tactic) : tactic := and_then t (repeat t) definition focus (t : tactic) : tactic := focus_at t 0 definition determ (t : tactic) : tactic := at_most t 1 definition trivial : tactic := or_else (apply eq.refl) assumption definition do (n : num) (t : tactic) : tactic := nat.rec id (λn t', and_then t t') (nat.of_num n) end tactic tactic_infixl `;`:15 := tactic.and_then tactic_notation T1 `:`:15 T2 := tactic.focus (tactic.and_then T1 (tactic.all_goals T2)) tactic_notation `(` h `|` r:(foldl `|` (e r, tactic.or_else r e) h) `)` := r
9998394e04d0e1c3b138fa94b9526418769d7084
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/group_theory/submonoid.lean
9e9340da01856ce247386d4e2c10a5024e1346f3
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
51,317
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Kenny Lau, Johan Commelin, Mario Carneiro, Kevin Buzzard, Amelia Livingston, Yury Kudryashov -/ import algebra.big_operators import algebra.free_monoid import algebra.group.prod import data.equiv.mul_add /-! # Submonoids This file defines multiplicative and additive submonoids, first in an unbundled form (deprecated) and then in a bundled form. We prove submonoids of a monoid form a complete lattice, and results about images and preimages of submonoids under monoid homomorphisms. For the unbundled submonoids, these theorems use unbundled monoid homomorphisms (also deprecated), and the bundled versions use bundled monoid homomorphisms. There are also theorems about the submonoids generated by an element or a subset of a monoid, defined both inductively and as the infimum of the set of submonoids containing a given element/subset. ## Implementation notes Unbundled submonoids will slowly be removed from mathlib. (Bundled) submonoid inclusion is denoted `≤` rather than `⊆`, although `∈` is defined as membership of a submonoid's underlying set. ## Tags submonoid, submonoids, is_submonoid -/ variables {M : Type*} [monoid M] {s : set M} variables {A : Type*} [add_monoid A] {t : set A} /-- `s` is an additive submonoid: a set containing 0 and closed under addition. -/ class is_add_submonoid (s : set A) : Prop := (zero_mem : (0:A) ∈ s) (add_mem {a b} : a ∈ s → b ∈ s → a + b ∈ s) /-- `s` is a submonoid: a set containing 1 and closed under multiplication. -/ @[to_additive is_add_submonoid] class is_submonoid (s : set M) : Prop := (one_mem : (1:M) ∈ s) (mul_mem {a b} : a ∈ s → b ∈ s → a * b ∈ s) lemma additive.is_add_submonoid (s : set M) : ∀ [is_submonoid s], @is_add_submonoid (additive M) _ s | ⟨h₁, h₂⟩ := ⟨h₁, @h₂⟩ theorem additive.is_add_submonoid_iff {s : set M} : @is_add_submonoid (additive M) _ s ↔ is_submonoid s := ⟨λ ⟨h₁, h₂⟩, ⟨h₁, @h₂⟩, λ h, by exactI additive.is_add_submonoid _⟩ lemma multiplicative.is_submonoid (s : set A) : ∀ [is_add_submonoid s], @is_submonoid (multiplicative A) _ s | ⟨h₁, h₂⟩ := ⟨h₁, @h₂⟩ theorem multiplicative.is_submonoid_iff {s : set A} : @is_submonoid (multiplicative A) _ s ↔ is_add_submonoid s := ⟨λ ⟨h₁, h₂⟩, ⟨h₁, @h₂⟩, λ h, by exactI multiplicative.is_submonoid _⟩ /-- The intersection of two submonoids of a monoid `M` is a submonoid of `M`. -/ @[to_additive "The intersection of two `add_submonoid`s of an `add_monoid` `M` is an `add_submonoid` of M."] instance is_submonoid.inter (s₁ s₂ : set M) [is_submonoid s₁] [is_submonoid s₂] : is_submonoid (s₁ ∩ s₂) := { one_mem := ⟨is_submonoid.one_mem, is_submonoid.one_mem⟩, mul_mem := λ x y hx hy, ⟨is_submonoid.mul_mem hx.1 hy.1, is_submonoid.mul_mem hx.2 hy.2⟩ } /-- The intersection of an indexed set of submonoids of a monoid `M` is a submonoid of `M`. -/ @[to_additive "The intersection of an indexed set of `add_submonoid`s of an `add_monoid` `M` is an `add_submonoid` of `M`."] instance is_submonoid.Inter {ι : Sort*} (s : ι → set M) [h : ∀ y : ι, is_submonoid (s y)] : is_submonoid (set.Inter s) := { one_mem := set.mem_Inter.2 $ λ y, is_submonoid.one_mem, mul_mem := λ x₁ x₂ h₁ h₂, set.mem_Inter.2 $ λ y, is_submonoid.mul_mem (set.mem_Inter.1 h₁ y) (set.mem_Inter.1 h₂ y) } /-- The union of an indexed, directed, nonempty set of submonoids of a monoid `M` is a submonoid of `M`. -/ @[to_additive is_add_submonoid_Union_of_directed "The union of an indexed, directed, nonempty set of `add_submonoid`s of an `add_monoid` `M` is an `add_submonoid` of `M`. "] lemma is_submonoid_Union_of_directed {ι : Type*} [hι : nonempty ι] (s : ι → set M) [∀ i, is_submonoid (s i)] (directed : ∀ i j, ∃ k, s i ⊆ s k ∧ s j ⊆ s k) : is_submonoid (⋃i, s i) := { one_mem := let ⟨i⟩ := hι in set.mem_Union.2 ⟨i, is_submonoid.one_mem⟩, mul_mem := λ a b ha hb, let ⟨i, hi⟩ := set.mem_Union.1 ha in let ⟨j, hj⟩ := set.mem_Union.1 hb in let ⟨k, hk⟩ := directed i j in set.mem_Union.2 ⟨k, is_submonoid.mul_mem (hk.1 hi) (hk.2 hj)⟩ } section powers /-- The set of natural number powers `1, x, x², ...` of an element `x` of a monoid. -/ def powers (x : M) : set M := {y | ∃ n:ℕ, x^n = y} /-- The set of natural number multiples `0, x, 2x, ...` of an element `x` of an `add_monoid`. -/ def multiples (x : A) : set A := {y | ∃ n:ℕ, add_monoid.smul n x = y} attribute [to_additive multiples] powers /-- 1 is in the set of natural number powers of an element of a monoid. -/ lemma powers.one_mem {x : M} : (1 : M) ∈ powers x := ⟨0, pow_zero _⟩ /-- 0 is in the set of natural number multiples of an element of an `add_monoid`. -/ lemma multiples.zero_mem {x : A} : (0 : A) ∈ multiples x := ⟨0, add_monoid.zero_smul _⟩ attribute [to_additive] powers.one_mem /-- An element of a monoid is in the set of that element's natural number powers. -/ lemma powers.self_mem {x : M} : x ∈ powers x := ⟨1, pow_one _⟩ /-- An element of an `add_monoid` is in the set of that element's natural number multiples. -/ lemma multiples.self_mem {x : A} : x ∈ multiples x := ⟨1, add_monoid.one_smul _⟩ attribute [to_additive] powers.self_mem /-- The set of natural number powers of an element of a monoid is closed under multiplication. -/ lemma powers.mul_mem {x y z : M} : (y ∈ powers x) → (z ∈ powers x) → (y * z ∈ powers x) := λ ⟨n₁, h₁⟩ ⟨n₂, h₂⟩, ⟨n₁ + n₂, by simp only [pow_add, *]⟩ /-- The set of natural number multiples of an element of an `add_monoid` is closed under addition. -/ lemma multiples.add_mem {x y z : A} : (y ∈ multiples x) → (z ∈ multiples x) → (y + z ∈ multiples x) := @powers.mul_mem (multiplicative A) _ _ _ _ attribute [to_additive] powers.mul_mem /-- The set of natural number powers of an element of a monoid `M` is a submonoid of `M`. -/ @[to_additive is_add_submonoid "The set of natural number multiples of an element of an `add_monoid` `M` is an `add_submonoid` of `M`."] instance powers.is_submonoid (x : M) : is_submonoid (powers x) := { one_mem := powers.one_mem, mul_mem := λ y z, powers.mul_mem } /-- A monoid is a submonoid of itself. -/ @[to_additive is_add_submonoid "An `add_monoid` is an `add_submonoid` of itself."] instance univ.is_submonoid : is_submonoid (@set.univ M) := by split; simp /-- The preimage of a submonoid under a monoid hom is a submonoid of the domain. -/ @[to_additive is_add_submonoid "The preimage of an `add_submonoid` under an `add_monoid` hom is an `add_submonoid` of the domain."] instance preimage.is_submonoid {N : Type*} [monoid N] (f : M → N) [is_monoid_hom f] (s : set N) [is_submonoid s] : is_submonoid (f ⁻¹' s) := { one_mem := show f 1 ∈ s, by rw is_monoid_hom.map_one f; exact is_submonoid.one_mem, mul_mem := λ a b (ha : f a ∈ s) (hb : f b ∈ s), show f (a * b) ∈ s, by rw is_monoid_hom.map_mul f; exact is_submonoid.mul_mem ha hb } /-- The image of a submonoid under a monoid hom is a submonoid of the codomain. -/ @[instance, to_additive is_add_submonoid "The image of an `add_submonoid` under an `add_monoid` hom is an `add_submonoid` of the codomain."] lemma image.is_submonoid {γ : Type*} [monoid γ] (f : M → γ) [is_monoid_hom f] (s : set M) [is_submonoid s] : is_submonoid (f '' s) := { one_mem := ⟨1, is_submonoid.one_mem, is_monoid_hom.map_one f⟩, mul_mem := λ a b ⟨x, hx⟩ ⟨y, hy⟩, ⟨x * y, is_submonoid.mul_mem hx.1 hy.1, by rw [is_monoid_hom.map_mul f, hx.2, hy.2]⟩ } /-- The image of a monoid hom is a submonoid of the codomain. -/ @[to_additive is_add_submonoid "The image of an `add_monoid` hom is an `add_submonoid` of the codomain."] instance range.is_submonoid {γ : Type*} [monoid γ] (f : M → γ) [is_monoid_hom f] : is_submonoid (set.range f) := by rw ← set.image_univ; apply_instance /-- Submonoids are closed under natural powers. -/ lemma is_submonoid.pow_mem {a : M} [is_submonoid s] (h : a ∈ s) : ∀ {n : ℕ}, a ^ n ∈ s | 0 := is_submonoid.one_mem | (n + 1) := is_submonoid.mul_mem h is_submonoid.pow_mem /-- An `add_submonoid` is closed under multiplication by naturals. -/ lemma is_add_submonoid.smul_mem {a : A} [is_add_submonoid t] : ∀ (h : a ∈ t) {n : ℕ}, add_monoid.smul n a ∈ t := @is_submonoid.pow_mem (multiplicative A) _ _ _ (multiplicative.is_submonoid _) attribute [to_additive smul_mem] is_submonoid.pow_mem /-- The set of natural number powers of an element of a submonoid is a subset of the submonoid. -/ lemma is_submonoid.power_subset {a : M} [is_submonoid s] (h : a ∈ s) : powers a ⊆ s := assume x ⟨n, hx⟩, hx ▸ is_submonoid.pow_mem h /-- The set of natural number multiples of an element of an `add_submonoid` is a subset of the `add_submonoid`. -/ lemma is_add_submonoid.multiple_subset {a : A} [is_add_submonoid t] : a ∈ t → multiples a ⊆ t := @is_submonoid.power_subset (multiplicative A) _ _ _ (multiplicative.is_submonoid _) attribute [to_additive multiple_subset] is_submonoid.power_subset end powers namespace is_submonoid /-- The product of a list of elements of a submonoid is an element of the submonoid. -/ @[to_additive "The sum of a list of elements of an `add_submonoid` is an element of the `add_submonoid`."] lemma list_prod_mem [is_submonoid s] : ∀{l : list M}, (∀x∈l, x ∈ s) → l.prod ∈ s | [] h := one_mem | (a::l) h := suffices a * l.prod ∈ s, by simpa, have a ∈ s ∧ (∀x∈l, x ∈ s), by simpa using h, is_submonoid.mul_mem this.1 (list_prod_mem this.2) /-- The product of a multiset of elements of a submonoid of a `comm_monoid` is an element of the submonoid. -/ @[to_additive "The sum of a multiset of elements of an `add_submonoid` of an `add_comm_monoid` is an element of the `add_submonoid`. "] lemma multiset_prod_mem {M} [comm_monoid M] (s : set M) [is_submonoid s] (m : multiset M) : (∀a∈m, a ∈ s) → m.prod ∈ s := begin refine quotient.induction_on m (assume l hl, _), rw [multiset.quot_mk_to_coe, multiset.coe_prod], exact list_prod_mem hl end /-- The product of elements of a submonoid of a `comm_monoid` indexed by a `finset` is an element of the submonoid. -/ @[to_additive "The sum of elements of an `add_submonoid` of an `add_comm_monoid` indexed by a `finset` is an element of the `add_submonoid`."] lemma finset_prod_mem {M A} [comm_monoid M] (s : set M) [is_submonoid s] (f : A → M) : ∀(t : finset A), (∀b∈t, f b ∈ s) → t.prod f ∈ s | ⟨m, hm⟩ hs := begin refine multiset_prod_mem s _ _, simp, rintros a b hb rfl, exact hs _ hb end end is_submonoid -- TODO: modify `subtype_instance` to produce this definition, then use it here -- and for `subtype.group` /-- Submonoids are themselves monoids. -/ @[to_additive add_monoid "An `add_submonoid` is itself an `add_monoid`."] instance subtype.monoid {s : set M} [is_submonoid s] : monoid s := { one := ⟨1, is_submonoid.one_mem⟩, mul := λ x y, ⟨x * y, is_submonoid.mul_mem x.2 y.2⟩, mul_one := λ x, subtype.eq $ mul_one x.1, one_mul := λ x, subtype.eq $ one_mul x.1, mul_assoc := λ x y z, subtype.eq $ mul_assoc x.1 y.1 z.1 } /-- Submonoids of commutative monoids are themselves commutative monoids. -/ @[to_additive add_comm_monoid "An `add_submonoid` of a commutative `add_monoid` is itself a commutative `add_monoid`. "] instance subtype.comm_monoid {M} [comm_monoid M] {s : set M} [is_submonoid s] : comm_monoid s := { mul_comm := λ x y, subtype.eq $ mul_comm x.1 y.1, .. subtype.monoid } /-- Submonoids inherit the 1 of the monoid. -/ @[simp, norm_cast, to_additive "An `add_submonoid` inherits the 0 of the `add_monoid`. "] lemma is_submonoid.coe_one [is_submonoid s] : ((1 : s) : M) = 1 := rfl attribute [norm_cast] is_add_submonoid.coe_zero /-- Submonoids inherit the multiplication of the monoid. -/ @[simp, norm_cast, to_additive "An `add_submonoid` inherits the addition of the `add_monoid`. "] lemma is_submonoid.coe_mul [is_submonoid s] (a b : s) : ((a * b : s) : M) = a * b := rfl attribute [norm_cast] is_add_submonoid.coe_add /-- Submonoids inherit the exponentiation by naturals of the monoid. -/ @[simp, norm_cast] lemma is_submonoid.coe_pow [is_submonoid s] (a : s) (n : ℕ) : ((a ^ n : s) : M) = a ^ n := by induction n; simp [*, pow_succ] /-- An `add_submonoid` inherits the multiplication by naturals of the `add_monoid`. -/ @[simp, norm_cast] lemma is_add_submonoid.smul_coe {A : Type*} [add_monoid A] {s : set A} [is_add_submonoid s] (a : s) (n : ℕ) : ((add_monoid.smul n a : s) : A) = add_monoid.smul n a := by {induction n, refl, simp [*, succ_smul]} attribute [to_additive smul_coe] is_submonoid.coe_pow /-- The natural injection from a submonoid into the monoid is a monoid hom. -/ @[to_additive is_add_monoid_hom "The natural injection from an `add_submonoid` into the `add_monoid` is an `add_monoid` hom. "] instance subtype_val.is_monoid_hom [is_submonoid s] : is_monoid_hom (subtype.val : s → M) := { map_one := rfl, map_mul := λ _ _, rfl } /-- The natural injection from a submonoid into the monoid is a monoid hom. -/ @[to_additive is_add_monoid_hom "The natural injection from an `add_submonoid` into the `add_monoid` is an `add_monoid` hom. "] instance coe.is_monoid_hom [is_submonoid s] : is_monoid_hom (coe : s → M) := subtype_val.is_monoid_hom /-- Given a monoid hom `f : γ → M` whose image is contained in a submonoid `s`, the induced map from `γ` to `s` is a monoid hom. -/ @[to_additive is_add_monoid_hom "Given an `add_monoid` hom `f : γ → M` whose image is contained in an `add_submonoid` s, the induced map from `γ` to `s` is an `add_monoid` hom."] instance subtype_mk.is_monoid_hom {γ : Type*} [monoid γ] [is_submonoid s] (f : γ → M) [is_monoid_hom f] (h : ∀ x, f x ∈ s) : is_monoid_hom (λ x, (⟨f x, h x⟩ : s)) := { map_one := subtype.eq (is_monoid_hom.map_one f), map_mul := λ x y, subtype.eq (is_monoid_hom.map_mul f x y) } /-- Given two submonoids `s` and `t` such that `s ⊆ t`, the natural injection from `s` into `t` is a monoid hom. -/ @[to_additive is_add_monoid_hom "Given two `add_submonoid`s `s` and `t` such that `s ⊆ t`, the natural injection from `s` into `t` is an `add_monoid` hom."] instance set_inclusion.is_monoid_hom (t : set M) [is_submonoid s] [is_submonoid t] (h : s ⊆ t) : is_monoid_hom (set.inclusion h) := subtype_mk.is_monoid_hom _ _ namespace add_monoid /-- The inductively defined membership predicate for the submonoid generated by a subset of a monoid. -/ inductive in_closure (s : set A) : A → Prop | basic {a : A} : a ∈ s → in_closure a | zero : in_closure 0 | add {a b : A} : in_closure a → in_closure b → in_closure (a + b) end add_monoid namespace monoid /-- The inductively defined membership predicate for the `add_submonoid` generated by a subset of an add_monoid. -/ inductive in_closure (s : set M) : M → Prop | basic {a : M} : a ∈ s → in_closure a | one : in_closure 1 | mul {a b : M} : in_closure a → in_closure b → in_closure (a * b) attribute [to_additive] monoid.in_closure attribute [to_additive] monoid.in_closure.one attribute [to_additive] monoid.in_closure.mul /-- The inductively defined submonoid generated by a subset of a monoid. -/ @[to_additive "The inductively defined `add_submonoid` genrated by a subset of an `add_monoid`."] def closure (s : set M) : set M := {a | in_closure s a } @[to_additive is_add_submonoid] instance closure.is_submonoid (s : set M) : is_submonoid (closure s) := { one_mem := in_closure.one, mul_mem := assume a b, in_closure.mul } /-- A subset of a monoid is contained in the submonoid it generates. -/ @[to_additive "A subset of an `add_monoid` is contained in the `add_submonoid` it generates."] theorem subset_closure {s : set M} : s ⊆ closure s := assume a, in_closure.basic /-- The submonoid generated by a set is contained in any submonoid that contains the set. -/ @[to_additive "The `add_submonoid` generated by a set is contained in any `add_submonoid` that contains the set."] theorem closure_subset {s t : set M} [is_submonoid t] (h : s ⊆ t) : closure s ⊆ t := assume a ha, by induction ha; simp [h _, *, is_submonoid.one_mem, is_submonoid.mul_mem] /-- Given subsets `t` and `s` of a monoid `M`, if `s ⊆ t`, the submonoid of `M` generated by `s` is contained in the submonoid generated by `t`. -/ @[to_additive "Given subsets `t` and `s` of an `add_monoid M`, if `s ⊆ t`, the `add_submonoid` of `M` generated by `s` is contained in the `add_submonoid` generated by `t`."] theorem closure_mono {s t : set M} (h : s ⊆ t) : closure s ⊆ closure t := closure_subset $ set.subset.trans h subset_closure /-- The submonoid generated by an element of a monoid equals the set of natural number powers of the element. -/ @[to_additive "The `add_submonoid` generated by an element of an `add_monoid` equals the set of natural number multiples of the element."] theorem closure_singleton {x : M} : closure ({x} : set M) = powers x := set.eq_of_subset_of_subset (closure_subset $ set.singleton_subset_iff.2 $ powers.self_mem) $ is_submonoid.power_subset $ set.singleton_subset_iff.1 $ subset_closure /-- The image under a monoid hom of the submonoid generated by a set equals the submonoid generated by the image of the set under the monoid hom. -/ @[to_additive "The image under an `add_monoid` hom of the `add_submonoid` generated by a set equals the `add_submonoid` generated by the image of the set under the `add_monoid` hom."] lemma image_closure {A : Type*} [monoid A] (f : M → A) [is_monoid_hom f] (s : set M) : f '' closure s = closure (f '' s) := le_antisymm begin rintros _ ⟨x, hx, rfl⟩, apply in_closure.rec_on hx; intros, { solve_by_elim [subset_closure, set.mem_image_of_mem] }, { rw [is_monoid_hom.map_one f], apply is_submonoid.one_mem }, { rw [is_monoid_hom.map_mul f], solve_by_elim [is_submonoid.mul_mem] } end (closure_subset $ set.image_subset _ subset_closure) /-- Given an element `a` of the submonoid of a monoid `M` generated by a set `s`, there exists a list of elements of `s` whose product is `a`. -/ @[to_additive "Given an element `a` of the `add_submonoid` of an `add_monoid M` generated by a set `s`, there exists a list of elements of `s` whose sum is `a`."] theorem exists_list_of_mem_closure {s : set M} {a : M} (h : a ∈ closure s) : (∃l:list M, (∀x∈l, x ∈ s) ∧ l.prod = a) := begin induction h, case in_closure.basic : a ha { existsi ([a]), simp [ha] }, case in_closure.one { existsi ([]), simp }, case in_closure.mul : a b _ _ ha hb { rcases ha with ⟨la, ha, eqa⟩, rcases hb with ⟨lb, hb, eqb⟩, existsi (la ++ lb), simp [eqa.symm, eqb.symm, or_imp_distrib], exact assume a, ⟨ha a, hb a⟩ } end /-- Given sets `s, t` of a commutative monoid `M`, `x ∈ M` is in the submonoid of `M` generated by `s ∪ t` iff there exists an element of the submonoid generated by `s` and an element of the submonoid generated by `t` whose product is `x`. -/ @[to_additive "Given sets `s, t` of a commutative `add_monoid M`, `x ∈ M` is in the `add_submonoid` of `M` generated by `s ∪ t` iff there exists an element of the `add_submonoid` generated by `s` and an element of the `add_submonoid` generated by `t` whose sum is `x`."] theorem mem_closure_union_iff {M : Type*} [comm_monoid M] {s t : set M} {x : M} : x ∈ closure (s ∪ t) ↔ ∃ y ∈ closure s, ∃ z ∈ closure t, y * z = x := ⟨λ hx, let ⟨L, HL1, HL2⟩ := exists_list_of_mem_closure hx in HL2 ▸ list.rec_on L (λ _, ⟨1, is_submonoid.one_mem, 1, is_submonoid.one_mem, mul_one _⟩) (λ hd tl ih HL1, let ⟨y, hy, z, hz, hyzx⟩ := ih (list.forall_mem_of_forall_mem_cons HL1) in or.cases_on (HL1 hd $ list.mem_cons_self _ _) (λ hs, ⟨hd * y, is_submonoid.mul_mem (subset_closure hs) hy, z, hz, by rw [mul_assoc, list.prod_cons, ← hyzx]; refl⟩) (λ ht, ⟨y, hy, z * hd, is_submonoid.mul_mem hz (subset_closure ht), by rw [← mul_assoc, list.prod_cons, ← hyzx, mul_comm hd]; refl⟩)) HL1, λ ⟨y, hy, z, hz, hyzx⟩, hyzx ▸ is_submonoid.mul_mem (closure_mono (set.subset_union_left _ _) hy) (closure_mono (set.subset_union_right _ _) hz)⟩ end monoid /-! ### Bundled submonoids and `add_submonoid`s -/ /-- A submonoid of a monoid `M` is a subset containing 1 and closed under multiplication. -/ structure submonoid (M : Type*) [monoid M] := (carrier : set M) (one_mem' : (1 : M) ∈ carrier) (mul_mem' {a b} : a ∈ carrier → b ∈ carrier → a * b ∈ carrier) /-- An additive submonoid of an additive monoid `M` is a subset containing 0 and closed under addition. -/ structure add_submonoid (M : Type*) [add_monoid M] := (carrier : set M) (zero_mem' : (0 : M) ∈ carrier) (add_mem' {a b} : a ∈ carrier → b ∈ carrier → a + b ∈ carrier) attribute [to_additive add_submonoid] submonoid /-- Create a bundled submonoid from a set `s` and `[is_submonoid s]`. -/ @[to_additive "Create a bundled additive submonoid from a set `s` and `[is_add_submonoid s]`."] def submonoid.of (s : set M) [h : is_submonoid s] : submonoid M := ⟨s, h.1, h.2⟩ /-- Map from submonoids of monoid `M` to `add_submonoid`s of `additive M`. -/ def submonoid.to_add_submonoid {M : Type*} [monoid M] (S : submonoid M) : add_submonoid (additive M) := { carrier := S.carrier, zero_mem' := S.one_mem', add_mem' := S.mul_mem' } /-- Map from `add_submonoid`s of `additive M` to submonoids of `M`. -/ def submonoid.of_add_submonoid {M : Type*} [monoid M] (S : add_submonoid (additive M)) : submonoid M := { carrier := S.carrier, one_mem' := S.zero_mem', mul_mem' := S.add_mem' } /-- Map from `add_submonoid`s of `add_monoid M` to submonoids of `multiplicative M`. -/ def add_submonoid.to_submonoid {M : Type*} [add_monoid M] (S : add_submonoid M) : submonoid (multiplicative M) := { carrier := S.carrier, one_mem' := S.zero_mem', mul_mem' := S.add_mem' } /-- Map from submonoids of `multiplicative M` to `add_submonoid`s of `add_monoid M`. -/ def add_submonoid.of_submonoid {M : Type*} [add_monoid M] (S : submonoid (multiplicative M)) : add_submonoid M := { carrier := S.carrier, zero_mem' := S.one_mem', add_mem' := S.mul_mem' } /-- Submonoids of monoid `M` are isomorphic to additive submonoids of `additive M`. -/ def submonoid.add_submonoid_equiv (M : Type*) [monoid M] : submonoid M ≃ add_submonoid (additive M) := { to_fun := submonoid.to_add_submonoid, inv_fun := submonoid.of_add_submonoid, left_inv := λ x, by cases x; refl, right_inv := λ x, by cases x; refl } namespace submonoid @[to_additive] instance : has_coe (submonoid M) (set M) := ⟨submonoid.carrier⟩ @[to_additive] instance : has_coe_to_sort (submonoid M) := ⟨Type*, λ S, S.carrier⟩ @[to_additive] instance : has_mem M (submonoid M) := ⟨λ m S, m ∈ (S:set M)⟩ @[simp, to_additive] lemma mem_carrier {s : submonoid M} {x : M} : x ∈ s.carrier ↔ x ∈ s := iff.rfl @[simp, norm_cast, to_additive] lemma mem_coe {S : submonoid M} {m : M} : m ∈ (S : set M) ↔ m ∈ S := iff.rfl @[simp, norm_cast, to_additive] lemma coe_coe (s : submonoid M) : ↥(s : set M) = s := rfl attribute [norm_cast] add_submonoid.mem_coe add_submonoid.coe_coe @[to_additive] instance is_submonoid (S : submonoid M) : is_submonoid (S : set M) := ⟨S.2, S.3⟩ end submonoid @[to_additive] protected lemma submonoid.exists {s : submonoid M} {p : s → Prop} : (∃ x : s, p x) ↔ ∃ x ∈ s, p ⟨x, ‹x ∈ s›⟩ := set_coe.exists @[to_additive] protected lemma submonoid.forall {s : submonoid M} {p : s → Prop} : (∀ x : s, p x) ↔ ∀ x ∈ s, p ⟨x, ‹x ∈ s›⟩ := set_coe.forall namespace submonoid variables (S : submonoid M) /-- Two submonoids are equal if the underlying subsets are equal. -/ @[to_additive "Two `add_submonoid`s are equal if the underlying subsets are equal."] theorem ext' ⦃S T : submonoid M⦄ (h : (S : set M) = T) : S = T := by cases S; cases T; congr' /-- Two submonoids are equal if and only if the underlying subsets are equal. -/ @[to_additive "Two `add_submonoid`s are equal if and only if the underlying subsets are equal."] protected theorem ext'_iff {S T : submonoid M} : S = T ↔ (S : set M) = T := ⟨λ h, h ▸ rfl, λ h, ext' h⟩ /-- Two submonoids are equal if they have the same elements. -/ @[ext, to_additive "Two `add_submonoid`s are equal if they have the same elements."] theorem ext {S T : submonoid M} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := ext' $ set.ext h attribute [ext] add_submonoid.ext /-- Copy a submonoid replacing `carrier` with a set that is equal to it. -/ @[to_additive "Copy an additive submonoid replacing `carrier` with a set that is equal to it."] def copy (S : submonoid M) (s : set M) (hs : s = S) : submonoid M := { carrier := s, one_mem' := hs.symm ▸ S.one_mem', mul_mem' := hs.symm ▸ S.mul_mem' } @[simp, to_additive] lemma coe_copy {S : submonoid M} {s : set M} (hs : s = S) : (S.copy s hs : set M) = s := rfl @[to_additive] lemma copy_eq {S : submonoid M} {s : set M} (hs : s = S) : S.copy s hs = S := ext' hs /-- A submonoid contains the monoid's 1. -/ @[to_additive "An `add_submonoid` contains the monoid's 0."] theorem one_mem : (1 : M) ∈ S := S.one_mem' /-- A submonoid is closed under multiplication. -/ @[to_additive "An `add_submonoid` is closed under addition."] theorem mul_mem {x y : M} : x ∈ S → y ∈ S → x * y ∈ S := submonoid.mul_mem' S /-- Product of a list of elements in a submonoid is in the submonoid. -/ @[to_additive "Sum of a list of elements in an `add_submonoid` is in the `add_submonoid`."] lemma list_prod_mem : ∀ {l : list M}, (∀x ∈ l, x ∈ S) → l.prod ∈ S | [] h := S.one_mem | (a::l) h := suffices a * l.prod ∈ S, by rwa [list.prod_cons], have a ∈ S ∧ (∀ x ∈ l, x ∈ S), from list.forall_mem_cons.1 h, S.mul_mem this.1 (list_prod_mem this.2) /-- Product of a multiset of elements in a submonoid of a `comm_monoid` is in the submonoid. -/ @[to_additive "Sum of a multiset of elements in an `add_submonoid` of an `add_comm_monoid` is in the `add_submonoid`."] lemma multiset_prod_mem {M} [comm_monoid M] (S : submonoid M) (m : multiset M) : (∀a ∈ m, a ∈ S) → m.prod ∈ S := begin refine quotient.induction_on m (assume l hl, _), rw [multiset.quot_mk_to_coe, multiset.coe_prod], exact S.list_prod_mem hl end /-- Product of elements of a submonoid of a `comm_monoid` indexed by a `finset` is in the submonoid. -/ @[to_additive "Sum of elements in an `add_submonoid` of an `add_comm_monoid` indexed by a `finset` is in the `add_submonoid`."] lemma prod_mem {M : Type*} [comm_monoid M] (S : submonoid M) {ι : Type*} {t : finset ι} {f : ι → M} (h : ∀c ∈ t, f c ∈ S) : t.prod f ∈ S := S.multiset_prod_mem (t.1.map f) $ λ x hx, let ⟨i, hi, hix⟩ := multiset.mem_map.1 hx in hix ▸ h i hi lemma pow_mem {x : M} (hx : x ∈ S) : ∀ n:ℕ, x^n ∈ S | 0 := S.one_mem | (n+1) := S.mul_mem hx (pow_mem n) /-- A submonoid of a monoid inherits a multiplication. -/ @[to_additive "An `add_submonoid` of an `add_monoid` inherits an addition."] instance has_mul : has_mul S := ⟨λ a b, ⟨a.1 * b.1, S.mul_mem a.2 b.2⟩⟩ /-- A submonoid of a monoid inherits a 1. -/ @[to_additive "An `add_submonoid` of an `add_monoid` inherits a zero."] instance has_one : has_one S := ⟨⟨_, S.one_mem⟩⟩ @[simp, to_additive] lemma coe_mul (x y : S) : (↑(x * y) : M) = ↑x * ↑y := rfl @[simp, to_additive] lemma coe_one : ((1 : S) : M) = 1 := rfl /-- A submonoid of a monoid inherits a monoid structure. -/ @[to_additive to_add_monoid "An `add_submonoid` of an `add_monoid` inherits an `add_monoid` structure."] instance to_monoid {M : Type*} [monoid M] (S : submonoid M) : monoid S := by refine { mul := (*), one := 1, ..}; by simp [mul_assoc] /-- A submonoid of a `comm_monoid` is a `comm_monoid`. -/ @[to_additive to_add_comm_monoid "An `add_submonoid` of an `add_comm_monoid` is an `add_comm_monoid`."] instance to_comm_monoid {M} [comm_monoid M] (S : submonoid M) : comm_monoid S := { mul_comm := λ _ _, subtype.eq $ mul_comm _ _, ..S.to_monoid} /-- The natural monoid hom from a submonoid of monoid `M` to `M`. -/ @[to_additive "The natural monoid hom from an `add_submonoid` of `add_monoid` `M` to `M`."] def subtype : S →* M := ⟨coe, rfl, λ _ _, rfl⟩ @[simp, to_additive] theorem coe_subtype : ⇑S.subtype = coe := rfl @[to_additive] instance : has_le (submonoid M) := ⟨λ S T, ∀ ⦃x⦄, x ∈ S → x ∈ T⟩ @[to_additive] lemma le_def {S T : submonoid M} : S ≤ T ↔ ∀ ⦃x : M⦄, x ∈ S → x ∈ T := iff.rfl @[simp, norm_cast, to_additive] lemma coe_subset_coe {S T : submonoid M} : (S : set M) ⊆ T ↔ S ≤ T := iff.rfl @[to_additive] instance : partial_order (submonoid M) := { le := λ S T, ∀ ⦃x⦄, x ∈ S → x ∈ T, .. partial_order.lift (coe : submonoid M → set M) ext' infer_instance } @[simp, norm_cast, to_additive] lemma coe_ssubset_coe {S T : submonoid M} : (S : set M) ⊂ T ↔ S < T := iff.rfl attribute [norm_cast] add_submonoid.coe_subset_coe add_submonoid.coe_ssubset_coe /-- The submonoid `M` of the monoid `M`. -/ @[to_additive "The `add_submonoid M` of the `add_monoid M`."] instance : has_top (submonoid M) := ⟨{ carrier := set.univ, one_mem' := set.mem_univ 1, mul_mem' := λ _ _ _ _, set.mem_univ _ }⟩ /-- The trivial submonoid `{1}` of an monoid `M`. -/ @[to_additive "The trivial `add_submonoid` `{0}` of an `add_monoid` `M`."] instance : has_bot (submonoid M) := ⟨{ carrier := {1}, one_mem' := set.mem_singleton 1, mul_mem' := λ a b ha hb, by { simp only [set.mem_singleton_iff] at *, rw [ha, hb, mul_one] }}⟩ @[to_additive] instance : inhabited (submonoid M) := ⟨⊥⟩ @[simp, to_additive] lemma mem_bot {x : M} : x ∈ (⊥ : submonoid M) ↔ x = 1 := set.mem_singleton_iff @[simp, to_additive] lemma mem_top (x : M) : x ∈ (⊤ : submonoid M) := set.mem_univ x @[simp, to_additive] lemma coe_top : ((⊤ : submonoid M) : set M) = set.univ := rfl @[simp, to_additive] lemma coe_bot : ((⊥ : submonoid M) : set M) = {1} := rfl /-- The inf of two submonoids is their intersection. -/ @[to_additive "The inf of two `add_submonoid`s is their intersection."] instance : has_inf (submonoid M) := ⟨λ S₁ S₂, { carrier := S₁ ∩ S₂, one_mem' := ⟨S₁.one_mem, S₂.one_mem⟩, mul_mem' := λ _ _ ⟨hx, hx'⟩ ⟨hy, hy'⟩, ⟨S₁.mul_mem hx hy, S₂.mul_mem hx' hy'⟩ }⟩ @[simp, to_additive] lemma coe_inf (p p' : submonoid M) : ((p ⊓ p' : submonoid M) : set M) = p ∩ p' := rfl @[simp, to_additive] lemma mem_inf {p p' : submonoid M} {x : M} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl @[to_additive] instance : has_Inf (submonoid M) := ⟨λ s, { carrier := ⋂ t ∈ s, ↑t, one_mem' := set.mem_bInter $ λ i h, i.one_mem, mul_mem' := λ x y hx hy, set.mem_bInter $ λ i h, i.mul_mem (by apply set.mem_bInter_iff.1 hx i h) (by apply set.mem_bInter_iff.1 hy i h) }⟩ @[simp, to_additive] lemma coe_Inf (S : set (submonoid M)) : ((Inf S : submonoid M) : set M) = ⋂ s ∈ S, ↑s := rfl @[to_additive] lemma mem_Inf {S : set (submonoid M)} {x : M} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_bInter_iff @[to_additive] lemma mem_infi {ι : Sort*} {S : ι → submonoid M} {x : M} : (x ∈ ⨅ i, S i) ↔ ∀ i, x ∈ S i := by simp only [infi, mem_Inf, set.forall_range_iff] @[simp, to_additive] lemma coe_infi {ι : Sort*} {S : ι → submonoid M} : (↑(⨅ i, S i) : set M) = ⋂ i, S i := by simp only [infi, coe_Inf, set.bInter_range] attribute [norm_cast] coe_Inf coe_infi /-- Submonoids of a monoid form a complete lattice. -/ @[to_additive "The `add_submonoid`s of an `add_monoid` form a complete lattice."] instance : complete_lattice (submonoid M) := { le := (≤), lt := (<), bot := (⊥), bot_le := λ S x hx, (mem_bot.1 hx).symm ▸ S.one_mem, top := (⊤), le_top := λ S x hx, mem_top x, inf := (⊓), Inf := has_Inf.Inf, le_inf := λ a b c ha hb x hx, ⟨ha hx, hb hx⟩, inf_le_left := λ a b x, and.left, inf_le_right := λ a b x, and.right, .. complete_lattice_of_Inf (submonoid M) $ λ s, is_glb.of_image (λ S T, show (S : set M) ≤ T ↔ S ≤ T, from coe_subset_coe) is_glb_binfi } /-- The `submonoid` generated by a set. -/ @[to_additive "The `add_submonoid` generated by a set"] def closure (s : set M) : submonoid M := Inf {S | s ⊆ S} @[to_additive] lemma mem_closure {x : M} : x ∈ closure s ↔ ∀ S : submonoid M, s ⊆ S → x ∈ S := mem_Inf /-- The submonoid generated by a set includes the set. -/ @[simp, to_additive "The `add_submonoid` generated by a set includes the set."] lemma subset_closure : s ⊆ closure s := λ x hx, mem_closure.2 $ λ S hS, hS hx variable {S} open set /-- A submonoid `S` includes `closure s` if and only if it includes `s`. -/ @[simp, to_additive "An additive submonoid `S` includes `closure s` if and only if it includes `s`"] lemma closure_le : closure s ≤ S ↔ s ⊆ S := ⟨subset.trans subset_closure, λ h, Inf_le h⟩ /-- Submonoid closure of a set is monotone in its argument: if `s ⊆ t`, then `closure s ≤ closure t`. -/ @[to_additive "Additive submonoid closure of a set is monotone in its argument: if `s ⊆ t`, then `closure s ≤ closure t`"] lemma closure_mono ⦃s t : set M⦄ (h : s ⊆ t) : closure s ≤ closure t := closure_le.2 $ subset.trans h subset_closure @[to_additive] lemma closure_eq_of_le (h₁ : s ⊆ S) (h₂ : S ≤ closure s) : closure s = S := le_antisymm (closure_le.2 h₁) h₂ variable (S) /-- An induction principle for closure membership. If `p` holds for `1` and all elements of `s`, and is preserved under multiplication, then `p` holds for all elements of the closure of `s`. -/ @[to_additive "An induction principle for additive closure membership. If `p` holds for `0` and all elements of `s`, and is preserved under addition, then `p` holds for all elements of the additive closure of `s`."] lemma closure_induction {p : M → Prop} {x} (h : x ∈ closure s) (Hs : ∀ x ∈ s, p x) (H1 : p 1) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x := (@closure_le _ _ _ ⟨p, H1, Hmul⟩).2 Hs h attribute [elab_as_eliminator] submonoid.closure_induction add_submonoid.closure_induction variable (M) /-- `closure` forms a Galois insertion with the coercion to set. -/ @[to_additive "`closure` forms a Galois insertion with the coercion to set."] protected def gi : galois_insertion (@closure M _) coe := { choice := λ s _, closure s, gc := λ s t, closure_le, le_l_u := λ s, subset_closure, choice_eq := λ s h, rfl } variable {M} /-- Closure of a submonoid `S` equals `S`. -/ @[simp, to_additive "Additive closure of an additive submonoid `S` equals `S`"] lemma closure_eq : closure (S : set M) = S := (submonoid.gi M).l_u_eq S @[simp, to_additive] lemma closure_empty : closure (∅ : set M) = ⊥ := (submonoid.gi M).gc.l_bot @[simp, to_additive] lemma closure_univ : closure (univ : set M) = ⊤ := @coe_top M _ ▸ closure_eq ⊤ @[to_additive] lemma closure_union (s t : set M) : closure (s ∪ t) = closure s ⊔ closure t := (submonoid.gi M).gc.l_sup @[to_additive] lemma closure_Union {ι} (s : ι → set M) : closure (⋃ i, s i) = ⨆ i, closure (s i) := (submonoid.gi M).gc.l_supr @[to_additive] lemma mem_supr_of_directed {ι} [hι : nonempty ι] {S : ι → submonoid M} (hS : directed (≤) S) {x : M} : x ∈ (supr S : submonoid M) ↔ ∃ i, x ∈ S i := begin refine ⟨_, λ ⟨i, hi⟩, (le_def.1 $ le_supr S i) hi⟩, suffices : x ∈ closure (⋃ i, (S i : set M)) → ∃ i, x ∈ S i, by simpa only [closure_Union, closure_eq (S _)] using this, refine (λ hx, closure_induction hx (λ _, mem_Union.1) _ _), { exact hι.elim (λ i, ⟨i, (S i).one_mem⟩) }, { rintros x y ⟨i, hi⟩ ⟨j, hj⟩, rcases hS i j with ⟨k, hki, hkj⟩, exact ⟨k, (S k).mul_mem (hki hi) (hkj hj)⟩ } end @[to_additive] lemma mem_Sup_of_directed_on {S : set (submonoid M)} (Sne : S.nonempty) (hS : directed_on (≤) S) {x : M} : x ∈ Sup S ↔ ∃ s ∈ S, x ∈ s := begin haveI : nonempty S := Sne.to_subtype, rw [Sup_eq_supr, supr_subtype', mem_supr_of_directed, subtype.exists], exact (directed_on_iff_directed _).1 hS end variables {N : Type*} [monoid N] {P : Type*} [monoid P] /-- The preimage of a submonoid along a monoid homomorphism is a submonoid. -/ @[to_additive "The preimage of an `add_submonoid` along an `add_monoid` homomorphism is an `add_submonoid`."] def comap (f : M →* N) (S : submonoid N) : submonoid M := { carrier := (f ⁻¹' S), one_mem' := show f 1 ∈ S, by rw f.map_one; exact S.one_mem, mul_mem' := λ a b ha hb, show f (a * b) ∈ S, by rw f.map_mul; exact S.mul_mem ha hb } @[simp, to_additive] lemma coe_comap (S : submonoid N) (f : M →* N) : (S.comap f : set M) = f ⁻¹' S := rfl @[simp, to_additive] lemma mem_comap {S : submonoid N} {f : M →* N} {x : M} : x ∈ S.comap f ↔ f x ∈ S := iff.rfl @[to_additive] lemma comap_comap (S : submonoid P) (g : N →* P) (f : M →* N) : (S.comap g).comap f = S.comap (g.comp f) := rfl /-- The image of a submonoid along a monoid homomorphism is a submonoid. -/ @[to_additive "The image of an `add_submonoid` along an `add_monoid` homomorphism is an `add_submonoid`."] def map (f : M →* N) (S : submonoid M) : submonoid N := { carrier := (f '' S), one_mem' := ⟨1, S.one_mem, f.map_one⟩, mul_mem' := begin rintros _ _ ⟨x, hx, rfl⟩ ⟨y, hy, rfl⟩, exact ⟨x * y, S.mul_mem hx hy, by rw f.map_mul; refl⟩ end } @[simp, to_additive] lemma coe_map (f : M →* N) (S : submonoid M) : (S.map f : set N) = f '' S := rfl @[simp, to_additive] lemma mem_map {f : M →* N} {S : submonoid M} {y : N} : y ∈ S.map f ↔ ∃ x ∈ S, f x = y := mem_image_iff_bex @[to_additive] lemma map_map (g : N →* P) (f : M →* N) : (S.map f).map g = S.map (g.comp f) := ext' $ image_image _ _ _ @[to_additive] lemma map_le_iff_le_comap {f : M →* N} {S : submonoid M} {T : submonoid N} : S.map f ≤ T ↔ S ≤ T.comap f := image_subset_iff @[to_additive] lemma gc_map_comap (f : M →* N) : galois_connection (map f) (comap f) := λ S T, map_le_iff_le_comap @[to_additive] lemma map_sup (S T : submonoid M) (f : M →* N) : (S ⊔ T).map f = S.map f ⊔ T.map f := (gc_map_comap f).l_sup @[to_additive] lemma map_supr {ι : Sort*} (f : M →* N) (s : ι → submonoid M) : (supr s).map f = ⨆ i, (s i).map f := (gc_map_comap f).l_supr @[to_additive] lemma comap_inf (S T : submonoid N) (f : M →* N) : (S ⊓ T).comap f = S.comap f ⊓ T.comap f := (gc_map_comap f).u_inf @[to_additive] lemma comap_infi {ι : Sort*} (f : M →* N) (s : ι → submonoid N) : (infi s).comap f = ⨅ i, (s i).comap f := (gc_map_comap f).u_infi @[simp, to_additive] lemma map_bot (f : M →* N) : (⊥ : submonoid M).map f = ⊥ := (gc_map_comap f).l_bot @[simp, to_additive] lemma comap_top (f : M →* N) : (⊤ : submonoid N).comap f = ⊤ := (gc_map_comap f).u_top /-- Given `submonoid`s `s`, `t` of monoids `M`, `N` respectively, `s × t` as a submonoid of `M × N`. -/ @[to_additive prod "Given `add_submonoid`s `s`, `t` of `add_monoid`s `A`, `B` respectively, `s × t` as an `add_submonoid` of `A × B`."] def prod (s : submonoid M) (t : submonoid N) : submonoid (M × N) := { carrier := (s : set M).prod t, one_mem' := ⟨s.one_mem, t.one_mem⟩, mul_mem' := λ p q hp hq, ⟨s.mul_mem hp.1 hq.1, t.mul_mem hp.2 hq.2⟩ } @[to_additive coe_prod] lemma coe_prod (s : submonoid M) (t : submonoid N) : (s.prod t : set (M × N)) = (s : set M).prod (t : set N) := rfl @[to_additive mem_prod] lemma mem_prod {s : submonoid M} {t : submonoid N} {p : M × N} : p ∈ s.prod t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl @[to_additive prod_mono] lemma prod_mono : ((≤) ⇒ (≤) ⇒ (≤)) (@prod M _ N _) (@prod M _ N _) := λ s s' hs t t' ht, set.prod_mono hs ht @[to_additive prod_mono_right] lemma prod_mono_right (s : submonoid M) : monotone (λ t : submonoid N, s.prod t) := prod_mono (le_refl s) @[to_additive prod_mono_left] lemma prod_mono_left (t : submonoid N) : monotone (λ s : submonoid M, s.prod t) := λ s₁ s₂ hs, prod_mono hs (le_refl t) @[to_additive prod_top] lemma prod_top (s : submonoid M) : s.prod (⊤ : submonoid N) = s.comap (monoid_hom.fst M N) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst] @[to_additive top_prod] lemma top_prod (s : submonoid N) : (⊤ : submonoid M).prod s = s.comap (monoid_hom.snd M N) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd] @[simp, to_additive top_prod_top] lemma top_prod_top : (⊤ : submonoid M).prod (⊤ : submonoid N) = ⊤ := (top_prod _).trans $ comap_top _ @[to_additive] lemma bot_prod_bot : (⊥ : submonoid M).prod (⊥ : submonoid N) = ⊥ := ext' $ by simp [coe_prod, prod.one_eq_mk] /-- Product of submonoids is isomorphic to their product as monoids. -/ @[to_additive prod_equiv "Product of additive submonoids is isomorphic to their product as additive monoids"] def prod_equiv (s : submonoid M) (t : submonoid N) : s.prod t ≃* s × t := { map_mul' := λ x y, rfl, .. equiv.set.prod ↑s ↑t } end submonoid namespace monoid_hom variables {N : Type*} {P : Type*} [monoid N] [monoid P] (S : submonoid M) open submonoid /-- The range of a monoid homomorphism is a submonoid. -/ @[to_additive "The range of an `add_monoid_hom` is an `add_submonoid`."] def mrange (f : M →* N) : submonoid N := (⊤ : submonoid M).map f @[simp, to_additive] lemma coe_mrange (f : M →* N) : (f.mrange : set N) = set.range f := set.image_univ @[simp, to_additive] lemma mem_mrange {f : M →* N} {y : N} : y ∈ f.mrange ↔ ∃ x, f x = y := by simp [mrange] @[to_additive] lemma map_mrange (g : N →* P) (f : M →* N) : f.mrange.map g = (g.comp f).mrange := (⊤ : submonoid M).map_map g f /-- Restriction of a monoid hom to a submonoid of the domain. -/ @[to_additive "Restriction of an add_monoid hom to an `add_submonoid` of the domain."] def restrict {N : Type*} [monoid N] (f : M →* N) (S : submonoid M) : S →* N := f.comp S.subtype @[to_additive] lemma restrict_apply {N : Type*} [monoid N] (f : M →* N) (x : S) : f.restrict S x = f x := rfl @[simp, to_additive] lemma restrict_eq {N : Type} [monoid N] (f : M →* N) (x) : f.restrict S x = f x := rfl /-- Restriction of a monoid hom to a submonoid of the codomain. -/ @[to_additive "Restriction of an `add_monoid` hom to an `add_submonoid` of the codomain."] def cod_restrict (f : M →* N) (S : submonoid N) (h : ∀ x, f x ∈ S) : M →* S := { to_fun := λ n, ⟨f n, h n⟩, map_one' := subtype.eq f.map_one, map_mul' := λ x y, subtype.eq (f.map_mul x y) } /-- Restriction of a monoid hom to its range iterpreted as a submonoid. -/ @[to_additive "Restriction of an `add_monoid` hom to its range interpreted as a submonoid."] def range_restrict {N} [monoid N] (f : M →* N) : M →* f.mrange := f.cod_restrict f.mrange $ λ x, ⟨x, submonoid.mem_top x, rfl⟩ @[simp, to_additive] lemma coe_range_restrict {N} [monoid N] (f : M →* N) (x : M) : (f.range_restrict x : N) = f x := rfl @[to_additive] lemma mrange_top_iff_surjective {N} [monoid N] {f : M →* N} : f.mrange = (⊤ : submonoid N) ↔ function.surjective f := submonoid.ext'_iff.trans $ iff.trans (by rw [coe_mrange, coe_top]) set.range_iff_surjective /-- The range of a surjective monoid hom is the whole of the codomain. -/ @[to_additive "The range of a surjective `add_monoid` hom is the whole of the codomain."] lemma mrange_top_of_surjective {N} [monoid N] (f : M →* N) (hf : function.surjective f) : f.mrange = (⊤ : submonoid N) := mrange_top_iff_surjective.2 hf /-- The submonoid of elements `x : M` such that `f x = g x` -/ @[to_additive "The additive submonoid of elements `x : M` such that `f x = g x`"] def eq_mlocus (f g : M →* N) : submonoid M := { carrier := {x | f x = g x}, one_mem' := by rw [set.mem_set_of_eq, f.map_one, g.map_one], mul_mem' := λ x y (hx : _ = _) (hy : _ = _), by simp [*] } /-- If two monoid homomorphisms are equal on a set, then they are equal on its submonoid closure. -/ @[to_additive] lemma eq_on_mclosure {f g : M →* N} {s : set M} (h : set.eq_on f g s) : set.eq_on f g (closure s) := show closure s ≤ f.eq_mlocus g, from closure_le.2 h @[to_additive] lemma eq_of_eq_on_mtop {f g : M →* N} (h : set.eq_on f g (⊤ : submonoid M)) : f = g := ext $ λ x, h trivial @[to_additive] lemma eq_of_eq_on_mdense {s : set M} (hs : closure s = ⊤) {f g : M →* N} (h : s.eq_on f g) : f = g := eq_of_eq_on_mtop $ hs ▸ eq_on_mclosure h @[to_additive] lemma closure_preimage_le (f : M →* N) (s : set N) : closure (f ⁻¹' s) ≤ (closure s).comap f := closure_le.2 $ λ x hx, mem_coe.2 $ mem_comap.2 $ subset_closure hx /-- The image under a monoid hom of the submonoid generated by a set equals the submonoid generated by the image of the set. -/ @[to_additive "The image under an `add_monoid` hom of the `add_submonoid` generated by a set equals the `add_submonoid` generated by the image of the set."] lemma map_mclosure (f : M →* N) (s : set M) : (closure s).map f = closure (f '' s) := le_antisymm (map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image _ _) (closure_preimage_le _ _)) (closure_le.2 $ set.image_subset _ subset_closure) end monoid_hom namespace free_monoid variables {α : Type*} open submonoid @[to_additive] theorem closure_range_of : closure (set.range $ @of α) = ⊤ := eq_top_iff.2 $ λ x hx, free_monoid.rec_on x (one_mem _) $ λ x xs hxs, mul_mem _ (subset_closure $ set.mem_range_self _) hxs end free_monoid namespace submonoid variables {N : Type*} [monoid N] open monoid_hom lattice /-- The monoid hom associated to an inclusion of submonoids. -/ @[to_additive "The `add_monoid` hom associated to an inclusion of submonoids."] def inclusion {S T : submonoid M} (h : S ≤ T) : S →* T := S.subtype.cod_restrict _ (λ x, h x.2) @[simp, to_additive] lemma range_subtype (s : submonoid M) : s.subtype.mrange = s := ext' $ (coe_mrange _).trans $ set.range_coe_subtype s lemma closure_singleton_eq (x : M) : closure ({x} : set M) = (powers_hom M x).mrange := closure_eq_of_le (set.singleton_subset_iff.2 ⟨multiplicative.of_add 1, trivial, pow_one x⟩) $ λ x ⟨n, _, hn⟩, hn ▸ pow_mem _ (subset_closure $ set.mem_singleton _) _ /-- The submonoid generated by an element of a monoid equals the set of natural number powers of the element. -/ lemma mem_closure_singleton {x y : M} : y ∈ closure ({x} : set M) ↔ ∃ n:ℕ, x^n=y := by rw [closure_singleton_eq, mem_mrange]; refl @[to_additive] lemma closure_eq_mrange (s : set M) : closure s = (free_monoid.lift s M coe).mrange := by rw [mrange, ← free_monoid.closure_range_of, map_mclosure, ← set.range_comp, free_monoid.lift_comp_of, set.range_coe_subtype] @[to_additive] lemma exists_list_of_mem_closure {s : set M} {x : M} (hx : x ∈ closure s) : ∃ (l : list M) (hl : ∀ y ∈ l, y ∈ s), l.prod = x := begin rw [closure_eq_mrange, mem_mrange] at hx, rcases hx with ⟨l, hx⟩, exact ⟨list.map coe l, λ y hy, let ⟨z, hz, hy⟩ := list.mem_map.1 hy in hy ▸ z.2, hx⟩ end @[to_additive] lemma map_inl (s : submonoid M) : s.map (inl M N) = s.prod ⊥ := ext $ λ p, ⟨λ ⟨x, hx, hp⟩, hp ▸ ⟨hx, set.mem_singleton 1⟩, λ ⟨hps, hp1⟩, ⟨p.1, hps, prod.ext rfl $ (set.eq_of_mem_singleton hp1).symm⟩⟩ @[to_additive] lemma map_inr (s : submonoid N) : s.map (inr M N) = prod ⊥ s := ext $ λ p, ⟨λ ⟨x, hx, hp⟩, hp ▸ ⟨set.mem_singleton 1, hx⟩, λ ⟨hp1, hps⟩, ⟨p.2, hps, prod.ext (set.eq_of_mem_singleton hp1).symm rfl⟩⟩ @[to_additive] lemma range_inl : (inl M N).mrange = prod ⊤ ⊥ := map_inl ⊤ @[to_additive] lemma range_inr : (inr M N).mrange = prod ⊥ ⊤ := map_inr ⊤ @[to_additive] lemma range_inl' : (inl M N).mrange = comap (snd M N) ⊥ := range_inl.trans (top_prod _) @[to_additive] lemma range_inr' : (inr M N).mrange = comap (fst M N) ⊥ := range_inr.trans (prod_top _) @[simp, to_additive] lemma range_fst : (fst M N).mrange = ⊤ := (fst M N).mrange_top_of_surjective $ @prod.fst_surjective _ _ ⟨1⟩ @[simp, to_additive] lemma range_snd : (snd M N).mrange = ⊤ := (snd M N).mrange_top_of_surjective $ @prod.snd_surjective _ _ ⟨1⟩ @[simp, to_additive prod_bot_sup_bot_prod] lemma prod_bot_sup_bot_prod (s : submonoid M) (t : submonoid N) : (s.prod ⊥) ⊔ (prod ⊥ t) = s.prod t := le_antisymm (sup_le (prod_mono_right s bot_le) (prod_mono_left t bot_le)) $ assume p hp, prod.fst_mul_snd p ▸ mul_mem _ ((le_sup_left : s.prod ⊥ ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨hp.1, set.mem_singleton 1⟩) ((le_sup_right : prod ⊥ t ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨set.mem_singleton 1, hp.2⟩) @[simp, to_additive] lemma range_inl_sup_range_inr : (inl M N).mrange ⊔ (inr M N).mrange = ⊤ := by simp only [range_inl, range_inr, prod_bot_sup_bot_prod, top_prod_top] end submonoid namespace submonoid variables {N : Type*} [comm_monoid N] open monoid_hom @[to_additive] lemma sup_eq_range (s t : submonoid N) : s ⊔ t = (s.subtype.coprod t.subtype).mrange := by rw [mrange, ← range_inl_sup_range_inr, map_sup, map_mrange, coprod_comp_inl, map_mrange, coprod_comp_inr, range_subtype, range_subtype] @[to_additive] lemma mem_sup {s t : submonoid N} {x : N} : x ∈ s ⊔ t ↔ ∃ (y ∈ s) (z ∈ t), y * z = x := by simp only [sup_eq_range, mem_mrange, coprod_apply, prod.exists, submonoid.exists, coe_subtype, subtype.coe_mk] end submonoid namespace add_submonoid open set lemma smul_mem (S : add_submonoid A) {x : A} (hx : x ∈ S) : ∀ n : ℕ, add_monoid.smul n x ∈ S | 0 := S.zero_mem | (n+1) := S.add_mem hx (smul_mem n) lemma closure_singleton_eq (x : A) : closure ({x} : set A) = (multiples_hom A x).mrange := closure_eq_of_le (set.singleton_subset_iff.2 ⟨1, trivial, add_monoid.one_smul x⟩) $ λ x ⟨n, _, hn⟩, hn ▸ smul_mem _ (subset_closure $ set.mem_singleton _) _ /-- The `add_submonoid` generated by an element of an `add_monoid` equals the set of natural number multiples of the element. -/ lemma mem_closure_singleton {x y : A} : y ∈ closure ({x} : set A) ↔ ∃ n:ℕ, add_monoid.smul n x = y := by rw [closure_singleton_eq, add_monoid_hom.mem_mrange]; refl end add_submonoid namespace mul_equiv variables {S T : submonoid M} /-- Makes the identity isomorphism from a proof two submonoids of a multiplicative monoid are equal. -/ @[to_additive add_submonoid_congr "Makes the identity additive isomorphism from a proof two submonoids of an additive monoid are equal."] def submonoid_congr (h : S = T) : S ≃* T := { map_mul' := λ _ _, rfl, ..equiv.set_congr $ submonoid.ext'_iff.1 h } end mul_equiv
8a1ca0a728c7c0eb790476a19e8b2f2f60af1f5d
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/ring_theory/noetherian.lean
86f8f9e3b743c2b93e793c5debc440c6e9490bd2
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
23,063
lean
/- Copyright (c) 2018 Mario Carneiro and Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kevin Buzzard -/ import ring_theory.ideal_operations import linear_algebra.basis /-! # Noetherian rings and modules The following are equivalent for a module M over a ring R: 1. Every increasing chain of submodule M₁ ⊆ M₂ ⊆ M₃ ⊆ ⋯ eventually stabilises. 2. Every submodule is finitely generated. A module satisfying these equivalent conditions is said to be a *Noetherian* R-module. A ring is a *Noetherian ring* if it is Noetherian as a module over itself. ## Main definitions Let `R` be a ring and let `M` and `P` be `R`-modules. Let `N` be an `R`-submodule of `M`. * `fg N : Prop` is the assertion that `N` is finitely generated as an `R`-module. * `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module. It is a class, implemented as the predicate that all `R`-submodules of `M` are finitely generated. ## Main statements * `exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul` is Nakayama's lemma, in the following form: if N is a finitely generated submodule of an ambient R-module M and I is an ideal of R such that N ⊆ IN, then there exists r ∈ 1 + I such that rN = 0. * `is_noetherian_iff_well_founded` is the theorem that an R-module M is Noetherian iff `>` is well-founded on `submodule R M`. Note that the Hilbert basis theorem, that if a commutative ring R is Noetherian then so is R[X], is proved in `ring_theory.polynomial`. ## References * [M. F. Atiyah and I. G. Macdonald, *Introduction to commutative algebra*][atiyah-macdonald] ## Tags Noetherian, noetherian, Noetherian ring, Noetherian module, noetherian ring, noetherian module -/ open set namespace submodule variables {R : Type*} {M : Type*} [ring R] [add_comm_group M] [module R M] /-- A submodule of `M` is finitely generated if it is the span of a finite subset of `M`. -/ def fg (N : submodule R M) : Prop := ∃ S : finset M, submodule.span R ↑S = N theorem fg_def {N : submodule R M} : N.fg ↔ ∃ S : set M, finite S ∧ span R S = N := ⟨λ ⟨t, h⟩, ⟨_, finset.finite_to_set t, h⟩, begin rintro ⟨t', h, rfl⟩, rcases finite.exists_finset_coe h with ⟨t, rfl⟩, exact ⟨t, rfl⟩ end⟩ /-- Nakayama's Lemma. Atiyah-Macdonald 2.5, Eisenbud 4.7, Matsumura 2.2, Stacks 00DV -/ theorem exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul {R : Type*} [comm_ring R] {M : Type*} [add_comm_group M] [module R M] (I : ideal R) (N : submodule R M) (hn : N.fg) (hin : N ≤ I • N) : ∃ r : R, r - 1 ∈ I ∧ ∀ n ∈ N, r • n = (0 : M) := begin rw fg_def at hn, rcases hn with ⟨s, hfs, hs⟩, have : ∃ r : R, r - 1 ∈ I ∧ N ≤ (I • span R s).comap (linear_map.lsmul R M r) ∧ s ⊆ N, { refine ⟨1, _, _, _⟩, { rw sub_self, exact I.zero_mem }, { rw [hs], intros n hn, rw [mem_comap], change (1:R) • n ∈ I • N, rw one_smul, exact hin hn }, { rw [← span_le, hs], exact le_refl N } }, clear hin hs, revert this, refine set.finite.dinduction_on hfs (λ H, _) (λ i s his hfs ih H, _), { rcases H with ⟨r, hr1, hrn, hs⟩, refine ⟨r, hr1, λ n hn, _⟩, specialize hrn hn, rwa [mem_comap, span_empty, smul_bot, mem_bot] at hrn }, apply ih, rcases H with ⟨r, hr1, hrn, hs⟩, rw [← set.singleton_union, span_union, smul_sup] at hrn, rw [set.insert_subset] at hs, have : ∃ c : R, c - 1 ∈ I ∧ c • i ∈ I • span R s, { specialize hrn hs.1, rw [mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • i at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨c, hci, rfl⟩, use r-c, split, { rw [sub_right_comm], exact I.sub_mem hr1 hci }, { rw [sub_smul, ← hyz, add_sub_cancel'], exact hz } }, rcases this with ⟨c, hc1, hci⟩, refine ⟨c * r, _, _, hs.2⟩, { rw [← ideal.quotient.eq, ideal.quotient.mk_one] at hr1 hc1 ⊢, rw [ideal.quotient.mk_mul, hc1, hr1, mul_one] }, { intros n hn, specialize hrn hn, rw [mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • n at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨d, hdi, rfl⟩, change _ • _ ∈ I • span R s, rw [mul_smul, ← hyz, smul_add, smul_smul, mul_comm, mul_smul], exact add_mem _ (smul_mem _ _ hci) (smul_mem _ _ hz) } end theorem fg_bot : (⊥ : submodule R M).fg := ⟨∅, by rw [finset.coe_empty, span_empty]⟩ theorem fg_sup {N₁ N₂ : submodule R M} (hN₁ : N₁.fg) (hN₂ : N₂.fg) : (N₁ ⊔ N₂).fg := let ⟨t₁, ht₁⟩ := fg_def.1 hN₁, ⟨t₂, ht₂⟩ := fg_def.1 hN₂ in fg_def.2 ⟨t₁ ∪ t₂, finite_union ht₁.1 ht₂.1, by rw [span_union, ht₁.2, ht₂.2]⟩ variables {P : Type*} [add_comm_group P] [module R P] variables {f : M →ₗ[R] P} theorem fg_map {N : submodule R M} (hs : N.fg) : (N.map f).fg := let ⟨t, ht⟩ := fg_def.1 hs in fg_def.2 ⟨f '' t, finite_image _ ht.1, by rw [span_image, ht.2]⟩ theorem fg_prod {sb : submodule R M} {sc : submodule R P} (hsb : sb.fg) (hsc : sc.fg) : (sb.prod sc).fg := let ⟨tb, htb⟩ := fg_def.1 hsb, ⟨tc, htc⟩ := fg_def.1 hsc in fg_def.2 ⟨prod.inl '' tb ∪ prod.inr '' tc, finite_union (finite_image _ htb.1) (finite_image _ htc.1), by rw [linear_map.span_inl_union_inr, htb.2, htc.2]⟩ variable (f) /-- If 0 → M' → M → M'' → 0 is exact and M' and M'' are finitely generated then so is M. -/ theorem fg_of_fg_map_of_fg_inf_ker {s : submodule R M} (hs1 : (s.map f).fg) (hs2 : (s ⊓ f.ker).fg) : s.fg := begin haveI := classical.dec_eq R, haveI := classical.dec_eq M, haveI := classical.dec_eq P, cases hs1 with t1 ht1, cases hs2 with t2 ht2, have : ∀ y ∈ t1, ∃ x ∈ s, f x = y, { intros y hy, have : y ∈ map f s, { rw ← ht1, exact subset_span hy }, rcases mem_map.1 this with ⟨x, hx1, hx2⟩, exact ⟨x, hx1, hx2⟩ }, have : ∃ g : P → M, ∀ y ∈ t1, g y ∈ s ∧ f (g y) = y, { choose g hg1 hg2, existsi λ y, if H : y ∈ t1 then g y H else 0, intros y H, split, { simp only [dif_pos H], apply hg1 }, { simp only [dif_pos H], apply hg2 } }, cases this with g hg, clear this, existsi t1.image g ∪ t2, rw [finset.coe_union, span_union, finset.coe_image], apply le_antisymm, { refine sup_le (span_le.2 $ image_subset_iff.2 _) (span_le.2 _), { intros y hy, exact (hg y hy).1 }, { intros x hx, have := subset_span hx, rw ht2 at this, exact this.1 } }, intros x hx, have : f x ∈ map f s, { rw mem_map, exact ⟨x, hx, rfl⟩ }, rw [← ht1,← set.image_id ↑t1, finsupp.mem_span_iff_total] at this, rcases this with ⟨l, hl1, hl2⟩, refine mem_sup.2 ⟨(finsupp.total M M R id).to_fun ((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l), _, x - finsupp.total M M R id ((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l), _, add_sub_cancel'_right _ _⟩, { rw [← set.image_id (g '' ↑t1), finsupp.mem_span_iff_total], refine ⟨_, _, rfl⟩, haveI : inhabited P := ⟨0⟩, rw [← finsupp.lmap_domain_supported _ _ g, mem_map], refine ⟨l, hl1, _⟩, refl, }, rw [ht2, mem_inf], split, { apply s.sub_mem hx, rw [finsupp.total_apply, finsupp.lmap_domain_apply, finsupp.sum_map_domain_index], refine s.sum_mem _, { intros y hy, exact s.smul_mem _ (hg y (hl1 hy)).1 }, { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } }, { rw [linear_map.mem_ker, f.map_sub, ← hl2], rw [finsupp.total_apply, finsupp.total_apply, finsupp.lmap_domain_apply], rw [finsupp.sum_map_domain_index, finsupp.sum, finsupp.sum, f.map_sum], rw sub_eq_zero, refine finset.sum_congr rfl (λ y hy, _), unfold id, rw [f.map_smul, (hg y (hl1 hy)).2], { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } } end end submodule /-- `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module, implemented as the predicate that all `R`-submodules of `M` are finitely generated. -/ class is_noetherian (R M) [ring R] [add_comm_group M] [module R M] : Prop := (noetherian : ∀ (s : submodule R M), s.fg) section variables {R : Type*} {M : Type*} {P : Type*} variables [ring R] [add_comm_group M] [add_comm_group P] variables [module R M] [module R P] open is_noetherian include R theorem is_noetherian_submodule {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, s ≤ N → s.fg := ⟨λ ⟨hn⟩, λ s hs, have s ≤ N.subtype.range, from (N.range_subtype).symm ▸ hs, linear_map.map_comap_eq_self this ▸ submodule.fg_map (hn _), λ h, ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker N.subtype (h _ $ submodule.map_subtype_le _ _) $ by rw [submodule.ker_subtype, inf_bot_eq]; exact submodule.fg_bot⟩⟩ theorem is_noetherian_submodule_left {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, (N ⊓ s).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_left, λ H s hs, (inf_of_le_right hs) ▸ H _⟩ theorem is_noetherian_submodule_right {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, (s ⊓ N).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_right, λ H s hs, (inf_of_le_left hs) ▸ H _⟩ variable (M) theorem is_noetherian_of_surjective (f : M →ₗ[R] P) (hf : f.range = ⊤) [is_noetherian R M] : is_noetherian R P := ⟨λ s, have (s.comap f).map f = s, from linear_map.map_comap_eq_self $ hf.symm ▸ le_top, this ▸ submodule.fg_map $ noetherian _⟩ variable {M} theorem is_noetherian_of_linear_equiv (f : M ≃ₗ[R] P) [is_noetherian R M] : is_noetherian R P := is_noetherian_of_surjective _ f.to_linear_map f.range instance is_noetherian_prod [is_noetherian R M] [is_noetherian R P] : is_noetherian R (M × P) := ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker (linear_map.snd R M P) (noetherian _) $ have s ⊓ linear_map.ker (linear_map.snd R M P) ≤ linear_map.range (linear_map.inl R M P), from λ x ⟨hx1, hx2⟩, ⟨x.1, trivial, prod.ext rfl $ eq.symm $ linear_map.mem_ker.1 hx2⟩, linear_map.map_comap_eq_self this ▸ submodule.fg_map (noetherian _)⟩ instance is_noetherian_pi {R ι : Type*} {M : ι → Type*} [ring R] [Π i, add_comm_group (M i)] [Π i, module R (M i)] [fintype ι] [∀ i, is_noetherian R (M i)] : is_noetherian R (Π i, M i) := begin haveI := classical.dec_eq ι, suffices : ∀ s : finset ι, is_noetherian R (Π i : (↑s : set ι), M i), { letI := this finset.univ, refine @is_noetherian_of_linear_equiv _ _ _ _ _ _ _ _ ⟨_, _, _, _, _, _⟩ (this finset.univ), { exact λ f i, f ⟨i, finset.mem_univ _⟩ }, { intros, ext, refl }, { intros, ext, refl }, { exact λ f i, f i.1 }, { intro, ext i, cases i, refl }, { intro, ext i, refl } }, intro s, induction s using finset.induction with a s has ih, { split, intro s, convert submodule.fg_bot, apply eq_bot_iff.2, intros x hx, refine (submodule.mem_bot R).2 _, ext i, cases i.2 }, refine @is_noetherian_of_linear_equiv _ _ _ _ _ _ _ _ ⟨_, _, _, _, _, _⟩ (@is_noetherian_prod _ (M a) _ _ _ _ _ _ _ ih), { exact λ f i, or.by_cases (finset.mem_insert.1 i.2) (λ h : i.1 = a, show M i.1, from (eq.rec_on h.symm f.1)) (λ h : i.1 ∈ s, show M i.1, from f.2 ⟨i.1, h⟩) }, { intros f g, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = _ + _, simp only [dif_pos], refl }, { change _ = _ + _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { intros c f, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = c • _, simp only [dif_pos], refl }, { change _ = c • _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { exact λ f, (f ⟨a, finset.mem_insert_self _ _⟩, λ i, f ⟨i.1, finset.mem_insert_of_mem i.2⟩) }, { intro f, apply prod.ext, { simp only [or.by_cases, dif_pos] }, { ext i, cases i with i his, have : ¬i = a, { rintro rfl, exact has his }, dsimp only [or.by_cases], change i ∈ s at his, rw [dif_neg this, dif_pos his] } }, { intro f, ext i, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { simp only [or.by_cases, dif_pos], refl }, { have : ¬i = a, { rintro rfl, exact has h }, simp only [or.by_cases, dif_neg this, dif_pos h], refl } } end end open is_noetherian submodule function theorem is_noetherian_iff_well_founded {R M} [ring R] [add_comm_group M] [module R M] : is_noetherian R M ↔ well_founded ((>) : submodule R M → submodule R M → Prop) := ⟨λ h, begin apply order_embedding.well_founded_iff_no_descending_seq.2, swap, { apply is_strict_order.swap }, rintro ⟨⟨N, hN⟩⟩, let Q := ⨆ n, N n, resetI, rcases submodule.fg_def.1 (noetherian Q) with ⟨t, h₁, h₂⟩, have hN' : ∀ {a b}, a ≤ b → N a ≤ N b := λ a b, (strict_mono.le_iff_le (λ _ _, hN.1)).2, have : t ⊆ ⋃ i, (N i : set M), { rw [← submodule.coe_supr_of_directed N _], { show t ⊆ Q, rw ← h₂, apply submodule.subset_span }, { exact λ i j, ⟨max i j, hN' (le_max_left _ _), hN' (le_max_right _ _)⟩ } }, simp [subset_def] at this, choose f hf using show ∀ x : t, ∃ (i : ℕ), x.1 ∈ N i, { simpa }, cases h₁ with h₁, let A := finset.sup (@finset.univ t h₁) f, have : Q ≤ N A, { rw ← h₂, apply submodule.span_le.2, exact λ x h, hN' (finset.le_sup (@finset.mem_univ t h₁ _)) (hf ⟨x, h⟩) }, exact not_le_of_lt (hN.1 (nat.lt_succ_self A)) (le_trans (le_supr _ _) this) end, begin assume h, split, assume N, suffices : ∀ P ≤ N, ∃ s, finite s ∧ P ⊔ submodule.span R s = N, { rcases this ⊥ bot_le with ⟨s, hs, e⟩, exact submodule.fg_def.2 ⟨s, hs, by simpa using e⟩ }, refine λ P, h.induction P _, intros P IH PN, letI := classical.dec, by_cases h : ∀ x, x ∈ N → x ∈ P, { cases le_antisymm PN h, exact ⟨∅, by simp⟩ }, { simp [not_forall] at h, rcases h with ⟨x, h, h₂⟩, have : ¬P ⊔ submodule.span R {x} ≤ P, { intro hn, apply h₂, have := le_trans le_sup_right hn, exact submodule.span_le.1 this (mem_singleton x) }, rcases IH (P ⊔ submodule.span R {x}) ⟨@le_sup_left _ _ P _, this⟩ (sup_le PN (submodule.span_le.2 (by simpa))) with ⟨s, hs, hs₂⟩, refine ⟨insert x s, finite_insert _ hs, _⟩, rw [← hs₂, sup_assoc, ← submodule.span_union], simp } end⟩ lemma well_founded_submodule_gt (R M) [ring R] [add_comm_group M] [module R M] : ∀ [is_noetherian R M], well_founded ((>) : submodule R M → submodule R M → Prop) := is_noetherian_iff_well_founded.mp lemma finite_of_linear_independent {R M} [nonzero_comm_ring R] [add_comm_group M] [module R M] [is_noetherian R M] {s : set M} (hs : linear_independent R (subtype.val : s → M)) : s.finite := begin refine classical.by_contradiction (λ hf, order_embedding.well_founded_iff_no_descending_seq.1 (well_founded_submodule_gt R M) ⟨_⟩), have f : ℕ ↪ s, from @infinite.nat_embedding s ⟨λ f, hf ⟨f⟩⟩, have : ∀ n, (subtype.val ∘ f) '' {m | m ≤ n} ⊆ s, { rintros n x ⟨y, hy₁, hy₂⟩, subst hy₂, exact (f y).2 }, have : ∀ a b : ℕ, a ≤ b ↔ span R ((subtype.val ∘ f) '' {m | m ≤ a}) ≤ span R ((subtype.val ∘ f) '' {m | m ≤ b}), { assume a b, rw [span_le_span_iff (@zero_ne_one R _) hs (this a) (this b), set.image_subset_image_iff (subtype.val_injective.comp f.inj), set.subset_def], exact ⟨λ hab x (hxa : x ≤ a), le_trans hxa hab, λ hx, hx a (le_refl a)⟩ }, exact ⟨⟨λ n, span R ((subtype.val ∘ f) '' {m | m ≤ n}), λ x y, by simp [le_antisymm_iff, (this _ _).symm] {contextual := tt}⟩, by dsimp [gt]; simp only [lt_iff_le_not_le, (this _ _).symm]; tauto⟩ end /-- A ring is Noetherian if it is Noetherian as a module over itself, i.e. all its ideals are finitely generated. -/ @[class] def is_noetherian_ring (R) [ring R] : Prop := is_noetherian R R instance is_noetherian_ring.to_is_noetherian {R : Type*} [ring R] : ∀ [is_noetherian_ring R], is_noetherian R R := id @[priority 80] -- see Note [lower instance priority] instance ring.is_noetherian_of_fintype (R M) [fintype M] [ring R] [add_comm_group M] [module R M] : is_noetherian R M := by letI := classical.dec; exact ⟨assume s, ⟨to_finset s, by rw [set.coe_to_finset, submodule.span_eq]⟩⟩ theorem ring.is_noetherian_of_zero_eq_one {R} [ring R] (h01 : (0 : R) = 1) : is_noetherian_ring R := by haveI := subsingleton_of_zero_eq_one R h01; haveI := fintype.of_subsingleton (0:R); exact ring.is_noetherian_of_fintype _ _ theorem is_noetherian_of_submodule_of_noetherian (R M) [ring R] [add_comm_group M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R N := begin rw is_noetherian_iff_well_founded at h ⊢, convert order_embedding.well_founded (order_embedding.rsymm (submodule.map_subtype.lt_order_embedding N)) h end theorem is_noetherian_of_quotient_of_noetherian (R) [ring R] (M) [add_comm_group M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R N.quotient := begin rw is_noetherian_iff_well_founded at h ⊢, convert order_embedding.well_founded (order_embedding.rsymm (submodule.comap_mkq.lt_order_embedding N)) h end theorem is_noetherian_of_fg_of_noetherian {R M} [ring R] [add_comm_group M] [module R M] (N : submodule R M) [is_noetherian_ring R] (hN : N.fg) : is_noetherian R N := let ⟨s, hs⟩ := hN in begin haveI := classical.dec_eq M, haveI := classical.dec_eq R, letI : is_noetherian R R := by apply_instance, have : ∀ x ∈ s, x ∈ N, from λ x hx, hs ▸ submodule.subset_span hx, refine @@is_noetherian_of_surjective ((↑s : set M) → R) _ _ _ (pi.module _) _ _ _ is_noetherian_pi, { fapply linear_map.mk, { exact λ f, ⟨s.attach.sum (λ i, f i • i.1), N.sum_mem (λ c _, N.smul_mem _ $ this _ c.2)⟩ }, { intros f g, apply subtype.eq, change s.attach.sum (λ i, (f i + g i) • _) = _, simp only [add_smul, finset.sum_add_distrib], refl }, { intros c f, apply subtype.eq, change s.attach.sum (λ i, (c • f i) • _) = _, simp only [smul_eq_mul, mul_smul], exact finset.smul_sum.symm } }, rw linear_map.range_eq_top, rintro ⟨n, hn⟩, change n ∈ N at hn, rw [← hs, ← set.image_id ↑s, finsupp.mem_span_iff_total] at hn, rcases hn with ⟨l, hl1, hl2⟩, refine ⟨λ x, l x.1, subtype.eq _⟩, change s.attach.sum (λ i, l i.1 • i.1) = n, rw [@finset.sum_attach M M s _ (λ i, l i • i), ← hl2, finsupp.total_apply, finsupp.sum, eq_comm], refine finset.sum_subset hl1 (λ x _ hx, _), rw [finsupp.not_mem_support_iff.1 hx, zero_smul] end /-- In a module over a noetherian ring, the submodule generated by finitely many vectors is noetherian. -/ theorem is_noetherian_span_of_finite (R) {M} [ring R] [add_comm_group M] [module R M] [is_noetherian_ring R] {A : set M} (hA : finite A) : is_noetherian R (submodule.span R A) := is_noetherian_of_fg_of_noetherian _ (submodule.fg_def.mpr ⟨A, hA, rfl⟩) theorem is_noetherian_ring_of_surjective (R) [comm_ring R] (S) [comm_ring S] (f : R →+* S) (hf : function.surjective f) [H : is_noetherian_ring R] : is_noetherian_ring S := begin unfold is_noetherian_ring at H ⊢, rw is_noetherian_iff_well_founded at H ⊢, convert order_embedding.well_founded (order_embedding.rsymm (ideal.lt_order_embedding_of_surjective f hf)) H end instance is_noetherian_ring_range {R} [comm_ring R] {S} [comm_ring S] (f : R →+* S) [is_noetherian_ring R] : is_noetherian_ring (set.range f) := is_noetherian_ring_of_surjective R (set.range f) (f.cod_restrict (set.range f) set.mem_range_self) set.surjective_onto_range theorem is_noetherian_ring_of_ring_equiv (R) [comm_ring R] {S} [comm_ring S] (f : R ≃+* S) [is_noetherian_ring R] : is_noetherian_ring S := is_noetherian_ring_of_surjective R S f.to_ring_hom f.to_equiv.surjective namespace is_noetherian_ring variables {R : Type*} [integral_domain R] [is_noetherian_ring R] open associates nat local attribute [elab_as_eliminator] well_founded.fix lemma well_founded_dvd_not_unit : well_founded (λ a b : R, a ≠ 0 ∧ ∃ x, ¬is_unit x ∧ b = a * x) := by simp only [ideal.span_singleton_lt_span_singleton.symm]; exact inv_image.wf (λ a, ideal.span ({a} : set R)) (well_founded_submodule_gt _ _) lemma exists_irreducible_factor {a : R} (ha : ¬ is_unit a) (ha0 : a ≠ 0) : ∃ i, irreducible i ∧ i ∣ a := (irreducible_or_factor a ha).elim (λ hai, ⟨a, hai, dvd_refl _⟩) (well_founded.fix well_founded_dvd_not_unit (λ a ih ha ha0 ⟨x, y, hx, hy, hxy⟩, have hx0 : x ≠ 0, from λ hx0, ha0 (by rw [← hxy, hx0, zero_mul]), (irreducible_or_factor x hx).elim (λ hxi, ⟨x, hxi, hxy ▸ by simp⟩) (λ hxf, let ⟨i, hi⟩ := ih x ⟨hx0, y, hy, hxy.symm⟩ hx hx0 hxf in ⟨i, hi.1, dvd.trans hi.2 (hxy ▸ by simp)⟩)) a ha ha0) @[elab_as_eliminator] lemma irreducible_induction_on {P : R → Prop} (a : R) (h0 : P 0) (hu : ∀ u : R, is_unit u → P u) (hi : ∀ a i : R, a ≠ 0 → irreducible i → P a → P (i * a)) : P a := by haveI := classical.dec; exact well_founded.fix well_founded_dvd_not_unit (λ a ih, if ha0 : a = 0 then ha0.symm ▸ h0 else if hau : is_unit a then hu a hau else let ⟨i, hii, ⟨b, hb⟩⟩ := exists_irreducible_factor hau ha0 in have hb0 : b ≠ 0, from λ hb0, by simp * at *, hb.symm ▸ hi _ _ hb0 hii (ih _ ⟨hb0, i, hii.1, by rw [hb, mul_comm]⟩)) a lemma exists_factors (a : R) : a ≠ 0 → ∃f : multiset R, (∀b ∈ f, irreducible b) ∧ associated a f.prod := is_noetherian_ring.irreducible_induction_on a (λ h, (h rfl).elim) (λ u hu _, ⟨0, by simp [associated_one_iff_is_unit, hu]⟩) (λ a i ha0 hii ih hia0, let ⟨s, hs⟩ := ih ha0 in ⟨i::s, ⟨by clear _let_match; finish, by rw multiset.prod_cons; exact associated_mul_mul (by refl) hs.2⟩⟩) end is_noetherian_ring namespace submodule variables {R : Type*} {A : Type*} [comm_ring R] [ring A] [algebra R A] variables (M N : submodule R A) local attribute [instance] set.pointwise_mul_semiring theorem fg_mul (hm : M.fg) (hn : N.fg) : (M * N).fg := let ⟨m, hfm, hm⟩ := fg_def.1 hm, ⟨n, hfn, hn⟩ := fg_def.1 hn in fg_def.2 ⟨m * n, set.pointwise_mul_finite hfm hfn, span_mul_span R m n ▸ hm ▸ hn ▸ rfl⟩ lemma fg_pow (h : M.fg) (n : ℕ) : (M ^ n).fg := nat.rec_on n (⟨{1}, by simp [one_eq_span]⟩) (λ n ih, by simpa [pow_succ] using fg_mul _ _ h ih) end submodule
eb31b7e56597f8f567347b787c361594ff71689c
7cdf3413c097e5d36492d12cdd07030eb991d394
/world_experiments/world7/level6andthreequarters.lean
9dde5613b24c39703bd02e9a42ba2892d495a0c0
[]
no_license
alreadydone/natural_number_game
3135b9385a9f43e74cfbf79513fc37e69b99e0b3
1a39e693df4f4e871eb449890d3c7715a25c2ec9
refs/heads/master
1,599,387,390,105
1,573,200,587,000
1,573,200,691,000
220,397,084
0
0
null
1,573,192,734,000
1,573,192,733,000
null
UTF-8
Lean
false
false
2,637
lean
import mynat.definition -- hide import mynat.add -- hide import game.world2.level6andahalf -- hide namespace mynat -- hide /- Tactic : have The `have` tactic is a way to prove an intermediate lemma, in the middle of your proof. If `h : A = B` is a hypothesis (i.e., a proof of `A = B`) and your goal contains one or more `A`s, then `rw h` will change them all to `B`'s. If you want to change `B`s to `A`s instead, try `rw ←h` (get the arrow with `\l`). ### Example: If your local context (the top right window) looks like this ``` a b : mynat, h : succ (succ a) = succ (succ b) ⊢ a = b ``` then after `have h2 : succ(a)=succ(b)` it will look like this: ``` 2 goals a b : mynat, h : succ (succ a) = succ (succ b) ⊢ succ a = succ b a b : mynat, h : succ (succ a) = succ (succ b), h2 : succ a = succ b ⊢ a = b ``` Note that we have to prove a new goal now, but note also that the second goal now has `h2 : succ a = succ b` as an extra hypothesis which wasn't there before. -/ /- # World 2 -- Addition World ## Level 6 and three quarters: -- `succ_succ_inj`. -/ /- In the below theorem, we need to apply `succ_inj` twice. Once to prove $succ(succ(a))=succ(succ(b))\implies succ(a)=succ(b)$, and then again to prove $succ(a)=succ(b)\implies a=b$. However `succ(a)=succ(b)` is nowhere to be found, it's neither an assumption or a goal when we start this levl. If we're going to follow our proof sketch above then we are going to have to prove it along the way, and the `have` tactic lets us do this. Delete the `sorry` below and try this for the first line of your proof: `have h2 : succ(a)=succ(b),` and look what happens: a new goal appears! We've seen the `induction` tactic change one goal into two, but the `have` tactic does it in a far more simplistic way -- it just creates an extra goal with the idea that if we can solve this new goal then the corresponding proof will help us along the way to solving our original goal. You can close this new goal with ease. We want to apply `succ_inj` to hypothesis h, so `exact succ_inj(h),` will do it. After you remember the command and hit enter, you're back down to one goal, but now we have a proof of `h2 : succ(a)=succ(b)`. So we can deduce `a = b` with another application of `succ_inj`: `exact succ_inj(h2),` and you're home. -/ /- Theorem For all naturals $a$ and $b$, if we assume $succ(succ(a))=succ(succ(b))$, then we can deduce $a=b$. -/ theorem succ_succ_inj {a b : mynat} (h : succ(succ(a)) = succ(succ(b))) : a = b := begin [less_leaky] have h2 : succ(a)=succ(b), exact succ_inj(h), exact succ_inj(h2), end end mynat -- hide
bdc373dce692f6dfcc5e3691428decb4c41359a4
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/measure_theory/function/simple_func_dense.lean
524954f92c8c60db7c5098345b69716b61f0c1f5
[ "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,373
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Yury Kudryashov, Heather Macbeth -/ import measure_theory.integral.lebesgue /-! # Density of simple functions Show that each Borel measurable function can be approximated pointwise by a sequence of simple functions. ## Main definitions * `measure_theory.simple_func.nearest_pt (e : ℕ → α) (N : ℕ) : α →ₛ ℕ`: the `simple_func` sending each `x : α` to the point `e k` which is the nearest to `x` among `e 0`, ..., `e N`. * `measure_theory.simple_func.approx_on (f : β → α) (hf : measurable f) (s : set α) (y₀ : α) (h₀ : y₀ ∈ s) [separable_space s] (n : ℕ) : β →ₛ α` : a simple function that takes values in `s` and approximates `f`. ## Main results * `tendsto_approx_on` (pointwise convergence): If `f x ∈ s`, then the sequence of simple approximations `measure_theory.simple_func.approx_on f hf s y₀ h₀ n`, evaluated at `x`, tends to `f x` as `n` tends to `∞`. ## Notations * `α →ₛ β` (local notation): the type of simple functions `α → β`. -/ open set function filter topological_space ennreal emetric finset open_locale classical topological_space ennreal measure_theory big_operators variables {α β ι E F 𝕜 : Type*} noncomputable theory namespace measure_theory local infixr ` →ₛ `:25 := simple_func namespace simple_func /-! ### Pointwise approximation by simple functions -/ variables [measurable_space α] [pseudo_emetric_space α] [opens_measurable_space α] /-- `nearest_pt_ind e N x` is the index `k` such that `e k` is the nearest point to `x` among the points `e 0`, ..., `e N`. If more than one point are at the same distance from `x`, then `nearest_pt_ind e N x` returns the least of their indexes. -/ noncomputable def nearest_pt_ind (e : ℕ → α) : ℕ → α →ₛ ℕ | 0 := const α 0 | (N + 1) := piecewise (⋂ k ≤ N, {x | edist (e (N + 1)) x < edist (e k) x}) (measurable_set.Inter $ λ k, measurable_set.Inter $ λ hk, measurable_set_lt measurable_edist_right measurable_edist_right) (const α $ N + 1) (nearest_pt_ind N) /-- `nearest_pt e N x` is the nearest point to `x` among the points `e 0`, ..., `e N`. If more than one point are at the same distance from `x`, then `nearest_pt e N x` returns the point with the least possible index. -/ noncomputable def nearest_pt (e : ℕ → α) (N : ℕ) : α →ₛ α := (nearest_pt_ind e N).map e @[simp] lemma nearest_pt_ind_zero (e : ℕ → α) : nearest_pt_ind e 0 = const α 0 := rfl @[simp] lemma nearest_pt_zero (e : ℕ → α) : nearest_pt e 0 = const α (e 0) := rfl lemma nearest_pt_ind_succ (e : ℕ → α) (N : ℕ) (x : α) : nearest_pt_ind e (N + 1) x = if ∀ k ≤ N, edist (e (N + 1)) x < edist (e k) x then N + 1 else nearest_pt_ind e N x := by { simp only [nearest_pt_ind, coe_piecewise, set.piecewise], congr, simp } lemma nearest_pt_ind_le (e : ℕ → α) (N : ℕ) (x : α) : nearest_pt_ind e N x ≤ N := begin induction N with N ihN, { simp }, simp only [nearest_pt_ind_succ], split_ifs, exacts [le_rfl, ihN.trans N.le_succ] end lemma edist_nearest_pt_le (e : ℕ → α) (x : α) {k N : ℕ} (hk : k ≤ N) : edist (nearest_pt e N x) x ≤ edist (e k) x := begin induction N with N ihN generalizing k, { simp [nonpos_iff_eq_zero.1 hk, le_refl] }, { simp only [nearest_pt, nearest_pt_ind_succ, map_apply], split_ifs, { rcases hk.eq_or_lt with rfl|hk, exacts [le_rfl, (h k (nat.lt_succ_iff.1 hk)).le] }, { push_neg at h, rcases h with ⟨l, hlN, hxl⟩, rcases hk.eq_or_lt with rfl|hk, exacts [(ihN hlN).trans hxl, ihN (nat.lt_succ_iff.1 hk)] } } end lemma tendsto_nearest_pt {e : ℕ → α} {x : α} (hx : x ∈ closure (range e)) : tendsto (λ N, nearest_pt e N x) at_top (𝓝 x) := begin refine (at_top_basis.tendsto_iff nhds_basis_eball).2 (λ ε hε, _), rcases emetric.mem_closure_iff.1 hx ε hε with ⟨_, ⟨N, rfl⟩, hN⟩, rw [edist_comm] at hN, exact ⟨N, trivial, λ n hn, (edist_nearest_pt_le e x hn).trans_lt hN⟩ end variables [measurable_space β] {f : β → α} /-- Approximate a measurable function by a sequence of simple functions `F n` such that `F n x ∈ s`. -/ noncomputable def approx_on (f : β → α) (hf : measurable f) (s : set α) (y₀ : α) (h₀ : y₀ ∈ s) [separable_space s] (n : ℕ) : β →ₛ α := by haveI : nonempty s := ⟨⟨y₀, h₀⟩⟩; exact comp (nearest_pt (λ k, nat.cases_on k y₀ (coe ∘ dense_seq s) : ℕ → α) n) f hf @[simp] lemma approx_on_zero {f : β → α} (hf : measurable f) {s : set α} {y₀ : α} (h₀ : y₀ ∈ s) [separable_space s] (x : β) : approx_on f hf s y₀ h₀ 0 x = y₀ := rfl lemma approx_on_mem {f : β → α} (hf : measurable f) {s : set α} {y₀ : α} (h₀ : y₀ ∈ s) [separable_space s] (n : ℕ) (x : β) : approx_on f hf s y₀ h₀ n x ∈ s := begin haveI : nonempty s := ⟨⟨y₀, h₀⟩⟩, suffices : ∀ n, (nat.cases_on n y₀ (coe ∘ dense_seq s) : α) ∈ s, { apply this }, rintro (_|n), exacts [h₀, subtype.mem _] end @[simp] lemma approx_on_comp {γ : Type*} [measurable_space γ] {f : β → α} (hf : measurable f) {g : γ → β} (hg : measurable g) {s : set α} {y₀ : α} (h₀ : y₀ ∈ s) [separable_space s] (n : ℕ) : approx_on (f ∘ g) (hf.comp hg) s y₀ h₀ n = (approx_on f hf s y₀ h₀ n).comp g hg := rfl lemma tendsto_approx_on {f : β → α} (hf : measurable f) {s : set α} {y₀ : α} (h₀ : y₀ ∈ s) [separable_space s] {x : β} (hx : f x ∈ closure s) : tendsto (λ n, approx_on f hf s y₀ h₀ n x) at_top (𝓝 $ f x) := begin haveI : nonempty s := ⟨⟨y₀, h₀⟩⟩, rw [← @subtype.range_coe _ s, ← image_univ, ← (dense_range_dense_seq s).closure_eq] at hx, simp only [approx_on, coe_comp], refine tendsto_nearest_pt (closure_minimal _ is_closed_closure hx), simp only [nat.range_cases_on, closure_union, range_comp coe], exact subset.trans (image_closure_subset_closure_image continuous_subtype_coe) (subset_union_right _ _) end lemma edist_approx_on_mono {f : β → α} (hf : measurable f) {s : set α} {y₀ : α} (h₀ : y₀ ∈ s) [separable_space s] (x : β) {m n : ℕ} (h : m ≤ n) : edist (approx_on f hf s y₀ h₀ n x) (f x) ≤ edist (approx_on f hf s y₀ h₀ m x) (f x) := begin dsimp only [approx_on, coe_comp, (∘)], exact edist_nearest_pt_le _ _ ((nearest_pt_ind_le _ _ _).trans h) end lemma edist_approx_on_le {f : β → α} (hf : measurable f) {s : set α} {y₀ : α} (h₀ : y₀ ∈ s) [separable_space s] (x : β) (n : ℕ) : edist (approx_on f hf s y₀ h₀ n x) (f x) ≤ edist y₀ (f x) := edist_approx_on_mono hf h₀ x (zero_le n) lemma edist_approx_on_y0_le {f : β → α} (hf : measurable f) {s : set α} {y₀ : α} (h₀ : y₀ ∈ s) [separable_space s] (x : β) (n : ℕ) : edist y₀ (approx_on f hf s y₀ h₀ n x) ≤ edist y₀ (f x) + edist y₀ (f x) := calc edist y₀ (approx_on f hf s y₀ h₀ n x) ≤ edist y₀ (f x) + edist (approx_on f hf s y₀ h₀ n x) (f x) : edist_triangle_right _ _ _ ... ≤ edist y₀ (f x) + edist y₀ (f x) : add_le_add_left (edist_approx_on_le hf h₀ x n) _ end simple_func end measure_theory
b0edffad4c5ef241922246b165192714bf0edb97
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/linear_algebra/affine_space/independent.lean
db354ac1c5cda1cae66b352204feefc25c971fe9
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
28,394
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers -/ import data.finset.sort import data.matrix.notation import linear_algebra.affine_space.combination import linear_algebra.affine_space.affine_equiv import linear_algebra.basis /-! # Affine independence This file defines affinely independent families of points. ## Main definitions * `affine_independent` defines affinely independent families of points as those where no nontrivial weighted subtraction is `0`. This is proved equivalent to two other formulations: linear independence of the results of subtracting a base point in the family from the other points in the family, or any equal affine combinations having the same weights. A bundled type `simplex` is provided for finite affinely independent families of points, with an abbreviation `triangle` for the case of three points. ## References * https://en.wikipedia.org/wiki/Affine_space -/ noncomputable theory open_locale big_operators classical affine open function section affine_independent variables (k : Type*) {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] variables [affine_space V P] {ι : Type*} include V /-- An indexed family is said to be affinely independent if no nontrivial weighted subtractions (where the sum of weights is 0) are 0. -/ def affine_independent (p : ι → P) : Prop := ∀ (s : finset ι) (w : ι → k), ∑ i in s, w i = 0 → s.weighted_vsub p w = (0:V) → ∀ i ∈ s, w i = 0 /-- The definition of `affine_independent`. -/ lemma affine_independent_def (p : ι → P) : affine_independent k p ↔ ∀ (s : finset ι) (w : ι → k), ∑ i in s, w i = 0 → s.weighted_vsub p w = (0 : V) → ∀ i ∈ s, w i = 0 := iff.rfl /-- A family with at most one point is affinely independent. -/ lemma affine_independent_of_subsingleton [subsingleton ι] (p : ι → P) : affine_independent k p := λ s w h hs i hi, fintype.eq_of_subsingleton_of_sum_eq h i hi /-- A family indexed by a `fintype` is affinely independent if and only if no nontrivial weighted subtractions over `finset.univ` (where the sum of the weights is 0) are 0. -/ lemma affine_independent_iff_of_fintype [fintype ι] (p : ι → P) : affine_independent k p ↔ ∀ w : ι → k, ∑ i, w i = 0 → finset.univ.weighted_vsub p w = (0 : V) → ∀ i, w i = 0 := begin split, { exact λ h w hw hs i, h finset.univ w hw hs i (finset.mem_univ _) }, { intros h s w hw hs i hi, rw finset.weighted_vsub_indicator_subset _ _ (finset.subset_univ s) at hs, rw set.sum_indicator_subset _ (finset.subset_univ s) at hw, replace h := h ((↑s : set ι).indicator w) hw hs i, simpa [hi] using h } end /-- A family is affinely independent if and only if the differences from a base point in that family are linearly independent. -/ lemma affine_independent_iff_linear_independent_vsub (p : ι → P) (i1 : ι) : affine_independent k p ↔ linear_independent k (λ i : {x // x ≠ i1}, (p i -ᵥ p i1 : V)) := begin split, { intro h, rw linear_independent_iff', intros s g hg i hi, set f : ι → k := λ x, if hx : x = i1 then -∑ y in s, g y else g ⟨x, hx⟩ with hfdef, let s2 : finset ι := insert i1 (s.map (embedding.subtype _)), have hfg : ∀ x : {x // x ≠ i1}, g x = f x, { intro x, rw hfdef, dsimp only [], erw [dif_neg x.property, subtype.coe_eta] }, rw hfg, have hf : ∑ ι in s2, f ι = 0, { rw [finset.sum_insert (finset.not_mem_map_subtype_of_not_property s (not_not.2 rfl)), finset.sum_subtype_map_embedding (λ x hx, (hfg x).symm)], rw hfdef, dsimp only [], rw dif_pos rfl, exact neg_add_self _ }, have hs2 : s2.weighted_vsub p f = (0:V), { set f2 : ι → V := λ x, f x • (p x -ᵥ p i1) with hf2def, set g2 : {x // x ≠ i1} → V := λ x, g x • (p x -ᵥ p i1) with hg2def, have hf2g2 : ∀ x : {x // x ≠ i1}, f2 x = g2 x, { simp_rw [hf2def, hg2def, hfg], exact λ x, rfl }, rw [finset.weighted_vsub_eq_weighted_vsub_of_point_of_sum_eq_zero s2 f p hf (p i1), finset.weighted_vsub_of_point_insert, finset.weighted_vsub_of_point_apply, finset.sum_subtype_map_embedding (λ x hx, hf2g2 x)], exact hg }, exact h s2 f hf hs2 i (finset.mem_insert_of_mem (finset.mem_map.2 ⟨i, hi, rfl⟩)) }, { intro h, rw linear_independent_iff' at h, intros s w hw hs i hi, rw [finset.weighted_vsub_eq_weighted_vsub_of_point_of_sum_eq_zero s w p hw (p i1), ←s.weighted_vsub_of_point_erase w p i1, finset.weighted_vsub_of_point_apply] at hs, let f : ι → V := λ i, w i • (p i -ᵥ p i1), have hs2 : ∑ i in (s.erase i1).subtype (λ i, i ≠ i1), f i = 0, { rw [←hs], convert finset.sum_subtype_of_mem f (λ x, finset.ne_of_mem_erase) }, have h2 := h ((s.erase i1).subtype (λ i, i ≠ i1)) (λ x, w x) hs2, simp_rw [finset.mem_subtype] at h2, have h2b : ∀ i ∈ s, i ≠ i1 → w i = 0 := λ i his hi, h2 ⟨i, hi⟩ (finset.mem_erase_of_ne_of_mem hi his), exact finset.eq_zero_of_sum_eq_zero hw h2b i hi } end /-- A set is affinely independent if and only if the differences from a base point in that set are linearly independent. -/ lemma affine_independent_set_iff_linear_independent_vsub {s : set P} {p₁ : P} (hp₁ : p₁ ∈ s) : affine_independent k (λ p, p : s → P) ↔ linear_independent k (λ v, v : (λ p, (p -ᵥ p₁ : V)) '' (s \ {p₁}) → V) := begin rw affine_independent_iff_linear_independent_vsub k (λ p, p : s → P) ⟨p₁, hp₁⟩, split, { intro h, have hv : ∀ v : (λ p, (p -ᵥ p₁ : V)) '' (s \ {p₁}), (v : V) +ᵥ p₁ ∈ s \ {p₁} := λ v, (vsub_left_injective p₁).mem_set_image.1 ((vadd_vsub (v : V) p₁).symm ▸ v.property), let f : (λ p : P, (p -ᵥ p₁ : V)) '' (s \ {p₁}) → {x : s // x ≠ ⟨p₁, hp₁⟩} := λ x, ⟨⟨(x : V) +ᵥ p₁, set.mem_of_mem_diff (hv x)⟩, λ hx, set.not_mem_of_mem_diff (hv x) (subtype.ext_iff.1 hx)⟩, convert h.comp f (λ x1 x2 hx, (subtype.ext (vadd_right_cancel p₁ (subtype.ext_iff.1 (subtype.ext_iff.1 hx))))), ext v, exact (vadd_vsub (v : V) p₁).symm }, { intro h, let f : {x : s // x ≠ ⟨p₁, hp₁⟩} → (λ p : P, (p -ᵥ p₁ : V)) '' (s \ {p₁}) := λ x, ⟨((x : s) : P) -ᵥ p₁, ⟨x, ⟨⟨(x : s).property, λ hx, x.property (subtype.ext hx)⟩, rfl⟩⟩⟩, convert h.comp f (λ x1 x2 hx, subtype.ext (subtype.ext (vsub_left_cancel (subtype.ext_iff.1 hx)))) } end /-- A set of nonzero vectors is linearly independent if and only if, given a point `p₁`, the vectors added to `p₁` and `p₁` itself are affinely independent. -/ lemma linear_independent_set_iff_affine_independent_vadd_union_singleton {s : set V} (hs : ∀ v ∈ s, v ≠ (0 : V)) (p₁ : P) : linear_independent k (λ v, v : s → V) ↔ affine_independent k (λ p, p : {p₁} ∪ ((λ v, v +ᵥ p₁) '' s) → P) := begin rw affine_independent_set_iff_linear_independent_vsub k (set.mem_union_left _ (set.mem_singleton p₁)), have h : (λ p, (p -ᵥ p₁ : V)) '' (({p₁} ∪ (λ v, v +ᵥ p₁) '' s) \ {p₁}) = s, { simp_rw [set.union_diff_left, set.image_diff (vsub_left_injective p₁), set.image_image, set.image_singleton, vsub_self, vadd_vsub, set.image_id'], exact set.diff_singleton_eq_self (λ h, hs 0 h rfl) }, rw h end /-- A family is affinely independent if and only if any affine combinations (with sum of weights 1) that evaluate to the same point have equal `set.indicator`. -/ lemma affine_independent_iff_indicator_eq_of_affine_combination_eq (p : ι → P) : affine_independent k p ↔ ∀ (s1 s2 : finset ι) (w1 w2 : ι → k), ∑ i in s1, w1 i = 1 → ∑ i in s2, w2 i = 1 → s1.affine_combination p w1 = s2.affine_combination p w2 → set.indicator ↑s1 w1 = set.indicator ↑s2 w2 := begin split, { intros ha s1 s2 w1 w2 hw1 hw2 heq, ext i, by_cases hi : i ∈ (s1 ∪ s2), { rw ←sub_eq_zero, rw set.sum_indicator_subset _ (finset.subset_union_left s1 s2) at hw1, rw set.sum_indicator_subset _ (finset.subset_union_right s1 s2) at hw2, have hws : ∑ i in s1 ∪ s2, (set.indicator ↑s1 w1 - set.indicator ↑s2 w2) i = 0, { simp [hw1, hw2] }, rw [finset.affine_combination_indicator_subset _ _ (finset.subset_union_left s1 s2), finset.affine_combination_indicator_subset _ _ (finset.subset_union_right s1 s2), ←@vsub_eq_zero_iff_eq V, finset.affine_combination_vsub] at heq, exact ha (s1 ∪ s2) (set.indicator ↑s1 w1 - set.indicator ↑s2 w2) hws heq i hi }, { rw [←finset.mem_coe, finset.coe_union] at hi, simp [mt (set.mem_union_left ↑s2) hi, mt (set.mem_union_right ↑s1) hi] } }, { intros ha s w hw hs i0 hi0, let w1 : ι → k := function.update (function.const ι 0) i0 1, have hw1 : ∑ i in s, w1 i = 1, { rw [finset.sum_update_of_mem hi0, finset.sum_const_zero, add_zero] }, have hw1s : s.affine_combination p w1 = p i0 := s.affine_combination_of_eq_one_of_eq_zero w1 p hi0 (function.update_same _ _ _) (λ _ _ hne, function.update_noteq hne _ _), let w2 := w + w1, have hw2 : ∑ i in s, w2 i = 1, { simp [w2, finset.sum_add_distrib, hw, hw1] }, have hw2s : s.affine_combination p w2 = p i0, { simp [w2, ←finset.weighted_vsub_vadd_affine_combination, hs, hw1s] }, replace ha := ha s s w2 w1 hw2 hw1 (hw1s.symm ▸ hw2s), have hws : w2 i0 - w1 i0 = 0, { rw ←finset.mem_coe at hi0, rw [←set.indicator_of_mem hi0 w2, ←set.indicator_of_mem hi0 w1, ha, sub_self] }, simpa [w2] using hws } end variables {k} lemma affine_independent.indicator_eq_of_affine_combination_eq {p : ι → P} (ha : affine_independent k p) (s₁ s₂ : finset ι) (w₁ w₂ : ι → k) (hw₁ : ∑ i in s₁, w₁ i = 1) (hw₂ : ∑ i in s₂, w₂ i = 1) (h : s₁.affine_combination p w₁ = s₂.affine_combination p w₂) : set.indicator ↑s₁ w₁ = set.indicator ↑s₂ w₂ := (affine_independent_iff_indicator_eq_of_affine_combination_eq k p).1 ha s₁ s₂ w₁ w₂ hw₁ hw₂ h /-- An affinely independent family is injective, if the underlying ring is nontrivial. -/ protected lemma affine_independent.injective [nontrivial k] {p : ι → P} (ha : affine_independent k p) : function.injective p := begin intros i j hij, rw affine_independent_iff_linear_independent_vsub _ _ j at ha, by_contra hij', exact ha.ne_zero ⟨i, hij'⟩ (vsub_eq_zero_iff_eq.mpr hij) end /-- If a family is affinely independent, so is any subfamily given by composition of an embedding into index type with the original family. -/ lemma affine_independent.comp_embedding {ι2 : Type*} (f : ι2 ↪ ι) {p : ι → P} (ha : affine_independent k p) : affine_independent k (p ∘ f) := begin intros fs w hw hs i0 hi0, let fs' := fs.map f, let w' := λ i, if h : ∃ i2, f i2 = i then w h.some else 0, have hw' : ∀ i2 : ι2, w' (f i2) = w i2, { intro i2, have h : ∃ i : ι2, f i = f i2 := ⟨i2, rfl⟩, have hs : h.some = i2 := f.injective h.some_spec, simp_rw [w', dif_pos h, hs] }, have hw's : ∑ i in fs', w' i = 0, { rw [←hw, finset.sum_map], simp [hw'] }, have hs' : fs'.weighted_vsub p w' = (0:V), { rw [←hs, finset.weighted_vsub_map], congr' with i, simp [hw'] }, rw [←ha fs' w' hw's hs' (f i0) ((finset.mem_map' _).2 hi0), hw'] end /-- If a family is affinely independent, so is any subfamily indexed by a subtype of the index type. -/ protected lemma affine_independent.subtype {p : ι → P} (ha : affine_independent k p) (s : set ι) : affine_independent k (λ i : s, p i) := ha.comp_embedding (embedding.subtype _) /-- If an indexed family of points is affinely independent, so is the corresponding set of points. -/ protected lemma affine_independent.range {p : ι → P} (ha : affine_independent k p) : affine_independent k (λ x, x : set.range p → P) := begin let f : set.range p → ι := λ x, x.property.some, have hf : ∀ x, p (f x) = x := λ x, x.property.some_spec, let fe : set.range p ↪ ι := ⟨f, λ x₁ x₂ he, subtype.ext (hf x₁ ▸ hf x₂ ▸ he ▸ rfl)⟩, convert ha.comp_embedding fe, ext, simp [hf] end /-- If a set of points is affinely independent, so is any subset. -/ protected lemma affine_independent.mono {s t : set P} (ha : affine_independent k (λ x, x : t → P)) (hs : s ⊆ t) : affine_independent k (λ x, x : s → P) := ha.comp_embedding (s.embedding_of_subset t hs) /-- If the range of an injective indexed family of points is affinely independent, so is that family. -/ lemma affine_independent.of_set_of_injective {p : ι → P} (ha : affine_independent k (λ x, x : set.range p → P)) (hi : function.injective p) : affine_independent k p := ha.comp_embedding (⟨λ i, ⟨p i, set.mem_range_self _⟩, λ x y h, hi (subtype.mk_eq_mk.1 h)⟩ : ι ↪ set.range p) section composition variables {V₂ P₂ : Type*} [add_comm_group V₂] [module k V₂] [affine_space V₂ P₂] include V₂ /-- If the image of a family of points in affine space under an affine transformation is affine- independent, then the original family of points is also affine-independent. -/ lemma affine_independent.of_comp {p : ι → P} (f : P →ᵃ[k] P₂) (hai : affine_independent k (f ∘ p)) : affine_independent k p := begin cases is_empty_or_nonempty ι with h h, { haveI := h, apply affine_independent_of_subsingleton, }, obtain ⟨i⟩ := h, rw affine_independent_iff_linear_independent_vsub k p i, simp_rw [affine_independent_iff_linear_independent_vsub k (f ∘ p) i, function.comp_app, ← f.linear_map_vsub] at hai, exact linear_independent.of_comp f.linear hai, end /-- The image of a family of points in affine space, under an injective affine transformation, is affine-independent. -/ lemma affine_independent.map' {p : ι → P} (hai : affine_independent k p) (f : P →ᵃ[k] P₂) (hf : function.injective f) : affine_independent k (f ∘ p) := begin cases is_empty_or_nonempty ι with h h, { haveI := h, apply affine_independent_of_subsingleton, }, obtain ⟨i⟩ := h, rw affine_independent_iff_linear_independent_vsub k p i at hai, simp_rw [affine_independent_iff_linear_independent_vsub k (f ∘ p) i, function.comp_app, ← f.linear_map_vsub], have hf' : f.linear.ker = ⊥, { rwa [linear_map.ker_eq_bot, f.injective_iff_linear_injective], }, exact linear_independent.map' hai f.linear hf', end /-- Injective affine maps preserve affine independence. -/ lemma affine_map.affine_independent_iff {p : ι → P} (f : P →ᵃ[k] P₂) (hf : function.injective f) : affine_independent k (f ∘ p) ↔ affine_independent k p := ⟨affine_independent.of_comp f, λ hai, affine_independent.map' hai f hf⟩ /-- In particular, affine equivalences preserve affine independence. -/ lemma affine_equiv.affine_independent_iff {p : ι → P} (e : P ≃ᵃ[k] P₂) : affine_independent k (e ∘ p) ↔ affine_independent k p := e.to_affine_map.affine_independent_iff e.to_equiv.injective omit V₂ /-- In particular, homotheties preserve affine independence (when the scale factor is a unit). -/ lemma affine_map.homothety_affine_independent_iff {k : Type*} [comm_ring k] [module k V] {p : ι → P} {q : P} {t : units k} : affine_independent k ((affine_map.homothety q (t : k)) ∘ p) ↔ affine_independent k p := (affine_equiv.homothety_units_mul_hom q t).affine_independent_iff end composition /-- If a family is affinely independent, and the spans of points indexed by two subsets of the index type have a point in common, those subsets of the index type have an element in common, if the underlying ring is nontrivial. -/ lemma affine_independent.exists_mem_inter_of_exists_mem_inter_affine_span [nontrivial k] {p : ι → P} (ha : affine_independent k p) {s1 s2 : set ι} {p0 : P} (hp0s1 : p0 ∈ affine_span k (p '' s1)) (hp0s2 : p0 ∈ affine_span k (p '' s2)): ∃ (i : ι), i ∈ s1 ∩ s2 := begin rw set.image_eq_range at hp0s1 hp0s2, rw [mem_affine_span_iff_eq_affine_combination, ←finset.eq_affine_combination_subset_iff_eq_affine_combination_subtype] at hp0s1 hp0s2, rcases hp0s1 with ⟨fs1, hfs1, w1, hw1, hp0s1⟩, rcases hp0s2 with ⟨fs2, hfs2, w2, hw2, hp0s2⟩, rw affine_independent_iff_indicator_eq_of_affine_combination_eq at ha, replace ha := ha fs1 fs2 w1 w2 hw1 hw2 (hp0s1 ▸ hp0s2), have hnz : ∑ i in fs1, w1 i ≠ 0 := hw1.symm ▸ one_ne_zero, rcases finset.exists_ne_zero_of_sum_ne_zero hnz with ⟨i, hifs1, hinz⟩, simp_rw [←set.indicator_of_mem (finset.mem_coe.2 hifs1) w1, ha] at hinz, use [i, hfs1 hifs1, hfs2 (set.mem_of_indicator_ne_zero hinz)] end /-- If a family is affinely independent, the spans of points indexed by disjoint subsets of the index type are disjoint, if the underlying ring is nontrivial. -/ lemma affine_independent.affine_span_disjoint_of_disjoint [nontrivial k] {p : ι → P} (ha : affine_independent k p) {s1 s2 : set ι} (hd : s1 ∩ s2 = ∅) : (affine_span k (p '' s1) : set P) ∩ affine_span k (p '' s2) = ∅ := begin by_contradiction hne, change (affine_span k (p '' s1) : set P) ∩ affine_span k (p '' s2) ≠ ∅ at hne, rw set.ne_empty_iff_nonempty at hne, rcases hne with ⟨p0, hp0s1, hp0s2⟩, cases ha.exists_mem_inter_of_exists_mem_inter_affine_span hp0s1 hp0s2 with i hi, exact set.not_mem_empty i (hd ▸ hi) end /-- If a family is affinely independent, a point in the family is in the span of some of the points given by a subset of the index type if and only if that point's index is in the subset, if the underlying ring is nontrivial. -/ @[simp] protected lemma affine_independent.mem_affine_span_iff [nontrivial k] {p : ι → P} (ha : affine_independent k p) (i : ι) (s : set ι) : p i ∈ affine_span k (p '' s) ↔ i ∈ s := begin split, { intro hs, have h := affine_independent.exists_mem_inter_of_exists_mem_inter_affine_span ha hs (mem_affine_span k (set.mem_image_of_mem _ (set.mem_singleton _))), rwa [←set.nonempty_def, set.inter_singleton_nonempty] at h }, { exact λ h, mem_affine_span k (set.mem_image_of_mem p h) } end /-- If a family is affinely independent, a point in the family is not in the affine span of the other points, if the underlying ring is nontrivial. -/ lemma affine_independent.not_mem_affine_span_diff [nontrivial k] {p : ι → P} (ha : affine_independent k p) (i : ι) (s : set ι) : p i ∉ affine_span k (p '' (s \ {i})) := by simp [ha] lemma exists_nontrivial_relation_sum_zero_of_not_affine_ind {t : finset V} (h : ¬ affine_independent k (coe : t → V)) : ∃ f : V → k, ∑ e in t, f e • e = 0 ∧ ∑ e in t, f e = 0 ∧ ∃ x ∈ t, f x ≠ 0 := begin classical, rw affine_independent_iff_of_fintype at h, simp only [exists_prop, not_forall] at h, obtain ⟨w, hw, hwt, i, hi⟩ := h, simp only [finset.weighted_vsub_eq_weighted_vsub_of_point_of_sum_eq_zero _ w (coe : t → V) hw 0, vsub_eq_sub, finset.weighted_vsub_of_point_apply, sub_zero] at hwt, let f : Π (x : V), x ∈ t → k := λ x hx, w ⟨x, hx⟩, refine ⟨λ x, if hx : x ∈ t then f x hx else (0 : k), _, _, by { use i, simp [hi, f], }⟩, suffices : ∑ (e : V) in t, dite (e ∈ t) (λ hx, (f e hx) • e) (λ hx, 0) = 0, { convert this, ext, by_cases hx : x ∈ t; simp [hx], }, all_goals { simp only [finset.sum_dite_of_true (λx h, h), subtype.val_eq_coe, finset.mk_coe, f, hwt, hw], }, end end affine_independent section field variables {k : Type*} {V : Type*} {P : Type*} [field k] [add_comm_group V] [module k V] variables [affine_space V P] {ι : Type*} include V /-- An affinely independent set of points can be extended to such a set that spans the whole space. -/ lemma exists_subset_affine_independent_affine_span_eq_top {s : set P} (h : affine_independent k (λ p, p : s → P)) : ∃ t : set P, s ⊆ t ∧ affine_independent k (λ p, p : t → P) ∧ affine_span k t = ⊤ := begin rcases s.eq_empty_or_nonempty with rfl | ⟨p₁, hp₁⟩, { have p₁ : P := add_torsor.nonempty.some, let hsv := basis.of_vector_space k V, have hsvi := hsv.linear_independent, have hsvt := hsv.span_eq, rw basis.coe_of_vector_space at hsvi hsvt, have h0 : ∀ v : V, v ∈ (basis.of_vector_space_index _ _) → v ≠ 0, { intros v hv, simpa using hsv.ne_zero ⟨v, hv⟩ }, rw linear_independent_set_iff_affine_independent_vadd_union_singleton k h0 p₁ at hsvi, exact ⟨{p₁} ∪ (λ v, v +ᵥ p₁) '' _, set.empty_subset _, hsvi, affine_span_singleton_union_vadd_eq_top_of_span_eq_top p₁ hsvt⟩ }, { rw affine_independent_set_iff_linear_independent_vsub k hp₁ at h, let bsv := basis.extend h, have hsvi := bsv.linear_independent, have hsvt := bsv.span_eq, rw basis.coe_extend at hsvi hsvt, have hsv := h.subset_extend (set.subset_univ _), have h0 : ∀ v : V, v ∈ (h.extend _) → v ≠ 0, { intros v hv, simpa using bsv.ne_zero ⟨v, hv⟩ }, rw linear_independent_set_iff_affine_independent_vadd_union_singleton k h0 p₁ at hsvi, refine ⟨{p₁} ∪ (λ v, v +ᵥ p₁) '' h.extend (set.subset_univ _), _, _⟩, { refine set.subset.trans _ (set.union_subset_union_right _ (set.image_subset _ hsv)), simp [set.image_image] }, { use [hsvi, affine_span_singleton_union_vadd_eq_top_of_span_eq_top p₁ hsvt] } } end variables (k) /-- Two different points are affinely independent. -/ lemma affine_independent_of_ne {p₁ p₂ : P} (h : p₁ ≠ p₂) : affine_independent k ![p₁, p₂] := begin rw affine_independent_iff_linear_independent_vsub k ![p₁, p₂] 0, let i₁ : {x // x ≠ (0 : fin 2)} := ⟨1, by norm_num⟩, have he' : ∀ i, i = i₁, { rintro ⟨i, hi⟩, ext, fin_cases i, { simpa using hi } }, haveI : unique {x // x ≠ (0 : fin 2)} := ⟨⟨i₁⟩, he'⟩, have hz : (![p₁, p₂] ↑(default {x // x ≠ (0 : fin 2)}) -ᵥ ![p₁, p₂] 0 : V) ≠ 0, { rw he' (default _), simp, cc }, exact linear_independent_unique _ hz end end field namespace affine variables (k : Type*) {V : Type*} (P : Type*) [ring k] [add_comm_group V] [module k V] variables [affine_space V P] include V /-- A `simplex k P n` is a collection of `n + 1` affinely independent points. -/ structure simplex (n : ℕ) := (points : fin (n + 1) → P) (independent : affine_independent k points) /-- A `triangle k P` is a collection of three affinely independent points. -/ abbreviation triangle := simplex k P 2 namespace simplex variables {P} /-- Construct a 0-simplex from a point. -/ def mk_of_point (p : P) : simplex k P 0 := ⟨λ _, p, affine_independent_of_subsingleton k _⟩ /-- The point in a simplex constructed with `mk_of_point`. -/ @[simp] lemma mk_of_point_points (p : P) (i : fin 1) : (mk_of_point k p).points i = p := rfl instance [inhabited P] : inhabited (simplex k P 0) := ⟨mk_of_point k $ default P⟩ instance nonempty : nonempty (simplex k P 0) := ⟨mk_of_point k $ add_torsor.nonempty.some⟩ variables {k V} /-- Two simplices are equal if they have the same points. -/ @[ext] lemma ext {n : ℕ} {s1 s2 : simplex k P n} (h : ∀ i, s1.points i = s2.points i) : s1 = s2 := begin cases s1, cases s2, congr' with i, exact h i end /-- Two simplices are equal if and only if they have the same points. -/ lemma ext_iff {n : ℕ} (s1 s2 : simplex k P n): s1 = s2 ↔ ∀ i, s1.points i = s2.points i := ⟨λ h _, h ▸ rfl, ext⟩ /-- A face of a simplex is a simplex with the given subset of points. -/ def face {n : ℕ} (s : simplex k P n) {fs : finset (fin (n + 1))} {m : ℕ} (h : fs.card = m + 1) : simplex k P m := ⟨s.points ∘ fs.order_emb_of_fin h, s.independent.comp_embedding (fs.order_emb_of_fin h).to_embedding⟩ /-- The points of a face of a simplex are given by `mono_of_fin`. -/ lemma face_points {n : ℕ} (s : simplex k P n) {fs : finset (fin (n + 1))} {m : ℕ} (h : fs.card = m + 1) (i : fin (m + 1)) : (s.face h).points i = s.points (fs.order_emb_of_fin h i) := rfl /-- The points of a face of a simplex are given by `mono_of_fin`. -/ lemma face_points' {n : ℕ} (s : simplex k P n) {fs : finset (fin (n + 1))} {m : ℕ} (h : fs.card = m + 1) : (s.face h).points = s.points ∘ (fs.order_emb_of_fin h) := rfl /-- A single-point face equals the 0-simplex constructed with `mk_of_point`. -/ @[simp] lemma face_eq_mk_of_point {n : ℕ} (s : simplex k P n) (i : fin (n + 1)) : s.face (finset.card_singleton i) = mk_of_point k (s.points i) := by { ext, simp [face_points] } /-- The set of points of a face. -/ @[simp] lemma range_face_points {n : ℕ} (s : simplex k P n) {fs : finset (fin (n + 1))} {m : ℕ} (h : fs.card = m + 1) : set.range (s.face h).points = s.points '' ↑fs := by rw [face_points', set.range_comp, finset.range_order_emb_of_fin] end simplex end affine namespace affine namespace simplex variables {k : Type*} {V : Type*} {P : Type*} [division_ring k] [add_comm_group V] [module k V] [affine_space V P] include V /-- The centroid of a face of a simplex as the centroid of a subset of the points. -/ @[simp] lemma face_centroid_eq_centroid {n : ℕ} (s : simplex k P n) {fs : finset (fin (n + 1))} {m : ℕ} (h : fs.card = m + 1) : finset.univ.centroid k (s.face h).points = fs.centroid k s.points := begin convert (finset.univ.centroid_map k (fs.order_emb_of_fin h).to_embedding s.points).symm, rw [← finset.coe_inj, finset.coe_map, finset.coe_univ, set.image_univ], simp end /-- Over a characteristic-zero division ring, the centroids given by two subsets of the points of a simplex are equal if and only if those faces are given by the same subset of points. -/ @[simp] lemma centroid_eq_iff [char_zero k] {n : ℕ} (s : simplex k P n) {fs₁ fs₂ : finset (fin (n + 1))} {m₁ m₂ : ℕ} (h₁ : fs₁.card = m₁ + 1) (h₂ : fs₂.card = m₂ + 1) : fs₁.centroid k s.points = fs₂.centroid k s.points ↔ fs₁ = fs₂ := begin split, { intro h, rw [finset.centroid_eq_affine_combination_fintype, finset.centroid_eq_affine_combination_fintype] at h, have ha := (affine_independent_iff_indicator_eq_of_affine_combination_eq k s.points).1 s.independent _ _ _ _ (fs₁.sum_centroid_weights_indicator_eq_one_of_card_eq_add_one k h₁) (fs₂.sum_centroid_weights_indicator_eq_one_of_card_eq_add_one k h₂) h, simp_rw [finset.coe_univ, set.indicator_univ, function.funext_iff, finset.centroid_weights_indicator_def, finset.centroid_weights, h₁, h₂] at ha, ext i, replace ha := ha i, split, all_goals { intro hi, by_contradiction hni, simp [hi, hni] at ha, norm_cast at ha } }, { intro h, have hm : m₁ = m₂, { subst h, simpa [h₁] using h₂ }, subst hm, congr, exact h } end /-- Over a characteristic-zero division ring, the centroids of two faces of a simplex are equal if and only if those faces are given by the same subset of points. -/ lemma face_centroid_eq_iff [char_zero k] {n : ℕ} (s : simplex k P n) {fs₁ fs₂ : finset (fin (n + 1))} {m₁ m₂ : ℕ} (h₁ : fs₁.card = m₁ + 1) (h₂ : fs₂.card = m₂ + 1) : finset.univ.centroid k (s.face h₁).points = finset.univ.centroid k (s.face h₂).points ↔ fs₁ = fs₂ := begin rw [face_centroid_eq_centroid, face_centroid_eq_centroid], exact s.centroid_eq_iff h₁ h₂ end /-- Two simplices with the same points have the same centroid. -/ lemma centroid_eq_of_range_eq {n : ℕ} {s₁ s₂ : simplex k P n} (h : set.range s₁.points = set.range s₂.points) : finset.univ.centroid k s₁.points = finset.univ.centroid k s₂.points := begin rw [←set.image_univ, ←set.image_univ, ←finset.coe_univ] at h, exact finset.univ.centroid_eq_of_inj_on_of_image_eq k _ (λ _ _ _ _ he, affine_independent.injective s₁.independent he) (λ _ _ _ _ he, affine_independent.injective s₂.independent he) h end end simplex end affine
9307a6a7ea0f9d3a999f8b13c76e84a0aab8a81b
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch4/ex0405.lean
1b17ed296f79238d45b6813e967489459100e4c0
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
167
lean
variables (α : Type) (p q : α → Prop) example (h : ∃ x, p x ∧ q x) : ∃ x, q x ∧ p x := match h with ⟨w, hw⟩ := ⟨w, hw.right, hw.left⟩ end
4ab0c89129e708eeb055eaaf1ab3275358303159
bf532e3e865883a676110e756f800e0ddeb465be
/data/equiv.lean
6a07cded1af45873dd797248db4b49ad020b354f
[ "Apache-2.0" ]
permissive
aqjune/mathlib
da42a97d9e6670d2efaa7d2aa53ed3585dafc289
f7977ff5a6bcf7e5c54eec908364ceb40dafc795
refs/heads/master
1,631,213,225,595
1,521,089,840,000
1,521,089,840,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
28,131
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro In the standard library we cannot assume the univalence axiom. We say two types are equivalent if they are isomorphic. Two equivalent types have the same cardinality. -/ import data.prod data.nat.pairing logic.function tactic data.set.lattice import algebra.group open function universes u v w variables {α : Sort u} {β : Sort v} {γ : Sort w} namespace subtype /-- Restriction of a function to a function on subtypes. -/ def map {p : α → Prop} {q : β → Prop} (f : α → β) (h : ∀a, p a → q (f a)) : subtype p → subtype q | ⟨v, hv⟩ := ⟨f v, h v hv⟩ theorem map_comp {p : α → Prop} {q : β → Prop} {r : γ → Prop} {x : subtype p} (f : α → β) (h : ∀a, p a → q (f a)) (g : β → γ) (l : ∀a, q a → r (g a)) : map g l (map f h x) = map (g ∘ f) (assume a ha, l (f a) $ h a ha) x := by cases x with v h; refl theorem map_id {p : α → Prop} {h : ∀a, p a → p (id a)} : map (@id α) h = id := funext $ assume ⟨v, h⟩, rfl end subtype namespace function theorem left_inverse.f_g_eq_id {f : α → β} {g : β → α} (h : left_inverse f g) : f ∘ g = id := funext $ h theorem right_inverse.g_f_eq_id {f : α → β} {g : β → α} (h : right_inverse f g) : g ∘ f = id := funext $ h theorem left_inverse.comp {f : α → β} {g : β → α} {h : β → γ} {i : γ → β} (hf : left_inverse f g) (hh : left_inverse h i) : left_inverse (h ∘ f) (g ∘ i) := assume a, show h (f (g (i a))) = a, by rw [hf (i a), hh a] theorem right_inverse.comp {f : α → β} {g : β → α} {h : β → γ} {i : γ → β} (hf : right_inverse f g) (hh : right_inverse h i) : right_inverse (h ∘ f) (g ∘ i) := left_inverse.comp hh hf end function /-- `α ≃ β` is the type of functions from `α → β` with a two-sided inverse. -/ structure equiv (α : Sort*) (β : Sort*) := (to_fun : α → β) (inv_fun : β → α) (left_inv : left_inverse inv_fun to_fun) (right_inv : right_inverse inv_fun to_fun) namespace equiv /-- `perm α` is the type of bijections from `α` to itself. -/ @[reducible] def perm (α : Sort*) := equiv α α infix ` ≃ `:50 := equiv instance : has_coe_to_fun (α ≃ β) := ⟨_, to_fun⟩ @[simp] theorem coe_fn_mk (f : α → β) (g l r) : (equiv.mk f g l r : α → β) = f := rfl theorem eq_of_to_fun_eq : ∀ {e₁ e₂ : equiv α β}, (e₁ : α → β) = e₂ → e₁ = e₂ | ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ h := have f₁ = f₂, from h, have g₁ = g₂, from funext $ assume x, have f₁ (g₁ x) = f₂ (g₂ x), from (r₁ x).trans (r₂ x).symm, have f₁ (g₁ x) = f₁ (g₂ x), by subst f₂; exact this, show g₁ x = g₂ x, from injective_of_left_inverse l₁ this, by simp * lemma ext (f g : equiv α β) (H : ∀ x, f x = g x) : f = g := eq_of_to_fun_eq (funext H) @[refl] protected def refl (α : Sort*) : α ≃ α := ⟨id, id, λ x, rfl, λ x, rfl⟩ @[symm] protected def symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun, e.right_inv, e.left_inv⟩ @[trans] protected def trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ := ⟨e₂.to_fun ∘ e₁.to_fun, e₁.inv_fun ∘ e₂.inv_fun, e₂.left_inv.comp e₁.left_inv, e₂.right_inv.comp e₁.right_inv⟩ protected theorem bijective : ∀ f : α ≃ β, bijective f | ⟨f, g, h₁, h₂⟩ := ⟨injective_of_left_inverse h₁, surjective_of_has_right_inverse ⟨_, h₂⟩⟩ protected theorem subsingleton (e : α ≃ β) : ∀ [subsingleton β], subsingleton α | ⟨H⟩ := ⟨λ a b, e.bijective.1 (H _ _)⟩ protected def decidable_eq (e : α ≃ β) [H : decidable_eq β] : decidable_eq α | a b := decidable_of_iff _ e.bijective.1.eq_iff protected def cast {α β : Sort*} (h : α = β) : α ≃ β := ⟨cast h, cast h.symm, λ x, by cases h; refl, λ x, by cases h; refl⟩ @[simp] theorem coe_fn_symm_mk (f : α → β) (g l r) : ((equiv.mk f g l r).symm : β → α) = g := rfl @[simp] theorem refl_apply (x : α) : equiv.refl α x = x := rfl @[simp] theorem trans_apply : ∀ (f : α ≃ β) (g : β ≃ γ) (a : α), (f.trans g) a = g (f a) | ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ a := rfl @[simp] theorem apply_inverse_apply : ∀ (e : α ≃ β) (x : β), e (e.symm x) = x | ⟨f₁, g₁, l₁, r₁⟩ x := by simp [equiv.symm]; rw r₁ @[simp] theorem inverse_apply_apply : ∀ (e : α ≃ β) (x : α), e.symm (e x) = x | ⟨f₁, g₁, l₁, r₁⟩ x := by simp [equiv.symm]; rw l₁ @[simp] theorem apply_eq_iff_eq : ∀ (f : α ≃ β) (x y : α), f x = f y ↔ x = y | ⟨f₁, g₁, l₁, r₁⟩ x y := (injective_of_left_inverse l₁).eq_iff @[simp] theorem cast_apply {α β} (h : α = β) (x : α) : equiv.cast h x = cast h x := rfl theorem apply_eq_iff_eq_inverse_apply : ∀ (f : α ≃ β) (x : α) (y : β), f x = y ↔ x = f.symm y | ⟨f₁, g₁, l₁, r₁⟩ x y := by simp [equiv.symm]; show f₁ x = y ↔ x = g₁ y; from ⟨λ e : f₁ x = y, e ▸ (l₁ x).symm, λ e : x = g₁ y, e.symm ▸ r₁ y⟩ /- The group of permutations (self-equivalences) of a type `α` -/ instance perm_group {α : Type u} : group (perm α) := begin refine { mul := λ f g, equiv.trans g f, one := equiv.refl α, inv:= equiv.symm, ..}; intros; apply equiv.ext; try { apply trans_apply }, apply inverse_apply_apply end def equiv_empty (h : α → false) : α ≃ empty := ⟨λ x, (h x).elim, λ e, e.rec _, λ x, (h x).elim, λ e, e.rec _⟩ def false_equiv_empty : false ≃ empty := equiv_empty _root_.id def empty_of_not_nonempty {α : Sort*} (h : ¬ nonempty α) : α ≃ empty := ⟨assume a, (h ⟨a⟩).elim, assume e, e.rec_on _, assume a, (h ⟨a⟩).elim, assume e, e.rec_on _⟩ protected def ulift {α : Type u} : ulift α ≃ α := ⟨ulift.down, ulift.up, ulift.up_down, λ a, rfl⟩ protected def plift : plift α ≃ α := ⟨plift.down, plift.up, plift.up_down, plift.down_up⟩ @[congr] def arrow_congr {α₁ β₁ α₂ β₂ : Sort*} : α₁ ≃ α₂ → β₁ ≃ β₂ → (α₁ → β₁) ≃ (α₂ → β₂) | ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ := ⟨λ (h : α₁ → β₁) (a : α₂), f₂ (h (g₁ a)), λ (h : α₂ → β₂) (a : α₁), g₂ (h (f₁ a)), λ h, by funext a; dsimp; rw [l₁, l₂], λ h, by funext a; dsimp; rw [r₁, r₂]⟩ section @[simp] def arrow_unit_equiv_unit (α : Sort*) : (α → unit) ≃ unit := ⟨λ f, (), λ u f, (), λ f, by funext x; cases f x; refl, λ u, by cases u; reflexivity⟩ @[simp] def unit_arrow_equiv (α : Sort*) : (unit → α) ≃ α := ⟨λ f, f (), λ a u, a, λ f, by funext x; cases x; refl, λ u, rfl⟩ @[simp] def empty_arrow_equiv_unit (α : Sort*) : (empty → α) ≃ unit := ⟨λ f, (), λ u e, e.rec _, λ f, funext $ λ x, x.rec _, λ u, by cases u; refl⟩ @[simp] def false_arrow_equiv_unit (α : Sort*) : (false → α) ≃ unit := calc (false → α) ≃ (empty → α) : arrow_congr false_equiv_empty (equiv.refl _) ... ≃ unit : empty_arrow_equiv_unit _ def arrow_empty_unit {α : Sort*} : (empty → α) ≃ unit := ⟨λf, (), λu e, e.rec_on _, assume f, funext $ assume e, e.rec_on _, assume u, unit_eq _ _⟩ end @[congr] def prod_congr {α₁ β₁ α₂ β₂ : Sort*} : α₁ ≃ α₂ → β₁ ≃ β₂ → (α₁ × β₁) ≃ (α₂ × β₂) | ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ := ⟨λ ⟨a, b⟩, (f₁ a, f₂ b), λ ⟨a, b⟩, (g₁ a, g₂ b), λ ⟨a, b⟩, show (g₁ (f₁ a), g₂ (f₂ b)) = (a, b), by rw [l₁ a, l₂ b], λ ⟨a, b⟩, show (f₁ (g₁ a), f₂ (g₂ b)) = (a, b), by rw [r₁ a, r₂ b]⟩ @[simp] theorem prod_congr_apply {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (a : α₁) (b : β₁) : prod_congr e₁ e₂ (a, b) = (e₁ a, e₂ b) := by cases e₁; cases e₂; refl @[simp] def prod_comm (α β : Sort*) : (α × β) ≃ (β × α) := ⟨λ p, (p.2, p.1), λ p, (p.2, p.1), λ⟨a, b⟩, rfl, λ⟨a, b⟩, rfl⟩ @[simp] def prod_assoc (α β γ : Sort*) : ((α × β) × γ) ≃ (α × (β × γ)) := ⟨λ p, ⟨p.1.1, ⟨p.1.2, p.2⟩⟩, λp, ⟨⟨p.1, p.2.1⟩, p.2.2⟩, λ ⟨⟨a, b⟩, c⟩, rfl, λ ⟨a, ⟨b, c⟩⟩, rfl⟩ @[simp] theorem prod_assoc_apply {α β γ : Sort*} (p : (α × β) × γ) : prod_assoc α β γ p = ⟨p.1.1, ⟨p.1.2, p.2⟩⟩ := rfl section @[simp] def prod_unit (α : Sort*) : (α × unit) ≃ α := ⟨λ p, p.1, λ a, (a, ()), λ ⟨_, ⟨⟩⟩, rfl, λ a, rfl⟩ @[simp] theorem prod_unit_apply {α : Sort*} (a : α × unit) : prod_unit α a = a.1 := rfl @[simp] def unit_prod (α : Sort*) : (unit × α) ≃ α := calc (unit × α) ≃ (α × unit) : prod_comm _ _ ... ≃ α : prod_unit _ @[simp] theorem unit_prod_apply {α : Sort*} (a : unit × α) : unit_prod α a = a.2 := rfl @[simp] def prod_empty (α : Sort*) : (α × empty) ≃ empty := equiv_empty (λ ⟨_, e⟩, e.rec _) @[simp] def empty_prod (α : Sort*) : (empty × α) ≃ empty := equiv_empty (λ ⟨e, _⟩, e.rec _) end section open sum def psum_equiv_sum (α β : Sort*) : psum α β ≃ (α ⊕ β) := ⟨λ s, psum.cases_on s inl inr, λ s, sum.cases_on s psum.inl psum.inr, λ s, by cases s; refl, λ s, by cases s; refl⟩ def sum_congr {α₁ β₁ α₂ β₂ : Sort*} : α₁ ≃ α₂ → β₁ ≃ β₂ → (α₁ ⊕ β₁) ≃ (α₂ ⊕ β₂) | ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ := ⟨λ s, match s with inl a₁ := inl (f₁ a₁) | inr b₁ := inr (f₂ b₁) end, λ s, match s with inl a₂ := inl (g₁ a₂) | inr b₂ := inr (g₂ b₂) end, λ s, match s with inl a := congr_arg inl (l₁ a) | inr a := congr_arg inr (l₂ a) end, λ s, match s with inl a := congr_arg inl (r₁ a) | inr a := congr_arg inr (r₂ a) end⟩ @[simp] theorem sum_congr_apply_inl {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (a : α₁) : sum_congr e₁ e₂ (inl a) = inl (e₁ a) := by cases e₁; cases e₂; refl @[simp] theorem sum_congr_apply_inr {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (b : β₁) : sum_congr e₁ e₂ (inr b) = inr (e₂ b) := by cases e₁; cases e₂; refl def bool_equiv_unit_sum_unit : bool ≃ (unit ⊕ unit) := ⟨λ b, cond b inl inr (), λ s, sum.rec_on s (λ_, tt) (λ_, ff), λ b, by cases b; refl, λ s, by rcases s with ⟨⟨⟩⟩ | ⟨⟨⟩⟩; refl⟩ noncomputable def Prop_equiv_bool : Prop ≃ bool := ⟨λ p, @to_bool p (classical.prop_decidable _), λ b, b, λ p, by simp, λ b, by simp⟩ @[simp] def sum_comm (α β : Sort*) : (α ⊕ β) ≃ (β ⊕ α) := ⟨λ s, match s with inl a := inr a | inr b := inl b end, λ s, match s with inl b := inr b | inr a := inl a end, λ s, by cases s; refl, λ s, by cases s; refl⟩ @[simp] def sum_assoc (α β γ : Sort*) : ((α ⊕ β) ⊕ γ) ≃ (α ⊕ (β ⊕ γ)) := ⟨λ s, match s with inl (inl a) := inl a | inl (inr b) := inr (inl b) | inr c := inr (inr c) end, λ s, match s with inl a := inl (inl a) | inr (inl b) := inl (inr b) | inr (inr c) := inr c end, λ s, by rcases s with ⟨_ | _⟩ | _; refl, λ s, by rcases s with _ | _ | _; refl⟩ @[simp] theorem sum_assoc_apply_in1 {α β γ} (a) : sum_assoc α β γ (inl (inl a)) = inl a := rfl @[simp] theorem sum_assoc_apply_in2 {α β γ} (b) : sum_assoc α β γ (inl (inr b)) = inr (inl b) := rfl @[simp] theorem sum_assoc_apply_in3 {α β γ} (c) : sum_assoc α β γ (inr c) = inr (inr c) := rfl @[simp] def sum_empty (α : Sort*) : (α ⊕ empty) ≃ α := ⟨λ s, match s with inl a := a | inr e := empty.rec _ e end, inl, λ s, by rcases s with _ | ⟨⟨⟩⟩; refl, λ a, rfl⟩ @[simp] def empty_sum (α : Sort*) : (empty ⊕ α) ≃ α := (sum_comm _ _).trans $ sum_empty _ @[simp] def option_equiv_sum_unit (α : Sort*) : option α ≃ (α ⊕ unit) := ⟨λ o, match o with none := inr () | some a := inl a end, λ s, match s with inr _ := none | inl a := some a end, λ o, by cases o; refl, λ s, by rcases s with _ | ⟨⟨⟩⟩; refl⟩ def sum_equiv_sigma_bool (α β : Sort*) : (α ⊕ β) ≃ (Σ b: bool, cond b α β) := ⟨λ s, match s with inl a := ⟨tt, a⟩ | inr b := ⟨ff, b⟩ end, λ s, match s with ⟨tt, a⟩ := inl a | ⟨ff, b⟩ := inr b end, λ s, by cases s; refl, λ s, by rcases s with ⟨_|_, _⟩; refl⟩ end section def Pi_congr_right {α} {β₁ β₂ : α → Sort*} (F : ∀ a, β₁ a ≃ β₂ a) : (Π a, β₁ a) ≃ (Π a, β₂ a) := ⟨λ H a, F a (H a), λ H a, (F a).symm (H a), λ H, funext $ by simp, λ H, funext $ by simp⟩ end section def psigma_equiv_sigma {α} (β : α → Sort*) : psigma β ≃ sigma β := ⟨λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩ def sigma_congr_right {α} {β₁ β₂ : α → Sort*} (F : ∀ a, β₁ a ≃ β₂ a) : sigma β₁ ≃ sigma β₂ := ⟨λ ⟨a, b⟩, ⟨a, F a b⟩, λ ⟨a, b⟩, ⟨a, (F a).symm b⟩, λ ⟨a, b⟩, congr_arg (sigma.mk a) $ inverse_apply_apply (F a) b, λ ⟨a, b⟩, congr_arg (sigma.mk a) $ apply_inverse_apply (F a) b⟩ def sigma_congr_left {α₁ α₂} {β : α₂ → Sort*} : ∀ f : α₁ ≃ α₂, (Σ a:α₁, β (f a)) ≃ (Σ a:α₂, β a) | ⟨f, g, l, r⟩ := ⟨λ ⟨a, b⟩, ⟨f a, b⟩, λ ⟨a, b⟩, ⟨g a, @@eq.rec β b (r a).symm⟩, λ ⟨a, b⟩, match g (f a), l a : ∀ a' (h : a' = a), @sigma.mk _ (β ∘ f) _ (@@eq.rec β b (congr_arg f h.symm)) = ⟨a, b⟩ with | _, rfl := rfl end, λ ⟨a, b⟩, match f (g a), _ : ∀ a' (h : a' = a), sigma.mk a' (@@eq.rec β b h.symm) = ⟨a, b⟩ with | _, rfl := rfl end⟩ def sigma_equiv_prod (α β : Sort*) : (Σ_:α, β) ≃ (α × β) := ⟨λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩ def sigma_equiv_prod_of_equiv {α β} {β₁ : α → Sort*} (F : ∀ a, β₁ a ≃ β) : sigma β₁ ≃ (α × β) := (sigma_congr_right F).trans (sigma_equiv_prod α β) end section def arrow_prod_equiv_prod_arrow (α β γ : Type*) : (γ → α × β) ≃ ((γ → α) × (γ → β)) := ⟨λ f, (λ c, (f c).1, λ c, (f c).2), λ p c, (p.1 c, p.2 c), λ f, funext $ λ c, prod.mk.eta, λ p, by cases p; refl⟩ def arrow_arrow_equiv_prod_arrow (α β γ : Sort*) : (α → β → γ) ≃ (α × β → γ) := ⟨λ f, λ p, f p.1 p.2, λ f, λ a b, f (a, b), λ f, rfl, λ f, by funext p; cases p; refl⟩ open sum def sum_arrow_equiv_prod_arrow (α β γ : Type*) : ((α ⊕ β) → γ) ≃ ((α → γ) × (β → γ)) := ⟨λ f, (f ∘ inl, f ∘ inr), λ p s, sum.rec_on s p.1 p.2, λ f, by funext s; cases s; refl, λ p, by cases p; refl⟩ def sum_prod_distrib (α β γ : Sort*) : ((α ⊕ β) × γ) ≃ ((α × γ) ⊕ (β × γ)) := ⟨λ p, match p with (inl a, c) := inl (a, c) | (inr b, c) := inr (b, c) end, λ s, match s with inl (a, c) := (inl a, c) | inr (b, c) := (inr b, c) end, λ p, by rcases p with ⟨_ | _, _⟩; refl, λ s, by rcases s with ⟨_, _⟩ | ⟨_, _⟩; refl⟩ @[simp] theorem sum_prod_distrib_apply_left {α β γ} (a : α) (c : γ) : sum_prod_distrib α β γ (sum.inl a, c) = sum.inl (a, c) := rfl @[simp] theorem sum_prod_distrib_apply_right {α β γ} (b : β) (c : γ) : sum_prod_distrib α β γ (sum.inr b, c) = sum.inr (b, c) := rfl def prod_sum_distrib (α β γ : Sort*) : (α × (β ⊕ γ)) ≃ ((α × β) ⊕ (α × γ)) := calc (α × (β ⊕ γ)) ≃ ((β ⊕ γ) × α) : prod_comm _ _ ... ≃ ((β × α) ⊕ (γ × α)) : sum_prod_distrib _ _ _ ... ≃ ((α × β) ⊕ (α × γ)) : sum_congr (prod_comm _ _) (prod_comm _ _) @[simp] theorem prod_sum_distrib_apply_left {α β γ} (a : α) (b : β) : prod_sum_distrib α β γ (a, sum.inl b) = sum.inl (a, b) := rfl @[simp] theorem prod_sum_distrib_apply_right {α β γ} (a : α) (c : γ) : prod_sum_distrib α β γ (a, sum.inr c) = sum.inr (a, c) := rfl def bool_prod_equiv_sum (α : Type u) : (bool × α) ≃ (α ⊕ α) := calc (bool × α) ≃ ((unit ⊕ unit) × α) : prod_congr bool_equiv_unit_sum_unit (equiv.refl _) ... ≃ (α × (unit ⊕ unit)) : prod_comm _ _ ... ≃ ((α × unit) ⊕ (α × unit)) : prod_sum_distrib _ _ _ ... ≃ (α ⊕ α) : sum_congr (prod_unit _) (prod_unit _) end section open sum nat def nat_equiv_nat_sum_unit : ℕ ≃ (ℕ ⊕ unit) := ⟨λ n, match n with zero := inr () | succ a := inl a end, λ s, match s with inl n := succ n | inr () := zero end, λ n, begin cases n, repeat { refl } end, λ s, begin cases s with a u, { refl }, {cases u, { refl }} end⟩ @[simp] def nat_sum_unit_equiv_nat : (ℕ ⊕ unit) ≃ ℕ := nat_equiv_nat_sum_unit.symm @[simp] def nat_prod_nat_equiv_nat : (ℕ × ℕ) ≃ ℕ := ⟨λ p, nat.mkpair p.1 p.2, nat.unpair, λ p, begin cases p, apply nat.unpair_mkpair end, nat.mkpair_unpair⟩ @[simp] def nat_sum_bool_equiv_nat : (ℕ ⊕ bool) ≃ ℕ := calc (ℕ ⊕ bool) ≃ (ℕ ⊕ (unit ⊕ unit)) : sum_congr (equiv.refl _) bool_equiv_unit_sum_unit ... ≃ ((ℕ ⊕ unit) ⊕ unit) : (sum_assoc ℕ unit unit).symm ... ≃ (ℕ ⊕ unit) : sum_congr nat_sum_unit_equiv_nat (equiv.refl _) ... ≃ ℕ : nat_sum_unit_equiv_nat @[simp] def bool_prod_nat_equiv_nat : (bool × ℕ) ≃ ℕ := ⟨λ ⟨b, n⟩, bit b n, bodd_div2, λ ⟨b, n⟩, by simp [bool_prod_nat_equiv_nat._match_1, bodd_bit, div2_bit], λ n, by simp [bool_prod_nat_equiv_nat._match_1, bit_decomp]⟩ @[simp] def nat_sum_nat_equiv_nat : (ℕ ⊕ ℕ) ≃ ℕ := (bool_prod_equiv_sum ℕ).symm.trans bool_prod_nat_equiv_nat def int_equiv_nat_sum_nat : ℤ ≃ (ℕ ⊕ ℕ) := by refine ⟨_, _, _, _⟩; intro z; {cases z; [left, right]; assumption} <|> {cases z; refl} def int_equiv_nat : ℤ ≃ ℕ := int_equiv_nat_sum_nat.trans nat_sum_nat_equiv_nat def prod_equiv_of_equiv_nat {α : Sort*} (e : α ≃ ℕ) : (α × α) ≃ α := calc (α × α) ≃ (ℕ × ℕ) : prod_congr e e ... ≃ ℕ : nat_prod_nat_equiv_nat ... ≃ α : e.symm end def list_equiv_of_equiv {α β : Type*} : α ≃ β → list α ≃ list β | ⟨f, g, l, r⟩ := by refine ⟨list.map f, list.map g, λ x, _, λ x, _⟩; simp [id_of_left_inverse l, id_of_right_inverse r] section open nat list private def list.to_nat : list ℕ → ℕ | [] := 0 | (a::l) := succ (mkpair l.to_nat a) private def list.of_nat : ℕ → list ℕ | 0 := [] | (succ v) := match unpair v, unpair_le v with | (v₂, v₁), h := have v₂ < succ v, from lt_succ_of_le h, v₁ :: list.of_nat v₂ end private theorem list.of_nat_to_nat : ∀ l : list ℕ, list.of_nat (list.to_nat l) = l | [] := rfl | (a::l) := by simp [list.to_nat, list.of_nat, unpair_mkpair, *] private theorem list.to_nat_of_nat : ∀ n : ℕ, list.to_nat (list.of_nat n) = n | 0 := rfl | (succ v) := begin cases e : unpair v with v₁ v₂, have := lt_succ_of_le (unpair_le v), have IH := have v₁ < succ v, by rwa e at this, list.to_nat_of_nat v₁, simp [list.of_nat, e, list.to_nat, IH, mkpair_unpair' e] end def list_nat_equiv_nat : list ℕ ≃ ℕ := ⟨list.to_nat, list.of_nat, list.of_nat_to_nat, list.to_nat_of_nat⟩ def list_equiv_self_of_equiv_nat {α : Type} (e : α ≃ ℕ) : list α ≃ α := calc list α ≃ list ℕ : list_equiv_of_equiv e ... ≃ ℕ : list_nat_equiv_nat ... ≃ α : e.symm end section def decidable_eq_of_equiv [h : decidable_eq α] : α ≃ β → decidable_eq β | ⟨f, g, l, r⟩ b₁ b₂ := match h (g b₁) (g b₂) with | (is_true he) := is_true $ have f (g b₁) = f (g b₂), from congr_arg f he, by rwa [r, r] at this | (is_false hn) := is_false $ λeq, hn.elim $ by rw [eq] end end def inhabited_of_equiv [inhabited α] : α ≃ β → inhabited β | ⟨f, g, l, r⟩ := ⟨f (default _)⟩ section open subtype def subtype_equiv_of_subtype {p : α → Prop} : Π (e : α ≃ β), {a : α // p a} ≃ {b : β // p (e.symm b)} | ⟨f, g, l, r⟩ := ⟨subtype.map f $ assume a ha, show p (g (f a)), by rwa [l], subtype.map g $ assume a ha, ha, assume p, by simp [map_comp, l.f_g_eq_id]; rw [map_id]; refl, assume p, by simp [map_comp, r.f_g_eq_id]; rw [map_id]; refl⟩ def subtype_subtype_equiv_subtype {α : Type u} (p : α → Prop) (q : subtype p → Prop) : subtype q ≃ {a : α // ∃h:p a, q ⟨a, h⟩ } := ⟨λ⟨⟨a, ha⟩, ha'⟩, ⟨a, ha, ha'⟩, λ⟨a, ha⟩, ⟨⟨a, ha.cases_on $ assume h _, h⟩, by cases ha; exact ha_h⟩, assume ⟨⟨a, ha⟩, h⟩, rfl, assume ⟨a, h₁, h₂⟩, rfl⟩ end namespace set open set protected def univ (α) : @univ α ≃ α := ⟨subtype.val, λ a, ⟨a, trivial⟩, λ ⟨a, _⟩, rfl, λ a, rfl⟩ protected def empty (α) : (∅ : set α) ≃ empty := equiv_empty $ λ ⟨x, h⟩, not_mem_empty x h protected def union {α} {s t : set α} [decidable_pred s] (H : s ∩ t = ∅) : (s ∪ t : set α) ≃ (s ⊕ t) := ⟨λ ⟨x, h⟩, if hs : x ∈ s then sum.inl ⟨_, hs⟩ else sum.inr ⟨_, h.resolve_left hs⟩, λ o, match o with | (sum.inl ⟨x, h⟩) := ⟨x, or.inl h⟩ | (sum.inr ⟨x, h⟩) := ⟨x, or.inr h⟩ end, λ ⟨x, h'⟩, by by_cases x ∈ s; simp [union._match_1, union._match_2, h]; congr, λ o, by rcases o with ⟨x, h⟩ | ⟨x, h⟩; simp [union._match_1, union._match_2, h]; simp [show x ∉ s, from λ h', eq_empty_iff_forall_not_mem.1 H _ ⟨h', h⟩]⟩ protected def singleton {α} (a : α) : ({a} : set α) ≃ unit := ⟨λ _, (), λ _, ⟨a, mem_singleton _⟩, λ ⟨x, h⟩, by simp at h; subst x, λ ⟨⟩, rfl⟩ protected def insert {α} {s : set.{u} α} [decidable_pred s] {a : α} (H : a ∉ s) : (insert a s : set α) ≃ (s ⊕ unit) := by rw ← union_singleton; exact (set.union $ inter_singleton_eq_empty.2 H).trans (sum_congr (equiv.refl _) (set.singleton _)) protected def sum_compl {α} (s : set α) [decidable_pred s] : (s ⊕ (-s : set α)) ≃ α := (set.union (inter_compl_self _)).symm.trans (by rw union_compl_self; exact set.univ _) protected def prod {α β} (s : set α) (t : set β) : (s.prod t) ≃ (s × t) := ⟨λ ⟨⟨x, y⟩, ⟨h₁, h₂⟩⟩, ⟨⟨x, h₁⟩, ⟨y, h₂⟩⟩, λ ⟨⟨x, h₁⟩, ⟨y, h₂⟩⟩, ⟨⟨x, y⟩, ⟨h₁, h₂⟩⟩, λ ⟨⟨x, y⟩, ⟨h₁, h₂⟩⟩, rfl, λ ⟨⟨x, h₁⟩, ⟨y, h₂⟩⟩, rfl⟩ protected noncomputable def image {α β} (f : α → β) (s : set α) (H : injective f) : s ≃ (f '' s) := ⟨λ ⟨x, h⟩, ⟨f x, mem_image_of_mem _ h⟩, λ ⟨y, h⟩, ⟨classical.some h, (classical.some_spec h).1⟩, λ ⟨x, h⟩, subtype.eq (H (classical.some_spec (mem_image_of_mem f h)).2), λ ⟨y, h⟩, subtype.eq (classical.some_spec h).2⟩ @[simp] theorem image_apply {α β} (f : α → β) (s : set α) (H : injective f) (a h) : set.image f s H ⟨a, h⟩ = ⟨f a, mem_image_of_mem _ h⟩ := rfl protected noncomputable def range {α β} (f : α → β) (H : injective f) : α ≃ range f := (set.univ _).symm.trans $ (set.image f univ H).trans (equiv.cast $ by rw image_univ) @[simp] theorem range_apply {α β} (f : α → β) (H : injective f) (a) : set.range f H a = ⟨f a, set.mem_range_self _⟩ := by dunfold equiv.set.range equiv.set.univ; simp [set_coe_cast, -image_univ, image_univ.symm] end set noncomputable def of_bijective {α β} {f : α → β} (hf : bijective f) : α ≃ β := begin have hg := bijective_comp equiv.plift.symm.bijective (bijective_comp hf equiv.plift.bijective), refine equiv.plift.symm.trans (equiv.trans _ equiv.plift), exact (set.range _ hg.1).trans ((equiv.cast (by rw set.range_iff_surjective.2 hg.2)).trans (set.univ _)) end @[simp] theorem of_bijective_to_fun {α β} {f : α → β} (hf : bijective f) : (of_bijective hf : α → β) = f := begin funext a, dunfold of_bijective equiv.set.univ, have hg := bijective_comp equiv.plift.symm.bijective (bijective_comp hf equiv.plift.bijective), simp [set.set_coe_cast, (∘), set.range_iff_surjective.2 hg.2], end section open set set_option eqn_compiler.zeta true noncomputable def set.bUnion_eq_sigma_of_disjoint {α β} {s : set α} {t : α → set β} (h : pairwise_on s (disjoint on t)) : (⋃i∈s, t i) ≃ (Σi:s, t i.val) := let f : (Σi:s, t i.val) → (⋃i∈s, t i) := λ⟨⟨a, ha⟩, ⟨b, hb⟩⟩, ⟨b, mem_bUnion ha hb⟩ in have injective f, from assume ⟨⟨a₁, ha₁⟩, ⟨b₁, hb₁⟩⟩ ⟨⟨a₂, ha₂⟩, ⟨b₂, hb₂⟩⟩ eq, have b_eq : b₁ = b₂, from congr_arg subtype.val eq, have a_eq : a₁ = a₂, from classical.by_contradiction $ assume ne, have b₁ ∈ t a₁ ∩ t a₂, from ⟨hb₁, b_eq.symm ▸ hb₂⟩, have t a₁ ∩ t a₂ ≠ ∅, from ne_empty_of_mem this, this $ h _ ha₁ _ ha₂ ne, sigma.eq (subtype.eq a_eq) (subtype.eq $ by subst b_eq; subst a_eq), have surjective f, from assume ⟨b, hb⟩, have ∃a∈s, b ∈ t a, by simpa using hb, let ⟨a, ha, hb⟩ := this in ⟨⟨⟨a, ha⟩, ⟨b, hb⟩⟩, rfl⟩, (equiv.of_bijective ⟨‹injective f›, ‹surjective f›⟩).symm end section swap variable [decidable_eq α] open decidable def swap_core (a b r : α) : α := if r = a then b else if r = b then a else r theorem swap_core_self (r a : α) : swap_core a a r = r := by by_cases r = a; simp [swap_core, *] theorem swap_core_swap_core (r a b : α) : swap_core a b (swap_core a b r) = r := begin by_cases hb : r = b, { by_cases ha : r = a, { simp [hb.symm, ha.symm, swap_core_self] }, { have : b ≠ a, by rwa [hb] at ha, simp [swap_core, *] } }, { by_cases ha : r = a, { have : b ≠ a, begin rw [ha] at hb, exact ne.symm hb end, simp [swap_core, *] }, simp [swap_core, *] } end theorem swap_core_comm (r a b : α) : swap_core a b r = swap_core b a r := begin by_cases hb : r = b, { by_cases ha : r = a, { simp [hb.symm, ha.symm, swap_core_self] }, { have : b ≠ a, by rwa [hb] at ha, simp [swap_core, *] } }, { by_cases ha : r = a, { have : a ≠ b, by rwa [ha] at hb, simp [swap_core, *] }, simp [swap_core, *] } end /-- `swap a b` is the permutation that swaps `a` and `b` and leaves other values as is. -/ def swap (a b : α) : perm α := ⟨swap_core a b, swap_core a b, λr, swap_core_swap_core r a b, λr, swap_core_swap_core r a b⟩ theorem swap_self (a : α) : swap a a = equiv.refl _ := eq_of_to_fun_eq $ funext $ λ r, swap_core_self r a theorem swap_comm (a b : α) : swap a b = swap b a := eq_of_to_fun_eq $ funext $ λ r, swap_core_comm r _ _ theorem swap_apply_def (a b x : α) : swap a b x = if x = a then b else if x = b then a else x := rfl theorem swap_apply_left (a b : α) : swap a b a = b := if_pos rfl theorem swap_apply_right (a b : α) : swap a b b = a := by by_cases b = a; simp [swap_apply_def, *] theorem swap_apply_of_ne_of_ne {a b x : α} : x ≠ a → x ≠ b → swap a b x = x := by simp [swap_apply_def] {contextual := tt} theorem swap_swap (a b : α) : (swap a b).trans (swap a b) = equiv.refl _ := eq_of_to_fun_eq $ funext $ λ x, swap_core_swap_core _ _ _ theorem swap_comp_apply {a b x : α} (π : perm α) : π.trans (swap a b) x = if π x = a then b else if π x = b then a else π x := by cases π; refl end swap end equiv instance {α} [subsingleton α] : subsingleton (ulift α) := equiv.ulift.subsingleton instance {α} [subsingleton α] : subsingleton (plift α) := equiv.plift.subsingleton instance {α} [decidable_eq α] : decidable_eq (ulift α) := equiv.ulift.decidable_eq instance {α} [decidable_eq α] : decidable_eq (plift α) := equiv.plift.decidable_eq
886e26b0c12865e0b05f2d407c01ee8871c2a8d0
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Meta/SynthInstance.lean
cac95fde45173722e2cf829c7675353ebe57293d
[ "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
34,745
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Daniel Selsam, Leonardo de Moura Type class instance synthesizer using tabled resolution. -/ import Lean.Meta.Basic import Lean.Meta.Instances import Lean.Meta.AbstractMVars import Lean.Meta.WHNF import Lean.Meta.Check import Lean.Util.Profile namespace Lean.Meta register_builtin_option synthInstance.maxHeartbeats : Nat := { defValue := 20000 descr := "maximum amount of heartbeats per typeclass resolution problem. A heartbeat is number of (small) memory allocations (in thousands), 0 means no limit" } register_builtin_option synthInstance.maxSize : Nat := { defValue := 128 descr := "maximum number of instances used to construct a solution in the type class instance synthesis procedure" } namespace SynthInstance def getMaxHeartbeats (opts : Options) : Nat := synthInstance.maxHeartbeats.get opts * 1000 open Std (HashMap) builtin_initialize inferTCGoalsRLAttr : TagAttribute ← registerTagAttribute `inferTCGoalsRL "instruct type class resolution procedure to solve goals from right to left for this instance" def hasInferTCGoalsRLAttribute (env : Environment) (constName : Name) : Bool := inferTCGoalsRLAttr.hasTag env constName structure GeneratorNode where mvar : Expr key : Expr mctx : MetavarContext instances : Array Expr currInstanceIdx : Nat deriving Inhabited structure ConsumerNode where mvar : Expr key : Expr mctx : MetavarContext subgoals : List Expr size : Nat -- instance size so far deriving Inhabited inductive Waiter where | consumerNode : ConsumerNode → Waiter | root : Waiter def Waiter.isRoot : Waiter → Bool | Waiter.consumerNode _ => false | Waiter.root => true /-! In tabled resolution, we creating a mapping from goals (e.g., `Coe Nat ?x`) to answers and waiters. Waiters are consumer nodes that are waiting for answers for a particular node. We implement this mapping using a `HashMap` where the keys are normalized expressions. That is, we replace assignable metavariables with auxiliary free variables of the form `_tc.<idx>`. We do not declare these free variables in any local context, and we should view them as "normalized names" for metavariables. For example, the term `f ?m ?m ?n` is normalized as `f _tc.0 _tc.0 _tc.1`. This approach is structural, and we may visit the same goal more than once if the different occurrences are just definitionally equal, but not structurally equal. Remark: a metavariable is assignable only if its depth is equal to the metavar context depth. -/ namespace MkTableKey structure State where nextIdx : Nat := 0 lmap : HashMap LMVarId Level := {} emap : HashMap MVarId Expr := {} mctx : MetavarContext abbrev M := StateM State instance : MonadMCtx M where getMCtx := return (← get).mctx modifyMCtx f := modify fun s => { s with mctx := f s.mctx } partial def normLevel (u : Level) : M Level := do if !u.hasMVar then return u else match u with | Level.succ v => return u.updateSucc! (← normLevel v) | Level.max v w => return u.updateMax! (← normLevel v) (← normLevel w) | Level.imax v w => return u.updateIMax! (← normLevel v) (← normLevel w) | Level.mvar mvarId => if !(← isLevelMVarAssignable mvarId) then return u else let s ← get match (← get).lmap.find? mvarId with | some u' => pure u' | none => let u' := mkLevelParam <| Name.mkNum `_tc s.nextIdx modify fun s => { s with nextIdx := s.nextIdx + 1, lmap := s.lmap.insert mvarId u' } return u' | u => return u partial def normExpr (e : Expr) : M Expr := do if !e.hasMVar then pure e else match e with | Expr.const _ us => return e.updateConst! (← us.mapM normLevel) | Expr.sort u => return e.updateSort! (← normLevel u) | Expr.app f a => return e.updateApp! (← normExpr f) (← normExpr a) | Expr.letE _ t v b _ => return e.updateLet! (← normExpr t) (← normExpr v) (← normExpr b) | Expr.forallE _ d b _ => return e.updateForallE! (← normExpr d) (← normExpr b) | Expr.lam _ d b _ => return e.updateLambdaE! (← normExpr d) (← normExpr b) | Expr.mdata _ b => return e.updateMData! (← normExpr b) | Expr.proj _ _ b => return e.updateProj! (← normExpr b) | Expr.mvar mvarId => if !(← mvarId.isAssignable) then return e else let s ← get match s.emap.find? mvarId with | some e' => pure e' | none => do let e' := mkFVar { name := Name.mkNum `_tc s.nextIdx } modify fun s => { s with nextIdx := s.nextIdx + 1, emap := s.emap.insert mvarId e' } return e' | _ => return e end MkTableKey /-- Remark: `mkTableKey` assumes `e` does not contain assigned metavariables. -/ def mkTableKey [Monad m] [MonadMCtx m] (e : Expr) : m Expr := do let (r, s) := MkTableKey.normExpr e |>.run { mctx := (← getMCtx) } setMCtx s.mctx return r structure Answer where result : AbstractMVarsResult resultType : Expr size : Nat deriving Inhabited structure TableEntry where waiters : Array Waiter answers : Array Answer := #[] structure Context where maxResultSize : Nat maxHeartbeats : Nat /-- Remark: the SynthInstance.State is not really an extension of `Meta.State`. The field `postponed` is not needed, and the field `mctx` is misleading since `synthInstance` methods operate over different `MetavarContext`s simultaneously. That being said, we still use `extends` because it makes it simpler to move from `M` to `MetaM`. -/ structure State where result? : Option AbstractMVarsResult := none generatorStack : Array GeneratorNode := #[] resumeStack : Array (ConsumerNode × Answer) := #[] tableEntries : HashMap Expr TableEntry := {} abbrev SynthM := ReaderT Context $ StateRefT State MetaM def checkMaxHeartbeats : SynthM Unit := do Core.checkMaxHeartbeatsCore "typeclass" `synthInstance.maxHeartbeats (← read).maxHeartbeats @[inline] def mapMetaM (f : forall {α}, MetaM α → MetaM α) {α} : SynthM α → SynthM α := monadMap @f instance : Inhabited (SynthM α) where default := fun _ _ => default /-- Return globals and locals instances that may unify with `type` -/ def getInstances (type : Expr) : MetaM (Array Expr) := do -- We must retrieve `localInstances` before we use `forallTelescopeReducing` because it will update the set of local instances let localInstances ← getLocalInstances forallTelescopeReducing type fun _ type => do let className? ← isClass? type match className? with | none => throwError "type class instance expected{indentExpr type}" | some className => let globalInstances ← getGlobalInstancesIndex let result ← globalInstances.getUnify type -- Using insertion sort because it is stable and the array `result` should be mostly sorted. -- Most instances have default priority. let result := result.insertionSort fun e₁ e₂ => e₁.priority < e₂.priority let erasedInstances ← getErasedInstances let result ← result.filterMapM fun e => match e.val with | Expr.const constName us => if erasedInstances.contains constName then return none else return some <| e.val.updateConst! (← us.mapM (fun _ => mkFreshLevelMVar)) | _ => panic! "global instance is not a constant" trace[Meta.synthInstance.globalInstances] "{type}, {result}" let result := localInstances.foldl (init := result) fun (result : Array Expr) linst => if linst.className == className then result.push linst.fvar else result return result def mkGeneratorNode? (key mvar : Expr) : MetaM (Option GeneratorNode) := do let mvarType ← inferType mvar let mvarType ← instantiateMVars mvarType let instances ← getInstances mvarType if instances.isEmpty then return none else let mctx ← getMCtx return some { mvar, key, mctx, instances currInstanceIdx := instances.size } /-- Create a new generator node for `mvar` and add `waiter` as its waiter. `key` must be `mkTableKey mctx mvarType`. -/ def newSubgoal (mctx : MetavarContext) (key : Expr) (mvar : Expr) (waiter : Waiter) : SynthM Unit := withMCtx mctx do trace[Meta.synthInstance.newSubgoal] key match (← mkGeneratorNode? key mvar) with | none => pure () | some node => let entry : TableEntry := { waiters := #[waiter] } modify fun s => { s with generatorStack := s.generatorStack.push node tableEntries := s.tableEntries.insert key entry } def findEntry? (key : Expr) : SynthM (Option TableEntry) := do return (← get).tableEntries.find? key def getEntry (key : Expr) : SynthM TableEntry := do match (← findEntry? key) with | none => panic! "invalid key at synthInstance" | some entry => pure entry /-- Create a `key` for the goal associated with the given metavariable. That is, we create a key for the type of the metavariable. We must instantiate assigned metavariables before we invoke `mkTableKey`. -/ def mkTableKeyFor (mctx : MetavarContext) (mvar : Expr) : SynthM Expr := withMCtx mctx do let mvarType ← inferType mvar let mvarType ← instantiateMVars mvarType mkTableKey mvarType /-- See `getSubgoals` and `getSubgoalsAux` We use the parameter `j` to reduce the number of `instantiate*` invocations. It is the same approach we use at `forallTelescope` and `lambdaTelescope`. Given `getSubgoalsAux args j subgoals instVal type`, we have that `type.instantiateRevRange j args.size args` does not have loose bound variables. -/ structure SubgoalsResult where subgoals : List Expr instVal : Expr instTypeBody : Expr private partial def getSubgoalsAux (lctx : LocalContext) (localInsts : LocalInstances) (xs : Array Expr) : Array Expr → Nat → List Expr → Expr → Expr → MetaM SubgoalsResult | args, j, subgoals, instVal, Expr.forallE _ d b bi => do let d := d.instantiateRevRange j args.size args let mvarType ← mkForallFVars xs d let mvar ← mkFreshExprMVarAt lctx localInsts mvarType let arg := mkAppN mvar xs let instVal := mkApp instVal arg let subgoals := if bi.isInstImplicit then mvar::subgoals else subgoals let args := args.push (mkAppN mvar xs) getSubgoalsAux lctx localInsts xs args j subgoals instVal b | args, j, subgoals, instVal, type => do let type := type.instantiateRevRange j args.size args let type ← whnf type if type.isForall then getSubgoalsAux lctx localInsts xs args args.size subgoals instVal type else return ⟨subgoals, instVal, type⟩ /-- `getSubgoals lctx localInsts xs inst` creates the subgoals for the instance `inst`. The subgoals are in the context of the free variables `xs`, and `(lctx, localInsts)` is the local context and instances before we added the free variables to it. This extra complication is required because 1- We want all metavariables created by `synthInstance` to share the same local context. 2- We want to ensure that applications such as `mvar xs` are higher order patterns. The method `getGoals` create a new metavariable for each parameter of `inst`. For example, suppose the type of `inst` is `forall (x_1 : A_1) ... (x_n : A_n), B x_1 ... x_n`. Then, we create the metavariables `?m_i : forall xs, A_i`, and return the subset of these metavariables that are instance implicit arguments, and the expressions: - `inst (?m_1 xs) ... (?m_n xs)` (aka `instVal`) - `B (?m_1 xs) ... (?m_n xs)` -/ def getSubgoals (lctx : LocalContext) (localInsts : LocalInstances) (xs : Array Expr) (inst : Expr) : MetaM SubgoalsResult := do let instType ← inferType inst let result ← getSubgoalsAux lctx localInsts xs #[] 0 [] inst instType match inst.getAppFn with | Expr.const constName _ => let env ← getEnv if hasInferTCGoalsRLAttribute env constName then return result else return { result with subgoals := result.subgoals.reverse } | _ => return result def tryResolveCore (mvar : Expr) (inst : Expr) : MetaM (Option (MetavarContext × List Expr)) := do let mvar ← instantiateMVars mvar if !(← hasAssignableMVar mvar) then /- The metavariable `mvar` may have been assinged when solving typing constraints. This may happen when a local instance type depends on other local instances. For example, in Mathlib, we have ``` @Submodule.setLike : {R : Type u_1} → {M : Type u_2} → [_inst_1 : Semiring R] → [_inst_2 : AddCommMonoid M] → [_inst_3 : @ModuleS R M _inst_1 _inst_2] → SetLike (@Submodule R M _inst_1 _inst_2 _inst_3) M ``` TODO: discuss what is the correct behavior here. There are other possibilities. 1) We could try to synthesize the instances `_inst_1` and `_inst_2` and check whether it is defeq to the one inferred by typing constraints. That is, we remove this `if`-statement. We discarded this one because some Mathlib theorems failed to be elaborated using it. 2) Generate an error/warning message when instances such as `Submodule.setLike` are declared, and instruct user to use `{}` binder annotation for `_inst_1` `_inst_2`. -/ return some ((← getMCtx), []) let mvarType ← inferType mvar let lctx ← getLCtx let localInsts ← getLocalInstances forallTelescopeReducing mvarType fun xs mvarTypeBody => do let ⟨subgoals, instVal, instTypeBody⟩ ← getSubgoals lctx localInsts xs inst trace[Meta.synthInstance.tryResolve] "{mvarTypeBody} =?= {instTypeBody}" if (← isDefEq mvarTypeBody instTypeBody) then let instVal ← mkLambdaFVars xs instVal if (← isDefEq mvar instVal) then trace[Meta.synthInstance.tryResolve] "success" return some ((← getMCtx), subgoals) else trace[Meta.synthInstance.tryResolve] "failure assigning" return none else trace[Meta.synthInstance.tryResolve] "failure" return none /-- Try to synthesize metavariable `mvar` using the instance `inst`. Remark: `mctx` contains `mvar`. If it succeeds, the result is a new updated metavariable context and a new list of subgoals. A subgoal is created for each instance implicit parameter of `inst`. -/ def tryResolve (mctx : MetavarContext) (mvar : Expr) (inst : Expr) : SynthM (Option (MetavarContext × List Expr)) := traceCtx `Meta.synthInstance.tryResolve <| withMCtx mctx <| tryResolveCore mvar inst /-- Assign a precomputed answer to `mvar`. If it succeeds, the result is a new updated metavariable context and a new list of subgoals. -/ def tryAnswer (mctx : MetavarContext) (mvar : Expr) (answer : Answer) : SynthM (Option MetavarContext) := withMCtx mctx do let (_, _, val) ← openAbstractMVarsResult answer.result if (← isDefEq mvar val) then return some (← getMCtx) else return none /-- Move waiters that are waiting for the given answer to the resume stack. -/ def wakeUp (answer : Answer) : Waiter → SynthM Unit | Waiter.root => do /- Recall that we now use `ignoreLevelMVarDepth := true`. Thus, we should allow solutions containing universe metavariables, and not check `answer.result.paramNames.isEmpty`. We use `openAbstractMVarsResult` to construct the universe metavariables at the correct depth. -/ if answer.result.numMVars == 0 then modify fun s => { s with result? := answer.result } else let (_, _, answerExpr) ← openAbstractMVarsResult answer.result trace[Meta.synthInstance] "skip answer containing metavariables {answerExpr}" | Waiter.consumerNode cNode => modify fun s => { s with resumeStack := s.resumeStack.push (cNode, answer) } def isNewAnswer (oldAnswers : Array Answer) (answer : Answer) : Bool := oldAnswers.all fun oldAnswer => -- Remark: isDefEq here is too expensive. TODO: if `==` is too imprecise, add some light normalization to `resultType` at `addAnswer` -- iseq ← isDefEq oldAnswer.resultType answer.resultType; pure (!iseq) oldAnswer.resultType != answer.resultType private def mkAnswer (cNode : ConsumerNode) : MetaM Answer := withMCtx cNode.mctx do traceM `Meta.synthInstance.newAnswer do pure m!"size: {cNode.size}, {← inferType cNode.mvar}" let val ← instantiateMVars cNode.mvar trace[Meta.synthInstance.newAnswer] "val: {val}" let result ← abstractMVars val -- assignable metavariables become parameters let resultType ← inferType result.expr return { result, resultType, size := cNode.size + 1 } /-- Create a new answer after `cNode` resolved all subgoals. That is, `cNode.subgoals == []`. And then, store it in the tabled entries map, and wakeup waiters. -/ def addAnswer (cNode : ConsumerNode) : SynthM Unit := do if cNode.size ≥ (← read).maxResultSize then traceM `Meta.synthInstance.discarded do withMCtx cNode.mctx do pure m!"size: {cNode.size} ≥ {(← read).maxResultSize}, {← inferType cNode.mvar}" return () else let answer ← mkAnswer cNode -- Remark: `answer` does not contain assignable or assigned metavariables. let key := cNode.key let entry ← getEntry key if isNewAnswer entry.answers answer then let newEntry := { entry with answers := entry.answers.push answer } modify fun s => { s with tableEntries := s.tableEntries.insert key newEntry } entry.waiters.forM (wakeUp answer) /-- Return `true` if a type of the form `(a_1 : A_1) → ... → (a_n : A_n) → B` has an unused argument `a_i`. Remark: This is syntactic check and no reduction is performed. -/ private def hasUnusedArguments : Expr → Bool | Expr.forallE _ _ b _ => !b.hasLooseBVar 0 || hasUnusedArguments b | _ => false /-- If the type of the metavariable `mvar` has unused argument, return a pair `(α, transformer)` where `α` is a new type without the unused arguments and the `transformer` is a function for coverting a solution with type `α` into a value that can be assigned to `mvar`. Example: suppose `mvar` has type `(a : A) → (b : B a) → (c : C a) → D a c`, the result is the pair ``` ((a : A) → (c : C a) → D a c, fun (f : (a : A) → (c : C a) → D a c) (a : A) (b : B a) (c : C a) => f a c ) ``` This method is used to improve the effectiveness of the TC resolution procedure. It was suggested and prototyped by Tomas Skrivan. It improves the support for instances of type `a : A → C` where `a` does not appear in class `C`. When we look for such an instance it is enough to look for an instance `c : C` and then return `fun _ => c`. Tomas' approach makes sure that instance of a type like `a : A → C` never gets tabled/cached. More on that later. At the core is the this methos. it takes an expression E and does two things: The modification to TC resolution works this way: We are looking for an instance of `E`, if it is tabled just get it as normal, but if not first remove all unused arguments producing `E'`. Now we look up the table again but for `E'`. If it exists, use the transforme to create E. If it does not exists, create a new goal `E'`. -/ private def removeUnusedArguments? (mctx : MetavarContext) (mvar : Expr) : MetaM (Option (Expr × Expr)) := withMCtx mctx do let mvarType ← instantiateMVars (← inferType mvar) if !hasUnusedArguments mvarType then return none else forallTelescope mvarType fun xs body => do let ys ← xs.foldrM (init := []) fun x ys => do if body.containsFVar x.fvarId! then return x :: ys else if (← ys.anyM fun y => return (← inferType y).containsFVar x.fvarId!) then return x :: ys else return ys let ys := ys.toArray let mvarType' ← mkForallFVars ys body withLocalDeclD `redf mvarType' fun f => do let transformer ← mkLambdaFVars #[f] (← mkLambdaFVars xs (mkAppN f ys)) trace[Meta.synthInstance.unusedArgs] "{mvarType}\nhas unused arguments, reduced type{indentExpr mvarType'}\nTransformer{indentExpr transformer}" return some (mvarType', transformer) /-- Process the next subgoal in the given consumer node. -/ def consume (cNode : ConsumerNode) : SynthM Unit := do match cNode.subgoals with | [] => addAnswer cNode | mvar::_ => let waiter := Waiter.consumerNode cNode let key ← mkTableKeyFor cNode.mctx mvar let entry? ← findEntry? key match entry? with | none => -- Remove unused arguments and try again, see comment at `removeUnusedArguments?` match (← removeUnusedArguments? cNode.mctx mvar) with | none => newSubgoal cNode.mctx key mvar waiter | some (mvarType', transformer) => let key' ← withMCtx cNode.mctx <| mkTableKey mvarType' match (← findEntry? key') with | none => let (mctx', mvar') ← withMCtx cNode.mctx do let mvar' ← mkFreshExprMVar mvarType' return (← getMCtx, mvar') newSubgoal mctx' key' mvar' (Waiter.consumerNode { cNode with mctx := mctx', subgoals := mvar'::cNode.subgoals }) | some entry' => let answers' ← entry'.answers.mapM fun a => withMCtx cNode.mctx do let trAnswr := Expr.betaRev transformer #[← instantiateMVars a.result.expr] let trAnswrType ← inferType trAnswr pure { a with result.expr := trAnswr, resultType := trAnswrType } modify fun s => { s with resumeStack := answers'.foldl (fun s answer => s.push (cNode, answer)) s.resumeStack, tableEntries := s.tableEntries.insert key' { entry' with waiters := entry'.waiters.push waiter } } | some entry => modify fun s => { s with resumeStack := entry.answers.foldl (fun s answer => s.push (cNode, answer)) s.resumeStack, tableEntries := s.tableEntries.insert key { entry with waiters := entry.waiters.push waiter } } def getTop : SynthM GeneratorNode := return (← get).generatorStack.back @[inline] def modifyTop (f : GeneratorNode → GeneratorNode) : SynthM Unit := modify fun s => { s with generatorStack := s.generatorStack.modify (s.generatorStack.size - 1) f } /-- Try the next instance in the node on the top of the generator stack. -/ def generate : SynthM Unit := do let gNode ← getTop if gNode.currInstanceIdx == 0 then modify fun s => { s with generatorStack := s.generatorStack.pop } else let key := gNode.key let idx := gNode.currInstanceIdx - 1 let inst := gNode.instances.get! idx let mctx := gNode.mctx let mvar := gNode.mvar trace[Meta.synthInstance.generate] "instance {inst}" modifyTop fun gNode => { gNode with currInstanceIdx := idx } match (← tryResolve mctx mvar inst) with | none => return () | some (mctx, subgoals) => consume { key, mvar, subgoals, mctx, size := 0 } def getNextToResume : SynthM (ConsumerNode × Answer) := do let r := (← get).resumeStack.back modify fun s => { s with resumeStack := s.resumeStack.pop } return r /-- Given `(cNode, answer)` on the top of the resume stack, continue execution by using `answer` to solve the next subgoal. -/ def resume : SynthM Unit := do let (cNode, answer) ← getNextToResume match cNode.subgoals with | [] => panic! "resume found no remaining subgoals" | mvar::rest => match (← tryAnswer cNode.mctx mvar answer) with | none => return () | some mctx => withMCtx mctx <| traceM `Meta.synthInstance.resume do let goal ← inferType cNode.mvar let subgoal ← inferType mvar return m!"size: {cNode.size + answer.size}, {goal} <== {subgoal}" consume { key := cNode.key, mvar := cNode.mvar, subgoals := rest, mctx, size := cNode.size + answer.size } def step : SynthM Bool := do checkMaxHeartbeats let s ← get if !s.resumeStack.isEmpty then resume return true else if !s.generatorStack.isEmpty then generate return true else return false def getResult : SynthM (Option AbstractMVarsResult) := return (← get).result? partial def synth : SynthM (Option AbstractMVarsResult) := do if (← step) then match (← getResult) with | none => synth | some result => return result else trace[Meta.synthInstance] "failed" return none def main (type : Expr) (maxResultSize : Nat) : MetaM (Option AbstractMVarsResult) := withCurrHeartbeats <| traceCtx `Meta.synthInstance do trace[Meta.synthInstance] "main goal {type}" let mvar ← mkFreshExprMVar type let key ← mkTableKey type let action : SynthM (Option AbstractMVarsResult) := do newSubgoal (← getMCtx) key mvar Waiter.root synth try action.run { maxResultSize := maxResultSize, maxHeartbeats := getMaxHeartbeats (← getOptions) } |>.run' {} catch ex => if ex.isMaxHeartbeat then throwError "failed to synthesize{indentExpr type}\n{ex.toMessageData}" else throw ex end SynthInstance /-! Type class parameters can be annotated with `outParam` annotations. Given `C a_1 ... a_n`, we replace `a_i` with a fresh metavariable `?m_i` IF `a_i` is an `outParam`. The result is type correct because we reject type class declarations IF it contains a regular parameter X that depends on an `out` parameter Y. Then, we execute type class resolution as usual. If it succeeds, and metavariables ?m_i have been assigned, we try to unify the original type `C a_1 ... a_n` witht the normalized one. -/ private def preprocess (type : Expr) : MetaM Expr := forallTelescopeReducing type fun xs type => do let type ← whnf type mkForallFVars xs type private def preprocessLevels (us : List Level) : MetaM (List Level × Bool) := do let mut r := #[] let mut modified := false for u in us do let u ← instantiateLevelMVars u if u.hasMVar then r := r.push (← mkFreshLevelMVar) modified := true else r := r.push u return (r.toList, modified) private partial def preprocessArgs (type : Expr) (i : Nat) (args : Array Expr) : MetaM (Array Expr) := do if h : i < args.size then let type ← whnf type match type with | Expr.forallE _ d b _ => do let arg := args.get ⟨i, h⟩ let arg ← if d.isOutParam then mkFreshExprMVar d else pure arg let args := args.set ⟨i, h⟩ arg preprocessArgs (b.instantiate1 arg) (i+1) args | _ => throwError "type class resolution failed, insufficient number of arguments" -- TODO improve error message else return args private def preprocessOutParam (type : Expr) : MetaM Expr := forallTelescope type fun xs typeBody => do match typeBody.getAppFn with | c@(Expr.const constName _) => let env ← getEnv if !hasOutParams env constName then return type else let args := typeBody.getAppArgs let cType ← inferType c let args ← preprocessArgs cType 0 args mkForallFVars xs (mkAppN c args) | _ => return type /-! Remark: when `maxResultSize? == none`, the configuration option `synthInstance.maxResultSize` is used. Remark: we use a different option for controlling the maximum result size for coercions. -/ def synthInstance? (type : Expr) (maxResultSize? : Option Nat := none) : MetaM (Option Expr) := do profileitM Exception "typeclass inference" (← getOptions) do let opts ← getOptions let maxResultSize := maxResultSize?.getD (synthInstance.maxSize.get opts) /- We disable eta for structures that are not classes during TC resolution because it allows us to find unintended solutions. See discussion at https://leanprover.zulipchat.com/#narrow/stream/270676-lean4/topic/.60constructor.60.20and.20.60Applicative.60/near/279984801 -/ withConfig (fun config => { config with isDefEqStuckEx := true, transparency := TransparencyMode.instances, foApprox := true, ctxApprox := true, constApprox := false, ignoreLevelMVarDepth := true, etaStruct := .notClasses }) do let type ← instantiateMVars type let type ← preprocess type let s ← get match s.cache.synthInstance.find? type with | some result => pure result | none => let result? ← withNewMCtxDepth do let normType ← preprocessOutParam type trace[Meta.synthInstance] "preprocess: {type} ==> {normType}" SynthInstance.main normType maxResultSize let resultHasUnivMVars := if let some result := result? then !result.paramNames.isEmpty else false let result? ← match result? with | none => pure none | some result => do let (_, _, result) ← openAbstractMVarsResult result trace[Meta.synthInstance] "result {result}" let resultType ← inferType result /- Output parameters of local instances may be marked as `syntheticOpaque` by the application-elaborator. We use `withAssignableSyntheticOpaque` to make sure this kind of parameter can be assigned by the following `isDefEq`. TODO: rewrite this check to avoid `withAssignableSyntheticOpaque`. -/ if (← withDefault <| withAssignableSyntheticOpaque <| isDefEq type resultType) then let result ← instantiateMVars result /- We use `check` to propogate universe constraints implied by the `result`. Recall that we use `ignoreLevelMVarDepth := true` which allows universe metavariables in the current depth to be assigned, but these assignments are discarded by `withNewMCtxDepth`. TODO: If this `check` is a performance bottleneck, we can improve performance by tracking whether a universe metavariable from previous universe levels have been assigned or not during TC resolution. We only need to perform the `check` if this kind of assignment have been performed. The example in the issue #796 exposed this issue. ``` structure A class B (a : outParam A) (α : Sort u) class C {a : A} (α : Sort u) [B a α] class D {a : A} (α : Sort u) [B a α] [c : C α] class E (a : A) where [c (α : Sort u) [B a α] : C α] instance c {a : A} [e : E a] (α : Sort u) [B a α] : C α := e.c α def d {a : A} [e : E a] (α : Sort u) [b : B a α] : D α := ⟨⟩ ``` The term `D α` has two instance implicit arguments. The second one has type `C α`, and TC resolution produces the result `@c.{u} a e α b`. Note that the `e` has type `E.{?v} a`, and `E` is universe polymorphic, but the universe does not occur in the parameter `a`. We have that `?v := u` is implied by `@c.{u} a e α b`, but this assignment is lost. -/ check result pure (some result) else trace[Meta.synthInstance] "result type{indentExpr resultType}\nis not definitionally equal to{indentExpr type}" pure none if type.hasMVar || resultHasUnivMVars then pure result? else do modify fun s => { s with cache.synthInstance := s.cache.synthInstance.insert type result? } pure result? /-- Return `LOption.some r` if succeeded, `LOption.none` if it failed, and `LOption.undef` if instance cannot be synthesized right now because `type` contains metavariables. -/ def trySynthInstance (type : Expr) (maxResultSize? : Option Nat := none) : MetaM (LOption Expr) := do catchInternalId isDefEqStuckExceptionId (toLOptionM <| synthInstance? type maxResultSize?) (fun _ => pure LOption.undef) def synthInstance (type : Expr) (maxResultSize? : Option Nat := none) : MetaM Expr := catchInternalId isDefEqStuckExceptionId (do let result? ← synthInstance? type maxResultSize? match result? with | some result => pure result | none => throwError "failed to synthesize{indentExpr type}") (fun _ => throwError "failed to synthesize{indentExpr type}") @[export lean_synth_pending] private def synthPendingImp (mvarId : MVarId) : MetaM Bool := withIncRecDepth <| mvarId.withContext do let mvarDecl ← mvarId.getDecl match mvarDecl.kind with | MetavarKind.syntheticOpaque => return false | _ => /- Check whether the type of the given metavariable is a class or not. If yes, then try to synthesize it using type class resolution. We only do it for `synthetic` and `natural` metavariables. -/ match (← isClass? mvarDecl.type) with | none => return false | some _ => /- TODO: use a configuration option instead of the hard-coded limit `1`. -/ if (← read).synthPendingDepth > 1 then trace[Meta.synthPending] "too many nested synthPending invocations" return false else withReader (fun ctx => { ctx with synthPendingDepth := ctx.synthPendingDepth + 1 }) do trace[Meta.synthPending] "synthPending {mkMVar mvarId}" let val? ← catchInternalId isDefEqStuckExceptionId (synthInstance? mvarDecl.type (maxResultSize? := none)) (fun _ => pure none) match val? with | none => return false | some val => if (← mvarId.isAssigned) then return false else mvarId.assign val return true builtin_initialize registerTraceClass `Meta.synthPending registerTraceClass `Meta.synthInstance registerTraceClass `Meta.synthInstance.globalInstances registerTraceClass `Meta.synthInstance.newSubgoal registerTraceClass `Meta.synthInstance.tryResolve registerTraceClass `Meta.synthInstance.resume registerTraceClass `Meta.synthInstance.generate registerTraceClass `Meta.synthInstance.unusedArgs registerTraceClass `Meta.synthInstance.newAnswer end Lean.Meta
4f4d2610b18a61ed263a6c7b42a83d124697c783
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/data/prod_auto.lean
f70439edc0deead606fca4c859f05595b659b7d0
[]
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,865
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, Jeremy Avigad -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.logic universes u v u₁ u₂ v₁ v₂ namespace Mathlib @[simp] theorem prod.mk.eta {α : Type u} {β : Type v} {p : α × β} : (prod.fst p, prod.snd p) = p := prod.cases_on p fun (p_fst : α) (p_snd : β) => idRhs ((prod.fst (p_fst, p_snd), prod.snd (p_fst, p_snd)) = (prod.fst (p_fst, p_snd), prod.snd (p_fst, p_snd))) rfl protected instance prod.inhabited {α : Type u} {β : Type v} [Inhabited α] [Inhabited β] : Inhabited (α × β) := { default := (Inhabited.default, Inhabited.default) } protected instance prod.decidable_eq {α : Type u} {β : Type v} [h₁ : DecidableEq α] [h₂ : DecidableEq β] : DecidableEq (α × β) := sorry protected instance prod.has_lt {α : Type u} {β : Type v} [HasLess α] [HasLess β] : HasLess (α × β) := { Less := fun (s t : α × β) => prod.fst s < prod.fst t ∨ prod.fst s = prod.fst t ∧ prod.snd s < prod.snd t } protected instance prod_has_decidable_lt {α : Type u} {β : Type v} [HasLess α] [HasLess β] [DecidableEq α] [DecidableEq β] [DecidableRel Less] [DecidableRel Less] (s : α × β) (t : α × β) : Decidable (s < t) := or.decidable theorem prod.lt_def {α : Type u} {β : Type v} [HasLess α] [HasLess β] (s : α × β) (t : α × β) : s < t = (prod.fst s < prod.fst t ∨ prod.fst s = prod.fst t ∧ prod.snd s < prod.snd t) := rfl def prod.map {α₁ : Type u₁} {α₂ : Type u₂} {β₁ : Type v₁} {β₂ : Type v₂} (f : α₁ → α₂) (g : β₁ → β₂) (x : α₁ × β₁) : α₂ × β₂ := (f (prod.fst x), g (prod.snd x)) end Mathlib
f1ddf3a1cb6d46a7a2130dbafd84e5a358111db5
ad0c7d243dc1bd563419e2767ed42fb323d7beea
/data/nat/binomial.lean
aa66aa0bc5e03e55ed008ac9acff4887b51de24a
[ "Apache-2.0" ]
permissive
sebzim4500/mathlib
e0b5a63b1655f910dee30badf09bd7e191d3cf30
6997cafbd3a7325af5cb318561768c316ceb7757
refs/heads/master
1,585,549,958,618
1,538,221,723,000
1,538,221,723,000
150,869,076
0
0
Apache-2.0
1,538,229,323,000
1,538,229,323,000
null
UTF-8
Lean
false
false
1,565
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.nat.choose algebra.big_operators open nat finset /-- The binomial theorem -/ theorem add_pow {α : Type*} [comm_semiring α] (x y : α) : ∀ n : ℕ, (x + y) ^ n = (range (succ n)).sum (λ m, x ^ m * y ^ (n - m) * choose n m) | 0 := by simp | (succ n) := have h₁ : x * (x ^ n * y ^ (n - n) * choose n n) = x ^ succ n * y ^ (succ n - succ n) * choose (succ n) (succ n), by simp [_root_.pow_succ, mul_assoc, mul_comm, mul_left_comm], have h₂ : y * (x^0 * y^(n - 0) * choose n 0) = x^0 * y^(succ n - 0) * choose (succ n) 0, by simp [_root_.pow_succ, mul_assoc, mul_comm, mul_left_comm], have h₃ : (range n).sum (λ m, x * (x ^ m * y ^ (n - m) * choose n m) + y * (x ^ succ m * y ^ (n - succ m) * choose n (succ m))) = (range n).sum (λ m, x ^ succ m * y ^ (succ n - succ m) * ↑(choose (succ n) (succ m))), from finset.sum_congr rfl $ λ m hm, begin simp only [mul_assoc, mul_left_comm y, mul_left_comm (y ^ (n - succ m)), mul_comm y], rw [← _root_.pow_succ', add_one, ← succ_sub (mem_range.1 hm)], simp [choose_succ_succ, mul_comm, mul_assoc, mul_left_comm, add_mul, mul_add, _root_.pow_succ] end, by rw [_root_.pow_succ, add_pow, add_mul, finset.mul_sum, finset.mul_sum, sum_range_succ, sum_range_succ', sum_range_succ, sum_range_succ', add_assoc, ← add_assoc ((range n).sum _), ← finset.sum_add_distrib, h₁, h₂, h₃]
d38060b64af7cdc4ed8d2b5ae1d5a6857dba980e
e30ff3aabdac29f8ea40ad76887544d0f9be9018
/ircbot/modules/ping_pong.lean
deec0d5b12d2d16a24fc038438f79ba20c994a68
[]
no_license
forked-from-1kasper/leanbot
bdef0efa3e4d0eb75b06c1707fb4e35086bb57fa
c61c8c7fdad7b05877e0d232719ce23d2999557f
refs/heads/master
1,651,846,081,986
1,646,404,009,000
1,646,404,009,000
127,132,795
12
1
null
1,605,183,650,000
1,522,237,998,000
Lean
UTF-8
Lean
false
false
1,554
lean
import ircbot.types ircbot.support open types support namespace modules.ping_pong def ping_pong_func (input : irc_text) : list irc_text := match input with | irc_text.parsed_normal { object := some ~nick!ident, type := message.privmsg, args := [subject], text := "\\ping" } := let new_subject := if subject.front = '#' then subject else nick in [privmsg new_subject $ sformat! "{nick}, pong"] | _ := [] end /-- For testing: send “pong” after “\ping”. -/ def ping_pong : bot_function := { name := "ping-pong", syntax := some "\\ping", description := "ping-pong game!", func := pure ∘ ping_pong_func } theorem ping_pong_is_correct_on_channel (nick ident subject: string) (on_channel : subject.front = '#') : (ping_pong_func $ irc_text.parsed_normal { object := some ~nick!ident, type := message.privmsg, args := [subject], text := "\\ping" }) = [privmsg subject $ sformat! "{nick}, pong"] := begin intros, simp [ping_pong_func], rw [on_channel], trivial end theorem ping_pong_is_correct_on_priv (nick ident subject bot_nickname : string) (bot_nickname_is_correct : bot_nickname.front ≠ '#') (not_on_channel : subject = bot_nickname): (ping_pong_func $ irc_text.parsed_normal { object := some ~nick!ident, type := message.privmsg, args := [bot_nickname], text := "\\ping" }) = [privmsg nick $ sformat! "{nick}, pong"] := begin intros, simp [privmsg], simp [ping_pong_func], simp [privmsg], simp [bot_nickname_is_correct] end end modules.ping_pong