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
22b3f18b7f2213aecc9e76898e234aadd24e2ce7
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/extend_from.lean
dec8438065b17bb42e95d843636f251b63abfc26
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
4,035
lean
/- Copyright (c) 2020 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Anatole Dedecker -/ import topology.separation /-! # Extending a function from a subset The main definition of this file is `extend_from A f` where `f : X → Y` and `A : set X`. This defines a new function `g : X → Y` which maps any `x₀ : X` to the limit of `f` as `x` tends to `x₀`, if such a limit exists. This is analoguous to the way `dense_inducing.extend` "extends" a function `f : X → Z` to a function `g : Y → Z` along a dense inducing `i : X → Y`. The main theorem we prove about this definition is `continuous_on_extend_from` which states that, for `extend_from A f` to be continuous on a set `B ⊆ closure A`, it suffices that `f` converges within `A` at any point of `B`, provided that `f` is a function to a regular space. -/ noncomputable theory open_locale topological_space open filter set variables {X Y : Type*} [topological_space X] [topological_space Y] /-- Extend a function from a set `A`. The resulting function `g` is such that at any `x₀`, if `f` converges to some `y` as `x` tends to `x₀` within `A`, then `g x₀` is defined to be one of these `y`. Else, `g x₀` could be anything. -/ def extend_from (A : set X) (f : X → Y) : X → Y := λ x, @@lim _ ⟨f x⟩ (𝓝[A] x) f /-- If `f` converges to some `y` as `x` tends to `x₀` within `A`, then `f` tends to `extend_from A f x` as `x` tends to `x₀`. -/ lemma tendsto_extend_from {A : set X} {f : X → Y} {x : X} (h : ∃ y, tendsto f (𝓝[A] x) (𝓝 y)) : tendsto f (𝓝[A] x) (𝓝 $ extend_from A f x) := tendsto_nhds_lim h lemma extend_from_eq [t2_space Y] {A : set X} {f : X → Y} {x : X} {y : Y} (hx : x ∈ closure A) (hf : tendsto f (𝓝[A] x) (𝓝 y)) : extend_from A f x = y := begin haveI := mem_closure_iff_nhds_within_ne_bot.mp hx, exact tendsto_nhds_unique (tendsto_nhds_lim ⟨y, hf⟩) hf, end lemma extend_from_extends [t2_space Y] {f : X → Y} {A : set X} (hf : continuous_on f A) : ∀ x ∈ A, extend_from A f x = f x := λ x x_in, extend_from_eq (subset_closure x_in) (hf x x_in) /-- If `f` is a function to a regular space `Y` which has a limit within `A` at any point of a set `B ⊆ closure A`, then `extend_from A f` is continuous on `B`. -/ lemma continuous_on_extend_from [regular_space Y] {f : X → Y} {A B : set X} (hB : B ⊆ closure A) (hf : ∀ x ∈ B, ∃ y, tendsto f (𝓝[A] x) (𝓝 y)) : continuous_on (extend_from A f) B := begin set φ := extend_from A f, intros x x_in, suffices : ∀ V' ∈ 𝓝 (φ x), is_closed V' → φ ⁻¹' V' ∈ 𝓝[B] x, by simpa [continuous_within_at, (closed_nhds_basis _).tendsto_right_iff], intros V' V'_in V'_closed, obtain ⟨V, V_in, V_op, hV⟩ : ∃ V ∈ 𝓝 x, is_open V ∧ V ∩ A ⊆ f ⁻¹' V', { have := tendsto_extend_from (hf x x_in), rcases (nhds_within_basis_open x A).tendsto_left_iff.mp this V' V'_in with ⟨V, ⟨hxV, V_op⟩, hV⟩, use [V, is_open.mem_nhds V_op hxV, V_op, hV] }, suffices : ∀ y ∈ V ∩ B, φ y ∈ V', from mem_of_superset (inter_mem_inf V_in $ mem_principal_self B) this, rintros y ⟨hyV, hyB⟩, haveI := mem_closure_iff_nhds_within_ne_bot.mp (hB hyB), have limy : tendsto f (𝓝[A] y) (𝓝 $ φ y) := tendsto_extend_from (hf y hyB), have hVy : V ∈ 𝓝 y := is_open.mem_nhds V_op hyV, have : V ∩ A ∈ (𝓝[A] y), by simpa [inter_comm] using inter_mem_nhds_within _ hVy, exact V'_closed.mem_of_tendsto limy (mem_of_superset this hV) end /-- If a function `f` to a regular space `Y` has a limit within a dense set `A` for any `x`, then `extend_from A f` is continuous. -/ lemma continuous_extend_from [regular_space Y] {f : X → Y} {A : set X} (hA : dense A) (hf : ∀ x, ∃ y, tendsto f (𝓝[A] x) (𝓝 y)) : continuous (extend_from A f) := begin rw continuous_iff_continuous_on_univ, exact continuous_on_extend_from (λ x _, hA x) (by simpa using hf) end
efd0a74cff9624c7298f53b5285c2a58257f36ce
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/calc_auto_trans_eq.lean
0ce25dfda47a0b9590ebfed87cfda1340308eae1
[ "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
530
lean
import data.list constant R : Π {A : Type}, A → A → Prop infix `~` := R example {A : Type} {a b c d : list nat} (H₁ : a ~ b) (H₂ : b = c) (H₃ : c = d) : a ~ d := calc a ~ b : H₁ ... = c : H₂ ... = d : H₃ example {A : Type} {a b c d : list nat} (H₁ : a = b) (H₂ : b = c) (H₃ : c ~ d) : a ~ d := calc a = b : H₁ ... = c : H₂ ... ~ d : H₃ example {A : Type} {a b c d : list nat} (H₁ : a = b) (H₂ : b ~ c) (H₃ : c = d) : a ~ d := calc a = b : H₁ ... ~ c : H₂ ... = d : H₃
37151da649fac6ad7762bfbfc2df1225645351c5
2c096fdfecf64e46ea7bc6ce5521f142b5926864
/src/Lean/ResolveName.lean
6ab7d4aa1df7a11e548bf097a5c9d344ded1be32
[ "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
Kha/lean4
1005785d2c8797ae266a303968848e5f6ce2fe87
b99e11346948023cd6c29d248cd8f3e3fb3474cf
refs/heads/master
1,693,355,498,027
1,669,080,461,000
1,669,113,138,000
184,748,176
0
0
Apache-2.0
1,665,995,520,000
1,556,884,930,000
Lean
UTF-8
Lean
false
false
14,384
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Data.OpenDecl import Lean.Hygiene import Lean.Modifiers import Lean.Exception namespace Lean /-! We use aliases to implement the `export <id> (<id>+)` command. An `export A (x)` in the namespace `B` produces an alias `B.x ~> A.x`. -/ abbrev AliasState := SMap Name (List Name) abbrev AliasEntry := Name × Name def addAliasEntry (s : AliasState) (e : AliasEntry) : AliasState := match s.find? e.1 with | none => s.insert e.1 [e.2] | some es => if es.contains e.2 then s else s.insert e.1 (e.2 :: es) builtin_initialize aliasExtension : SimplePersistentEnvExtension AliasEntry AliasState ← registerSimplePersistentEnvExtension { addEntryFn := addAliasEntry, addImportedFn := fun es => mkStateFromImportedEntries addAliasEntry {} es |>.switch } /-- Add alias `a` for `e` -/ @[export lean_add_alias] def addAlias (env : Environment) (a : Name) (e : Name) : Environment := aliasExtension.addEntry env (a, e) def getAliasState (env : Environment) : AliasState := aliasExtension.getState env /-- Retrieve aliases for `a`. If `skipProtected` is `true`, then the resulting list only includes declarations that are not marked as `proctected`. -/ def getAliases (env : Environment) (a : Name) (skipProtected : Bool) : List Name := match aliasExtension.getState env |>.find? a with | none => [] | some es => if skipProtected then es.filter (!isProtected env ·) else es -- slower, but only used in the pretty printer def getRevAliases (env : Environment) (e : Name) : List Name := (aliasExtension.getState env).fold (fun as a es => if List.contains es e then a :: as else as) [] /-! # Global name resolution -/ namespace ResolveName /-- Check whether `ns ++ id` is a valid namepace name and/or there are aliases names `ns ++ id`. -/ private def resolveQualifiedName (env : Environment) (ns : Name) (id : Name) : List Name := let resolvedId := ns ++ id -- We ignore protected aliases if `id` is atomic. let resolvedIds := getAliases env resolvedId (skipProtected := id.isAtomic) if env.contains resolvedId && (!id.isAtomic || !isProtected env resolvedId) then resolvedId :: resolvedIds else -- Check whether environment contains the private version. That is, `_private.<module_name>.ns.id`. let resolvedIdPrv := mkPrivateName env resolvedId if env.contains resolvedIdPrv then resolvedIdPrv :: resolvedIds else resolvedIds /-- Check surrounding namespaces -/ private def resolveUsingNamespace (env : Environment) (id : Name) : Name → List Name | ns@(.str p _) => match resolveQualifiedName env ns id with | [] => resolveUsingNamespace env id p | resolvedIds => resolvedIds | _ => [] /-- Check exact name -/ private def resolveExact (env : Environment) (id : Name) : Option Name := if id.isAtomic then none else let resolvedId := id.replacePrefix rootNamespace Name.anonymous if env.contains resolvedId then some resolvedId else -- We also allow `_root` when accessing private declarations. -- If we change our minds, we should just replace `resolvedId` with `id` let resolvedIdPrv := mkPrivateName env resolvedId if env.contains resolvedIdPrv then some resolvedIdPrv else none /-- Check `OpenDecl`s -/ private def resolveOpenDecls (env : Environment) (id : Name) : List OpenDecl → List Name → List Name | [], resolvedIds => resolvedIds | OpenDecl.simple ns exs :: openDecls, resolvedIds => if exs.contains id then resolveOpenDecls env id openDecls resolvedIds else let newResolvedIds := resolveQualifiedName env ns id resolveOpenDecls env id openDecls (newResolvedIds ++ resolvedIds) | OpenDecl.explicit openedId resolvedId :: openDecls, resolvedIds => let resolvedIds := if openedId == id then resolvedId :: resolvedIds else if openedId.isPrefixOf id then let candidate := id.replacePrefix openedId resolvedId if env.contains candidate then candidate :: resolvedIds else resolvedIds else resolvedIds resolveOpenDecls env id openDecls resolvedIds def resolveGlobalName (env : Environment) (ns : Name) (openDecls : List OpenDecl) (id : Name) : List (Name × List String) := -- decode macro scopes from name before recursion let extractionResult := extractMacroScopes id let rec loop (id : Name) (projs : List String) : List (Name × List String) := match id with | .str p s => -- NOTE: we assume that macro scopes always belong to the projected constant, not the projections let id := { extractionResult with name := id }.review match resolveUsingNamespace env id ns with | resolvedIds@(_ :: _) => resolvedIds.eraseDups.map fun id => (id, projs) | [] => match resolveExact env id with | some newId => [(newId, projs)] | none => let resolvedIds := if env.contains id then [id] else [] let idPrv := mkPrivateName env id let resolvedIds := if env.contains idPrv then [idPrv] ++ resolvedIds else resolvedIds let resolvedIds := resolveOpenDecls env id openDecls resolvedIds let resolvedIds := getAliases env id (skipProtected := id.isAtomic) ++ resolvedIds match resolvedIds with | _ :: _ => resolvedIds.eraseDups.map fun id => (id, projs) | [] => loop p (s::projs) | _ => [] loop extractionResult.name [] /-! # Namespace resolution -/ def resolveNamespaceUsingScope? (env : Environment) (n : Name) : Name → Option Name | .anonymous => if env.isNamespace n then some n else none | ns@(.str p _) => if env.isNamespace (ns ++ n) then some (ns ++ n) else resolveNamespaceUsingScope? env n p | _ => unreachable! def resolveNamespaceUsingOpenDecls (env : Environment) (n : Name) : List OpenDecl → List Name | [] => [] | OpenDecl.simple ns exs :: ds => if env.isNamespace (ns ++ n) && !exs.contains n then (ns ++ n) :: resolveNamespaceUsingOpenDecls env n ds else resolveNamespaceUsingOpenDecls env n ds | _ :: ds => resolveNamespaceUsingOpenDecls env n ds /-- Given a name `id` try to find namespaces it may refer to. The resolution procedure works as follows 1- If `id` is in the scope of `namespace` commands the namespace `s_1. ... . s_n`, then we include `s_1 . ... . s_i ++ n` in the result if it is the name of an existing namespace. We search "backwards", and include at most one of the in the list of resulting namespaces. 2- If `id` is the extact name of an existing namespace, then include `id` 3- Finally, for each command `open N`, include in the result `N ++ n` if it is the name of an existing namespace. We only consider simple `open` commands. -/ def resolveNamespace (env : Environment) (ns : Name) (openDecls : List OpenDecl) (id : Name) : List Name := match resolveNamespaceUsingScope? env id ns with | some ns => ns :: resolveNamespaceUsingOpenDecls env id openDecls | none => resolveNamespaceUsingOpenDecls env id openDecls end ResolveName class MonadResolveName (m : Type → Type) where getCurrNamespace : m Name getOpenDecls : m (List OpenDecl) export MonadResolveName (getCurrNamespace getOpenDecls) instance (m n) [MonadLift m n] [MonadResolveName m] : MonadResolveName n where getCurrNamespace := liftM (m:=m) getCurrNamespace getOpenDecls := liftM (m:=m) getOpenDecls /-- Given a name `n`, return a list of possible interpretations. Each interpretation is a pair `(declName, fieldList)`, where `declName` is the name of a declaration in the current environment, and `fieldList` are (potential) field names. The pair is needed because in Lean `.` may be part of a qualified name or a field (aka dot-notation). As an example, consider the following definitions ``` def Boo.x := 1 def Foo.x := 2 def Foo.x.y := 3 ``` After `open Foo`, we have - `resolveGlobalName x` => `[(Foo.x, [])]` - `resolveGlobalName x.y` => `[(Foo.x.y, [])]` - `resolveGlobalName x.z.w` => `[(Foo.x, [z, w])]` After `open Foo open Boo`, we have - `resolveGlobalName x` => `[(Foo.x, []), (Boo.x, [])]` - `resolveGlobalName x.y` => `[(Foo.x.y, [])]` - `resolveGlobalName x.z.w` => `[(Foo.x, [z, w]), (Boo.x, [z, w])]` -/ def resolveGlobalName [Monad m] [MonadResolveName m] [MonadEnv m] (id : Name) : m (List (Name × List String)) := do return ResolveName.resolveGlobalName (← getEnv) (← getCurrNamespace) (← getOpenDecls) id /-- Given a namespace name, return a list of possible interpretations. Names extracted from syntax should be passed to `resolveNamespace` instead. -/ def resolveNamespaceCore [Monad m] [MonadResolveName m] [MonadEnv m] [MonadError m] (id : Name) (allowEmpty := false) : m (List Name) := do let nss := ResolveName.resolveNamespace (← getEnv) (← getCurrNamespace) (← getOpenDecls) id if !allowEmpty && nss.isEmpty then throwError s!"unknown namespace '{id}'" return nss /-- Given a namespace identifier, return a list of possible interpretations. -/ def resolveNamespace [Monad m] [MonadResolveName m] [MonadEnv m] [MonadError m] : Ident → m (List Name) | stx@⟨Syntax.ident _ _ n pre⟩ => do let pre := pre.filterMap fun | .namespace ns => some ns | _ => none if pre.isEmpty then withRef stx <| resolveNamespaceCore n else return pre | stx => throwErrorAt stx s!"expected identifier" /-- Given a namespace identifier, return the unique interpretation or else fail. -/ def resolveUniqueNamespace [Monad m] [MonadResolveName m] [MonadEnv m] [MonadError m] (id : Ident) : m Name := do match (← resolveNamespace id) with | [ns] => return ns | nss => throwError s!"ambiguous namespace '{id.getId}', possible interpretations: '{nss}'" /-- Given a name `n`, return a list of possible interpretations for global constants. Similar to `resolveGlobalName`, but discard any candidate whose `fieldList` is not empty. For identifiers taken from syntax, use `resolveGlobalConst` instead, which respects preresolved names. -/ def resolveGlobalConstCore [Monad m] [MonadResolveName m] [MonadEnv m] [MonadError m] (n : Name) : m (List Name) := do let cs ← resolveGlobalName n let cs := cs.filter fun (_, fieldList) => fieldList.isEmpty if cs.isEmpty then throwUnknownConstant n return cs.map (·.1) /-- For identifiers taken from syntax, use `resolveGlobalConstNoOverload` instead, which respects preresolved names. -/ def resolveGlobalConstNoOverloadCore [Monad m] [MonadResolveName m] [MonadEnv m] [MonadError m] (n : Name) : m Name := do let cs ← resolveGlobalConstCore n match cs with | [c] => pure c | _ => throwError s!"ambiguous identifier '{mkConst n}', possible interpretations: {cs.map mkConst}" /-- Interpret the syntax `n` as an identifier for a global constant, and return a list of resolved constant names that it could be refering to based on the currently open namespaces. This should be used instead of `resolveGlobalConstCore` for identifiers taken from syntax because `Syntax` objects may have names that have already been resolved. ## Example: ``` def Boo.x := 1 def Foo.x := 2 def Foo.x.y := 3 ``` After `open Foo`, we have - `resolveGlobalConst x` => `[Foo.x]` - `resolveGlobalConst x.y` => `[Foo.x.y]` - `resolveGlobalConst x.z.w` => error: unknown constant After `open Foo open Boo`, we have - `resolveGlobalConst x` => `[Foo.x, Boo.x]` - `resolveGlobalConst x.y` => `[Foo.x.y]` - `resolveGlobalConst x.z.w` => error: unknown constant -/ def resolveGlobalConst [Monad m] [MonadResolveName m] [MonadEnv m] [MonadError m] : Syntax → m (List Name) | stx@(Syntax.ident _ _ n pre) => do let pre := pre.filterMap fun | .decl n [] => some n | _ => none if pre.isEmpty then withRef stx <| resolveGlobalConstCore n else return pre | stx => throwErrorAt stx s!"expected identifier" /-- Interpret the syntax `n` as an identifier for a global constant, and return a resolved constant name. If there are multiple possible interpretations it will throw. ## Example: ``` def Boo.x := 1 def Foo.x := 2 def Foo.x.y := 3 ``` After `open Foo`, we have - `resolveGlobalConstNoOverload x` => `Foo.x` - `resolveGlobalConstNoOverload x.y` => `Foo.x.y` - `resolveGlobalConstNoOverload x.z.w` => error: unknown constant After `open Foo open Boo`, we have - `resolveGlobalConstNoOverload x` => error: ambiguous identifier - `resolveGlobalConstNoOverload x.y` => `Foo.x.y` - `resolveGlobalConstNoOverload x.z.w` => error: unknown constant -/ def resolveGlobalConstNoOverload [Monad m] [MonadResolveName m] [MonadEnv m] [MonadError m] (id : Syntax) : m Name := do let cs ← resolveGlobalConst id match cs with | [c] => pure c | _ => throwErrorAt id s!"ambiguous identifier '{id}', possible interpretations: {cs.map mkConst}" def unresolveNameGlobal [Monad m] [MonadResolveName m] [MonadEnv m] (n₀ : Name) (fullNames := false) : m Name := do if n₀.hasMacroScopes then return n₀ if fullNames then match (← resolveGlobalName n₀) with | [(potentialMatch, _)] => if potentialMatch == n₀ then return n₀ else return rootNamespace ++ n₀ | _ => return n₀ -- if can't resolve, return the original let mut initialNames := (getRevAliases (← getEnv) n₀).toArray initialNames := initialNames.push (rootNamespace ++ n₀) for initialName in initialNames do match (← unresolveNameCore initialName) with | none => continue | some n => return n return n₀ -- if can't resolve, return the original where unresolveNameCore (n : Name) : m (Option Name) := do let mut revComponents := n.componentsRev let mut candidate := Name.anonymous for _ in [:revComponents.length] do match revComponents with | [] => return none | cmpt::rest => candidate := cmpt ++ candidate; revComponents := rest match (← resolveGlobalName candidate) with | [(potentialMatch, _)] => if potentialMatch == n₀ then return some candidate else continue | _ => continue return none end Lean
b261b93f973ed7d1d3f587da6d0e2dd9937d68d3
958488bc7f3c2044206e0358e56d7690b6ae696c
/lean/exercise_7_10_1.lean
3d8142af021739d04ccd57c969240e916eb7faa3
[]
no_license
possientis/Prog
a08eec1c1b121c2fd6c70a8ae89e2fbef952adb4
d4b3debc37610a88e0dac3ac5914903604fd1d1f
refs/heads/master
1,692,263,717,723
1,691,757,179,000
1,691,757,179,000
40,361,602
3
0
null
1,679,896,438,000
1,438,953,859,000
Coq
UTF-8
Lean
false
false
4,348
lean
namespace hidden def prod (n : ℕ) : ℕ → ℕ := nat.rec_on n (λ m, 0) (λ n prod_n, λ m, m + prod_n m) def pred (n : ℕ) : ℕ := nat.rec_on n 0 (λ n pred_n, n) def sub (n m : ℕ) : ℕ := nat.rec_on m n (λ m sub_n_m, pred (sub_n_m)) def exp (n m : ℕ) : ℕ := nat.rec_on m 1 (λ m exp_n_m, n * exp_n_m) lemma one_prod : ∀ (n : ℕ), prod 1 n = n := assume n, calc prod 1 n = n + prod 0 n : by refl ... = n + 0 : by refl ... = n : by refl open nat lemma prod_one : ∀ (n : ℕ), prod n 1 = n := assume n, begin induction n with n IH, {by refl}, {from calc prod (succ n) 1 = 1 + prod n 1 : by refl ... = 1 + n : by rw IH ... = succ n : by simp } end lemma add_prod : ∀ (n m p : ℕ), prod (n + m) p = prod n p + prod m p := assume n, begin induction n with n IH, {from assume m p, calc prod (0 + m) p = prod m p : by rw zero_add ... = 0 + prod m p : by rw zero_add ... = prod 0 p + prod m p : by refl}, {from assume m p, calc prod (succ n + m) p = prod (succ (n + m)) p : by rw succ_add ... = p + prod (n + m) p : by refl ... = p + (prod n p + prod m p) : by rw IH ... = (p + prod n p) + prod m p : by rw add_assoc ... = prod (succ n) p + prod m p : by refl } end lemma prod_assoc : ∀ (n m p : ℕ), prod (prod n m) p = prod n (prod m p) := assume n, begin induction n with n IH, {from assume m p, calc prod (prod 0 m) p = prod 0 p : by refl ... = 0 : by refl ... = prod 0 (prod m p) : by refl}, {from assume m p, calc prod (prod (succ n) m) p = prod (m + prod n m) p : by refl ... = prod m p + prod (prod n m) p : by rw add_prod ... = prod m p + prod n (prod m p) : by rw IH ... = prod (succ n)(prod m p) : by refl} end lemma prod_succ : ∀ (n m : ℕ), prod n (succ m) = n + prod n m := assume n, begin induction n with n IH, {from assume m, calc prod 0 (succ m) = 0 : by refl ... = 0 + 0 : by refl ... = 0 + prod 0 m : by refl}, {from assume m, calc prod (succ n) (succ m) = (succ m) + prod n (succ m) : by refl ... = (succ m) + (n + prod n m) : by rw IH ... = (succ m + n) + prod n m : by rw add_assoc ... = succ (m + n) + prod n m : by rw succ_add ... = (m + succ n) + prod n m : by rw add_succ ... = (succ n + m) + prod n m : by rw (add_comm m) ... = succ n + (m + prod n m) : by rw add_assoc ... = succ n + prod (succ n) m : by refl} end lemma zero_prod : ∀ (n : ℕ), prod 0 n = 0 := assume n, by refl lemma prod_zero : ∀ (n : ℕ), prod n 0 = 0 := assume n, begin induction n with n IH, {by refl}, {by calc prod (succ n) 0 = 0 + prod n 0 : by refl ... = 0 : by rw IH } end lemma prod_comm : ∀ (n m : ℕ), prod n m = prod m n := assume n, begin induction n with n IH, {from assume m, calc prod 0 m = 0 : by refl ... = prod m 0 : by rw prod_zero}, {from assume m, calc prod (succ n) m = m + prod n m : by refl ... = m + prod m n : by rw IH ... = prod m (succ n) : by rw prod_succ} end --#check one_prod --#check prod_one --#check add_prod --#check prod_assoc --#check prod_succ --#check prod_zero --#check prod_comm end hidden
c5c3dbbdd7fb898ae83d84be0b601369fd2f3b2e
41ebf3cb010344adfa84907b3304db00e02db0a6
/uexp/src/uexp/rules/pushJoinThroughUnionOnLeft.lean
d12660d3ce98bf99ac7c199b666982584fad62f9
[ "BSD-2-Clause" ]
permissive
ReinierKoops/Cosette
e061b2ba58b26f4eddf4cd052dcf7abd16dfe8fb
eb8dadd06ee05fe7b6b99de431dd7c4faef5cb29
refs/heads/master
1,686,483,953,198
1,624,293,498,000
1,624,293,498,000
378,997,885
0
0
BSD-2-Clause
1,624,293,485,000
1,624,293,484,000
null
UTF-8
Lean
false
false
1,833
lean
import ..sql import ..tactics import ..u_semiring import ..extra_constants import ..meta.UDP set_option profiler true open Expr open Proj open Pred open SQL open tree notation `int` := datatypes.int theorem rule: forall ( Γ scm_t scm_account scm_bonus scm_dept scm_emp: Schema) (rel_t: relation scm_t) (rel_account: relation scm_account) (rel_bonus: relation scm_bonus) (rel_dept: relation scm_dept) (rel_emp: relation scm_emp) (t_k0 : Column int scm_t) (t_c1 : Column int scm_t) (t_f1_a0 : Column int scm_t) (t_f2_a0 : Column int scm_t) (t_f0_c0 : Column int scm_t) (t_f1_c0 : Column int scm_t) (t_f0_c1 : Column int scm_t) (t_f1_c2 : Column int scm_t) (t_f2_c3 : Column int scm_t) (account_acctno : Column int scm_account) (account_type : Column int scm_account) (account_balance : Column int scm_account) (bonus_ename : Column int scm_bonus) (bonus_job : Column int scm_bonus) (bonus_sal : Column int scm_bonus) (bonus_comm : Column int scm_bonus) (dept_deptno : Column int scm_dept) (dept_name : Column int scm_dept) (emp_empno : Column int scm_emp) (emp_ename : Column int scm_emp) (emp_job : Column int scm_emp) (emp_mgr : Column int scm_emp) (emp_hiredate : Column int scm_emp) (emp_comm : Column int scm_emp) (emp_sal : Column int scm_emp) (emp_deptno : Column int scm_emp) (emp_slacker : Column int scm_emp), denoteSQL ((SELECT1 (right⋅left⋅emp_sal) FROM1 (product (((SELECT * FROM1 (table rel_emp) )) UNION ALL ((SELECT * FROM1 (table rel_emp) ))) (table rel_emp)) ) : SQL Γ _ ) = denoteSQL ((SELECT1 (right⋅right⋅emp_sal) FROM1 (((SELECT * FROM1 (product (table rel_emp) (table rel_emp)) )) UNION ALL ((SELECT * FROM1 (product (table rel_emp) (table rel_emp)) ))) ) : SQL Γ _) := begin intros, unfold_all_denotations, funext, print_size, simp, print_size, UDP, end
eb56eb7bc8d88ca509c2cb3a76b9dc89c01e8c24
4727251e0cd73359b15b664c3170e5d754078599
/src/group_theory/group_action/defs.lean
ee7b302f12f9bdb0e7ef7a5c88eeb1c685070117
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
31,767
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Yury Kudryashov -/ import algebra.group.type_tags import algebra.hom.group import algebra.opposites import logic.embedding /-! # Definitions of group actions This file defines a hierarchy of group action type-classes on top of the previously defined notation classes `has_scalar` and its additive version `has_vadd`: * `mul_action M α` and its additive version `add_action G P` are typeclasses used for actions of multiplicative and additive monoids and groups; they extend notation classes `has_scalar` and `has_vadd` that are defined in `algebra.group.defs`; * `distrib_mul_action M A` is a typeclass for an action of a multiplicative monoid on an additive monoid such that `a • (b + c) = a • b + a • c` and `a • 0 = 0`. The hierarchy is extended further by `module`, defined elsewhere. Also provided are typeclasses for faithful and transitive actions, and typeclasses regarding the interaction of different group actions, * `smul_comm_class M N α` and its additive version `vadd_comm_class M N α`; * `is_scalar_tower M N α` (no additive version). * `is_central_scalar M α` (no additive version). ## Notation - `a • b` is used as notation for `has_scalar.smul a b`. - `a +ᵥ b` is used as notation for `has_vadd.vadd a b`. ## Implementation details This file should avoid depending on other parts of `group_theory`, to avoid import cycles. More sophisticated lemmas belong in `group_theory.group_action`. ## Tags group action -/ variables {M N G A B α β γ δ : Type*} open function (injective surjective) /-! ### Faithful actions -/ /-- Typeclass for faithful actions. -/ class has_faithful_vadd (G : Type*) (P : Type*) [has_vadd G P] : Prop := (eq_of_vadd_eq_vadd : ∀ {g₁ g₂ : G}, (∀ p : P, g₁ +ᵥ p = g₂ +ᵥ p) → g₁ = g₂) /-- Typeclass for faithful actions. -/ @[to_additive has_faithful_vadd] class has_faithful_scalar (M : Type*) (α : Type*) [has_scalar M α] : Prop := (eq_of_smul_eq_smul : ∀ {m₁ m₂ : M}, (∀ a : α, m₁ • a = m₂ • a) → m₁ = m₂) export has_faithful_scalar (eq_of_smul_eq_smul) has_faithful_vadd (eq_of_vadd_eq_vadd) @[to_additive] lemma smul_left_injective' [has_scalar M α] [has_faithful_scalar M α] : function.injective ((•) : M → α → α) := λ m₁ m₂ h, has_faithful_scalar.eq_of_smul_eq_smul (congr_fun h) /-- See also `monoid.to_mul_action` and `mul_zero_class.to_smul_with_zero`. -/ @[priority 910, to_additive] -- see Note [lower instance priority] instance has_mul.to_has_scalar (α : Type*) [has_mul α] : has_scalar α α := ⟨(*)⟩ @[simp, to_additive] lemma smul_eq_mul (α : Type*) [has_mul α] {a a' : α} : a • a' = a * a' := rfl /-- Type class for additive monoid actions. -/ @[ext, protect_proj] class add_action (G : Type*) (P : Type*) [add_monoid G] extends has_vadd G P := (zero_vadd : ∀ p : P, (0 : G) +ᵥ p = p) (add_vadd : ∀ (g₁ g₂ : G) (p : P), (g₁ + g₂) +ᵥ p = g₁ +ᵥ (g₂ +ᵥ p)) /-- Typeclass for multiplicative actions by monoids. This generalizes group actions. -/ @[ext, protect_proj, to_additive] class mul_action (α : Type*) (β : Type*) [monoid α] extends has_scalar α β := (one_smul : ∀ b : β, (1 : α) • b = b) (mul_smul : ∀ (x y : α) (b : β), (x * y) • b = x • y • b) instance additive.add_action [monoid α] [mul_action α β] : add_action (additive α) β := { vadd := (•) ∘ additive.to_mul, zero_vadd := mul_action.one_smul, add_vadd := mul_action.mul_smul } @[simp] lemma additive.of_mul_vadd [monoid α] [mul_action α β] (a : α) (b : β) : additive.of_mul a +ᵥ b = a • b := rfl instance multiplicative.mul_action [add_monoid α] [add_action α β] : mul_action (multiplicative α) β := { smul := (+ᵥ) ∘ multiplicative.to_add, one_smul := add_action.zero_vadd, mul_smul := add_action.add_vadd } @[simp] lemma multiplicative.of_add_smul [add_monoid α] [add_action α β] (a : α) (b : β) : multiplicative.of_add a • b = a +ᵥ b := rfl /-! ### (Pre)transitive action `M` acts pretransitively on `α` if for any `x y` there is `g` such that `g • x = y` (or `g +ᵥ x = y` for an additive action). A transitive action should furthermore have `α` nonempty. In this section we define typeclasses `mul_action.is_pretransitive` and `add_action.is_pretransitive` and provide `mul_action.exists_smul_eq`/`add_action.exists_vadd_eq`, `mul_action.surjective_smul`/`add_action.surjective_vadd` as public interface to access this property. We do not provide typeclasses `*_action.is_transitive`; users should assume `[mul_action.is_pretransitive M α] [nonempty α]` instead. -/ /-- `M` acts pretransitively on `α` if for any `x y` there is `g` such that `g +ᵥ x = y`. A transitive action should furthermore have `α` nonempty. -/ class add_action.is_pretransitive (M α : Type*) [has_vadd M α] : Prop := (exists_vadd_eq : ∀ x y : α, ∃ g : M, g +ᵥ x = y) /-- `M` acts pretransitively on `α` if for any `x y` there is `g` such that `g • x = y`. A transitive action should furthermore have `α` nonempty. -/ @[to_additive] class mul_action.is_pretransitive (M α : Type*) [has_scalar M α] : Prop := (exists_smul_eq : ∀ x y : α, ∃ g : M, g • x = y) namespace mul_action variables (M) {α} [has_scalar M α] [is_pretransitive M α] @[to_additive] lemma exists_smul_eq (x y : α) : ∃ m : M, m • x = y := is_pretransitive.exists_smul_eq x y @[to_additive] lemma surjective_smul (x : α) : surjective (λ c : M, c • x) := exists_smul_eq M x /-- The regular action of a group on itself is transitive. -/ @[to_additive] instance regular.is_pretransitive [group G] : is_pretransitive G G := ⟨λ x y, ⟨y * x⁻¹, inv_mul_cancel_right _ _⟩⟩ end mul_action /-! ### Scalar tower and commuting actions -/ /-- A typeclass mixin saying that two additive actions on the same space commute. -/ class vadd_comm_class (M N α : Type*) [has_vadd M α] [has_vadd N α] : Prop := (vadd_comm : ∀ (m : M) (n : N) (a : α), m +ᵥ (n +ᵥ a) = n +ᵥ (m +ᵥ a)) /-- A typeclass mixin saying that two multiplicative actions on the same space commute. -/ @[to_additive] class smul_comm_class (M N α : Type*) [has_scalar M α] [has_scalar N α] : Prop := (smul_comm : ∀ (m : M) (n : N) (a : α), m • n • a = n • m • a) export mul_action (mul_smul) add_action (add_vadd) smul_comm_class (smul_comm) vadd_comm_class (vadd_comm) /-- Frequently, we find ourselves wanting to express a bilinear map `M →ₗ[R] N →ₗ[R] P` or an equivalence between maps `(M →ₗ[R] N) ≃ₗ[R] (M' →ₗ[R] N')` where the maps have an associated ring `R`. Unfortunately, using definitions like these requires that `R` satisfy `comm_semiring R`, and not just `semiring R`. Using `M →ₗ[R] N →+ P` and `(M →ₗ[R] N) ≃+ (M' →ₗ[R] N')` avoids this problem, but throws away structure that is useful for when we _do_ have a commutative (semi)ring. To avoid making this compromise, we instead state these definitions as `M →ₗ[R] N →ₗ[S] P` or `(M →ₗ[R] N) ≃ₗ[S] (M' →ₗ[R] N')` and require `smul_comm_class S R` on the appropriate modules. When the caller has `comm_semiring R`, they can set `S = R` and `smul_comm_class_self` will populate the instance. If the caller only has `semiring R` they can still set either `R = ℕ` or `S = ℕ`, and `add_comm_monoid.nat_smul_comm_class` or `add_comm_monoid.nat_smul_comm_class'` will populate the typeclass, which is still sufficient to recover a `≃+` or `→+` structure. An example of where this is used is `linear_map.prod_equiv`. -/ library_note "bundled maps over different rings" /-- Commutativity of actions is a symmetric relation. This lemma can't be an instance because this would cause a loop in the instance search graph. -/ @[to_additive] lemma smul_comm_class.symm (M N α : Type*) [has_scalar M α] [has_scalar N α] [smul_comm_class M N α] : smul_comm_class N M α := ⟨λ a' a b, (smul_comm a a' b).symm⟩ /-- Commutativity of additive actions is a symmetric relation. This lemma can't be an instance because this would cause a loop in the instance search graph. -/ add_decl_doc vadd_comm_class.symm @[to_additive] instance smul_comm_class_self (M α : Type*) [comm_monoid M] [mul_action M α] : smul_comm_class M M α := ⟨λ a a' b, by rw [← mul_smul, mul_comm, mul_smul]⟩ /-- An instance of `is_scalar_tower M N α` states that the multiplicative action of `M` on `α` is determined by the multiplicative actions of `M` on `N` and `N` on `α`. -/ class is_scalar_tower (M N α : Type*) [has_scalar M N] [has_scalar N α] [has_scalar M α] : Prop := (smul_assoc : ∀ (x : M) (y : N) (z : α), (x • y) • z = x • (y • z)) @[simp] lemma smul_assoc {M N} [has_scalar M N] [has_scalar N α] [has_scalar M α] [is_scalar_tower M N α] (x : M) (y : N) (z : α) : (x • y) • z = x • y • z := is_scalar_tower.smul_assoc x y z instance semigroup.is_scalar_tower [semigroup α] : is_scalar_tower α α α := ⟨mul_assoc⟩ /-- A typeclass indicating that the right (aka `mul_opposite`) and left actions by `M` on `α` are equal, that is that `M` acts centrally on `α`. This can be thought of as a version of commutativity for `•`. -/ class is_central_scalar (M α : Type*) [has_scalar M α] [has_scalar Mᵐᵒᵖ α] : Prop := (op_smul_eq_smul : ∀ (m : M) (a : α), mul_opposite.op m • a = m • a) lemma is_central_scalar.unop_smul_eq_smul {M α : Type*} [has_scalar M α] [has_scalar Mᵐᵒᵖ α] [is_central_scalar M α] (m : Mᵐᵒᵖ) (a : α) : (mul_opposite.unop m) • a = m • a := mul_opposite.rec (by exact λ m, (is_central_scalar.op_smul_eq_smul _ _).symm) m export is_central_scalar (op_smul_eq_smul unop_smul_eq_smul) -- these instances are very low priority, as there is usually a faster way to find these instances @[priority 50] instance smul_comm_class.op_left [has_scalar M α] [has_scalar Mᵐᵒᵖ α] [is_central_scalar M α] [has_scalar N α] [smul_comm_class M N α] : smul_comm_class Mᵐᵒᵖ N α := ⟨λ m n a, by rw [←unop_smul_eq_smul m (n • a), ←unop_smul_eq_smul m a, smul_comm]⟩ @[priority 50] instance smul_comm_class.op_right [has_scalar M α] [has_scalar N α] [has_scalar Nᵐᵒᵖ α] [is_central_scalar N α] [smul_comm_class M N α] : smul_comm_class M Nᵐᵒᵖ α := ⟨λ m n a, by rw [←unop_smul_eq_smul n (m • a), ←unop_smul_eq_smul n a, smul_comm]⟩ @[priority 50] instance is_scalar_tower.op_left [has_scalar M α] [has_scalar Mᵐᵒᵖ α] [is_central_scalar M α] [has_scalar M N] [has_scalar Mᵐᵒᵖ N] [is_central_scalar M N] [has_scalar N α] [is_scalar_tower M N α] : is_scalar_tower Mᵐᵒᵖ N α := ⟨λ m n a, by rw [←unop_smul_eq_smul m (n • a), ←unop_smul_eq_smul m n, smul_assoc]⟩ @[priority 50] instance is_scalar_tower.op_right [has_scalar M α] [has_scalar M N] [has_scalar N α] [has_scalar Nᵐᵒᵖ α] [is_central_scalar N α] [is_scalar_tower M N α] : is_scalar_tower M Nᵐᵒᵖ α := ⟨λ m n a, by rw [←unop_smul_eq_smul n a, ←unop_smul_eq_smul (m • n) a, mul_opposite.unop_smul, smul_assoc]⟩ namespace has_scalar variables [has_scalar M α] /-- Auxiliary definition for `has_scalar.comp`, `mul_action.comp_hom`, `distrib_mul_action.comp_hom`, `module.comp_hom`, etc. -/ @[simp, to_additive /-" Auxiliary definition for `has_vadd.comp`, `add_action.comp_hom`, etc. "-/] def comp.smul (g : N → M) (n : N) (a : α) : α := g n • a variables (α) /-- An action of `M` on `α` and a function `N → M` induces an action of `N` on `α`. See note [reducible non-instances]. Since this is reducible, we make sure to go via `has_scalar.comp.smul` to prevent typeclass inference unfolding too far. -/ @[reducible, to_additive /-" An additive action of `M` on `α` and a function `N → M` induces an additive action of `N` on `α` "-/] def comp (g : N → M) : has_scalar N α := { smul := has_scalar.comp.smul g } variables {α} /-- Given a tower of scalar actions `M → α → β`, if we use `has_scalar.comp` to pull back both of `M`'s actions by a map `g : N → M`, then we obtain a new tower of scalar actions `N → α → β`. This cannot be an instance because it can cause infinite loops whenever the `has_scalar` arguments are still metavariables. -/ @[priority 100] lemma comp.is_scalar_tower [has_scalar M β] [has_scalar α β] [is_scalar_tower M α β] (g : N → M) : (by haveI := comp α g; haveI := comp β g; exact is_scalar_tower N α β) := by exact {smul_assoc := λ n, @smul_assoc _ _ _ _ _ _ _ (g n) } /-- This cannot be an instance because it can cause infinite loops whenever the `has_scalar` arguments are still metavariables. -/ @[priority 100] lemma comp.smul_comm_class [has_scalar β α] [smul_comm_class M β α] (g : N → M) : (by haveI := comp α g; exact smul_comm_class N β α) := by exact {smul_comm := λ n, @smul_comm _ _ _ _ _ _ (g n) } /-- This cannot be an instance because it can cause infinite loops whenever the `has_scalar` arguments are still metavariables. -/ @[priority 100] lemma comp.smul_comm_class' [has_scalar β α] [smul_comm_class β M α] (g : N → M) : (by haveI := comp α g; exact smul_comm_class β N α) := by exact {smul_comm := λ _ n, @smul_comm _ _ _ _ _ _ _ (g n) } end has_scalar section /-- Note that the `smul_comm_class α β β` typeclass argument is usually satisfied by `algebra α β`. -/ @[to_additive] lemma mul_smul_comm [has_mul β] [has_scalar α β] [smul_comm_class α β β] (s : α) (x y : β) : x * (s • y) = s • (x * y) := (smul_comm s x y).symm /-- Note that the `is_scalar_tower α β β` typeclass argument is usually satisfied by `algebra α β`. -/ lemma smul_mul_assoc [has_mul β] [has_scalar α β] [is_scalar_tower α β β] (r : α) (x y : β) : (r • x) * y = r • (x * y) := smul_assoc r x y lemma smul_smul_smul_comm [has_scalar α β] [has_scalar α γ] [has_scalar β δ] [has_scalar α δ] [has_scalar γ δ] [is_scalar_tower α β δ] [is_scalar_tower α γ δ] [smul_comm_class β γ δ] (a : α) (b : β) (c : γ) (d : δ) : (a • b) • (c • d) = (a • c) • b • d := by { rw [smul_assoc, smul_assoc, smul_comm b], apply_instance } variables [has_scalar M α] lemma commute.smul_right [has_mul α] [smul_comm_class M α α] [is_scalar_tower M α α] {a b : α} (h : commute a b) (r : M) : commute a (r • b) := (mul_smul_comm _ _ _).trans ((congr_arg _ h).trans $ (smul_mul_assoc _ _ _).symm) lemma commute.smul_left [has_mul α] [smul_comm_class M α α] [is_scalar_tower M α α] {a b : α} (h : commute a b) (r : M) : commute (r • a) b := (h.symm.smul_right r).symm end section ite variables [has_scalar M α] (p : Prop) [decidable p] @[to_additive] lemma ite_smul (a₁ a₂ : M) (b : α) : (ite p a₁ a₂) • b = ite p (a₁ • b) (a₂ • b) := by split_ifs; refl @[to_additive] lemma smul_ite (a : M) (b₁ b₂ : α) : a • (ite p b₁ b₂) = ite p (a • b₁) (a • b₂) := by split_ifs; refl end ite section variables [monoid M] [mul_action M α] @[to_additive] lemma smul_smul (a₁ a₂ : M) (b : α) : a₁ • a₂ • b = (a₁ * a₂) • b := (mul_smul _ _ _).symm variable (M) @[simp, to_additive] theorem one_smul (b : α) : (1 : M) • b = b := mul_action.one_smul _ /-- `has_scalar` version of `one_mul_eq_id` -/ @[to_additive] lemma one_smul_eq_id : ((•) (1 : M) : α → α) = id := funext $ one_smul _ /-- `has_scalar` version of `comp_mul_left` -/ @[to_additive] lemma comp_smul_left (a₁ a₂ : M) : (•) a₁ ∘ (•) a₂ = ((•) (a₁ * a₂) : α → α) := funext $ λ _, (mul_smul _ _ _).symm variables {M} /-- Pullback a multiplicative action along an injective map respecting `•`. See note [reducible non-instances]. -/ @[reducible, to_additive "Pullback an additive action along an injective map respecting `+ᵥ`."] protected def function.injective.mul_action [has_scalar M β] (f : β → α) (hf : injective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) : mul_action M β := { smul := (•), one_smul := λ x, hf $ (smul _ _).trans $ one_smul _ (f x), mul_smul := λ c₁ c₂ x, hf $ by simp only [smul, mul_smul] } /-- Pushforward a multiplicative action along a surjective map respecting `•`. See note [reducible non-instances]. -/ @[reducible, to_additive "Pushforward an additive action along a surjective map respecting `+ᵥ`."] protected def function.surjective.mul_action [has_scalar M β] (f : α → β) (hf : surjective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) : mul_action M β := { smul := (•), one_smul := λ y, by { rcases hf y with ⟨x, rfl⟩, rw [← smul, one_smul] }, mul_smul := λ c₁ c₂ y, by { rcases hf y with ⟨x, rfl⟩, simp only [← smul, mul_smul] } } /-- Push forward the action of `R` on `M` along a compatible surjective map `f : R →* S`. See also `function.surjective.distrib_mul_action_left` and `function.surjective.module_left`. -/ @[reducible, to_additive "Push forward the action of `R` on `M` along a compatible surjective map `f : R →+ S`."] def function.surjective.mul_action_left {R S M : Type*} [monoid R] [mul_action R M] [monoid S] [has_scalar S M] (f : R →* S) (hf : function.surjective f) (hsmul : ∀ c (x : M), f c • x = c • x) : mul_action S M := { smul := (•), one_smul := λ b, by rw [← f.map_one, hsmul, one_smul], mul_smul := hf.forall₂.mpr $ λ a b x, by simp only [← f.map_mul, hsmul, mul_smul] } section variables (M) /-- The regular action of a monoid on itself by left multiplication. This is promoted to a module by `semiring.to_module`. -/ @[priority 910, to_additive] -- see Note [lower instance priority] instance monoid.to_mul_action : mul_action M M := { smul := (*), one_smul := one_mul, mul_smul := mul_assoc } /-- The regular action of a monoid on itself by left addition. This is promoted to an `add_torsor` by `add_group_is_add_torsor`. -/ add_decl_doc add_monoid.to_add_action instance is_scalar_tower.left : is_scalar_tower M M α := ⟨λ x y z, mul_smul x y z⟩ variables {M} /-- Note that the `is_scalar_tower M α α` and `smul_comm_class M α α` typeclass arguments are usually satisfied by `algebra M α`. -/ lemma smul_mul_smul [has_mul α] (r s : M) (x y : α) [is_scalar_tower M α α] [smul_comm_class M α α] : (r • x) * (s • y) = (r * s) • (x * y) := by rw [smul_mul_assoc, mul_smul_comm, ← smul_assoc, smul_eq_mul] end namespace mul_action variables (M α) /-- Embedding of `α` into functions `M → α` induced by a multiplicative action of `M` on `α`. -/ @[to_additive] def to_fun : α ↪ (M → α) := ⟨λ y x, x • y, λ y₁ y₂ H, one_smul M y₁ ▸ one_smul M y₂ ▸ by convert congr_fun H 1⟩ /-- Embedding of `α` into functions `M → α` induced by an additive action of `M` on `α`. -/ add_decl_doc add_action.to_fun variables {M α} @[simp, to_additive] lemma to_fun_apply (x : M) (y : α) : mul_action.to_fun M α y x = x • y := rfl variable (α) /-- A multiplicative action of `M` on `α` and a monoid homomorphism `N → M` induce a multiplicative action of `N` on `α`. See note [reducible non-instances]. -/ @[reducible, to_additive] def comp_hom [monoid N] (g : N →* M) : mul_action N α := { smul := has_scalar.comp.smul g, one_smul := by simp [g.map_one, mul_action.one_smul], mul_smul := by simp [g.map_mul, mul_action.mul_smul] } /-- An additive action of `M` on `α` and an additive monoid homomorphism `N → M` induce an additive action of `N` on `α`. See note [reducible non-instances]. -/ add_decl_doc add_action.comp_hom end mul_action end section compatible_scalar @[simp] lemma smul_one_smul {M} (N) [monoid N] [has_scalar M N] [mul_action N α] [has_scalar M α] [is_scalar_tower M N α] (x : M) (y : α) : (x • (1 : N)) • y = x • y := by rw [smul_assoc, one_smul] @[simp] lemma smul_one_mul {M N} [monoid N] [has_scalar M N] [is_scalar_tower M N N] (x : M) (y : N) : (x • 1) * y = x • y := smul_one_smul N x y @[simp, to_additive] lemma mul_smul_one {M N} [mul_one_class N] [has_scalar M N] [smul_comm_class M N N] (x : M) (y : N) : y * (x • 1) = x • y := by rw [← smul_eq_mul, ← smul_comm, smul_eq_mul, mul_one] lemma is_scalar_tower.of_smul_one_mul {M N} [monoid N] [has_scalar M N] (h : ∀ (x : M) (y : N), (x • (1 : N)) * y = x • y) : is_scalar_tower M N N := ⟨λ x y z, by rw [← h, smul_eq_mul, mul_assoc, h, smul_eq_mul]⟩ @[to_additive] lemma smul_comm_class.of_mul_smul_one {M N} [monoid N] [has_scalar M N] (H : ∀ (x : M) (y : N), y * (x • (1 : N)) = x • y) : smul_comm_class M N N := ⟨λ x y z, by rw [← H x z, smul_eq_mul, ← H, smul_eq_mul, mul_assoc]⟩ end compatible_scalar /-- Typeclass for multiplicative actions on additive structures. This generalizes group modules. -/ @[ext] class distrib_mul_action (M : Type*) (A : Type*) [monoid M] [add_monoid A] extends mul_action M A := (smul_add : ∀(r : M) (x y : A), r • (x + y) = r • x + r • y) (smul_zero : ∀(r : M), r • (0 : A) = 0) section variables [monoid M] [add_monoid A] [distrib_mul_action M A] theorem smul_add (a : M) (b₁ b₂ : A) : a • (b₁ + b₂) = a • b₁ + a • b₂ := distrib_mul_action.smul_add _ _ _ @[simp] theorem smul_zero (a : M) : a • (0 : A) = 0 := distrib_mul_action.smul_zero _ /-- Pullback a distributive multiplicative action along an injective additive monoid homomorphism. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.distrib_mul_action [add_monoid B] [has_scalar M B] (f : B →+ A) (hf : injective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) : distrib_mul_action M B := { smul := (•), smul_add := λ c x y, hf $ by simp only [smul, f.map_add, smul_add], smul_zero := λ c, hf $ by simp only [smul, f.map_zero, smul_zero], .. hf.mul_action f smul } /-- Pushforward a distributive multiplicative action along a surjective additive monoid homomorphism. See note [reducible non-instances]. -/ @[reducible] protected def function.surjective.distrib_mul_action [add_monoid B] [has_scalar M B] (f : A →+ B) (hf : surjective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) : distrib_mul_action M B := { smul := (•), smul_add := λ c x y, by { rcases hf x with ⟨x, rfl⟩, rcases hf y with ⟨y, rfl⟩, simp only [smul_add, ← smul, ← f.map_add] }, smul_zero := λ c, by simp only [← f.map_zero, ← smul, smul_zero], .. hf.mul_action f smul } /-- Push forward the action of `R` on `M` along a compatible surjective map `f : R →* S`. See also `function.surjective.mul_action_left` and `function.surjective.module_left`. -/ @[reducible] def function.surjective.distrib_mul_action_left {R S M : Type*} [monoid R] [add_monoid M] [distrib_mul_action R M] [monoid S] [has_scalar S M] (f : R →* S) (hf : function.surjective f) (hsmul : ∀ c (x : M), f c • x = c • x) : distrib_mul_action S M := { smul := (•), smul_zero := hf.forall.mpr $ λ c, by rw [hsmul, smul_zero], smul_add := hf.forall.mpr $ λ c x y, by simp only [hsmul, smul_add], .. hf.mul_action_left f hsmul } variable (A) /-- Compose a `distrib_mul_action` with a `monoid_hom`, with action `f r' • m`. See note [reducible non-instances]. -/ @[reducible] def distrib_mul_action.comp_hom [monoid N] (f : N →* M) : distrib_mul_action N A := { smul := has_scalar.comp.smul f, smul_zero := λ x, smul_zero (f x), smul_add := λ x, smul_add (f x), .. mul_action.comp_hom A f } /-- Each element of the monoid defines a additive monoid homomorphism. -/ @[simps] def distrib_mul_action.to_add_monoid_hom (x : M) : A →+ A := { to_fun := (•) x, map_zero' := smul_zero x, map_add' := smul_add x } variables (M) /-- Each element of the monoid defines an additive monoid homomorphism. -/ @[simps] def distrib_mul_action.to_add_monoid_End : M →* add_monoid.End A := { to_fun := distrib_mul_action.to_add_monoid_hom A, map_one' := add_monoid_hom.ext $ one_smul M, map_mul' := λ x y, add_monoid_hom.ext $ mul_smul x y } instance add_monoid.nat_smul_comm_class : smul_comm_class ℕ M A := { smul_comm := λ n x y, ((distrib_mul_action.to_add_monoid_hom A x).map_nsmul y n).symm } -- `smul_comm_class.symm` is not registered as an instance, as it would cause a loop instance add_monoid.nat_smul_comm_class' : smul_comm_class M ℕ A := smul_comm_class.symm _ _ _ end section variables [monoid M] [add_group A] [distrib_mul_action M A] instance add_group.int_smul_comm_class : smul_comm_class ℤ M A := { smul_comm := λ n x y, ((distrib_mul_action.to_add_monoid_hom A x).map_zsmul y n).symm } -- `smul_comm_class.symm` is not registered as an instance, as it would cause a loop instance add_group.int_smul_comm_class' : smul_comm_class M ℤ A := smul_comm_class.symm _ _ _ @[simp] theorem smul_neg (r : M) (x : A) : r • (-x) = -(r • x) := eq_neg_of_add_eq_zero_left $ by rw [← smul_add, neg_add_self, smul_zero] theorem smul_sub (r : M) (x y : A) : r • (x - y) = r • x - r • y := by rw [sub_eq_add_neg, sub_eq_add_neg, smul_add, smul_neg] end /-- Typeclass for multiplicative actions on multiplicative structures. This generalizes conjugation actions. -/ @[ext] class mul_distrib_mul_action (M : Type*) (A : Type*) [monoid M] [monoid A] extends mul_action M A := (smul_mul : ∀ (r : M) (x y : A), r • (x * y) = (r • x) * (r • y)) (smul_one : ∀ (r : M), r • (1 : A) = 1) export mul_distrib_mul_action (smul_one) section variables [monoid M] [monoid A] [mul_distrib_mul_action M A] theorem smul_mul' (a : M) (b₁ b₂ : A) : a • (b₁ * b₂) = (a • b₁) * (a • b₂) := mul_distrib_mul_action.smul_mul _ _ _ /-- Pullback a multiplicative distributive multiplicative action along an injective monoid homomorphism. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.mul_distrib_mul_action [monoid B] [has_scalar M B] (f : B →* A) (hf : injective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) : mul_distrib_mul_action M B := { smul := (•), smul_mul := λ c x y, hf $ by simp only [smul, f.map_mul, smul_mul'], smul_one := λ c, hf $ by simp only [smul, f.map_one, smul_one], .. hf.mul_action f smul } /-- Pushforward a multiplicative distributive multiplicative action along a surjective monoid homomorphism. See note [reducible non-instances]. -/ @[reducible] protected def function.surjective.mul_distrib_mul_action [monoid B] [has_scalar M B] (f : A →* B) (hf : surjective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) : mul_distrib_mul_action M B := { smul := (•), smul_mul := λ c x y, by { rcases hf x with ⟨x, rfl⟩, rcases hf y with ⟨y, rfl⟩, simp only [smul_mul', ← smul, ← f.map_mul] }, smul_one := λ c, by simp only [← f.map_one, ← smul, smul_one], .. hf.mul_action f smul } variable (A) /-- Compose a `mul_distrib_mul_action` with a `monoid_hom`, with action `f r' • m`. See note [reducible non-instances]. -/ @[reducible] def mul_distrib_mul_action.comp_hom [monoid N] (f : N →* M) : mul_distrib_mul_action N A := { smul := has_scalar.comp.smul f, smul_one := λ x, smul_one (f x), smul_mul := λ x, smul_mul' (f x), .. mul_action.comp_hom A f } /-- Scalar multiplication by `r` as a `monoid_hom`. -/ def mul_distrib_mul_action.to_monoid_hom (r : M) : A →* A := { to_fun := (•) r, map_one' := smul_one r, map_mul' := smul_mul' r } variable {A} @[simp] lemma mul_distrib_mul_action.to_monoid_hom_apply (r : M) (x : A) : mul_distrib_mul_action.to_monoid_hom A r x = r • x := rfl variables (M A) /-- Each element of the monoid defines a monoid homomorphism. -/ @[simps] def mul_distrib_mul_action.to_monoid_End : M →* monoid.End A := { to_fun := mul_distrib_mul_action.to_monoid_hom A, map_one' := monoid_hom.ext $ one_smul M, map_mul' := λ x y, monoid_hom.ext $ mul_smul x y } end section variables [monoid M] [group A] [mul_distrib_mul_action M A] @[simp] theorem smul_inv' (r : M) (x : A) : r • (x⁻¹) = (r • x)⁻¹ := (mul_distrib_mul_action.to_monoid_hom A r).map_inv x theorem smul_div' (r : M) (x y : A) : r • (x / y) = (r • x) / (r • y) := (mul_distrib_mul_action.to_monoid_hom A r).map_div x y end variable (α) /-- The monoid of endomorphisms. Note that this is generalized by `category_theory.End` to categories other than `Type u`. -/ protected def function.End := α → α instance : monoid (function.End α) := { one := id, mul := (∘), mul_assoc := λ f g h, rfl, mul_one := λ f, rfl, one_mul := λ f, rfl, } instance : inhabited (function.End α) := ⟨1⟩ variable {α} /-- The tautological action by `function.End α` on `α`. This is generalized to bundled endomorphisms by: * `equiv.perm.apply_mul_action` * `add_monoid.End.apply_distrib_mul_action` * `add_aut.apply_distrib_mul_action` * `mul_aut.apply_mul_distrib_mul_action` * `ring_hom.apply_distrib_mul_action` * `linear_equiv.apply_distrib_mul_action` * `linear_map.apply_module` * `ring_hom.apply_mul_semiring_action` * `alg_equiv.apply_mul_semiring_action` -/ instance function.End.apply_mul_action : mul_action (function.End α) α := { smul := ($), one_smul := λ _, rfl, mul_smul := λ _ _ _, rfl } @[simp] lemma function.End.smul_def (f : function.End α) (a : α) : f • a = f a := rfl /-- `function.End.apply_mul_action` is faithful. -/ instance function.End.apply_has_faithful_scalar : has_faithful_scalar (function.End α) α := ⟨λ x y, funext⟩ /-- The tautological action by `add_monoid.End α` on `α`. This generalizes `function.End.apply_mul_action`. -/ instance add_monoid.End.apply_distrib_mul_action [add_monoid α] : distrib_mul_action (add_monoid.End α) α := { smul := ($), smul_zero := add_monoid_hom.map_zero, smul_add := add_monoid_hom.map_add, one_smul := λ _, rfl, mul_smul := λ _ _ _, rfl } @[simp] lemma add_monoid.End.smul_def [add_monoid α] (f : add_monoid.End α) (a : α) : f • a = f a := rfl /-- `add_monoid.End.apply_distrib_mul_action` is faithful. -/ instance add_monoid.End.apply_has_faithful_scalar [add_monoid α] : has_faithful_scalar (add_monoid.End α) α := ⟨add_monoid_hom.ext⟩ /-- The monoid hom representing a monoid action. When `M` is a group, see `mul_action.to_perm_hom`. -/ def mul_action.to_End_hom [monoid M] [mul_action M α] : M →* function.End α := { to_fun := (•), map_one' := funext (one_smul M), map_mul' := λ x y, funext (mul_smul x y) } /-- The monoid action induced by a monoid hom to `function.End α` See note [reducible non-instances]. -/ @[reducible] def mul_action.of_End_hom [monoid M] (f : M →* function.End α) : mul_action M α := mul_action.comp_hom α f /-- The tautological additive action by `additive (function.End α)` on `α`. -/ instance add_action.function_End : add_action (additive (function.End α)) α := { vadd := ($), zero_vadd := λ _, rfl, add_vadd := λ _ _ _, rfl } /-- The additive monoid hom representing an additive monoid action. When `M` is a group, see `add_action.to_perm_hom`. -/ def add_action.to_End_hom [add_monoid M] [add_action M α] : M →+ additive (function.End α) := { to_fun := (+ᵥ), map_zero' := funext (zero_vadd M), map_add' := λ x y, funext (add_vadd x y) } /-- The additive action induced by a hom to `additive (function.End α)` See note [reducible non-instances]. -/ @[reducible] def add_action.of_End_hom [add_monoid M] (f : M →+ additive (function.End α)) : add_action M α := add_action.comp_hom α f
89ba09fbce102c58256a6346ab58c51870f1cc46
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/hom_functor.lean
42b06ff978ecfd5a509123bf2acc9ec08252eada
[ "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
885
lean
/- Copyright (c) 2018 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Scott Morrison -/ import category_theory.products.basic /-! The hom functor, sending `(X, Y)` to the type `X ⟶ Y`. -/ universes v u open opposite open category_theory namespace category_theory.functor variables (C : Type u) [category.{v} C] /-- `functor.hom` is the hom-pairing, sending `(X, Y)` to `X ⟶ Y`, contravariant in `X` and covariant in `Y`. -/ definition hom : Cᵒᵖ × C ⥤ Type v := { obj := λ p, unop p.1 ⟶ p.2, map := λ X Y f, λ h, f.1.unop ≫ h ≫ f.2 } @[simp] lemma hom_obj (X : Cᵒᵖ × C) : (hom C).obj X = (unop X.1 ⟶ X.2) := rfl @[simp] lemma hom_pairing_map {X Y : Cᵒᵖ × C} (f : X ⟶ Y) : (hom C).map f = λ h, f.1.unop ≫ h ≫ f.2 := rfl end category_theory.functor
2d20436511bff2c59c1ee9de9ff7d5705d0e8b9a
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/simplifier13.lean
e12675a886bee4e93daca8e0d13e95fa880483a9
[ "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
346
lean
universe l constants (T : Type.{l}) (f : T → T → T) (g : T → T) constants (P : T → Prop) (Q : Prop) (Hfg : ∀ (x : T), f x x = g x) constants (c : Π (x y z : T), P x → P y → P z → Q) constants (x y z : T) (px : P (f x x)) (py : P (f y y)) (pz : P (g z)) attribute Hfg [simp] #simplify eq env 0 c (f x x) (f y y) (g z) px py pz
fa96568ae0480cf7b53a7c491ff449c47c1c910e
c777c32c8e484e195053731103c5e52af26a25d1
/src/ring_theory/witt_vector/isocrystal.lean
bc06cef87421a8de27bded8a371b9eb30ae2f952
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
8,649
lean
/- Copyright (c) 2022 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth -/ import ring_theory.witt_vector.frobenius_fraction_field /-! ## F-isocrystals over a perfect field When `k` is an integral domain, so is `𝕎 k`, and we can consider its field of fractions `K(p, k)`. The endomorphism `witt_vector.frobenius` lifts to `φ : K(p, k) → K(p, k)`; if `k` is perfect, `φ` is an automorphism. Let `k` be a perfect integral domain. Let `V` be a vector space over `K(p,k)`. An *isocrystal* is a bijective map `V → V` that is `φ`-semilinear. A theorem of Dieudonné and Manin classifies the finite-dimensional isocrystals over algebraically closed fields. In the one-dimensional case, this classification states that the isocrystal structures are parametrized by their "slope" `m : ℤ`. Any one-dimensional isocrystal is isomorphic to `φ(p^m • x) : K(p,k) → K(p,k)` for some `m`. This file proves this one-dimensional case of the classification theorem. The construction is described in Dupuis, Lewis, and Macbeth, [Formalized functional analysis via semilinear maps][dupuis-lewis-macbeth2022]. ## Main declarations * `witt_vector.isocrystal`: a vector space over the field `K(p, k)` additionally equipped with a Frobenius-linear automorphism. * `witt_vector.isocrystal_classification`: a one-dimensional isocrystal admits an isomorphism to one of the standard one-dimensional isocrystals. ## Notation This file introduces notation in the locale `isocrystal`. * `K(p, k)`: `fraction_ring (witt_vector p k)` * `φ(p, k)`: `witt_vector.fraction_ring.frobenius_ring_hom p k` * `M →ᶠˡ[p, k] M₂`: `linear_map (witt_vector.fraction_ring.frobenius_ring_hom p k) M M₂` * `M ≃ᶠˡ[p, k] M₂`: `linear_equiv (witt_vector.fraction_ring.frobenius_ring_hom p k) M M₂` * `Φ(p, k)`: `witt_vector.isocrystal.frobenius p k` * `M →ᶠⁱ[p, k] M₂`: `witt_vector.isocrystal_hom p k M M₂` * `M ≃ᶠⁱ[p, k] M₂`: `witt_vector.isocrystal_equiv p k M M₂` ## References * [Formalized functional analysis via semilinear maps][dupuis-lewis-macbeth2022] * [Theory of commutative formal groups over fields of finite characteristic][manin1963] * <https://www.math.ias.edu/~lurie/205notes/Lecture26-Isocrystals.pdf> -/ noncomputable theory open finite_dimensional namespace witt_vector variables (p : ℕ) [fact p.prime] variables (k : Type*) [comm_ring k] localized "notation (name := witt_vector.fraction_ring) `K(`p`, `k`)` := fraction_ring (witt_vector p k)" in isocrystal section perfect_ring variables [is_domain k] [char_p k p] [perfect_ring k p] /-! ### Frobenius-linear maps -/ /-- The Frobenius automorphism of `k` induces an automorphism of `K`. -/ def fraction_ring.frobenius : K(p, k) ≃+* K(p, k) := is_fraction_ring.field_equiv_of_ring_equiv (frobenius_equiv p k) /-- The Frobenius automorphism of `k` induces an endomorphism of `K`. For notation purposes. -/ def fraction_ring.frobenius_ring_hom : K(p, k) →+* K(p, k) := fraction_ring.frobenius p k localized "notation (name := witt_vector.frobenius_ring_hom) `φ(`p`, `k`)` := witt_vector.fraction_ring.frobenius_ring_hom p k" in isocrystal instance inv_pair₁ : ring_hom_inv_pair (φ(p, k)) _ := ring_hom_inv_pair.of_ring_equiv (fraction_ring.frobenius p k) instance inv_pair₂ : ring_hom_inv_pair ((fraction_ring.frobenius p k).symm : K(p, k) →+* K(p, k)) _ := ring_hom_inv_pair.of_ring_equiv (fraction_ring.frobenius p k).symm localized "notation (name := frobenius_ring_hom.linear_map) M ` →ᶠˡ[`:50 p `, ` k `] ` M₂ := linear_map (witt_vector.fraction_ring.frobenius_ring_hom p k) M M₂" in isocrystal localized "notation (name := frobenius_ring_hom.linear_equiv) M ` ≃ᶠˡ[`:50 p `, ` k `] ` M₂ := linear_equiv (witt_vector.fraction_ring.frobenius_ring_hom p k) M M₂" in isocrystal /-! ### Isocrystals -/ /-- An isocrystal is a vector space over the field `K(p, k)` additionally equipped with a Frobenius-linear automorphism. -/ class isocrystal (V : Type*) [add_comm_group V] extends module K(p, k) V := ( frob : V ≃ᶠˡ[p, k] V ) variables (V : Type*) [add_comm_group V] [isocrystal p k V] variables (V₂ : Type*) [add_comm_group V₂] [isocrystal p k V₂] variables {V} /-- Project the Frobenius automorphism from an isocrystal. Denoted by `Φ(p, k)` when V can be inferred. -/ def isocrystal.frobenius : V ≃ᶠˡ[p, k] V := @isocrystal.frob p _ k _ _ _ _ _ _ _ variables (V) localized "notation `Φ(`p`, `k`)` := witt_vector.isocrystal.frobenius p k" in isocrystal /-- A homomorphism between isocrystals respects the Frobenius map. -/ @[nolint has_nonempty_instance] structure isocrystal_hom extends V →ₗ[K(p, k)] V₂ := ( frob_equivariant : ∀ x : V, Φ(p, k) (to_linear_map x) = to_linear_map (Φ(p, k) x) ) /-- An isomorphism between isocrystals respects the Frobenius map. -/ @[nolint has_nonempty_instance] structure isocrystal_equiv extends V ≃ₗ[K(p, k)] V₂ := ( frob_equivariant : ∀ x : V, Φ(p, k) (to_linear_equiv x) = to_linear_equiv (Φ(p, k) x) ) localized "notation (name := isocrystal_hom) M ` →ᶠⁱ[`:50 p `, ` k `] ` M₂ := witt_vector.isocrystal_hom p k M M₂" in isocrystal localized "notation (name := isocrystal_equiv) M ` ≃ᶠⁱ[`:50 p `, ` k `] ` M₂ := witt_vector.isocrystal_equiv p k M M₂" in isocrystal end perfect_ring open_locale isocrystal /-! ### Classification of isocrystals in dimension 1 -/ /-- A helper instance for type class inference. -/ local attribute [instance] def fraction_ring.module : module K(p, k) K(p, k) := semiring.to_module /-- Type synonym for `K(p, k)` to carry the standard 1-dimensional isocrystal structure of slope `m : ℤ`. -/ @[nolint unused_arguments has_nonempty_instance, derive [add_comm_group, module K(p, k)]] def standard_one_dim_isocrystal (m : ℤ) : Type* := K(p, k) section perfect_ring variables [is_domain k] [char_p k p] [perfect_ring k p] /-- The standard one-dimensional isocrystal of slope `m : ℤ` is an isocrystal. -/ instance (m : ℤ) : isocrystal p k (standard_one_dim_isocrystal p k m) := { frob := (fraction_ring.frobenius p k).to_semilinear_equiv.trans (linear_equiv.smul_of_ne_zero _ _ _ (zpow_ne_zero m (witt_vector.fraction_ring.p_nonzero p k))) } @[simp] lemma standard_one_dim_isocrystal.frobenius_apply (m : ℤ) (x : standard_one_dim_isocrystal p k m) : Φ(p, k) x = (p:K(p, k)) ^ m • φ(p, k) x := rfl end perfect_ring /-- A one-dimensional isocrystal over an algebraically closed field admits an isomorphism to one of the standard (indexed by `m : ℤ`) one-dimensional isocrystals. -/ theorem isocrystal_classification (k : Type*) [field k] [is_alg_closed k] [char_p k p] (V : Type*) [add_comm_group V] [isocrystal p k V] (h_dim : finrank K(p, k) V = 1) : ∃ (m : ℤ), nonempty (standard_one_dim_isocrystal p k m ≃ᶠⁱ[p, k] V) := begin haveI : nontrivial V := finite_dimensional.nontrivial_of_finrank_eq_succ h_dim, obtain ⟨x, hx⟩ : ∃ x : V, x ≠ 0 := exists_ne 0, have : Φ(p, k) x ≠ 0 := by simpa only [map_zero] using Φ(p,k).injective.ne hx, obtain ⟨a, ha, hax⟩ : ∃ a : K(p, k), a ≠ 0 ∧ Φ(p, k) x = a • x, { rw finrank_eq_one_iff_of_nonzero' x hx at h_dim, obtain ⟨a, ha⟩ := h_dim (Φ(p, k) x), refine ⟨a, _, ha.symm⟩, intros ha', apply this, simp only [←ha, ha', zero_smul] }, obtain ⟨b, hb, m, hmb⟩ := witt_vector.exists_frobenius_solution_fraction_ring p ha, replace hmb : φ(p, k) b * a = p ^ m * b := by convert hmb, use m, let F₀ : standard_one_dim_isocrystal p k m →ₗ[K(p,k)] V := linear_map.to_span_singleton K(p, k) V x, let F : standard_one_dim_isocrystal p k m ≃ₗ[K(p,k)] V, { refine linear_equiv.of_bijective F₀ ⟨_, _⟩, { rw ← linear_map.ker_eq_bot, exact linear_map.ker_to_span_singleton K(p, k) V hx }, { rw ← linear_map.range_eq_top, rw ← (finrank_eq_one_iff_of_nonzero x hx).mp h_dim, rw linear_map.span_singleton_eq_range } }, refine ⟨⟨(linear_equiv.smul_of_ne_zero K(p, k) _ _ hb).trans F, _⟩⟩, intros c, rw [linear_equiv.trans_apply, linear_equiv.trans_apply, linear_equiv.smul_of_ne_zero_apply, linear_equiv.smul_of_ne_zero_apply, linear_equiv.map_smul, linear_equiv.map_smul], simp only [hax, linear_equiv.of_bijective_apply, linear_map.to_span_singleton_apply, linear_equiv.map_smulₛₗ, standard_one_dim_isocrystal.frobenius_apply, algebra.id.smul_eq_mul], simp only [←mul_smul], congr' 1, linear_combination φ(p,k) c * hmb, end end witt_vector
364242cc104e7689d227cf78c4b7ad1a4f7e1d34
63abd62053d479eae5abf4951554e1064a4c45b4
/src/topology/algebra/open_subgroup.lean
5d0b62436c58bc47a6d72232553e7fc88dd33fd1
[ "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
7,369
lean
/- Copyright (c) 2019 Johan Commelin All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import order.filter.lift import topology.opens import topology.algebra.ring open topological_space open_locale topological_space set_option old_structure_cmd true /-- The type of open subgroups of a topological additive group. -/ @[ancestor add_subgroup] structure open_add_subgroup (G : Type*) [add_group G] [topological_space G] extends add_subgroup G := (is_open' : is_open carrier) /-- The type of open subgroups of a topological group. -/ @[ancestor subgroup, to_additive] structure open_subgroup (G : Type*) [group G] [topological_space G] extends subgroup G := (is_open' : is_open carrier) /-- Reinterpret an `open_subgroup` as a `subgroup`. -/ add_decl_doc open_subgroup.to_subgroup /-- Reinterpret an `open_add_subgroup` as an `add_subgroup`. -/ add_decl_doc open_add_subgroup.to_add_subgroup -- Tell Lean that `open_add_subgroup` is a namespace namespace open_add_subgroup end open_add_subgroup namespace open_subgroup open function topological_space variables {G : Type*} [group G] [topological_space G] variables {U V : open_subgroup G} {g : G} @[to_additive] instance has_coe_set : has_coe_t (open_subgroup G) (set G) := ⟨λ U, U.1⟩ @[to_additive] instance : has_mem G (open_subgroup G) := ⟨λ g U, g ∈ (U : set G)⟩ @[to_additive] instance has_coe_subgroup : has_coe_t (open_subgroup G) (subgroup G) := ⟨to_subgroup⟩ @[to_additive] instance has_coe_opens : has_coe_t (open_subgroup G) (opens G) := ⟨λ U, ⟨U, U.is_open'⟩⟩ @[simp, to_additive] lemma mem_coe : g ∈ (U : set G) ↔ g ∈ U := iff.rfl @[simp, to_additive] lemma mem_coe_opens : g ∈ (U : opens G) ↔ g ∈ U := iff.rfl @[simp, to_additive] lemma mem_coe_subgroup : g ∈ (U : subgroup G) ↔ g ∈ U := iff.rfl attribute [norm_cast] mem_coe mem_coe_opens mem_coe_subgroup open_add_subgroup.mem_coe open_add_subgroup.mem_coe_opens open_add_subgroup.mem_coe_add_subgroup @[to_additive] lemma coe_injective : injective (coe : open_subgroup G → set G) := λ U V h, by cases U; cases V; congr; assumption @[ext, to_additive] lemma ext (h : ∀ x, x ∈ U ↔ x ∈ V) : (U = V) := coe_injective $ set.ext h @[to_additive] lemma ext_iff : (U = V) ↔ (∀ x, x ∈ U ↔ x ∈ V) := ⟨λ h x, h ▸ iff.rfl, ext⟩ variable (U) @[to_additive] protected lemma is_open : is_open (U : set G) := U.is_open' @[to_additive] protected lemma one_mem : (1 : G) ∈ U := U.one_mem' @[to_additive] protected lemma inv_mem {g : G} (h : g ∈ U) : g⁻¹ ∈ U := U.inv_mem' h @[to_additive] protected lemma mul_mem {g₁ g₂ : G} (h₁ : g₁ ∈ U) (h₂ : g₂ ∈ U) : g₁ * g₂ ∈ U := U.mul_mem' h₁ h₂ @[to_additive] lemma mem_nhds_one : (U : set G) ∈ 𝓝 (1 : G) := mem_nhds_sets U.is_open U.one_mem variable {U} @[to_additive] instance : has_top (open_subgroup G) := ⟨{ is_open' := is_open_univ, .. (⊤ : subgroup G) }⟩ @[to_additive] instance : inhabited (open_subgroup G) := ⟨⊤⟩ @[to_additive] lemma is_closed [has_continuous_mul G] (U : open_subgroup G) : is_closed (U : set G) := begin refine is_open_iff_forall_mem_open.2 (λ x hx, ⟨(λ y, y * x⁻¹) ⁻¹' U, _, _, _⟩), { intros u hux, simp only [set.mem_preimage, set.mem_compl_iff, mem_coe] at hux hx ⊢, refine mt (λ hu, _) hx, convert U.mul_mem (U.inv_mem hux) hu, simp }, { exact (continuous_mul_right _) _ U.is_open }, { simp [U.one_mem] } end section variables {H : Type*} [group H] [topological_space H] /-- The product of two open subgroups as an open subgroup of the product group. -/ @[to_additive "The product of two open subgroups as an open subgroup of the product group."] def prod (U : open_subgroup G) (V : open_subgroup H) : open_subgroup (G × H) := { carrier := (U : set G).prod (V : set H), is_open' := U.is_open.prod V.is_open, .. (U : subgroup G).prod (V : subgroup H) } end @[to_additive] instance : partial_order (open_subgroup G) := { le := λ U V, ∀ ⦃x⦄, x ∈ U → x ∈ V, .. partial_order.lift (coe : open_subgroup G → set G) coe_injective } @[to_additive] instance : semilattice_inf_top (open_subgroup G) := { inf := λ U V, { is_open' := is_open_inter U.is_open V.is_open, .. (U : subgroup G) ⊓ V }, inf_le_left := λ U V, set.inter_subset_left _ _, inf_le_right := λ U V, set.inter_subset_right _ _, le_inf := λ U V W hV hW, set.subset_inter hV hW, top := ⊤, le_top := λ U, set.subset_univ _, ..open_subgroup.partial_order } @[simp, to_additive] lemma coe_inf : (↑(U ⊓ V) : set G) = (U : set G) ∩ V := rfl @[simp, to_additive] lemma coe_subset : (U : set G) ⊆ V ↔ U ≤ V := iff.rfl @[simp, to_additive] lemma coe_subgroup_le : (U : subgroup G) ≤ (V : subgroup G) ↔ U ≤ V := iff.rfl attribute [norm_cast] coe_inf coe_subset coe_subgroup_le open_add_subgroup.coe_inf open_add_subgroup.coe_subset open_add_subgroup.coe_add_subgroup_le end open_subgroup namespace subgroup variables {G : Type*} [group G] [topological_space G] [has_continuous_mul G] (H : subgroup G) @[to_additive] lemma is_open_of_mem_nhds {g : G} (hg : (H : set G) ∈ 𝓝 g) : is_open (H : set G) := begin simp only [is_open_iff_mem_nhds, subgroup.mem_coe] at hg ⊢, intros x hx, have : filter.tendsto (λ y, y * (x⁻¹ * g)) (𝓝 x) (𝓝 $ x * (x⁻¹ * g)) := (continuous_id.mul continuous_const).tendsto _, rw [mul_inv_cancel_left] at this, have := filter.mem_map.1 (this hg), replace hg : g ∈ H := subgroup.mem_coe.1 (mem_of_nhds hg), simp only [subgroup.mem_coe, H.mul_mem_cancel_right (H.mul_mem (H.inv_mem hx) hg)] at this, exact this end @[to_additive] lemma is_open_of_open_subgroup {U : open_subgroup G} (h : U.1 ≤ H) : is_open (H : set G) := H.is_open_of_mem_nhds (filter.mem_sets_of_superset U.mem_nhds_one h) @[to_additive] lemma is_open_mono {H₁ H₂ : subgroup G} (h : H₁ ≤ H₂) (h₁ : is_open (H₁ :set G)) : is_open (H₂ : set G) := @is_open_of_open_subgroup _ _ _ _ H₂ { is_open' := h₁, .. H₁ } h end subgroup namespace open_subgroup variables {G : Type*} [group G] [topological_space G] [has_continuous_mul G] @[to_additive] instance : semilattice_sup_top (open_subgroup G) := { sup := λ U V, { is_open' := show is_open (((U : subgroup G) ⊔ V : subgroup G) : set G), from subgroup.is_open_mono le_sup_left U.is_open, .. ((U : subgroup G) ⊔ V) }, le_sup_left := λ U V, coe_subgroup_le.1 le_sup_left, le_sup_right := λ U V, coe_subgroup_le.1 le_sup_right, sup_le := λ U V W hU hV, coe_subgroup_le.1 (sup_le hU hV), ..open_subgroup.semilattice_inf_top } end open_subgroup namespace submodule open open_add_subgroup variables {R : Type*} {M : Type*} [comm_ring R] variables [add_comm_group M] [topological_space M] [topological_add_group M] [module R M] lemma is_open_mono {U P : submodule R M} (h : U ≤ P) (hU : is_open (U : set M)) : is_open (P : set M) := @add_subgroup.is_open_mono M _ _ _ U.to_add_subgroup P.to_add_subgroup h hU end submodule namespace ideal variables {R : Type*} [comm_ring R] variables [topological_space R] [topological_ring R] lemma is_open_of_open_subideal {U I : ideal R} (h : U ≤ I) (hU : is_open (U : set R)) : is_open (I : set R) := submodule.is_open_mono h hU end ideal
82c842f95b485a1c245240559ed86ab2f9b6cc93
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/module/localized_module.lean
7df4bd5427c3bc969e24b7767158e2102ee2d9f8
[ "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
41,335
lean
/- Copyright (c) 2022 Jujian Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang, Jujian Zhang -/ import group_theory.monoid_localization import ring_theory.localization.basic import algebra.algebra.restrict_scalars /-! # Localized Module > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Given a commutative ring `R`, a multiplicative subset `S ⊆ R` and an `R`-module `M`, we can localize `M` by `S`. This gives us a `localization S`-module. ## Main definitions * `localized_module.r` : the equivalence relation defining this localization, namely `(m, s) ≈ (m', s')` if and only if if there is some `u : S` such that `u • s' • m = u • s • m'`. * `localized_module M S` : the localized module by `S`. * `localized_module.mk` : the canonical map sending `(m, s) : M × S ↦ m/s : localized_module M S` * `localized_module.lift_on` : any well defined function `f : M × S → α` respecting `r` descents to a function `localized_module M S → α` * `localized_module.lift_on₂` : any well defined function `f : M × S → M × S → α` respecting `r` descents to a function `localized_module M S → localized_module M S` * `localized_module.mk_add_mk` : in the localized module `mk m s + mk m' s' = mk (s' • m + s • m') (s * s')` * `localized_module.mk_smul_mk` : in the localized module, for any `r : R`, `s t : S`, `m : M`, we have `mk r s • mk m t = mk (r • m) (s * t)` where `mk r s : localization S` is localized ring by `S`. * `localized_module.is_module` : `localized_module M S` is a `localization S`-module. ## Future work * Redefine `localization` for monoids and rings to coincide with `localized_module`. -/ namespace localized_module universes u v variables {R : Type u} [comm_semiring R] (S : submonoid R) variables (M : Type v) [add_comm_monoid M] [module R M] /--The equivalence relation on `M × S` where `(m1, s1) ≈ (m2, s2)` if and only if for some (u : S), u * (s2 • m1 - s1 • m2) = 0-/ def r (a b : M × S) : Prop := ∃ (u : S), u • b.2 • a.1 = u • a.2 • b.1 lemma r.is_equiv : is_equiv _ (r S M) := { refl := λ ⟨m, s⟩, ⟨1, by rw [one_smul]⟩, trans := λ ⟨m1, s1⟩ ⟨m2, s2⟩ ⟨m3, s3⟩ ⟨u1, hu1⟩ ⟨u2, hu2⟩, begin use u1 * u2 * s2, -- Put everything in the same shape, sorting the terms using `simp` have hu1' := congr_arg ((•) (u2 * s3)) hu1.symm, have hu2' := congr_arg ((•) (u1 * s1)) hu2.symm, simp only [← mul_smul, smul_assoc, mul_assoc, mul_comm, mul_left_comm] at ⊢ hu1' hu2', rw [hu2', hu1'] end, symm := λ ⟨m1, s1⟩ ⟨m2, s2⟩ ⟨u, hu⟩, ⟨u, hu.symm⟩ } instance r.setoid : setoid (M × S) := { r := r S M, iseqv := ⟨(r.is_equiv S M).refl, (r.is_equiv S M).symm, (r.is_equiv S M).trans⟩ } -- TODO: change `localization` to use `r'` instead of `r` so that the two types are also defeq, -- `localization S = localized_module S R`. example {R} [comm_semiring R] (S : submonoid R) : ⇑(localization.r' S) = localized_module.r S R := rfl /-- If `S` is a multiplicative subset of a ring `R` and `M` an `R`-module, then we can localize `M` by `S`. -/ @[nolint has_nonempty_instance] def _root_.localized_module : Type (max u v) := quotient (r.setoid S M) section variables {M S} /--The canonical map sending `(m, s) ↦ m/s`-/ def mk (m : M) (s : S) : localized_module S M := quotient.mk ⟨m, s⟩ lemma mk_eq {m m' : M} {s s' : S} : mk m s = mk m' s' ↔ ∃ (u : S), u • s' • m = u • s • m' := quotient.eq @[elab_as_eliminator] lemma induction_on {β : localized_module S M → Prop} (h : ∀ (m : M) (s : S), β (mk m s)) : ∀ (x : localized_module S M), β x := by { rintro ⟨⟨m, s⟩⟩, exact h m s } @[elab_as_eliminator] lemma induction_on₂ {β : localized_module S M → localized_module S M → Prop} (h : ∀ (m m' : M) (s s' : S), β (mk m s) (mk m' s')) : ∀ x y, β x y := by { rintro ⟨⟨m, s⟩⟩ ⟨⟨m', s'⟩⟩, exact h m m' s s' } /--If `f : M × S → α` respects the equivalence relation `localized_module.r`, then `f` descents to a map `localized_module M S → α`. -/ def lift_on {α : Type*} (x : localized_module S M) (f : M × S → α) (wd : ∀ (p p' : M × S) (h1 : p ≈ p'), f p = f p') : α := quotient.lift_on x f wd lemma lift_on_mk {α : Type*} {f : M × S → α} (wd : ∀ (p p' : M × S) (h1 : p ≈ p'), f p = f p') (m : M) (s : S) : lift_on (mk m s) f wd = f ⟨m, s⟩ := by convert quotient.lift_on_mk f wd ⟨m, s⟩ /--If `f : M × S → M × S → α` respects the equivalence relation `localized_module.r`, then `f` descents to a map `localized_module M S → localized_module M S → α`. -/ def lift_on₂ {α : Type*} (x y : localized_module S M) (f : (M × S) → (M × S) → α) (wd : ∀ (p q p' q' : M × S) (h1 : p ≈ p') (h2 : q ≈ q'), f p q = f p' q') : α := quotient.lift_on₂ x y f wd lemma lift_on₂_mk {α : Type*} (f : (M × S) → (M × S) → α) (wd : ∀ (p q p' q' : M × S) (h1 : p ≈ p') (h2 : q ≈ q'), f p q = f p' q') (m m' : M) (s s' : S) : lift_on₂ (mk m s) (mk m' s') f wd = f ⟨m, s⟩ ⟨m', s'⟩ := by convert quotient.lift_on₂_mk f wd _ _ instance : has_zero (localized_module S M) := ⟨mk 0 1⟩ @[simp] lemma zero_mk (s : S) : mk (0 : M) s = 0 := mk_eq.mpr ⟨1, by rw [one_smul, smul_zero, smul_zero, one_smul]⟩ instance : has_add (localized_module S M) := { add := λ p1 p2, lift_on₂ p1 p2 (λ x y, mk (y.2 • x.1 + x.2 • y.1) (x.2 * y.2)) $ λ ⟨m1, s1⟩ ⟨m2, s2⟩ ⟨m1', s1'⟩ ⟨m2', s2'⟩ ⟨u1, hu1⟩ ⟨u2, hu2⟩, mk_eq.mpr ⟨u1 * u2, begin -- Put everything in the same shape, sorting the terms using `simp` have hu1' := congr_arg ((•) (u2 * s2 * s2')) hu1, have hu2' := congr_arg ((•) (u1 * s1 * s1')) hu2, simp only [smul_add, ← mul_smul, smul_assoc, mul_assoc, mul_comm, mul_left_comm] at ⊢ hu1' hu2', rw [hu1', hu2'] end⟩ } lemma mk_add_mk {m1 m2 : M} {s1 s2 : S} : mk m1 s1 + mk m2 s2 = mk (s2 • m1 + s1 • m2) (s1 * s2) := mk_eq.mpr $ ⟨1, by dsimp only; rw [one_smul]⟩ private lemma add_assoc' (x y z : localized_module S M) : x + y + z = x + (y + z) := begin induction x using localized_module.induction_on with mx sx, induction y using localized_module.induction_on with my sy, induction z using localized_module.induction_on with mz sz, simp only [mk_add_mk, smul_add], refine mk_eq.mpr ⟨1, _⟩, rw [one_smul, one_smul], congr' 1, { rw [mul_assoc] }, { rw [eq_comm, mul_comm, add_assoc, mul_smul, mul_smul, ←mul_smul sx sz, mul_comm, mul_smul], }, end private lemma add_comm' (x y : localized_module S M) : x + y = y + x := localized_module.induction_on₂ (λ m m' s s', by rw [mk_add_mk, mk_add_mk, add_comm, mul_comm]) x y private lemma zero_add' (x : localized_module S M) : 0 + x = x := induction_on (λ m s, by rw [← zero_mk s, mk_add_mk, smul_zero, zero_add, mk_eq]; exact ⟨1, by rw [one_smul, mul_smul, one_smul]⟩) x private lemma add_zero' (x : localized_module S M) : x + 0 = x := induction_on (λ m s, by rw [← zero_mk s, mk_add_mk, smul_zero, add_zero, mk_eq]; exact ⟨1, by rw [one_smul, mul_smul, one_smul]⟩) x instance has_nat_smul : has_smul ℕ (localized_module S M) := { smul := λ n, nsmul_rec n } private lemma nsmul_zero' (x : localized_module S M) : (0 : ℕ) • x = 0 := localized_module.induction_on (λ _ _, rfl) x private lemma nsmul_succ' (n : ℕ) (x : localized_module S M) : n.succ • x = x + n • x := localized_module.induction_on (λ _ _, rfl) x instance : add_comm_monoid (localized_module S M) := { add := (+), add_assoc := add_assoc', zero := 0, zero_add := zero_add', add_zero := add_zero', nsmul := (•), nsmul_zero' := nsmul_zero', nsmul_succ' := nsmul_succ', add_comm := add_comm' } instance {M : Type*} [add_comm_group M] [module R M] : add_comm_group (localized_module S M) := { neg := λ p, lift_on p (λ x, localized_module.mk (-x.1) x.2) (λ ⟨m1, s1⟩ ⟨m2, s2⟩ ⟨u, hu⟩, by { rw mk_eq, exact ⟨u, by simpa⟩ }), add_left_neg := λ p, begin obtain ⟨⟨m, s⟩, rfl : mk m s = p⟩ := quotient.exists_rep p, change (mk m s).lift_on (λ x, mk (-x.1) x.2) (λ ⟨m1, s1⟩ ⟨m2, s2⟩ ⟨u, hu⟩, by { rw mk_eq, exact ⟨u, by simpa⟩ }) + mk m s = 0, rw [lift_on_mk, mk_add_mk], simp end, ..(show add_comm_monoid (localized_module S M), by apply_instance) } lemma mk_neg {M : Type*} [add_comm_group M] [module R M] {m : M} {s : S} : mk (-m) s = - mk m s := rfl instance {A : Type*} [semiring A] [algebra R A] {S : submonoid R} : semiring (localized_module S A) := { mul := λ m₁ m₂, lift_on₂ m₁ m₂ (λ x₁ x₂, localized_module.mk (x₁.1 * x₂.1) (x₁.2 * x₂.2)) (begin rintros ⟨a₁, s₁⟩ ⟨a₂, s₂⟩ ⟨b₁, t₁⟩ ⟨b₂, t₂⟩ ⟨u₁, e₁⟩ ⟨u₂, e₂⟩, rw mk_eq, use u₁ * u₂, dsimp only at ⊢ e₁ e₂, rw eq_comm, transitivity (u₁ • t₁ • a₁) • u₂ • t₂ • a₂, rw [e₁, e₂], swap, rw eq_comm, all_goals { rw [smul_smul, mul_mul_mul_comm, ← smul_eq_mul, ← smul_eq_mul A, smul_smul_smul_comm, mul_smul, mul_smul] } end), left_distrib := begin intros x₁ x₂ x₃, obtain ⟨⟨a₁, s₁⟩, rfl : mk a₁ s₁ = x₁⟩ := quotient.exists_rep x₁, obtain ⟨⟨a₂, s₂⟩, rfl : mk a₂ s₂ = x₂⟩ := quotient.exists_rep x₂, obtain ⟨⟨a₃, s₃⟩, rfl : mk a₃ s₃ = x₃⟩ := quotient.exists_rep x₃, apply mk_eq.mpr _, use 1, simp only [one_mul, smul_add, mul_add, mul_smul_comm, smul_smul, ← mul_assoc, mul_right_comm] end, right_distrib := begin intros x₁ x₂ x₃, obtain ⟨⟨a₁, s₁⟩, rfl : mk a₁ s₁ = x₁⟩ := quotient.exists_rep x₁, obtain ⟨⟨a₂, s₂⟩, rfl : mk a₂ s₂ = x₂⟩ := quotient.exists_rep x₂, obtain ⟨⟨a₃, s₃⟩, rfl : mk a₃ s₃ = x₃⟩ := quotient.exists_rep x₃, apply mk_eq.mpr _, use 1, simp only [one_mul, smul_add, add_mul, smul_smul, ← mul_assoc, smul_mul_assoc, mul_right_comm], end, zero_mul := begin intros x, obtain ⟨⟨a, s⟩, rfl : mk a s = x⟩ := quotient.exists_rep x, exact mk_eq.mpr ⟨1, by simp only [zero_mul, smul_zero]⟩, end, mul_zero := begin intros x, obtain ⟨⟨a, s⟩, rfl : mk a s = x⟩ := quotient.exists_rep x, exact mk_eq.mpr ⟨1, by simp only [mul_zero, smul_zero]⟩, end, mul_assoc := begin intros x₁ x₂ x₃, obtain ⟨⟨a₁, s₁⟩, rfl : mk a₁ s₁ = x₁⟩ := quotient.exists_rep x₁, obtain ⟨⟨a₂, s₂⟩, rfl : mk a₂ s₂ = x₂⟩ := quotient.exists_rep x₂, obtain ⟨⟨a₃, s₃⟩, rfl : mk a₃ s₃ = x₃⟩ := quotient.exists_rep x₃, apply mk_eq.mpr _, use 1, simp only [one_mul, smul_smul, ← mul_assoc, mul_right_comm], end, one := mk 1 (1 : S), one_mul := begin intros x, obtain ⟨⟨a, s⟩, rfl : mk a s = x⟩ := quotient.exists_rep x, exact mk_eq.mpr ⟨1, by simp only [one_mul, one_smul]⟩, end, mul_one := begin intros x, obtain ⟨⟨a, s⟩, rfl : mk a s = x⟩ := quotient.exists_rep x, exact mk_eq.mpr ⟨1, by simp only [mul_one, one_smul]⟩, end, ..(show add_comm_monoid (localized_module S A), by apply_instance) } instance {A : Type*} [comm_semiring A] [algebra R A] {S : submonoid R} : comm_semiring (localized_module S A) := { mul_comm := begin intros x₁ x₂, obtain ⟨⟨a₁, s₁⟩, rfl : mk a₁ s₁ = x₁⟩ := quotient.exists_rep x₁, obtain ⟨⟨a₂, s₂⟩, rfl : mk a₂ s₂ = x₂⟩ := quotient.exists_rep x₂, exact mk_eq.mpr ⟨1, by simp only [one_smul, mul_comm]⟩ end, ..(show semiring (localized_module S A), by apply_instance) } instance {A : Type*} [ring A] [algebra R A] {S : submonoid R} : ring (localized_module S A) := { ..(show add_comm_group (localized_module S A), by apply_instance), ..(show monoid (localized_module S A), by apply_instance), ..(show distrib (localized_module S A), by apply_instance) } instance {A : Type*} [comm_ring A] [algebra R A] {S : submonoid R} : comm_ring (localized_module S A) := { mul_comm := begin intros x₁ x₂, obtain ⟨⟨a₁, s₁⟩, rfl : mk a₁ s₁ = x₁⟩ := quotient.exists_rep x₁, obtain ⟨⟨a₂, s₂⟩, rfl : mk a₂ s₂ = x₂⟩ := quotient.exists_rep x₂, exact mk_eq.mpr ⟨1, by simp only [one_smul, mul_comm]⟩ end, ..(show ring (localized_module S A), by apply_instance) } lemma mk_mul_mk {A : Type*} [semiring A] [algebra R A] {a₁ a₂ : A} {s₁ s₂ : S} : mk a₁ s₁ * mk a₂ s₂ = mk (a₁ * a₂) (s₁ * s₂) := rfl instance : has_smul (localization S) (localized_module S M) := { smul := λ f x, localization.lift_on f (λ r s, lift_on x (λ p, mk (r • p.1) (s * p.2)) begin rintros ⟨m1, t1⟩ ⟨m2, t2⟩ ⟨u, h⟩, refine mk_eq.mpr ⟨u, _⟩, have h' := congr_arg ((•) (s • r)) h, simp only [← mul_smul, smul_assoc, mul_comm, mul_left_comm, submonoid.smul_def, submonoid.coe_mul] at ⊢ h', rw h', end) begin induction x using localized_module.induction_on with m t, rintros r r' s s' h, simp only [lift_on_mk, lift_on_mk, mk_eq], obtain ⟨u, eq1⟩ := localization.r_iff_exists.mp h, use u, have eq1' := congr_arg (• (t • m)) eq1, simp only [← mul_smul, smul_assoc, submonoid.smul_def, submonoid.coe_mul] at ⊢ eq1', ring_nf at ⊢ eq1', rw eq1' end } lemma mk_smul_mk (r : R) (m : M) (s t : S) : localization.mk r s • mk m t = mk (r • m) (s * t) := begin unfold has_smul.smul, rw [localization.lift_on_mk, lift_on_mk], end private lemma one_smul' (m : localized_module S M) : (1 : localization S) • m = m := begin induction m using localized_module.induction_on with m s, rw [← localization.mk_one, mk_smul_mk, one_smul, one_mul], end private lemma mul_smul' (x y : localization S) (m : localized_module S M) : (x * y) • m = x • y • m := begin induction x using localization.induction_on with data, induction y using localization.induction_on with data', rcases ⟨data, data'⟩ with ⟨⟨r, s⟩, ⟨r', s'⟩⟩, induction m using localized_module.induction_on with m t, rw [localization.mk_mul, mk_smul_mk, mk_smul_mk, mk_smul_mk, mul_smul, mul_assoc], end private lemma smul_add' (x : localization S) (y z : localized_module S M) : x • (y + z) = x • y + x • z := begin induction x using localization.induction_on with data, rcases data with ⟨r, u⟩, induction y using localized_module.induction_on with m s, induction z using localized_module.induction_on with n t, rw [mk_smul_mk, mk_smul_mk, mk_add_mk, mk_smul_mk, mk_add_mk, mk_eq], use 1, simp only [one_smul, smul_add, ← mul_smul, submonoid.smul_def, submonoid.coe_mul], ring_nf end private lemma smul_zero' (x : localization S) : x • (0 : localized_module S M) = 0 := begin induction x using localization.induction_on with data, rcases data with ⟨r, s⟩, rw [←zero_mk s, mk_smul_mk, smul_zero, zero_mk, zero_mk], end private lemma add_smul' (x y : localization S) (z : localized_module S M) : (x + y) • z = x • z + y • z := begin induction x using localization.induction_on with datax, induction y using localization.induction_on with datay, induction z using localized_module.induction_on with m t, rcases ⟨datax, datay⟩ with ⟨⟨r, s⟩, ⟨r', s'⟩⟩, rw [localization.add_mk, mk_smul_mk, mk_smul_mk, mk_smul_mk, mk_add_mk, mk_eq], use 1, simp only [one_smul, add_smul, smul_add, ← mul_smul, submonoid.smul_def, submonoid.coe_mul, submonoid.coe_one], rw add_comm, -- Commutativity of addition in the module is not applied by `ring`. ring_nf, end private lemma zero_smul' (x : localized_module S M) : (0 : localization S) • x = 0 := begin induction x using localized_module.induction_on with m s, rw [← localization.mk_zero s, mk_smul_mk, zero_smul, zero_mk], end instance is_module : module (localization S) (localized_module S M) := { smul := (•), one_smul := one_smul', mul_smul := mul_smul', smul_add := smul_add', smul_zero := smul_zero', add_smul := add_smul', zero_smul := zero_smul' } @[simp] lemma mk_cancel_common_left (s' s : S) (m : M) : mk (s' • m) (s' * s) = mk m s := mk_eq.mpr ⟨1, by { simp only [mul_smul, one_smul], rw smul_comm }⟩ @[simp] lemma mk_cancel (s : S) (m : M) : mk (s • m) s = mk m 1 := mk_eq.mpr ⟨1, by simp⟩ @[simp] lemma mk_cancel_common_right (s s' : S) (m : M) : mk (s' • m) (s * s') = mk m s := mk_eq.mpr ⟨1, by simp [mul_smul]⟩ instance is_module' : module R (localized_module S M) := { ..module.comp_hom (localized_module S M) $ (algebra_map R (localization S)) } lemma smul'_mk (r : R) (s : S) (m : M) : r • mk m s = mk (r • m) s := by erw [mk_smul_mk r m 1 s, one_mul] instance {A : Type*} [semiring A] [algebra R A] : algebra (localization S) (localized_module S A) := algebra.of_module begin intros r x₁ x₂, obtain ⟨y, s, rfl : is_localization.mk' _ y s = r⟩ := is_localization.mk'_surjective S r, obtain ⟨⟨a₁, s₁⟩, rfl : mk a₁ s₁ = x₁⟩ := quotient.exists_rep x₁, obtain ⟨⟨a₂, s₂⟩, rfl : mk a₂ s₂ = x₂⟩ := quotient.exists_rep x₂, rw [mk_mul_mk, ← localization.mk_eq_mk', mk_smul_mk, mk_smul_mk, mk_mul_mk, mul_assoc, smul_mul_assoc], end begin intros r x₁ x₂, obtain ⟨y, s, rfl : is_localization.mk' _ y s = r⟩ := is_localization.mk'_surjective S r, obtain ⟨⟨a₁, s₁⟩, rfl : mk a₁ s₁ = x₁⟩ := quotient.exists_rep x₁, obtain ⟨⟨a₂, s₂⟩, rfl : mk a₂ s₂ = x₂⟩ := quotient.exists_rep x₂, rw [mk_mul_mk, ← localization.mk_eq_mk', mk_smul_mk, mk_smul_mk, mk_mul_mk, mul_left_comm, mul_smul_comm] end lemma algebra_map_mk {A : Type*} [semiring A] [algebra R A] (a : R) (s : S) : algebra_map _ _ (localization.mk a s) = mk (algebra_map R A a) s := begin rw [algebra.algebra_map_eq_smul_one], change _ • mk _ _ = _, rw [mk_smul_mk, algebra.algebra_map_eq_smul_one, mul_one] end instance : is_scalar_tower R (localization S) (localized_module S M) := restrict_scalars.is_scalar_tower R (localization S) (localized_module S M) instance algebra' {A : Type*} [semiring A] [algebra R A] : algebra R (localized_module S A) := { commutes' := begin intros r x, obtain ⟨⟨a, s⟩, rfl : mk a s = x⟩ := quotient.exists_rep x, dsimp, rw [← localization.mk_one_eq_algebra_map, algebra_map_mk, mk_mul_mk, mk_mul_mk, mul_comm, algebra.commutes], end, smul_def' := begin intros r x, obtain ⟨⟨a, s⟩, rfl : mk a s = x⟩ := quotient.exists_rep x, dsimp, rw [← localization.mk_one_eq_algebra_map, algebra_map_mk, mk_mul_mk, smul'_mk, algebra.smul_def, one_mul], end, ..(algebra_map (localization S) (localized_module S A)).comp (algebra_map R $ localization S), ..(show module R (localized_module S A), by apply_instance) } section variables (S M) /-- The function `m ↦ m / 1` as an `R`-linear map. -/ @[simps] def mk_linear_map : M →ₗ[R] localized_module S M := { to_fun := λ m, mk m 1, map_add' := λ x y, by simp [mk_add_mk], map_smul' := λ r x, (smul'_mk _ _ _).symm } end /-- For any `s : S`, there is an `R`-linear map given by `a/b ↦ a/(b*s)`. -/ @[simps] def div_by (s : S) : localized_module S M →ₗ[R] localized_module S M := { to_fun := λ p, p.lift_on (λ p, mk p.1 (s * p.2)) $ λ ⟨a, b⟩ ⟨a', b'⟩ ⟨c, eq1⟩, mk_eq.mpr ⟨c, begin rw [mul_smul, mul_smul, smul_comm c, eq1, smul_comm s]; apply_instance, end⟩, map_add' := λ x y, x.induction_on₂ (begin intros m₁ m₂ t₁ t₂, simp only [mk_add_mk, localized_module.lift_on_mk, mul_smul, ←smul_add, mul_assoc, mk_cancel_common_left s], rw show s * (t₁ * t₂) = t₁ * (s * t₂), by { ext, simp only [submonoid.coe_mul], ring }, end) y, map_smul' := λ r x, x.induction_on $ by { intros, simp [localized_module.lift_on_mk, smul'_mk] } } lemma div_by_mul_by (s : S) (p : localized_module S M) : div_by s (algebra_map R (module.End R (localized_module S M)) s p) = p := p.induction_on begin intros m t, simp only [localized_module.lift_on_mk, module.algebra_map_End_apply, smul'_mk, div_by_apply], erw mk_cancel_common_left s t, end lemma mul_by_div_by (s : S) (p : localized_module S M) : algebra_map R (module.End R (localized_module S M)) s (div_by s p) = p := p.induction_on begin intros m t, simp only [localized_module.lift_on_mk, div_by_apply, module.algebra_map_End_apply, smul'_mk], erw mk_cancel_common_left s t, end end end localized_module section is_localized_module universes u v variables {R : Type*} [comm_ring R] (S : submonoid R) variables {M M' M'' : Type*} [add_comm_monoid M] [add_comm_monoid M'] [add_comm_monoid M''] variables [module R M] [module R M'] [module R M''] (f : M →ₗ[R] M') (g : M →ₗ[R] M'') /-- The characteristic predicate for localized module. `is_localized_module S f` describes that `f : M ⟶ M'` is the localization map identifying `M'` as `localized_module S M`. -/ class is_localized_module : Prop := (map_units [] : ∀ (x : S), is_unit (algebra_map R (module.End R M') x)) (surj [] : ∀ y : M', ∃ (x : M × S), x.2 • y = f x.1) (eq_iff_exists [] : ∀ {x₁ x₂}, f x₁ = f x₂ ↔ ∃ c : S, c • x₂ = c • x₁) namespace localized_module /-- If `g` is a linear map `M → M''` such that all scalar multiplication by `s : S` is invertible, then there is a linear map `localized_module S M → M''`. -/ noncomputable def lift' (g : M →ₗ[R] M'') (h : ∀ (x : S), is_unit ((algebra_map R (module.End R M'')) x)) : (localized_module S M) → M'' := λ m, m.lift_on (λ p, (h $ p.2).unit⁻¹ $ g p.1) $ λ ⟨m, s⟩ ⟨m', s'⟩ ⟨c, eq1⟩, begin generalize_proofs h1 h2, erw [module.End_algebra_map_is_unit_inv_apply_eq_iff, ←h2.unit⁻¹.1.map_smul], symmetry, erw [module.End_algebra_map_is_unit_inv_apply_eq_iff], dsimp, have : c • s • g m' = c • s' • g m, { erw [←g.map_smul, ←g.map_smul, ←g.map_smul, ←g.map_smul, eq1], refl, }, have : function.injective (h c).unit.inv, { rw function.injective_iff_has_left_inverse, refine ⟨(h c).unit, _⟩, intros x, change ((h c).unit.1 * (h c).unit.inv) x = x, simp only [units.inv_eq_coe_inv, is_unit.mul_coe_inv, linear_map.one_apply], }, apply_fun (h c).unit.inv, erw [units.inv_eq_coe_inv, module.End_algebra_map_is_unit_inv_apply_eq_iff, ←(h c).unit⁻¹.1.map_smul], symmetry, erw [module.End_algebra_map_is_unit_inv_apply_eq_iff, ←g.map_smul, ←g.map_smul, ←g.map_smul, ←g.map_smul, eq1], refl, end lemma lift'_mk (g : M →ₗ[R] M'') (h : ∀ (x : S), is_unit ((algebra_map R (module.End R M'')) x)) (m : M) (s : S) : localized_module.lift' S g h (localized_module.mk m s) = (h s).unit⁻¹.1 (g m) := rfl lemma lift'_add (g : M →ₗ[R] M'') (h : ∀ (x : S), is_unit ((algebra_map R (module.End R M'')) x)) (x y) : localized_module.lift' S g h (x + y) = localized_module.lift' S g h x + localized_module.lift' S g h y := localized_module.induction_on₂ begin intros a a' b b', erw [localized_module.lift'_mk, localized_module.lift'_mk, localized_module.lift'_mk], dsimp, generalize_proofs h1 h2 h3, erw [map_add, module.End_algebra_map_is_unit_inv_apply_eq_iff, smul_add, ←h2.unit⁻¹.1.map_smul, ←h3.unit⁻¹.1.map_smul], congr' 1; symmetry, erw [module.End_algebra_map_is_unit_inv_apply_eq_iff, mul_smul, ←map_smul], refl, erw [module.End_algebra_map_is_unit_inv_apply_eq_iff, mul_comm, mul_smul, ←map_smul], refl, end x y lemma lift'_smul (g : M →ₗ[R] M'') (h : ∀ (x : S), is_unit ((algebra_map R (module.End R M'')) x)) (r : R) (m) : r • localized_module.lift' S g h m = localized_module.lift' S g h (r • m) := m.induction_on begin intros a b, rw [localized_module.lift'_mk, localized_module.smul'_mk, localized_module.lift'_mk], generalize_proofs h1 h2, erw [←h1.unit⁻¹.1.map_smul, ←g.map_smul], end /-- If `g` is a linear map `M → M''` such that all scalar multiplication by `s : S` is invertible, then there is a linear map `localized_module S M → M''`. -/ noncomputable def lift (g : M →ₗ[R] M'') (h : ∀ (x : S), is_unit ((algebra_map R (module.End R M'')) x)) : (localized_module S M) →ₗ[R] M'' := { to_fun := localized_module.lift' S g h, map_add' := localized_module.lift'_add S g h, map_smul' := λ r x, by rw [localized_module.lift'_smul, ring_hom.id_apply] } /-- If `g` is a linear map `M → M''` such that all scalar multiplication by `s : S` is invertible, then `lift g m s = s⁻¹ • g m`. -/ lemma lift_mk (g : M →ₗ[R] M'') (h : ∀ (x : S), is_unit ((algebra_map R (module.End R M'')) x)) (m : M) (s : S) : localized_module.lift S g h (localized_module.mk m s) = (h s).unit⁻¹.1 (g m) := rfl /-- If `g` is a linear map `M → M''` such that all scalar multiplication by `s : S` is invertible, then there is a linear map `lift g ∘ mk_linear_map = g`. -/ lemma lift_comp (g : M →ₗ[R] M'') (h : ∀ (x : S), is_unit ((algebra_map R (module.End R M'')) x)) : (lift S g h).comp (mk_linear_map S M) = g := begin ext x, dsimp, rw localized_module.lift_mk, erw [module.End_algebra_map_is_unit_inv_apply_eq_iff, one_smul], end /-- If `g` is a linear map `M → M''` such that all scalar multiplication by `s : S` is invertible and `l` is another linear map `localized_module S M ⟶ M''` such that `l ∘ mk_linear_map = g` then `l = lift g` -/ lemma lift_unique (g : M →ₗ[R] M'') (h : ∀ (x : S), is_unit ((algebra_map R (module.End R M'')) x)) (l : localized_module S M →ₗ[R] M'') (hl : l.comp (localized_module.mk_linear_map S M) = g) : localized_module.lift S g h = l := begin ext x, induction x using localized_module.induction_on with m s, rw [localized_module.lift_mk], erw [module.End_algebra_map_is_unit_inv_apply_eq_iff, ←hl, linear_map.coe_comp, function.comp_app, localized_module.mk_linear_map_apply, ←l.map_smul, localized_module.smul'_mk], congr' 1, rw localized_module.mk_eq, refine ⟨1, _⟩, simp only [one_smul], refl, end end localized_module instance localized_module_is_localized_module : is_localized_module S (localized_module.mk_linear_map S M) := { map_units := λ s, ⟨⟨algebra_map R (module.End R (localized_module S M)) s, localized_module.div_by s, fun_like.ext _ _ $ localized_module.mul_by_div_by s, fun_like.ext _ _ $ localized_module.div_by_mul_by s⟩, fun_like.ext _ _ $ λ p, p.induction_on $ by { intros, refl }⟩, surj := λ p, p.induction_on begin intros m t, refine ⟨⟨m, t⟩, _⟩, erw [localized_module.smul'_mk, localized_module.mk_linear_map_apply, submonoid.coe_subtype, localized_module.mk_cancel t ], end, eq_iff_exists := λ m1 m2, { mp := λ eq1, by simpa only [eq_comm, one_smul] using localized_module.mk_eq.mp eq1, mpr := λ ⟨c, eq1⟩, localized_module.mk_eq.mpr ⟨c, by simpa only [eq_comm, one_smul] using eq1⟩ } } namespace is_localized_module variable [is_localized_module S f] /-- If `(M', f : M ⟶ M')` satisfies universal property of localized module, there is a canonical map `localized_module S M ⟶ M'`. -/ noncomputable def from_localized_module' : localized_module S M → M' := λ p, p.lift_on (λ x, (is_localized_module.map_units f x.2).unit⁻¹ (f x.1)) begin rintros ⟨a, b⟩ ⟨a', b'⟩ ⟨c, eq1⟩, dsimp, generalize_proofs h1 h2, erw [module.End_algebra_map_is_unit_inv_apply_eq_iff, ←h2.unit⁻¹.1.map_smul, module.End_algebra_map_is_unit_inv_apply_eq_iff', ←linear_map.map_smul, ←linear_map.map_smul], exact (is_localized_module.eq_iff_exists S f).mpr ⟨c, eq1⟩, end @[simp] lemma from_localized_module'_mk (m : M) (s : S) : from_localized_module' S f (localized_module.mk m s) = (is_localized_module.map_units f s).unit⁻¹ (f m) := rfl lemma from_localized_module'_add (x y : localized_module S M) : from_localized_module' S f (x + y) = from_localized_module' S f x + from_localized_module' S f y := localized_module.induction_on₂ begin intros a a' b b', simp only [localized_module.mk_add_mk, from_localized_module'_mk], generalize_proofs h1 h2 h3, erw [module.End_algebra_map_is_unit_inv_apply_eq_iff, smul_add, ←h2.unit⁻¹.1.map_smul, ←h3.unit⁻¹.1.map_smul, map_add], congr' 1, all_goals { erw [module.End_algebra_map_is_unit_inv_apply_eq_iff'] }, { dsimp, erw [mul_smul, f.map_smul], refl, }, { dsimp, erw [mul_comm, f.map_smul, mul_smul], refl, }, end x y lemma from_localized_module'_smul (r : R) (x : localized_module S M) : r • from_localized_module' S f x = from_localized_module' S f (r • x) := localized_module.induction_on begin intros a b, rw [from_localized_module'_mk, localized_module.smul'_mk, from_localized_module'_mk], generalize_proofs h1, erw [f.map_smul, h1.unit⁻¹.1.map_smul], refl, end x /-- If `(M', f : M ⟶ M')` satisfies universal property of localized module, there is a canonical map `localized_module S M ⟶ M'`. -/ noncomputable def from_localized_module : localized_module S M →ₗ[R] M' := { to_fun := from_localized_module' S f, map_add' := from_localized_module'_add S f, map_smul' := λ r x, by rw [from_localized_module'_smul, ring_hom.id_apply] } lemma from_localized_module_mk (m : M) (s : S) : from_localized_module S f (localized_module.mk m s) = (is_localized_module.map_units f s).unit⁻¹ (f m) := rfl lemma from_localized_module.inj : function.injective $ from_localized_module S f := λ x y eq1, begin induction x using localized_module.induction_on with a b, induction y using localized_module.induction_on with a' b', simp only [from_localized_module_mk] at eq1, generalize_proofs h1 h2 at eq1, erw [module.End_algebra_map_is_unit_inv_apply_eq_iff, ←linear_map.map_smul, module.End_algebra_map_is_unit_inv_apply_eq_iff'] at eq1, erw [localized_module.mk_eq, ←is_localized_module.eq_iff_exists S f, f.map_smul, f.map_smul, eq1], refl, end lemma from_localized_module.surj : function.surjective $ from_localized_module S f := λ x, let ⟨⟨m, s⟩, eq1⟩ := is_localized_module.surj S f x in ⟨localized_module.mk m s, by { rw [from_localized_module_mk, module.End_algebra_map_is_unit_inv_apply_eq_iff, ←eq1], refl }⟩ lemma from_localized_module.bij : function.bijective $ from_localized_module S f := ⟨from_localized_module.inj _ _, from_localized_module.surj _ _⟩ /-- If `(M', f : M ⟶ M')` satisfies universal property of localized module, then `M'` is isomorphic to `localized_module S M` as an `R`-module. -/ @[simps] noncomputable def iso : localized_module S M ≃ₗ[R] M' := { ..from_localized_module S f, ..equiv.of_bijective (from_localized_module S f) $ from_localized_module.bij _ _} lemma iso_apply_mk (m : M) (s : S) : iso S f (localized_module.mk m s) = (is_localized_module.map_units f s).unit⁻¹ (f m) := rfl lemma iso_symm_apply_aux (m : M') : (iso S f).symm m = localized_module.mk (is_localized_module.surj S f m).some.1 (is_localized_module.surj S f m).some.2 := begin generalize_proofs _ h2, apply_fun (iso S f) using linear_equiv.injective _, rw [linear_equiv.apply_symm_apply], simp only [iso_apply, linear_map.to_fun_eq_coe, from_localized_module_mk], erw [module.End_algebra_map_is_unit_inv_apply_eq_iff', h2.some_spec], end lemma iso_symm_apply' (m : M') (a : M) (b : S) (eq1 : b • m = f a) : (iso S f).symm m = localized_module.mk a b := (iso_symm_apply_aux S f m).trans $ localized_module.mk_eq.mpr $ begin generalize_proofs h1, erw [←is_localized_module.eq_iff_exists S f, f.map_smul, f.map_smul, ←h1.some_spec, ←mul_smul, mul_comm, mul_smul, eq1], end lemma iso_symm_comp : (iso S f).symm.to_linear_map.comp f = localized_module.mk_linear_map S M := begin ext m, rw [linear_map.comp_apply, localized_module.mk_linear_map_apply], change (iso S f).symm _ = _, rw [iso_symm_apply'], exact one_smul _ _, end /-- If `M'` is a localized module and `g` is a linear map `M' → M''` such that all scalar multiplication by `s : S` is invertible, then there is a linear map `M' → M''`. -/ noncomputable def lift (g : M →ₗ[R] M'') (h : ∀ (x : S), is_unit ((algebra_map R (module.End R M'')) x)) : M' →ₗ[R] M'' := (localized_module.lift S g h).comp (iso S f).symm.to_linear_map lemma lift_comp (g : M →ₗ[R] M'') (h : ∀ (x : S), is_unit ((algebra_map R (module.End R M'')) x)) : (lift S f g h).comp f = g := begin dunfold is_localized_module.lift, rw [linear_map.comp_assoc], convert localized_module.lift_comp S g h, exact iso_symm_comp _ _, end lemma lift_unique (g : M →ₗ[R] M'') (h : ∀ (x : S), is_unit ((algebra_map R (module.End R M'')) x)) (l : M' →ₗ[R] M'') (hl : l.comp f = g) : lift S f g h = l := begin dunfold is_localized_module.lift, rw [localized_module.lift_unique S g h (l.comp (iso S f).to_linear_map), linear_map.comp_assoc, show (iso S f).to_linear_map.comp (iso S f).symm.to_linear_map = linear_map.id, from _, linear_map.comp_id], { rw [linear_equiv.comp_to_linear_map_symm_eq, linear_map.id_comp], }, { rw [linear_map.comp_assoc, ←hl], congr' 1, ext x, erw [from_localized_module_mk, module.End_algebra_map_is_unit_inv_apply_eq_iff, one_smul], }, end /-- Universal property from localized module: If `(M', f : M ⟶ M')` is a localized module then it satisfies the following universal property: For every `R`-module `M''` which every `s : S`-scalar multiplication is invertible and for every `R`-linear map `g : M ⟶ M''`, there is a unique `R`-linear map `l : M' ⟶ M''` such that `l ∘ f = g`. ``` M -----f----> M' | / |g / | / l v / M'' ``` -/ lemma is_universal : ∀ (g : M →ₗ[R] M'') (map_unit : ∀ (x : S), is_unit ((algebra_map R (module.End R M'')) x)), ∃! (l : M' →ₗ[R] M''), l.comp f = g := λ g h, ⟨lift S f g h, lift_comp S f g h, λ l hl, (lift_unique S f g h l hl).symm⟩ lemma ring_hom_ext (map_unit : ∀ (x : S), is_unit ((algebra_map R (module.End R M'')) x)) ⦃j k : M' →ₗ[R] M''⦄ (h : j.comp f = k.comp f) : j = k := by { rw [←lift_unique S f (k.comp f) map_unit j h, lift_unique], refl } /-- If `(M', f)` and `(M'', g)` both satisfy universal property of localized module, then `M', M''` are isomorphic as `R`-module -/ noncomputable def linear_equiv [is_localized_module S g] : M' ≃ₗ[R] M'' := (iso S f).symm.trans (iso S g) variable {S} lemma smul_injective (s : S) : function.injective (λ m : M', s • m) := ((module.End_is_unit_iff _).mp (is_localized_module.map_units f s)).injective lemma smul_inj (s : S) (m₁ m₂ : M') : s • m₁ = s • m₂ ↔ m₁ = m₂ := (smul_injective f s).eq_iff /-- `mk' f m s` is the fraction `m/s` with respect to the localization map `f`. -/ noncomputable def mk' (m : M) (s : S) : M' := from_localized_module S f (localized_module.mk m s) lemma mk'_smul (r : R) (m : M) (s : S) : mk' f (r • m) s = r • mk' f m s := by { delta mk', rw [← localized_module.smul'_mk, linear_map.map_smul] } lemma mk'_add_mk' (m₁ m₂ : M) (s₁ s₂ : S) : mk' f m₁ s₁ + mk' f m₂ s₂ = mk' f (s₂ • m₁ + s₁ • m₂) (s₁ * s₂) := by { delta mk', rw [← map_add, localized_module.mk_add_mk] } @[simp] lemma mk'_zero (s : S) : mk' f 0 s = 0 := by rw [← zero_smul R (0 : M), mk'_smul, zero_smul] variable (S) @[simp] lemma mk'_one (m : M) : mk' f m (1 : S) = f m := by { delta mk', rw [from_localized_module_mk, module.End_algebra_map_is_unit_inv_apply_eq_iff, submonoid.coe_one, one_smul] } variable {S} @[simp] lemma mk'_cancel (m : M) (s : S) : mk' f (s • m) s = f m := by { delta mk', rw [localized_module.mk_cancel, ← mk'_one S f], refl } @[simp] lemma mk'_cancel' (m : M) (s : S) : s • mk' f m s = f m := by rw [submonoid.smul_def, ← mk'_smul, ← submonoid.smul_def, mk'_cancel] @[simp] lemma mk'_cancel_left (m : M) (s₁ s₂ : S) : mk' f (s₁ • m) (s₁ * s₂) = mk' f m s₂ := by { delta mk', rw localized_module.mk_cancel_common_left } @[simp] lemma mk'_cancel_right (m : M) (s₁ s₂ : S) : mk' f (s₂ • m) (s₁ * s₂) = mk' f m s₁ := by { delta mk', rw localized_module.mk_cancel_common_right } lemma mk'_add (m₁ m₂ : M) (s : S) : mk' f (m₁ + m₂) s = mk' f m₁ s + mk' f m₂ s := by { rw [mk'_add_mk', ← smul_add, mk'_cancel_left] } lemma mk'_eq_mk'_iff (m₁ m₂ : M) (s₁ s₂ : S) : mk' f m₁ s₁ = mk' f m₂ s₂ ↔ ∃ s : S, s • s₁ • m₂ = s • s₂ • m₁ := begin delta mk', rw [(from_localized_module.inj S f).eq_iff, localized_module.mk_eq], simp_rw eq_comm end lemma mk'_neg {M M' : Type*} [add_comm_group M] [add_comm_group M'] [module R M] [module R M'] (f : M →ₗ[R] M') [is_localized_module S f] (m : M) (s : S) : mk' f (-m) s = - mk' f m s := by { delta mk', rw [localized_module.mk_neg, map_neg] } lemma mk'_sub {M M' : Type*} [add_comm_group M] [add_comm_group M'] [module R M] [module R M'] (f : M →ₗ[R] M') [is_localized_module S f] (m₁ m₂ : M) (s : S) : mk' f (m₁ - m₂) s = mk' f m₁ s - mk' f m₂ s := by rw [sub_eq_add_neg, sub_eq_add_neg, mk'_add, mk'_neg] lemma mk'_sub_mk' {M M' : Type*} [add_comm_group M] [add_comm_group M'] [module R M] [module R M'] (f : M →ₗ[R] M') [is_localized_module S f] (m₁ m₂ : M) (s₁ s₂ : S) : mk' f m₁ s₁ - mk' f m₂ s₂ = mk' f (s₂ • m₁ - s₁ • m₂) (s₁ * s₂) := by rw [sub_eq_add_neg, ← mk'_neg, mk'_add_mk', smul_neg, ← sub_eq_add_neg] lemma mk'_mul_mk'_of_map_mul {M M' : Type*} [semiring M] [semiring M'] [module R M] [algebra R M'] (f : M →ₗ[R] M') (hf : ∀ m₁ m₂, f (m₁ * m₂) = f m₁ * f m₂) [is_localized_module S f] (m₁ m₂ : M) (s₁ s₂ : S) : mk' f m₁ s₁ * mk' f m₂ s₂ = mk' f (m₁ * m₂) (s₁ * s₂) := begin symmetry, apply (module.End_algebra_map_is_unit_inv_apply_eq_iff _ _ _).mpr, simp_rw [submonoid.coe_mul, ← smul_eq_mul], rw [smul_smul_smul_comm, ← mk'_smul, ← mk'_smul], simp_rw [← submonoid.smul_def, mk'_cancel, smul_eq_mul, hf], end lemma mk'_mul_mk' {M M' : Type*} [semiring M] [semiring M'] [algebra R M] [algebra R M'] (f : M →ₐ[R] M') [is_localized_module S f.to_linear_map] (m₁ m₂ : M) (s₁ s₂ : S) : mk' f.to_linear_map m₁ s₁ * mk' f.to_linear_map m₂ s₂ = mk' f.to_linear_map (m₁ * m₂) (s₁ * s₂) := mk'_mul_mk'_of_map_mul f.to_linear_map f.map_mul m₁ m₂ s₁ s₂ variables {f} @[simp] lemma mk'_eq_iff {m : M} {s : S} {m' : M'} : mk' f m s = m' ↔ f m = s • m' := by rw [← smul_inj f s, submonoid.smul_def, ← mk'_smul, ← submonoid.smul_def, mk'_cancel] @[simp] lemma mk'_eq_zero {m : M} (s : S) : mk' f m s = 0 ↔ f m = 0 := by rw [mk'_eq_iff, smul_zero] variable (f) lemma mk'_eq_zero' {m : M} (s : S) : mk' f m s = 0 ↔ ∃ s' : S, s' • m = 0 := by simp_rw [← mk'_zero f (1 : S), mk'_eq_mk'_iff, smul_zero, one_smul, eq_comm] lemma mk_eq_mk' (s : S) (m : M) : localized_module.mk m s = mk' (localized_module.mk_linear_map S M) m s := by rw [eq_comm, mk'_eq_iff, submonoid.smul_def, localized_module.smul'_mk, ← submonoid.smul_def, localized_module.mk_cancel, localized_module.mk_linear_map_apply] variable (S) lemma eq_zero_iff {m : M} : f m = 0 ↔ ∃ s' : S, s' • m = 0 := (mk'_eq_zero (1 : S)).symm.trans (mk'_eq_zero' f _) lemma mk'_surjective : function.surjective (function.uncurry $ mk' f : M × S → M') := begin intro x, obtain ⟨⟨m, s⟩, e : s • x = f m⟩ := is_localized_module.surj S f x, exact ⟨⟨m, s⟩, mk'_eq_iff.mpr e.symm⟩ end section algebra lemma mk_of_algebra {R S S' : Type*} [comm_ring R] [comm_ring S] [comm_ring S'] [algebra R S] [algebra R S'] (M : submonoid R) (f : S →ₐ[R] S') (h₁ : ∀ x ∈ M, is_unit (algebra_map R S' x)) (h₂ : ∀ y, ∃ (x : S × M), x.2 • y = f x.1) (h₃ : ∀ x, f x = 0 → ∃ m : M, m • x = 0) : is_localized_module M f.to_linear_map := begin replace h₃ := λ x, iff.intro (h₃ x) (λ ⟨⟨m, hm⟩, e⟩, (h₁ m hm).mul_left_cancel $ by { rw ← algebra.smul_def, simpa [submonoid.smul_def] using f.congr_arg e }), constructor, { intro x, rw module.End_is_unit_iff, split, { rintros a b (e : x • a = x • b), simp_rw [submonoid.smul_def, algebra.smul_def] at e, exact (h₁ x x.2).mul_left_cancel e }, { intro a, refine ⟨((h₁ x x.2).unit⁻¹ : _) * a, _⟩, change (x : R) • (_ * a) = _, rw [algebra.smul_def, ← mul_assoc, is_unit.mul_coe_inv, one_mul] } }, { exact h₂ }, { intros, dsimp, rw [eq_comm, ← sub_eq_zero, ← map_sub, h₃], simp_rw [smul_sub, sub_eq_zero] }, end end algebra end is_localized_module end is_localized_module
3c49cad67c550dbdd73d90e0e4b37e459a9c5923
55781f50a9288b13ccfbaca46c185208d861dacc
/src/start-here.lean
cc677dc69face68fd01250b6fe2494bca4750919
[ "Apache-2.0" ]
permissive
kevinsullivan/dms20-old2
ce1ab5a71e73b304e68a0baddf462595589a9b37
f0f6368106f8cf39fa3e8a52ef2e9502914728ed
refs/heads/master
1,607,521,213,167
1,578,793,021,000
1,578,793,021,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
46
lean
import topology.basic #check topological_space
5b4f5946c61d44f9afc8bd2f01cbee5d1488f55e
491068d2ad28831e7dade8d6dff871c3e49d9431
/hott/types/unit.hlean
b77ac5be8a1fa919659f18ea8412f06dac5c2857
[ "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
734
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 Theorems about the unit type -/ open equiv option namespace unit definition unit_equiv_option_empty : unit ≃ option empty := begin fapply equiv.MK, { intro u, exact none}, { intro e, exact star}, { intro e, cases e, reflexivity, contradiction}, { intro u, cases u, reflexivity}, end definition unit_imp_equiv (A : Type) : (unit → A) ≃ A := begin fapply equiv.MK, { intro f, exact f star}, { intro a u, exact a}, { intro a, reflexivity}, { intro f, apply eq_of_homotopy, intro u, cases u, reflexivity}, end end unit
071538eea5944e2098037a527cef682c2d0be1a0
5e3548e65f2c037cb94cd5524c90c623fbd6d46a
/src_icannos_totilas/reduction/cpge_reduction_012_c.lean
6f6e1ba797ac842144398d2fa3b1f436bd8250f9
[]
no_license
ahayat16/lean_exos
d4f08c30adb601a06511a71b5ffb4d22d12ef77f
682f2552d5b04a8c8eb9e4ab15f875a91b03845c
refs/heads/main
1,693,101,073,585
1,636,479,336,000
1,636,479,336,000
415,000,441
0
0
null
null
null
null
UTF-8
Lean
false
false
1,027
lean
import data.real.basic import data.polynomial.derivative import linear_algebra.basic import linear_algebra.finite_dimensional -- On se place dans le R -espace vectoriel E = R[X] . -- (a) Soit H un sous-espace vectoriel de dimension finie et f un endomorphisme de H. Montrer qu'il existe p ∈ N tel que -- ∀k ≥ p, Ker f k+1 = Ker f k. -- -- Soit F un sous-espace vectoriel de E stable par l'opérateur D de dérivation. -- (b) On suppose que F est de dimension finie non nulle. Montrer que l'endomorphisme induit par D sur R n [X] est nilpotent pour tout n ∈ N . -- Montrer qu'il existe m ∈ N tel que F = R m [X] . -- (c) Montrer que si F est de dimension innie alors F = R[X] . -- (d) Soit g ∈ L(E) tel que g^2 = kId + D avec k ∈ R . Quel est le signe de k ? variable F: submodule real (polynomial real) variable HF: forall p: polynomial real, p ∈ F.carrier -> polynomial.derivative p ∈ F.carrier theorem c: (finite_dimensional real F) \/ (exists _: F ≃ₗ[real] polynomial real, true) := sorry
8b04e9651e1ebedd13ddf70a24ded010ae88cda3
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/mv_polynomial/basic_auto.lean
0fa05d00075545cd66d75d7b4ab25453f6027727
[]
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
39,360
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Johan Commelin, Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.polynomial.eval import Mathlib.PostPort universes u_1 u_2 u w v x namespace Mathlib /-! # Multivariate polynomials This file defines polynomial rings over a base ring (or even semiring), with variables from a general type `σ` (which could be infinite). ## Important definitions Let `R` be a commutative ring (or a semiring) and let `σ` be an arbitrary type. This file creates the type `mv_polynomial σ R`, which mathematicians might denote $R[X_i : i \in σ]$. It is the type of multivariate (a.k.a. multivariable) polynomials, with variables corresponding to the terms in `σ`, and coefficients in `R`. ### Notation In the definitions below, we use the following notation: + `σ : Type*` (indexing the variables) + `R : Type*` `[comm_semiring R]` (the coefficients) + `s : σ →₀ ℕ`, a function from `σ` to `ℕ` which is zero away from a finite set. This will give rise to a monomial in `mv_polynomial σ R` which mathematicians might call `X^s` + `a : R` + `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians + `p : mv_polynomial σ R` ### Definitions * `mv_polynomial σ R` : the type of polynomials with variables of type `σ` and coefficients in the commutative semiring `R` * `monomial s a` : the monomial which mathematically would be denoted `a * X^s` * `C a` : the constant polynomial with value `a` * `X i` : the degree one monomial corresponding to i; mathematically this might be denoted `Xᵢ`. * `coeff s p` : the coefficient of `s` in `p`. * `eval₂ (f : R → S₁) (g : σ → S₁) p` : given a semiring homomorphism from `R` to another semiring `S₁`, and a map `σ → S₁`, evaluates `p` at this valuation, returning a term of type `S₁`. Note that `eval₂` can be made using `eval` and `map` (see below), and it has been suggested that sticking to `eval` and `map` might make the code less brittle. * `eval (g : σ → R) p` : given a map `σ → R`, evaluates `p` at this valuation, returning a term of type `R` * `map (f : R → S₁) p` : returns the multivariate polynomial obtained from `p` by the change of coefficient semiring corresponding to `f` ## Implementation notes Recall that if `Y` has a zero, then `X →₀ Y` is the type of functions from `X` to `Y` with finite support, i.e. such that only finitely many elements of `X` get sent to non-zero terms in `Y`. The definition of `mv_polynomial σ R` is `(σ →₀ ℕ) →₀ R` ; here `σ →₀ ℕ` denotes the space of all monomials in the variables, and the function to `R` sends a monomial to its coefficient in the polynomial being represented. ## Tags polynomial, multivariate polynomial, multivariable polynomial -/ /-- Multivariate polynomial, where `σ` is the index set of the variables and `R` is the coefficient ring -/ def mv_polynomial (σ : Type u_1) (R : Type u_2) [comm_semiring R] := add_monoid_algebra R (σ →₀ ℕ) namespace mv_polynomial protected instance decidable_eq_mv_polynomial {R : Type u} {σ : Type u_1} [comm_semiring R] [DecidableEq σ] [DecidableEq R] : DecidableEq (mv_polynomial σ R) := finsupp.finsupp.decidable_eq protected instance comm_semiring {R : Type u} {σ : Type u_1} [comm_semiring R] : comm_semiring (mv_polynomial σ R) := add_monoid_algebra.comm_semiring protected instance inhabited {R : Type u} {σ : Type u_1} [comm_semiring R] : Inhabited (mv_polynomial σ R) := { default := 0 } protected instance has_scalar {R : Type u} {σ : Type u_1} [comm_semiring R] : has_scalar R (mv_polynomial σ R) := add_monoid_algebra.has_scalar protected instance semimodule {R : Type u} {σ : Type u_1} [comm_semiring R] : semimodule R (mv_polynomial σ R) := add_monoid_algebra.semimodule protected instance algebra {R : Type u} {σ : Type u_1} [comm_semiring R] : algebra R (mv_polynomial σ R) := add_monoid_algebra.algebra /-- The coercion turning an `mv_polynomial` into the function which reports the coefficient of a given monomial. -/ def coeff_coe_to_fun {R : Type u} {σ : Type u_1} [comm_semiring R] : has_coe_to_fun (mv_polynomial σ R) := finsupp.has_coe_to_fun /-- `monomial s a` is the monomial with coefficient `a` and exponents given by `s` -/ def monomial {R : Type u} {σ : Type u_1} [comm_semiring R] (s : σ →₀ ℕ) (a : R) : mv_polynomial σ R := finsupp.single s a theorem single_eq_monomial {R : Type u} {σ : Type u_1} [comm_semiring R] (s : σ →₀ ℕ) (a : R) : finsupp.single s a = monomial s a := rfl /-- `C a` is the constant polynomial with value `a` -/ def C {R : Type u} {σ : Type u_1} [comm_semiring R] : R →+* mv_polynomial σ R := ring_hom.mk (monomial 0) sorry sorry sorry sorry theorem algebra_map_eq (R : Type u) (σ : Type u_1) [comm_semiring R] : algebra_map R (mv_polynomial σ R) = C := rfl /-- `X n` is the degree `1` monomial $X_n$. -/ def X {R : Type u} {σ : Type u_1} [comm_semiring R] (n : σ) : mv_polynomial σ R := monomial (finsupp.single n 1) 1 @[simp] theorem C_0 {R : Type u} {σ : Type u_1} [comm_semiring R] : coe_fn C 0 = 0 := sorry @[simp] theorem C_1 {R : Type u} {σ : Type u_1} [comm_semiring R] : coe_fn C 1 = 1 := rfl theorem C_mul_monomial {R : Type u} {σ : Type u_1} {a : R} {a' : R} {s : σ →₀ ℕ} [comm_semiring R] : coe_fn C a * monomial s a' = monomial s (a * a') := sorry @[simp] theorem C_add {R : Type u} {σ : Type u_1} {a : R} {a' : R} [comm_semiring R] : coe_fn C (a + a') = coe_fn C a + coe_fn C a' := finsupp.single_add @[simp] theorem C_mul {R : Type u} {σ : Type u_1} {a : R} {a' : R} [comm_semiring R] : coe_fn C (a * a') = coe_fn C a * coe_fn C a' := Eq.symm C_mul_monomial @[simp] theorem C_pow {R : Type u} {σ : Type u_1} [comm_semiring R] (a : R) (n : ℕ) : coe_fn C (a ^ n) = coe_fn C a ^ n := sorry theorem C_injective (σ : Type u_1) (R : Type u_2) [comm_semiring R] : function.injective ⇑C := finsupp.single_injective 0 theorem C_surjective {R : Type u_1} [comm_semiring R] (σ : Type u_2) (hσ : ¬Nonempty σ) : function.surjective ⇑C := sorry theorem C_surjective_fin_0 {R : Type u_1} [comm_ring R] : function.surjective ⇑C := sorry @[simp] theorem C_inj {σ : Type u_1} (R : Type u_2) [comm_semiring R] (r : R) (s : R) : coe_fn C r = coe_fn C s ↔ r = s := function.injective.eq_iff (C_injective σ R) protected instance infinite_of_infinite (σ : Type u_1) (R : Type u_2) [comm_semiring R] [infinite R] : infinite (mv_polynomial σ R) := infinite.of_injective (⇑C) (C_injective σ R) protected instance infinite_of_nonempty (σ : Type u_1) (R : Type u_2) [Nonempty σ] [comm_semiring R] [nontrivial R] : infinite (mv_polynomial σ R) := sorry theorem C_eq_coe_nat {R : Type u} {σ : Type u_1} [comm_semiring R] (n : ℕ) : coe_fn C ↑n = ↑n := sorry theorem C_mul' {R : Type u} {σ : Type u_1} {a : R} [comm_semiring R] {p : mv_polynomial σ R} : coe_fn C a * p = a • p := sorry theorem smul_eq_C_mul {R : Type u} {σ : Type u_1} [comm_semiring R] (p : mv_polynomial σ R) (a : R) : a • p = coe_fn C a * p := Eq.symm C_mul' theorem X_pow_eq_single {R : Type u} {σ : Type u_1} {e : ℕ} {n : σ} [comm_semiring R] : X n ^ e = monomial (finsupp.single n e) 1 := sorry theorem monomial_add_single {R : Type u} {σ : Type u_1} {a : R} {e : ℕ} {n : σ} {s : σ →₀ ℕ} [comm_semiring R] : monomial (s + finsupp.single n e) a = monomial s a * X n ^ e := sorry theorem monomial_single_add {R : Type u} {σ : Type u_1} {a : R} {e : ℕ} {n : σ} {s : σ →₀ ℕ} [comm_semiring R] : monomial (finsupp.single n e + s) a = X n ^ e * monomial s a := sorry theorem single_eq_C_mul_X {R : Type u} {σ : Type u_1} [comm_semiring R] {s : σ} {a : R} {n : ℕ} : monomial (finsupp.single s n) a = coe_fn C a * X s ^ n := sorry @[simp] theorem monomial_add {R : Type u} {σ : Type u_1} [comm_semiring R] {s : σ →₀ ℕ} {a : R} {b : R} : monomial s a + monomial s b = monomial s (a + b) := sorry @[simp] theorem monomial_mul {R : Type u} {σ : Type u_1} [comm_semiring R] {s : σ →₀ ℕ} {s' : σ →₀ ℕ} {a : R} {b : R} : monomial s a * monomial s' b = monomial (s + s') (a * b) := sorry @[simp] theorem monomial_zero {R : Type u} {σ : Type u_1} [comm_semiring R] {s : σ →₀ ℕ} : monomial s 0 = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (monomial s 0 = 0)) (monomial.equations._eqn_1 s 0))) (eq.mpr (id (Eq._oldrec (Eq.refl (finsupp.single s 0 = 0)) finsupp.single_zero)) (Eq.refl 0)) @[simp] theorem sum_monomial {R : Type u} {σ : Type u_1} [comm_semiring R] {A : Type u_2} [add_comm_monoid A] {u : σ →₀ ℕ} {r : R} {b : (σ →₀ ℕ) → R → A} (w : b u 0 = 0) : finsupp.sum (monomial u r) b = b u r := finsupp.sum_single_index w theorem monomial_eq {R : Type u} {σ : Type u_1} {a : R} {s : σ →₀ ℕ} [comm_semiring R] : monomial s a = coe_fn C a * finsupp.prod s fun (n : σ) (e : ℕ) => X n ^ e := sorry theorem induction_on {R : Type u} {σ : Type u_1} [comm_semiring R] {M : mv_polynomial σ R → Prop} (p : mv_polynomial σ R) (h_C : ∀ (a : R), M (coe_fn C a)) (h_add : ∀ (p q : mv_polynomial σ R), M p → M q → M (p + q)) (h_X : ∀ (p : mv_polynomial σ R) (n : σ), M p → M (p * X n)) : M p := sorry theorem induction_on' {R : Type u} {σ : Type u_1} [comm_semiring R] {P : mv_polynomial σ R → Prop} (p : mv_polynomial σ R) (h1 : ∀ (u : σ →₀ ℕ) (a : R), P (monomial u a)) (h2 : ∀ (p q : mv_polynomial σ R), P p → P q → P (p + q)) : P p := sorry theorem ring_hom_ext {R : Type u} {σ : Type u_1} [comm_semiring R] {A : Type u_2} [semiring A] {f : mv_polynomial σ R →+* A} {g : mv_polynomial σ R →+* A} (hC : ∀ (r : R), coe_fn f (coe_fn C r) = coe_fn g (coe_fn C r)) (hX : ∀ (i : σ), coe_fn f (X i) = coe_fn g (X i)) : f = g := add_monoid_algebra.ring_hom_ext' (ring_hom.ext fun (x : R) => hC x) (finsupp.mul_hom_ext' fun (x : σ) => monoid_hom.ext_mnat (hX x)) theorem hom_eq_hom {R : Type u} {S₂ : Type w} {σ : Type u_1} [comm_semiring R] [semiring S₂] (f : mv_polynomial σ R →+* S₂) (g : mv_polynomial σ R →+* S₂) (hC : ∀ (a : R), coe_fn f (coe_fn C a) = coe_fn g (coe_fn C a)) (hX : ∀ (n : σ), coe_fn f (X n) = coe_fn g (X n)) (p : mv_polynomial σ R) : coe_fn f p = coe_fn g p := ring_hom.congr_fun (ring_hom_ext hC hX) p theorem is_id {R : Type u} {σ : Type u_1} [comm_semiring R] (f : mv_polynomial σ R →+* mv_polynomial σ R) (hC : ∀ (a : R), coe_fn f (coe_fn C a) = coe_fn C a) (hX : ∀ (n : σ), coe_fn f (X n) = X n) (p : mv_polynomial σ R) : coe_fn f p = p := hom_eq_hom f (ring_hom.id (mv_polynomial σ R)) hC hX p theorem alg_hom_ext {R : Type u} {σ : Type u_1} [comm_semiring R] {A : Type u_2} [comm_semiring A] [algebra R A] {f : alg_hom R (mv_polynomial σ R) A} {g : alg_hom R (mv_polynomial σ R) A} (hf : ∀ (i : σ), coe_fn f (X i) = coe_fn g (X i)) : f = g := add_monoid_algebra.alg_hom_ext' (finsupp.mul_hom_ext' fun (x : σ) => monoid_hom.ext_mnat (hf x)) @[simp] theorem alg_hom_C {R : Type u} {σ : Type u_1} [comm_semiring R] (f : alg_hom R (mv_polynomial σ R) (mv_polynomial σ R)) (r : R) : coe_fn f (coe_fn C r) = coe_fn C r := alg_hom.commutes f r -- While setting up `coeff`, we make `mv_polynomial` reducible so we can treat it as a function. /-- The coefficient of the monomial `m` in the multi-variable polynomial `p`. -/ def coeff {R : Type u} {σ : Type u_1} [comm_semiring R] (m : σ →₀ ℕ) (p : mv_polynomial σ R) : R := coe_fn p m theorem ext {R : Type u} {σ : Type u_1} [comm_semiring R] (p : mv_polynomial σ R) (q : mv_polynomial σ R) : (∀ (m : σ →₀ ℕ), coeff m p = coeff m q) → p = q := finsupp.ext theorem ext_iff {R : Type u} {σ : Type u_1} [comm_semiring R] (p : mv_polynomial σ R) (q : mv_polynomial σ R) : p = q ↔ ∀ (m : σ →₀ ℕ), coeff m p = coeff m q := { mp := fun (h : p = q) (m : σ →₀ ℕ) => eq.mpr (id (Eq._oldrec (Eq.refl (coeff m p = coeff m q)) h)) (Eq.refl (coeff m q)), mpr := ext p q } @[simp] theorem coeff_add {R : Type u} {σ : Type u_1} [comm_semiring R] (m : σ →₀ ℕ) (p : mv_polynomial σ R) (q : mv_polynomial σ R) : coeff m (p + q) = coeff m p + coeff m q := finsupp.add_apply @[simp] theorem coeff_zero {R : Type u} {σ : Type u_1} [comm_semiring R] (m : σ →₀ ℕ) : coeff m 0 = 0 := rfl @[simp] theorem coeff_zero_X {R : Type u} {σ : Type u_1} [comm_semiring R] (i : σ) : coeff 0 (X i) = 0 := sorry protected instance coeff.is_add_monoid_hom {R : Type u} {σ : Type u_1} [comm_semiring R] (m : σ →₀ ℕ) : is_add_monoid_hom (coeff m) := is_add_monoid_hom.mk (coeff_zero m) theorem coeff_sum {R : Type u} {σ : Type u_1} [comm_semiring R] {X : Type u_2} (s : finset X) (f : X → mv_polynomial σ R) (m : σ →₀ ℕ) : coeff m (finset.sum s fun (x : X) => f x) = finset.sum s fun (x : X) => coeff m (f x) := Eq.symm (finset.sum_hom s (coeff m)) theorem monic_monomial_eq {R : Type u} {σ : Type u_1} [comm_semiring R] (m : σ →₀ ℕ) : monomial m 1 = finsupp.prod m fun (n : σ) (e : ℕ) => X n ^ e := sorry @[simp] theorem coeff_monomial {R : Type u} {σ : Type u_1} [comm_semiring R] (m : σ →₀ ℕ) (n : σ →₀ ℕ) (a : R) : coeff m (monomial n a) = ite (n = m) a 0 := sorry @[simp] theorem coeff_C {R : Type u} {σ : Type u_1} [comm_semiring R] (m : σ →₀ ℕ) (a : R) : coeff m (coe_fn C a) = ite (0 = m) a 0 := sorry theorem coeff_X_pow {R : Type u} {σ : Type u_1} [comm_semiring R] (i : σ) (m : σ →₀ ℕ) (k : ℕ) : coeff m (X i ^ k) = ite (finsupp.single i k = m) 1 0 := sorry theorem coeff_X' {R : Type u} {σ : Type u_1} [comm_semiring R] (i : σ) (m : σ →₀ ℕ) : coeff m (X i) = ite (finsupp.single i 1 = m) 1 0 := eq.mpr (id (Eq._oldrec (Eq.refl (coeff m (X i) = ite (finsupp.single i 1 = m) 1 0)) (Eq.symm (coeff_X_pow i m 1)))) (eq.mpr (id (Eq._oldrec (Eq.refl (coeff m (X i) = coeff m (X i ^ 1))) (pow_one (X i)))) (Eq.refl (coeff m (X i)))) @[simp] theorem coeff_X {R : Type u} {σ : Type u_1} [comm_semiring R] (i : σ) : coeff (finsupp.single i 1) (X i) = 1 := eq.mpr (id (Eq._oldrec (Eq.refl (coeff (finsupp.single i 1) (X i) = 1)) (coeff_X' i (finsupp.single i 1)))) (eq.mpr (id (Eq._oldrec (Eq.refl (ite (finsupp.single i 1 = finsupp.single i 1) 1 0 = 1)) (if_pos rfl))) (Eq.refl 1)) @[simp] theorem coeff_C_mul {R : Type u} {σ : Type u_1} [comm_semiring R] (m : σ →₀ ℕ) (a : R) (p : mv_polynomial σ R) : coeff m (coe_fn C a * p) = a * coeff m p := sorry theorem coeff_mul {R : Type u} {σ : Type u_1} [comm_semiring R] (p : mv_polynomial σ R) (q : mv_polynomial σ R) (n : σ →₀ ℕ) : coeff n (p * q) = finset.sum (finsupp.support (finsupp.antidiagonal n)) fun (x : (σ →₀ ℕ) × (σ →₀ ℕ)) => coeff (prod.fst x) p * coeff (prod.snd x) q := sorry @[simp] theorem coeff_mul_X {R : Type u} {σ : Type u_1} [comm_semiring R] (m : σ →₀ ℕ) (s : σ) (p : mv_polynomial σ R) : coeff (m + finsupp.single s 1) (p * X s) = coeff m p := sorry theorem coeff_mul_X' {R : Type u} {σ : Type u_1} [comm_semiring R] (m : σ →₀ ℕ) (s : σ) (p : mv_polynomial σ R) : coeff m (p * X s) = ite (s ∈ finsupp.support m) (coeff (m - finsupp.single s 1) p) 0 := sorry theorem eq_zero_iff {R : Type u} {σ : Type u_1} [comm_semiring R] {p : mv_polynomial σ R} : p = 0 ↔ ∀ (d : σ →₀ ℕ), coeff d p = 0 := sorry theorem ne_zero_iff {R : Type u} {σ : Type u_1} [comm_semiring R] {p : mv_polynomial σ R} : p ≠ 0 ↔ ∃ (d : σ →₀ ℕ), coeff d p ≠ 0 := sorry theorem exists_coeff_ne_zero {R : Type u} {σ : Type u_1} [comm_semiring R] {p : mv_polynomial σ R} (h : p ≠ 0) : ∃ (d : σ →₀ ℕ), coeff d p ≠ 0 := iff.mp ne_zero_iff h theorem C_dvd_iff_dvd_coeff {R : Type u} {σ : Type u_1} [comm_semiring R] (r : R) (φ : mv_polynomial σ R) : coe_fn C r ∣ φ ↔ ∀ (i : σ →₀ ℕ), r ∣ coeff i φ := sorry /-- `constant_coeff p` returns the constant term of the polynomial `p`, defined as `coeff 0 p`. This is a ring homomorphism. -/ def constant_coeff {R : Type u} {σ : Type u_1} [comm_semiring R] : mv_polynomial σ R →+* R := ring_hom.mk (coeff 0) sorry sorry sorry sorry theorem constant_coeff_eq {R : Type u} {σ : Type u_1} [comm_semiring R] : ⇑constant_coeff = coeff 0 := rfl @[simp] theorem constant_coeff_C {R : Type u} {σ : Type u_1} [comm_semiring R] (r : R) : coe_fn constant_coeff (coe_fn C r) = r := sorry @[simp] theorem constant_coeff_X {R : Type u} {σ : Type u_1} [comm_semiring R] (i : σ) : coe_fn constant_coeff (X i) = 0 := sorry theorem constant_coeff_monomial {R : Type u} {σ : Type u_1} [comm_semiring R] (d : σ →₀ ℕ) (r : R) : coe_fn constant_coeff (monomial d r) = ite (d = 0) r 0 := eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn constant_coeff (monomial d r) = ite (d = 0) r 0)) constant_coeff_eq)) (eq.mpr (id (Eq._oldrec (Eq.refl (coeff 0 (monomial d r) = ite (d = 0) r 0)) (coeff_monomial 0 d r))) (Eq.refl (ite (d = 0) r 0))) @[simp] theorem constant_coeff_comp_C (R : Type u) (σ : Type u_1) [comm_semiring R] : ring_hom.comp constant_coeff C = ring_hom.id R := ring_hom.ext fun (x : R) => constant_coeff_C x @[simp] theorem constant_coeff_comp_algebra_map (R : Type u) (σ : Type u_1) [comm_semiring R] : ring_hom.comp constant_coeff (algebra_map R (mv_polynomial σ R)) = ring_hom.id R := constant_coeff_comp_C R σ @[simp] theorem support_sum_monomial_coeff {R : Type u} {σ : Type u_1} [comm_semiring R] (p : mv_polynomial σ R) : (finset.sum (finsupp.support p) fun (v : σ →₀ ℕ) => monomial v (coeff v p)) = p := finsupp.sum_single p theorem as_sum {R : Type u} {σ : Type u_1} [comm_semiring R] (p : mv_polynomial σ R) : p = finset.sum (finsupp.support p) fun (v : σ →₀ ℕ) => monomial v (coeff v p) := Eq.symm (support_sum_monomial_coeff p) /-- Evaluate a polynomial `p` given a valuation `g` of all the variables and a ring hom `f` from the scalar ring to the target -/ def eval₂ {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] (f : R →+* S₁) (g : σ → S₁) (p : mv_polynomial σ R) : S₁ := finsupp.sum p fun (s : σ →₀ ℕ) (a : R) => coe_fn f a * finsupp.prod s fun (n : σ) (e : ℕ) => g n ^ e theorem eval₂_eq {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] (g : R →+* S₁) (x : σ → S₁) (f : mv_polynomial σ R) : eval₂ g x f = finset.sum (finsupp.support f) fun (d : σ →₀ ℕ) => coe_fn g (coeff d f) * finset.prod (finsupp.support d) fun (i : σ) => x i ^ coe_fn d i := rfl theorem eval₂_eq' {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] [fintype σ] (g : R →+* S₁) (x : σ → S₁) (f : mv_polynomial σ R) : eval₂ g x f = finset.sum (finsupp.support f) fun (d : σ →₀ ℕ) => coe_fn g (coeff d f) * finset.prod finset.univ fun (i : σ) => x i ^ coe_fn d i := sorry @[simp] theorem eval₂_zero {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] (f : R →+* S₁) (g : σ → S₁) : eval₂ f g 0 = 0 := finsupp.sum_zero_index @[simp] theorem eval₂_add {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] {p : mv_polynomial σ R} {q : mv_polynomial σ R} [comm_semiring S₁] (f : R →+* S₁) (g : σ → S₁) : eval₂ f g (p + q) = eval₂ f g p + eval₂ f g q := sorry @[simp] theorem eval₂_monomial {R : Type u} {S₁ : Type v} {σ : Type u_1} {a : R} {s : σ →₀ ℕ} [comm_semiring R] [comm_semiring S₁] (f : R →+* S₁) (g : σ → S₁) : eval₂ f g (monomial s a) = coe_fn f a * finsupp.prod s fun (n : σ) (e : ℕ) => g n ^ e := sorry @[simp] theorem eval₂_C {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] (f : R →+* S₁) (g : σ → S₁) (a : R) : eval₂ f g (coe_fn C a) = coe_fn f a := sorry @[simp] theorem eval₂_one {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] (f : R →+* S₁) (g : σ → S₁) : eval₂ f g 1 = 1 := Eq.trans (eval₂_C f g 1) (is_semiring_hom.map_one ⇑f) @[simp] theorem eval₂_X {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] (f : R →+* S₁) (g : σ → S₁) (n : σ) : eval₂ f g (X n) = g n := sorry theorem eval₂_mul_monomial {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] {p : mv_polynomial σ R} [comm_semiring S₁] (f : R →+* S₁) (g : σ → S₁) {s : σ →₀ ℕ} {a : R} : eval₂ f g (p * monomial s a) = eval₂ f g p * coe_fn f a * finsupp.prod s fun (n : σ) (e : ℕ) => g n ^ e := sorry @[simp] theorem eval₂_mul {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] {q : mv_polynomial σ R} [comm_semiring S₁] (f : R →+* S₁) (g : σ → S₁) {p : mv_polynomial σ R} : eval₂ f g (p * q) = eval₂ f g p * eval₂ f g q := sorry @[simp] theorem eval₂_pow {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] (f : R →+* S₁) (g : σ → S₁) {p : mv_polynomial σ R} {n : ℕ} : eval₂ f g (p ^ n) = eval₂ f g p ^ n := sorry protected instance eval₂.is_semiring_hom {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] (f : R →+* S₁) (g : σ → S₁) : is_semiring_hom (eval₂ f g) := is_semiring_hom.mk (eval₂_zero f g) (eval₂_one f g) (fun (p q : mv_polynomial σ R) => eval₂_add f g) fun (p q : mv_polynomial σ R) => eval₂_mul f g /-- `mv_polynomial.eval₂` as a `ring_hom`. -/ def eval₂_hom {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] (f : R →+* S₁) (g : σ → S₁) : mv_polynomial σ R →+* S₁ := ring_hom.of (eval₂ f g) @[simp] theorem coe_eval₂_hom {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] (f : R →+* S₁) (g : σ → S₁) : ⇑(eval₂_hom f g) = eval₂ f g := rfl theorem eval₂_hom_congr {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] {f₁ : R →+* S₁} {f₂ : R →+* S₁} {g₁ : σ → S₁} {g₂ : σ → S₁} {p₁ : mv_polynomial σ R} {p₂ : mv_polynomial σ R} : f₁ = f₂ → g₁ = g₂ → p₁ = p₂ → coe_fn (eval₂_hom f₁ g₁) p₁ = coe_fn (eval₂_hom f₂ g₂) p₂ := fun (ᾰ : f₁ = f₂) (ᾰ_1 : g₁ = g₂) (ᾰ_2 : p₁ = p₂) => Eq._oldrec (Eq._oldrec (Eq._oldrec (Eq.refl (coe_fn (eval₂_hom f₁ g₁) p₁)) ᾰ_2) ᾰ_1) ᾰ @[simp] theorem eval₂_hom_C {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] (f : R →+* S₁) (g : σ → S₁) (r : R) : coe_fn (eval₂_hom f g) (coe_fn C r) = coe_fn f r := eval₂_C f g r @[simp] theorem eval₂_hom_X' {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] (f : R →+* S₁) (g : σ → S₁) (i : σ) : coe_fn (eval₂_hom f g) (X i) = g i := eval₂_X f g i @[simp] theorem comp_eval₂_hom {R : Type u} {S₁ : Type v} {S₂ : Type w} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₁) (φ : S₁ →+* S₂) : ring_hom.comp φ (eval₂_hom f g) = eval₂_hom (ring_hom.comp φ f) fun (i : σ) => coe_fn φ (g i) := sorry theorem map_eval₂_hom {R : Type u} {S₁ : Type v} {S₂ : Type w} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₁) (φ : S₁ →+* S₂) (p : mv_polynomial σ R) : coe_fn φ (coe_fn (eval₂_hom f g) p) = coe_fn (eval₂_hom (ring_hom.comp φ f) fun (i : σ) => coe_fn φ (g i)) p := sorry theorem eval₂_hom_monomial {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] (f : R →+* S₁) (g : σ → S₁) (d : σ →₀ ℕ) (r : R) : coe_fn (eval₂_hom f g) (monomial d r) = coe_fn f r * finsupp.prod d fun (i : σ) (k : ℕ) => g i ^ k := sorry theorem eval₂_comp_left {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] {S₂ : Type u_2} [comm_semiring S₂] (k : S₁ →+* S₂) (f : R →+* S₁) (g : σ → S₁) (p : mv_polynomial σ R) : coe_fn k (eval₂ f g p) = eval₂ (ring_hom.comp k f) (⇑k ∘ g) p := sorry @[simp] theorem eval₂_eta {R : Type u} {σ : Type u_1} [comm_semiring R] (p : mv_polynomial σ R) : eval₂ C X p = p := sorry theorem eval₂_congr {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] {p : mv_polynomial σ R} [comm_semiring S₁] (f : R →+* S₁) (g₁ : σ → S₁) (g₂ : σ → S₁) (h : ∀ {i : σ} {c : σ →₀ ℕ}, i ∈ finsupp.support c → coeff c p ≠ 0 → g₁ i = g₂ i) : eval₂ f g₁ p = eval₂ f g₂ p := sorry @[simp] theorem eval₂_prod {R : Type u} {S₁ : Type v} {S₂ : Type w} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] (f : R →+* S₁) (g : σ → S₁) (s : finset S₂) (p : S₂ → mv_polynomial σ R) : eval₂ f g (finset.prod s fun (x : S₂) => p x) = finset.prod s fun (x : S₂) => eval₂ f g (p x) := Eq.symm (finset.prod_hom s (eval₂ f g)) @[simp] theorem eval₂_sum {R : Type u} {S₁ : Type v} {S₂ : Type w} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] (f : R →+* S₁) (g : σ → S₁) (s : finset S₂) (p : S₂ → mv_polynomial σ R) : eval₂ f g (finset.sum s fun (x : S₂) => p x) = finset.sum s fun (x : S₂) => eval₂ f g (p x) := Eq.symm (finset.sum_hom s (eval₂ f g)) theorem eval₂_assoc {R : Type u} {S₁ : Type v} {S₂ : Type w} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] (f : R →+* S₁) (g : σ → S₁) (q : S₂ → mv_polynomial σ R) (p : mv_polynomial S₂ R) : eval₂ f (fun (t : S₂) => eval₂ f g (q t)) p = eval₂ f g (eval₂ C q p) := sorry /-- Evaluate a polynomial `p` given a valuation `f` of all the variables -/ def eval {R : Type u} {σ : Type u_1} [comm_semiring R] (f : σ → R) : mv_polynomial σ R →+* R := eval₂_hom (ring_hom.id R) f theorem eval_eq {R : Type u} {σ : Type u_1} [comm_semiring R] (x : σ → R) (f : mv_polynomial σ R) : coe_fn (eval x) f = finset.sum (finsupp.support f) fun (d : σ →₀ ℕ) => coeff d f * finset.prod (finsupp.support d) fun (i : σ) => x i ^ coe_fn d i := rfl theorem eval_eq' {R : Type u} {σ : Type u_1} [comm_semiring R] [fintype σ] (x : σ → R) (f : mv_polynomial σ R) : coe_fn (eval x) f = finset.sum (finsupp.support f) fun (d : σ →₀ ℕ) => coeff d f * finset.prod finset.univ fun (i : σ) => x i ^ coe_fn d i := eval₂_eq' (ring_hom.id R) x f theorem eval_monomial {R : Type u} {σ : Type u_1} {a : R} {s : σ →₀ ℕ} [comm_semiring R] {f : σ → R} : coe_fn (eval f) (monomial s a) = a * finsupp.prod s fun (n : σ) (e : ℕ) => f n ^ e := eval₂_monomial (ring_hom.id R) fun (n : σ) => f n @[simp] theorem eval_C {R : Type u} {σ : Type u_1} [comm_semiring R] {f : σ → R} (a : R) : coe_fn (eval f) (coe_fn C a) = a := eval₂_C (ring_hom.id R) fun (n : σ) => f n @[simp] theorem eval_X {R : Type u} {σ : Type u_1} [comm_semiring R] {f : σ → R} (n : σ) : coe_fn (eval f) (X n) = f n := eval₂_X (ring_hom.id R) fun (n : σ) => f n @[simp] theorem smul_eval {R : Type u} {σ : Type u_1} [comm_semiring R] (x : σ → R) (p : mv_polynomial σ R) (s : R) : coe_fn (eval x) (s • p) = s * coe_fn (eval x) p := sorry theorem eval_sum {R : Type u} {σ : Type u_1} [comm_semiring R] {ι : Type u_2} (s : finset ι) (f : ι → mv_polynomial σ R) (g : σ → R) : coe_fn (eval g) (finset.sum s fun (i : ι) => f i) = finset.sum s fun (i : ι) => coe_fn (eval g) (f i) := ring_hom.map_sum (eval g) (fun (i : ι) => f i) s theorem eval_prod {R : Type u} {σ : Type u_1} [comm_semiring R] {ι : Type u_2} (s : finset ι) (f : ι → mv_polynomial σ R) (g : σ → R) : coe_fn (eval g) (finset.prod s fun (i : ι) => f i) = finset.prod s fun (i : ι) => coe_fn (eval g) (f i) := ring_hom.map_prod (eval g) (fun (i : ι) => f i) s theorem eval_assoc {R : Type u} {σ : Type u_1} [comm_semiring R] {τ : Type u_2} (f : σ → mv_polynomial τ R) (g : τ → R) (p : mv_polynomial σ R) : coe_fn (eval (⇑(eval g) ∘ f)) p = coe_fn (eval g) (eval₂ C f p) := sorry /-- `map f p` maps a polynomial `p` across a ring hom `f` -/ def map {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] (f : R →+* S₁) : mv_polynomial σ R →+* mv_polynomial σ S₁ := eval₂_hom (ring_hom.comp C f) X @[simp] theorem map_monomial {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] (f : R →+* S₁) (s : σ →₀ ℕ) (a : R) : coe_fn (map f) (monomial s a) = monomial s (coe_fn f a) := Eq.trans (eval₂_monomial (ring_hom.comp C f) fun (n : σ) => X n) (Eq.symm monomial_eq) @[simp] theorem map_C {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] (f : R →+* S₁) (a : R) : coe_fn (map f) (coe_fn C a) = coe_fn C (coe_fn f a) := map_monomial f 0 @[simp] theorem map_X {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] (f : R →+* S₁) (n : σ) : coe_fn (map f) (X n) = X n := eval₂_X (ring_hom.comp C f) fun (n : σ) => X n theorem map_id {R : Type u} {σ : Type u_1} [comm_semiring R] (p : mv_polynomial σ R) : coe_fn (map (ring_hom.id R)) p = p := eval₂_eta theorem map_map {R : Type u} {S₁ : Type v} {S₂ : Type w} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] (f : R →+* S₁) [comm_semiring S₂] (g : S₁ →+* S₂) (p : mv_polynomial σ R) : coe_fn (map g) (coe_fn (map f) p) = coe_fn (map (ring_hom.comp g f)) p := sorry theorem eval₂_eq_eval_map {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] (f : R →+* S₁) (g : σ → S₁) (p : mv_polynomial σ R) : eval₂ f g p = coe_fn (eval g) (coe_fn (map f) p) := sorry theorem eval₂_comp_right {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] {S₂ : Type u_2} [comm_semiring S₂] (k : S₁ →+* S₂) (f : R →+* S₁) (g : σ → S₁) (p : mv_polynomial σ R) : coe_fn k (eval₂ f g p) = eval₂ k (⇑k ∘ g) (coe_fn (map f) p) := sorry theorem map_eval₂ {R : Type u} {S₁ : Type v} {S₂ : Type w} {S₃ : Type x} [comm_semiring R] [comm_semiring S₁] (f : R →+* S₁) (g : S₂ → mv_polynomial S₃ R) (p : mv_polynomial S₂ R) : coe_fn (map f) (eval₂ C g p) = eval₂ C (⇑(map f) ∘ g) (coe_fn (map f) p) := sorry theorem coeff_map {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] (f : R →+* S₁) (p : mv_polynomial σ R) (m : σ →₀ ℕ) : coeff m (coe_fn (map f) p) = coe_fn f (coeff m p) := sorry theorem map_injective {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] (f : R →+* S₁) (hf : function.injective ⇑f) : function.injective ⇑(map f) := sorry @[simp] theorem eval_map {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] (f : R →+* S₁) (g : σ → S₁) (p : mv_polynomial σ R) : coe_fn (eval g) (coe_fn (map f) p) = eval₂ f g p := sorry @[simp] theorem eval₂_map {R : Type u} {S₁ : Type v} {S₂ : Type w} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₂) (φ : S₁ →+* S₂) (p : mv_polynomial σ R) : eval₂ φ g (coe_fn (map f) p) = eval₂ (ring_hom.comp φ f) g p := sorry @[simp] theorem eval₂_hom_map_hom {R : Type u} {S₁ : Type v} {S₂ : Type w} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₂) (φ : S₁ →+* S₂) (p : mv_polynomial σ R) : coe_fn (eval₂_hom φ g) (coe_fn (map f) p) = coe_fn (eval₂_hom (ring_hom.comp φ f) g) p := eval₂_map f g φ p @[simp] theorem constant_coeff_map {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] (f : R →+* S₁) (φ : mv_polynomial σ R) : coe_fn constant_coeff (coe_fn (map f) φ) = coe_fn f (coe_fn constant_coeff φ) := coeff_map f φ 0 theorem constant_coeff_comp_map {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] (f : R →+* S₁) : ring_hom.comp constant_coeff (map f) = ring_hom.comp f constant_coeff := sorry theorem support_map_subset {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] (f : R →+* S₁) (p : mv_polynomial σ R) : finsupp.support (coe_fn (map f) p) ⊆ finsupp.support p := sorry theorem support_map_of_injective {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] (p : mv_polynomial σ R) {f : R →+* S₁} (hf : function.injective ⇑f) : finsupp.support (coe_fn (map f) p) = finsupp.support p := sorry theorem C_dvd_iff_map_hom_eq_zero {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] (q : R →+* S₁) (r : R) (hr : ∀ (r' : R), coe_fn q r' = 0 ↔ r ∣ r') (φ : mv_polynomial σ R) : coe_fn C r ∣ φ ↔ coe_fn (map q) φ = 0 := sorry theorem map_map_range_eq_iff {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] (f : R →+* S₁) (g : S₁ → R) (hg : g 0 = 0) (φ : mv_polynomial σ S₁) : coe_fn (map f) (finsupp.map_range g hg φ) = φ ↔ ∀ (d : σ →₀ ℕ), coe_fn f (g (coeff d φ)) = coeff d φ := sorry /-! ### The algebra of multivariate polynomials -/ /-- A map `σ → S₁` where `S₁` is an algebra over `R` generates an `R`-algebra homomorphism from multivariate polynomials over `σ` to `S₁`. -/ def aeval {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] (f : σ → S₁) [comm_semiring S₁] [algebra R S₁] : alg_hom R (mv_polynomial σ R) S₁ := alg_hom.mk (ring_hom.to_fun (eval₂_hom (algebra_map R S₁) f)) sorry sorry sorry sorry sorry theorem aeval_def {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] (f : σ → S₁) [comm_semiring S₁] [algebra R S₁] (p : mv_polynomial σ R) : coe_fn (aeval f) p = eval₂ (algebra_map R S₁) f p := rfl theorem aeval_eq_eval₂_hom {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] (f : σ → S₁) [comm_semiring S₁] [algebra R S₁] (p : mv_polynomial σ R) : coe_fn (aeval f) p = coe_fn (eval₂_hom (algebra_map R S₁) f) p := rfl @[simp] theorem aeval_X {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] (f : σ → S₁) [comm_semiring S₁] [algebra R S₁] (s : σ) : coe_fn (aeval f) (X s) = f s := eval₂_X (algebra_map R S₁) (fun (n : σ) => f n) s @[simp] theorem aeval_C {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] (f : σ → S₁) [comm_semiring S₁] [algebra R S₁] (r : R) : coe_fn (aeval f) (coe_fn C r) = coe_fn (algebra_map R S₁) r := eval₂_C (algebra_map R S₁) (fun (n : σ) => f n) r theorem aeval_unique {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] [algebra R S₁] (φ : alg_hom R (mv_polynomial σ R) S₁) : φ = aeval (⇑φ ∘ X) := sorry theorem comp_aeval {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] (f : σ → S₁) [comm_semiring S₁] [algebra R S₁] {B : Type u_2} [comm_semiring B] [algebra R B] (φ : alg_hom R S₁ B) : alg_hom.comp φ (aeval f) = aeval fun (i : σ) => coe_fn φ (f i) := sorry @[simp] theorem map_aeval {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] [algebra R S₁] {B : Type u_2} [comm_semiring B] (g : σ → S₁) (φ : S₁ →+* B) (p : mv_polynomial σ R) : coe_fn φ (coe_fn (aeval g) p) = coe_fn (eval₂_hom (ring_hom.comp φ (algebra_map R S₁)) fun (i : σ) => coe_fn φ (g i)) p := sorry @[simp] theorem eval₂_hom_zero {R : Type u} {S₂ : Type w} {σ : Type u_1} [comm_semiring R] [comm_semiring S₂] (f : R →+* S₂) (p : mv_polynomial σ R) : coe_fn (eval₂_hom f 0) p = coe_fn f (coe_fn constant_coeff p) := sorry @[simp] theorem eval₂_hom_zero' {R : Type u} {S₂ : Type w} {σ : Type u_1} [comm_semiring R] [comm_semiring S₂] (f : R →+* S₂) (p : mv_polynomial σ R) : coe_fn (eval₂_hom f fun (_x : σ) => 0) p = coe_fn f (coe_fn constant_coeff p) := eval₂_hom_zero f p @[simp] theorem aeval_zero {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] [algebra R S₁] (p : mv_polynomial σ R) : coe_fn (aeval 0) p = coe_fn (algebra_map R S₁) (coe_fn constant_coeff p) := eval₂_hom_zero (algebra_map R S₁) p @[simp] theorem aeval_zero' {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] [algebra R S₁] (p : mv_polynomial σ R) : coe_fn (aeval fun (_x : σ) => 0) p = coe_fn (algebra_map R S₁) (coe_fn constant_coeff p) := aeval_zero p theorem aeval_monomial {R : Type u} {S₁ : Type v} {σ : Type u_1} [comm_semiring R] [comm_semiring S₁] [algebra R S₁] (g : σ → S₁) (d : σ →₀ ℕ) (r : R) : coe_fn (aeval g) (monomial d r) = coe_fn (algebra_map R S₁) r * finsupp.prod d fun (i : σ) (k : ℕ) => g i ^ k := eval₂_hom_monomial (algebra_map R S₁) (fun (n : σ) => g n) d r theorem eval₂_hom_eq_zero {R : Type u} {S₂ : Type w} {σ : Type u_1} [comm_semiring R] [comm_semiring S₂] (f : R →+* S₂) (g : σ → S₂) (φ : mv_polynomial σ R) (h : ∀ (d : σ →₀ ℕ), coeff d φ ≠ 0 → ∃ (i : σ), ∃ (H : i ∈ finsupp.support d), g i = 0) : coe_fn (eval₂_hom f g) φ = 0 := sorry theorem aeval_eq_zero {R : Type u} {S₂ : Type w} {σ : Type u_1} [comm_semiring R] [comm_semiring S₂] [algebra R S₂] (f : σ → S₂) (φ : mv_polynomial σ R) (h : ∀ (d : σ →₀ ℕ), coeff d φ ≠ 0 → ∃ (i : σ), ∃ (H : i ∈ finsupp.support d), f i = 0) : coe_fn (aeval f) φ = 0 := eval₂_hom_eq_zero (algebra_map R S₂) (fun (n : σ) => f n) φ h end Mathlib
6117dc5fe8cc4b6eeea706376cdc5a235617d179
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/pkg/user_attr/UserAttr/BlaAttr.lean
efcaf85273393e08e924f742b27e8dc338030896
[ "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
721
lean
import Lean open Lean initialize blaAttr : TagAttribute ← registerTagAttribute `bla "simple user defined attribute" /-- My new simp attribute -/ register_simp_attr my_simp "my own simp attribute" syntax (name := foo) "foo" num "important"? : attr initialize fooAttr : ParametricAttribute (Nat × Bool) ← registerParametricAttribute { name := `foo descr := "parametric attribute containing a priority and flag" getParam := fun _ stx => match stx with | `(attr| foo $prio:num $[important%$imp]?) => return (prio.getNat, imp.isSome) | _ => throwError "unexpected foo attribute" afterSet := fun declName _ => do IO.println s!"set attribute [foo] at {declName}" }
5bfe02c13c713e0c08778cc98d89eefacbbbe40f
cc4e32129597fc42f4ac133f6eef3dbfd3d16218
/Analysis/Pre.lean
985c8a7932daa969be032e44eded98cb7acc1d8a
[]
no_license
JasonKYi/analysis_in_lean4
9791c76ab5f9408731acca075cf604ef4700b117
280d45bf2fc9c2f599b365a60a4b980bb2721c24
refs/heads/main
1,683,375,225,248
1,622,048,948,000
1,622,048,948,000
370,429,249
0
0
null
null
null
null
UTF-8
Lean
false
false
182
lean
class Mem (α : outParam $ Type u) (γ : Type v) where mem : α → γ → Prop infix:55 " ∈ " => Mem.mem notation:55 x " ∉ " s => ¬ x ∈ s instance : Coe α α := ⟨id⟩
cedd6fd362fbe8813d73aead63bec06de7dda21a
d1bbf1801b3dcb214451d48214589f511061da63
/src/measure_theory/interval_integral.lean
2bc700e5c0b4cc836fc46031927883729663745c
[ "Apache-2.0" ]
permissive
cheraghchi/mathlib
5c366f8c4f8e66973b60c37881889da8390cab86
f29d1c3038422168fbbdb2526abf7c0ff13e86db
refs/heads/master
1,676,577,831,283
1,610,894,638,000
1,610,894,638,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
74,389
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Yury G. Kudryashov -/ import measure_theory.set_integral import measure_theory.lebesgue_measure import analysis.calculus.fderiv_measurable import analysis.calculus.mean_value /-! # Integral over an interval In this file we define `∫ x in a..b, f x ∂μ` to be `∫ x in Ioc a b, f x ∂μ` if `a ≤ b` and `-∫ x in Ioc b a, f x ∂μ` if `b ≤ a`. We prove a few simple properties and many versions of the first part of the [fundamental theorem of calculus](https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus). Recall that it states that the function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(δu, δv) ↦ δv • f b - δu • f a` at `(a, b)` provided that `f` is continuous at `a` and `b`. ## Main statements ### FTC-1 for Lebesgue measure We prove several versions of FTC-1, all in the `interval_integral` namespace. Many of them follow the naming scheme `integral_has(_strict?)_(f?)deriv(_within?)_at(_of_tendsto_ae?)(_right|_left?)`. They formulate FTC in terms of `has(_strict?)_(f?)deriv(_within?)_at`. Let us explain the meaning of each part of the name: * `_strict` means that the theorem is about strict differentiability; * `f` means that the theorem is about differentiability in both endpoints; incompatible with `_right|_left`; * `_within` means that the theorem is about one-sided derivatives, see below for details; * `_of_tendsto_ae` means that instead of continuity the theorem assumes that `f` has a finite limit almost surely as `x` tends to `a` and/or `b`; * `_right` or `_left` mean that the theorem is about differentiability in the right (resp., left) endpoint. We also reformulate these theorems in terms of `(f?)deriv(_within?)`. These theorems are named `(f?)deriv(_within?)_integral(_of_tendsto_ae?)(_right|_left?)` with the same meaning of parts of the name. ### One-sided derivatives Theorem `integral_has_fderiv_within_at_of_tendsto_ae` states that `(u, v) ↦ ∫ x in u..v, f x` has a derivative `(δu, δv) ↦ δv • cb - δu • ca` within the set `s × t` at `(a, b)` provided that `f` tends to `ca` (resp., `cb`) almost surely at `la` (resp., `lb`), where possible values of `s`, `t`, and corresponding filters `la`, `lb` are given in the following table. | `s` | `la` | `t` | `lb` | | ------- | ---- | --- | ---- | | `Iic a` | `𝓝[Iic a] a` | `Iic b` | `𝓝[Iic b] b` | | `Ici a` | `𝓝[Ioi a] a` | `Ici b` | `𝓝[Ioi b] b` | | `{a}` | `⊥` | `{b}` | `⊥` | | `univ` | `𝓝 a` | `univ` | `𝓝 b` | We use a typeclass `FTC_filter` to make Lean automatically find `la`/`lb` based on `s`/`t`. This way we can formulate one theorem instead of `16` (or `8` if we leave only non-trivial ones not covered by `integral_has_deriv_within_at_of_tendsto_ae_(left|right)` and `integral_has_fderiv_at_of_tendsto_ae`). Similarly, `integral_has_deriv_within_at_of_tendsto_ae_right` works for both one-sided derivatives using the same typeclass to find an appropriate filter. ### FTC for a locally finite measure Before proving FTC for the Lebesgue measure, we prove a few statements that can be seen as FTC for any measure. The most general of them, `measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae`, states the following. Let `(la, la')` be an `FTC_filter` pair of filters around `a` (i.e., `FTC_filter a la la'`) and let `(lb, lb')` be an `FTC_filter` pair of filters around `b`. If `f` has finite limits `ca` and `cb` almost surely at `la'` and `lb'`, respectively, then `∫ x in va..vb, f x ∂μ - ∫ x in ua..ub, f x ∂μ = ∫ x in ub..vb, cb ∂μ - ∫ x in ua..va, ca ∂μ + o(∥∫ x in ua..va, (1:ℝ) ∂μ∥ + ∥∫ x in ub..vb, (1:ℝ) ∂μ∥)` as `ua` and `va` tend to `la` while `ub` and `vb` tend to `lb`. ## Implementation notes ### Avoiding `if`, `min`, and `max` In order to avoid `if`s in the definition, we define `interval_integrable f μ a b` as `integrable_on f (Ioc a b) μ ∧ integrable_on f (Ioc b a) μ`. For any `a`, `b` one of these intervals is empty and the other coincides with `Ioc (min a b) (max a b)`. Similarly, we define `∫ x in a..b, f x ∂μ` to be `∫ x in Ioc a b, f x ∂μ - ∫ x in Ioc b a, f x ∂μ`. Again, for any `a`, `b` one of these integrals is zero, and the other gives the expected result. This way some properties can be translated from integrals over sets without dealing with the cases `a ≤ b` and `b ≤ a` separately. ### Choice of the interval We use integral over `Ioc (min a b) (max a b)` instead of one of the other three possible intervals with the same endpoints for two reasons: * this way `∫ x in a..b, f x ∂μ + ∫ x in b..c, f x ∂μ = ∫ x in a..c, f x ∂μ` holds whenever `f` is integrable on each interval; in particular, it works even if the measure `μ` has an atom at `b`; this rules out `Ioo` and `Icc` intervals; * with this definition for a probability measure `μ`, the integral `∫ x in a..b, 1 ∂μ` equals the difference $F_μ(b)-F_μ(a)$, where $F_μ(a)=μ(-∞, a]$ is the [cumulative distribution function](https://en.wikipedia.org/wiki/Cumulative_distribution_function) of `μ`. ### `FTC_filter` class As explained above, many theorems in this file rely on the typeclass `FTC_filter (a : α) (l l' : filter α)` to avoid code duplication. This typeclass combines four assumptions: - `pure a ≤ l`; - `l' ≤ 𝓝 a`; - `l'` has a basis of measurable sets; - if `u n` and `v n` tend to `l`, then for any `s ∈ l'`, `Ioc (u n) (v n)` is eventually included in `s`. This typeclass has exactly four “real” instances: `(a, pure a, ⊥)`, `(a, 𝓝[Ici a] a, 𝓝[Ioi a] a)`, `(a, 𝓝[Iic a] a, 𝓝[Iic a] a)`, `(a, 𝓝 a, 𝓝 a)`, and two instances that are equal to the first and last “real” instances: `(a, 𝓝[{a}] a, ⊥)` and `(a, 𝓝[univ] a, 𝓝[univ] a)`. While the difference between `Ici a` and `Ioi a` doesn't matter for theorems about Lebesgue measure, it becomes important in the versions of FTC about any locally finite measure if this measure has an atom at one of the endpoints. ## Tags integral, fundamental theorem of calculus -/ noncomputable theory open topological_space (second_countable_topology) open measure_theory set classical filter open_locale classical topological_space filter variables {α β 𝕜 E F : Type*} [linear_order α] [measurable_space α] [measurable_space E] [normed_group E] /-! ### Integrability at an interval -/ /-- A function `f` is called *interval integrable* with respect to a measure `μ` on an unordered interval `a..b` if it is integrable on both intervals `(a, b]` and `(b, a]`. One of these intervals is always empty, so this property is equivalent to `f` being integrable on `(min a b, max a b]`. -/ def interval_integrable (f : α → E) (μ : measure α) (a b : α) := integrable_on f (Ioc a b) μ ∧ integrable_on f (Ioc b a) μ lemma measure_theory.integrable.interval_integrable {f : α → E} {μ : measure α} (hf : integrable f μ) {a b : α} : interval_integrable f μ a b := ⟨hf.integrable_on, hf.integrable_on⟩ namespace interval_integrable section variables {f : α → E} {a b c : α} {μ : measure α} @[symm] lemma symm (h : interval_integrable f μ a b) : interval_integrable f μ b a := h.symm @[refl] lemma refl : interval_integrable f μ a a := by split; simp @[trans] lemma trans (hab : interval_integrable f μ a b) (hbc : interval_integrable f μ b c) : interval_integrable f μ a c := ⟨(hab.1.union hbc.1).mono_set Ioc_subset_Ioc_union_Ioc, (hbc.2.union hab.2).mono_set Ioc_subset_Ioc_union_Ioc⟩ lemma neg [borel_space E] (h : interval_integrable f μ a b) : interval_integrable (-f) μ a b := ⟨h.1.neg, h.2.neg⟩ protected lemma ae_measurable (h : interval_integrable f μ a b) : ae_measurable f (μ.restrict (Ioc a b)):= h.1.ae_measurable protected lemma ae_measurable' (h : interval_integrable f μ a b) : ae_measurable f (μ.restrict (Ioc b a)):= h.2.ae_measurable end variables [borel_space E] {f g : α → E} {a b : α} {μ : measure α} lemma smul [normed_field 𝕜] [normed_space 𝕜 E] {f : α → E} {a b : α} {μ : measure α} (h : interval_integrable f μ a b) (r : 𝕜) : interval_integrable (r • f) μ a b := ⟨h.1.smul r, h.2.smul r⟩ lemma add [second_countable_topology E] (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) : interval_integrable (f + g) μ a b := ⟨hf.1.add hg.1, hf.2.add hg.2⟩ lemma sub [second_countable_topology E] (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) : interval_integrable (f - g) μ a b := ⟨hf.1.sub hg.1, hf.2.sub hg.2⟩ end interval_integrable section variables {μ : measure ℝ} [locally_finite_measure μ] lemma continuous_on.interval_integrable [borel_space E] {u : ℝ → E} {a b : ℝ} (hu : continuous_on u (interval a b)) : interval_integrable u μ a b := begin split, all_goals { refine measure_theory.integrable_on.mono_set _ Ioc_subset_Icc_self, refine continuous_on.integrable_on_compact compact_Icc (hu.mono _) }, exacts [Icc_subset_interval, Icc_subset_interval'] end lemma continuous_on.interval_integrable_of_Icc [borel_space E] {u : ℝ → E} {a b : ℝ} (h : a ≤ b) (hu : continuous_on u (Icc a b)) : interval_integrable u μ a b := continuous_on.interval_integrable ((interval_of_le h).symm ▸ hu) /-- A continuous function on `ℝ` is `interval_integrable` with respect to any locally finite measure `ν` on ℝ. -/ lemma continuous.interval_integrable [borel_space E] {u : ℝ → E} (hu : continuous u) (a b : ℝ) : interval_integrable u μ a b := hu.continuous_on.interval_integrable end /-- Let `l'` be a measurably generated filter; let `l` be a of filter such that each `s ∈ l'` eventually includes `Ioc u v` as both `u` and `v` tend to `l`. Let `μ` be a measure finite at `l'`. Suppose that `f : α → E` has a finite limit at `l' ⊓ μ.ae`. Then `f` is interval integrable on `u..v` provided that both `u` and `v` tend to `l`. Typeclass instances allow Lean to find `l'` based on `l` but not vice versa, so `apply tendsto.eventually_interval_integrable_ae` will generate goals `filter α` and `tendsto_Ixx_class Ioc ?m_1 l'`. -/ lemma filter.tendsto.eventually_interval_integrable_ae {f : α → E} {μ : measure α} {l l' : filter α} (hfm : measurable_at_filter f l' μ) [tendsto_Ixx_class Ioc l l'] [is_measurably_generated l'] (hμ : μ.finite_at_filter l') {c : E} (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) {u v : β → α} {lt : filter β} (hu : tendsto u lt l) (hv : tendsto v lt l) : ∀ᶠ t in lt, interval_integrable f μ (u t) (v t) := have _ := (hf.integrable_at_filter_ae hfm hμ).eventually, ((hu.Ioc hv).eventually this).and $ (hv.Ioc hu).eventually this /-- Let `l'` be a measurably generated filter; let `l` be a of filter such that each `s ∈ l'` eventually includes `Ioc u v` as both `u` and `v` tend to `l`. Let `μ` be a measure finite at `l'`. Suppose that `f : α → E` has a finite limit at `l`. Then `f` is interval integrable on `u..v` provided that both `u` and `v` tend to `l`. Typeclass instances allow Lean to find `l'` based on `l` but not vice versa, so `apply tendsto.eventually_interval_integrable_ae` will generate goals `filter α` and `tendsto_Ixx_class Ioc ?m_1 l'`. -/ lemma filter.tendsto.eventually_interval_integrable {f : α → E} {μ : measure α} {l l' : filter α} (hfm : measurable_at_filter f l' μ) [tendsto_Ixx_class Ioc l l'] [is_measurably_generated l'] (hμ : μ.finite_at_filter l') {c : E} (hf : tendsto f l' (𝓝 c)) {u v : β → α} {lt : filter β} (hu : tendsto u lt l) (hv : tendsto v lt l) : ∀ᶠ t in lt, interval_integrable f μ (u t) (v t) := (hf.mono_left inf_le_left).eventually_interval_integrable_ae hfm hμ hu hv /-! ### Interval integral: definition and basic properties In this section we define `∫ x in a..b, f x ∂μ` as `∫ x in Ioc a b, f x ∂μ - ∫ x in Ioc b a, f x ∂μ` and prove some basic properties. -/ variables [second_countable_topology E] [complete_space E] [normed_space ℝ E] [borel_space E] /-- The interval integral `∫ x in a..b, f x ∂μ` is defined as `∫ x in Ioc a b, f x ∂μ - ∫ x in Ioc b a, f x ∂μ`. If `a ≤ b`, then it equals `∫ x in Ioc a b, f x ∂μ`, otherwise it equals `-∫ x in Ioc b a, f x ∂μ`. -/ def interval_integral (f : α → E) (a b : α) (μ : measure α) := ∫ x in Ioc a b, f x ∂μ - ∫ x in Ioc b a, f x ∂μ notation `∫` binders ` in ` a `..` b `, ` r:(scoped:60 f, f) ` ∂` μ:70 := interval_integral r a b μ notation `∫` binders ` in ` a `..` b `, ` r:(scoped:60 f, interval_integral f a b volume) := r namespace interval_integral section variables {a b c d : α} {f g : α → E} {μ : measure α} @[simp] lemma integral_zero : ∫ x in a..b, (0 : E) ∂μ = 0 := by simp [interval_integral] lemma integral_of_le (h : a ≤ b) : ∫ x in a..b, f x ∂μ = ∫ x in Ioc a b, f x ∂μ := by simp [interval_integral, h] @[simp] lemma integral_same : ∫ x in a..a, f x ∂μ = 0 := sub_self _ lemma integral_symm (a b) : ∫ x in b..a, f x ∂μ = -∫ x in a..b, f x ∂μ := by simp only [interval_integral, neg_sub] lemma integral_of_ge (h : b ≤ a) : ∫ x in a..b, f x ∂μ = -∫ x in Ioc b a, f x ∂μ := by simp only [integral_symm b, integral_of_le h] lemma integral_cases (f : α → E) (a b) : ∫ x in a..b, f x ∂μ ∈ ({∫ x in Ioc (min a b) (max a b), f x ∂μ, -∫ x in Ioc (min a b) (max a b), f x ∂μ} : set E) := (le_total a b).imp (λ h, by simp [h, integral_of_le]) (λ h, by simp [h, integral_of_ge]) lemma integral_non_ae_measurable {f : α → E} {a b} (h : a < b) (hf : ¬ ae_measurable f (μ.restrict (Ioc a b))) : ∫ x in a..b, f x ∂μ = 0 := by rw [integral_of_le h.le, integral_non_ae_measurable hf] lemma norm_integral_eq_norm_integral_Ioc : ∥∫ x in a..b, f x ∂μ∥ = ∥∫ x in Ioc (min a b) (max a b), f x ∂μ∥ := (integral_cases f a b).elim (congr_arg _) (λ h, (congr_arg _ h).trans (norm_neg _)) lemma norm_integral_le_integral_norm_Ioc : ∥∫ x in a..b, f x ∂μ∥ ≤ ∫ x in Ioc (min a b) (max a b), ∥f x∥ ∂μ := calc ∥∫ x in a..b, f x ∂μ∥ = ∥∫ x in Ioc (min a b) (max a b), f x ∂μ∥ : norm_integral_eq_norm_integral_Ioc ... ≤ ∫ x in Ioc (min a b) (max a b), ∥f x∥ ∂μ : norm_integral_le_integral_norm f lemma norm_integral_le_abs_integral_norm : ∥∫ x in a..b, f x ∂μ∥ ≤ abs (∫ x in a..b, ∥f x∥ ∂μ) := begin simp only [← real.norm_eq_abs, norm_integral_eq_norm_integral_Ioc], exact le_trans (norm_integral_le_integral_norm _) (le_abs_self _) end lemma norm_integral_le_of_norm_le_const_ae {a b C : ℝ} {f : ℝ → E} (h : ∀ᵐ x, x ∈ Ioc (min a b) (max a b) → ∥f x∥ ≤ C) : ∥∫ x in a..b, f x∥ ≤ C * abs (b - a) := begin rw [norm_integral_eq_norm_integral_Ioc], convert norm_set_integral_le_of_norm_le_const_ae'' _ is_measurable_Ioc h, { rw [real.volume_Ioc, max_sub_min_eq_abs, ennreal.to_real_of_real (abs_nonneg _)] }, { simp only [real.volume_Ioc, ennreal.of_real_lt_top] }, end lemma norm_integral_le_of_norm_le_const {a b C : ℝ} {f : ℝ → E} (h : ∀ x ∈ Ioc (min a b) (max a b), ∥f x∥ ≤ C) : ∥∫ x in a..b, f x∥ ≤ C * abs (b - a) := norm_integral_le_of_norm_le_const_ae $ eventually_of_forall h lemma integral_add (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) : ∫ x in a..b, f x + g x ∂μ = ∫ x in a..b, f x ∂μ + ∫ x in a..b, g x ∂μ := by { simp only [interval_integral, integral_add hf.1 hg.1, integral_add hf.2 hg.2], abel } @[simp] lemma integral_neg : ∫ x in a..b, -f x ∂μ = -∫ x in a..b, f x ∂μ := by { simp only [interval_integral, integral_neg], abel } lemma integral_sub (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) : ∫ x in a..b, f x - g x ∂μ = ∫ x in a..b, f x ∂μ - ∫ x in a..b, g x ∂μ := by simpa only [sub_eq_add_neg] using (integral_add hf hg.neg).trans (congr_arg _ integral_neg) lemma integral_smul (r : ℝ) : ∫ x in a..b, r • f x ∂μ = r • ∫ x in a..b, f x ∂μ := by simp only [interval_integral, integral_smul, smul_sub] lemma integral_const' (c : E) : ∫ x in a..b, c ∂μ = ((μ $ Ioc a b).to_real - (μ $ Ioc b a).to_real) • c := by simp only [interval_integral, set_integral_const, sub_smul] lemma integral_const {a b : ℝ} (c : E) : (∫ (x : ℝ) in a..b, c) = (b - a) • c := by simp only [integral_const', real.volume_Ioc, ennreal.to_real_of_real', ← neg_sub b, max_zero_sub_eq_self] lemma integral_smul_measure (c : ennreal) : ∫ x in a..b, f x ∂(c • μ) = c.to_real • ∫ x in a..b, f x ∂μ := by simp only [interval_integral, measure.restrict_smul, integral_smul_measure, smul_sub] lemma integral_comp_add_right (a b c : ℝ) (f : ℝ → E) (hfm : ae_measurable f) : ∫ x in a..b, f (x + c) = ∫ x in a+c..b+c, f x := have A : ae_measurable f (measure.map (λ x, x + c) volume), by rwa [real.map_volume_add_right], calc ∫ x in a..b, f (x + c) = ∫ x in a+c..b+c, f x ∂(measure.map (λ x, x + c) volume) : by simp only [interval_integral, set_integral_map is_measurable_Ioc A (measurable_add_right _), preimage_add_const_Ioc, add_sub_cancel] ... = ∫ x in a+c..b+c, f x : by rw [real.map_volume_add_right] lemma integral_comp_mul_right {c : ℝ} (hc : 0 < c) (a b : ℝ) (f : ℝ → E) (hfm : ae_measurable f) : ∫ x in a..b, f (x * c) = c⁻¹ • ∫ x in a*c..b*c, f x := begin have A : ae_measurable f (measure.map (λ (x : ℝ), x*c) volume), by { rw real.map_volume_mul_right (ne_of_gt hc), exact hfm.smul_measure _ }, conv_rhs { rw [← real.smul_map_volume_mul_right (ne_of_gt hc)] }, rw [integral_smul_measure], simp only [interval_integral, set_integral_map is_measurable_Ioc A (measurable_mul_right _), hc, preimage_mul_const_Ioc, mul_div_cancel _ (ne_of_gt hc), abs_of_pos, ennreal.to_real_of_real (le_of_lt hc), inv_smul_smul' (ne_of_gt hc)], end lemma integral_comp_neg (a b : ℝ) (f : ℝ → E) (hfm : ae_measurable f) : ∫ x in a..b, f (-x) = ∫ x in -b..-a, f x := begin have A : ae_measurable f (measure.map (λ (x : ℝ), -x) volume), by rwa real.map_volume_neg, conv_rhs { rw ← real.map_volume_neg }, simp only [interval_integral, set_integral_map is_measurable_Ioc A measurable_neg, neg_preimage, preimage_neg_Ioc, neg_neg, restrict_congr_set Ico_ae_eq_Ioc] end /-! ### Integral is an additive function of the interval In this section we prove that `∫ x in a..b, f x ∂μ + ∫ x in b..c, f x ∂μ = ∫ x in a..c, f x ∂μ` as well as a few other identities trivially equivalent to this one. We also prove that `∫ x in a..b, f x ∂μ = ∫ x, f x ∂μ` provided that `support f ⊆ Ioc a b`. -/ variables [topological_space α] [opens_measurable_space α] section order_closed_topology variables [order_closed_topology α] lemma integral_add_adjacent_intervals_cancel (hab : interval_integrable f μ a b) (hbc : interval_integrable f μ b c) : ∫ x in a..b, f x ∂μ + ∫ x in b..c, f x ∂μ + ∫ x in c..a, f x ∂μ = 0 := begin have hac := hab.trans hbc, simp only [interval_integral, ← add_sub_comm, sub_eq_zero], iterate 4 { rw ← integral_union }, { suffices : Ioc a b ∪ Ioc b c ∪ Ioc c a = Ioc b a ∪ Ioc c b ∪ Ioc a c, by rw this, rw [Ioc_union_Ioc_union_Ioc_cycle, union_right_comm, Ioc_union_Ioc_union_Ioc_cycle, min_left_comm, max_left_comm] }, all_goals { simp [*, is_measurable.union, is_measurable_Ioc, Ioc_disjoint_Ioc_same, Ioc_disjoint_Ioc_same.symm, hab.1, hab.2, hbc.1, hbc.2, hac.1, hac.2] } end lemma integral_add_adjacent_intervals (hab : interval_integrable f μ a b) (hbc : interval_integrable f μ b c) : ∫ x in a..b, f x ∂μ + ∫ x in b..c, f x ∂μ = ∫ x in a..c, f x ∂μ := by rw [← add_neg_eq_zero, ← integral_symm, integral_add_adjacent_intervals_cancel hab hbc] lemma integral_interval_sub_left (hab : interval_integrable f μ a b) (hac : interval_integrable f μ a c) : ∫ x in a..b, f x ∂μ - ∫ x in a..c, f x ∂μ = ∫ x in c..b, f x ∂μ := sub_eq_of_eq_add' $ eq.symm $ integral_add_adjacent_intervals hac (hac.symm.trans hab) lemma integral_interval_add_interval_comm (hab : interval_integrable f μ a b) (hcd : interval_integrable f μ c d) (hac : interval_integrable f μ a c) : ∫ x in a..b, f x ∂μ + ∫ x in c..d, f x ∂μ = ∫ x in a..d, f x ∂μ + ∫ x in c..b, f x ∂μ := by rw [← integral_add_adjacent_intervals hac hcd, add_assoc, add_left_comm, integral_add_adjacent_intervals hac (hac.symm.trans hab), add_comm] lemma integral_interval_sub_interval_comm (hab : interval_integrable f μ a b) (hcd : interval_integrable f μ c d) (hac : interval_integrable f μ a c) : ∫ x in a..b, f x ∂μ - ∫ x in c..d, f x ∂μ = ∫ x in a..c, f x ∂μ - ∫ x in b..d, f x ∂μ := by simp only [sub_eq_add_neg, ← integral_symm, integral_interval_add_interval_comm hab hcd.symm (hac.trans hcd)] lemma integral_interval_sub_interval_comm' (hab : interval_integrable f μ a b) (hcd : interval_integrable f μ c d) (hac : interval_integrable f μ a c) : ∫ x in a..b, f x ∂μ - ∫ x in c..d, f x ∂μ = ∫ x in d..b, f x ∂μ - ∫ x in c..a, f x ∂μ := by { rw [integral_interval_sub_interval_comm hab hcd hac, integral_symm b d, integral_symm a c, sub_neg_eq_add, sub_eq_neg_add], } lemma integral_Iic_sub_Iic (ha : integrable_on f (Iic a) μ) (hb : integrable_on f (Iic b) μ) : ∫ x in Iic b, f x ∂μ - ∫ x in Iic a, f x ∂μ = ∫ x in a..b, f x ∂μ := begin wlog hab : a ≤ b using [a b] tactic.skip, { rw [sub_eq_iff_eq_add', integral_of_le hab, ← integral_union (Iic_disjoint_Ioc (le_refl _)), Iic_union_Ioc_eq_Iic hab], exacts [is_measurable_Iic, is_measurable_Ioc, ha, hb.mono_set (λ _, and.right)] }, { intros ha hb, rw [integral_symm, ← this hb ha, neg_sub] } end /-- If `μ` is a finite measure then `∫ x in a..b, c ∂μ = (μ (Iic b) - μ (Iic a)) • c`. -/ lemma integral_const_of_cdf [finite_measure μ] (c : E) : ∫ x in a..b, c ∂μ = ((μ (Iic b)).to_real - (μ (Iic a)).to_real) • c := begin simp only [sub_smul, ← set_integral_const], refine (integral_Iic_sub_Iic _ _).symm; simp only [integrable_on_const, measure_lt_top, or_true] end lemma integral_eq_integral_of_support_subset {f : α → E} {a b} (h : function.support f ⊆ Ioc a b) : ∫ x in a..b, f x ∂μ = ∫ x, f x ∂μ := begin cases le_total a b with hab hab, { rw [integral_of_le hab, ← integral_indicator is_measurable_Ioc, indicator_eq_self.2 h]; apply_instance }, { rw [Ioc_eq_empty hab, subset_empty_iff, function.support_eq_empty_iff] at h, simp [h] } end end order_closed_topology end lemma integral_eq_zero_iff_of_le_of_nonneg_ae {f : ℝ → ℝ} {a b : ℝ} (hab : a ≤ b) (hf : 0 ≤ᵐ[volume.restrict (Ioc a b)] f) (hfi : interval_integrable f volume a b) : ∫ x in a..b, f x = 0 ↔ f =ᵐ[volume.restrict (Ioc a b)] 0 := by rw [integral_of_le hab, integral_eq_zero_iff_of_nonneg_ae hf hfi.1] lemma integral_eq_zero_iff_of_nonneg_ae {f : ℝ → ℝ} {a b : ℝ} (hf : 0 ≤ᵐ[volume.restrict (Ioc a b ∪ Ioc b a)] f) (hfi : interval_integrable f volume a b) : ∫ x in a..b, f x = 0 ↔ f =ᵐ[volume.restrict (Ioc a b ∪ Ioc b a)] 0 := begin cases le_total a b with hab hab; simp only [Ioc_eq_empty hab, empty_union, union_empty] at *, { exact integral_eq_zero_iff_of_le_of_nonneg_ae hab hf hfi }, { rw [integral_symm, neg_eq_zero], exact integral_eq_zero_iff_of_le_of_nonneg_ae hab hf hfi.symm } end lemma integral_pos_iff_support_of_nonneg_ae' {f : ℝ → ℝ} {a b : ℝ} (hf : 0 ≤ᵐ[volume.restrict (Ioc a b ∪ Ioc b a)] f) (hfi : interval_integrable f volume a b) : 0 < ∫ x in a..b, f x ↔ a < b ∧ 0 < volume (function.support f ∩ Ioc a b) := begin cases le_total a b with hab hab, { simp only [integral_of_le hab, Ioc_eq_empty hab, union_empty] at hf ⊢, symmetry, rw [set_integral_pos_iff_support_of_nonneg_ae hf hfi.1, and_iff_right_iff_imp], contrapose!, intro h, simp [Ioc_eq_empty h] }, { rw [Ioc_eq_empty hab, empty_union] at hf, simp [integral_of_ge hab, Ioc_eq_empty hab, integral_nonneg_of_ae hf] } end lemma integral_pos_iff_support_of_nonneg_ae {f : ℝ → ℝ} {a b : ℝ} (hf : 0 ≤ᵐ[volume] f) (hfi : interval_integrable f volume a b) : 0 < ∫ x in a..b, f x ↔ a < b ∧ 0 < volume (function.support f ∩ Ioc a b) := integral_pos_iff_support_of_nonneg_ae' (ae_mono measure.restrict_le_self hf) hfi /-! ### Fundamental theorem of calculus, part 1, for any measure In this section we prove a few lemmas that can be seen as versions of FTC-1 for interval integrals w.r.t. any measure. Many theorems are formulated for one or two pairs of filters related by `FTC_filter a l l'`. This typeclass has exactly four “real” instances: `(a, pure a, ⊥)`, `(a, 𝓝[Ici a] a, 𝓝[Ioi a] a)`, `(a, 𝓝[Iic a] a, 𝓝[Iic a] a)`, `(a, 𝓝 a, 𝓝 a)`, and two instances that are equal to the first and last “real” instances: `(a, 𝓝[{a}] a, ⊥)` and `(a, 𝓝[univ] a, 𝓝[univ] a)`. We use this approach to avoid repeating arguments in many very similar cases. Lean can automatically find both `a` and `l'` based on `l`. The most general theorem `measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae` can be seen as a generalization of lemma `integral_has_strict_fderiv_at` below which states strict differentiability of `∫ x in u..v, f x` in `(u, v)` at `(a, b)` for a measurable function `f` that is integrable on `a..b` and is continuous at `a` and `b`. The lemma is generalized in three directions: first, `measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae` deals with any locally finite measure `μ`; second, it works for one-sided limits/derivatives; third, it assumes only that `f` has finite limits almost surely at `a` and `b`. Namely, let `f` be a measurable function integrable on `a..b`. Let `(la, la')` be a pair of `FTC_filter`s around `a`; let `(lb, lb')` be a pair of `FTC_filter`s around `b`. Suppose that `f` has finite limits `ca` and `cb` at `la' ⊓ μ.ae` and `lb' ⊓ μ.ae`, respectively. Then `∫ x in va..vb, f x ∂μ - ∫ x in ua..ub, f x ∂μ = ∫ x in ub..vb, cb ∂μ - ∫ x in ua..va, ca ∂μ + o(∥∫ x in ua..va, (1:ℝ) ∂μ∥ + ∥∫ x in ub..vb, (1:ℝ) ∂μ∥)` as `ua` and `va` tend to `la` while `ub` and `vb` tend to `lb`. This theorem is formulated with integral of constants instead of measures in the right hand sides for two reasons: first, this way we avoid `min`/`max` in the statements; second, often it is possible to write better `simp` lemmas for these integrals, see `integral_const` and `integral_const_of_cdf`. In the next subsection we apply this theorem to prove various theorems about differentiability of the integral w.r.t. Lebesgue measure. -/ /-- An auxiliary typeclass for the Fundamental theorem of calculus, part 1. It is used to formulate theorems that work simultaneously for left and right one-sided derivatives of `∫ x in u..v, f x`. There are four instances: `(a, pure a, ⊥)`, `(a, 𝓝[Ici a], 𝓝[Ioi a])`, `(a, 𝓝[Iic a], 𝓝[Iic a])`, and `(a, 𝓝 a, 𝓝 a)`. -/ class FTC_filter {β : Type*} [linear_order β] [measurable_space β] [topological_space β] (a : out_param β) (outer : filter β) (inner : out_param $ filter β) extends tendsto_Ixx_class Ioc outer inner : Prop := (pure_le : pure a ≤ outer) (le_nhds : inner ≤ 𝓝 a) [meas_gen : is_measurably_generated inner] /- The `dangerous_instance` linter doesn't take `out_param`s into account, so it thinks that `FTC_filter.to_tendsto_Ixx_class` is dangerous. Disable this linter using `nolint`. -/ attribute [nolint dangerous_instance] FTC_filter.to_tendsto_Ixx_class namespace FTC_filter variables [linear_order β] [measurable_space β] [topological_space β] instance pure (a : β) : FTC_filter a (pure a) ⊥ := { pure_le := le_refl _, le_nhds := bot_le } instance nhds_within_singleton (a : β) : FTC_filter a (𝓝[{a}] a) ⊥ := by { rw [nhds_within, principal_singleton, inf_eq_right.2 (pure_le_nhds a)], apply_instance } lemma finite_at_inner {a : β} (l : filter β) {l'} [h : FTC_filter a l l'] {μ : measure β} [locally_finite_measure μ] : μ.finite_at_filter l' := (μ.finite_at_nhds a).filter_mono h.le_nhds variables [opens_measurable_space β] [order_topology β] instance nhds (a : β) : FTC_filter a (𝓝 a) (𝓝 a) := { pure_le := pure_le_nhds a, le_nhds := le_refl _ } instance nhds_univ (a : β) : FTC_filter a (𝓝[univ] a) (𝓝 a) := by { rw nhds_within_univ, apply_instance } instance nhds_left (a : β) : FTC_filter a (𝓝[Iic a] a) (𝓝[Iic a] a) := { pure_le := pure_le_nhds_within right_mem_Iic, le_nhds := inf_le_left } instance nhds_right (a : β) : FTC_filter a (𝓝[Ici a] a) (𝓝[Ioi a] a) := { pure_le := pure_le_nhds_within left_mem_Ici, le_nhds := inf_le_left } end FTC_filter open asymptotics section variables {f : α → E} {a b : α} {c ca cb : E} {l l' la la' lb lb' : filter α} {lt : filter β} {μ : measure α} {u v ua va ub vb : β → α} /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `tendsto_Ixx_class Ioc`. If `f` has a finite limit `c` at `l' ⊓ μ.ae`, where `μ` is a measure finite at `l'`, then `∫ x in u..v, f x ∂μ = ∫ x in u..v, c ∂μ + o(∫ x in u..v, 1 ∂μ)` as both `u` and `v` tend to `l`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae` for a version assuming `[FTC_filter a l l']` and `[locally_finite_measure μ]`. If `l` is one of `𝓝[Ici a] a`, `𝓝[Iic a] a`, `𝓝 a`, then it's easier to apply the non-primed version. The primed version also works, e.g., for `l = l' = at_top`. We use integrals of constants instead of measures because this way it is easier to formulate a statement that works in both cases `u ≤ v` and `v ≤ u`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae' [is_measurably_generated l'] [tendsto_Ixx_class Ioc l l'] (hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hl : μ.finite_at_filter l') (hu : tendsto u lt l) (hv : tendsto v lt l) : is_o (λ t, ∫ x in u t..v t, f x ∂μ - ∫ x in u t..v t, c ∂μ) (λ t, ∫ x in u t..v t, (1:ℝ) ∂μ) lt := begin have A := hf.integral_sub_linear_is_o_ae hfm hl (hu.Ioc hv), have B := hf.integral_sub_linear_is_o_ae hfm hl (hv.Ioc hu), simp only [integral_const'], convert (A.trans_le _).sub (B.trans_le _), { ext t, simp_rw [(∘), interval_integral, sub_smul], abel }, all_goals { intro t, cases le_total (u t) (v t) with huv huv; simp [huv] } end /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `tendsto_Ixx_class Ioc`. If `f` has a finite limit `c` at `l ⊓ μ.ae`, where `μ` is a measure finite at `l`, then `∫ x in u..v, f x ∂μ = μ (Ioc u v) • c + o(μ(Ioc u v))` as both `u` and `v` tend to `l` so that `u ≤ v`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae_of_le` for a version assuming `[FTC_filter a l l']` and `[locally_finite_measure μ]`. If `l` is one of `𝓝[Ici a] a`, `𝓝[Iic a] a`, `𝓝 a`, then it's easier to apply the non-primed version. The primed version also works, e.g., for `l = l' = at_top`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae_of_le' [is_measurably_generated l'] [tendsto_Ixx_class Ioc l l'] (hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hl : μ.finite_at_filter l') (hu : tendsto u lt l) (hv : tendsto v lt l) (huv : u ≤ᶠ[lt] v) : is_o (λ t, ∫ x in u t..v t, f x ∂μ - (μ (Ioc (u t) (v t))).to_real • c) (λ t, (μ $ Ioc (u t) (v t)).to_real) lt := (measure_integral_sub_linear_is_o_of_tendsto_ae' hfm hf hl hu hv).congr' (huv.mono $ λ x hx, by simp [integral_const', hx]) (huv.mono $ λ x hx, by simp [integral_const', hx]) /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `tendsto_Ixx_class Ioc`. If `f` has a finite limit `c` at `l ⊓ μ.ae`, where `μ` is a measure finite at `l`, then `∫ x in u..v, f x ∂μ = -μ (Ioc v u) • c + o(μ(Ioc v u))` as both `u` and `v` tend to `l` so that `v ≤ u`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge` for a version assuming `[FTC_filter a l l']` and `[locally_finite_measure μ]`. If `l` is one of `𝓝[Ici a] a`, `𝓝[Iic a] a`, `𝓝 a`, then it's easier to apply the non-primed version. The primed version also works, e.g., for `l = l' = at_top`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge' [is_measurably_generated l'] [tendsto_Ixx_class Ioc l l'] (hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hl : μ.finite_at_filter l') (hu : tendsto u lt l) (hv : tendsto v lt l) (huv : v ≤ᶠ[lt] u) : is_o (λ t, ∫ x in u t..v t, f x ∂μ + (μ (Ioc (v t) (u t))).to_real • c) (λ t, (μ $ Ioc (v t) (u t)).to_real) lt := (measure_integral_sub_linear_is_o_of_tendsto_ae_of_le' hfm hf hl hv hu huv).neg_left.congr_left $ λ t, by simp [integral_symm (u t), add_comm] variables [topological_space α] section variables [locally_finite_measure μ] [FTC_filter a l l'] include a local attribute [instance] FTC_filter.meas_gen /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `[FTC_filter a l l']`; let `μ` be a locally finite measure. If `f` has a finite limit `c` at `l' ⊓ μ.ae`, then `∫ x in u..v, f x ∂μ = ∫ x in u..v, c ∂μ + o(∫ x in u..v, 1 ∂μ)` as both `u` and `v` tend to `l`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae'` for a version that also works, e.g., for `l = l' = at_top`. We use integrals of constants instead of measures because this way it is easier to formulate a statement that works in both cases `u ≤ v` and `v ≤ u`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae (hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hu : tendsto u lt l) (hv : tendsto v lt l) : is_o (λ t, ∫ x in u t..v t, f x ∂μ - ∫ x in u t..v t, c ∂μ) (λ t, ∫ x in u t..v t, (1:ℝ) ∂μ) lt := measure_integral_sub_linear_is_o_of_tendsto_ae' hfm hf (FTC_filter.finite_at_inner l) hu hv /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `[FTC_filter a l l']`; let `μ` be a locally finite measure. If `f` has a finite limit `c` at `l' ⊓ μ.ae`, then `∫ x in u..v, f x ∂μ = μ (Ioc u v) • c + o(μ(Ioc u v))` as both `u` and `v` tend to `l`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae_of_le'` for a version that also works, e.g., for `l = l' = at_top`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae_of_le (hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hu : tendsto u lt l) (hv : tendsto v lt l) (huv : u ≤ᶠ[lt] v) : is_o (λ t, ∫ x in u t..v t, f x ∂μ - (μ (Ioc (u t) (v t))).to_real • c) (λ t, (μ $ Ioc (u t) (v t)).to_real) lt := measure_integral_sub_linear_is_o_of_tendsto_ae_of_le' hfm hf (FTC_filter.finite_at_inner l) hu hv huv /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `[FTC_filter a l l']`; let `μ` be a locally finite measure. If `f` has a finite limit `c` at `l' ⊓ μ.ae`, then `∫ x in u..v, f x ∂μ = -μ (Ioc v u) • c + o(μ(Ioc v u))` as both `u` and `v` tend to `l`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge'` for a version that also works, e.g., for `l = l' = at_top`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge (hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hu : tendsto u lt l) (hv : tendsto v lt l) (huv : v ≤ᶠ[lt] u) : is_o (λ t, ∫ x in u t..v t, f x ∂μ + (μ (Ioc (v t) (u t))).to_real • c) (λ t, (μ $ Ioc (v t) (u t)).to_real) lt := measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge' hfm hf (FTC_filter.finite_at_inner l) hu hv huv end variables [order_topology α] [borel_space α] local attribute [instance] FTC_filter.meas_gen variables [FTC_filter a la la'] [FTC_filter b lb lb'] [locally_finite_measure μ] /-- Fundamental theorem of calculus-1, strict derivative in both limits for a locally finite measure. Let `f` be a measurable function integrable on `a..b`. Let `(la, la')` be a pair of `FTC_filter`s around `a`; let `(lb, lb')` be a pair of `FTC_filter`s around `b`. Suppose that `f` has finite limits `ca` and `cb` at `la' ⊓ μ.ae` and `lb' ⊓ μ.ae`, respectively. Then `∫ x in va..vb, f x ∂μ - ∫ x in ua..ub, f x ∂μ = ∫ x in ub..vb, cb ∂μ - ∫ x in ua..va, ca ∂μ + o(∥∫ x in ua..va, (1:ℝ) ∂μ∥ + ∥∫ x in ub..vb, (1:ℝ) ∂μ∥)` as `ua` and `va` tend to `la` while `ub` and `vb` tend to `lb`. -/ lemma measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae (hab : interval_integrable f μ a b) (hmeas_a : measurable_at_filter f la' μ) (hmeas_b : measurable_at_filter f lb' μ) (ha_lim : tendsto f (la' ⊓ μ.ae) (𝓝 ca)) (hb_lim : tendsto f (lb' ⊓ μ.ae) (𝓝 cb)) (hua : tendsto ua lt la) (hva : tendsto va lt la) (hub : tendsto ub lt lb) (hvb : tendsto vb lt lb) : is_o (λ t, (∫ x in va t..vb t, f x ∂μ) - (∫ x in ua t..ub t, f x ∂μ) - (∫ x in ub t..vb t, cb ∂μ - ∫ x in ua t..va t, ca ∂μ)) (λ t, ∥∫ x in ua t..va t, (1:ℝ) ∂μ∥ + ∥∫ x in ub t..vb t, (1:ℝ) ∂μ∥) lt := begin refine ((measure_integral_sub_linear_is_o_of_tendsto_ae hmeas_a ha_lim hua hva).neg_left.add_add (measure_integral_sub_linear_is_o_of_tendsto_ae hmeas_b hb_lim hub hvb)).congr' _ (eventually_eq.refl _ _), have A : ∀ᶠ t in lt, interval_integrable f μ (ua t) (va t) := ha_lim.eventually_interval_integrable_ae hmeas_a (FTC_filter.finite_at_inner la) hua hva, have A' : ∀ᶠ t in lt, interval_integrable f μ a (ua t) := ha_lim.eventually_interval_integrable_ae hmeas_a (FTC_filter.finite_at_inner la) (tendsto_const_pure.mono_right FTC_filter.pure_le) hua, have B : ∀ᶠ t in lt, interval_integrable f μ (ub t) (vb t) := hb_lim.eventually_interval_integrable_ae hmeas_b (FTC_filter.finite_at_inner lb) hub hvb, have B' : ∀ᶠ t in lt, interval_integrable f μ b (ub t) := hb_lim.eventually_interval_integrable_ae hmeas_b (FTC_filter.finite_at_inner lb) (tendsto_const_pure.mono_right FTC_filter.pure_le) hub, filter_upwards [A, A', B, B'], intros t ua_va a_ua ub_vb b_ub, rw [← integral_interval_sub_interval_comm'], { dsimp only [], abel }, exacts [ub_vb, ua_va, b_ub.symm.trans $ hab.symm.trans a_ua] end /-- Fundamental theorem of calculus-1, strict derivative in right endpoint for a locally finite measure. Let `f` be a measurable function integrable on `a..b`. Let `(lb, lb')` be a pair of `FTC_filter`s around `b`. Suppose that `f` has a finite limit `c` at `lb' ⊓ μ.ae`. Then `∫ x in a..v, f x ∂μ - ∫ x in a..u, f x ∂μ = ∫ x in u..v, c ∂μ + o(∫ x in u..v, (1:ℝ) ∂μ)` as `u` and `v` tend to `lb`. -/ lemma measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right (hab : interval_integrable f μ a b) (hmeas : measurable_at_filter f lb' μ) (hf : tendsto f (lb' ⊓ μ.ae) (𝓝 c)) (hu : tendsto u lt lb) (hv : tendsto v lt lb) : is_o (λ t, ∫ x in a..v t, f x ∂μ - ∫ x in a..u t, f x ∂μ - ∫ x in u t..v t, c ∂μ) (λ t, ∫ x in u t..v t, (1:ℝ) ∂μ) lt := by simpa using measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae hab measurable_at_bot hmeas ((tendsto_bot : tendsto _ ⊥ (𝓝 0)).mono_left inf_le_left) hf (tendsto_const_pure : tendsto _ _ (pure a)) tendsto_const_pure hu hv /-- Fundamental theorem of calculus-1, strict derivative in left endpoint for a locally finite measure. Let `f` be a measurable function integrable on `a..b`. Let `(la, la')` be a pair of `FTC_filter`s around `a`. Suppose that `f` has a finite limit `c` at `la' ⊓ μ.ae`. Then `∫ x in v..b, f x ∂μ - ∫ x in u..b, f x ∂μ = -∫ x in u..v, c ∂μ + o(∫ x in u..v, (1:ℝ) ∂μ)` as `u` and `v` tend to `la`. -/ lemma measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae_left (hab : interval_integrable f μ a b) (hmeas : measurable_at_filter f la' μ) (hf : tendsto f (la' ⊓ μ.ae) (𝓝 c)) (hu : tendsto u lt la) (hv : tendsto v lt la) : is_o (λ t, ∫ x in v t..b, f x ∂μ - ∫ x in u t..b, f x ∂μ + ∫ x in u t..v t, c ∂μ) (λ t, ∫ x in u t..v t, (1:ℝ) ∂μ) lt := by simpa using measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae hab hmeas measurable_at_bot hf ((tendsto_bot : tendsto _ ⊥ (𝓝 0)).mono_left inf_le_left) hu hv (tendsto_const_pure : tendsto _ _ (pure b)) tendsto_const_pure end /-! ### Fundamental theorem of calculus-1 for Lebesgue measure In this section we restate theorems from the previous section for Lebesgue measure. In particular, we prove that `∫ x in u..v, f x` is strictly differentiable in `(u, v)` at `(a, b)` provided that `f` is integrable on `a..b` and is continuous at `a` and `b`. -/ variables {f : ℝ → E} {c ca cb : E} {l l' la la' lb lb' : filter ℝ} {lt : filter β} {a b z : ℝ} {u v ua ub va vb : β → ℝ} [FTC_filter a la la'] [FTC_filter b lb lb'] /-! #### Auxiliary `is_o` statements In this section we prove several lemmas that can be interpreted as strict differentiability of `(u, v) ↦ ∫ x in u..v, f x ∂μ` in `u` and/or `v` at a filter. The statements use `is_o` because we have no definition of `has_strict_(f)deriv_at_filter` in the library. -/ /-- Fundamental theorem of calculus-1, local version. If `f` has a finite limit `c` almost surely at `l'`, where `(l, l')` is an `FTC_filter` pair around `a`, then `∫ x in u..v, f x ∂μ = (v - u) • c + o (v - u)` as both `u` and `v` tend to `l`. -/ lemma integral_sub_linear_is_o_of_tendsto_ae [FTC_filter a l l'] (hfm : measurable_at_filter f l') (hf : tendsto f (l' ⊓ volume.ae) (𝓝 c)) {u v : β → ℝ} (hu : tendsto u lt l) (hv : tendsto v lt l) : is_o (λ t, (∫ x in u t..v t, f x) - (v t - u t) • c) (v - u) lt := by simpa [integral_const] using measure_integral_sub_linear_is_o_of_tendsto_ae hfm hf hu hv /-- Fundamental theorem of calculus-1, strict differentiability at filter in both endpoints. If `f` is a measurable function integrable on `a..b`, `(la, la')` is an `FTC_filter` pair around `a`, and `(lb, lb')` is an `FTC_filter` pair around `b`, and `f` has finite limits `ca` and `cb` almost surely at `la'` and `lb'`, respectively, then `(∫ x in va..vb, f x) - ∫ x in ua..ub, f x = (vb - ub) • cb - (va - ua) • ca + o(∥va - ua∥ + ∥vb - ub∥)` as `ua` and `va` tend to `la` while `ub` and `vb` tend to `lb`. This lemma could've been formulated using `has_strict_fderiv_at_filter` if we had this definition. -/ lemma integral_sub_integral_sub_linear_is_o_of_tendsto_ae (hab : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f la') (hmeas_b : measurable_at_filter f lb') (ha_lim : tendsto f (la' ⊓ volume.ae) (𝓝 ca)) (hb_lim : tendsto f (lb' ⊓ volume.ae) (𝓝 cb)) (hua : tendsto ua lt la) (hva : tendsto va lt la) (hub : tendsto ub lt lb) (hvb : tendsto vb lt lb) : is_o (λ t, (∫ x in va t..vb t, f x) - (∫ x in ua t..ub t, f x) - ((vb t - ub t) • cb - (va t - ua t) • ca)) (λ t, ∥va t - ua t∥ + ∥vb t - ub t∥) lt := by simpa [integral_const] using measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae hab hmeas_a hmeas_b ha_lim hb_lim hua hva hub hvb /-- Fundamental theorem of calculus-1, strict differentiability at filter in both endpoints. If `f` is a measurable function integrable on `a..b`, `(lb, lb')` is an `FTC_filter` pair around `b`, and `f` has a finite limit `c` almost surely at `lb'`, then `(∫ x in a..v, f x) - ∫ x in a..u, f x = (v - u) • c + o(∥v - u∥)` as `u` and `v` tend to `lb`. This lemma could've been formulated using `has_strict_deriv_at_filter` if we had this definition. -/ lemma integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right (hab : interval_integrable f volume a b) (hmeas : measurable_at_filter f lb') (hf : tendsto f (lb' ⊓ volume.ae) (𝓝 c)) (hu : tendsto u lt lb) (hv : tendsto v lt lb) : is_o (λ t, (∫ x in a..v t, f x) - (∫ x in a..u t, f x) - (v t - u t) • c) (v - u) lt := by simpa only [integral_const, smul_eq_mul, mul_one] using measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right hab hmeas hf hu hv /-- Fundamental theorem of calculus-1, strict differentiability at filter in both endpoints. If `f` is a measurable function integrable on `a..b`, `(la, la')` is an `FTC_filter` pair around `a`, and `f` has a finite limit `c` almost surely at `la'`, then `(∫ x in v..b, f x) - ∫ x in u..b, f x = -(v - u) • c + o(∥v - u∥)` as `u` and `v` tend to `la`. This lemma could've been formulated using `has_strict_deriv_at_filter` if we had this definition. -/ lemma integral_sub_integral_sub_linear_is_o_of_tendsto_ae_left (hab : interval_integrable f volume a b) (hmeas : measurable_at_filter f la') (hf : tendsto f (la' ⊓ volume.ae) (𝓝 c)) (hu : tendsto u lt la) (hv : tendsto v lt la) : is_o (λ t, (∫ x in v t..b, f x) - (∫ x in u t..b, f x) + (v t - u t) • c) (v - u) lt := by simpa only [integral_const, smul_eq_mul, mul_one] using measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae_left hab hmeas hf hu hv open continuous_linear_map (fst snd smul_right sub_apply smul_right_apply coe_fst' coe_snd' map_sub) /-! #### Strict differentiability In this section we prove that for a measurable function `f` integrable on `a..b`, * `integral_has_strict_fderiv_at_of_tendsto_ae`: the function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)` in the sense of strict differentiability provided that `f` tends to `ca` and `cb` almost surely as `x` tendsto to `a` and `b`, respectively; * `integral_has_strict_fderiv_at`: the function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • f b - u • f a` at `(a, b)` in the sense of strict differentiability provided that `f` is continuous at `a` and `b`; * `integral_has_strict_deriv_at_of_tendsto_ae_right`: the function `u ↦ ∫ x in a..u, f x` has derivative `c` at `b` in the sense of strict differentiability provided that `f` tends to `c` almost surely as `x` tends to `b`; * `integral_has_strict_deriv_at_right`: the function `u ↦ ∫ x in a..u, f x` has derivative `f b` at `b` in the sense of strict differentiability provided that `f` is continuous at `b`; * `integral_has_strict_deriv_at_of_tendsto_ae_left`: the function `u ↦ ∫ x in u..b, f x` has derivative `-c` at `a` in the sense of strict differentiability provided that `f` tends to `c` almost surely as `x` tends to `a`; * `integral_has_strict_deriv_at_left`: the function `u ↦ ∫ x in u..b, f x` has derivative `-f a` at `a` in the sense of strict differentiability provided that `f` is continuous at `a`. -/ /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has finite limits `ca` and `cb` almost surely as `x` tends to `a` and `b`, respectively, then `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)` in the sense of strict differentiability. -/ lemma integral_has_strict_fderiv_at_of_tendsto_ae (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b)) (ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 cb)) : has_strict_fderiv_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca) (a, b) := begin have := integral_sub_integral_sub_linear_is_o_of_tendsto_ae hf hmeas_a hmeas_b ha hb ((continuous_fst.comp continuous_snd).tendsto ((a, b), (a, b))) ((continuous_fst.comp continuous_fst).tendsto ((a, b), (a, b))) ((continuous_snd.comp continuous_snd).tendsto ((a, b), (a, b))) ((continuous_snd.comp continuous_fst).tendsto ((a, b), (a, b))), refine (this.congr_left _).trans_is_O _, { intro x, simp [sub_smul] }, { exact is_O_fst_prod.norm_left.add is_O_snd_prod.norm_left } end /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a` and `b`, then `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)` in the sense of strict differentiability. -/ lemma integral_has_strict_fderiv_at (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b)) (ha : continuous_at f a) (hb : continuous_at f b) : has_strict_fderiv_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right (f b) - (fst ℝ ℝ ℝ).smul_right (f a)) (a, b) := integral_has_strict_fderiv_at_of_tendsto_ae hf hmeas_a hmeas_b (ha.mono_left inf_le_left) (hb.mono_left inf_le_left) /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely at `b`, then `u ↦ ∫ x in a..u, f x` has derivative `c` at `b` in the sense of strict differentiability. -/ lemma integral_has_strict_deriv_at_of_tendsto_ae_right (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 c)) : has_strict_deriv_at (λ u, ∫ x in a..u, f x) c b := integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right hf hmeas hb continuous_at_snd continuous_at_fst /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `b`, then `u ↦ ∫ x in a..u, f x` has derivative `f b` at `b` in the sense of strict differentiability. -/ lemma integral_has_strict_deriv_at_right (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b)) (hb : continuous_at f b) : has_strict_deriv_at (λ u, ∫ x in a..u, f x) (f b) b := integral_has_strict_deriv_at_of_tendsto_ae_right hf hmeas (hb.mono_left inf_le_left) /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely at `a`, then `u ↦ ∫ x in u..b, f x` has derivative `-c` at `a` in the sense of strict differentiability. -/ lemma integral_has_strict_deriv_at_of_tendsto_ae_left (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a)) (ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 c)) : has_strict_deriv_at (λ u, ∫ x in u..b, f x) (-c) a := by simpa only [← integral_symm] using (integral_has_strict_deriv_at_of_tendsto_ae_right hf.symm hmeas ha).neg /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a`, then `u ↦ ∫ x in u..b, f x` has derivative `-f a` at `a` in the sense of strict differentiability. -/ lemma integral_has_strict_deriv_at_left (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a)) (ha : continuous_at f a) : has_strict_deriv_at (λ u, ∫ x in u..b, f x) (-f a) a := by simpa only [← integral_symm] using (integral_has_strict_deriv_at_right hf.symm hmeas ha).neg /-! #### Fréchet differentiability In this subsection we restate results from the previous subsection in terms of `has_fderiv_at`, `has_deriv_at`, `fderiv`, and `deriv`. -/ /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has finite limits `ca` and `cb` almost surely as `x` tends to `a` and `b`, respectively, then `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)`. -/ lemma integral_has_fderiv_at_of_tendsto_ae (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b)) (ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 cb)) : has_fderiv_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca) (a, b) := (integral_has_strict_fderiv_at_of_tendsto_ae hf hmeas_a hmeas_b ha hb).has_fderiv_at /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a` and `b`, then `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)`. -/ lemma integral_has_fderiv_at (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b)) (ha : continuous_at f a) (hb : continuous_at f b) : has_fderiv_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right (f b) - (fst ℝ ℝ ℝ).smul_right (f a)) (a, b) := (integral_has_strict_fderiv_at hf hmeas_a hmeas_b ha hb).has_fderiv_at /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has finite limits `ca` and `cb` almost surely as `x` tends to `a` and `b`, respectively, then `fderiv` derivative of `(u, v) ↦ ∫ x in u..v, f x` at `(a, b)` equals `(u, v) ↦ v • cb - u • ca`. -/ lemma fderiv_integral_of_tendsto_ae (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b)) (ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 cb)) : fderiv ℝ (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) (a, b) = (snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca := (integral_has_fderiv_at_of_tendsto_ae hf hmeas_a hmeas_b ha hb).fderiv /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a` and `b`, then `fderiv` derivative of `(u, v) ↦ ∫ x in u..v, f x` at `(a, b)` equals `(u, v) ↦ v • cb - u • ca`. -/ lemma fderiv_integral (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b)) (ha : continuous_at f a) (hb : continuous_at f b) : fderiv ℝ (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) (a, b) = (snd ℝ ℝ ℝ).smul_right (f b) - (fst ℝ ℝ ℝ).smul_right (f a) := (integral_has_fderiv_at hf hmeas_a hmeas_b ha hb).fderiv /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely at `b`, then `u ↦ ∫ x in a..u, f x` has derivative `c` at `b`. -/ lemma integral_has_deriv_at_of_tendsto_ae_right (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 c)) : has_deriv_at (λ u, ∫ x in a..u, f x) c b := (integral_has_strict_deriv_at_of_tendsto_ae_right hf hmeas hb).has_deriv_at /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `b`, then `u ↦ ∫ x in a..u, f x` has derivative `f b` at `b`. -/ lemma integral_has_deriv_at_right (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b)) (hb : continuous_at f b) : has_deriv_at (λ u, ∫ x in a..u, f x) (f b) b := (integral_has_strict_deriv_at_right hf hmeas hb).has_deriv_at /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f` has a finite limit `c` almost surely at `b`, then the derivative of `u ↦ ∫ x in a..u, f x` at `b` equals `c`. -/ lemma deriv_integral_of_tendsto_ae_right (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 c)) : deriv (λ u, ∫ x in a..u, f x) b = c := (integral_has_deriv_at_of_tendsto_ae_right hf hmeas hb).deriv /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `b`, then the derivative of `u ↦ ∫ x in a..u, f x` at `b` equals `f b`. -/ lemma deriv_integral_right (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b)) (hb : continuous_at f b) : deriv (λ u, ∫ x in a..u, f x) b = f b := (integral_has_deriv_at_right hf hmeas hb).deriv /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely at `a`, then `u ↦ ∫ x in u..b, f x` has derivative `-c` at `a`. -/ lemma integral_has_deriv_at_of_tendsto_ae_left (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a)) (ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 c)) : has_deriv_at (λ u, ∫ x in u..b, f x) (-c) a := (integral_has_strict_deriv_at_of_tendsto_ae_left hf hmeas ha).has_deriv_at /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a`, then `u ↦ ∫ x in u..b, f x` has derivative `-f a` at `a`. -/ lemma integral_has_deriv_at_left (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a)) (ha : continuous_at f a) : has_deriv_at (λ u, ∫ x in u..b, f x) (-f a) a := (integral_has_strict_deriv_at_left hf hmeas ha).has_deriv_at /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f` has a finite limit `c` almost surely at `a`, then the derivative of `u ↦ ∫ x in u..b, f x` at `a` equals `-c`. -/ lemma deriv_integral_of_tendsto_ae_left (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a)) (hb : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 c)) : deriv (λ u, ∫ x in u..b, f x) a = -c := (integral_has_deriv_at_of_tendsto_ae_left hf hmeas hb).deriv /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a`, then the derivative of `u ↦ ∫ x in u..b, f x` at `a` equals `-f a`. -/ lemma deriv_integral_left (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a)) (hb : continuous_at f a) : deriv (λ u, ∫ x in u..b, f x) a = -f a := (integral_has_deriv_at_left hf hmeas hb).deriv /-! #### One-sided derivatives -/ /-- Let `f` be a measurable function integrable on `a..b`. The function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` within `s × t` at `(a, b)`, where `s ∈ {Iic a, {a}, Ici a, univ}` and `t ∈ {Iic b, {b}, Ici b, univ}` provided that `f` tends to `ca` and `cb` almost surely at the filters `la` and `lb` from the following table. | `s` | `la` | `t` | `lb` | | ------- | ---- | --- | ---- | | `Iic a` | `𝓝[Iic a] a` | `Iic b` | `𝓝[Iic b] b` | | `Ici a` | `𝓝[Ioi a] a` | `Ici b` | `𝓝[Ioi b] b` | | `{a}` | `⊥` | `{b}` | `⊥` | | `univ` | `𝓝 a` | `univ` | `𝓝 b` | -/ lemma integral_has_fderiv_within_at_of_tendsto_ae (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter a (𝓝[s] a) la] [FTC_filter b (𝓝[t] b) lb] (hmeas_a : measurable_at_filter f la) (hmeas_b : measurable_at_filter f lb) (ha : tendsto f (la ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (lb ⊓ volume.ae) (𝓝 cb)) : has_fderiv_within_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca) (s.prod t) (a, b) := begin rw [has_fderiv_within_at, nhds_within_prod_eq], have := integral_sub_integral_sub_linear_is_o_of_tendsto_ae hf hmeas_a hmeas_b ha hb (tendsto_const_pure.mono_right FTC_filter.pure_le : tendsto _ _ (𝓝[s] a)) tendsto_fst (tendsto_const_pure.mono_right FTC_filter.pure_le : tendsto _ _ (𝓝[t] b)) tendsto_snd, refine (this.congr_left _).trans_is_O _, { intro x, simp [sub_smul] }, { exact is_O_fst_prod.norm_left.add is_O_snd_prod.norm_left } end /-- Let `f` be a measurable function integrable on `a..b`. The function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • f b - u • f a` within `s × t` at `(a, b)`, where `s ∈ {Iic a, {a}, Ici a, univ}` and `t ∈ {Iic b, {b}, Ici b, univ}` provided that `f` tends to `f a` and `f b` at the filters `la` and `lb` from the following table. In most cases this assumption is definitionally equal `continuous_at f _` or `continuous_within_at f _ _`. | `s` | `la` | `t` | `lb` | | ------- | ---- | --- | ---- | | `Iic a` | `𝓝[Iic a] a` | `Iic b` | `𝓝[Iic b] b` | | `Ici a` | `𝓝[Ioi a] a` | `Ici b` | `𝓝[Ioi b] b` | | `{a}` | `⊥` | `{b}` | `⊥` | | `univ` | `𝓝 a` | `univ` | `𝓝 b` | -/ lemma integral_has_fderiv_within_at (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f la) (hmeas_b : measurable_at_filter f lb) {s t : set ℝ} [FTC_filter a (𝓝[s] a) la] [FTC_filter b (𝓝[t] b) lb] (ha : tendsto f la (𝓝 $ f a)) (hb : tendsto f lb (𝓝 $ f b)) : has_fderiv_within_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right (f b) - (fst ℝ ℝ ℝ).smul_right (f a)) (s.prod t) (a, b) := integral_has_fderiv_within_at_of_tendsto_ae hf hmeas_a hmeas_b (ha.mono_left inf_le_left) (hb.mono_left inf_le_left) /-- An auxiliary tactic closing goals `unique_diff_within_at ℝ s a` where `s ∈ {Iic a, Ici a, univ}`. -/ meta def unique_diff_within_at_Ici_Iic_univ : tactic unit := `[apply_rules [unique_diff_on.unique_diff_within_at, unique_diff_on_Ici, unique_diff_on_Iic, left_mem_Ici, right_mem_Iic, unique_diff_within_at_univ]] /-- Let `f` be a measurable function integrable on `a..b`. Choose `s ∈ {Iic a, Ici a, univ}` and `t ∈ {Iic b, Ici b, univ}`. Suppose that `f` tends to `ca` and `cb` almost surely at the filters `la` and `lb` from the table below. Then `fderiv_within ℝ (λ p, ∫ x in p.1..p.2, f x) (s.prod t)` is equal to `(u, v) ↦ u • cb - v • ca`. | `s` | `la` | `t` | `lb` | | ------- | ---- | --- | ---- | | `Iic a` | `𝓝[Iic a] a` | `Iic b` | `𝓝[Iic b] b` | | `Ici a` | `𝓝[Ioi a] a` | `Ici b` | `𝓝[Ioi b] b` | | `univ` | `𝓝 a` | `univ` | `𝓝 b` | -/ lemma fderiv_within_integral_of_tendsto_ae (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f la) (hmeas_b : measurable_at_filter f lb) {s t : set ℝ} [FTC_filter a (𝓝[s] a) la] [FTC_filter b (𝓝[t] b) lb] (ha : tendsto f (la ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (lb ⊓ volume.ae) (𝓝 cb)) (hs : unique_diff_within_at ℝ s a . unique_diff_within_at_Ici_Iic_univ) (ht : unique_diff_within_at ℝ t b . unique_diff_within_at_Ici_Iic_univ) : fderiv_within ℝ (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) (s.prod t) (a, b) = ((snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca) := (integral_has_fderiv_within_at_of_tendsto_ae hf hmeas_a hmeas_b ha hb).fderiv_within $ hs.prod ht /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely as `x` tends to `b` from the right or from the left, then `u ↦ ∫ x in a..u, f x` has right (resp., left) derivative `c` at `b`. -/ lemma integral_has_deriv_within_at_of_tendsto_ae_right (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter b (𝓝[s] b) (𝓝[t] b)] (hmeas : measurable_at_filter f (𝓝[t] b)) (hb : tendsto f (𝓝[t] b ⊓ volume.ae) (𝓝 c)) : has_deriv_within_at (λ u, ∫ x in a..u, f x) c s b := integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right hf hmeas hb (tendsto_const_pure.mono_right FTC_filter.pure_le) tendsto_id /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` is continuous from the left or from the right at `b`, then `u ↦ ∫ x in a..u, f x` has left (resp., right) derivative `f b` at `b`. -/ lemma integral_has_deriv_within_at_right (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter b (𝓝[s] b) (𝓝[t] b)] (hmeas : measurable_at_filter f (𝓝[t] b)) (hb : continuous_within_at f t b) : has_deriv_within_at (λ u, ∫ x in a..u, f x) (f b) s b := integral_has_deriv_within_at_of_tendsto_ae_right hf hmeas (hb.mono_left inf_le_left) /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely as `x` tends to `b` from the right or from the left, then the right (resp., left) derivative of `u ↦ ∫ x in a..u, f x` at `b` equals `c`. -/ lemma deriv_within_integral_of_tendsto_ae_right (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter b (𝓝[s] b) (𝓝[t] b)] (hmeas: measurable_at_filter f (𝓝[t] b)) (hb : tendsto f (𝓝[t] b ⊓ volume.ae) (𝓝 c)) (hs : unique_diff_within_at ℝ s b . unique_diff_within_at_Ici_Iic_univ) : deriv_within (λ u, ∫ x in a..u, f x) s b = c := (integral_has_deriv_within_at_of_tendsto_ae_right hf hmeas hb).deriv_within hs /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` is continuous on the right or on the left at `b`, then the right (resp., left) derivative of `u ↦ ∫ x in a..u, f x` at `b` equals `f b`. -/ lemma deriv_within_integral_right (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter b (𝓝[s] b) (𝓝[t] b)] (hmeas : measurable_at_filter f (𝓝[t] b)) (hb : continuous_within_at f t b) (hs : unique_diff_within_at ℝ s b . unique_diff_within_at_Ici_Iic_univ) : deriv_within (λ u, ∫ x in a..u, f x) s b = f b := (integral_has_deriv_within_at_right hf hmeas hb).deriv_within hs /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely as `x` tends to `a` from the right or from the left, then `u ↦ ∫ x in u..b, f x` has right (resp., left) derivative `-c` at `a`. -/ lemma integral_has_deriv_within_at_of_tendsto_ae_left (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter a (𝓝[s] a) (𝓝[t] a)] (hmeas : measurable_at_filter f (𝓝[t] a)) (ha : tendsto f (𝓝[t] a ⊓ volume.ae) (𝓝 c)) : has_deriv_within_at (λ u, ∫ x in u..b, f x) (-c) s a := by { simp only [integral_symm b], exact (integral_has_deriv_within_at_of_tendsto_ae_right hf.symm hmeas ha).neg } /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` is continuous from the left or from the right at `a`, then `u ↦ ∫ x in u..b, f x` has left (resp., right) derivative `-f a` at `a`. -/ lemma integral_has_deriv_within_at_left (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter a (𝓝[s] a) (𝓝[t] a)] (hmeas : measurable_at_filter f (𝓝[t] a)) (ha : continuous_within_at f t a) : has_deriv_within_at (λ u, ∫ x in u..b, f x) (-f a) s a := integral_has_deriv_within_at_of_tendsto_ae_left hf hmeas (ha.mono_left inf_le_left) /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely as `x` tends to `a` from the right or from the left, then the right (resp., left) derivative of `u ↦ ∫ x in u..b, f x` at `a` equals `-c`. -/ lemma deriv_within_integral_of_tendsto_ae_left (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter a (𝓝[s] a) (𝓝[t] a)] (hmeas : measurable_at_filter f (𝓝[t] a)) (ha : tendsto f (𝓝[t] a ⊓ volume.ae) (𝓝 c)) (hs : unique_diff_within_at ℝ s a . unique_diff_within_at_Ici_Iic_univ) : deriv_within (λ u, ∫ x in u..b, f x) s a = -c := (integral_has_deriv_within_at_of_tendsto_ae_left hf hmeas ha).deriv_within hs /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` is continuous on the right or on the left at `a`, then the right (resp., left) derivative of `u ↦ ∫ x in u..b, f x` at `a` equals `-f a`. -/ lemma deriv_within_integral_left (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter a (𝓝[s] a) (𝓝[t] a)] (hmeas : measurable_at_filter f (𝓝[t] a)) (ha : continuous_within_at f t a) (hs : unique_diff_within_at ℝ s a . unique_diff_within_at_Ici_Iic_univ) : deriv_within (λ u, ∫ x in u..b, f x) s a = -f a := (integral_has_deriv_within_at_left hf hmeas ha).deriv_within hs /-! ### Fundamental theorem of calculus, part 2 This section contains theorems pertaining to FTC-2 for interval integrals. -/ variables {f' : ℝ → E} /-- The integral of a continuous function is differentiable on a real set `s`. -/ theorem differentiable_on_integral_of_continuous {s : set ℝ} (hintg : ∀ x ∈ s, interval_integrable f volume a x) (hcont : continuous f) : differentiable_on ℝ (λ u, ∫ x in a..u, f x) s := λ y hy, (integral_has_deriv_at_right (hintg y hy) hcont.measurable.ae_measurable.measurable_at_filter hcont.continuous_at) .differentiable_at.differentiable_within_at /-- The integral of a continuous function is continuous on a real set `s`. This is true even without the assumption of continuity, but a proof of that fact does not yet exist in mathlib. -/ theorem continuous_on_integral_of_continuous {s : set ℝ} (hintg : ∀ x ∈ s, interval_integrable f volume a x) (hcont : continuous f) : continuous_on (λ u, ∫ x in a..u, f x) s := (differentiable_on_integral_of_continuous hintg hcont).continuous_on /-- Fundamental theorem of calculus-2: If `f : ℝ → E` is continuous on `[a, b]` and has a right derivative at `f' x` for all `x` in `[a, b)`, and `f'` is continuous on `[a, b]` and measurable, then `∫ y in a..b, f' y` equals `f b - f a`. -/ theorem integral_eq_sub_of_has_deriv_right_of_le (hab : a ≤ b) (hcont : continuous_on f (Icc a b)) (hderiv : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) (hcont' : continuous_on f' (Icc a b)) : ∫ y in a..b, f' y = f b - f a := begin have hmeas' : ae_measurable f' (volume.restrict (Icc a b)), from hcont'.ae_measurable is_measurable_Icc, refine eq_sub_of_add_eq (eq_of_has_deriv_right_eq (λ y hy, _) hderiv (λ y hy, _) hcont (by simp) _ (right_mem_Icc.2 hab)), { refine (integral_has_deriv_within_at_right _ _ _).add_const _, { refine (hcont'.mono _).interval_integrable, simp only [hy.left, Icc_subset_Icc_right hy.right.le, interval_of_le] }, { exact ⟨_, Icc_mem_nhds_within_Ioi hy, hmeas'⟩, }, { exact (hcont' _ (mem_Icc_of_Ico hy)).mono_of_mem (Icc_mem_nhds_within_Ioi hy) } }, { -- TODO: prove that integral of any integrable function is continuous, and use here letI : tendsto_Ixx_class Ioc (𝓟 (Icc a b)) (𝓟 (Ioc a b)) := tendsto_Ixx_class_principal.2 (λ x hx y hy, Ioc_subset_Ioc hx.1 hy.2), haveI : is_measurably_generated (𝓝[Ioc a b] y) := is_measurable_Ioc.nhds_within_is_measurably_generated y, letI : FTC_filter y (𝓝[Icc a b] y) (𝓝[Ioc a b] y) := ⟨pure_le_nhds_within hy, inf_le_left⟩, refine (integral_has_deriv_within_at_right _ _ _).continuous_within_at.add continuous_within_at_const, { exact (hcont'.mono $ Icc_subset_Icc_right hy.2).interval_integrable_of_Icc hy.1 }, { exact ⟨_, mem_sets_of_superset self_mem_nhds_within Ioc_subset_Icc_self, hmeas'⟩ }, { exact (hcont' y hy).mono Ioc_subset_Icc_self } } end /-- Fundamental theorem of calculus-2: If `f : ℝ → E` is continuous on `[a, b]` (where `a ≤ b`) and has a right derivative at `f' x` for all `x` in `[a, b)`, and `f'` is continuous on `[a, b]` and measurable, then `∫ y in a..b, f' y` equals `f b - f a`. -/ theorem integral_eq_sub_of_has_deriv_right (hcont : continuous_on f (interval a b)) (hderiv : ∀ x ∈ Ico (min a b) (max a b), has_deriv_within_at f (f' x) (Ici x) x) (hcont' : continuous_on f' (interval a b)) : ∫ y in a..b, f' y = f b - f a := begin cases le_total a b with hab hab, { simp only [interval_of_le, min_eq_left, max_eq_right, hab] at hcont hcont' hderiv, exact integral_eq_sub_of_has_deriv_right_of_le hab hcont hderiv hcont' }, { simp only [interval_of_ge, min_eq_right, max_eq_left, hab] at hcont hcont' hderiv, rw [integral_symm, integral_eq_sub_of_has_deriv_right_of_le hab hcont hderiv hcont', neg_sub] } end /-- Fundamental theorem of calculus-2: If `f : ℝ → E` is continuous on `[a, b]` and has a derivative at `f' x` for all `x` in `[a, b)`, and `f'` is continuous on `[a, b]` and measurable, then `∫ y in a..b, f' y` equals `f b - f a`. -/ theorem integral_eq_sub_of_has_deriv_at' (hcont : continuous_on f (interval a b)) (hderiv : ∀ x ∈ Ico (min a b) (max a b), has_deriv_at f (f' x) x) (hcont' : continuous_on f' (interval a b)) : ∫ y in a..b, f' y = f b - f a := integral_eq_sub_of_has_deriv_right hcont (λ x hx, (hderiv x hx).has_deriv_within_at) hcont' /-- Fundamental theorem of calculus-2: If `f : ℝ → E` has a derivative at `f' x` for all `x` in `[a, b]` and `f'` is continuous on `[a, b]` and measurable, then `∫ y in a..b, f' y` equals `f b - f a`. -/ theorem integral_eq_sub_of_has_deriv_at (hderiv : ∀ x ∈ interval a b, has_deriv_at f (f' x) x) (hcont' : continuous_on f' (interval a b)) : ∫ y in a..b, f' y = f b - f a := integral_eq_sub_of_has_deriv_at' (λ x hx, (hderiv x hx).continuous_at.continuous_within_at) (λ x hx, hderiv _ (mem_Icc_of_Ico hx)) hcont' /-- Fundamental theorem of calculus-2: If `f : ℝ → E` is differentiable at every `x` in `[a, b]` and its derivative is continuous on `[a, b]`, then `∫ y in a..b, deriv f y` equals `f b - f a`. -/ theorem integral_deriv_eq_sub (hderiv : ∀ x ∈ interval a b, differentiable_at ℝ f x) (hcont' : continuous_on (deriv f) (interval a b)) : ∫ y in a..b, deriv f y = f b - f a := integral_eq_sub_of_has_deriv_at (λ x hx, (hderiv x hx).has_deriv_at) hcont' end interval_integral
2a87a58f2dcb7a3df964be4e5c1473431e3c7086
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/nat/basic.lean
e8a701cb2757c5d1b3e44c0a81903d0a621c3e33
[ "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
62,103
lean
/- Copyright (c) 2014 Floris van Doorn (c) 2016 Microsoft Corporation. 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 -/ import algebra.group_power.basic import algebra.order_functions /-! # Basic operations on the natural numbers This file contains: - instances on the natural numbers - some basic lemmas about natural numbers - extra recursors: * `le_rec_on`, `le_induction`: recursion and induction principles starting at non-zero numbers * `decreasing_induction`: recursion growing downwards * `strong_rec'`: recursion based on strong inequalities - decidability instances on predicates about the natural numbers -/ universes u v /-! ### instances -/ instance : nontrivial ℕ := ⟨⟨0, 1, nat.zero_ne_one⟩⟩ instance : comm_semiring nat := { add := nat.add, add_assoc := nat.add_assoc, zero := nat.zero, zero_add := nat.zero_add, add_zero := nat.add_zero, add_comm := nat.add_comm, mul := nat.mul, mul_assoc := nat.mul_assoc, one := nat.succ nat.zero, one_mul := nat.one_mul, mul_one := nat.mul_one, left_distrib := nat.left_distrib, right_distrib := nat.right_distrib, zero_mul := nat.zero_mul, mul_zero := nat.mul_zero, mul_comm := nat.mul_comm } instance : linear_ordered_semiring nat := { add_left_cancel := @nat.add_left_cancel, add_right_cancel := @nat.add_right_cancel, lt := nat.lt, add_le_add_left := @nat.add_le_add_left, le_of_add_le_add_left := @nat.le_of_add_le_add_left, zero_le_one := nat.le_of_lt (nat.zero_lt_succ 0), mul_lt_mul_of_pos_left := @nat.mul_lt_mul_of_pos_left, mul_lt_mul_of_pos_right := @nat.mul_lt_mul_of_pos_right, decidable_eq := nat.decidable_eq, exists_pair_ne := ⟨0, 1, ne_of_lt nat.zero_lt_one⟩, ..nat.comm_semiring, ..nat.linear_order } -- all the fields are already included in the linear_ordered_semiring instance instance : linear_ordered_cancel_add_comm_monoid ℕ := { add_left_cancel := @nat.add_left_cancel, ..nat.linear_ordered_semiring } /-! Extra instances to short-circuit type class resolution -/ instance : add_comm_monoid nat := by apply_instance instance : add_monoid nat := by apply_instance instance : monoid nat := by apply_instance instance : comm_monoid nat := by apply_instance instance : comm_semigroup nat := by apply_instance instance : semigroup nat := by apply_instance instance : add_comm_semigroup nat := by apply_instance instance : add_semigroup nat := by apply_instance instance : distrib nat := by apply_instance instance : semiring nat := by apply_instance instance : ordered_semiring nat := by apply_instance instance : canonically_ordered_comm_semiring ℕ := { le_iff_exists_add := assume a b, ⟨assume h, let ⟨c, hc⟩ := nat.le.dest h in ⟨c, hc.symm⟩, assume ⟨c, hc⟩, hc.symm ▸ nat.le_add_right _ _⟩, eq_zero_or_eq_zero_of_mul_eq_zero := assume a b, nat.eq_zero_of_mul_eq_zero, bot := 0, bot_le := nat.zero_le, .. nat.nontrivial, .. (infer_instance : ordered_add_comm_monoid ℕ), .. (infer_instance : linear_ordered_semiring ℕ), .. (infer_instance : comm_semiring ℕ) } instance nat.subtype.semilattice_sup_bot (s : set ℕ) [decidable_pred s] [h : nonempty s] : semilattice_sup_bot s := { bot := ⟨nat.find (nonempty_subtype.1 h), nat.find_spec (nonempty_subtype.1 h)⟩, bot_le := λ x, nat.find_min' _ x.2, ..subtype.linear_order s, ..lattice_of_linear_order } theorem nat.eq_of_mul_eq_mul_right {n m k : ℕ} (Hm : 0 < m) (H : n * m = k * m) : n = k := by rw [mul_comm n m, mul_comm k m] at H; exact nat.eq_of_mul_eq_mul_left Hm H instance nat.comm_cancel_monoid_with_zero : comm_cancel_monoid_with_zero ℕ := { mul_left_cancel_of_ne_zero := λ _ _ _ h1 h2, nat.eq_of_mul_eq_mul_left (nat.pos_of_ne_zero h1) h2, mul_right_cancel_of_ne_zero := λ _ _ _ h1 h2, nat.eq_of_mul_eq_mul_right (nat.pos_of_ne_zero h1) h2, .. (infer_instance : comm_monoid_with_zero ℕ) } /-! Inject some simple facts into the type class system. This `fact` should not be confused with the factorial function `nat.fact`! -/ section facts instance succ_pos'' (n : ℕ) : fact (0 < n.succ) := n.succ_pos instance pos_of_one_lt (n : ℕ) [h : fact (1 < n)] : fact (0 < n) := lt_trans zero_lt_one h end facts namespace nat variables {m n k : ℕ} /-! ### Recursion and `set.range` -/ section set open set theorem zero_union_range_succ : {0} ∪ range succ = univ := by { ext n, cases n; simp } variables {α : Type*} theorem range_of_succ (f : ℕ → α) : {f 0} ∪ range (f ∘ succ) = range f := by rw [← image_singleton, range_comp, ← image_union, zero_union_range_succ, image_univ] theorem range_rec {α : Type*} (x : α) (f : ℕ → α → α) : (set.range (λ n, nat.rec x f n) : set α) = {x} ∪ set.range (λ n, nat.rec (f 0 x) (f ∘ succ) n) := begin convert (range_of_succ _).symm, ext n, induction n with n ihn, { refl }, { dsimp at ihn ⊢, rw ihn } end theorem range_cases_on {α : Type*} (x : α) (f : ℕ → α) : (set.range (λ n, nat.cases_on n x f) : set α) = {x} ∪ set.range f := (range_of_succ _).symm end set /-! ### The units of the natural numbers as a `monoid` and `add_monoid` -/ theorem units_eq_one (u : units ℕ) : u = 1 := units.ext $ nat.eq_one_of_dvd_one ⟨u.inv, u.val_inv.symm⟩ theorem add_units_eq_zero (u : add_units ℕ) : u = 0 := add_units.ext $ (nat.eq_zero_of_add_eq_zero u.val_neg).1 @[simp] protected theorem is_unit_iff {n : ℕ} : is_unit n ↔ n = 1 := iff.intro (assume ⟨u, hu⟩, match n, u, hu, nat.units_eq_one u with _, _, rfl, rfl := rfl end) (assume h, h.symm ▸ ⟨1, rfl⟩) /-! ### Equalities and inequalities involving zero and one -/ theorem pos_iff_ne_zero : 0 < n ↔ n ≠ 0 := ⟨ne_of_gt, nat.pos_of_ne_zero⟩ lemma one_lt_iff_ne_zero_and_ne_one : ∀ {n : ℕ}, 1 < n ↔ n ≠ 0 ∧ n ≠ 1 | 0 := dec_trivial | 1 := dec_trivial | (n+2) := dec_trivial 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 @[simp] protected theorem mul_eq_zero {a b : ℕ} : a * b = 0 ↔ a = 0 ∨ b = 0 := iff.intro eq_zero_of_mul_eq_zero (by simp [or_imp_distrib] {contextual := tt}) @[simp] protected theorem zero_eq_mul {a b : ℕ} : 0 = a * b ↔ a = 0 ∨ b = 0 := by rw [eq_comm, nat.mul_eq_zero] lemma eq_zero_of_double_le {a : ℕ} (h : 2 * a ≤ a) : a = 0 := nat.eq_zero_of_le_zero $ by rwa [two_mul, nat.add_le_to_le_sub, nat.sub_self] at h; refl lemma eq_zero_of_mul_le {a b : ℕ} (hb : 2 ≤ b) (h : b * a ≤ a) : a = 0 := eq_zero_of_double_le $ le_trans (nat.mul_le_mul_right _ hb) h theorem le_zero_iff {i : ℕ} : i ≤ 0 ↔ i = 0 := ⟨nat.eq_zero_of_le_zero, assume h, h ▸ le_refl i⟩ lemma zero_max {m : ℕ} : max 0 m = m := max_eq_right (zero_le _) lemma one_le_of_lt {n m : ℕ} (h : n < m) : 1 ≤ m := lt_of_le_of_lt (nat.zero_le _) h theorem eq_one_of_mul_eq_one_right {m n : ℕ} (H : m * n = 1) : m = 1 := eq_one_of_dvd_one ⟨n, H.symm⟩ theorem eq_one_of_mul_eq_one_left {m n : ℕ} (H : m * n = 1) : n = 1 := eq_one_of_mul_eq_one_right (by rwa mul_comm) /-! ### `succ` -/ theorem eq_of_lt_succ_of_not_lt {a b : ℕ} (h1 : a < b + 1) (h2 : ¬ a < b) : a = b := have h3 : a ≤ b, from le_of_lt_succ h1, or.elim (eq_or_lt_of_not_lt h2) (λ h, h) (λ h, absurd h (not_lt_of_ge h3)) theorem one_add (n : ℕ) : 1 + n = succ n := by simp [add_comm] @[simp] lemma succ_pos' {n : ℕ} : 0 < succ n := succ_pos n theorem succ_inj' {n m : ℕ} : succ n = succ m ↔ n = m := ⟨succ.inj, congr_arg _⟩ theorem succ_injective : function.injective nat.succ := λ x y, succ.inj theorem succ_le_succ_iff {m n : ℕ} : succ m ≤ succ n ↔ m ≤ n := ⟨le_of_succ_le_succ, succ_le_succ⟩ theorem max_succ_succ {m n : ℕ} : max (succ m) (succ n) = succ (max m n) := begin by_cases h1 : m ≤ n, rw [max_eq_right h1, max_eq_right (succ_le_succ h1)], { rw not_le at h1, have h2 := le_of_lt h1, rw [max_eq_left h2, max_eq_left (succ_le_succ h2)] } end lemma not_succ_lt_self {n : ℕ} : ¬succ n < n := not_lt_of_ge (nat.le_succ _) theorem lt_succ_iff {m n : ℕ} : m < succ n ↔ m ≤ n := succ_le_succ_iff lemma succ_le_iff {m n : ℕ} : succ m ≤ n ↔ m < n := ⟨lt_of_succ_le, succ_le_of_lt⟩ lemma lt_iff_add_one_le {m n : ℕ} : m < n ↔ m + 1 ≤ n := by rw succ_le_iff -- Just a restatement of `nat.lt_succ_iff` using `+1`. lemma lt_add_one_iff {a b : ℕ} : a < b + 1 ↔ a ≤ b := lt_succ_iff -- A flipped version of `lt_add_one_iff`. lemma lt_one_add_iff {a b : ℕ} : a < 1 + b ↔ a ≤ b := by simp only [add_comm, lt_succ_iff] -- This is true reflexively, by the definition of `≤` on ℕ, -- but it's still useful to have, to convince Lean to change the syntactic type. lemma add_one_le_iff {a b : ℕ} : a + 1 ≤ b ↔ a < b := iff.refl _ lemma one_add_le_iff {a b : ℕ} : 1 + a ≤ b ↔ a < b := by simp only [add_comm, add_one_le_iff] theorem of_le_succ {n m : ℕ} (H : n ≤ m.succ) : n ≤ m ∨ n = m.succ := (lt_or_eq_of_le H).imp le_of_lt_succ id /-! ### `add` -/ -- Sometimes a bare `nat.add` or similar appears as a consequence of unfolding -- during pattern matching. These lemmas package them back up as typeclass -- mediated operations. @[simp] theorem add_def {a b : ℕ} : nat.add a b = a + b := rfl @[simp] theorem mul_def {a b : ℕ} : nat.mul a b = a * b := rfl attribute [simp] nat.add_sub_cancel nat.add_sub_cancel_left attribute [simp] nat.sub_self lemma exists_eq_add_of_le : ∀ {m n : ℕ}, m ≤ n → ∃ k : ℕ, n = m + k | 0 0 h := ⟨0, by simp⟩ | 0 (n+1) h := ⟨n+1, by simp⟩ | (m+1) (n+1) h := let ⟨k, hk⟩ := exists_eq_add_of_le (nat.le_of_succ_le_succ h) in ⟨k, by simp [hk, add_comm, add_left_comm]⟩ lemma exists_eq_add_of_lt : ∀ {m n : ℕ}, m < n → ∃ k : ℕ, n = m + k + 1 | 0 0 h := false.elim $ lt_irrefl _ h | 0 (n+1) h := ⟨n, by simp⟩ | (m+1) (n+1) h := let ⟨k, hk⟩ := exists_eq_add_of_le (nat.le_of_succ_le_succ h) in ⟨k, by simp [hk]⟩ theorem add_pos_left {m : ℕ} (h : 0 < m) (n : ℕ) : 0 < m + n := 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 : 0 < n) : 0 < m + n := begin rw add_comm, exact add_pos_left h m end theorem add_pos_iff_pos_or_pos (m n : ℕ) : 0 < m + n ↔ 0 < m ∨ 0 < n := 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 lemma add_eq_one_iff : ∀ {a b : ℕ}, a + b = 1 ↔ (a = 0 ∧ b = 1) ∨ (a = 1 ∧ b = 0) | 0 0 := dec_trivial | 0 1 := dec_trivial | 1 0 := dec_trivial | 1 1 := dec_trivial | (a+2) _ := by rw add_right_comm; exact dec_trivial | _ (b+2) := by rw [← add_assoc]; simp only [nat.succ_inj', nat.succ_ne_zero]; simp 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⟩ lemma add_succ_lt_add {a b c d : ℕ} (hab : a < b) (hcd : c < d) : a + c + 1 < b + d := begin rw add_assoc, exact add_lt_add_of_lt_of_le hab (nat.succ_le_iff.2 hcd) end /-! ### `pred` -/ @[simp] lemma add_succ_sub_one (n m : ℕ) : (n + succ m) - 1 = n + m := by rw [add_succ, succ_sub_one] @[simp] lemma succ_add_sub_one (n m : ℕ) : (succ n + m) - 1 = n + m := by rw [succ_add, succ_sub_one] lemma pred_eq_sub_one (n : ℕ) : pred n = n - 1 := rfl theorem pred_eq_of_eq_succ {m n : ℕ} (H : m = n.succ) : m.pred = n := by simp [H] @[simp] lemma pred_eq_succ_iff {n m : ℕ} : pred n = succ m ↔ n = m + 2 := by cases n; split; rintro ⟨⟩; refl theorem pred_sub (n m : ℕ) : pred n - m = pred (n - m) := by rw [← sub_one, nat.sub_sub, one_add]; refl lemma le_pred_of_lt {n m : ℕ} (h : m < n) : m ≤ n - 1 := nat.sub_le_sub_right h 1 lemma le_of_pred_lt {m n : ℕ} : pred m < n → m ≤ n := match m with | 0 := le_of_lt | m+1 := id end /-- This ensures that `simp` succeeds on `pred (n + 1) = n`. -/ @[simp] lemma pred_one_add (n : ℕ) : pred (1 + n) = n := by rw [add_comm, add_one, pred_succ] /-! ### `sub` -/ 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) theorem sub_add_eq_max (n m : ℕ) : n - m + m = max n m := eq_max (nat.le_sub_add _ _) (le_add_left _ _) $ λ k h₁ h₂, by rw ← nat.sub_add_cancel h₂; exact add_le_add_right (nat.sub_le_sub_right h₁ _) _ theorem add_sub_eq_max (n m : ℕ) : n + (m - n) = max n m := by rw [add_comm, max_comm, sub_add_eq_max] theorem sub_add_min (n m : ℕ) : n - m + min n m = n := (le_total n m).elim (λ h, by rw [min_eq_left h, sub_eq_zero_of_le h, zero_add]) (λ h, by rw [min_eq_right h, nat.sub_add_cancel h]) protected theorem add_sub_cancel' {n m : ℕ} (h : m ≤ n) : m + (n - m) = n := by rw [add_comm, nat.sub_add_cancel h] protected theorem sub_add_sub_cancel {a b c : ℕ} (hab : b ≤ a) (hbc : c ≤ b) : (a - b) + (b - c) = a - c := by rw [←nat.add_sub_assoc hbc, ←nat.sub_add_comm hab, nat.add_sub_cancel] protected theorem sub_eq_of_eq_add (h : k = m + n) : k - m = n := begin rw [h, nat.add_sub_cancel_left] end theorem sub_cancel {a b c : ℕ} (h₁ : a ≤ b) (h₂ : a ≤ c) (w : b - a = c - a) : b = c := by rw [←nat.sub_add_cancel h₁, ←nat.sub_add_cancel h₂, w] lemma sub_sub_sub_cancel_right {a b c : ℕ} (h₂ : c ≤ b) : (a - c) - (b - c) = a - b := by rw [nat.sub_sub, ←nat.add_sub_assoc h₂, nat.add_sub_cancel_left] lemma add_sub_cancel_right (n m k : ℕ) : n + (m + k) - k = n + m := by { rw [nat.add_sub_assoc, nat.add_sub_cancel], apply k.le_add_left } protected lemma sub_add_eq_add_sub {a b c : ℕ} (h : b ≤ a) : (a - b) + c = (a + c) - b := by rw [add_comm a, nat.add_sub_assoc h, add_comm] theorem sub_min (n m : ℕ) : n - min n m = n - m := nat.sub_eq_of_eq_add $ by rw [add_comm, sub_add_min] theorem sub_sub_assoc {a b c : ℕ} (h₁ : b ≤ a) (h₂ : c ≤ b) : a - (b - c) = a - b + c := (nat.sub_eq_iff_eq_add (le_trans (nat.sub_le _ _) h₁)).2 $ by rw [add_right_comm, add_assoc, nat.sub_add_cancel h₂, nat.sub_add_cancel h₁] protected theorem lt_of_sub_pos (h : 0 < n - m) : m < n := lt_of_not_ge (assume : n ≤ m, 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 := lt_imp_lt_of_le_imp_le (λ h, nat.sub_le_sub_right h _) protected theorem lt_of_sub_lt_sub_left : m - n < m - k → k < n := lt_imp_lt_of_le_imp_le (nat.sub_le_sub_left _) protected theorem sub_lt_self (h₁ : 0 < m) (h₂ : 0 < n) : 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_of_lt_imp_lt nat.lt_sub_right_of_add_lt protected theorem le_add_of_sub_le_left : n - k ≤ m → n ≤ k + m := le_imp_le_of_lt_imp_lt nat.lt_sub_left_of_add_lt protected theorem lt_add_of_sub_lt_right : n - k < m → n < m + k := lt_imp_lt_of_le_imp_le nat.le_sub_right_of_add_le protected theorem lt_add_of_sub_lt_left : n - k < m → n < k + m := lt_imp_lt_of_le_imp_le nat.le_sub_left_of_add_le protected theorem sub_le_left_of_le_add : n ≤ k + m → n - k ≤ m := le_imp_le_of_lt_imp_lt nat.add_lt_of_lt_sub_left protected theorem sub_le_right_of_le_add : n ≤ m + k → n - k ≤ m := le_imp_le_of_lt_imp_lt 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) 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 : n < k - m ↔ m + n < k := ⟨nat.add_lt_of_lt_sub_left, nat.lt_sub_left_of_add_lt⟩ protected theorem lt_sub_right_iff_add_lt : m < k - n ↔ m + n < k := by rw [nat.lt_sub_left_iff_add_lt, add_comm] theorem sub_le_left_iff_le_add : m - n ≤ k ↔ m ≤ n + k := le_iff_le_iff_lt_iff_lt.2 nat.lt_sub_left_iff_add_lt theorem sub_le_right_iff_le_add : m - k ≤ n ↔ m ≤ n + k := by rw [nat.sub_le_left_iff_le_add, add_comm] 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 := lt_iff_lt_of_le_iff_le (nat.sub_le_sub_right_iff _ _ _ H) protected theorem sub_lt_sub_left_iff (H : n ≤ m) : m - n < m - k ↔ k < n := lt_iff_lt_of_le_iff_le (nat.sub_le_sub_left_iff H) protected theorem sub_le_iff : m - n ≤ k ↔ m - k ≤ n := nat.sub_le_left_iff_le_add.trans nat.sub_le_right_iff_le_add.symm protected lemma sub_le_self (n m : ℕ) : n - m ≤ n := nat.sub_le_left_of_le_add (nat.le_add_left _ _) 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 pred_le_iff {n m : ℕ} : pred n ≤ m ↔ n ≤ succ m := @nat.sub_le_right_iff_le_add n m 1 lemma lt_pred_iff {n m : ℕ} : n < pred m ↔ succ n < m := @nat.lt_sub_right_iff_add_lt n 1 m lemma lt_of_lt_pred {a b : ℕ} (h : a < b - 1) : a < b := lt_of_succ_lt (lt_pred_iff.1 h) /-! ### `mul` -/ theorem mul_self_le_mul_self {n m : ℕ} (h : n ≤ m) : n * n ≤ m * m := mul_le_mul h h (zero_le _) (zero_le _) theorem mul_self_lt_mul_self : Π {n m : ℕ}, n < m → n * n < m * m | 0 m h := mul_pos h h | (succ n) m h := mul_lt_mul h (le_of_lt h) (succ_pos _) (zero_le _) theorem mul_self_le_mul_self_iff {n m : ℕ} : n ≤ m ↔ n * n ≤ m * m := ⟨mul_self_le_mul_self, λh, decidable.by_contradiction $ λhn, not_lt_of_ge h $ mul_self_lt_mul_self $ lt_of_not_ge hn⟩ theorem mul_self_lt_mul_self_iff {n m : ℕ} : n < m ↔ n * n < m * m := iff.trans (lt_iff_not_ge _ _) $ iff.trans (not_iff_not_of_iff mul_self_le_mul_self_iff) $ iff.symm (lt_iff_not_ge _ _) theorem le_mul_self : Π (n : ℕ), n ≤ n * n | 0 := le_refl _ | (n+1) := let t := mul_le_mul_left (n+1) (succ_pos n) in by simp at t; exact t lemma le_mul_of_pos_left {m n : ℕ} (h : 0 < n) : m ≤ n * m := begin conv {to_lhs, rw [← one_mul(m)]}, exact mul_le_mul_of_nonneg_right (nat.succ_le_of_lt h) dec_trivial, end lemma le_mul_of_pos_right {m n : ℕ} (h : 0 < n) : m ≤ m * n := begin conv {to_lhs, rw [← mul_one(m)]}, exact mul_le_mul_of_nonneg_left (nat.succ_le_of_lt h) dec_trivial, end theorem two_mul_ne_two_mul_add_one {n m} : 2 * n ≠ 2 * m + 1 := mt (congr_arg (%2)) (by rw [add_comm, add_mul_mod_self_left, mul_mod_right]; exact dec_trivial) lemma mul_eq_one_iff : ∀ {a b : ℕ}, a * b = 1 ↔ a = 1 ∧ b = 1 | 0 0 := dec_trivial | 0 1 := dec_trivial | 1 0 := dec_trivial | (a+2) 0 := by simp | 0 (b+2) := by simp | (a+1) (b+1) := ⟨λ h, by simp only [add_mul, mul_add, mul_add, one_mul, mul_one, (add_assoc _ _ _).symm, nat.succ_inj', add_eq_zero_iff] at h; simp [h.1.2, h.2], by clear_aux_decl; finish⟩ protected theorem mul_left_inj {a b c : ℕ} (ha : 0 < a) : b * a = c * a ↔ b = c := ⟨nat.eq_of_mul_eq_mul_right ha, λ e, e ▸ rfl⟩ protected theorem mul_right_inj {a b c : ℕ} (ha : 0 < a) : a * b = a * c ↔ b = c := ⟨nat.eq_of_mul_eq_mul_left ha, λ e, e ▸ rfl⟩ lemma mul_right_eq_self_iff {a b : ℕ} (ha : 0 < a) : a * b = a ↔ b = 1 := suffices a * b = a * 1 ↔ b = 1, by rwa mul_one at this, nat.mul_right_inj ha lemma mul_left_eq_self_iff {a b : ℕ} (hb : 0 < b) : a * b = b ↔ a = 1 := by rw [mul_comm, nat.mul_right_eq_self_iff hb] 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 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 /-! ### Recursion and induction principles This section is here due to dependencies -- the lemmas here require some of the lemmas proved above, and some of the results in later sections depend on the definitions in this section. -/ /-- Recursion starting at a non-zero number: given a map `C k → C (k+1)` for each `k`, there is a map from `C n` to each `C m`, `n ≤ m`. -/ @[elab_as_eliminator] def le_rec_on {C : ℕ → Sort u} {n : ℕ} : Π {m : ℕ}, n ≤ m → (Π {k}, C k → C (k+1)) → C n → C m | 0 H next x := eq.rec_on (eq_zero_of_le_zero H) x | (m+1) H next x := or.by_cases (of_le_succ H) (λ h : n ≤ m, next $ le_rec_on h @next x) (λ h : n = m + 1, eq.rec_on h x) theorem le_rec_on_self {C : ℕ → Sort u} {n} {h : n ≤ n} {next} (x : C n) : (le_rec_on h next x : C n) = x := by cases n; unfold le_rec_on or.by_cases; rw [dif_neg n.not_succ_le_self, dif_pos rfl] theorem le_rec_on_succ {C : ℕ → Sort u} {n m} (h1 : n ≤ m) {h2 : n ≤ m+1} {next} (x : C n) : (le_rec_on h2 @next x : C (m+1)) = next (le_rec_on h1 @next x : C m) := by conv { to_lhs, rw [le_rec_on, or.by_cases, dif_pos h1] } theorem le_rec_on_succ' {C : ℕ → Sort u} {n} {h : n ≤ n+1} {next} (x : C n) : (le_rec_on h next x : C (n+1)) = next x := by rw [le_rec_on_succ (le_refl n), le_rec_on_self] theorem le_rec_on_trans {C : ℕ → Sort u} {n m k} (hnm : n ≤ m) (hmk : m ≤ k) {next} (x : C n) : (le_rec_on (le_trans hnm hmk) @next x : C k) = le_rec_on hmk @next (le_rec_on hnm @next x) := begin induction hmk with k hmk ih, { rw le_rec_on_self }, rw [le_rec_on_succ (le_trans hnm hmk), ih, le_rec_on_succ] end theorem le_rec_on_succ_left {C : ℕ → Sort u} {n m} (h1 : n ≤ m) (h2 : n+1 ≤ m) {next : Π{{k}}, C k → C (k+1)} (x : C n) : (le_rec_on h2 next (next x) : C m) = (le_rec_on h1 next x : C m) := begin rw [subsingleton.elim h1 (le_trans (le_succ n) h2), le_rec_on_trans (le_succ n) h2, le_rec_on_succ'] end theorem le_rec_on_injective {C : ℕ → Sort u} {n m} (hnm : n ≤ m) (next : Π n, C n → C (n+1)) (Hnext : ∀ n, function.injective (next n)) : function.injective (le_rec_on hnm next) := begin induction hnm with m hnm ih, { intros x y H, rwa [le_rec_on_self, le_rec_on_self] at H }, intros x y H, rw [le_rec_on_succ hnm, le_rec_on_succ hnm] at H, exact ih (Hnext _ H) end theorem le_rec_on_surjective {C : ℕ → Sort u} {n m} (hnm : n ≤ m) (next : Π n, C n → C (n+1)) (Hnext : ∀ n, function.surjective (next n)) : function.surjective (le_rec_on hnm next) := begin induction hnm with m hnm ih, { intros x, use x, rw le_rec_on_self }, intros x, rcases Hnext _ x with ⟨w, rfl⟩, rcases ih w with ⟨x, rfl⟩, use x, rw le_rec_on_succ end /-- Recursion principle based on `<`. -/ @[elab_as_eliminator] protected def strong_rec' {p : ℕ → Sort u} (H : ∀ n, (∀ m, m < n → p m) → p n) : ∀ (n : ℕ), p n | n := H n (λ m hm, strong_rec' m) /-- Recursion principle based on `<` applied to some natural number. -/ @[elab_as_eliminator] def strong_rec_on' {P : ℕ → Sort*} (n : ℕ) (h : ∀ n, (∀ m, m < n → P m) → P n) : P n := nat.strong_rec' h n theorem strong_rec_on_beta' {P : ℕ → Sort*} {h} {n : ℕ} : (strong_rec_on' n h : P n) = h n (λ m hmn, (strong_rec_on' m h : P m)) := by { simp only [strong_rec_on'], rw nat.strong_rec' } /-- Induction principle starting at a non-zero number. For maps to a `Sort*` see `le_rec_on`. -/ @[elab_as_eliminator] lemma le_induction {P : nat → Prop} {m} (h0 : P m) (h1 : ∀ n, m ≤ n → P n → P (n + 1)) : ∀ n, m ≤ n → P n := by apply nat.less_than_or_equal.rec h0; exact h1 /-- Decreasing induction: if `P (k+1)` implies `P k`, then `P n` implies `P m` for all `m ≤ n`. Also works for functions to `Sort*`. -/ @[elab_as_eliminator] def decreasing_induction {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n : ℕ} (mn : m ≤ n) (hP : P n) : P m := le_rec_on mn (λ k ih hsk, ih $ h k hsk) (λ h, h) hP @[simp] lemma decreasing_induction_self {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {n : ℕ} (nn : n ≤ n) (hP : P n) : (decreasing_induction h nn hP : P n) = hP := by { dunfold decreasing_induction, rw [le_rec_on_self] } lemma decreasing_induction_succ {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n : ℕ} (mn : m ≤ n) (msn : m ≤ n + 1) (hP : P (n+1)) : (decreasing_induction h msn hP : P m) = decreasing_induction h mn (h n hP) := by { dunfold decreasing_induction, rw [le_rec_on_succ] } @[simp] lemma decreasing_induction_succ' {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m : ℕ} (msm : m ≤ m + 1) (hP : P (m+1)) : (decreasing_induction h msm hP : P m) = h m hP := by { dunfold decreasing_induction, rw [le_rec_on_succ'] } lemma decreasing_induction_trans {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n k : ℕ} (mn : m ≤ n) (nk : n ≤ k) (hP : P k) : (decreasing_induction h (le_trans mn nk) hP : P m) = decreasing_induction h mn (decreasing_induction h nk hP) := by { induction nk with k nk ih, rw [decreasing_induction_self], rw [decreasing_induction_succ h (le_trans mn nk), ih, decreasing_induction_succ] } lemma decreasing_induction_succ_left {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n : ℕ} (smn : m + 1 ≤ n) (mn : m ≤ n) (hP : P n) : (decreasing_induction h mn hP : P m) = h m (decreasing_induction h smn hP) := by { rw [subsingleton.elim mn (le_trans (le_succ m) smn), decreasing_induction_trans, decreasing_induction_succ'] } /-! ### `div` -/ attribute [simp] nat.div_self protected lemma div_le_of_le_mul' {m n : ℕ} {k} (h : m ≤ k * n) : m / k ≤ n := (eq_zero_or_pos k).elim (λ k0, by rw [k0, nat.div_zero]; apply zero_le) (λ k0, (decidable.mul_le_mul_left k0).1 $ calc k * (m / k) ≤ m % k + k * (m / k) : le_add_left _ _ ... = m : mod_add_div _ _ ... ≤ k * n : h) protected lemma div_le_self' (m n : ℕ) : m / n ≤ m := (eq_zero_or_pos n).elim (λ n0, by rw [n0, nat.div_zero]; apply zero_le) (λ n0, nat.div_le_of_le_mul' $ calc m = 1 * m : (one_mul _).symm ... ≤ n * m : mul_le_mul_right _ n0) /-- A version of `nat.div_lt_self` using successors, rather than additional hypotheses. -/ lemma div_lt_self' (n b : ℕ) : (n+1)/(b+2) < n+1 := nat.div_lt_self (nat.succ_pos n) (nat.succ_lt_succ (nat.succ_pos _)) theorem le_div_iff_mul_le' {x y : ℕ} {k : ℕ} (k0 : 0 < k) : x ≤ y / k ↔ x * k ≤ y := begin revert x, refine nat.strong_rec' _ y, clear y, intros y IH x, cases decidable.lt_or_le y k with h h, { rw [div_eq_of_lt h], cases x with x, { simp [zero_mul, zero_le] }, { rw succ_mul, exact iff_of_false (not_succ_le_zero _) (not_le_of_lt $ lt_of_lt_of_le h (le_add_left _ _)) } }, { rw [div_eq_sub_div k0 h], cases x with x, { simp [zero_mul, zero_le] }, { rw [← add_one, nat.add_le_add_iff_le_right, succ_mul, IH _ (sub_lt_of_pos_le _ _ k0 h), add_le_to_le_sub _ h] } } end theorem div_mul_le_self' (m n : ℕ) : m / n * n ≤ m := (nat.eq_zero_or_pos n).elim (λ n0, by simp [n0, zero_le]) $ λ n0, (le_div_iff_mul_le' n0).1 (le_refl _) theorem div_lt_iff_lt_mul' {x y : ℕ} {k : ℕ} (k0 : 0 < k) : x / k < y ↔ x < y * k := lt_iff_lt_of_le_iff_le $ le_div_iff_mul_le' k0 protected theorem div_le_div_right {n m : ℕ} (h : n ≤ m) {k : ℕ} : n / k ≤ m / k := (nat.eq_zero_or_pos k).elim (λ k0, by simp [k0]) $ λ hk, (le_div_iff_mul_le' hk).2 $ le_trans (nat.div_mul_le_self' _ _) h lemma lt_of_div_lt_div {m n k : ℕ} (h : m / k < n / k) : m < n := by_contradiction $ λ h₁, absurd h (not_lt_of_ge (nat.div_le_div_right (not_lt.1 h₁))) protected lemma div_pos {a b : ℕ} (hba : b ≤ a) (hb : 0 < b) : 0 < a / b := nat.pos_of_ne_zero (λ h, lt_irrefl a (calc a = a % b : by simpa [h] using (mod_add_div a b).symm ... < b : nat.mod_lt a hb ... ≤ a : hba)) protected lemma div_lt_of_lt_mul {m n k : ℕ} (h : m < n * k) : m / n < k := lt_of_mul_lt_mul_left (calc n * (m / n) ≤ m % n + n * (m / n) : nat.le_add_left _ _ ... = m : mod_add_div _ _ ... < n * k : h) (nat.zero_le n) lemma lt_mul_of_div_lt {a b c : ℕ} (h : a / c < b) (w : 0 < c) : a < b * c := lt_of_not_ge $ not_le_of_gt h ∘ (nat.le_div_iff_mul_le _ _ w).2 protected lemma div_eq_zero_iff {a b : ℕ} (hb : 0 < b) : a / b = 0 ↔ a < b := ⟨λ h, by rw [← mod_add_div a b, h, mul_zero, add_zero]; exact mod_lt _ hb, λ h, by rw [← nat.mul_right_inj hb, ← @add_left_cancel_iff _ _ (a % b), mod_add_div, mod_eq_of_lt h, mul_zero, add_zero]⟩ protected lemma div_eq_zero {a b : ℕ} (hb : a < b) : a / b = 0 := (nat.div_eq_zero_iff $ (zero_le a).trans_lt hb).mpr hb lemma eq_zero_of_le_div {a b : ℕ} (hb : 2 ≤ b) (h : a ≤ a / b) : a = 0 := eq_zero_of_mul_le hb $ by rw mul_comm; exact (nat.le_div_iff_mul_le' (lt_of_lt_of_le dec_trivial hb)).1 h lemma mul_div_le_mul_div_assoc (a b c : ℕ) : a * (b / c) ≤ (a * b) / c := if hc0 : c = 0 then by simp [hc0] else (nat.le_div_iff_mul_le _ _ (nat.pos_of_ne_zero hc0)).2 (by rw [mul_assoc]; exact mul_le_mul_left _ (nat.div_mul_le_self _ _)) lemma div_mul_div_le_div (a b c : ℕ) : ((a / c) * b) / a ≤ b / c := if ha0 : a = 0 then by simp [ha0] else calc a / c * b / a ≤ b * a / c / a : nat.div_le_div_right (by rw [mul_comm]; exact mul_div_le_mul_div_assoc _ _ _) ... = b / c : by rw [nat.div_div_eq_div_mul, mul_comm b, mul_comm c, nat.mul_div_mul _ _ (nat.pos_of_ne_zero ha0)] lemma eq_zero_of_le_half {a : ℕ} (h : a ≤ a / 2) : a = 0 := eq_zero_of_le_div (le_refl _) h 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 : 0 < b) (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 : 0 < b) (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_div_cancel_left' {a b : ℕ} (Hd : a ∣ b) : a * (b / a) = b := by rw [mul_comm,nat.div_mul_cancel Hd] /-! ### `mod`, `dvd` -/ protected theorem div_mod_unique {n k m d : ℕ} (h : 0 < k) : n / k = d ∧ n % k = m ↔ m + k * d = n ∧ m < k := ⟨λ ⟨e₁, e₂⟩, e₁ ▸ e₂ ▸ ⟨mod_add_div _ _, mod_lt _ h⟩, λ ⟨h₁, h₂⟩, h₁ ▸ by rw [add_mul_div_left _ _ h, add_mul_mod_self_left]; simp [div_eq_of_lt, mod_eq_of_lt, h₂]⟩ lemma two_mul_odd_div_two {n : ℕ} (hn : n % 2 = 1) : 2 * (n / 2) = n - 1 := by conv {to_rhs, rw [← nat.mod_add_div n 2, hn, nat.add_sub_cancel_left]} lemma div_dvd_of_dvd {a b : ℕ} (h : b ∣ a) : (a / b) ∣ a := ⟨b, (nat.div_mul_cancel h).symm⟩ protected lemma div_div_self : ∀ {a b : ℕ}, b ∣ a → 0 < a → a / (a / b) = b | a 0 h₁ h₂ := by rw eq_zero_of_zero_dvd h₁; refl | 0 b h₁ h₂ := absurd h₂ dec_trivial | (a+1) (b+1) h₁ h₂ := (nat.mul_left_inj (nat.div_pos (le_of_dvd (succ_pos a) h₁) (succ_pos b))).1 $ by rw [nat.div_mul_cancel (div_dvd_of_dvd h₁), nat.mul_div_cancel' h₁] lemma mod_mul_right_div_self (a b c : ℕ) : a % (b * c) / b = (a / b) % c := if hb : b = 0 then by simp [hb] else if hc : c = 0 then by simp [hc] else by conv {to_rhs, rw ← mod_add_div a (b * c)}; rw [mul_assoc, nat.add_mul_div_left _ _ (nat.pos_of_ne_zero hb), add_mul_mod_self_left, mod_eq_of_lt (nat.div_lt_of_lt_mul (mod_lt _ (mul_pos (nat.pos_of_ne_zero hb) (nat.pos_of_ne_zero hc))))] lemma mod_mul_left_div_self (a b c : ℕ) : a % (c * b) / b = (a / b) % c := by rw [mul_comm c, mod_mul_right_div_self] @[simp] protected theorem dvd_one {n : ℕ} : n ∣ 1 ↔ n = 1 := ⟨eq_one_of_dvd_one, λ e, e.symm ▸ dvd_refl _⟩ protected theorem dvd_add_left {k m n : ℕ} (h : k ∣ n) : k ∣ m + n ↔ k ∣ m := (nat.dvd_add_iff_left h).symm protected theorem dvd_add_right {k m n : ℕ} (h : k ∣ m) : k ∣ m + n ↔ k ∣ n := (nat.dvd_add_iff_right h).symm @[simp] protected theorem not_two_dvd_bit1 (n : ℕ) : ¬ 2 ∣ bit1 n := mt (nat.dvd_add_right two_dvd_bit0).1 dec_trivial /-- A natural number m divides the sum m + n if and only if m divides b.-/ @[simp] protected lemma dvd_add_self_left {m n : ℕ} : m ∣ m + n ↔ m ∣ n := nat.dvd_add_right (dvd_refl m) /-- A natural number m divides the sum n + m if and only if m divides b.-/ @[simp] protected lemma dvd_add_self_right {m n : ℕ} : m ∣ n + m ↔ m ∣ n := nat.dvd_add_left (dvd_refl m) protected theorem mul_dvd_mul_iff_left {a b c : ℕ} (ha : 0 < a) : a * b ∣ a * c ↔ b ∣ c := exists_congr $ λ d, by rw [mul_assoc, nat.mul_right_inj ha] protected theorem mul_dvd_mul_iff_right {a b c : ℕ} (hc : 0 < c) : a * c ∣ b * c ↔ a ∣ b := exists_congr $ λ d, by rw [mul_right_comm, nat.mul_left_inj hc] lemma succ_div : ∀ (a b : ℕ), (a + 1) / b = a / b + if b ∣ a + 1 then 1 else 0 | a 0 := by simp | 0 1 := rfl | 0 (b+2) := have hb2 : b + 2 > 1, from dec_trivial, by simp [ne_of_gt hb2, div_eq_of_lt hb2] | (a+1) (b+1) := begin rw [nat.div_def], conv_rhs { rw nat.div_def }, by_cases hb_eq_a : b = a + 1, { simp [hb_eq_a, le_refl] }, by_cases hb_le_a1 : b ≤ a + 1, { have hb_le_a : b ≤ a, from le_of_lt_succ (lt_of_le_of_ne hb_le_a1 hb_eq_a), have h₁ : (0 < b + 1 ∧ b + 1 ≤ a + 1 + 1), from ⟨succ_pos _, (add_le_add_iff_right _).2 hb_le_a1⟩, have h₂ : (0 < b + 1 ∧ b + 1 ≤ a + 1), from ⟨succ_pos _, (add_le_add_iff_right _).2 hb_le_a⟩, have dvd_iff : b + 1 ∣ a - b + 1 ↔ b + 1 ∣ a + 1 + 1, { rw [nat.dvd_add_iff_left (dvd_refl (b + 1)), ← nat.add_sub_add_right a 1 b, add_comm (_ - _), add_assoc, nat.sub_add_cancel (succ_le_succ hb_le_a), add_comm 1] }, have wf : a - b < a + 1, from lt_succ_of_le (nat.sub_le_self _ _), rw [if_pos h₁, if_pos h₂, nat.add_sub_add_right, nat.sub_add_comm hb_le_a, by exact have _ := wf, succ_div (a - b), nat.add_sub_add_right], simp [dvd_iff, succ_eq_add_one, add_comm 1, add_assoc] }, { have hba : ¬ b ≤ a, from not_le_of_gt (lt_trans (lt_succ_self a) (lt_of_not_ge hb_le_a1)), have hb_dvd_a : ¬ b + 1 ∣ a + 2, from λ h, hb_le_a1 (le_of_succ_le_succ (le_of_dvd (succ_pos _) h)), simp [hba, hb_le_a1, hb_dvd_a], } end lemma succ_div_of_dvd {a b : ℕ} (hba : b ∣ a + 1) : (a + 1) / b = a / b + 1 := by rw [succ_div, if_pos hba] lemma succ_div_of_not_dvd {a b : ℕ} (hba : ¬ b ∣ a + 1) : (a + 1) / b = a / b := by rw [succ_div, if_neg hba, add_zero] @[simp] theorem mod_mod_of_dvd (n : nat) {m k : nat} (h : m ∣ k) : n % k % m = n % m := begin conv { to_rhs, rw ←mod_add_div n k }, rcases h with ⟨t, rfl⟩, rw [mul_assoc, add_mul_mod_self_left] end @[simp] theorem mod_mod (a n : ℕ) : (a % n) % n = a % n := (eq_zero_or_pos n).elim (λ n0, by simp [n0]) (λ npos, mod_eq_of_lt (mod_lt _ npos)) /-- If `a` and `b` are equal mod `c`, `a - b` is zero mod `c`. -/ lemma sub_mod_eq_zero_of_mod_eq {a b c : ℕ} (h : a % c = b % c) : (a - b) % c = 0 := by rw [←nat.mod_add_div a c, ←nat.mod_add_div b c, ←h, ←nat.sub_sub, nat.add_sub_cancel_left, ←nat.mul_sub_left_distrib, nat.mul_mod_right] @[simp] lemma one_mod (n : ℕ) : 1 % (n + 2) = 1 := nat.mod_eq_of_lt (add_lt_add_right n.succ_pos 1) lemma dvd_sub_mod (k : ℕ) : n ∣ (k - (k % n)) := ⟨k / n, nat.sub_eq_of_eq_add (nat.mod_add_div k n).symm⟩ @[simp] theorem mod_add_mod (m n k : ℕ) : (m % n + k) % n = (m + k) % n := by have := (add_mul_mod_self_left (m % n + k) n (m / n)).symm; rwa [add_right_comm, mod_add_div] at this @[simp] theorem add_mod_mod (m n k : ℕ) : (m + n % k) % k = (m + n) % k := by rw [add_comm, mod_add_mod, add_comm] lemma add_mod (a b n : ℕ) : (a + b) % n = ((a % n) + (b % n)) % n := by rw [add_mod_mod, mod_add_mod] theorem add_mod_eq_add_mod_right {m n k : ℕ} (i : ℕ) (H : m % n = k % n) : (m + i) % n = (k + i) % n := by rw [← mod_add_mod, ← mod_add_mod k, H] theorem add_mod_eq_add_mod_left {m n k : ℕ} (i : ℕ) (H : m % n = k % n) : (i + m) % n = (i + k) % n := by rw [add_comm, add_mod_eq_add_mod_right _ H, add_comm] lemma mul_mod (a b n : ℕ) : (a * b) % n = ((a % n) * (b % n)) % n := begin conv_lhs { rw [←mod_add_div a n, ←mod_add_div b n, right_distrib, left_distrib, left_distrib, mul_assoc, mul_assoc, ←left_distrib n _ _, add_mul_mod_self_left, mul_comm _ (n * (b / n)), mul_assoc, add_mul_mod_self_left] } end lemma dvd_div_of_mul_dvd {a b c : ℕ} (h : a * b ∣ c) : b ∣ c / a := if ha : a = 0 then by simp [ha] else have ha : 0 < a, from nat.pos_of_ne_zero ha, have h1 : ∃ d, c = a * b * d, from h, let ⟨d, hd⟩ := h1 in have hac : a ∣ c, from dvd_of_mul_right_dvd h, have h2 : c / a = b * d, from nat.div_eq_of_eq_mul_right ha (by simpa [mul_assoc] using hd), show ∃ d, c / a = b * d, from ⟨d, h2⟩ lemma mul_dvd_of_dvd_div {a b c : ℕ} (hab : c ∣ b) (h : a ∣ b / c) : c * a ∣ b := have h1 : ∃ d, b / c = a * d, from h, have h2 : ∃ e, b = c * e, from hab, let ⟨d, hd⟩ := h1, ⟨e, he⟩ := h2 in have h3 : b = a * d * c, from nat.eq_mul_of_div_eq_left hab hd, show ∃ d, b = c * a * d, from ⟨d, by cc⟩ lemma div_mul_div {a b c d : ℕ} (hab : b ∣ a) (hcd : d ∣ c) : (a / b) * (c / d) = (a * c) / (b * d) := have exi1 : ∃ x, a = b * x, from hab, have exi2 : ∃ y, c = d * y, from hcd, if hb : b = 0 then by simp [hb] else have 0 < b, from nat.pos_of_ne_zero hb, if hd : d = 0 then by simp [hd] else have 0 < d, from nat.pos_of_ne_zero hd, begin cases exi1 with x hx, cases exi2 with y hy, rw [hx, hy, nat.mul_div_cancel_left, nat.mul_div_cancel_left], symmetry, apply nat.div_eq_of_eq_mul_left, apply mul_pos, repeat {assumption}, cc end @[simp] lemma div_div_div_eq_div : ∀ {a b c : ℕ} (dvd : b ∣ a) (dvd2 : a ∣ c), (c / (a / b)) / b = c / a | 0 _ := by simp | (a + 1) 0 := λ _ dvd _, by simpa using dvd | (a + 1) (c + 1) := have a_split : a + 1 ≠ 0 := succ_ne_zero a, have c_split : c + 1 ≠ 0 := succ_ne_zero c, λ b dvd dvd2, begin rcases dvd2 with ⟨k, rfl⟩, rcases dvd with ⟨k2, pr⟩, have k2_nonzero : k2 ≠ 0 := λ k2_zero, by simpa [k2_zero] using pr, rw [nat.mul_div_cancel_left k (nat.pos_of_ne_zero a_split), pr, nat.mul_div_cancel_left k2 (nat.pos_of_ne_zero c_split), nat.mul_comm ((c + 1) * k2) k, ←nat.mul_assoc k (c + 1) k2, nat.mul_div_cancel _ (nat.pos_of_ne_zero k2_nonzero), nat.mul_div_cancel _ (nat.pos_of_ne_zero c_split)], end lemma eq_of_dvd_of_div_eq_one {a b : ℕ} (w : a ∣ b) (h : b / a = 1) : a = b := by rw [←nat.div_mul_cancel w, h, one_mul] lemma eq_zero_of_dvd_of_div_eq_zero {a b : ℕ} (w : a ∣ b) (h : b / a = 0) : b = 0 := by rw [←nat.div_mul_cancel w, h, zero_mul] /-- If a small natural number is divisible by a larger natural number, the small number is zero. -/ lemma eq_zero_of_dvd_of_lt {a b : ℕ} (w : a ∣ b) (h : b < a) : b = 0 := nat.eq_zero_of_dvd_of_div_eq_zero w ((nat.div_eq_zero_iff (lt_of_le_of_lt (zero_le b) h)).elim_right h) lemma div_le_div_left {a b c : ℕ} (h₁ : c ≤ b) (h₂ : 0 < c) : a / b ≤ a / c := (nat.le_div_iff_mul_le _ _ h₂).2 $ le_trans (mul_le_mul_left _ h₁) (div_mul_le_self _ _) lemma div_eq_self {a b : ℕ} : a / b = a ↔ a = 0 ∨ b = 1 := begin split, { intro, cases b, { simp * at * }, { cases b, { right, refl }, { left, have : a / (b + 2) ≤ a / 2 := div_le_div_left (by simp) dec_trivial, refine eq_zero_of_le_half _, simp * at * } } }, { rintros (rfl|rfl); simp } end /-! ### `pow` -/ -- This is redundant with `canonically_ordered_semiring.pow_le_pow_of_le_left`, -- but `canonically_ordered_semiring` is not such an obvious abstraction, and also quite long. -- So, we leave a version in the `nat` namespace as well. -- (The global `pow_le_pow_of_le_left` needs an extra hypothesis `0 ≤ x`.) protected theorem pow_le_pow_of_le_left {x y : ℕ} (H : x ≤ y) : ∀ i : ℕ, x^i ≤ y^i := canonically_ordered_semiring.pow_le_pow_of_le_left H theorem pow_le_pow_of_le_right {x : ℕ} (H : x > 0) {i : ℕ} : ∀ {j}, i ≤ j → x^i ≤ x^j | 0 h := by rw eq_zero_of_le_zero h; apply le_refl | (succ j) h := (lt_or_eq_of_le h).elim (λhl, by rw [pow_succ', ← nat.mul_one (x^i)]; exact nat.mul_le_mul (pow_le_pow_of_le_right $ le_of_lt_succ hl) H) (λe, by rw e; refl) theorem pow_lt_pow_of_lt_left {x y : ℕ} (H : x < y) {i} (h : 0 < i) : x^i < y^i := begin cases i with i, { exact absurd h (not_lt_zero _) }, rw [pow_succ', pow_succ'], exact nat.mul_lt_mul' (nat.pow_le_pow_of_le_left (le_of_lt H) _) H (pow_pos (lt_of_le_of_lt (zero_le _) H) _) end theorem pow_lt_pow_of_lt_right {x : ℕ} (H : x > 1) {i j : ℕ} (h : i < j) : x^i < x^j := begin have xpos := lt_of_succ_lt H, refine lt_of_lt_of_le _ (pow_le_pow_of_le_right xpos h), rw [← nat.mul_one (x^i), pow_succ'], exact nat.mul_lt_mul_of_pos_left H (pow_pos xpos _) end -- TODO: Generalize? lemma pow_lt_pow_succ {p : ℕ} (h : 1 < p) (n : ℕ) : p^n < p^(n+1) := suffices 1*p^n < p*p^n, by simpa, nat.mul_lt_mul_of_pos_right h (pow_pos (lt_of_succ_lt h) n) lemma lt_pow_self {p : ℕ} (h : 1 < p) : ∀ n : ℕ, n < p ^ n | 0 := by simp [zero_lt_one] | (n+1) := calc n + 1 < p^n + 1 : nat.add_lt_add_right (lt_pow_self _) _ ... ≤ p ^ (n+1) : pow_lt_pow_succ h _ lemma lt_two_pow (n : ℕ) : n < 2^n := lt_pow_self dec_trivial n lemma one_le_pow (n m : ℕ) (h : 0 < m) : 1 ≤ m^n := by { rw ←one_pow n, exact nat.pow_le_pow_of_le_left h n } lemma one_le_pow' (n m : ℕ) : 1 ≤ (m+1)^n := one_le_pow n (m+1) (succ_pos m) lemma one_le_two_pow (n : ℕ) : 1 ≤ 2^n := one_le_pow n 2 dec_trivial lemma one_lt_pow (n m : ℕ) (h₀ : 0 < n) (h₁ : 1 < m) : 1 < m^n := by { rw ←one_pow n, exact pow_lt_pow_of_lt_left h₁ h₀ } lemma one_lt_pow' (n m : ℕ) : 1 < (m+2)^(n+1) := one_lt_pow (n+1) (m+2) (succ_pos n) (nat.lt_of_sub_eq_succ rfl) lemma one_lt_two_pow (n : ℕ) (h₀ : 0 < n) : 1 < 2^n := one_lt_pow n 2 h₀ dec_trivial lemma one_lt_two_pow' (n : ℕ) : 1 < 2^(n+1) := one_lt_pow (n+1) 2 (succ_pos n) dec_trivial lemma pow_right_strict_mono {x : ℕ} (k : 2 ≤ x) : strict_mono (λ (n : ℕ), x^n) := λ _ _, pow_lt_pow_of_lt_right k lemma pow_le_iff_le_right {x m n : ℕ} (k : 2 ≤ x) : x^m ≤ x^n ↔ m ≤ n := strict_mono.le_iff_le (pow_right_strict_mono k) lemma pow_lt_iff_lt_right {x m n : ℕ} (k : 2 ≤ x) : x^m < x^n ↔ m < n := strict_mono.lt_iff_lt (pow_right_strict_mono k) lemma pow_right_injective {x : ℕ} (k : 2 ≤ x) : function.injective (λ (n : ℕ), x^n) := strict_mono.injective (pow_right_strict_mono k) lemma pow_left_strict_mono {m : ℕ} (k : 1 ≤ m) : strict_mono (λ (x : ℕ), x^m) := λ _ _ h, pow_lt_pow_of_lt_left h k lemma pow_le_iff_le_left {m x y : ℕ} (k : 1 ≤ m) : x^m ≤ y^m ↔ x ≤ y := strict_mono.le_iff_le (pow_left_strict_mono k) lemma pow_lt_iff_lt_left {m x y : ℕ} (k : 1 ≤ m) : x^m < y^m ↔ x < y := strict_mono.lt_iff_lt (pow_left_strict_mono k) lemma pow_left_injective {m : ℕ} (k : 1 ≤ m) : function.injective (λ (x : ℕ), x^m) := strict_mono.injective (pow_left_strict_mono k) /-! ### `pow` and `mod` / `dvd` -/ theorem mod_pow_succ {b : ℕ} (b_pos : 0 < b) (w m : ℕ) : m % (b^succ w) = b * (m/b % b^w) + m % b := begin apply nat.strong_induction_on m, clear m, intros p IH, cases lt_or_ge p (b^succ w) with h₁ h₁, -- base case: p < b^succ w { have h₂ : p / b < b^w, { rw [div_lt_iff_lt_mul p _ b_pos], simpa [pow_succ'] using h₁ }, rw [mod_eq_of_lt h₁, mod_eq_of_lt h₂], simp [mod_add_div, nat.add_comm] }, -- step: p ≥ b^succ w { -- Generate condition for induction hypothesis have h₂ : p - b^succ w < p, { apply sub_lt_of_pos_le _ _ (pow_pos b_pos _) h₁ }, -- Apply induction rw [mod_eq_sub_mod h₁, IH _ h₂], -- Normalize goal and h1 simp only [pow_succ], simp only [ge, pow_succ] at h₁, -- Pull subtraction outside mod and div rw [sub_mul_mod _ _ _ h₁, sub_mul_div _ _ _ h₁], -- Cancel subtraction inside mod b^w have p_b_ge : b^w ≤ p / b, { rw [le_div_iff_mul_le _ _ b_pos, mul_comm], exact h₁ }, rw [eq.symm (mod_eq_sub_mod p_b_ge)] } end lemma pow_dvd_pow_iff_pow_le_pow {k l : ℕ} : Π {x : ℕ} (w : 0 < x), x^k ∣ x^l ↔ x^k ≤ x^l | (x+1) w := begin split, { intro a, exact le_of_dvd (pow_pos (succ_pos x) l) a, }, { intro a, cases x with x, { simp only [one_pow], }, { have le := (pow_le_iff_le_right (le_add_left _ _)).mp a, use (x+2)^(l-k), rw [←pow_add, add_comm k, nat.sub_add_cancel le], } } end /-- If `1 < x`, then `x^k` divides `x^l` if and only if `k` is at most `l`. -/ lemma pow_dvd_pow_iff_le_right {x k l : ℕ} (w : 1 < x) : x^k ∣ x^l ↔ k ≤ l := by rw [pow_dvd_pow_iff_pow_le_pow (lt_of_succ_lt w), pow_le_iff_le_right w] lemma pow_dvd_pow_iff_le_right' {b k l : ℕ} : (b+2)^k ∣ (b+2)^l ↔ k ≤ l := pow_dvd_pow_iff_le_right (nat.lt_of_sub_eq_succ rfl) lemma not_pos_pow_dvd : ∀ {p k : ℕ} (hp : 1 < p) (hk : 1 < k), ¬ p^k ∣ p | (succ p) (succ k) hp hk h := have succ p * (succ p)^k ∣ succ p * 1, by simpa, have (succ p) ^ k ∣ 1, from dvd_of_mul_dvd_mul_left (succ_pos _) this, have he : (succ p) ^ k = 1, from eq_one_of_dvd_one this, have k < (succ p) ^ k, from lt_pow_self hp k, have k < 1, by rwa [he] at this, have k = 0, from eq_zero_of_le_zero $ le_of_lt_succ this, have 1 < 1, by rwa [this] at hk, absurd this dec_trivial lemma pow_dvd_of_le_of_pow_dvd {p m n k : ℕ} (hmn : m ≤ n) (hdiv : p ^ n ∣ k) : p ^ m ∣ k := have p ^ m ∣ p ^ n, from pow_dvd_pow _ hmn, dvd_trans this hdiv lemma dvd_of_pow_dvd {p k m : ℕ} (hk : 1 ≤ k) (hpk : p^k ∣ m) : p ∣ m := by rw ←pow_one p; exact pow_dvd_of_le_of_pow_dvd hk hpk /-- `m` is not divisible by `n` iff it is between `n * k` and `n * (k + 1)` for some `k`. -/ lemma exists_lt_and_lt_iff_not_dvd (m : ℕ) {n : ℕ} (hn : 0 < n) : (∃ k, n * k < m ∧ m < n * (k + 1)) ↔ ¬ n ∣ m := begin split, { rintro ⟨k, h1k, h2k⟩ ⟨l, rfl⟩, rw [mul_lt_mul_left hn] at h1k h2k, rw [lt_succ_iff, ← not_lt] at h2k, exact h2k h1k }, { intro h, rw [dvd_iff_mod_eq_zero, ← ne.def, ← pos_iff_ne_zero] at h, simp only [← mod_add_div m n] {single_pass := tt}, refine ⟨m / n, lt_add_of_pos_left _ h, _⟩, rw [add_comm _ 1, left_distrib, mul_one], exact add_lt_add_right (mod_lt _ hn) _ } end /-! ### `find` -/ section find lemma find_eq_iff {p : ℕ → Prop} [decidable_pred p] (h : ∃ n, p n) {m} : nat.find h = m ↔ p m ∧ ∀ n < m, ¬ p n := begin split, { rintro rfl, exact ⟨nat.find_spec h, λ _, nat.find_min h⟩ }, { rintro ⟨hm, hlt⟩, exact le_antisymm (nat.find_min' h hm) (not_lt.1 $ imp_not_comm.1 (hlt _) $ nat.find_spec h) } end @[simp] lemma find_eq_zero {p : ℕ → Prop} [decidable_pred p] (h : ∃ (n : ℕ), p n) : nat.find h = 0 ↔ p 0 := by simp [find_eq_iff] @[simp] lemma find_pos {p : ℕ → Prop} [decidable_pred p] (h : ∃ (n : ℕ), p n) : 0 < nat.find h ↔ ¬ p 0 := by rw [nat.pos_iff_ne_zero, not_iff_not, nat.find_eq_zero] end find /-! ### `find_greatest` -/ section find_greatest /-- `find_greatest P b` is the largest `i ≤ bound` such that `P i` holds, or `0` if no such `i` exists -/ protected def find_greatest (P : ℕ → Prop) [decidable_pred P] : ℕ → ℕ | 0 := 0 | (n + 1) := if P (n + 1) then n + 1 else find_greatest n variables {P : ℕ → Prop} [decidable_pred P] @[simp] lemma find_greatest_zero : nat.find_greatest P 0 = 0 := rfl @[simp] lemma find_greatest_eq : ∀{b}, P b → nat.find_greatest P b = b | 0 h := rfl | (n + 1) h := by simp [nat.find_greatest, h] @[simp] lemma find_greatest_of_not {b} (h : ¬ P (b + 1)) : nat.find_greatest P (b + 1) = nat.find_greatest P b := by simp [nat.find_greatest, h] lemma find_greatest_eq_iff {b m} : nat.find_greatest P b = m ↔ m ≤ b ∧ (m ≠ 0 → P m) ∧ (∀ ⦃n⦄, m < n → n ≤ b → ¬P n) := begin induction b with b ihb generalizing m, { rw [eq_comm, iff.comm], simp only [le_zero_iff_eq, ne.def, and_iff_left_iff_imp, find_greatest_zero], rintro rfl, exact ⟨λ h, (h rfl).elim, λ n hlt heq, (hlt.ne heq.symm).elim⟩ }, { by_cases hb : P (b + 1), { rw [find_greatest_eq hb], split, { rintro rfl, exact ⟨le_refl _, λ _, hb, λ n hlt hle, (hlt.not_le hle).elim⟩ }, { rintros ⟨hle, h0, hm⟩, rcases hle.eq_or_lt with rfl|hlt, exacts [rfl, (hm hlt (le_refl _) hb).elim] } }, { rw [find_greatest_of_not hb, ihb], split, { rintros ⟨hle, hP, hm⟩, refine ⟨hle.trans b.le_succ, hP, λ n hlt hle, _⟩, rcases hle.eq_or_lt with rfl|hlt', exacts [hb, hm hlt $ lt_succ_iff.1 hlt'] }, { rintros ⟨hle, hP, hm⟩, refine ⟨lt_succ_iff.1 (hle.lt_of_ne _), hP, λ n hlt hle, hm hlt (hle.trans b.le_succ)⟩, rintro rfl, exact hb (hP b.succ_ne_zero) } } } end lemma find_greatest_eq_zero_iff {b} : nat.find_greatest P b = 0 ↔ ∀ ⦃n⦄, 0 < n → n ≤ b → ¬P n := by simp [find_greatest_eq_iff] lemma find_greatest_spec {b} (h : ∃m, m ≤ b ∧ P m) : P (nat.find_greatest P b) := begin rcases h with ⟨m, hmb, hm⟩, by_cases h : nat.find_greatest P b = 0, { cases m, { rwa h }, exact ((find_greatest_eq_zero_iff.1 h) m.zero_lt_succ hmb hm).elim }, { exact (find_greatest_eq_iff.1 rfl).2.1 h } end lemma find_greatest_le {b} : nat.find_greatest P b ≤ b := (find_greatest_eq_iff.1 rfl).1 lemma le_find_greatest {b m} (hmb : m ≤ b) (hm : P m) : m ≤ nat.find_greatest P b := le_of_not_lt $ λ hlt, (find_greatest_eq_iff.1 rfl).2.2 hlt hmb hm lemma find_greatest_is_greatest {b k} (hk : nat.find_greatest P b < k) (hkb : k ≤ b) : ¬ P k := (find_greatest_eq_iff.1 rfl).2.2 hk hkb lemma find_greatest_of_ne_zero {b m} (h : nat.find_greatest P b = m) (h0 : m ≠ 0) : P m := (find_greatest_eq_iff.1 h).2.1 h0 end find_greatest /-! ### `bodd_div2` and `bodd` -/ @[simp] theorem bodd_div2_eq (n : ℕ) : bodd_div2 n = (bodd n, div2 n) := by unfold bodd div2; cases bodd_div2 n; refl @[simp] lemma bodd_bit0 (n) : bodd (bit0 n) = ff := bodd_bit ff n @[simp] lemma bodd_bit1 (n) : bodd (bit1 n) = tt := bodd_bit tt n @[simp] lemma div2_bit0 (n) : div2 (bit0 n) = n := div2_bit ff n @[simp] lemma div2_bit1 (n) : div2 (bit1 n) = n := div2_bit tt n /-! ### `bit0` and `bit1` -/ 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 _)) @[simp] lemma bit0_le_bit1_iff : bit0 k ≤ bit1 n ↔ k ≤ n := ⟨λ h, by rwa [← nat.lt_succ_iff, n.bit1_eq_succ_bit0, ← n.bit0_succ_eq, bit0_lt_bit0, nat.lt_succ_iff] at h, λ h, le_of_lt (nat.bit0_lt_bit1 h)⟩ @[simp] lemma bit0_lt_bit1_iff : bit0 k < bit1 n ↔ k ≤ n := ⟨λ h, bit0_le_bit1_iff.1 (le_of_lt h), nat.bit0_lt_bit1⟩ @[simp] lemma bit1_le_bit0_iff : bit1 k ≤ bit0 n ↔ k < n := ⟨λ h, by rwa [k.bit1_eq_succ_bit0, succ_le_iff, bit0_lt_bit0] at h, λ h, le_of_lt (nat.bit1_lt_bit0 h)⟩ @[simp] lemma bit1_lt_bit0_iff : bit1 k < bit0 n ↔ k < n := ⟨λ h, bit1_le_bit0_iff.1 (le_of_lt h), nat.bit1_lt_bit0⟩ @[simp] lemma one_le_bit0_iff : 1 ≤ bit0 n ↔ 0 < n := by { convert bit1_le_bit0_iff, refl, } @[simp] lemma one_lt_bit0_iff : 1 < bit0 n ↔ 1 ≤ n := by { convert bit1_lt_bit0_iff, refl, } @[simp] lemma bit_le_bit_iff : ∀ {b : bool}, bit b k ≤ bit b n ↔ k ≤ n | ff := bit0_le_bit0 | tt := bit1_le_bit1 @[simp] lemma bit_lt_bit_iff : ∀ {b : bool}, bit b k < bit b n ↔ k < n | ff := bit0_lt_bit0 | tt := bit1_lt_bit1 @[simp] lemma bit_le_bit1_iff : ∀ {b : bool}, bit b k ≤ bit1 n ↔ k ≤ n | ff := bit0_le_bit1_iff | tt := bit1_le_bit1 @[simp] lemma bit0_mod_two : bit0 n % 2 = 0 := by { rw nat.mod_two_of_bodd, simp } @[simp] lemma bit1_mod_two : bit1 n % 2 = 1 := by { rw nat.mod_two_of_bodd, simp } lemma pos_of_bit0_pos {n : ℕ} (h : 0 < bit0 n) : 0 < n := by { cases n, cases h, apply succ_pos, } /-- Define a function on `ℕ` depending on parity of the argument. -/ @[elab_as_eliminator] def bit_cases {C : ℕ → Sort u} (H : Π b n, C (bit b n)) (n : ℕ) : C n := eq.rec_on n.bit_decomp (H (bodd n) (div2 n)) /-! ### `shiftl` and `shiftr` -/ lemma shiftl_eq_mul_pow (m) : ∀ n, shiftl m n = m * 2 ^ n | 0 := (nat.mul_one _).symm | (k+1) := show bit0 (shiftl m k) = m * (2 * 2 ^ k), by rw [bit0_val, shiftl_eq_mul_pow, mul_left_comm] lemma shiftl'_tt_eq_mul_pow (m) : ∀ n, shiftl' tt m n + 1 = (m + 1) * 2 ^ n | 0 := by simp [shiftl, shiftl', pow_zero, nat.one_mul] | (k+1) := begin change bit1 (shiftl' tt m k) + 1 = (m + 1) * (2 * 2 ^ k), rw bit1_val, change 2 * (shiftl' tt m k + 1) = _, rw [shiftl'_tt_eq_mul_pow, mul_left_comm] end lemma one_shiftl (n) : shiftl 1 n = 2 ^ n := (shiftl_eq_mul_pow _ _).trans (nat.one_mul _) @[simp] lemma zero_shiftl (n) : shiftl 0 n = 0 := (shiftl_eq_mul_pow _ _).trans (nat.zero_mul _) lemma shiftr_eq_div_pow (m) : ∀ n, shiftr m n = m / 2 ^ n | 0 := (nat.div_one _).symm | (k+1) := (congr_arg div2 (shiftr_eq_div_pow k)).trans $ by rw [div2_val, nat.div_div_eq_div_mul, mul_comm]; refl @[simp] lemma zero_shiftr (n) : shiftr 0 n = 0 := (shiftr_eq_div_pow _ _).trans (nat.zero_div _) 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 _ /-! ### `size` -/ @[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, 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_one : size 1 = 1 := by apply size_bit1 0 @[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 s0 : shiftl' b m n = 0; [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 e : bit b m = 0, { 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 lt_imp_lt_of_le_imp_le (λ 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 _) /-! ### decidability of predicates -/ 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; intro; resetI, { exact is_true (λ n, dec_trivial) }, cases IH (λ k h, P k (lt_succ_of_lt h)) with h, { refine is_false (mt _ h), intros hn k h, apply hn }, by_cases p : P n (lt_succ_self n), { exact is_true (λ k h', (lt_or_eq_of_le $ le_of_lt_succ h').elim (h _) (λ 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 end nat
20cb69ac82b418ed69dde32e1c1f42b34433f8f7
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/nat/gcd_auto.lean
5cc447e3ce0eb0f73c96c395dc215ff871e3a114
[]
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
15,624
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 -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.nat.basic import Mathlib.PostPort namespace Mathlib /-! # Definitions and properties of `gcd`, `lcm`, and `coprime` -/ namespace nat /-! ### `gcd` -/ theorem gcd_dvd (m : ℕ) (n : ℕ) : gcd m n ∣ m ∧ gcd m n ∣ n := sorry theorem gcd_dvd_left (m : ℕ) (n : ℕ) : gcd m n ∣ m := and.left (gcd_dvd m n) theorem gcd_dvd_right (m : ℕ) (n : ℕ) : gcd m n ∣ n := and.right (gcd_dvd m n) theorem gcd_le_left {m : ℕ} (n : ℕ) (h : 0 < m) : gcd m n ≤ m := le_of_dvd h (gcd_dvd_left m n) theorem gcd_le_right (m : ℕ) {n : ℕ} (h : 0 < n) : gcd m n ≤ n := le_of_dvd h (gcd_dvd_right m n) theorem dvd_gcd {m : ℕ} {n : ℕ} {k : ℕ} : k ∣ m → k ∣ n → k ∣ gcd m n := sorry theorem dvd_gcd_iff {m : ℕ} {n : ℕ} {k : ℕ} : k ∣ gcd m n ↔ k ∣ m ∧ k ∣ n := sorry theorem gcd_comm (m : ℕ) (n : ℕ) : gcd m n = gcd n m := dvd_antisymm (dvd_gcd (gcd_dvd_right m n) (gcd_dvd_left m n)) (dvd_gcd (gcd_dvd_right n m) (gcd_dvd_left n m)) theorem gcd_eq_left_iff_dvd {m : ℕ} {n : ℕ} : m ∣ n ↔ gcd m n = m := sorry theorem gcd_eq_right_iff_dvd {m : ℕ} {n : ℕ} : m ∣ n ↔ gcd n m = m := eq.mpr (id (Eq._oldrec (Eq.refl (m ∣ n ↔ gcd n m = m)) (gcd_comm n m))) gcd_eq_left_iff_dvd theorem gcd_assoc (m : ℕ) (n : ℕ) (k : ℕ) : gcd (gcd m n) k = gcd m (gcd n k) := sorry @[simp] theorem gcd_one_right (n : ℕ) : gcd n 1 = 1 := Eq.trans (gcd_comm n 1) (gcd_one_left n) theorem gcd_mul_left (m : ℕ) (n : ℕ) (k : ℕ) : gcd (m * n) (m * k) = m * gcd n k := sorry theorem gcd_mul_right (m : ℕ) (n : ℕ) (k : ℕ) : gcd (m * n) (k * n) = gcd m k * n := sorry theorem gcd_pos_of_pos_left {m : ℕ} (n : ℕ) (mpos : 0 < m) : 0 < gcd m n := pos_of_dvd_of_pos (gcd_dvd_left m n) mpos theorem gcd_pos_of_pos_right (m : ℕ) {n : ℕ} (npos : 0 < n) : 0 < gcd m n := pos_of_dvd_of_pos (gcd_dvd_right m n) npos theorem eq_zero_of_gcd_eq_zero_left {m : ℕ} {n : ℕ} (H : gcd m n = 0) : m = 0 := or.elim (eq_zero_or_pos m) id fun (H1 : 0 < m) => absurd (Eq.symm H) (ne_of_lt (gcd_pos_of_pos_left n H1)) theorem eq_zero_of_gcd_eq_zero_right {m : ℕ} {n : ℕ} (H : gcd m n = 0) : n = 0 := eq_zero_of_gcd_eq_zero_left (eq.mp (Eq._oldrec (Eq.refl (gcd m n = 0)) (gcd_comm m n)) H) theorem gcd_div {m : ℕ} {n : ℕ} {k : ℕ} (H1 : k ∣ m) (H2 : k ∣ n) : gcd (m / k) (n / k) = gcd m n / k := sorry theorem gcd_dvd_gcd_of_dvd_left {m : ℕ} {k : ℕ} (n : ℕ) (H : m ∣ k) : gcd m n ∣ gcd k n := dvd_gcd (dvd.trans (gcd_dvd_left m n) H) (gcd_dvd_right m n) theorem gcd_dvd_gcd_of_dvd_right {m : ℕ} {k : ℕ} (n : ℕ) (H : m ∣ k) : gcd n m ∣ gcd n k := dvd_gcd (gcd_dvd_left n m) (dvd.trans (gcd_dvd_right n m) H) theorem gcd_dvd_gcd_mul_left (m : ℕ) (n : ℕ) (k : ℕ) : gcd m n ∣ gcd (k * m) n := gcd_dvd_gcd_of_dvd_left n (dvd_mul_left m k) theorem gcd_dvd_gcd_mul_right (m : ℕ) (n : ℕ) (k : ℕ) : gcd m n ∣ gcd (m * k) n := gcd_dvd_gcd_of_dvd_left n (dvd_mul_right m k) theorem gcd_dvd_gcd_mul_left_right (m : ℕ) (n : ℕ) (k : ℕ) : gcd m n ∣ gcd m (k * n) := gcd_dvd_gcd_of_dvd_right m (dvd_mul_left n k) theorem gcd_dvd_gcd_mul_right_right (m : ℕ) (n : ℕ) (k : ℕ) : gcd m n ∣ gcd m (n * k) := gcd_dvd_gcd_of_dvd_right m (dvd_mul_right n k) theorem gcd_eq_left {m : ℕ} {n : ℕ} (H : m ∣ n) : gcd m n = m := dvd_antisymm (gcd_dvd_left m n) (dvd_gcd (dvd_refl m) H) theorem gcd_eq_right {m : ℕ} {n : ℕ} (H : n ∣ m) : gcd m n = n := eq.mpr (id (Eq._oldrec (Eq.refl (gcd m n = n)) (gcd_comm m n))) (eq.mpr (id (Eq._oldrec (Eq.refl (gcd n m = n)) (gcd_eq_left H))) (Eq.refl n)) @[simp] theorem gcd_mul_left_left (m : ℕ) (n : ℕ) : gcd (m * n) n = n := dvd_antisymm (gcd_dvd_right (m * n) n) (dvd_gcd (dvd_mul_left n m) (dvd_refl n)) @[simp] theorem gcd_mul_left_right (m : ℕ) (n : ℕ) : gcd n (m * n) = n := eq.mpr (id (Eq._oldrec (Eq.refl (gcd n (m * n) = n)) (gcd_comm n (m * n)))) (eq.mpr (id (Eq._oldrec (Eq.refl (gcd (m * n) n = n)) (gcd_mul_left_left m n))) (Eq.refl n)) @[simp] theorem gcd_mul_right_left (m : ℕ) (n : ℕ) : gcd (n * m) n = n := eq.mpr (id (Eq._oldrec (Eq.refl (gcd (n * m) n = n)) (mul_comm n m))) (eq.mpr (id (Eq._oldrec (Eq.refl (gcd (m * n) n = n)) (gcd_mul_left_left m n))) (Eq.refl n)) @[simp] theorem gcd_mul_right_right (m : ℕ) (n : ℕ) : gcd n (n * m) = n := eq.mpr (id (Eq._oldrec (Eq.refl (gcd n (n * m) = n)) (gcd_comm n (n * m)))) (eq.mpr (id (Eq._oldrec (Eq.refl (gcd (n * m) n = n)) (gcd_mul_right_left m n))) (Eq.refl n)) @[simp] theorem gcd_gcd_self_right_left (m : ℕ) (n : ℕ) : gcd m (gcd m n) = gcd m n := dvd_antisymm (gcd_dvd_right m (gcd m n)) (dvd_gcd (gcd_dvd_left m n) (dvd_refl (gcd m n))) @[simp] theorem gcd_gcd_self_right_right (m : ℕ) (n : ℕ) : gcd m (gcd n m) = gcd n m := eq.mpr (id (Eq._oldrec (Eq.refl (gcd m (gcd n m) = gcd n m)) (gcd_comm n m))) (eq.mpr (id (Eq._oldrec (Eq.refl (gcd m (gcd m n) = gcd m n)) (gcd_gcd_self_right_left m n))) (Eq.refl (gcd m n))) @[simp] theorem gcd_gcd_self_left_right (m : ℕ) (n : ℕ) : gcd (gcd n m) m = gcd n m := eq.mpr (id (Eq._oldrec (Eq.refl (gcd (gcd n m) m = gcd n m)) (gcd_comm (gcd n m) m))) (eq.mpr (id (Eq._oldrec (Eq.refl (gcd m (gcd n m) = gcd n m)) (gcd_gcd_self_right_right m n))) (Eq.refl (gcd n m))) @[simp] theorem gcd_gcd_self_left_left (m : ℕ) (n : ℕ) : gcd (gcd m n) m = gcd m n := eq.mpr (id (Eq._oldrec (Eq.refl (gcd (gcd m n) m = gcd m n)) (gcd_comm m n))) (eq.mpr (id (Eq._oldrec (Eq.refl (gcd (gcd n m) m = gcd n m)) (gcd_gcd_self_left_right m n))) (Eq.refl (gcd n m))) theorem gcd_add_mul_self (m : ℕ) (n : ℕ) (k : ℕ) : gcd m (n + k * m) = gcd m n := sorry theorem gcd_eq_zero_iff {i : ℕ} {j : ℕ} : gcd i j = 0 ↔ i = 0 ∧ j = 0 := sorry /-! ### `lcm` -/ theorem lcm_comm (m : ℕ) (n : ℕ) : lcm m n = lcm n m := id (eq.mpr (id (Eq._oldrec (Eq.refl (m * n / gcd m n = n * m / gcd n m)) (mul_comm m n))) (eq.mpr (id (Eq._oldrec (Eq.refl (n * m / gcd m n = n * m / gcd n m)) (gcd_comm m n))) (Eq.refl (n * m / gcd n m)))) @[simp] theorem lcm_zero_left (m : ℕ) : lcm 0 m = 0 := id (eq.mpr (id (Eq._oldrec (Eq.refl (0 * m / gcd 0 m = 0)) (zero_mul m))) (eq.mpr (id (Eq._oldrec (Eq.refl (0 / gcd 0 m = 0)) (nat.zero_div (gcd 0 m)))) (Eq.refl 0))) @[simp] theorem lcm_zero_right (m : ℕ) : lcm m 0 = 0 := lcm_comm 0 m ▸ lcm_zero_left m @[simp] theorem lcm_one_left (m : ℕ) : lcm 1 m = m := sorry @[simp] theorem lcm_one_right (m : ℕ) : lcm m 1 = m := lcm_comm 1 m ▸ lcm_one_left m @[simp] theorem lcm_self (m : ℕ) : lcm m m = m := sorry theorem dvd_lcm_left (m : ℕ) (n : ℕ) : m ∣ lcm m n := dvd.intro (n / gcd m n) (Eq.symm (nat.mul_div_assoc m (gcd_dvd_right m n))) theorem dvd_lcm_right (m : ℕ) (n : ℕ) : n ∣ lcm m n := lcm_comm n m ▸ dvd_lcm_left n m theorem gcd_mul_lcm (m : ℕ) (n : ℕ) : gcd m n * lcm m n = m * n := sorry theorem lcm_dvd {m : ℕ} {n : ℕ} {k : ℕ} (H1 : m ∣ k) (H2 : n ∣ k) : lcm m n ∣ k := sorry theorem lcm_assoc (m : ℕ) (n : ℕ) (k : ℕ) : lcm (lcm m n) k = lcm m (lcm n k) := sorry theorem lcm_ne_zero {m : ℕ} {n : ℕ} (hm : m ≠ 0) (hn : n ≠ 0) : lcm m n ≠ 0 := sorry /-! ### `coprime` See also `nat.coprime_of_dvd` and `nat.coprime_of_dvd'` to prove `nat.coprime m n`. -/ protected instance coprime.decidable (m : ℕ) (n : ℕ) : Decidable (coprime m n) := eq.mpr sorry (nat.decidable_eq (gcd m n) 1) theorem coprime.gcd_eq_one {m : ℕ} {n : ℕ} : coprime m n → gcd m n = 1 := id theorem coprime.symm {m : ℕ} {n : ℕ} : coprime n m → coprime m n := Eq.trans (gcd_comm m n) theorem coprime.dvd_of_dvd_mul_right {m : ℕ} {n : ℕ} {k : ℕ} (H1 : coprime k n) (H2 : k ∣ m * n) : k ∣ m := sorry theorem coprime.dvd_of_dvd_mul_left {m : ℕ} {n : ℕ} {k : ℕ} (H1 : coprime k m) (H2 : k ∣ m * n) : k ∣ n := coprime.dvd_of_dvd_mul_right H1 (eq.mp (Eq._oldrec (Eq.refl (k ∣ m * n)) (mul_comm m n)) H2) theorem coprime.gcd_mul_left_cancel {k : ℕ} (m : ℕ) {n : ℕ} (H : coprime k n) : gcd (k * m) n = gcd m n := sorry theorem coprime.gcd_mul_right_cancel (m : ℕ) {k : ℕ} {n : ℕ} (H : coprime k n) : gcd (m * k) n = gcd m n := eq.mpr (id (Eq._oldrec (Eq.refl (gcd (m * k) n = gcd m n)) (mul_comm m k))) (eq.mpr (id (Eq._oldrec (Eq.refl (gcd (k * m) n = gcd m n)) (coprime.gcd_mul_left_cancel m H))) (Eq.refl (gcd m n))) theorem coprime.gcd_mul_left_cancel_right {k : ℕ} {m : ℕ} (n : ℕ) (H : coprime k m) : gcd m (k * n) = gcd m n := sorry theorem coprime.gcd_mul_right_cancel_right {k : ℕ} {m : ℕ} (n : ℕ) (H : coprime k m) : gcd m (n * k) = gcd m n := eq.mpr (id (Eq._oldrec (Eq.refl (gcd m (n * k) = gcd m n)) (mul_comm n k))) (eq.mpr (id (Eq._oldrec (Eq.refl (gcd m (k * n) = gcd m n)) (coprime.gcd_mul_left_cancel_right n H))) (Eq.refl (gcd m n))) theorem coprime_div_gcd_div_gcd {m : ℕ} {n : ℕ} (H : 0 < gcd m n) : coprime (m / gcd m n) (n / gcd m n) := sorry theorem not_coprime_of_dvd_of_dvd {m : ℕ} {n : ℕ} {d : ℕ} (dgt1 : 1 < d) (Hm : d ∣ m) (Hn : d ∣ n) : ¬coprime m n := fun (co : gcd m n = 1) => not_lt_of_ge (le_of_dvd zero_lt_one (eq.mpr (id (Eq._oldrec (Eq.refl (d ∣ 1)) (Eq.symm co))) (dvd_gcd Hm Hn))) dgt1 theorem exists_coprime {m : ℕ} {n : ℕ} (H : 0 < gcd m n) : ∃ (m' : ℕ), ∃ (n' : ℕ), coprime m' n' ∧ m = m' * gcd m n ∧ n = n' * gcd m n := sorry theorem exists_coprime' {m : ℕ} {n : ℕ} (H : 0 < gcd m n) : ∃ (g : ℕ), ∃ (m' : ℕ), ∃ (n' : ℕ), 0 < g ∧ coprime m' n' ∧ m = m' * g ∧ n = n' * g := sorry theorem coprime.mul {m : ℕ} {n : ℕ} {k : ℕ} (H1 : coprime m k) (H2 : coprime n k) : coprime (m * n) k := Eq.trans (coprime.gcd_mul_left_cancel n H1) H2 theorem coprime.mul_right {k : ℕ} {m : ℕ} {n : ℕ} (H1 : coprime k m) (H2 : coprime k n) : coprime k (m * n) := coprime.symm (coprime.mul (coprime.symm H1) (coprime.symm H2)) theorem coprime.coprime_dvd_left {m : ℕ} {k : ℕ} {n : ℕ} (H1 : m ∣ k) (H2 : coprime k n) : coprime m n := sorry theorem coprime.coprime_dvd_right {m : ℕ} {k : ℕ} {n : ℕ} (H1 : n ∣ m) (H2 : coprime k m) : coprime k n := coprime.symm (coprime.coprime_dvd_left H1 (coprime.symm H2)) theorem coprime.coprime_mul_left {k : ℕ} {m : ℕ} {n : ℕ} (H : coprime (k * m) n) : coprime m n := coprime.coprime_dvd_left (dvd_mul_left m k) H theorem coprime.coprime_mul_right {k : ℕ} {m : ℕ} {n : ℕ} (H : coprime (m * k) n) : coprime m n := coprime.coprime_dvd_left (dvd_mul_right m k) H theorem coprime.coprime_mul_left_right {k : ℕ} {m : ℕ} {n : ℕ} (H : coprime m (k * n)) : coprime m n := coprime.coprime_dvd_right (dvd_mul_left n k) H theorem coprime.coprime_mul_right_right {k : ℕ} {m : ℕ} {n : ℕ} (H : coprime m (n * k)) : coprime m n := coprime.coprime_dvd_right (dvd_mul_right n k) H theorem coprime.coprime_div_left {m : ℕ} {n : ℕ} {a : ℕ} (cmn : coprime m n) (dvd : a ∣ m) : coprime (m / a) n := sorry theorem coprime.coprime_div_right {m : ℕ} {n : ℕ} {a : ℕ} (cmn : coprime m n) (dvd : a ∣ n) : coprime m (n / a) := coprime.symm (coprime.coprime_div_left (coprime.symm cmn) dvd) theorem coprime_mul_iff_left {k : ℕ} {m : ℕ} {n : ℕ} : coprime (m * n) k ↔ coprime m k ∧ coprime n k := sorry theorem coprime_mul_iff_right {k : ℕ} {m : ℕ} {n : ℕ} : coprime k (m * n) ↔ coprime k m ∧ coprime k n := sorry theorem coprime.gcd_left (k : ℕ) {m : ℕ} {n : ℕ} (hmn : coprime m n) : coprime (gcd k m) n := coprime.coprime_dvd_left (gcd_dvd_right k m) hmn theorem coprime.gcd_right (k : ℕ) {m : ℕ} {n : ℕ} (hmn : coprime m n) : coprime m (gcd k n) := coprime.coprime_dvd_right (gcd_dvd_right k n) hmn theorem coprime.gcd_both (k : ℕ) (l : ℕ) {m : ℕ} {n : ℕ} (hmn : coprime m n) : coprime (gcd k m) (gcd l n) := coprime.gcd_right l (coprime.gcd_left k hmn) theorem coprime.mul_dvd_of_dvd_of_dvd {a : ℕ} {n : ℕ} {m : ℕ} (hmn : coprime m n) (hm : m ∣ a) (hn : n ∣ a) : m * n ∣ a := sorry theorem coprime_one_left (n : ℕ) : coprime 1 n := gcd_one_left theorem coprime_one_right (n : ℕ) : coprime n 1 := gcd_one_right theorem coprime.pow_left {m : ℕ} {k : ℕ} (n : ℕ) (H1 : coprime m k) : coprime (m ^ n) k := nat.rec_on n (coprime_one_left k) fun (n : ℕ) (IH : coprime (m ^ n) k) => coprime.mul H1 IH theorem coprime.pow_right {m : ℕ} {k : ℕ} (n : ℕ) (H1 : coprime k m) : coprime k (m ^ n) := coprime.symm (coprime.pow_left n (coprime.symm H1)) theorem coprime.pow {k : ℕ} {l : ℕ} (m : ℕ) (n : ℕ) (H1 : coprime k l) : coprime (k ^ m) (l ^ n) := coprime.pow_right n (coprime.pow_left m H1) theorem coprime.eq_one_of_dvd {k : ℕ} {m : ℕ} (H : coprime k m) (d : k ∣ m) : k = 1 := eq.mpr (id (Eq._oldrec (Eq.refl (k = 1)) (Eq.symm (coprime.gcd_eq_one H)))) (eq.mpr (id (Eq._oldrec (Eq.refl (k = gcd k m)) (gcd_eq_left d))) (Eq.refl k)) @[simp] theorem coprime_zero_left (n : ℕ) : coprime 0 n ↔ n = 1 := sorry @[simp] theorem coprime_zero_right (n : ℕ) : coprime n 0 ↔ n = 1 := sorry @[simp] theorem coprime_one_left_iff (n : ℕ) : coprime 1 n ↔ True := sorry @[simp] theorem coprime_one_right_iff (n : ℕ) : coprime n 1 ↔ True := sorry @[simp] theorem coprime_self (n : ℕ) : coprime n n ↔ n = 1 := sorry /-- Represent a divisor of `m * n` as a product of a divisor of `m` and a divisor of `n`. -/ def prod_dvd_and_dvd_of_dvd_prod {m : ℕ} {n : ℕ} {k : ℕ} (H : k ∣ m * n) : Subtype fun (d : (Subtype fun (m' : ℕ) => m' ∣ m) × Subtype fun (n' : ℕ) => n' ∣ n) => k = ↑(prod.fst d) * ↑(prod.snd d) := (fun (_x : ℕ) (h0 : gcd k m = _x) => nat.cases_on _x (fun (h0 : gcd k m = 0) => Eq._oldrec (fun (H : 0 ∣ m * n) (h0 : gcd 0 m = 0) => Eq._oldrec (fun (H : 0 ∣ 0 * n) (h0 : gcd 0 0 = 0) => { val := ({ val := 0, property := sorry }, { val := n, property := dvd_refl n }), property := sorry }) sorry H h0) sorry H h0) (fun (n_1 : ℕ) (h0 : gcd k m = Nat.succ n_1) => (fun (h0 : gcd k m = Nat.succ n_1) => { val := ({ val := gcd k m, property := gcd_dvd_right k m }, { val := k / gcd k m, property := sorry }), property := sorry }) h0) h0) (gcd k m) sorry theorem gcd_mul_dvd_mul_gcd (k : ℕ) (m : ℕ) (n : ℕ) : gcd k (m * n) ∣ gcd k m * gcd k n := sorry theorem coprime.gcd_mul (k : ℕ) {m : ℕ} {n : ℕ} (h : coprime m n) : gcd k (m * n) = gcd k m * gcd k n := dvd_antisymm (gcd_mul_dvd_mul_gcd k m n) (coprime.mul_dvd_of_dvd_of_dvd (coprime.gcd_both k k h) (gcd_dvd_gcd_mul_right_right k m n) (gcd_dvd_gcd_mul_left_right k n m)) theorem pow_dvd_pow_iff {a : ℕ} {b : ℕ} {n : ℕ} (n0 : 0 < n) : a ^ n ∣ b ^ n ↔ a ∣ b := sorry theorem gcd_mul_gcd_of_coprime_of_mul_eq_mul {a : ℕ} {b : ℕ} {c : ℕ} {d : ℕ} (cop : coprime c d) (h : a * b = c * d) : gcd a c * gcd b c = c := sorry end Mathlib
1bad306b21964bc4b2ae5aba4caf1fdaf0454b12
54deab7025df5d2df4573383df7e1e5497b7a2c2
/data/option.lean
944af475171d1cdf3a543969956deb19a2542163
[ "Apache-2.0" ]
permissive
HGldJ1966/mathlib
f8daac93a5b4ae805cfb0ecebac21a9ce9469009
c5c5b504b918a6c5e91e372ee29ed754b0513e85
refs/heads/master
1,611,340,395,683
1,503,040,489,000
1,503,040,489,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
313
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ universes u v namespace option @[reducible] def iget {α : Type u} [inhabited α] : option α → α | (some x) := x | none := arbitrary α end option
81e315ad708297bb9f8a116daada5a7d27f094fb
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/analysis/special_functions/trigonometric.lean
0307a1acd67e8b54d08e5b7659ee1fccd5beb205
[]
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
109,694
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.analysis.special_functions.exp_log import Mathlib.data.set.intervals.infinite import Mathlib.algebra.quadratic_discriminant import Mathlib.ring_theory.polynomial.chebyshev.defs import Mathlib.analysis.calculus.times_cont_diff import Mathlib.PostPort universes u_1 namespace Mathlib /-! # Trigonometric functions ## Main definitions This file contains the following definitions: * π, arcsin, arccos, arctan * argument of a complex number * logarithm on complex numbers ## Main statements Many basic inequalities on trigonometric functions are established. The continuity and differentiability of the usual trigonometric functions are proved, and their derivatives are computed. * `polynomial.chebyshev₁_complex_cos`: the `n`-th Chebyshev polynomial evaluates on `complex.cos θ` to the value `n * complex.cos θ`. ## Tags log, sin, cos, tan, arcsin, arccos, arctan, angle, argument -/ namespace complex /-- The complex sine function is everywhere differentiable, with the derivative `cos x`. -/ theorem has_deriv_at_sin (x : ℂ) : has_deriv_at sin (cos x) x := sorry theorem times_cont_diff_sin {n : with_top ℕ} : times_cont_diff ℂ n sin := sorry theorem differentiable_sin : differentiable ℂ sin := fun (x : ℂ) => has_deriv_at.differentiable_at (has_deriv_at_sin x) theorem differentiable_at_sin {x : ℂ} : differentiable_at ℂ sin x := differentiable_sin x @[simp] theorem deriv_sin : deriv sin = cos := funext fun (x : ℂ) => has_deriv_at.deriv (has_deriv_at_sin x) theorem continuous_sin : continuous sin := differentiable.continuous differentiable_sin theorem continuous_on_sin {s : set ℂ} : continuous_on sin s := continuous.continuous_on continuous_sin theorem measurable_sin : measurable sin := continuous.measurable continuous_sin /-- The complex cosine function is everywhere differentiable, with the derivative `-sin x`. -/ theorem has_deriv_at_cos (x : ℂ) : has_deriv_at cos (-sin x) x := sorry theorem times_cont_diff_cos {n : with_top ℕ} : times_cont_diff ℂ n cos := times_cont_diff.div_const (times_cont_diff.add (times_cont_diff.cexp (times_cont_diff.mul times_cont_diff_id times_cont_diff_const)) (times_cont_diff.cexp (times_cont_diff.mul times_cont_diff_neg times_cont_diff_const))) theorem differentiable_cos : differentiable ℂ cos := fun (x : ℂ) => has_deriv_at.differentiable_at (has_deriv_at_cos x) theorem differentiable_at_cos {x : ℂ} : differentiable_at ℂ cos x := differentiable_cos x theorem deriv_cos {x : ℂ} : deriv cos x = -sin x := has_deriv_at.deriv (has_deriv_at_cos x) @[simp] theorem deriv_cos' : deriv cos = fun (x : ℂ) => -sin x := funext fun (x : ℂ) => deriv_cos theorem continuous_cos : continuous cos := differentiable.continuous differentiable_cos theorem continuous_on_cos {s : set ℂ} : continuous_on cos s := continuous.continuous_on continuous_cos theorem measurable_cos : measurable cos := continuous.measurable continuous_cos /-- The complex hyperbolic sine function is everywhere differentiable, with the derivative `cosh x`. -/ theorem has_deriv_at_sinh (x : ℂ) : has_deriv_at sinh (cosh x) x := sorry theorem times_cont_diff_sinh {n : with_top ℕ} : times_cont_diff ℂ n sinh := times_cont_diff.div_const (times_cont_diff.sub times_cont_diff_exp (times_cont_diff.cexp times_cont_diff_neg)) theorem differentiable_sinh : differentiable ℂ sinh := fun (x : ℂ) => has_deriv_at.differentiable_at (has_deriv_at_sinh x) theorem differentiable_at_sinh {x : ℂ} : differentiable_at ℂ sinh x := differentiable_sinh x @[simp] theorem deriv_sinh : deriv sinh = cosh := funext fun (x : ℂ) => has_deriv_at.deriv (has_deriv_at_sinh x) theorem continuous_sinh : continuous sinh := differentiable.continuous differentiable_sinh theorem measurable_sinh : measurable sinh := continuous.measurable continuous_sinh /-- The complex hyperbolic cosine function is everywhere differentiable, with the derivative `sinh x`. -/ theorem has_deriv_at_cosh (x : ℂ) : has_deriv_at cosh (sinh x) x := sorry theorem times_cont_diff_cosh {n : with_top ℕ} : times_cont_diff ℂ n cosh := times_cont_diff.div_const (times_cont_diff.add times_cont_diff_exp (times_cont_diff.cexp times_cont_diff_neg)) theorem differentiable_cosh : differentiable ℂ cosh := fun (x : ℂ) => has_deriv_at.differentiable_at (has_deriv_at_cosh x) theorem differentiable_at_cosh {x : ℂ} : differentiable_at ℂ cos x := differentiable_cos x @[simp] theorem deriv_cosh : deriv cosh = sinh := funext fun (x : ℂ) => has_deriv_at.deriv (has_deriv_at_cosh x) theorem continuous_cosh : continuous cosh := differentiable.continuous differentiable_cosh theorem measurable_cosh : measurable cosh := continuous.measurable continuous_cosh end complex /-! ### Simp lemmas for derivatives of `λ x, complex.cos (f x)` etc., `f : ℂ → ℂ` -/ /-! #### `complex.cos` -/ theorem measurable.ccos {α : Type u_1} [measurable_space α] {f : α → ℂ} (hf : measurable f) : measurable fun (x : α) => complex.cos (f x) := measurable.comp complex.measurable_cos hf theorem has_deriv_at.ccos {f : ℂ → ℂ} {f' : ℂ} {x : ℂ} (hf : has_deriv_at f f' x) : has_deriv_at (fun (x : ℂ) => complex.cos (f x)) (-complex.sin (f x) * f') x := has_deriv_at.comp x (complex.has_deriv_at_cos (f x)) hf theorem has_deriv_within_at.ccos {f : ℂ → ℂ} {f' : ℂ} {x : ℂ} {s : set ℂ} (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (fun (x : ℂ) => complex.cos (f x)) (-complex.sin (f x) * f') s x := has_deriv_at.comp_has_deriv_within_at x (complex.has_deriv_at_cos (f x)) hf theorem deriv_within_ccos {f : ℂ → ℂ} {x : ℂ} {s : set ℂ} (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : deriv_within (fun (x : ℂ) => complex.cos (f x)) s x = -complex.sin (f x) * deriv_within f s x := has_deriv_within_at.deriv_within (has_deriv_within_at.ccos (differentiable_within_at.has_deriv_within_at hf)) hxs @[simp] theorem deriv_ccos {f : ℂ → ℂ} {x : ℂ} (hc : differentiable_at ℂ f x) : deriv (fun (x : ℂ) => complex.cos (f x)) x = -complex.sin (f x) * deriv f x := has_deriv_at.deriv (has_deriv_at.ccos (differentiable_at.has_deriv_at hc)) /-! #### `complex.sin` -/ theorem measurable.csin {α : Type u_1} [measurable_space α] {f : α → ℂ} (hf : measurable f) : measurable fun (x : α) => complex.sin (f x) := measurable.comp complex.measurable_sin hf theorem has_deriv_at.csin {f : ℂ → ℂ} {f' : ℂ} {x : ℂ} (hf : has_deriv_at f f' x) : has_deriv_at (fun (x : ℂ) => complex.sin (f x)) (complex.cos (f x) * f') x := has_deriv_at.comp x (complex.has_deriv_at_sin (f x)) hf theorem has_deriv_within_at.csin {f : ℂ → ℂ} {f' : ℂ} {x : ℂ} {s : set ℂ} (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (fun (x : ℂ) => complex.sin (f x)) (complex.cos (f x) * f') s x := has_deriv_at.comp_has_deriv_within_at x (complex.has_deriv_at_sin (f x)) hf theorem deriv_within_csin {f : ℂ → ℂ} {x : ℂ} {s : set ℂ} (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : deriv_within (fun (x : ℂ) => complex.sin (f x)) s x = complex.cos (f x) * deriv_within f s x := has_deriv_within_at.deriv_within (has_deriv_within_at.csin (differentiable_within_at.has_deriv_within_at hf)) hxs @[simp] theorem deriv_csin {f : ℂ → ℂ} {x : ℂ} (hc : differentiable_at ℂ f x) : deriv (fun (x : ℂ) => complex.sin (f x)) x = complex.cos (f x) * deriv f x := has_deriv_at.deriv (has_deriv_at.csin (differentiable_at.has_deriv_at hc)) /-! #### `complex.cosh` -/ theorem measurable.ccosh {α : Type u_1} [measurable_space α] {f : α → ℂ} (hf : measurable f) : measurable fun (x : α) => complex.cosh (f x) := measurable.comp complex.measurable_cosh hf theorem has_deriv_at.ccosh {f : ℂ → ℂ} {f' : ℂ} {x : ℂ} (hf : has_deriv_at f f' x) : has_deriv_at (fun (x : ℂ) => complex.cosh (f x)) (complex.sinh (f x) * f') x := has_deriv_at.comp x (complex.has_deriv_at_cosh (f x)) hf theorem has_deriv_within_at.ccosh {f : ℂ → ℂ} {f' : ℂ} {x : ℂ} {s : set ℂ} (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (fun (x : ℂ) => complex.cosh (f x)) (complex.sinh (f x) * f') s x := has_deriv_at.comp_has_deriv_within_at x (complex.has_deriv_at_cosh (f x)) hf theorem deriv_within_ccosh {f : ℂ → ℂ} {x : ℂ} {s : set ℂ} (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : deriv_within (fun (x : ℂ) => complex.cosh (f x)) s x = complex.sinh (f x) * deriv_within f s x := has_deriv_within_at.deriv_within (has_deriv_within_at.ccosh (differentiable_within_at.has_deriv_within_at hf)) hxs @[simp] theorem deriv_ccosh {f : ℂ → ℂ} {x : ℂ} (hc : differentiable_at ℂ f x) : deriv (fun (x : ℂ) => complex.cosh (f x)) x = complex.sinh (f x) * deriv f x := has_deriv_at.deriv (has_deriv_at.ccosh (differentiable_at.has_deriv_at hc)) /-! #### `complex.sinh` -/ theorem measurable.csinh {α : Type u_1} [measurable_space α] {f : α → ℂ} (hf : measurable f) : measurable fun (x : α) => complex.sinh (f x) := measurable.comp complex.measurable_sinh hf theorem has_deriv_at.csinh {f : ℂ → ℂ} {f' : ℂ} {x : ℂ} (hf : has_deriv_at f f' x) : has_deriv_at (fun (x : ℂ) => complex.sinh (f x)) (complex.cosh (f x) * f') x := has_deriv_at.comp x (complex.has_deriv_at_sinh (f x)) hf theorem has_deriv_within_at.csinh {f : ℂ → ℂ} {f' : ℂ} {x : ℂ} {s : set ℂ} (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (fun (x : ℂ) => complex.sinh (f x)) (complex.cosh (f x) * f') s x := has_deriv_at.comp_has_deriv_within_at x (complex.has_deriv_at_sinh (f x)) hf theorem deriv_within_csinh {f : ℂ → ℂ} {x : ℂ} {s : set ℂ} (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : deriv_within (fun (x : ℂ) => complex.sinh (f x)) s x = complex.cosh (f x) * deriv_within f s x := has_deriv_within_at.deriv_within (has_deriv_within_at.csinh (differentiable_within_at.has_deriv_within_at hf)) hxs @[simp] theorem deriv_csinh {f : ℂ → ℂ} {x : ℂ} (hc : differentiable_at ℂ f x) : deriv (fun (x : ℂ) => complex.sinh (f x)) x = complex.cosh (f x) * deriv f x := has_deriv_at.deriv (has_deriv_at.csinh (differentiable_at.has_deriv_at hc)) /-! ### Simp lemmas for derivatives of `λ x, complex.cos (f x)` etc., `f : E → ℂ` -/ /-! #### `complex.cos` -/ theorem has_fderiv_at.ccos {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {f' : continuous_linear_map ℂ E ℂ} {x : E} (hf : has_fderiv_at f f' x) : has_fderiv_at (fun (x : E) => complex.cos (f x)) (-complex.sin (f x) • f') x := has_deriv_at.comp_has_fderiv_at x (complex.has_deriv_at_cos (f x)) hf theorem has_fderiv_within_at.ccos {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {f' : continuous_linear_map ℂ E ℂ} {x : E} {s : set E} (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (fun (x : E) => complex.cos (f x)) (-complex.sin (f x) • f') s x := has_deriv_at.comp_has_fderiv_within_at x (complex.has_deriv_at_cos (f x)) hf theorem differentiable_within_at.ccos {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {x : E} {s : set E} (hf : differentiable_within_at ℂ f s x) : differentiable_within_at ℂ (fun (x : E) => complex.cos (f x)) s x := has_fderiv_within_at.differentiable_within_at (has_fderiv_within_at.ccos (differentiable_within_at.has_fderiv_within_at hf)) @[simp] theorem differentiable_at.ccos {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {x : E} (hc : differentiable_at ℂ f x) : differentiable_at ℂ (fun (x : E) => complex.cos (f x)) x := has_fderiv_at.differentiable_at (has_fderiv_at.ccos (differentiable_at.has_fderiv_at hc)) theorem differentiable_on.ccos {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {s : set E} (hc : differentiable_on ℂ f s) : differentiable_on ℂ (fun (x : E) => complex.cos (f x)) s := fun (x : E) (h : x ∈ s) => differentiable_within_at.ccos (hc x h) @[simp] theorem differentiable.ccos {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} (hc : differentiable ℂ f) : differentiable ℂ fun (x : E) => complex.cos (f x) := fun (x : E) => differentiable_at.ccos (hc x) theorem fderiv_within_ccos {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {x : E} {s : set E} (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : fderiv_within ℂ (fun (x : E) => complex.cos (f x)) s x = -complex.sin (f x) • fderiv_within ℂ f s x := has_fderiv_within_at.fderiv_within (has_fderiv_within_at.ccos (differentiable_within_at.has_fderiv_within_at hf)) hxs @[simp] theorem fderiv_ccos {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {x : E} (hc : differentiable_at ℂ f x) : fderiv ℂ (fun (x : E) => complex.cos (f x)) x = -complex.sin (f x) • fderiv ℂ f x := has_fderiv_at.fderiv (has_fderiv_at.ccos (differentiable_at.has_fderiv_at hc)) theorem times_cont_diff.ccos {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {n : with_top ℕ} (h : times_cont_diff ℂ n f) : times_cont_diff ℂ n fun (x : E) => complex.cos (f x) := times_cont_diff.comp complex.times_cont_diff_cos h theorem times_cont_diff_at.ccos {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {x : E} {n : with_top ℕ} (hf : times_cont_diff_at ℂ n f x) : times_cont_diff_at ℂ n (fun (x : E) => complex.cos (f x)) x := times_cont_diff_at.comp x (times_cont_diff.times_cont_diff_at complex.times_cont_diff_cos) hf theorem times_cont_diff_on.ccos {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {s : set E} {n : with_top ℕ} (hf : times_cont_diff_on ℂ n f s) : times_cont_diff_on ℂ n (fun (x : E) => complex.cos (f x)) s := times_cont_diff.comp_times_cont_diff_on complex.times_cont_diff_cos hf theorem times_cont_diff_within_at.ccos {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {x : E} {s : set E} {n : with_top ℕ} (hf : times_cont_diff_within_at ℂ n f s x) : times_cont_diff_within_at ℂ n (fun (x : E) => complex.cos (f x)) s x := times_cont_diff_at.comp_times_cont_diff_within_at x (times_cont_diff.times_cont_diff_at complex.times_cont_diff_cos) hf /-! #### `complex.sin` -/ theorem has_fderiv_at.csin {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {f' : continuous_linear_map ℂ E ℂ} {x : E} (hf : has_fderiv_at f f' x) : has_fderiv_at (fun (x : E) => complex.sin (f x)) (complex.cos (f x) • f') x := has_deriv_at.comp_has_fderiv_at x (complex.has_deriv_at_sin (f x)) hf theorem has_fderiv_within_at.csin {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {f' : continuous_linear_map ℂ E ℂ} {x : E} {s : set E} (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (fun (x : E) => complex.sin (f x)) (complex.cos (f x) • f') s x := has_deriv_at.comp_has_fderiv_within_at x (complex.has_deriv_at_sin (f x)) hf theorem differentiable_within_at.csin {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {x : E} {s : set E} (hf : differentiable_within_at ℂ f s x) : differentiable_within_at ℂ (fun (x : E) => complex.sin (f x)) s x := has_fderiv_within_at.differentiable_within_at (has_fderiv_within_at.csin (differentiable_within_at.has_fderiv_within_at hf)) @[simp] theorem differentiable_at.csin {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {x : E} (hc : differentiable_at ℂ f x) : differentiable_at ℂ (fun (x : E) => complex.sin (f x)) x := has_fderiv_at.differentiable_at (has_fderiv_at.csin (differentiable_at.has_fderiv_at hc)) theorem differentiable_on.csin {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {s : set E} (hc : differentiable_on ℂ f s) : differentiable_on ℂ (fun (x : E) => complex.sin (f x)) s := fun (x : E) (h : x ∈ s) => differentiable_within_at.csin (hc x h) @[simp] theorem differentiable.csin {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} (hc : differentiable ℂ f) : differentiable ℂ fun (x : E) => complex.sin (f x) := fun (x : E) => differentiable_at.csin (hc x) theorem fderiv_within_csin {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {x : E} {s : set E} (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : fderiv_within ℂ (fun (x : E) => complex.sin (f x)) s x = complex.cos (f x) • fderiv_within ℂ f s x := has_fderiv_within_at.fderiv_within (has_fderiv_within_at.csin (differentiable_within_at.has_fderiv_within_at hf)) hxs @[simp] theorem fderiv_csin {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {x : E} (hc : differentiable_at ℂ f x) : fderiv ℂ (fun (x : E) => complex.sin (f x)) x = complex.cos (f x) • fderiv ℂ f x := has_fderiv_at.fderiv (has_fderiv_at.csin (differentiable_at.has_fderiv_at hc)) theorem times_cont_diff.csin {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {n : with_top ℕ} (h : times_cont_diff ℂ n f) : times_cont_diff ℂ n fun (x : E) => complex.sin (f x) := times_cont_diff.comp complex.times_cont_diff_sin h theorem times_cont_diff_at.csin {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {x : E} {n : with_top ℕ} (hf : times_cont_diff_at ℂ n f x) : times_cont_diff_at ℂ n (fun (x : E) => complex.sin (f x)) x := times_cont_diff_at.comp x (times_cont_diff.times_cont_diff_at complex.times_cont_diff_sin) hf theorem times_cont_diff_on.csin {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {s : set E} {n : with_top ℕ} (hf : times_cont_diff_on ℂ n f s) : times_cont_diff_on ℂ n (fun (x : E) => complex.sin (f x)) s := times_cont_diff.comp_times_cont_diff_on complex.times_cont_diff_sin hf theorem times_cont_diff_within_at.csin {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {x : E} {s : set E} {n : with_top ℕ} (hf : times_cont_diff_within_at ℂ n f s x) : times_cont_diff_within_at ℂ n (fun (x : E) => complex.sin (f x)) s x := times_cont_diff_at.comp_times_cont_diff_within_at x (times_cont_diff.times_cont_diff_at complex.times_cont_diff_sin) hf /-! #### `complex.cosh` -/ theorem has_fderiv_at.ccosh {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {f' : continuous_linear_map ℂ E ℂ} {x : E} (hf : has_fderiv_at f f' x) : has_fderiv_at (fun (x : E) => complex.cosh (f x)) (complex.sinh (f x) • f') x := has_deriv_at.comp_has_fderiv_at x (complex.has_deriv_at_cosh (f x)) hf theorem has_fderiv_within_at.ccosh {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {f' : continuous_linear_map ℂ E ℂ} {x : E} {s : set E} (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (fun (x : E) => complex.cosh (f x)) (complex.sinh (f x) • f') s x := has_deriv_at.comp_has_fderiv_within_at x (complex.has_deriv_at_cosh (f x)) hf theorem differentiable_within_at.ccosh {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {x : E} {s : set E} (hf : differentiable_within_at ℂ f s x) : differentiable_within_at ℂ (fun (x : E) => complex.cosh (f x)) s x := has_fderiv_within_at.differentiable_within_at (has_fderiv_within_at.ccosh (differentiable_within_at.has_fderiv_within_at hf)) @[simp] theorem differentiable_at.ccosh {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {x : E} (hc : differentiable_at ℂ f x) : differentiable_at ℂ (fun (x : E) => complex.cosh (f x)) x := has_fderiv_at.differentiable_at (has_fderiv_at.ccosh (differentiable_at.has_fderiv_at hc)) theorem differentiable_on.ccosh {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {s : set E} (hc : differentiable_on ℂ f s) : differentiable_on ℂ (fun (x : E) => complex.cosh (f x)) s := fun (x : E) (h : x ∈ s) => differentiable_within_at.ccosh (hc x h) @[simp] theorem differentiable.ccosh {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} (hc : differentiable ℂ f) : differentiable ℂ fun (x : E) => complex.cosh (f x) := fun (x : E) => differentiable_at.ccosh (hc x) theorem fderiv_within_ccosh {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {x : E} {s : set E} (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : fderiv_within ℂ (fun (x : E) => complex.cosh (f x)) s x = complex.sinh (f x) • fderiv_within ℂ f s x := has_fderiv_within_at.fderiv_within (has_fderiv_within_at.ccosh (differentiable_within_at.has_fderiv_within_at hf)) hxs @[simp] theorem fderiv_ccosh {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {x : E} (hc : differentiable_at ℂ f x) : fderiv ℂ (fun (x : E) => complex.cosh (f x)) x = complex.sinh (f x) • fderiv ℂ f x := has_fderiv_at.fderiv (has_fderiv_at.ccosh (differentiable_at.has_fderiv_at hc)) theorem times_cont_diff.ccosh {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {n : with_top ℕ} (h : times_cont_diff ℂ n f) : times_cont_diff ℂ n fun (x : E) => complex.cosh (f x) := times_cont_diff.comp complex.times_cont_diff_cosh h theorem times_cont_diff_at.ccosh {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {x : E} {n : with_top ℕ} (hf : times_cont_diff_at ℂ n f x) : times_cont_diff_at ℂ n (fun (x : E) => complex.cosh (f x)) x := times_cont_diff_at.comp x (times_cont_diff.times_cont_diff_at complex.times_cont_diff_cosh) hf theorem times_cont_diff_on.ccosh {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {s : set E} {n : with_top ℕ} (hf : times_cont_diff_on ℂ n f s) : times_cont_diff_on ℂ n (fun (x : E) => complex.cosh (f x)) s := times_cont_diff.comp_times_cont_diff_on complex.times_cont_diff_cosh hf theorem times_cont_diff_within_at.ccosh {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {x : E} {s : set E} {n : with_top ℕ} (hf : times_cont_diff_within_at ℂ n f s x) : times_cont_diff_within_at ℂ n (fun (x : E) => complex.cosh (f x)) s x := times_cont_diff_at.comp_times_cont_diff_within_at x (times_cont_diff.times_cont_diff_at complex.times_cont_diff_cosh) hf /-! #### `complex.sinh` -/ theorem has_fderiv_at.csinh {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {f' : continuous_linear_map ℂ E ℂ} {x : E} (hf : has_fderiv_at f f' x) : has_fderiv_at (fun (x : E) => complex.sinh (f x)) (complex.cosh (f x) • f') x := has_deriv_at.comp_has_fderiv_at x (complex.has_deriv_at_sinh (f x)) hf theorem has_fderiv_within_at.csinh {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {f' : continuous_linear_map ℂ E ℂ} {x : E} {s : set E} (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (fun (x : E) => complex.sinh (f x)) (complex.cosh (f x) • f') s x := has_deriv_at.comp_has_fderiv_within_at x (complex.has_deriv_at_sinh (f x)) hf theorem differentiable_within_at.csinh {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {x : E} {s : set E} (hf : differentiable_within_at ℂ f s x) : differentiable_within_at ℂ (fun (x : E) => complex.sinh (f x)) s x := has_fderiv_within_at.differentiable_within_at (has_fderiv_within_at.csinh (differentiable_within_at.has_fderiv_within_at hf)) @[simp] theorem differentiable_at.csinh {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {x : E} (hc : differentiable_at ℂ f x) : differentiable_at ℂ (fun (x : E) => complex.sinh (f x)) x := has_fderiv_at.differentiable_at (has_fderiv_at.csinh (differentiable_at.has_fderiv_at hc)) theorem differentiable_on.csinh {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {s : set E} (hc : differentiable_on ℂ f s) : differentiable_on ℂ (fun (x : E) => complex.sinh (f x)) s := fun (x : E) (h : x ∈ s) => differentiable_within_at.csinh (hc x h) @[simp] theorem differentiable.csinh {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} (hc : differentiable ℂ f) : differentiable ℂ fun (x : E) => complex.sinh (f x) := fun (x : E) => differentiable_at.csinh (hc x) theorem fderiv_within_csinh {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {x : E} {s : set E} (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : fderiv_within ℂ (fun (x : E) => complex.sinh (f x)) s x = complex.cosh (f x) • fderiv_within ℂ f s x := has_fderiv_within_at.fderiv_within (has_fderiv_within_at.csinh (differentiable_within_at.has_fderiv_within_at hf)) hxs @[simp] theorem fderiv_csinh {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {x : E} (hc : differentiable_at ℂ f x) : fderiv ℂ (fun (x : E) => complex.sinh (f x)) x = complex.cosh (f x) • fderiv ℂ f x := has_fderiv_at.fderiv (has_fderiv_at.csinh (differentiable_at.has_fderiv_at hc)) theorem times_cont_diff.csinh {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {n : with_top ℕ} (h : times_cont_diff ℂ n f) : times_cont_diff ℂ n fun (x : E) => complex.sinh (f x) := times_cont_diff.comp complex.times_cont_diff_sinh h theorem times_cont_diff_at.csinh {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {x : E} {n : with_top ℕ} (hf : times_cont_diff_at ℂ n f x) : times_cont_diff_at ℂ n (fun (x : E) => complex.sinh (f x)) x := times_cont_diff_at.comp x (times_cont_diff.times_cont_diff_at complex.times_cont_diff_sinh) hf theorem times_cont_diff_on.csinh {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {s : set E} {n : with_top ℕ} (hf : times_cont_diff_on ℂ n f s) : times_cont_diff_on ℂ n (fun (x : E) => complex.sinh (f x)) s := times_cont_diff.comp_times_cont_diff_on complex.times_cont_diff_sinh hf theorem times_cont_diff_within_at.csinh {E : Type u_1} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {x : E} {s : set E} {n : with_top ℕ} (hf : times_cont_diff_within_at ℂ n f s x) : times_cont_diff_within_at ℂ n (fun (x : E) => complex.sinh (f x)) s x := times_cont_diff_at.comp_times_cont_diff_within_at x (times_cont_diff.times_cont_diff_at complex.times_cont_diff_sinh) hf namespace real theorem has_deriv_at_sin (x : ℝ) : has_deriv_at sin (cos x) x := has_deriv_at.real_of_complex (complex.has_deriv_at_sin ↑x) theorem times_cont_diff_sin {n : with_top ℕ} : times_cont_diff ℝ n sin := times_cont_diff.real_of_complex complex.times_cont_diff_sin theorem differentiable_sin : differentiable ℝ sin := fun (x : ℝ) => has_deriv_at.differentiable_at (has_deriv_at_sin x) theorem differentiable_at_sin {x : ℝ} : differentiable_at ℝ sin x := differentiable_sin x @[simp] theorem deriv_sin : deriv sin = cos := funext fun (x : ℝ) => has_deriv_at.deriv (has_deriv_at_sin x) theorem continuous_sin : continuous sin := differentiable.continuous differentiable_sin theorem measurable_sin : measurable sin := continuous.measurable continuous_sin theorem has_deriv_at_cos (x : ℝ) : has_deriv_at cos (-sin x) x := has_deriv_at.real_of_complex (complex.has_deriv_at_cos ↑x) theorem times_cont_diff_cos {n : with_top ℕ} : times_cont_diff ℝ n cos := times_cont_diff.real_of_complex complex.times_cont_diff_cos theorem differentiable_cos : differentiable ℝ cos := fun (x : ℝ) => has_deriv_at.differentiable_at (has_deriv_at_cos x) theorem differentiable_at_cos {x : ℝ} : differentiable_at ℝ cos x := differentiable_cos x theorem deriv_cos {x : ℝ} : deriv cos x = -sin x := has_deriv_at.deriv (has_deriv_at_cos x) @[simp] theorem deriv_cos' : deriv cos = fun (x : ℝ) => -sin x := funext fun (_x : ℝ) => deriv_cos theorem continuous_cos : continuous cos := differentiable.continuous differentiable_cos theorem continuous_on_cos {s : set ℝ} : continuous_on cos s := continuous.continuous_on continuous_cos theorem measurable_cos : measurable cos := continuous.measurable continuous_cos theorem has_deriv_at_sinh (x : ℝ) : has_deriv_at sinh (cosh x) x := has_deriv_at.real_of_complex (complex.has_deriv_at_sinh ↑x) theorem times_cont_diff_sinh {n : with_top ℕ} : times_cont_diff ℝ n sinh := times_cont_diff.real_of_complex complex.times_cont_diff_sinh theorem differentiable_sinh : differentiable ℝ sinh := fun (x : ℝ) => has_deriv_at.differentiable_at (has_deriv_at_sinh x) theorem differentiable_at_sinh {x : ℝ} : differentiable_at ℝ sinh x := differentiable_sinh x @[simp] theorem deriv_sinh : deriv sinh = cosh := funext fun (x : ℝ) => has_deriv_at.deriv (has_deriv_at_sinh x) theorem continuous_sinh : continuous sinh := differentiable.continuous differentiable_sinh theorem measurable_sinh : measurable sinh := continuous.measurable continuous_sinh theorem has_deriv_at_cosh (x : ℝ) : has_deriv_at cosh (sinh x) x := has_deriv_at.real_of_complex (complex.has_deriv_at_cosh ↑x) theorem times_cont_diff_cosh {n : with_top ℕ} : times_cont_diff ℝ n cosh := times_cont_diff.real_of_complex complex.times_cont_diff_cosh theorem differentiable_cosh : differentiable ℝ cosh := fun (x : ℝ) => has_deriv_at.differentiable_at (has_deriv_at_cosh x) theorem differentiable_at_cosh {x : ℝ} : differentiable_at ℝ cosh x := differentiable_cosh x @[simp] theorem deriv_cosh : deriv cosh = sinh := funext fun (x : ℝ) => has_deriv_at.deriv (has_deriv_at_cosh x) theorem continuous_cosh : continuous cosh := differentiable.continuous differentiable_cosh theorem measurable_cosh : measurable cosh := continuous.measurable continuous_cosh /-- `sinh` is strictly monotone. -/ theorem sinh_strict_mono : strict_mono sinh := strict_mono_of_deriv_pos differentiable_sinh (eq.mpr (id (Eq._oldrec (Eq.refl (∀ (x : ℝ), 0 < deriv sinh x)) deriv_sinh)) cosh_pos) end real /-! ### Simp lemmas for derivatives of `λ x, real.cos (f x)` etc., `f : ℝ → ℝ` -/ /-! #### `real.cos` -/ theorem measurable.cos {α : Type u_1} [measurable_space α] {f : α → ℝ} (hf : measurable f) : measurable fun (x : α) => real.cos (f x) := measurable.comp real.measurable_cos hf theorem has_deriv_at.cos {f : ℝ → ℝ} {f' : ℝ} {x : ℝ} (hf : has_deriv_at f f' x) : has_deriv_at (fun (x : ℝ) => real.cos (f x)) (-real.sin (f x) * f') x := has_deriv_at.comp x (real.has_deriv_at_cos (f x)) hf theorem has_deriv_within_at.cos {f : ℝ → ℝ} {f' : ℝ} {x : ℝ} {s : set ℝ} (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (fun (x : ℝ) => real.cos (f x)) (-real.sin (f x) * f') s x := has_deriv_at.comp_has_deriv_within_at x (real.has_deriv_at_cos (f x)) hf theorem deriv_within_cos {f : ℝ → ℝ} {x : ℝ} {s : set ℝ} (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : deriv_within (fun (x : ℝ) => real.cos (f x)) s x = -real.sin (f x) * deriv_within f s x := has_deriv_within_at.deriv_within (has_deriv_within_at.cos (differentiable_within_at.has_deriv_within_at hf)) hxs @[simp] theorem deriv_cos {f : ℝ → ℝ} {x : ℝ} (hc : differentiable_at ℝ f x) : deriv (fun (x : ℝ) => real.cos (f x)) x = -real.sin (f x) * deriv f x := has_deriv_at.deriv (has_deriv_at.cos (differentiable_at.has_deriv_at hc)) /-! #### `real.sin` -/ theorem measurable.sin {α : Type u_1} [measurable_space α] {f : α → ℝ} (hf : measurable f) : measurable fun (x : α) => real.sin (f x) := measurable.comp real.measurable_sin hf theorem has_deriv_at.sin {f : ℝ → ℝ} {f' : ℝ} {x : ℝ} (hf : has_deriv_at f f' x) : has_deriv_at (fun (x : ℝ) => real.sin (f x)) (real.cos (f x) * f') x := has_deriv_at.comp x (real.has_deriv_at_sin (f x)) hf theorem has_deriv_within_at.sin {f : ℝ → ℝ} {f' : ℝ} {x : ℝ} {s : set ℝ} (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (fun (x : ℝ) => real.sin (f x)) (real.cos (f x) * f') s x := has_deriv_at.comp_has_deriv_within_at x (real.has_deriv_at_sin (f x)) hf theorem deriv_within_sin {f : ℝ → ℝ} {x : ℝ} {s : set ℝ} (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : deriv_within (fun (x : ℝ) => real.sin (f x)) s x = real.cos (f x) * deriv_within f s x := has_deriv_within_at.deriv_within (has_deriv_within_at.sin (differentiable_within_at.has_deriv_within_at hf)) hxs @[simp] theorem deriv_sin {f : ℝ → ℝ} {x : ℝ} (hc : differentiable_at ℝ f x) : deriv (fun (x : ℝ) => real.sin (f x)) x = real.cos (f x) * deriv f x := has_deriv_at.deriv (has_deriv_at.sin (differentiable_at.has_deriv_at hc)) /-! #### `real.cosh` -/ theorem measurable.cosh {α : Type u_1} [measurable_space α] {f : α → ℝ} (hf : measurable f) : measurable fun (x : α) => real.cosh (f x) := measurable.comp real.measurable_cosh hf theorem has_deriv_at.cosh {f : ℝ → ℝ} {f' : ℝ} {x : ℝ} (hf : has_deriv_at f f' x) : has_deriv_at (fun (x : ℝ) => real.cosh (f x)) (real.sinh (f x) * f') x := has_deriv_at.comp x (real.has_deriv_at_cosh (f x)) hf theorem has_deriv_within_at.cosh {f : ℝ → ℝ} {f' : ℝ} {x : ℝ} {s : set ℝ} (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (fun (x : ℝ) => real.cosh (f x)) (real.sinh (f x) * f') s x := has_deriv_at.comp_has_deriv_within_at x (real.has_deriv_at_cosh (f x)) hf theorem deriv_within_cosh {f : ℝ → ℝ} {x : ℝ} {s : set ℝ} (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : deriv_within (fun (x : ℝ) => real.cosh (f x)) s x = real.sinh (f x) * deriv_within f s x := has_deriv_within_at.deriv_within (has_deriv_within_at.cosh (differentiable_within_at.has_deriv_within_at hf)) hxs @[simp] theorem deriv_cosh {f : ℝ → ℝ} {x : ℝ} (hc : differentiable_at ℝ f x) : deriv (fun (x : ℝ) => real.cosh (f x)) x = real.sinh (f x) * deriv f x := has_deriv_at.deriv (has_deriv_at.cosh (differentiable_at.has_deriv_at hc)) /-! #### `real.sinh` -/ theorem measurable.sinh {α : Type u_1} [measurable_space α] {f : α → ℝ} (hf : measurable f) : measurable fun (x : α) => real.sinh (f x) := measurable.comp real.measurable_sinh hf theorem has_deriv_at.sinh {f : ℝ → ℝ} {f' : ℝ} {x : ℝ} (hf : has_deriv_at f f' x) : has_deriv_at (fun (x : ℝ) => real.sinh (f x)) (real.cosh (f x) * f') x := has_deriv_at.comp x (real.has_deriv_at_sinh (f x)) hf theorem has_deriv_within_at.sinh {f : ℝ → ℝ} {f' : ℝ} {x : ℝ} {s : set ℝ} (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (fun (x : ℝ) => real.sinh (f x)) (real.cosh (f x) * f') s x := has_deriv_at.comp_has_deriv_within_at x (real.has_deriv_at_sinh (f x)) hf theorem deriv_within_sinh {f : ℝ → ℝ} {x : ℝ} {s : set ℝ} (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : deriv_within (fun (x : ℝ) => real.sinh (f x)) s x = real.cosh (f x) * deriv_within f s x := has_deriv_within_at.deriv_within (has_deriv_within_at.sinh (differentiable_within_at.has_deriv_within_at hf)) hxs @[simp] theorem deriv_sinh {f : ℝ → ℝ} {x : ℝ} (hc : differentiable_at ℝ f x) : deriv (fun (x : ℝ) => real.sinh (f x)) x = real.cosh (f x) * deriv f x := has_deriv_at.deriv (has_deriv_at.sinh (differentiable_at.has_deriv_at hc)) /-! ### Simp lemmas for derivatives of `λ x, real.cos (f x)` etc., `f : E → ℝ` -/ /-! #### `real.cos` -/ theorem has_fderiv_at.cos {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {f' : continuous_linear_map ℝ E ℝ} {x : E} (hf : has_fderiv_at f f' x) : has_fderiv_at (fun (x : E) => real.cos (f x)) (-real.sin (f x) • f') x := has_deriv_at.comp_has_fderiv_at x (real.has_deriv_at_cos (f x)) hf theorem has_fderiv_within_at.cos {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {f' : continuous_linear_map ℝ E ℝ} {x : E} {s : set E} (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (fun (x : E) => real.cos (f x)) (-real.sin (f x) • f') s x := has_deriv_at.comp_has_fderiv_within_at x (real.has_deriv_at_cos (f x)) hf theorem differentiable_within_at.cos {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {x : E} {s : set E} (hf : differentiable_within_at ℝ f s x) : differentiable_within_at ℝ (fun (x : E) => real.cos (f x)) s x := has_fderiv_within_at.differentiable_within_at (has_fderiv_within_at.cos (differentiable_within_at.has_fderiv_within_at hf)) @[simp] theorem differentiable_at.cos {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {x : E} (hc : differentiable_at ℝ f x) : differentiable_at ℝ (fun (x : E) => real.cos (f x)) x := has_fderiv_at.differentiable_at (has_fderiv_at.cos (differentiable_at.has_fderiv_at hc)) theorem differentiable_on.cos {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {s : set E} (hc : differentiable_on ℝ f s) : differentiable_on ℝ (fun (x : E) => real.cos (f x)) s := fun (x : E) (h : x ∈ s) => differentiable_within_at.cos (hc x h) @[simp] theorem differentiable.cos {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} (hc : differentiable ℝ f) : differentiable ℝ fun (x : E) => real.cos (f x) := fun (x : E) => differentiable_at.cos (hc x) theorem fderiv_within_cos {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {x : E} {s : set E} (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : fderiv_within ℝ (fun (x : E) => real.cos (f x)) s x = -real.sin (f x) • fderiv_within ℝ f s x := has_fderiv_within_at.fderiv_within (has_fderiv_within_at.cos (differentiable_within_at.has_fderiv_within_at hf)) hxs @[simp] theorem fderiv_cos {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {x : E} (hc : differentiable_at ℝ f x) : fderiv ℝ (fun (x : E) => real.cos (f x)) x = -real.sin (f x) • fderiv ℝ f x := has_fderiv_at.fderiv (has_fderiv_at.cos (differentiable_at.has_fderiv_at hc)) theorem times_cont_diff.cos {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {n : with_top ℕ} (h : times_cont_diff ℝ n f) : times_cont_diff ℝ n fun (x : E) => real.cos (f x) := times_cont_diff.comp real.times_cont_diff_cos h theorem times_cont_diff_at.cos {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {x : E} {n : with_top ℕ} (hf : times_cont_diff_at ℝ n f x) : times_cont_diff_at ℝ n (fun (x : E) => real.cos (f x)) x := times_cont_diff_at.comp x (times_cont_diff.times_cont_diff_at real.times_cont_diff_cos) hf theorem times_cont_diff_on.cos {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {s : set E} {n : with_top ℕ} (hf : times_cont_diff_on ℝ n f s) : times_cont_diff_on ℝ n (fun (x : E) => real.cos (f x)) s := times_cont_diff.comp_times_cont_diff_on real.times_cont_diff_cos hf theorem times_cont_diff_within_at.cos {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {x : E} {s : set E} {n : with_top ℕ} (hf : times_cont_diff_within_at ℝ n f s x) : times_cont_diff_within_at ℝ n (fun (x : E) => real.cos (f x)) s x := times_cont_diff_at.comp_times_cont_diff_within_at x (times_cont_diff.times_cont_diff_at real.times_cont_diff_cos) hf /-! #### `real.sin` -/ theorem has_fderiv_at.sin {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {f' : continuous_linear_map ℝ E ℝ} {x : E} (hf : has_fderiv_at f f' x) : has_fderiv_at (fun (x : E) => real.sin (f x)) (real.cos (f x) • f') x := has_deriv_at.comp_has_fderiv_at x (real.has_deriv_at_sin (f x)) hf theorem has_fderiv_within_at.sin {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {f' : continuous_linear_map ℝ E ℝ} {x : E} {s : set E} (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (fun (x : E) => real.sin (f x)) (real.cos (f x) • f') s x := has_deriv_at.comp_has_fderiv_within_at x (real.has_deriv_at_sin (f x)) hf theorem differentiable_within_at.sin {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {x : E} {s : set E} (hf : differentiable_within_at ℝ f s x) : differentiable_within_at ℝ (fun (x : E) => real.sin (f x)) s x := has_fderiv_within_at.differentiable_within_at (has_fderiv_within_at.sin (differentiable_within_at.has_fderiv_within_at hf)) @[simp] theorem differentiable_at.sin {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {x : E} (hc : differentiable_at ℝ f x) : differentiable_at ℝ (fun (x : E) => real.sin (f x)) x := has_fderiv_at.differentiable_at (has_fderiv_at.sin (differentiable_at.has_fderiv_at hc)) theorem differentiable_on.sin {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {s : set E} (hc : differentiable_on ℝ f s) : differentiable_on ℝ (fun (x : E) => real.sin (f x)) s := fun (x : E) (h : x ∈ s) => differentiable_within_at.sin (hc x h) @[simp] theorem differentiable.sin {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} (hc : differentiable ℝ f) : differentiable ℝ fun (x : E) => real.sin (f x) := fun (x : E) => differentiable_at.sin (hc x) theorem fderiv_within_sin {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {x : E} {s : set E} (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : fderiv_within ℝ (fun (x : E) => real.sin (f x)) s x = real.cos (f x) • fderiv_within ℝ f s x := has_fderiv_within_at.fderiv_within (has_fderiv_within_at.sin (differentiable_within_at.has_fderiv_within_at hf)) hxs @[simp] theorem fderiv_sin {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {x : E} (hc : differentiable_at ℝ f x) : fderiv ℝ (fun (x : E) => real.sin (f x)) x = real.cos (f x) • fderiv ℝ f x := has_fderiv_at.fderiv (has_fderiv_at.sin (differentiable_at.has_fderiv_at hc)) theorem times_cont_diff.sin {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {n : with_top ℕ} (h : times_cont_diff ℝ n f) : times_cont_diff ℝ n fun (x : E) => real.sin (f x) := times_cont_diff.comp real.times_cont_diff_sin h theorem times_cont_diff_at.sin {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {x : E} {n : with_top ℕ} (hf : times_cont_diff_at ℝ n f x) : times_cont_diff_at ℝ n (fun (x : E) => real.sin (f x)) x := times_cont_diff_at.comp x (times_cont_diff.times_cont_diff_at real.times_cont_diff_sin) hf theorem times_cont_diff_on.sin {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {s : set E} {n : with_top ℕ} (hf : times_cont_diff_on ℝ n f s) : times_cont_diff_on ℝ n (fun (x : E) => real.sin (f x)) s := times_cont_diff.comp_times_cont_diff_on real.times_cont_diff_sin hf theorem times_cont_diff_within_at.sin {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {x : E} {s : set E} {n : with_top ℕ} (hf : times_cont_diff_within_at ℝ n f s x) : times_cont_diff_within_at ℝ n (fun (x : E) => real.sin (f x)) s x := times_cont_diff_at.comp_times_cont_diff_within_at x (times_cont_diff.times_cont_diff_at real.times_cont_diff_sin) hf /-! #### `real.cosh` -/ theorem has_fderiv_at.cosh {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {f' : continuous_linear_map ℝ E ℝ} {x : E} (hf : has_fderiv_at f f' x) : has_fderiv_at (fun (x : E) => real.cosh (f x)) (real.sinh (f x) • f') x := has_deriv_at.comp_has_fderiv_at x (real.has_deriv_at_cosh (f x)) hf theorem has_fderiv_within_at.cosh {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {f' : continuous_linear_map ℝ E ℝ} {x : E} {s : set E} (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (fun (x : E) => real.cosh (f x)) (real.sinh (f x) • f') s x := has_deriv_at.comp_has_fderiv_within_at x (real.has_deriv_at_cosh (f x)) hf theorem differentiable_within_at.cosh {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {x : E} {s : set E} (hf : differentiable_within_at ℝ f s x) : differentiable_within_at ℝ (fun (x : E) => real.cosh (f x)) s x := has_fderiv_within_at.differentiable_within_at (has_fderiv_within_at.cosh (differentiable_within_at.has_fderiv_within_at hf)) @[simp] theorem differentiable_at.cosh {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {x : E} (hc : differentiable_at ℝ f x) : differentiable_at ℝ (fun (x : E) => real.cosh (f x)) x := has_fderiv_at.differentiable_at (has_fderiv_at.cosh (differentiable_at.has_fderiv_at hc)) theorem differentiable_on.cosh {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {s : set E} (hc : differentiable_on ℝ f s) : differentiable_on ℝ (fun (x : E) => real.cosh (f x)) s := fun (x : E) (h : x ∈ s) => differentiable_within_at.cosh (hc x h) @[simp] theorem differentiable.cosh {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} (hc : differentiable ℝ f) : differentiable ℝ fun (x : E) => real.cosh (f x) := fun (x : E) => differentiable_at.cosh (hc x) theorem fderiv_within_cosh {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {x : E} {s : set E} (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : fderiv_within ℝ (fun (x : E) => real.cosh (f x)) s x = real.sinh (f x) • fderiv_within ℝ f s x := has_fderiv_within_at.fderiv_within (has_fderiv_within_at.cosh (differentiable_within_at.has_fderiv_within_at hf)) hxs @[simp] theorem fderiv_cosh {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {x : E} (hc : differentiable_at ℝ f x) : fderiv ℝ (fun (x : E) => real.cosh (f x)) x = real.sinh (f x) • fderiv ℝ f x := has_fderiv_at.fderiv (has_fderiv_at.cosh (differentiable_at.has_fderiv_at hc)) theorem times_cont_diff.cosh {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {n : with_top ℕ} (h : times_cont_diff ℝ n f) : times_cont_diff ℝ n fun (x : E) => real.cosh (f x) := times_cont_diff.comp real.times_cont_diff_cosh h theorem times_cont_diff_at.cosh {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {x : E} {n : with_top ℕ} (hf : times_cont_diff_at ℝ n f x) : times_cont_diff_at ℝ n (fun (x : E) => real.cosh (f x)) x := times_cont_diff_at.comp x (times_cont_diff.times_cont_diff_at real.times_cont_diff_cosh) hf theorem times_cont_diff_on.cosh {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {s : set E} {n : with_top ℕ} (hf : times_cont_diff_on ℝ n f s) : times_cont_diff_on ℝ n (fun (x : E) => real.cosh (f x)) s := times_cont_diff.comp_times_cont_diff_on real.times_cont_diff_cosh hf theorem times_cont_diff_within_at.cosh {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {x : E} {s : set E} {n : with_top ℕ} (hf : times_cont_diff_within_at ℝ n f s x) : times_cont_diff_within_at ℝ n (fun (x : E) => real.cosh (f x)) s x := times_cont_diff_at.comp_times_cont_diff_within_at x (times_cont_diff.times_cont_diff_at real.times_cont_diff_cosh) hf /-! #### `real.sinh` -/ theorem has_fderiv_at.sinh {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {f' : continuous_linear_map ℝ E ℝ} {x : E} (hf : has_fderiv_at f f' x) : has_fderiv_at (fun (x : E) => real.sinh (f x)) (real.cosh (f x) • f') x := has_deriv_at.comp_has_fderiv_at x (real.has_deriv_at_sinh (f x)) hf theorem has_fderiv_within_at.sinh {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {f' : continuous_linear_map ℝ E ℝ} {x : E} {s : set E} (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (fun (x : E) => real.sinh (f x)) (real.cosh (f x) • f') s x := has_deriv_at.comp_has_fderiv_within_at x (real.has_deriv_at_sinh (f x)) hf theorem differentiable_within_at.sinh {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {x : E} {s : set E} (hf : differentiable_within_at ℝ f s x) : differentiable_within_at ℝ (fun (x : E) => real.sinh (f x)) s x := has_fderiv_within_at.differentiable_within_at (has_fderiv_within_at.sinh (differentiable_within_at.has_fderiv_within_at hf)) @[simp] theorem differentiable_at.sinh {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {x : E} (hc : differentiable_at ℝ f x) : differentiable_at ℝ (fun (x : E) => real.sinh (f x)) x := has_fderiv_at.differentiable_at (has_fderiv_at.sinh (differentiable_at.has_fderiv_at hc)) theorem differentiable_on.sinh {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {s : set E} (hc : differentiable_on ℝ f s) : differentiable_on ℝ (fun (x : E) => real.sinh (f x)) s := fun (x : E) (h : x ∈ s) => differentiable_within_at.sinh (hc x h) @[simp] theorem differentiable.sinh {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} (hc : differentiable ℝ f) : differentiable ℝ fun (x : E) => real.sinh (f x) := fun (x : E) => differentiable_at.sinh (hc x) theorem fderiv_within_sinh {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {x : E} {s : set E} (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : fderiv_within ℝ (fun (x : E) => real.sinh (f x)) s x = real.cosh (f x) • fderiv_within ℝ f s x := has_fderiv_within_at.fderiv_within (has_fderiv_within_at.sinh (differentiable_within_at.has_fderiv_within_at hf)) hxs @[simp] theorem fderiv_sinh {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {x : E} (hc : differentiable_at ℝ f x) : fderiv ℝ (fun (x : E) => real.sinh (f x)) x = real.cosh (f x) • fderiv ℝ f x := has_fderiv_at.fderiv (has_fderiv_at.sinh (differentiable_at.has_fderiv_at hc)) theorem times_cont_diff.sinh {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {n : with_top ℕ} (h : times_cont_diff ℝ n f) : times_cont_diff ℝ n fun (x : E) => real.sinh (f x) := times_cont_diff.comp real.times_cont_diff_sinh h theorem times_cont_diff_at.sinh {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {x : E} {n : with_top ℕ} (hf : times_cont_diff_at ℝ n f x) : times_cont_diff_at ℝ n (fun (x : E) => real.sinh (f x)) x := times_cont_diff_at.comp x (times_cont_diff.times_cont_diff_at real.times_cont_diff_sinh) hf theorem times_cont_diff_on.sinh {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {s : set E} {n : with_top ℕ} (hf : times_cont_diff_on ℝ n f s) : times_cont_diff_on ℝ n (fun (x : E) => real.sinh (f x)) s := times_cont_diff.comp_times_cont_diff_on real.times_cont_diff_sinh hf theorem times_cont_diff_within_at.sinh {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {x : E} {s : set E} {n : with_top ℕ} (hf : times_cont_diff_within_at ℝ n f s x) : times_cont_diff_within_at ℝ n (fun (x : E) => real.sinh (f x)) s x := times_cont_diff_at.comp_times_cont_diff_within_at x (times_cont_diff.times_cont_diff_at real.times_cont_diff_sinh) hf namespace real theorem exists_cos_eq_zero : 0 ∈ cos '' set.Icc 1 (bit0 1) := intermediate_value_Icc' (eq.mpr (id (eq_true_intro (norm_num.le_one_bit0 1 (le_refl 1)))) trivial) continuous_on_cos { left := le_of_lt cos_two_neg, right := le_of_lt cos_one_pos } /-- The number π = 3.14159265... Defined here using choice as twice a zero of cos in [1,2], from which one can derive all its properties. For explicit bounds on π, see `data.real.pi`. -/ def pi : ℝ := bit0 1 * classical.some exists_cos_eq_zero @[simp] theorem cos_pi_div_two : cos (pi / bit0 1) = 0 := sorry theorem one_le_pi_div_two : 1 ≤ pi / bit0 1 := sorry theorem pi_div_two_le_two : pi / bit0 1 ≤ bit0 1 := sorry theorem two_le_pi : bit0 1 ≤ pi := iff.mp (div_le_div_right ((fun (this : 0 < bit0 1) => this) (eq.mpr (id (eq_true_intro (bit0_pos zero_lt_one'))) trivial))) (eq.mpr (id (Eq._oldrec (Eq.refl (bit0 1 / bit0 1 ≤ pi / bit0 1)) (div_self two_ne_zero'))) one_le_pi_div_two) theorem pi_le_four : pi ≤ bit0 (bit0 1) := sorry theorem pi_pos : 0 < pi := lt_of_lt_of_le (eq.mpr (id (eq_true_intro (bit0_pos zero_lt_one'))) trivial) two_le_pi theorem pi_ne_zero : pi ≠ 0 := ne_of_gt pi_pos theorem pi_div_two_pos : 0 < pi / bit0 1 := half_pos pi_pos theorem two_pi_pos : 0 < bit0 1 * pi := sorry @[simp] theorem sin_pi : sin pi = 0 := sorry @[simp] theorem cos_pi : cos pi = -1 := sorry @[simp] theorem sin_two_pi : sin (bit0 1 * pi) = 0 := sorry @[simp] theorem cos_two_pi : cos (bit0 1 * pi) = 1 := sorry theorem sin_add_pi (x : ℝ) : sin (x + pi) = -sin x := sorry theorem sin_add_two_pi (x : ℝ) : sin (x + bit0 1 * pi) = sin x := sorry theorem cos_add_two_pi (x : ℝ) : cos (x + bit0 1 * pi) = cos x := sorry theorem sin_pi_sub (x : ℝ) : sin (pi - x) = sin x := sorry theorem cos_add_pi (x : ℝ) : cos (x + pi) = -cos x := sorry theorem cos_pi_sub (x : ℝ) : cos (pi - x) = -cos x := sorry theorem sin_pos_of_pos_of_lt_pi {x : ℝ} (h0x : 0 < x) (hxp : x < pi) : 0 < sin x := sorry theorem sin_pos_of_mem_Ioo {x : ℝ} (hx : x ∈ set.Ioo 0 pi) : 0 < sin x := sin_pos_of_pos_of_lt_pi (and.left hx) (and.right hx) theorem sin_nonneg_of_mem_Icc {x : ℝ} (hx : x ∈ set.Icc 0 pi) : 0 ≤ sin x := closure_lt_subset_le continuous_const continuous_sin (closure_mono (fun (y : ℝ) => sin_pos_of_mem_Ioo) (eq.mp (Eq._oldrec (Eq.refl (x ∈ set.Icc 0 pi)) (Eq.symm (closure_Ioo pi_pos))) hx)) theorem sin_nonneg_of_nonneg_of_le_pi {x : ℝ} (h0x : 0 ≤ x) (hxp : x ≤ pi) : 0 ≤ sin x := sin_nonneg_of_mem_Icc { left := h0x, right := hxp } theorem sin_neg_of_neg_of_neg_pi_lt {x : ℝ} (hx0 : x < 0) (hpx : -pi < x) : sin x < 0 := iff.mp neg_pos (sin_neg x ▸ sin_pos_of_pos_of_lt_pi (iff.mpr neg_pos hx0) (iff.mp neg_lt hpx)) theorem sin_nonpos_of_nonnpos_of_neg_pi_le {x : ℝ} (hx0 : x ≤ 0) (hpx : -pi ≤ x) : sin x ≤ 0 := iff.mp neg_nonneg (sin_neg x ▸ sin_nonneg_of_nonneg_of_le_pi (iff.mpr neg_nonneg hx0) (iff.mp neg_le hpx)) @[simp] theorem sin_pi_div_two : sin (pi / bit0 1) = 1 := sorry theorem sin_add_pi_div_two (x : ℝ) : sin (x + pi / bit0 1) = cos x := sorry theorem sin_sub_pi_div_two (x : ℝ) : sin (x - pi / bit0 1) = -cos x := sorry theorem sin_pi_div_two_sub (x : ℝ) : sin (pi / bit0 1 - x) = cos x := sorry theorem cos_add_pi_div_two (x : ℝ) : cos (x + pi / bit0 1) = -sin x := sorry theorem cos_sub_pi_div_two (x : ℝ) : cos (x - pi / bit0 1) = sin x := sorry theorem cos_pi_div_two_sub (x : ℝ) : cos (pi / bit0 1 - x) = sin x := eq.mpr (id (Eq._oldrec (Eq.refl (cos (pi / bit0 1 - x) = sin x)) (Eq.symm (cos_neg (pi / bit0 1 - x))))) (eq.mpr (id (Eq._oldrec (Eq.refl (cos (-(pi / bit0 1 - x)) = sin x)) (neg_sub (pi / bit0 1) x))) (eq.mpr (id (Eq._oldrec (Eq.refl (cos (x - pi / bit0 1) = sin x)) (cos_sub_pi_div_two x))) (Eq.refl (sin x)))) theorem cos_pos_of_mem_Ioo {x : ℝ} (hx : x ∈ set.Ioo (-(pi / bit0 1)) (pi / bit0 1)) : 0 < cos x := sorry theorem cos_nonneg_of_mem_Icc {x : ℝ} (hx : x ∈ set.Icc (-(pi / bit0 1)) (pi / bit0 1)) : 0 ≤ cos x := sorry theorem cos_neg_of_pi_div_two_lt_of_lt {x : ℝ} (hx₁ : pi / bit0 1 < x) (hx₂ : x < pi + pi / bit0 1) : cos x < 0 := sorry theorem cos_nonpos_of_pi_div_two_le_of_le {x : ℝ} (hx₁ : pi / bit0 1 ≤ x) (hx₂ : x ≤ pi + pi / bit0 1) : cos x ≤ 0 := sorry theorem sin_nat_mul_pi (n : ℕ) : sin (↑n * pi) = 0 := sorry theorem sin_int_mul_pi (n : ℤ) : sin (↑n * pi) = 0 := sorry theorem cos_nat_mul_two_pi (n : ℕ) : cos (↑n * (bit0 1 * pi)) = 1 := sorry theorem cos_int_mul_two_pi (n : ℤ) : cos (↑n * (bit0 1 * pi)) = 1 := sorry theorem cos_int_mul_two_pi_add_pi (n : ℤ) : cos (↑n * (bit0 1 * pi) + pi) = -1 := sorry theorem sin_eq_zero_iff_of_lt_of_lt {x : ℝ} (hx₁ : -pi < x) (hx₂ : x < pi) : sin x = 0 ↔ x = 0 := sorry theorem sin_eq_zero_iff {x : ℝ} : sin x = 0 ↔ ∃ (n : ℤ), ↑n * pi = x := sorry theorem sin_ne_zero_iff {x : ℝ} : sin x ≠ 0 ↔ ∀ (n : ℤ), ↑n * pi ≠ x := sorry theorem sin_eq_zero_iff_cos_eq {x : ℝ} : sin x = 0 ↔ cos x = 1 ∨ cos x = -1 := sorry theorem cos_eq_one_iff (x : ℝ) : cos x = 1 ↔ ∃ (n : ℤ), ↑n * (bit0 1 * pi) = x := sorry theorem cos_eq_one_iff_of_lt_of_lt {x : ℝ} (hx₁ : -(bit0 1 * pi) < x) (hx₂ : x < bit0 1 * pi) : cos x = 1 ↔ x = 0 := sorry theorem cos_lt_cos_of_nonneg_of_le_pi_div_two {x : ℝ} {y : ℝ} (hx₁ : 0 ≤ x) (hy₂ : y ≤ pi / bit0 1) (hxy : x < y) : cos y < cos x := sorry theorem cos_lt_cos_of_nonneg_of_le_pi {x : ℝ} {y : ℝ} (hx₁ : 0 ≤ x) (hy₂ : y ≤ pi) (hxy : x < y) : cos y < cos x := sorry theorem strict_mono_decr_on_cos : strict_mono_decr_on cos (set.Icc 0 pi) := fun (x : ℝ) (hx : x ∈ set.Icc 0 pi) (y : ℝ) (hy : y ∈ set.Icc 0 pi) (hxy : x < y) => cos_lt_cos_of_nonneg_of_le_pi (and.left hx) (and.right hy) hxy theorem cos_le_cos_of_nonneg_of_le_pi {x : ℝ} {y : ℝ} (hx₁ : 0 ≤ x) (hy₂ : y ≤ pi) (hxy : x ≤ y) : cos y ≤ cos x := sorry theorem sin_lt_sin_of_lt_of_le_pi_div_two {x : ℝ} {y : ℝ} (hx₁ : -(pi / bit0 1) ≤ x) (hy₂ : y ≤ pi / bit0 1) (hxy : x < y) : sin x < sin y := sorry theorem strict_mono_incr_on_sin : strict_mono_incr_on sin (set.Icc (-(pi / bit0 1)) (pi / bit0 1)) := fun (x : ℝ) (hx : x ∈ set.Icc (-(pi / bit0 1)) (pi / bit0 1)) (y : ℝ) (hy : y ∈ set.Icc (-(pi / bit0 1)) (pi / bit0 1)) (hxy : x < y) => sin_lt_sin_of_lt_of_le_pi_div_two (and.left hx) (and.right hy) hxy theorem sin_le_sin_of_le_of_le_pi_div_two {x : ℝ} {y : ℝ} (hx₁ : -(pi / bit0 1) ≤ x) (hy₂ : y ≤ pi / bit0 1) (hxy : x ≤ y) : sin x ≤ sin y := sorry theorem inj_on_sin : set.inj_on sin (set.Icc (-(pi / bit0 1)) (pi / bit0 1)) := strict_mono_incr_on.inj_on strict_mono_incr_on_sin theorem inj_on_cos : set.inj_on cos (set.Icc 0 pi) := strict_mono_decr_on.inj_on strict_mono_decr_on_cos theorem surj_on_sin : set.surj_on sin (set.Icc (-(pi / bit0 1)) (pi / bit0 1)) (set.Icc (-1) 1) := sorry theorem surj_on_cos : set.surj_on cos (set.Icc 0 pi) (set.Icc (-1) 1) := sorry theorem sin_mem_Icc (x : ℝ) : sin x ∈ set.Icc (-1) 1 := { left := neg_one_le_sin x, right := sin_le_one x } theorem cos_mem_Icc (x : ℝ) : cos x ∈ set.Icc (-1) 1 := { left := neg_one_le_cos x, right := cos_le_one x } theorem maps_to_sin (s : set ℝ) : set.maps_to sin s (set.Icc (-1) 1) := fun (x : ℝ) (_x : x ∈ s) => sin_mem_Icc x theorem maps_to_cos (s : set ℝ) : set.maps_to cos s (set.Icc (-1) 1) := fun (x : ℝ) (_x : x ∈ s) => cos_mem_Icc x theorem bij_on_sin : set.bij_on sin (set.Icc (-(pi / bit0 1)) (pi / bit0 1)) (set.Icc (-1) 1) := { left := maps_to_sin (set.Icc (-(pi / bit0 1)) (pi / bit0 1)), right := { left := inj_on_sin, right := surj_on_sin } } theorem bij_on_cos : set.bij_on cos (set.Icc 0 pi) (set.Icc (-1) 1) := { left := maps_to_cos (set.Icc 0 pi), right := { left := inj_on_cos, right := surj_on_cos } } @[simp] theorem range_cos : set.range cos = set.Icc (-1) 1 := set.subset.antisymm (iff.mpr set.range_subset_iff cos_mem_Icc) (set.surj_on.subset_range surj_on_cos) @[simp] theorem range_sin : set.range sin = set.Icc (-1) 1 := set.subset.antisymm (iff.mpr set.range_subset_iff sin_mem_Icc) (set.surj_on.subset_range surj_on_sin) theorem range_cos_infinite : set.infinite (set.range cos) := eq.mpr (id (Eq._oldrec (Eq.refl (set.infinite (set.range cos))) range_cos)) (set.Icc.infinite (eq.mpr (id (eq_true_intro (norm_num.lt_neg_pos 1 1 zero_lt_one' zero_lt_one'))) trivial)) theorem range_sin_infinite : set.infinite (set.range sin) := eq.mpr (id (Eq._oldrec (Eq.refl (set.infinite (set.range sin))) range_sin)) (set.Icc.infinite (eq.mpr (id (eq_true_intro (norm_num.lt_neg_pos 1 1 zero_lt_one' zero_lt_one'))) trivial)) theorem sin_lt {x : ℝ} (h : 0 < x) : sin x < x := sorry /- note 1: this inequality is not tight, the tighter inequality is sin x > x - x ^ 3 / 6. note 2: this is also true for x > 1, but it's nontrivial for x just above 1. -/ theorem sin_gt_sub_cube {x : ℝ} (h : 0 < x) (h' : x ≤ 1) : x - x ^ bit1 1 / bit0 (bit0 1) < sin x := sorry /-- the series `sqrt_two_add_series x n` is `sqrt(2 + sqrt(2 + ... ))` with `n` square roots, starting with `x`. We define it here because `cos (pi / 2 ^ (n+1)) = sqrt_two_add_series 0 n / 2` -/ @[simp] def sqrt_two_add_series (x : ℝ) : ℕ → ℝ := sorry theorem sqrt_two_add_series_zero (x : ℝ) : sqrt_two_add_series x 0 = x := sorry theorem sqrt_two_add_series_one : sqrt_two_add_series 0 1 = sqrt (bit0 1) := sorry theorem sqrt_two_add_series_two : sqrt_two_add_series 0 (bit0 1) = sqrt (bit0 1 + sqrt (bit0 1)) := sorry theorem sqrt_two_add_series_zero_nonneg (n : ℕ) : 0 ≤ sqrt_two_add_series 0 n := sorry theorem sqrt_two_add_series_nonneg {x : ℝ} (h : 0 ≤ x) (n : ℕ) : 0 ≤ sqrt_two_add_series x n := sorry theorem sqrt_two_add_series_lt_two (n : ℕ) : sqrt_two_add_series 0 n < bit0 1 := sorry theorem sqrt_two_add_series_succ (x : ℝ) (n : ℕ) : sqrt_two_add_series x (n + 1) = sqrt_two_add_series (sqrt (bit0 1 + x)) n := sorry theorem sqrt_two_add_series_monotone_left {x : ℝ} {y : ℝ} (h : x ≤ y) (n : ℕ) : sqrt_two_add_series x n ≤ sqrt_two_add_series y n := sorry @[simp] theorem cos_pi_over_two_pow (n : ℕ) : cos (pi / bit0 1 ^ (n + 1)) = sqrt_two_add_series 0 n / bit0 1 := sorry theorem sin_square_pi_over_two_pow (n : ℕ) : sin (pi / bit0 1 ^ (n + 1)) ^ bit0 1 = 1 - (sqrt_two_add_series 0 n / bit0 1) ^ bit0 1 := sorry theorem sin_square_pi_over_two_pow_succ (n : ℕ) : sin (pi / bit0 1 ^ (n + bit0 1)) ^ bit0 1 = 1 / bit0 1 - sqrt_two_add_series 0 n / bit0 (bit0 1) := sorry @[simp] theorem sin_pi_over_two_pow_succ (n : ℕ) : sin (pi / bit0 1 ^ (n + bit0 1)) = sqrt (bit0 1 - sqrt_two_add_series 0 n) / bit0 1 := sorry @[simp] theorem cos_pi_div_four : cos (pi / bit0 (bit0 1)) = sqrt (bit0 1) / bit0 1 := sorry @[simp] theorem sin_pi_div_four : sin (pi / bit0 (bit0 1)) = sqrt (bit0 1) / bit0 1 := sorry @[simp] theorem cos_pi_div_eight : cos (pi / bit0 (bit0 (bit0 1))) = sqrt (bit0 1 + sqrt (bit0 1)) / bit0 1 := sorry @[simp] theorem sin_pi_div_eight : sin (pi / bit0 (bit0 (bit0 1))) = sqrt (bit0 1 - sqrt (bit0 1)) / bit0 1 := sorry @[simp] theorem cos_pi_div_sixteen : cos (pi / bit0 (bit0 (bit0 (bit0 1)))) = sqrt (bit0 1 + sqrt (bit0 1 + sqrt (bit0 1))) / bit0 1 := sorry @[simp] theorem sin_pi_div_sixteen : sin (pi / bit0 (bit0 (bit0 (bit0 1)))) = sqrt (bit0 1 - sqrt (bit0 1 + sqrt (bit0 1))) / bit0 1 := sorry @[simp] theorem cos_pi_div_thirty_two : cos (pi / bit0 (bit0 (bit0 (bit0 (bit0 1))))) = sqrt (bit0 1 + sqrt (bit0 1 + sqrt (bit0 1 + sqrt (bit0 1)))) / bit0 1 := sorry @[simp] theorem sin_pi_div_thirty_two : sin (pi / bit0 (bit0 (bit0 (bit0 (bit0 1))))) = sqrt (bit0 1 - sqrt (bit0 1 + sqrt (bit0 1 + sqrt (bit0 1)))) / bit0 1 := sorry -- This section is also a convenient location for other explicit values of `sin` and `cos`. /-- The cosine of `π / 3` is `1 / 2`. -/ @[simp] theorem cos_pi_div_three : cos (pi / bit1 1) = 1 / bit0 1 := sorry /-- The square of the cosine of `π / 6` is `3 / 4` (this is sometimes more convenient than the result for cosine itself). -/ theorem square_cos_pi_div_six : cos (pi / bit0 (bit1 1)) ^ bit0 1 = bit1 1 / bit0 (bit0 1) := sorry /-- The cosine of `π / 6` is `√3 / 2`. -/ @[simp] theorem cos_pi_div_six : cos (pi / bit0 (bit1 1)) = sqrt (bit1 1) / bit0 1 := sorry /-- The sine of `π / 6` is `1 / 2`. -/ @[simp] theorem sin_pi_div_six : sin (pi / bit0 (bit1 1)) = 1 / bit0 1 := sorry /-- The square of the sine of `π / 3` is `3 / 4` (this is sometimes more convenient than the result for cosine itself). -/ theorem square_sin_pi_div_three : sin (pi / bit1 1) ^ bit0 1 = bit1 1 / bit0 (bit0 1) := sorry /-- The sine of `π / 3` is `√3 / 2`. -/ @[simp] theorem sin_pi_div_three : sin (pi / bit1 1) = sqrt (bit1 1) / bit0 1 := sorry /-- The type of angles -/ def angle := quotient_add_group.quotient (add_subgroup.gmultiples (bit0 1 * pi)) namespace angle protected instance angle.add_comm_group : add_comm_group angle := quotient_add_group.add_comm_group (add_subgroup.gmultiples (bit0 1 * pi)) protected instance inhabited : Inhabited angle := { default := 0 } protected instance angle.has_coe : has_coe ℝ angle := has_coe.mk quotient.mk' @[simp] theorem coe_zero : ↑0 = 0 := rfl @[simp] theorem coe_add (x : ℝ) (y : ℝ) : ↑(x + y) = ↑x + ↑y := rfl @[simp] theorem coe_neg (x : ℝ) : ↑(-x) = -↑x := rfl @[simp] theorem coe_sub (x : ℝ) (y : ℝ) : ↑(x - y) = ↑x - ↑y := sorry @[simp] theorem coe_nat_mul_eq_nsmul (x : ℝ) (n : ℕ) : ↑(↑n * x) = n •ℕ ↑x := sorry @[simp] theorem coe_int_mul_eq_gsmul (x : ℝ) (n : ℤ) : ↑(↑n * x) = n •ℤ ↑x := sorry @[simp] theorem coe_two_pi : ↑(bit0 1 * pi) = 0 := sorry theorem angle_eq_iff_two_pi_dvd_sub {ψ : ℝ} {θ : ℝ} : ↑θ = ↑ψ ↔ ∃ (k : ℤ), θ - ψ = bit0 1 * pi * ↑k := sorry theorem cos_eq_iff_eq_or_eq_neg {θ : ℝ} {ψ : ℝ} : cos θ = cos ψ ↔ ↑θ = ↑ψ ∨ ↑θ = -↑ψ := sorry theorem sin_eq_iff_eq_or_add_eq_pi {θ : ℝ} {ψ : ℝ} : sin θ = sin ψ ↔ ↑θ = ↑ψ ∨ ↑θ + ↑ψ = ↑pi := sorry theorem cos_sin_inj {θ : ℝ} {ψ : ℝ} (Hcos : cos θ = cos ψ) (Hsin : sin θ = sin ψ) : ↑θ = ↑ψ := sorry end angle /-- `real.sin` as an `order_iso` between `[-(π / 2), π / 2]` and `[-1, 1]`. -/ def sin_order_iso : ↥(set.Icc (-(pi / bit0 1)) (pi / bit0 1)) ≃o ↥(set.Icc (-1) 1) := order_iso.trans (strict_mono_incr_on.order_iso sin (set.Icc (-(pi / bit0 1)) (pi / bit0 1)) strict_mono_incr_on_sin) (order_iso.set_congr (sin '' set.Icc (-(pi / bit0 1)) (pi / bit0 1)) (set.Icc (-1) 1) sorry) @[simp] theorem coe_sin_order_iso_apply (x : ↥(set.Icc (-(pi / bit0 1)) (pi / bit0 1))) : ↑(coe_fn sin_order_iso x) = sin ↑x := rfl theorem sin_order_iso_apply (x : ↥(set.Icc (-(pi / bit0 1)) (pi / bit0 1))) : coe_fn sin_order_iso x = { val := sin ↑x, property := sin_mem_Icc ↑x } := rfl /-- Inverse of the `sin` function, returns values in the range `-π / 2 ≤ arcsin x ≤ π / 2`. It defaults to `-π / 2` on `(-∞, -1)` and to `π / 2` to `(1, ∞)`. -/ def arcsin : ℝ → ℝ := coe ∘ set.Icc_extend sorry ⇑(order_iso.symm sin_order_iso) theorem arcsin_mem_Icc (x : ℝ) : arcsin x ∈ set.Icc (-(pi / bit0 1)) (pi / bit0 1) := subtype.coe_prop (set.Icc_extend arcsin._proof_1 (⇑(order_iso.symm sin_order_iso)) x) @[simp] theorem range_arcsin : set.range arcsin = set.Icc (-(pi / bit0 1)) (pi / bit0 1) := sorry theorem arcsin_le_pi_div_two (x : ℝ) : arcsin x ≤ pi / bit0 1 := and.right (arcsin_mem_Icc x) theorem neg_pi_div_two_le_arcsin (x : ℝ) : -(pi / bit0 1) ≤ arcsin x := and.left (arcsin_mem_Icc x) theorem arcsin_proj_Icc (x : ℝ) : arcsin ↑(set.proj_Icc (-1) 1 (neg_le_self zero_le_one) x) = arcsin x := sorry theorem sin_arcsin' {x : ℝ} (hx : x ∈ set.Icc (-1) 1) : sin (arcsin x) = x := sorry theorem sin_arcsin {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : sin (arcsin x) = x := sin_arcsin' { left := hx₁, right := hx₂ } theorem arcsin_sin' {x : ℝ} (hx : x ∈ set.Icc (-(pi / bit0 1)) (pi / bit0 1)) : arcsin (sin x) = x := inj_on_sin (arcsin_mem_Icc (sin x)) hx (eq.mpr (id (Eq._oldrec (Eq.refl (sin (arcsin (sin x)) = sin x)) (sin_arcsin (neg_one_le_sin x) (sin_le_one x)))) (Eq.refl (sin x))) theorem arcsin_sin {x : ℝ} (hx₁ : -(pi / bit0 1) ≤ x) (hx₂ : x ≤ pi / bit0 1) : arcsin (sin x) = x := arcsin_sin' { left := hx₁, right := hx₂ } theorem strict_mono_incr_on_arcsin : strict_mono_incr_on arcsin (set.Icc (-1) 1) := strict_mono.comp_strict_mono_incr_on (subtype.strict_mono_coe fun (x : ℝ) => x ∈ set.Icc (-(pi / bit0 1)) (pi / bit0 1)) (strict_mono.strict_mono_incr_on_Icc_extend arcsin._proof_1 (order_iso.strict_mono (order_iso.symm sin_order_iso))) theorem monotone_arcsin : monotone arcsin := monotone.comp (subtype.mono_coe fun (x : ℝ) => x ∈ set.Icc (-(pi / bit0 1)) (pi / bit0 1)) (monotone.Icc_extend arcsin._proof_1 (order_iso.monotone (order_iso.symm sin_order_iso))) theorem inj_on_arcsin : set.inj_on arcsin (set.Icc (-1) 1) := strict_mono_incr_on.inj_on strict_mono_incr_on_arcsin theorem arcsin_inj {x : ℝ} {y : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) (hy₁ : -1 ≤ y) (hy₂ : y ≤ 1) : arcsin x = arcsin y ↔ x = y := set.inj_on.eq_iff inj_on_arcsin { left := hx₁, right := hx₂ } { left := hy₁, right := hy₂ } theorem continuous_arcsin : continuous arcsin := continuous.comp continuous_subtype_coe (continuous.Icc_extend (order_iso.continuous (order_iso.symm sin_order_iso))) theorem continuous_at_arcsin {x : ℝ} : continuous_at arcsin x := continuous.continuous_at continuous_arcsin theorem arcsin_eq_of_sin_eq {x : ℝ} {y : ℝ} (h₁ : sin x = y) (h₂ : x ∈ set.Icc (-(pi / bit0 1)) (pi / bit0 1)) : arcsin y = x := Eq._oldrec (inj_on_sin (arcsin_mem_Icc (sin x)) h₂ (sin_arcsin' (sin_mem_Icc x))) h₁ @[simp] theorem arcsin_zero : arcsin 0 = 0 := arcsin_eq_of_sin_eq sin_zero { left := iff.mpr neg_nonpos (has_lt.lt.le pi_div_two_pos), right := has_lt.lt.le pi_div_two_pos } @[simp] theorem arcsin_one : arcsin 1 = pi / bit0 1 := arcsin_eq_of_sin_eq sin_pi_div_two (iff.mpr set.right_mem_Icc (neg_le_self (has_lt.lt.le pi_div_two_pos))) theorem arcsin_of_one_le {x : ℝ} (hx : 1 ≤ x) : arcsin x = pi / bit0 1 := sorry theorem arcsin_neg_one : arcsin (-1) = -(pi / bit0 1) := sorry theorem arcsin_of_le_neg_one {x : ℝ} (hx : x ≤ -1) : arcsin x = -(pi / bit0 1) := sorry @[simp] theorem arcsin_neg (x : ℝ) : arcsin (-x) = -arcsin x := sorry theorem arcsin_le_iff_le_sin {x : ℝ} {y : ℝ} (hx : x ∈ set.Icc (-1) 1) (hy : y ∈ set.Icc (-(pi / bit0 1)) (pi / bit0 1)) : arcsin x ≤ y ↔ x ≤ sin y := sorry theorem arcsin_le_iff_le_sin' {x : ℝ} {y : ℝ} (hy : y ∈ set.Ico (-(pi / bit0 1)) (pi / bit0 1)) : arcsin x ≤ y ↔ x ≤ sin y := sorry theorem le_arcsin_iff_sin_le {x : ℝ} {y : ℝ} (hx : x ∈ set.Icc (-(pi / bit0 1)) (pi / bit0 1)) (hy : y ∈ set.Icc (-1) 1) : x ≤ arcsin y ↔ sin x ≤ y := sorry theorem le_arcsin_iff_sin_le' {x : ℝ} {y : ℝ} (hx : x ∈ set.Ioc (-(pi / bit0 1)) (pi / bit0 1)) : x ≤ arcsin y ↔ sin x ≤ y := sorry theorem arcsin_lt_iff_lt_sin {x : ℝ} {y : ℝ} (hx : x ∈ set.Icc (-1) 1) (hy : y ∈ set.Icc (-(pi / bit0 1)) (pi / bit0 1)) : arcsin x < y ↔ x < sin y := iff.trans (iff.symm not_le) (iff.trans (not_congr (le_arcsin_iff_sin_le hy hx)) not_le) theorem arcsin_lt_iff_lt_sin' {x : ℝ} {y : ℝ} (hy : y ∈ set.Ioc (-(pi / bit0 1)) (pi / bit0 1)) : arcsin x < y ↔ x < sin y := iff.trans (iff.symm not_le) (iff.trans (not_congr (le_arcsin_iff_sin_le' hy)) not_le) theorem lt_arcsin_iff_sin_lt {x : ℝ} {y : ℝ} (hx : x ∈ set.Icc (-(pi / bit0 1)) (pi / bit0 1)) (hy : y ∈ set.Icc (-1) 1) : x < arcsin y ↔ sin x < y := iff.trans (iff.symm not_le) (iff.trans (not_congr (arcsin_le_iff_le_sin hy hx)) not_le) theorem lt_arcsin_iff_sin_lt' {x : ℝ} {y : ℝ} (hx : x ∈ set.Ico (-(pi / bit0 1)) (pi / bit0 1)) : x < arcsin y ↔ sin x < y := iff.trans (iff.symm not_le) (iff.trans (not_congr (arcsin_le_iff_le_sin' hx)) not_le) theorem arcsin_eq_iff_eq_sin {x : ℝ} {y : ℝ} (hy : y ∈ set.Ioo (-(pi / bit0 1)) (pi / bit0 1)) : arcsin x = y ↔ x = sin y := sorry @[simp] theorem arcsin_nonneg {x : ℝ} : 0 ≤ arcsin x ↔ 0 ≤ x := iff.trans (le_arcsin_iff_sin_le' { left := iff.mpr neg_lt_zero pi_div_two_pos, right := has_lt.lt.le pi_div_two_pos }) (eq.mpr (id (Eq._oldrec (Eq.refl (sin 0 ≤ x ↔ 0 ≤ x)) sin_zero)) (iff.refl (0 ≤ x))) @[simp] theorem arcsin_nonpos {x : ℝ} : arcsin x ≤ 0 ↔ x ≤ 0 := iff.trans (iff.symm neg_nonneg) (arcsin_neg x ▸ iff.trans arcsin_nonneg neg_nonneg) @[simp] theorem arcsin_eq_zero_iff {x : ℝ} : arcsin x = 0 ↔ x = 0 := sorry @[simp] theorem zero_eq_arcsin_iff {x : ℝ} : 0 = arcsin x ↔ x = 0 := iff.trans eq_comm arcsin_eq_zero_iff @[simp] theorem arcsin_pos {x : ℝ} : 0 < arcsin x ↔ 0 < x := lt_iff_lt_of_le_iff_le arcsin_nonpos @[simp] theorem arcsin_lt_zero {x : ℝ} : arcsin x < 0 ↔ x < 0 := lt_iff_lt_of_le_iff_le arcsin_nonneg @[simp] theorem arcsin_lt_pi_div_two {x : ℝ} : arcsin x < pi / bit0 1 ↔ x < 1 := iff.trans (arcsin_lt_iff_lt_sin' (iff.mpr set.right_mem_Ioc (neg_lt_self pi_div_two_pos))) (eq.mpr (id (Eq._oldrec (Eq.refl (x < sin (pi / bit0 1) ↔ x < 1)) sin_pi_div_two)) (iff.refl (x < 1))) @[simp] theorem neg_pi_div_two_lt_arcsin {x : ℝ} : -(pi / bit0 1) < arcsin x ↔ -1 < x := iff.trans (lt_arcsin_iff_sin_lt' (iff.mpr set.left_mem_Ico (neg_lt_self pi_div_two_pos))) (eq.mpr (id (Eq._oldrec (Eq.refl (sin (-(pi / bit0 1)) < x ↔ -1 < x)) (sin_neg (pi / bit0 1)))) (eq.mpr (id (Eq._oldrec (Eq.refl (-sin (pi / bit0 1) < x ↔ -1 < x)) sin_pi_div_two)) (iff.refl (-1 < x)))) @[simp] theorem arcsin_eq_pi_div_two {x : ℝ} : arcsin x = pi / bit0 1 ↔ 1 ≤ x := sorry @[simp] theorem pi_div_two_eq_arcsin {x : ℝ} : pi / bit0 1 = arcsin x ↔ 1 ≤ x := iff.trans eq_comm arcsin_eq_pi_div_two @[simp] theorem pi_div_two_le_arcsin {x : ℝ} : pi / bit0 1 ≤ arcsin x ↔ 1 ≤ x := iff.trans (has_le.le.le_iff_eq (arcsin_le_pi_div_two x)) pi_div_two_eq_arcsin @[simp] theorem arcsin_eq_neg_pi_div_two {x : ℝ} : arcsin x = -(pi / bit0 1) ↔ x ≤ -1 := sorry @[simp] theorem neg_pi_div_two_eq_arcsin {x : ℝ} : -(pi / bit0 1) = arcsin x ↔ x ≤ -1 := iff.trans eq_comm arcsin_eq_neg_pi_div_two @[simp] theorem arcsin_le_neg_pi_div_two {x : ℝ} : arcsin x ≤ -(pi / bit0 1) ↔ x ≤ -1 := iff.trans (has_le.le.le_iff_eq (neg_pi_div_two_le_arcsin x)) arcsin_eq_neg_pi_div_two theorem maps_to_sin_Ioo : set.maps_to sin (set.Ioo (-(pi / bit0 1)) (pi / bit0 1)) (set.Ioo (-1) 1) := sorry /-- `real.sin` as a `local_homeomorph` between `(-π / 2, π / 2)` and `(-1, 1)`. -/ @[simp] def sin_local_homeomorph : local_homeomorph ℝ ℝ := local_homeomorph.mk (local_equiv.mk sin arcsin (set.Ioo (-(pi / bit0 1)) (pi / bit0 1)) (set.Ioo (-1) 1) maps_to_sin_Ioo sorry sorry sorry) sorry sorry sorry sorry theorem cos_arcsin_nonneg (x : ℝ) : 0 ≤ cos (arcsin x) := cos_nonneg_of_mem_Icc { left := neg_pi_div_two_le_arcsin x, right := arcsin_le_pi_div_two x } theorem cos_arcsin {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : cos (arcsin x) = sqrt (1 - x ^ bit0 1) := sorry theorem deriv_arcsin_aux {x : ℝ} (h₁ : x ≠ -1) (h₂ : x ≠ 1) : has_deriv_at arcsin (1 / sqrt (1 - x ^ bit0 1)) x ∧ times_cont_diff_at ℝ ⊤ arcsin x := sorry theorem has_deriv_at_arcsin {x : ℝ} (h₁ : x ≠ -1) (h₂ : x ≠ 1) : has_deriv_at arcsin (1 / sqrt (1 - x ^ bit0 1)) x := and.left (deriv_arcsin_aux h₁ h₂) theorem times_cont_diff_at_arcsin {x : ℝ} (h₁ : x ≠ -1) (h₂ : x ≠ 1) {n : with_top ℕ} : times_cont_diff_at ℝ n arcsin x := times_cont_diff_at.of_le (and.right (deriv_arcsin_aux h₁ h₂)) le_top theorem has_deriv_within_at_arcsin_Ici {x : ℝ} (h : x ≠ -1) : has_deriv_within_at arcsin (1 / sqrt (1 - x ^ bit0 1)) (set.Ici x) x := sorry theorem has_deriv_within_at_arcsin_Iic {x : ℝ} (h : x ≠ 1) : has_deriv_within_at arcsin (1 / sqrt (1 - x ^ bit0 1)) (set.Iic x) x := sorry theorem differentiable_within_at_arcsin_Ici {x : ℝ} : differentiable_within_at ℝ arcsin (set.Ici x) x ↔ x ≠ -1 := sorry theorem differentiable_within_at_arcsin_Iic {x : ℝ} : differentiable_within_at ℝ arcsin (set.Iic x) x ↔ x ≠ 1 := sorry theorem differentiable_at_arcsin {x : ℝ} : differentiable_at ℝ arcsin x ↔ x ≠ -1 ∧ x ≠ 1 := sorry @[simp] theorem deriv_arcsin : deriv arcsin = fun (x : ℝ) => 1 / sqrt (1 - x ^ bit0 1) := sorry theorem differentiable_on_arcsin : differentiable_on ℝ arcsin (insert (-1) (singleton 1)ᶜ) := sorry theorem times_cont_diff_on_arcsin {n : with_top ℕ} : times_cont_diff_on ℝ n arcsin (insert (-1) (singleton 1)ᶜ) := fun (x : ℝ) (hx : x ∈ (insert (-1) (singleton 1)ᶜ)) => times_cont_diff_at.times_cont_diff_within_at (times_cont_diff_at_arcsin (mt Or.inl hx) (mt Or.inr hx)) theorem times_cont_diff_at_arcsin_iff {x : ℝ} {n : with_top ℕ} : times_cont_diff_at ℝ n arcsin x ↔ n = 0 ∨ x ≠ -1 ∧ x ≠ 1 := sorry theorem measurable_arcsin : measurable arcsin := continuous.measurable continuous_arcsin /-- Inverse of the `cos` function, returns values in the range `0 ≤ arccos x` and `arccos x ≤ π`. If the argument is not between `-1` and `1` it defaults to `π / 2` -/ def arccos (x : ℝ) : ℝ := pi / bit0 1 - arcsin x theorem arccos_eq_pi_div_two_sub_arcsin (x : ℝ) : arccos x = pi / bit0 1 - arcsin x := rfl theorem arcsin_eq_pi_div_two_sub_arccos (x : ℝ) : arcsin x = pi / bit0 1 - arccos x := sorry theorem arccos_le_pi (x : ℝ) : arccos x ≤ pi := sorry theorem arccos_nonneg (x : ℝ) : 0 ≤ arccos x := sorry theorem cos_arccos {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : cos (arccos x) = x := eq.mpr (id (Eq._oldrec (Eq.refl (cos (arccos x) = x)) (arccos.equations._eqn_1 x))) (eq.mpr (id (Eq._oldrec (Eq.refl (cos (pi / bit0 1 - arcsin x) = x)) (cos_pi_div_two_sub (arcsin x)))) (eq.mpr (id (Eq._oldrec (Eq.refl (sin (arcsin x) = x)) (sin_arcsin hx₁ hx₂))) (Eq.refl x))) theorem arccos_cos {x : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ pi) : arccos (cos x) = x := sorry theorem strict_mono_decr_on_arccos : strict_mono_decr_on arccos (set.Icc (-1) 1) := fun (x : ℝ) (hx : x ∈ set.Icc (-1) 1) (y : ℝ) (hy : y ∈ set.Icc (-1) 1) (h : x < y) => sub_lt_sub_left (strict_mono_incr_on_arcsin hx hy h) (pi / bit0 1) theorem arccos_inj_on : set.inj_on arccos (set.Icc (-1) 1) := strict_mono_decr_on.inj_on strict_mono_decr_on_arccos theorem arccos_inj {x : ℝ} {y : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) (hy₁ : -1 ≤ y) (hy₂ : y ≤ 1) : arccos x = arccos y ↔ x = y := set.inj_on.eq_iff arccos_inj_on { left := hx₁, right := hx₂ } { left := hy₁, right := hy₂ } @[simp] theorem arccos_zero : arccos 0 = pi / bit0 1 := sorry @[simp] theorem arccos_one : arccos 1 = 0 := sorry @[simp] theorem arccos_neg_one : arccos (-1) = pi := sorry @[simp] theorem arccos_eq_zero {x : ℝ} : arccos x = 0 ↔ 1 ≤ x := sorry @[simp] theorem arccos_eq_pi_div_two {x : ℝ} : arccos x = pi / bit0 1 ↔ x = 0 := sorry @[simp] theorem arccos_eq_pi {x : ℝ} : arccos x = pi ↔ x ≤ -1 := sorry theorem arccos_neg (x : ℝ) : arccos (-x) = pi - arccos x := sorry theorem sin_arccos {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : sin (arccos x) = sqrt (1 - x ^ bit0 1) := sorry theorem continuous_arccos : continuous arccos := continuous.sub continuous_const continuous_arcsin theorem has_deriv_at_arccos {x : ℝ} (h₁ : x ≠ -1) (h₂ : x ≠ 1) : has_deriv_at arccos (-(1 / sqrt (1 - x ^ bit0 1))) x := has_deriv_at.const_sub (pi / bit0 1) (has_deriv_at_arcsin h₁ h₂) theorem times_cont_diff_at_arccos {x : ℝ} (h₁ : x ≠ -1) (h₂ : x ≠ 1) {n : with_top ℕ} : times_cont_diff_at ℝ n arccos x := times_cont_diff_at.sub times_cont_diff_at_const (times_cont_diff_at_arcsin h₁ h₂) theorem has_deriv_within_at_arccos_Ici {x : ℝ} (h : x ≠ -1) : has_deriv_within_at arccos (-(1 / sqrt (1 - x ^ bit0 1))) (set.Ici x) x := has_deriv_within_at.const_sub (pi / bit0 1) (has_deriv_within_at_arcsin_Ici h) theorem has_deriv_within_at_arccos_Iic {x : ℝ} (h : x ≠ 1) : has_deriv_within_at arccos (-(1 / sqrt (1 - x ^ bit0 1))) (set.Iic x) x := has_deriv_within_at.const_sub (pi / bit0 1) (has_deriv_within_at_arcsin_Iic h) theorem differentiable_within_at_arccos_Ici {x : ℝ} : differentiable_within_at ℝ arccos (set.Ici x) x ↔ x ≠ -1 := iff.trans (differentiable_within_at_const_sub_iff (pi / bit0 1)) differentiable_within_at_arcsin_Ici theorem differentiable_within_at_arccos_Iic {x : ℝ} : differentiable_within_at ℝ arccos (set.Iic x) x ↔ x ≠ 1 := iff.trans (differentiable_within_at_const_sub_iff (pi / bit0 1)) differentiable_within_at_arcsin_Iic theorem differentiable_at_arccos {x : ℝ} : differentiable_at ℝ arccos x ↔ x ≠ -1 ∧ x ≠ 1 := iff.trans (differentiable_at_const_sub_iff (pi / bit0 1)) differentiable_at_arcsin @[simp] theorem deriv_arccos : deriv arccos = fun (x : ℝ) => -(1 / sqrt (1 - x ^ bit0 1)) := sorry theorem differentiable_on_arccos : differentiable_on ℝ arccos (insert (-1) (singleton 1)ᶜ) := differentiable_on.const_sub differentiable_on_arcsin (pi / bit0 1) theorem times_cont_diff_on_arccos {n : with_top ℕ} : times_cont_diff_on ℝ n arccos (insert (-1) (singleton 1)ᶜ) := times_cont_diff_on.sub times_cont_diff_on_const times_cont_diff_on_arcsin theorem times_cont_diff_at_arccos_iff {x : ℝ} {n : with_top ℕ} : times_cont_diff_at ℝ n arccos x ↔ n = 0 ∨ x ≠ -1 ∧ x ≠ 1 := sorry theorem measurable_arccos : measurable arccos := continuous.measurable continuous_arccos @[simp] theorem tan_pi_div_four : tan (pi / bit0 (bit0 1)) = 1 := sorry @[simp] theorem tan_pi_div_two : tan (pi / bit0 1) = 0 := sorry theorem tan_pos_of_pos_of_lt_pi_div_two {x : ℝ} (h0x : 0 < x) (hxp : x < pi / bit0 1) : 0 < tan x := sorry theorem tan_nonneg_of_nonneg_of_le_pi_div_two {x : ℝ} (h0x : 0 ≤ x) (hxp : x ≤ pi / bit0 1) : 0 ≤ tan x := sorry theorem tan_neg_of_neg_of_pi_div_two_lt {x : ℝ} (hx0 : x < 0) (hpx : -(pi / bit0 1) < x) : tan x < 0 := sorry theorem tan_nonpos_of_nonpos_of_neg_pi_div_two_le {x : ℝ} (hx0 : x ≤ 0) (hpx : -(pi / bit0 1) ≤ x) : tan x ≤ 0 := sorry theorem tan_lt_tan_of_nonneg_of_lt_pi_div_two {x : ℝ} {y : ℝ} (hx₁ : 0 ≤ x) (hy₂ : y < pi / bit0 1) (hxy : x < y) : tan x < tan y := sorry theorem tan_lt_tan_of_lt_of_lt_pi_div_two {x : ℝ} {y : ℝ} (hx₁ : -(pi / bit0 1) < x) (hy₂ : y < pi / bit0 1) (hxy : x < y) : tan x < tan y := sorry theorem strict_mono_incr_on_tan : strict_mono_incr_on tan (set.Ioo (-(pi / bit0 1)) (pi / bit0 1)) := fun (x : ℝ) (hx : x ∈ set.Ioo (-(pi / bit0 1)) (pi / bit0 1)) (y : ℝ) (hy : y ∈ set.Ioo (-(pi / bit0 1)) (pi / bit0 1)) => tan_lt_tan_of_lt_of_lt_pi_div_two (and.left hx) (and.right hy) theorem inj_on_tan : set.inj_on tan (set.Ioo (-(pi / bit0 1)) (pi / bit0 1)) := strict_mono_incr_on.inj_on strict_mono_incr_on_tan theorem tan_inj_of_lt_of_lt_pi_div_two {x : ℝ} {y : ℝ} (hx₁ : -(pi / bit0 1) < x) (hx₂ : x < pi / bit0 1) (hy₁ : -(pi / bit0 1) < y) (hy₂ : y < pi / bit0 1) (hxy : tan x = tan y) : x = y := inj_on_tan { left := hx₁, right := hx₂ } { left := hy₁, right := hy₂ } hxy end real namespace complex /-- `arg` returns values in the range (-π, π], such that for `x ≠ 0`, `sin (arg x) = x.im / x.abs` and `cos (arg x) = x.re / x.abs`, `arg 0` defaults to `0` -/ def arg (x : ℂ) : ℝ := ite (0 ≤ re x) (real.arcsin (im x / abs x)) (ite (0 ≤ im x) (real.arcsin (im (-x) / abs x) + real.pi) (real.arcsin (im (-x) / abs x) - real.pi)) theorem arg_le_pi (x : ℂ) : arg x ≤ real.pi := sorry theorem neg_pi_lt_arg (x : ℂ) : -real.pi < arg x := sorry theorem arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg {x : ℂ} (hxr : re x < 0) (hxi : 0 ≤ im x) : arg x = arg (-x) + real.pi := sorry theorem arg_eq_arg_neg_sub_pi_of_im_neg_of_re_neg {x : ℂ} (hxr : re x < 0) (hxi : im x < 0) : arg x = arg (-x) - real.pi := sorry @[simp] theorem arg_zero : arg 0 = 0 := sorry @[simp] theorem arg_one : arg 1 = 0 := sorry @[simp] theorem arg_neg_one : arg (-1) = real.pi := sorry @[simp] theorem arg_I : arg I = real.pi / bit0 1 := sorry @[simp] theorem arg_neg_I : arg (-I) = -(real.pi / bit0 1) := sorry theorem sin_arg (x : ℂ) : real.sin (arg x) = im x / abs x := sorry theorem cos_arg {x : ℂ} (hx : x ≠ 0) : real.cos (arg x) = re x / abs x := sorry theorem tan_arg {x : ℂ} : real.tan (arg x) = im x / re x := sorry theorem arg_cos_add_sin_mul_I {x : ℝ} (hx₁ : -real.pi < x) (hx₂ : x ≤ real.pi) : arg (cos ↑x + sin ↑x * I) = x := sorry theorem arg_eq_arg_iff {x : ℂ} {y : ℂ} (hx : x ≠ 0) (hy : y ≠ 0) : arg x = arg y ↔ ↑(abs y) / ↑(abs x) * x = y := sorry theorem arg_real_mul (x : ℂ) {r : ℝ} (hr : 0 < r) : arg (↑r * x) = arg x := sorry theorem ext_abs_arg {x : ℂ} {y : ℂ} (h₁ : abs x = abs y) (h₂ : arg x = arg y) : x = y := sorry theorem arg_of_real_of_nonneg {x : ℝ} (hx : 0 ≤ x) : arg ↑x = 0 := sorry theorem arg_of_real_of_neg {x : ℝ} (hx : x < 0) : arg ↑x = real.pi := sorry /-- Inverse of the `exp` function. Returns values such that `(log x).im > - π` and `(log x).im ≤ π`. `log 0 = 0`-/ def log (x : ℂ) : ℂ := ↑(real.log (abs x)) + ↑(arg x) * I theorem log_re (x : ℂ) : re (log x) = real.log (abs x) := sorry theorem log_im (x : ℂ) : im (log x) = arg x := sorry theorem exp_log {x : ℂ} (hx : x ≠ 0) : exp (log x) = x := sorry theorem range_exp : set.range exp = set_of fun (x : ℂ) => x ≠ 0 := sorry theorem exp_inj_of_neg_pi_lt_of_le_pi {x : ℂ} {y : ℂ} (hx₁ : -real.pi < im x) (hx₂ : im x ≤ real.pi) (hy₁ : -real.pi < im y) (hy₂ : im y ≤ real.pi) (hxy : exp x = exp y) : x = y := sorry theorem log_exp {x : ℂ} (hx₁ : -real.pi < im x) (hx₂ : im x ≤ real.pi) : log (exp x) = x := sorry theorem of_real_log {x : ℝ} (hx : 0 ≤ x) : ↑(real.log x) = log ↑x := sorry theorem log_of_real_re (x : ℝ) : re (log ↑x) = real.log x := sorry @[simp] theorem log_zero : log 0 = 0 := sorry @[simp] theorem log_one : log 1 = 0 := sorry theorem log_neg_one : log (-1) = ↑real.pi * I := sorry theorem log_I : log I = ↑real.pi / bit0 1 * I := sorry theorem log_neg_I : log (-I) = -(↑real.pi / bit0 1) * I := sorry theorem exists_pow_nat_eq (x : ℂ) {n : ℕ} (hn : 0 < n) : ∃ (z : ℂ), z ^ n = x := sorry theorem exists_eq_mul_self (x : ℂ) : ∃ (z : ℂ), x = z * z := Exists.dcases_on (exists_pow_nat_eq x zero_lt_two) fun (z : ℂ) (h : z ^ bit0 1 = x) => Eq._oldrec (Exists.intro z (pow_two z)) h theorem two_pi_I_ne_zero : bit0 1 * ↑real.pi * I ≠ 0 := sorry theorem exp_eq_one_iff {x : ℂ} : exp x = 1 ↔ ∃ (n : ℤ), x = ↑n * (bit0 1 * ↑real.pi * I) := sorry theorem exp_eq_exp_iff_exp_sub_eq_one {x : ℂ} {y : ℂ} : exp x = exp y ↔ exp (x - y) = 1 := eq.mpr (id (Eq._oldrec (Eq.refl (exp x = exp y ↔ exp (x - y) = 1)) (exp_sub x y))) (eq.mpr (id (Eq._oldrec (Eq.refl (exp x = exp y ↔ exp x / exp y = 1)) (propext (div_eq_one_iff_eq (exp_ne_zero y))))) (iff.refl (exp x = exp y))) theorem exp_eq_exp_iff_exists_int {x : ℂ} {y : ℂ} : exp x = exp y ↔ ∃ (n : ℤ), x = y + ↑n * (bit0 1 * ↑real.pi * I) := sorry @[simp] theorem cos_pi_div_two : cos (↑real.pi / bit0 1) = 0 := sorry @[simp] theorem sin_pi_div_two : sin (↑real.pi / bit0 1) = 1 := sorry @[simp] theorem sin_pi : sin ↑real.pi = 0 := sorry @[simp] theorem cos_pi : cos ↑real.pi = -1 := sorry @[simp] theorem sin_two_pi : sin (bit0 1 * ↑real.pi) = 0 := sorry @[simp] theorem cos_two_pi : cos (bit0 1 * ↑real.pi) = 1 := sorry theorem sin_add_pi (x : ℂ) : sin (x + ↑real.pi) = -sin x := sorry theorem sin_add_two_pi (x : ℂ) : sin (x + bit0 1 * ↑real.pi) = sin x := sorry theorem cos_add_two_pi (x : ℂ) : cos (x + bit0 1 * ↑real.pi) = cos x := sorry theorem sin_pi_sub (x : ℂ) : sin (↑real.pi - x) = sin x := sorry theorem cos_add_pi (x : ℂ) : cos (x + ↑real.pi) = -cos x := sorry theorem cos_pi_sub (x : ℂ) : cos (↑real.pi - x) = -cos x := sorry theorem sin_add_pi_div_two (x : ℂ) : sin (x + ↑real.pi / bit0 1) = cos x := sorry theorem sin_sub_pi_div_two (x : ℂ) : sin (x - ↑real.pi / bit0 1) = -cos x := sorry theorem sin_pi_div_two_sub (x : ℂ) : sin (↑real.pi / bit0 1 - x) = cos x := sorry theorem cos_add_pi_div_two (x : ℂ) : cos (x + ↑real.pi / bit0 1) = -sin x := sorry theorem cos_sub_pi_div_two (x : ℂ) : cos (x - ↑real.pi / bit0 1) = sin x := sorry theorem cos_pi_div_two_sub (x : ℂ) : cos (↑real.pi / bit0 1 - x) = sin x := eq.mpr (id (Eq._oldrec (Eq.refl (cos (↑real.pi / bit0 1 - x) = sin x)) (Eq.symm (cos_neg (↑real.pi / bit0 1 - x))))) (eq.mpr (id (Eq._oldrec (Eq.refl (cos (-(↑real.pi / bit0 1 - x)) = sin x)) (neg_sub (↑real.pi / bit0 1) x))) (eq.mpr (id (Eq._oldrec (Eq.refl (cos (x - ↑real.pi / bit0 1) = sin x)) (cos_sub_pi_div_two x))) (Eq.refl (sin x)))) theorem sin_nat_mul_pi (n : ℕ) : sin (↑n * ↑real.pi) = 0 := sorry theorem sin_int_mul_pi (n : ℤ) : sin (↑n * ↑real.pi) = 0 := sorry theorem cos_nat_mul_two_pi (n : ℕ) : cos (↑n * (bit0 1 * ↑real.pi)) = 1 := sorry theorem cos_int_mul_two_pi (n : ℤ) : cos (↑n * (bit0 1 * ↑real.pi)) = 1 := sorry theorem cos_int_mul_two_pi_add_pi (n : ℤ) : cos (↑n * (bit0 1 * ↑real.pi) + ↑real.pi) = -1 := sorry theorem exp_pi_mul_I : exp (↑real.pi * I) = -1 := sorry theorem cos_eq_zero_iff {θ : ℂ} : cos θ = 0 ↔ ∃ (k : ℤ), θ = (bit0 1 * ↑k + 1) * ↑real.pi / bit0 1 := sorry theorem cos_ne_zero_iff {θ : ℂ} : cos θ ≠ 0 ↔ ∀ (k : ℤ), θ ≠ (bit0 1 * ↑k + 1) * ↑real.pi / bit0 1 := sorry theorem sin_eq_zero_iff {θ : ℂ} : sin θ = 0 ↔ ∃ (k : ℤ), θ = ↑k * ↑real.pi := sorry theorem sin_ne_zero_iff {θ : ℂ} : sin θ ≠ 0 ↔ ∀ (k : ℤ), θ ≠ ↑k * ↑real.pi := sorry theorem sin_eq_zero_iff_cos_eq {z : ℂ} : sin z = 0 ↔ cos z = 1 ∨ cos z = -1 := sorry theorem tan_eq_zero_iff {θ : ℂ} : tan θ = 0 ↔ ∃ (k : ℤ), θ = ↑k * ↑real.pi / bit0 1 := sorry theorem tan_ne_zero_iff {θ : ℂ} : tan θ ≠ 0 ↔ ∀ (k : ℤ), θ ≠ ↑k * ↑real.pi / bit0 1 := sorry theorem tan_int_mul_pi_div_two (n : ℤ) : tan (↑n * ↑real.pi / bit0 1) = 0 := iff.mpr tan_eq_zero_iff (Exists.intro n (id (Eq.refl (↑n * ↑real.pi / bit0 1)))) theorem tan_int_mul_pi (n : ℤ) : tan (↑n * ↑real.pi) = 0 := sorry theorem cos_eq_cos_iff {x : ℂ} {y : ℂ} : cos x = cos y ↔ ∃ (k : ℤ), y = bit0 1 * ↑k * ↑real.pi + x ∨ y = bit0 1 * ↑k * ↑real.pi - x := sorry theorem sin_eq_sin_iff {x : ℂ} {y : ℂ} : sin x = sin y ↔ ∃ (k : ℤ), y = bit0 1 * ↑k * ↑real.pi + x ∨ y = (bit0 1 * ↑k + 1) * ↑real.pi - x := sorry theorem tan_add {x : ℂ} {y : ℂ} (h : ((∀ (k : ℤ), x ≠ (bit0 1 * ↑k + 1) * ↑real.pi / bit0 1) ∧ ∀ (l : ℤ), y ≠ (bit0 1 * ↑l + 1) * ↑real.pi / bit0 1) ∨ (∃ (k : ℤ), x = (bit0 1 * ↑k + 1) * ↑real.pi / bit0 1) ∧ ∃ (l : ℤ), y = (bit0 1 * ↑l + 1) * ↑real.pi / bit0 1) : tan (x + y) = (tan x + tan y) / (1 - tan x * tan y) := sorry theorem tan_add' {x : ℂ} {y : ℂ} (h : (∀ (k : ℤ), x ≠ (bit0 1 * ↑k + 1) * ↑real.pi / bit0 1) ∧ ∀ (l : ℤ), y ≠ (bit0 1 * ↑l + 1) * ↑real.pi / bit0 1) : tan (x + y) = (tan x + tan y) / (1 - tan x * tan y) := tan_add (Or.inl h) theorem tan_two_mul {z : ℂ} : tan (bit0 1 * z) = bit0 1 * tan z / (1 - tan z ^ bit0 1) := sorry theorem tan_add_mul_I {x : ℂ} {y : ℂ} (h : ((∀ (k : ℤ), x ≠ (bit0 1 * ↑k + 1) * ↑real.pi / bit0 1) ∧ ∀ (l : ℤ), y * I ≠ (bit0 1 * ↑l + 1) * ↑real.pi / bit0 1) ∨ (∃ (k : ℤ), x = (bit0 1 * ↑k + 1) * ↑real.pi / bit0 1) ∧ ∃ (l : ℤ), y * I = (bit0 1 * ↑l + 1) * ↑real.pi / bit0 1) : tan (x + y * I) = (tan x + tanh y * I) / (1 - tan x * tanh y * I) := sorry theorem tan_eq {z : ℂ} (h : ((∀ (k : ℤ), ↑(re z) ≠ (bit0 1 * ↑k + 1) * ↑real.pi / bit0 1) ∧ ∀ (l : ℤ), ↑(im z) * I ≠ (bit0 1 * ↑l + 1) * ↑real.pi / bit0 1) ∨ (∃ (k : ℤ), ↑(re z) = (bit0 1 * ↑k + 1) * ↑real.pi / bit0 1) ∧ ∃ (l : ℤ), ↑(im z) * I = (bit0 1 * ↑l + 1) * ↑real.pi / bit0 1) : tan z = (tan ↑(re z) + tanh ↑(im z) * I) / (1 - tan ↑(re z) * tanh ↑(im z) * I) := sorry theorem has_deriv_at_tan {x : ℂ} (h : cos x ≠ 0) : has_deriv_at tan (1 / cos x ^ bit0 1) x := sorry theorem tendsto_abs_tan_of_cos_eq_zero {x : ℂ} (hx : cos x = 0) : filter.tendsto (fun (x : ℂ) => abs (tan x)) (nhds_within x (singleton xᶜ)) filter.at_top := sorry theorem tendsto_abs_tan_at_top (k : ℤ) : filter.tendsto (fun (x : ℂ) => abs (tan x)) (nhds_within ((bit0 1 * ↑k + 1) * ↑real.pi / bit0 1) (singleton ((bit0 1 * ↑k + 1) * ↑real.pi / bit0 1)ᶜ)) filter.at_top := tendsto_abs_tan_of_cos_eq_zero (iff.mpr cos_eq_zero_iff (Exists.intro k rfl)) @[simp] theorem continuous_at_tan {x : ℂ} : continuous_at tan x ↔ cos x ≠ 0 := sorry @[simp] theorem differentiable_at_tan {x : ℂ} : differentiable_at ℂ tan x ↔ cos x ≠ 0 := { mp := fun (h : differentiable_at ℂ tan x) => iff.mp continuous_at_tan (differentiable_at.continuous_at h), mpr := fun (h : cos x ≠ 0) => has_deriv_at.differentiable_at (has_deriv_at_tan h) } @[simp] theorem deriv_tan (x : ℂ) : deriv tan x = 1 / cos x ^ bit0 1 := sorry theorem continuous_on_tan : continuous_on tan (set_of fun (x : ℂ) => cos x ≠ 0) := continuous_on.div continuous_on_sin continuous_on_cos fun (x : ℂ) => id theorem continuous_tan : continuous fun (x : ↥(set_of fun (x : ℂ) => cos x ≠ 0)) => tan ↑x := iff.mp continuous_on_iff_continuous_restrict continuous_on_tan @[simp] theorem times_cont_diff_at_tan {x : ℂ} {n : with_top ℕ} : times_cont_diff_at ℂ n tan x ↔ cos x ≠ 0 := sorry theorem cos_eq_iff_quadratic {z : ℂ} {w : ℂ} : cos z = w ↔ exp (z * I) ^ bit0 1 - bit0 1 * w * exp (z * I) + 1 = 0 := sorry theorem cos_surjective : function.surjective cos := sorry @[simp] theorem range_cos : set.range cos = set.univ := function.surjective.range_eq cos_surjective theorem sin_surjective : function.surjective sin := sorry @[simp] theorem range_sin : set.range sin = set.univ := function.surjective.range_eq sin_surjective end complex /-- The `n`-th Chebyshev polynomial of the first kind evaluates on `cos θ` to the value `cos (n * θ)`. -/ theorem chebyshev₁_complex_cos (θ : ℂ) (n : ℕ) : polynomial.eval (complex.cos θ) (polynomial.chebyshev₁ ℂ n) = complex.cos (↑n * θ) := sorry /-- `cos (n * θ)` is equal to the `n`-th Chebyshev polynomial of the first kind evaluated on `cos θ`. -/ theorem cos_nat_mul (n : ℕ) (θ : ℂ) : complex.cos (↑n * θ) = polynomial.eval (complex.cos θ) (polynomial.chebyshev₁ ℂ n) := Eq.symm (chebyshev₁_complex_cos θ n) /-- The `n`-th Chebyshev polynomial of the second kind evaluates on `cos θ` to the value `sin ((n+1) * θ) / sin θ`. -/ theorem chebyshev₂_complex_cos (θ : ℂ) (n : ℕ) : polynomial.eval (complex.cos θ) (polynomial.chebyshev₂ ℂ n) * complex.sin θ = complex.sin ((↑n + 1) * θ) := sorry /-- `sin ((n + 1) * θ)` is equal to `sin θ` multiplied with the `n`-th Chebyshev polynomial of the second kind evaluated on `cos θ`. -/ theorem sin_nat_succ_mul (n : ℕ) (θ : ℂ) : complex.sin ((↑n + 1) * θ) = polynomial.eval (complex.cos θ) (polynomial.chebyshev₂ ℂ n) * complex.sin θ := Eq.symm (chebyshev₂_complex_cos θ n) namespace real theorem tan_add {x : ℝ} {y : ℝ} (h : ((∀ (k : ℤ), x ≠ (bit0 1 * ↑k + 1) * pi / bit0 1) ∧ ∀ (l : ℤ), y ≠ (bit0 1 * ↑l + 1) * pi / bit0 1) ∨ (∃ (k : ℤ), x = (bit0 1 * ↑k + 1) * pi / bit0 1) ∧ ∃ (l : ℤ), y = (bit0 1 * ↑l + 1) * pi / bit0 1) : tan (x + y) = (tan x + tan y) / (1 - tan x * tan y) := sorry theorem tan_add' {x : ℝ} {y : ℝ} (h : (∀ (k : ℤ), x ≠ (bit0 1 * ↑k + 1) * pi / bit0 1) ∧ ∀ (l : ℤ), y ≠ (bit0 1 * ↑l + 1) * pi / bit0 1) : tan (x + y) = (tan x + tan y) / (1 - tan x * tan y) := tan_add (Or.inl h) theorem tan_two_mul {x : ℝ} : tan (bit0 1 * x) = bit0 1 * tan x / (1 - tan x ^ bit0 1) := sorry theorem cos_eq_zero_iff {θ : ℝ} : cos θ = 0 ↔ ∃ (k : ℤ), θ = (bit0 1 * ↑k + 1) * pi / bit0 1 := sorry theorem cos_ne_zero_iff {θ : ℝ} : cos θ ≠ 0 ↔ ∀ (k : ℤ), θ ≠ (bit0 1 * ↑k + 1) * pi / bit0 1 := sorry theorem tan_ne_zero_iff {θ : ℝ} : tan θ ≠ 0 ↔ ∀ (k : ℤ), θ ≠ ↑k * pi / bit0 1 := sorry theorem tan_eq_zero_iff {θ : ℝ} : tan θ = 0 ↔ ∃ (k : ℤ), θ = ↑k * pi / bit0 1 := sorry theorem tan_int_mul_pi_div_two (n : ℤ) : tan (↑n * pi / bit0 1) = 0 := iff.mpr tan_eq_zero_iff (Exists.intro n (id (Eq.refl (↑n * pi / bit0 1)))) theorem tan_int_mul_pi (n : ℤ) : tan (↑n * pi) = 0 := sorry theorem cos_eq_cos_iff {x : ℝ} {y : ℝ} : cos x = cos y ↔ ∃ (k : ℤ), y = bit0 1 * ↑k * pi + x ∨ y = bit0 1 * ↑k * pi - x := sorry theorem sin_eq_sin_iff {x : ℝ} {y : ℝ} : sin x = sin y ↔ ∃ (k : ℤ), y = bit0 1 * ↑k * pi + x ∨ y = (bit0 1 * ↑k + 1) * pi - x := sorry theorem has_deriv_at_tan {x : ℝ} (h : cos x ≠ 0) : has_deriv_at tan (1 / cos x ^ bit0 1) x := sorry theorem tendsto_abs_tan_of_cos_eq_zero {x : ℝ} (hx : cos x = 0) : filter.tendsto (fun (x : ℝ) => abs (tan x)) (nhds_within x (singleton xᶜ)) filter.at_top := sorry theorem tendsto_abs_tan_at_top (k : ℤ) : filter.tendsto (fun (x : ℝ) => abs (tan x)) (nhds_within ((bit0 1 * ↑k + 1) * pi / bit0 1) (singleton ((bit0 1 * ↑k + 1) * pi / bit0 1)ᶜ)) filter.at_top := tendsto_abs_tan_of_cos_eq_zero (iff.mpr cos_eq_zero_iff (Exists.intro k rfl)) theorem continuous_at_tan {x : ℝ} : continuous_at tan x ↔ cos x ≠ 0 := sorry theorem differentiable_at_tan {x : ℝ} : differentiable_at ℝ tan x ↔ cos x ≠ 0 := { mp := fun (h : differentiable_at ℝ tan x) => iff.mp continuous_at_tan (differentiable_at.continuous_at h), mpr := fun (h : cos x ≠ 0) => has_deriv_at.differentiable_at (has_deriv_at_tan h) } @[simp] theorem deriv_tan (x : ℝ) : deriv tan x = 1 / cos x ^ bit0 1 := sorry @[simp] theorem times_cont_diff_at_tan {n : with_top ℕ} {x : ℝ} : times_cont_diff_at ℝ n tan x ↔ cos x ≠ 0 := sorry theorem continuous_on_tan : continuous_on tan (set_of fun (x : ℝ) => cos x ≠ 0) := fun (x : ℝ) (hx : x ∈ set_of fun (x : ℝ) => cos x ≠ 0) => continuous_at.continuous_within_at (iff.mpr continuous_at_tan hx) theorem has_deriv_at_tan_of_mem_Ioo {x : ℝ} (h : x ∈ set.Ioo (-(pi / bit0 1)) (pi / bit0 1)) : has_deriv_at tan (1 / cos x ^ bit0 1) x := has_deriv_at_tan (has_lt.lt.ne' (cos_pos_of_mem_Ioo h)) theorem differentiable_at_tan_of_mem_Ioo {x : ℝ} (h : x ∈ set.Ioo (-(pi / bit0 1)) (pi / bit0 1)) : differentiable_at ℝ tan x := has_deriv_at.differentiable_at (has_deriv_at_tan_of_mem_Ioo h) theorem continuous_on_tan_Ioo : continuous_on tan (set.Ioo (-(pi / bit0 1)) (pi / bit0 1)) := fun (x : ℝ) (hx : x ∈ set.Ioo (-(pi / bit0 1)) (pi / bit0 1)) => continuous_at.continuous_within_at (differentiable_at.continuous_at (differentiable_at_tan_of_mem_Ioo hx)) theorem tendsto_sin_pi_div_two : filter.tendsto sin (nhds_within (pi / bit0 1) (set.Iio (pi / bit0 1))) (nhds 1) := sorry theorem tendsto_cos_pi_div_two : filter.tendsto cos (nhds_within (pi / bit0 1) (set.Iio (pi / bit0 1))) (nhds_within 0 (set.Ioi 0)) := sorry theorem tendsto_tan_pi_div_two : filter.tendsto tan (nhds_within (pi / bit0 1) (set.Iio (pi / bit0 1))) filter.at_top := sorry theorem tendsto_sin_neg_pi_div_two : filter.tendsto sin (nhds_within (-(pi / bit0 1)) (set.Ioi (-(pi / bit0 1)))) (nhds (-1)) := sorry theorem tendsto_cos_neg_pi_div_two : filter.tendsto cos (nhds_within (-(pi / bit0 1)) (set.Ioi (-(pi / bit0 1)))) (nhds_within 0 (set.Ioi 0)) := sorry theorem tendsto_tan_neg_pi_div_two : filter.tendsto tan (nhds_within (-(pi / bit0 1)) (set.Ioi (-(pi / bit0 1)))) filter.at_bot := sorry theorem surj_on_tan : set.surj_on tan (set.Ioo (-(pi / bit0 1)) (pi / bit0 1)) set.univ := sorry theorem tan_surjective : function.surjective tan := fun (x : ℝ) => set.surj_on.subset_range surj_on_tan trivial theorem image_tan_Ioo : tan '' set.Ioo (-(pi / bit0 1)) (pi / bit0 1) = set.univ := iff.mp set.univ_subset_iff surj_on_tan /-- `real.tan` as an `order_iso` between `(-(π / 2), π / 2)` and `ℝ`. -/ def tan_order_iso : ↥(set.Ioo (-(pi / bit0 1)) (pi / bit0 1)) ≃o ℝ := order_iso.trans (strict_mono_incr_on.order_iso tan (set.Ioo (-(pi / bit0 1)) (pi / bit0 1)) strict_mono_incr_on_tan) (order_iso.trans (order_iso.set_congr (tan '' set.Ioo (-(pi / bit0 1)) (pi / bit0 1)) set.univ image_tan_Ioo) order_iso.set.univ) /-- Inverse of the `tan` function, returns values in the range `-π / 2 < arctan x` and `arctan x < π / 2` -/ def arctan (x : ℝ) : ℝ := ↑(coe_fn (order_iso.symm tan_order_iso) x) @[simp] theorem tan_arctan (x : ℝ) : tan (arctan x) = x := order_iso.apply_symm_apply tan_order_iso x theorem arctan_mem_Ioo (x : ℝ) : arctan x ∈ set.Ioo (-(pi / bit0 1)) (pi / bit0 1) := subtype.coe_prop (coe_fn (order_iso.symm tan_order_iso) x) theorem arctan_tan {x : ℝ} (hx₁ : -(pi / bit0 1) < x) (hx₂ : x < pi / bit0 1) : arctan (tan x) = x := iff.mp subtype.ext_iff (order_iso.symm_apply_apply tan_order_iso { val := x, property := { left := hx₁, right := hx₂ } }) theorem cos_arctan_pos (x : ℝ) : 0 < cos (arctan x) := cos_pos_of_mem_Ioo (arctan_mem_Ioo x) theorem cos_sq_arctan (x : ℝ) : cos (arctan x) ^ bit0 1 = 1 / (1 + x ^ bit0 1) := sorry theorem sin_arctan (x : ℝ) : sin (arctan x) = x / sqrt (1 + x ^ bit0 1) := sorry theorem cos_arctan (x : ℝ) : cos (arctan x) = 1 / sqrt (1 + x ^ bit0 1) := sorry theorem arctan_lt_pi_div_two (x : ℝ) : arctan x < pi / bit0 1 := and.right (arctan_mem_Ioo x) theorem neg_pi_div_two_lt_arctan (x : ℝ) : -(pi / bit0 1) < arctan x := and.left (arctan_mem_Ioo x) theorem arctan_eq_arcsin (x : ℝ) : arctan x = arcsin (x / sqrt (1 + x ^ bit0 1)) := Eq.symm (arcsin_eq_of_sin_eq (sin_arctan x) (set.mem_Icc_of_Ioo (arctan_mem_Ioo x))) @[simp] theorem arctan_zero : arctan 0 = 0 := sorry theorem arctan_eq_of_tan_eq {x : ℝ} {y : ℝ} (h : tan x = y) (hx : x ∈ set.Ioo (-(pi / bit0 1)) (pi / bit0 1)) : arctan y = x := inj_on_tan (arctan_mem_Ioo y) hx (eq.mpr (id (Eq._oldrec (Eq.refl (tan (arctan y) = tan x)) (tan_arctan y))) (eq.mpr (id (Eq._oldrec (Eq.refl (y = tan x)) h)) (Eq.refl y))) @[simp] theorem arctan_one : arctan 1 = pi / bit0 (bit0 1) := sorry @[simp] theorem arctan_neg (x : ℝ) : arctan (-x) = -arctan x := sorry theorem continuous_arctan : continuous arctan := continuous.comp continuous_subtype_coe (homeomorph.continuous_inv_fun (order_iso.to_homeomorph tan_order_iso)) theorem continuous_at_arctan {x : ℝ} : continuous_at arctan x := continuous.continuous_at continuous_arctan /-- `real.tan` as a `local_homeomorph` between `(-(π / 2), π / 2)` and the whole line. -/ def tan_local_homeomorph : local_homeomorph ℝ ℝ := local_homeomorph.mk (local_equiv.mk tan arctan (set.Ioo (-(pi / bit0 1)) (pi / bit0 1)) set.univ sorry sorry sorry sorry) sorry sorry continuous_on_tan_Ioo sorry @[simp] theorem coe_tan_local_homeomorph : ⇑tan_local_homeomorph = tan := rfl @[simp] theorem coe_tan_local_homeomorph_symm : ⇑(local_homeomorph.symm tan_local_homeomorph) = arctan := rfl theorem has_deriv_at_arctan (x : ℝ) : has_deriv_at arctan (1 / (1 + x ^ bit0 1)) x := sorry theorem differentiable_at_arctan (x : ℝ) : differentiable_at ℝ arctan x := has_deriv_at.differentiable_at (has_deriv_at_arctan x) theorem differentiable_arctan : differentiable ℝ arctan := differentiable_at_arctan @[simp] theorem deriv_arctan : deriv arctan = fun (x : ℝ) => 1 / (1 + x ^ bit0 1) := funext fun (x : ℝ) => has_deriv_at.deriv (has_deriv_at_arctan x) theorem times_cont_diff_arctan {n : with_top ℕ} : times_cont_diff ℝ n arctan := sorry theorem measurable_arctan : measurable arctan := continuous.measurable continuous_arctan end real /-! ### Lemmas for derivatives of the composition of `real.arctan` with a differentiable function In this section we register lemmas for the derivatives of the composition of `real.arctan` with a differentiable function, for standalone use and use with `simp`. -/ theorem measurable.arctan {α : Type u_1} [measurable_space α] {f : α → ℝ} (hf : measurable f) : measurable fun (x : α) => real.arctan (f x) := measurable.comp real.measurable_arctan hf theorem has_deriv_at.arctan {f : ℝ → ℝ} {f' : ℝ} {x : ℝ} (hf : has_deriv_at f f' x) : has_deriv_at (fun (x : ℝ) => real.arctan (f x)) (1 / (1 + f x ^ bit0 1) * f') x := has_deriv_at.comp x (real.has_deriv_at_arctan (f x)) hf theorem has_deriv_within_at.arctan {f : ℝ → ℝ} {f' : ℝ} {x : ℝ} {s : set ℝ} (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (fun (x : ℝ) => real.arctan (f x)) (1 / (1 + f x ^ bit0 1) * f') s x := has_deriv_at.comp_has_deriv_within_at x (real.has_deriv_at_arctan (f x)) hf theorem deriv_within_arctan {f : ℝ → ℝ} {x : ℝ} {s : set ℝ} (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : deriv_within (fun (x : ℝ) => real.arctan (f x)) s x = 1 / (1 + f x ^ bit0 1) * deriv_within f s x := has_deriv_within_at.deriv_within (has_deriv_within_at.arctan (differentiable_within_at.has_deriv_within_at hf)) hxs @[simp] theorem deriv_arctan {f : ℝ → ℝ} {x : ℝ} (hc : differentiable_at ℝ f x) : deriv (fun (x : ℝ) => real.arctan (f x)) x = 1 / (1 + f x ^ bit0 1) * deriv f x := has_deriv_at.deriv (has_deriv_at.arctan (differentiable_at.has_deriv_at hc)) theorem has_fderiv_at.arctan {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {f' : continuous_linear_map ℝ E ℝ} {x : E} (hf : has_fderiv_at f f' x) : has_fderiv_at (fun (x : E) => real.arctan (f x)) ((1 / (1 + f x ^ bit0 1)) • f') x := has_deriv_at.comp_has_fderiv_at x (real.has_deriv_at_arctan (f x)) hf theorem has_fderiv_within_at.arctan {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {f' : continuous_linear_map ℝ E ℝ} {x : E} {s : set E} (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (fun (x : E) => real.arctan (f x)) ((1 / (1 + f x ^ bit0 1)) • f') s x := has_deriv_at.comp_has_fderiv_within_at x (real.has_deriv_at_arctan (f x)) hf theorem fderiv_within_arctan {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {x : E} {s : set E} (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : fderiv_within ℝ (fun (x : E) => real.arctan (f x)) s x = (1 / (1 + f x ^ bit0 1)) • fderiv_within ℝ f s x := has_fderiv_within_at.fderiv_within (has_fderiv_within_at.arctan (differentiable_within_at.has_fderiv_within_at hf)) hxs @[simp] theorem fderiv_arctan {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {x : E} (hc : differentiable_at ℝ f x) : fderiv ℝ (fun (x : E) => real.arctan (f x)) x = (1 / (1 + f x ^ bit0 1)) • fderiv ℝ f x := has_fderiv_at.fderiv (has_fderiv_at.arctan (differentiable_at.has_fderiv_at hc)) theorem differentiable_within_at.arctan {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {x : E} {s : set E} (hf : differentiable_within_at ℝ f s x) : differentiable_within_at ℝ (fun (x : E) => real.arctan (f x)) s x := has_fderiv_within_at.differentiable_within_at (has_fderiv_within_at.arctan (differentiable_within_at.has_fderiv_within_at hf)) @[simp] theorem differentiable_at.arctan {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {x : E} (hc : differentiable_at ℝ f x) : differentiable_at ℝ (fun (x : E) => real.arctan (f x)) x := has_fderiv_at.differentiable_at (has_fderiv_at.arctan (differentiable_at.has_fderiv_at hc)) theorem differentiable_on.arctan {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {s : set E} (hc : differentiable_on ℝ f s) : differentiable_on ℝ (fun (x : E) => real.arctan (f x)) s := fun (x : E) (h : x ∈ s) => differentiable_within_at.arctan (hc x h) @[simp] theorem differentiable.arctan {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} (hc : differentiable ℝ f) : differentiable ℝ fun (x : E) => real.arctan (f x) := fun (x : E) => differentiable_at.arctan (hc x) theorem times_cont_diff_at.arctan {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {x : E} {n : with_top ℕ} (h : times_cont_diff_at ℝ n f x) : times_cont_diff_at ℝ n (fun (x : E) => real.arctan (f x)) x := times_cont_diff_at.comp x (times_cont_diff.times_cont_diff_at real.times_cont_diff_arctan) h theorem times_cont_diff.arctan {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {n : with_top ℕ} (h : times_cont_diff ℝ n f) : times_cont_diff ℝ n fun (x : E) => real.arctan (f x) := times_cont_diff.comp real.times_cont_diff_arctan h theorem times_cont_diff_within_at.arctan {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {x : E} {s : set E} {n : with_top ℕ} (h : times_cont_diff_within_at ℝ n f s x) : times_cont_diff_within_at ℝ n (fun (x : E) => real.arctan (f x)) s x := times_cont_diff.comp_times_cont_diff_within_at real.times_cont_diff_arctan h theorem times_cont_diff_on.arctan {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {s : set E} {n : with_top ℕ} (h : times_cont_diff_on ℝ n f s) : times_cont_diff_on ℝ n (fun (x : E) => real.arctan (f x)) s := times_cont_diff.comp_times_cont_diff_on real.times_cont_diff_arctan h
709b437aa8dfc75c58a989819832ddd59dbe2fa7
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Data/PrefixTree.lean
6f10c4eb76e45596ea3ed218e4c194972a565d42
[ "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
3,875
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Std.Data.RBMap namespace Lean open Std /- Similar to trie, but for arbitrary keys -/ inductive PrefixTreeNode (α : Type u) (β : Type v) where | Node : Option β → RBNode α (fun _ => PrefixTreeNode α β) → PrefixTreeNode α β instance : Inhabited (PrefixTreeNode α β) where default := PrefixTreeNode.Node none RBNode.leaf namespace PrefixTreeNode def empty : PrefixTreeNode α β := PrefixTreeNode.Node none RBNode.leaf @[specialize] partial def insert (t : PrefixTreeNode α β) (cmp : α → α → Ordering) (k : List α) (val : β) : PrefixTreeNode α β := let rec insertEmpty (k : List α) : PrefixTreeNode α β := match k with | [] => PrefixTreeNode.Node (some val) RBNode.leaf | k :: ks => let t := insertEmpty ks PrefixTreeNode.Node none (RBNode.singleton k t) let rec loop | PrefixTreeNode.Node v m, [] => PrefixTreeNode.Node (some val) m -- overrides old value | PrefixTreeNode.Node v m, k :: ks => let t := match RBNode.find cmp m k with | none => insertEmpty ks | some t => loop t ks PrefixTreeNode.Node v (RBNode.insert cmp m k t) loop t k @[specialize] partial def find? (t : PrefixTreeNode α β) (cmp : α → α → Ordering) (k : List α) : Option β := let rec loop | PrefixTreeNode.Node val m, [] => val | PrefixTreeNode.Node val m, k :: ks => match RBNode.find cmp m k with | none => none | some t => loop t ks loop t k @[specialize] partial def foldMatchingM [Monad m] (t : PrefixTreeNode α β) (cmp : α → α → Ordering) (k : List α) (init : σ) (f : β → σ → m σ) : m σ := let rec fold : PrefixTreeNode α β → σ → m σ | PrefixTreeNode.Node b? n, d => do let d ← match b? with | none => pure d | some b => f b d n.foldM (init := d) fun d _ t => fold t d let rec find : List α → PrefixTreeNode α β → σ → m σ | [], t, d => fold t d | k::ks, PrefixTreeNode.Node _ m, d => match RBNode.find cmp m k with | none => pure init | some t => find ks t d find k t init inductive WellFormed (cmp : α → α → Ordering) : PrefixTreeNode α β → Prop where | emptyWff : WellFormed cmp empty | insertWff {t : PrefixTreeNode α β} {k : List α} {val : β} : WellFormed cmp t → WellFormed cmp (insert t cmp k val) end PrefixTreeNode def PrefixTree (α : Type u) (β : Type v) (cmp : α → α → Ordering) : Type (max u v) := { t : PrefixTreeNode α β // t.WellFormed cmp } open PrefixTreeNode def PrefixTree.empty : PrefixTree α β p := ⟨PrefixTreeNode.empty, WellFormed.emptyWff⟩ instance : Inhabited (PrefixTree α β p) where default := PrefixTree.empty instance : EmptyCollection (PrefixTree α β p) where emptyCollection := PrefixTree.empty @[inline] def PrefixTree.insert (t : PrefixTree α β p) (k : List α) (v : β) : PrefixTree α β p := ⟨t.val.insert p k v, WellFormed.insertWff t.property⟩ @[inline] def PrefixTree.find? (t : PrefixTree α β p) (k : List α) : Option β := t.val.find? p k @[inline] def PrefixTree.foldMatchingM [Monad m] (t : PrefixTree α β p) (k : List α) (init : σ) (f : β → σ → m σ) : m σ := t.val.foldMatchingM p k init f @[inline] def PrefixTree.foldM [Monad m] (t : PrefixTree α β p) (init : σ) (f : β → σ → m σ) : m σ := t.foldMatchingM [] init f @[inline] def PrefixTree.forMatchingM [Monad m] (t : PrefixTree α β p) (k : List α) (f : β → m Unit) : m Unit := t.val.foldMatchingM p k () (fun b _ => f b) @[inline] def PrefixTree.forM [Monad m] (t : PrefixTree α β p) (f : β → m Unit) : m Unit := t.forMatchingM [] f end Lean
378c8869063ecd611f486f4ba4f5ea0ab4e8ed9a
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/435.lean
0e0048ebfc1b40844b7f00e55278c3dcee83c9ba
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
203
lean
variable {α} (op : α → α → α) local infixr:60 " ∙ " => op example (x y : α) : x ∙ y = y ∙ x := sorry infixr:60 " *** " => op -- Error, only local notation can reference section variables
d86b6c1a431e048fedca8933bf179483e78abe8e
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/topology/metric_space/basic.lean
37d69c29d05d0b669c9fd2324e77c1071519c43f
[ "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
98,818
lean
/- Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel -/ import topology.metric_space.emetric_space import topology.algebra.ordered.basic import data.fintype.intervals /-! # Metric spaces This file defines metric spaces. Many definitions and theorems expected on metric spaces are already introduced on uniform spaces and topological spaces. For example: open and closed sets, compactness, completeness, continuity and uniform continuity ## Main definitions * `has_dist α`: Endows a space `α` with a function `dist a b`. * `pseudo_metric_space α`: A space endowed with a distance function, which can be zero even if the two elements are non-equal. * `metric.ball x ε`: The set of all points `y` with `dist y x < ε`. * `metric.bounded s`: Whether a subset of a `pseudo_metric_space` is bounded. * `metric_space α`: A `pseudo_metric_space` with the guarantee `dist x y = 0 → x = y`. Additional useful definitions: * `nndist a b`: `dist` as a function to the non-negative reals. * `metric.closed_ball x ε`: The set of all points `y` with `dist y x ≤ ε`. * `metric.sphere x ε`: The set of all points `y` with `dist y x = ε`. * `proper_space α`: A `pseudo_metric_space` where all closed balls are compact. * `metric.diam s` : The `supr` of the distances of members of `s`. Defined in terms of `emetric.diam`, for better handling of the case when it should be infinite. TODO (anyone): Add "Main results" section. ## Implementation notes Since a lot of elementary properties don't require `eq_of_dist_eq_zero` we start setting up the theory of `pseudo_metric_space`, where we don't require `dist x y = 0 → x = y` and we specialize to `metric_space` at the end. ## Tags metric, pseudo_metric, dist -/ open set filter topological_space noncomputable theory open_locale uniformity topological_space big_operators filter nnreal ennreal universes u v w variables {α : Type u} {β : Type v} /-- Construct a uniform structure core from a distance function and metric space axioms. This is a technical construction that can be immediately used to construct a uniform structure from a distance function and metric space axioms but is also useful when discussing metrizable topologies, see `pseudo_metric_space.of_metrizable`. -/ def uniform_space.core_of_dist {α : Type*} (dist : α → α → ℝ) (dist_self : ∀ x : α, dist x x = 0) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) : uniform_space.core α := { uniformity := (⨅ ε>0, 𝓟 {p:α×α | dist p.1 p.2 < ε}), refl := le_infi $ assume ε, le_infi $ by simp [set.subset_def, id_rel, dist_self, (>)] {contextual := tt}, comp := le_infi $ assume ε, le_infi $ assume h, lift'_le (mem_infi_of_mem (ε / 2) $ mem_infi_of_mem (div_pos h zero_lt_two) (subset.refl _)) $ have ∀ (a b c : α), dist a c < ε / 2 → dist c b < ε / 2 → dist a b < ε, from assume a b c hac hcb, calc dist a b ≤ dist a c + dist c b : dist_triangle _ _ _ ... < ε / 2 + ε / 2 : add_lt_add hac hcb ... = ε : by rw [div_add_div_same, add_self_div_two], by simpa [comp_rel], symm := tendsto_infi.2 $ assume ε, tendsto_infi.2 $ assume h, tendsto_infi' ε $ tendsto_infi' h $ tendsto_principal_principal.2 $ by simp [dist_comm] } /-- Construct a uniform structure from a distance function and metric space axioms -/ def uniform_space_of_dist (dist : α → α → ℝ) (dist_self : ∀ x : α, dist x x = 0) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) : uniform_space α := uniform_space.of_core (uniform_space.core_of_dist dist dist_self dist_comm dist_triangle) /-- The distance function (given an ambient metric space on `α`), which returns a nonnegative real number `dist x y` given `x y : α`. -/ class has_dist (α : Type*) := (dist : α → α → ℝ) export has_dist (dist) -- the uniform structure and the emetric space structure are embedded in the metric space structure -- to avoid instance diamond issues. See Note [forgetful inheritance]. /-- Metric space Each metric space induces a canonical `uniform_space` and hence a canonical `topological_space`. This is enforced in the type class definition, by extending the `uniform_space` structure. When instantiating a `metric_space` structure, the uniformity fields are not necessary, they will be filled in by default. In the same way, each metric space induces an emetric space structure. It is included in the structure, but filled in by default. -/ class pseudo_metric_space (α : Type u) extends has_dist α : Type u := (dist_self : ∀ x : α, dist x x = 0) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) (edist : α → α → ℝ≥0∞ := λx y, ennreal.of_real (dist x y)) (edist_dist : ∀ x y : α, edist x y = ennreal.of_real (dist x y) . control_laws_tac) (to_uniform_space : uniform_space α := uniform_space_of_dist dist dist_self dist_comm dist_triangle) (uniformity_dist : 𝓤 α = ⨅ ε>0, 𝓟 {p:α×α | dist p.1 p.2 < ε} . control_laws_tac) variables [pseudo_metric_space α] @[priority 100] -- see Note [lower instance priority] instance metric_space.to_uniform_space' : uniform_space α := pseudo_metric_space.to_uniform_space @[priority 200] -- see Note [lower instance priority] instance pseudo_metric_space.to_has_edist : has_edist α := ⟨pseudo_metric_space.edist⟩ /-- Construct a pseudo-metric space structure whose underlying topological space structure (definitionally) agrees which a pre-existing topology which is compatible with a given distance function. -/ def pseudo_metric_space.of_metrizable {α : Type*} [topological_space α] (dist : α → α → ℝ) (dist_self : ∀ x : α, dist x x = 0) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) (H : ∀ s : set α, is_open s ↔ ∀ x ∈ s, ∃ ε > 0, ∀ y, dist x y < ε → y ∈ s) : pseudo_metric_space α := { dist := dist, dist_self := dist_self, dist_comm := dist_comm, dist_triangle := dist_triangle, to_uniform_space := { is_open_uniformity := begin dsimp only [uniform_space.core_of_dist], intros s, change is_open s ↔ _, rw H s, apply forall_congr, intro x, apply forall_congr, intro x_in, erw (has_basis_binfi_principal _ nonempty_Ioi).mem_iff, { apply exists_congr, intros ε, apply exists_congr, intros ε_pos, simp only [prod.forall, set_of_subset_set_of], split, { rintros h _ y H rfl, exact h y H }, { intros h y hxy, exact h _ _ hxy rfl } }, { exact λ r (hr : 0 < r) p (hp : 0 < p), ⟨min r p, lt_min hr hp, λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_left r p), λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_right r p)⟩ }, { apply_instance } end, ..uniform_space.core_of_dist dist dist_self dist_comm dist_triangle }, uniformity_dist := rfl } @[simp] theorem dist_self (x : α) : dist x x = 0 := pseudo_metric_space.dist_self x theorem dist_comm (x y : α) : dist x y = dist y x := pseudo_metric_space.dist_comm x y theorem edist_dist (x y : α) : edist x y = ennreal.of_real (dist x y) := pseudo_metric_space.edist_dist x y theorem dist_triangle (x y z : α) : dist x z ≤ dist x y + dist y z := pseudo_metric_space.dist_triangle x y z theorem dist_triangle_left (x y z : α) : dist x y ≤ dist z x + dist z y := by rw dist_comm z; apply dist_triangle theorem dist_triangle_right (x y z : α) : dist x y ≤ dist x z + dist y z := by rw dist_comm y; apply dist_triangle lemma dist_triangle4 (x y z w : α) : dist x w ≤ dist x y + dist y z + dist z w := calc dist x w ≤ dist x z + dist z w : dist_triangle x z w ... ≤ (dist x y + dist y z) + dist z w : add_le_add_right (dist_triangle x y z) _ lemma dist_triangle4_left (x₁ y₁ x₂ y₂ : α) : dist x₂ y₂ ≤ dist x₁ y₁ + (dist x₁ x₂ + dist y₁ y₂) := by { rw [add_left_comm, dist_comm x₁, ← add_assoc], apply dist_triangle4 } lemma dist_triangle4_right (x₁ y₁ x₂ y₂ : α) : dist x₁ y₁ ≤ dist x₁ x₂ + dist y₁ y₂ + dist x₂ y₂ := by { rw [add_right_comm, dist_comm y₁], apply dist_triangle4 } /-- The triangle (polygon) inequality for sequences of points; `finset.Ico` version. -/ lemma dist_le_Ico_sum_dist (f : ℕ → α) {m n} (h : m ≤ n) : dist (f m) (f n) ≤ ∑ i in finset.Ico m n, dist (f i) (f (i + 1)) := begin revert n, apply nat.le_induction, { simp only [finset.sum_empty, finset.Ico.self_eq_empty, dist_self] }, { assume n hn hrec, calc dist (f m) (f (n+1)) ≤ dist (f m) (f n) + dist _ _ : dist_triangle _ _ _ ... ≤ ∑ i in finset.Ico m n, _ + _ : add_le_add hrec (le_refl _) ... = ∑ i in finset.Ico m (n+1), _ : by rw [finset.Ico.succ_top hn, finset.sum_insert, add_comm]; simp } end /-- The triangle (polygon) inequality for sequences of points; `finset.range` version. -/ lemma dist_le_range_sum_dist (f : ℕ → α) (n : ℕ) : dist (f 0) (f n) ≤ ∑ i in finset.range n, dist (f i) (f (i + 1)) := finset.Ico.zero_bot n ▸ dist_le_Ico_sum_dist f (nat.zero_le n) /-- A version of `dist_le_Ico_sum_dist` with each intermediate distance replaced with an upper estimate. -/ lemma dist_le_Ico_sum_of_dist_le {f : ℕ → α} {m n} (hmn : m ≤ n) {d : ℕ → ℝ} (hd : ∀ {k}, m ≤ k → k < n → dist (f k) (f (k + 1)) ≤ d k) : dist (f m) (f n) ≤ ∑ i in finset.Ico m n, d i := le_trans (dist_le_Ico_sum_dist f hmn) $ finset.sum_le_sum $ λ k hk, hd (finset.Ico.mem.1 hk).1 (finset.Ico.mem.1 hk).2 /-- A version of `dist_le_range_sum_dist` with each intermediate distance replaced with an upper estimate. -/ lemma dist_le_range_sum_of_dist_le {f : ℕ → α} (n : ℕ) {d : ℕ → ℝ} (hd : ∀ {k}, k < n → dist (f k) (f (k + 1)) ≤ d k) : dist (f 0) (f n) ≤ ∑ i in finset.range n, d i := finset.Ico.zero_bot n ▸ dist_le_Ico_sum_of_dist_le (zero_le n) (λ _ _, hd) theorem swap_dist : function.swap (@dist α _) = dist := by funext x y; exact dist_comm _ _ theorem abs_dist_sub_le (x y z : α) : abs (dist x z - dist y z) ≤ dist x y := abs_sub_le_iff.2 ⟨sub_le_iff_le_add.2 (dist_triangle _ _ _), sub_le_iff_le_add.2 (dist_triangle_left _ _ _)⟩ theorem dist_nonneg {x y : α} : 0 ≤ dist x y := have 2 * dist x y ≥ 0, from calc 2 * dist x y = dist x y + dist y x : by rw [dist_comm x y, two_mul] ... ≥ 0 : by rw ← dist_self x; apply dist_triangle, nonneg_of_mul_nonneg_left this zero_lt_two @[simp] theorem abs_dist {a b : α} : abs (dist a b) = dist a b := abs_of_nonneg dist_nonneg /-- A version of `has_dist` that takes value in `ℝ≥0`. -/ class has_nndist (α : Type*) := (nndist : α → α → ℝ≥0) export has_nndist (nndist) /-- Distance as a nonnegative real number. -/ @[priority 100] -- see Note [lower instance priority] instance pseudo_metric_space.to_has_nndist : has_nndist α := ⟨λ a b, ⟨dist a b, dist_nonneg⟩⟩ /--Express `nndist` in terms of `edist`-/ lemma nndist_edist (x y : α) : nndist x y = (edist x y).to_nnreal := by simp [nndist, edist_dist, real.to_nnreal, max_eq_left dist_nonneg, ennreal.of_real] /--Express `edist` in terms of `nndist`-/ lemma edist_nndist (x y : α) : edist x y = ↑(nndist x y) := by { simpa only [edist_dist, ennreal.of_real_eq_coe_nnreal dist_nonneg] } @[simp, norm_cast] lemma coe_nnreal_ennreal_nndist (x y : α) : ↑(nndist x y) = edist x y := (edist_nndist x y).symm @[simp, norm_cast] lemma edist_lt_coe {x y : α} {c : ℝ≥0} : edist x y < c ↔ nndist x y < c := by rw [edist_nndist, ennreal.coe_lt_coe] @[simp, norm_cast] lemma edist_le_coe {x y : α} {c : ℝ≥0} : edist x y ≤ c ↔ nndist x y ≤ c := by rw [edist_nndist, ennreal.coe_le_coe] /--In a pseudometric space, the extended distance is always finite-/ lemma edist_ne_top (x y : α) : edist x y ≠ ⊤ := by rw [edist_dist x y]; apply ennreal.coe_ne_top /--In a pseudometric space, the extended distance is always finite-/ lemma edist_lt_top {α : Type*} [pseudo_metric_space α] (x y : α) : edist x y < ⊤ := ennreal.lt_top_iff_ne_top.2 (edist_ne_top x y) /--`nndist x x` vanishes-/ @[simp] lemma nndist_self (a : α) : nndist a a = 0 := (nnreal.coe_eq_zero _).1 (dist_self a) /--Express `dist` in terms of `nndist`-/ lemma dist_nndist (x y : α) : dist x y = ↑(nndist x y) := rfl @[simp, norm_cast] lemma coe_nndist (x y : α) : ↑(nndist x y) = dist x y := (dist_nndist x y).symm @[simp, norm_cast] lemma dist_lt_coe {x y : α} {c : ℝ≥0} : dist x y < c ↔ nndist x y < c := iff.rfl @[simp, norm_cast] lemma dist_le_coe {x y : α} {c : ℝ≥0} : dist x y ≤ c ↔ nndist x y ≤ c := iff.rfl /--Express `nndist` in terms of `dist`-/ lemma nndist_dist (x y : α) : nndist x y = real.to_nnreal (dist x y) := by rw [dist_nndist, real.to_nnreal_coe] theorem nndist_comm (x y : α) : nndist x y = nndist y x := by simpa only [dist_nndist, nnreal.coe_eq] using dist_comm x y /--Triangle inequality for the nonnegative distance-/ theorem nndist_triangle (x y z : α) : nndist x z ≤ nndist x y + nndist y z := dist_triangle _ _ _ theorem nndist_triangle_left (x y z : α) : nndist x y ≤ nndist z x + nndist z y := dist_triangle_left _ _ _ theorem nndist_triangle_right (x y z : α) : nndist x y ≤ nndist x z + nndist y z := dist_triangle_right _ _ _ /--Express `dist` in terms of `edist`-/ lemma dist_edist (x y : α) : dist x y = (edist x y).to_real := by rw [edist_dist, ennreal.to_real_of_real (dist_nonneg)] namespace metric /- instantiate pseudometric space as a topology -/ variables {x y z : α} {ε ε₁ ε₂ : ℝ} {s : set α} /-- `ball x ε` is the set of all points `y` with `dist y x < ε` -/ def ball (x : α) (ε : ℝ) : set α := {y | dist y x < ε} @[simp] theorem mem_ball : y ∈ ball x ε ↔ dist y x < ε := iff.rfl theorem mem_ball' : y ∈ ball x ε ↔ dist x y < ε := by rw dist_comm; refl theorem pos_of_mem_ball (hy : y ∈ ball x ε) : 0 < ε := dist_nonneg.trans_lt hy theorem mem_ball_self (h : 0 < ε) : x ∈ ball x ε := show dist x x < ε, by rw dist_self; assumption @[simp] lemma nonempty_ball : (ball x ε).nonempty ↔ 0 < ε := ⟨λ ⟨x, hx⟩, pos_of_mem_ball hx, λ h, ⟨x, mem_ball_self h⟩⟩ @[simp] lemma ball_eq_empty : ball x ε = ∅ ↔ ε ≤ 0 := by rw [← not_nonempty_iff_eq_empty, nonempty_ball, not_lt] @[simp] lemma ball_zero : ball x 0 = ∅ := by rw [ball_eq_empty] lemma ball_eq_ball (ε : ℝ) (x : α) : uniform_space.ball x {p | dist p.2 p.1 < ε} = metric.ball x ε := rfl lemma ball_eq_ball' (ε : ℝ) (x : α) : uniform_space.ball x {p | dist p.1 p.2 < ε} = metric.ball x ε := by { ext, simp [dist_comm, uniform_space.ball] } @[simp] lemma Union_ball_nat (x : α) : (⋃ n : ℕ, ball x n) = univ := Union_eq_univ_iff.2 $ λ y, exists_nat_gt (dist y x) @[simp] lemma Union_ball_nat_succ (x : α) : (⋃ n : ℕ, ball x (n + 1)) = univ := Union_eq_univ_iff.2 $ λ y, (exists_nat_gt (dist y x)).imp $ λ n hn, hn.trans (lt_add_one _) /-- `closed_ball x ε` is the set of all points `y` with `dist y x ≤ ε` -/ def closed_ball (x : α) (ε : ℝ) := {y | dist y x ≤ ε} @[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ dist y x ≤ ε := iff.rfl /-- `sphere x ε` is the set of all points `y` with `dist y x = ε` -/ def sphere (x : α) (ε : ℝ) := {y | dist y x = ε} @[simp] theorem mem_sphere : y ∈ sphere x ε ↔ dist y x = ε := iff.rfl theorem mem_closed_ball' : y ∈ closed_ball x ε ↔ dist x y ≤ ε := by { rw dist_comm, refl } theorem mem_closed_ball_self (h : 0 ≤ ε) : x ∈ closed_ball x ε := show dist x x ≤ ε, by rw dist_self; assumption @[simp] lemma nonempty_closed_ball : (closed_ball x ε).nonempty ↔ 0 ≤ ε := ⟨λ ⟨x, hx⟩, dist_nonneg.trans hx, λ h, ⟨x, mem_closed_ball_self h⟩⟩ @[simp] lemma closed_ball_eq_empty : closed_ball x ε = ∅ ↔ ε < 0 := by rw [← not_nonempty_iff_eq_empty, nonempty_closed_ball, not_le] theorem ball_subset_closed_ball : ball x ε ⊆ closed_ball x ε := assume y (hy : _ < _), le_of_lt hy theorem sphere_subset_closed_ball : sphere x ε ⊆ closed_ball x ε := λ y, le_of_eq theorem sphere_disjoint_ball : disjoint (sphere x ε) (ball x ε) := λ y ⟨hy₁, hy₂⟩, absurd hy₁ $ ne_of_lt hy₂ @[simp] theorem ball_union_sphere : ball x ε ∪ sphere x ε = closed_ball x ε := set.ext $ λ y, (@le_iff_lt_or_eq ℝ _ _ _).symm @[simp] theorem sphere_union_ball : sphere x ε ∪ ball x ε = closed_ball x ε := by rw [union_comm, ball_union_sphere] @[simp] theorem closed_ball_diff_sphere : closed_ball x ε \ sphere x ε = ball x ε := by rw [← ball_union_sphere, set.union_diff_cancel_right sphere_disjoint_ball.symm] @[simp] theorem closed_ball_diff_ball : closed_ball x ε \ ball x ε = sphere x ε := by rw [← ball_union_sphere, set.union_diff_cancel_left sphere_disjoint_ball.symm] theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε := by simp [dist_comm] theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ := λ y (yx : _ < ε₁), lt_of_lt_of_le yx h theorem closed_ball_subset_closed_ball (h : ε₁ ≤ ε₂) : closed_ball x ε₁ ⊆ closed_ball x ε₂ := λ y (yx : _ ≤ ε₁), le_trans yx h theorem closed_ball_subset_ball (h : ε₁ < ε₂) : closed_ball x ε₁ ⊆ ball x ε₂ := λ y (yh : dist y x ≤ ε₁), lt_of_le_of_lt yh h @[simp] lemma Union_closed_ball_nat (x : α) : (⋃ n : ℕ, closed_ball x n) = univ := Union_eq_univ_iff.2 $ λ y, exists_nat_ge (dist y x) theorem ball_disjoint (h : ε₁ + ε₂ ≤ dist x y) : ball x ε₁ ∩ ball y ε₂ = ∅ := eq_empty_iff_forall_not_mem.2 $ λ z ⟨h₁, h₂⟩, not_lt_of_le (dist_triangle_left x y z) (lt_of_lt_of_le (add_lt_add h₁ h₂) h) theorem ball_disjoint_same (h : ε ≤ dist x y / 2) : ball x ε ∩ ball y ε = ∅ := ball_disjoint $ by rwa [← two_mul, ← le_div_iff' (@zero_lt_two ℝ _ _)] theorem ball_subset (h : dist x y ≤ ε₂ - ε₁) : ball x ε₁ ⊆ ball y ε₂ := λ z zx, by rw ← add_sub_cancel'_right ε₁ ε₂; exact lt_of_le_of_lt (dist_triangle z x y) (add_lt_add_of_lt_of_le zx h) theorem ball_half_subset (y) (h : y ∈ ball x (ε / 2)) : ball y (ε / 2) ⊆ ball x ε := ball_subset $ by rw sub_self_div_two; exact le_of_lt h theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε := ⟨_, sub_pos.2 h, ball_subset $ by rw sub_sub_self⟩ theorem uniformity_basis_dist : (𝓤 α).has_basis (λ ε : ℝ, 0 < ε) (λ ε, {p:α×α | dist p.1 p.2 < ε}) := begin rw ← pseudo_metric_space.uniformity_dist.symm, refine has_basis_binfi_principal _ nonempty_Ioi, exact λ r (hr : 0 < r) p (hp : 0 < p), ⟨min r p, lt_min hr hp, λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_left r p), λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_right r p)⟩ end /-- Given `f : β → ℝ`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`. For specific bases see `uniformity_basis_dist`, `uniformity_basis_dist_inv_nat_succ`, and `uniformity_basis_dist_inv_nat_pos`. -/ protected theorem mk_uniformity_basis {β : Type*} {p : β → Prop} {f : β → ℝ} (hf₀ : ∀ i, p i → 0 < f i) (hf : ∀ ⦃ε⦄, 0 < ε → ∃ i (hi : p i), f i ≤ ε) : (𝓤 α).has_basis p (λ i, {p:α×α | dist p.1 p.2 < f i}) := begin refine ⟨λ s, uniformity_basis_dist.mem_iff.trans _⟩, split, { rintros ⟨ε, ε₀, hε⟩, obtain ⟨i, hi, H⟩ : ∃ i (hi : p i), f i ≤ ε, from hf ε₀, exact ⟨i, hi, λ x (hx : _ < _), hε $ lt_of_lt_of_le hx H⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, H⟩ } end theorem uniformity_basis_dist_inv_nat_succ : (𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | dist p.1 p.2 < 1 / (↑n+1) }) := metric.mk_uniformity_basis (λ n _, div_pos zero_lt_one $ nat.cast_add_one_pos n) (λ ε ε0, (exists_nat_one_div_lt ε0).imp $ λ n hn, ⟨trivial, le_of_lt hn⟩) theorem uniformity_basis_dist_inv_nat_pos : (𝓤 α).has_basis (λ n:ℕ, 0<n) (λ n:ℕ, {p:α×α | dist p.1 p.2 < 1 / ↑n }) := metric.mk_uniformity_basis (λ n hn, div_pos zero_lt_one $ nat.cast_pos.2 hn) (λ ε ε0, let ⟨n, hn⟩ := exists_nat_one_div_lt ε0 in ⟨n+1, nat.succ_pos n, hn.le⟩) theorem uniformity_basis_dist_pow {r : ℝ} (h0 : 0 < r) (h1 : r < 1) : (𝓤 α).has_basis (λ n:ℕ, true) (λ n:ℕ, {p:α×α | dist p.1 p.2 < r ^ n }) := metric.mk_uniformity_basis (λ n hn, pow_pos h0 _) (λ ε ε0, let ⟨n, hn⟩ := exists_pow_lt_of_lt_one ε0 h1 in ⟨n, trivial, hn.le⟩) theorem uniformity_basis_dist_lt {R : ℝ} (hR : 0 < R) : (𝓤 α).has_basis (λ r : ℝ, 0 < r ∧ r < R) (λ r, {p : α × α | dist p.1 p.2 < r}) := metric.mk_uniformity_basis (λ r, and.left) $ λ r hr, ⟨min r (R / 2), ⟨lt_min hr (half_pos hR), min_lt_iff.2 $ or.inr (half_lt_self hR)⟩, min_le_left _ _⟩ /-- Given `f : β → ℝ`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then closed neighborhoods of the diagonal of sizes `{f i | p i}` form a basis of `𝓤 α`. Currently we have only one specific basis `uniformity_basis_dist_le` based on this constructor. More can be easily added if needed in the future. -/ protected theorem mk_uniformity_basis_le {β : Type*} {p : β → Prop} {f : β → ℝ} (hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) : (𝓤 α).has_basis p (λ x, {p:α×α | dist p.1 p.2 ≤ f x}) := begin refine ⟨λ s, uniformity_basis_dist.mem_iff.trans _⟩, split, { rintros ⟨ε, ε₀, hε⟩, rcases exists_between ε₀ with ⟨ε', hε'⟩, rcases hf ε' hε'.1 with ⟨i, hi, H⟩, exact ⟨i, hi, λ x (hx : _ ≤ _), hε $ lt_of_le_of_lt (le_trans hx H) hε'.2⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, λ x (hx : _ < _), H (le_of_lt hx)⟩ } end /-- Contant size closed neighborhoods of the diagonal form a basis of the uniformity filter. -/ theorem uniformity_basis_dist_le : (𝓤 α).has_basis (λ ε : ℝ, 0 < ε) (λ ε, {p:α×α | dist p.1 p.2 ≤ ε}) := metric.mk_uniformity_basis_le (λ _, id) (λ ε ε₀, ⟨ε, ε₀, le_refl ε⟩) theorem uniformity_basis_dist_le_pow {r : ℝ} (h0 : 0 < r) (h1 : r < 1) : (𝓤 α).has_basis (λ n:ℕ, true) (λ n:ℕ, {p:α×α | dist p.1 p.2 ≤ r ^ n }) := metric.mk_uniformity_basis_le (λ n hn, pow_pos h0 _) (λ ε ε0, let ⟨n, hn⟩ := exists_pow_lt_of_lt_one ε0 h1 in ⟨n, trivial, hn.le⟩) theorem mem_uniformity_dist {s : set (α×α)} : s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, dist a b < ε → (a, b) ∈ s) := uniformity_basis_dist.mem_uniformity_iff /-- A constant size neighborhood of the diagonal is an entourage. -/ theorem dist_mem_uniformity {ε:ℝ} (ε0 : 0 < ε) : {p:α×α | dist p.1 p.2 < ε} ∈ 𝓤 α := mem_uniformity_dist.2 ⟨ε, ε0, λ a b, id⟩ theorem uniform_continuous_iff [pseudo_metric_space β] {f : α → β} : uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0, ∀{a b:α}, dist a b < δ → dist (f a) (f b) < ε := uniformity_basis_dist.uniform_continuous_iff uniformity_basis_dist lemma uniform_continuous_on_iff [pseudo_metric_space β] {f : α → β} {s : set α} : uniform_continuous_on f s ↔ ∀ ε > 0, ∃ δ > 0, ∀ x y ∈ s, dist x y < δ → dist (f x) (f y) < ε := metric.uniformity_basis_dist.uniform_continuous_on_iff metric.uniformity_basis_dist lemma uniform_continuous_on_iff_le [pseudo_metric_space β] {f : α → β} {s : set α} : uniform_continuous_on f s ↔ ∀ ε > 0, ∃ δ > 0, ∀ x y ∈ s, dist x y ≤ δ → dist (f x) (f y) ≤ ε := metric.uniformity_basis_dist_le.uniform_continuous_on_iff metric.uniformity_basis_dist_le theorem uniform_embedding_iff [pseudo_metric_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧ ∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ := uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl ⟨λ H δ δ0, let ⟨t, tu, ht⟩ := H _ (dist_mem_uniformity δ0), ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 tu in ⟨ε, ε0, λ a b h, ht _ _ (hε h)⟩, λ H s su, let ⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 su, ⟨ε, ε0, hε⟩ := H _ δ0 in ⟨_, dist_mem_uniformity ε0, λ a b h, hδ (hε h)⟩⟩ /-- If a map between pseudometric spaces is a uniform embedding then the distance between `f x` and `f y` is controlled in terms of the distance between `x` and `y`. -/ theorem controlled_of_uniform_embedding [pseudo_metric_space β] {f : α → β} : uniform_embedding f → (∀ ε > 0, ∃ δ > 0, ∀ {a b : α}, dist a b < δ → dist (f a) (f b) < ε) ∧ (∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ) := begin assume h, exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1, (uniform_embedding_iff.1 h).2.2⟩ end theorem totally_bounded_iff {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t : set α, finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, H _ (dist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 ru, ⟨t, ft, h⟩ := H ε ε0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩ /-- A pseudometric space space is totally bounded if one can reconstruct up to any ε>0 any element of the space from finitely many data. -/ lemma totally_bounded_of_finite_discretization {s : set α} (H : ∀ε > (0 : ℝ), ∃ (β : Type u) (_ : fintype β) (F : s → β), ∀x y, F x = F y → dist (x:α) y < ε) : totally_bounded s := begin cases s.eq_empty_or_nonempty with hs hs, { rw hs, exact totally_bounded_empty }, rcases hs with ⟨x0, hx0⟩, haveI : inhabited s := ⟨⟨x0, hx0⟩⟩, refine totally_bounded_iff.2 (λ ε ε0, _), rcases H ε ε0 with ⟨β, fβ, F, hF⟩, resetI, let Finv := function.inv_fun F, refine ⟨range (subtype.val ∘ Finv), finite_range _, λ x xs, _⟩, let x' := Finv (F ⟨x, xs⟩), have : F x' = F ⟨x, xs⟩ := function.inv_fun_eq ⟨⟨x, xs⟩, rfl⟩, simp only [set.mem_Union, set.mem_range], exact ⟨_, ⟨F ⟨x, xs⟩, rfl⟩, hF _ _ this.symm⟩ end theorem finite_approx_of_totally_bounded {s : set α} (hs : totally_bounded s) : ∀ ε > 0, ∃ t ⊆ s, finite t ∧ s ⊆ ⋃y∈t, ball y ε := begin intros ε ε_pos, rw totally_bounded_iff_subset at hs, exact hs _ (dist_mem_uniformity ε_pos), end /-- Expressing locally uniform convergence on a set using `dist`. -/ lemma tendsto_locally_uniformly_on_iff {ι : Type*} [topological_space β] {F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} : tendsto_locally_uniformly_on F f p s ↔ ∀ ε > 0, ∀ x ∈ s, ∃ t ∈ 𝓝[s] x, ∀ᶠ n in p, ∀ y ∈ t, dist (f y) (F n y) < ε := begin refine ⟨λ H ε hε, H _ (dist_mem_uniformity hε), λ H u hu x hx, _⟩, rcases mem_uniformity_dist.1 hu with ⟨ε, εpos, hε⟩, rcases H ε εpos x hx with ⟨t, ht, Ht⟩, exact ⟨t, ht, Ht.mono (λ n hs x hx, hε (hs x hx))⟩ end /-- Expressing uniform convergence on a set using `dist`. -/ lemma tendsto_uniformly_on_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} : tendsto_uniformly_on F f p s ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x ∈ s, dist (f x) (F n x) < ε := begin refine ⟨λ H ε hε, H _ (dist_mem_uniformity hε), λ H u hu, _⟩, rcases mem_uniformity_dist.1 hu with ⟨ε, εpos, hε⟩, exact (H ε εpos).mono (λ n hs x hx, hε (hs x hx)) end /-- Expressing locally uniform convergence using `dist`. -/ lemma tendsto_locally_uniformly_iff {ι : Type*} [topological_space β] {F : ι → β → α} {f : β → α} {p : filter ι} : tendsto_locally_uniformly F f p ↔ ∀ ε > 0, ∀ (x : β), ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, dist (f y) (F n y) < ε := by simp only [← tendsto_locally_uniformly_on_univ, tendsto_locally_uniformly_on_iff, nhds_within_univ, mem_univ, forall_const, exists_prop] /-- Expressing uniform convergence using `dist`. -/ lemma tendsto_uniformly_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} : tendsto_uniformly F f p ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x, dist (f x) (F n x) < ε := by { rw [← tendsto_uniformly_on_univ, tendsto_uniformly_on_iff], simp } protected lemma cauchy_iff {f : filter α} : cauchy f ↔ ne_bot f ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x y ∈ t, dist x y < ε := uniformity_basis_dist.cauchy_iff theorem nhds_basis_ball : (𝓝 x).has_basis (λ ε:ℝ, 0 < ε) (ball x) := nhds_basis_uniformity uniformity_basis_dist theorem mem_nhds_iff : s ∈ 𝓝 x ↔ ∃ε>0, ball x ε ⊆ s := nhds_basis_ball.mem_iff theorem eventually_nhds_iff {p : α → Prop} : (∀ᶠ y in 𝓝 x, p y) ↔ ∃ε>0, ∀ ⦃y⦄, dist y x < ε → p y := mem_nhds_iff lemma eventually_nhds_iff_ball {p : α → Prop} : (∀ᶠ y in 𝓝 x, p y) ↔ ∃ ε>0, ∀ y ∈ ball x ε, p y := mem_nhds_iff theorem nhds_basis_closed_ball : (𝓝 x).has_basis (λ ε:ℝ, 0 < ε) (closed_ball x) := nhds_basis_uniformity uniformity_basis_dist_le theorem nhds_basis_ball_inv_nat_succ : (𝓝 x).has_basis (λ _, true) (λ n:ℕ, ball x (1 / (↑n+1))) := nhds_basis_uniformity uniformity_basis_dist_inv_nat_succ theorem nhds_basis_ball_inv_nat_pos : (𝓝 x).has_basis (λ n, 0<n) (λ n:ℕ, ball x (1 / ↑n)) := nhds_basis_uniformity uniformity_basis_dist_inv_nat_pos theorem nhds_basis_ball_pow {r : ℝ} (h0 : 0 < r) (h1 : r < 1) : (𝓝 x).has_basis (λ n, true) (λ n:ℕ, ball x (r ^ n)) := nhds_basis_uniformity (uniformity_basis_dist_pow h0 h1) theorem nhds_basis_closed_ball_pow {r : ℝ} (h0 : 0 < r) (h1 : r < 1) : (𝓝 x).has_basis (λ n, true) (λ n:ℕ, closed_ball x (r ^ n)) := nhds_basis_uniformity (uniformity_basis_dist_le_pow h0 h1) theorem is_open_iff : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s := by simp only [is_open_iff_mem_nhds, mem_nhds_iff] theorem is_open_ball : is_open (ball x ε) := is_open_iff.2 $ λ y, exists_ball_subset_ball theorem ball_mem_nhds (x : α) {ε : ℝ} (ε0 : 0 < ε) : ball x ε ∈ 𝓝 x := is_open.mem_nhds is_open_ball (mem_ball_self ε0) theorem closed_ball_mem_nhds (x : α) {ε : ℝ} (ε0 : 0 < ε) : closed_ball x ε ∈ 𝓝 x := mem_of_superset (ball_mem_nhds x ε0) ball_subset_closed_ball theorem nhds_within_basis_ball {s : set α} : (𝓝[s] x).has_basis (λ ε:ℝ, 0 < ε) (λ ε, ball x ε ∩ s) := nhds_within_has_basis nhds_basis_ball s theorem mem_nhds_within_iff {t : set α} : s ∈ 𝓝[t] x ↔ ∃ε>0, ball x ε ∩ t ⊆ s := nhds_within_basis_ball.mem_iff theorem tendsto_nhds_within_nhds_within [pseudo_metric_space β] {t : set β} {f : α → β} {a b} : tendsto f (𝓝[s] a) (𝓝[t] b) ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → f x ∈ t ∧ dist (f x) b < ε := (nhds_within_basis_ball.tendsto_iff nhds_within_basis_ball).trans $ by simp only [inter_comm, mem_inter_iff, and_imp, mem_ball] theorem tendsto_nhds_within_nhds [pseudo_metric_space β] {f : α → β} {a b} : tendsto f (𝓝[s] a) (𝓝 b) ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → dist (f x) b < ε := by { rw [← nhds_within_univ b, tendsto_nhds_within_nhds_within], simp only [mem_univ, true_and] } theorem tendsto_nhds_nhds [pseudo_metric_space β] {f : α → β} {a b} : tendsto f (𝓝 a) (𝓝 b) ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, dist x a < δ → dist (f x) b < ε := nhds_basis_ball.tendsto_iff nhds_basis_ball theorem continuous_at_iff [pseudo_metric_space β] {f : α → β} {a : α} : continuous_at f a ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, dist x a < δ → dist (f x) (f a) < ε := by rw [continuous_at, tendsto_nhds_nhds] theorem continuous_within_at_iff [pseudo_metric_space β] {f : α → β} {a : α} {s : set α} : continuous_within_at f s a ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → dist (f x) (f a) < ε := by rw [continuous_within_at, tendsto_nhds_within_nhds] theorem continuous_on_iff [pseudo_metric_space β] {f : α → β} {s : set α} : continuous_on f s ↔ ∀ (b ∈ s) (ε > 0), ∃ δ > 0, ∀a ∈ s, dist a b < δ → dist (f a) (f b) < ε := by simp [continuous_on, continuous_within_at_iff] theorem continuous_iff [pseudo_metric_space β] {f : α → β} : continuous f ↔ ∀b (ε > 0), ∃ δ > 0, ∀a, dist a b < δ → dist (f a) (f b) < ε := continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_nhds theorem tendsto_nhds {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, dist (u x) a < ε := nhds_basis_ball.tendsto_right_iff theorem continuous_at_iff' [topological_space β] {f : β → α} {b : β} : continuous_at f b ↔ ∀ ε > 0, ∀ᶠ x in 𝓝 b, dist (f x) (f b) < ε := by rw [continuous_at, tendsto_nhds] theorem continuous_within_at_iff' [topological_space β] {f : β → α} {b : β} {s : set β} : continuous_within_at f s b ↔ ∀ ε > 0, ∀ᶠ x in 𝓝[s] b, dist (f x) (f b) < ε := by rw [continuous_within_at, tendsto_nhds] theorem continuous_on_iff' [topological_space β] {f : β → α} {s : set β} : continuous_on f s ↔ ∀ (b ∈ s) (ε > 0), ∀ᶠ x in 𝓝[s] b, dist (f x) (f b) < ε := by simp [continuous_on, continuous_within_at_iff'] theorem continuous_iff' [topological_space β] {f : β → α} : continuous f ↔ ∀a (ε > 0), ∀ᶠ x in 𝓝 a, dist (f x) (f a) < ε := continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds theorem tendsto_at_top [nonempty β] [semilattice_sup β] {u : β → α} {a : α} : tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, dist (u n) a < ε := (at_top_basis.tendsto_iff nhds_basis_ball).trans $ by { simp only [exists_prop, true_and], refl } /-- A variant of `tendsto_at_top` that uses `∃ N, ∀ n > N, ...` rather than `∃ N, ∀ n ≥ N, ...` -/ theorem tendsto_at_top' [nonempty β] [semilattice_sup β] [no_top_order β] {u : β → α} {a : α} : tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n>N, dist (u n) a < ε := (at_top_basis_Ioi.tendsto_iff nhds_basis_ball).trans $ by { simp only [exists_prop, true_and], refl } lemma is_open_singleton_iff {α : Type*} [pseudo_metric_space α] {x : α} : is_open ({x} : set α) ↔ ∃ ε > 0, ∀ y, dist y x < ε → y = x := by simp [is_open_iff, subset_singleton_iff, mem_ball] /-- Given a point `x` in a discrete subset `s` of a pseudometric space, there is an open ball centered at `x` and intersecting `s` only at `x`. -/ lemma exists_ball_inter_eq_singleton_of_mem_discrete [discrete_topology s] {x : α} (hx : x ∈ s) : ∃ ε > 0, metric.ball x ε ∩ s = {x} := nhds_basis_ball.exists_inter_eq_singleton_of_mem_discrete hx /-- Given a point `x` in a discrete subset `s` of a pseudometric space, there is a closed ball of positive radius centered at `x` and intersecting `s` only at `x`. -/ lemma exists_closed_ball_inter_eq_singleton_of_discrete [discrete_topology s] {x : α} (hx : x ∈ s) : ∃ ε > 0, metric.closed_ball x ε ∩ s = {x} := nhds_basis_closed_ball.exists_inter_eq_singleton_of_mem_discrete hx end metric open metric /-Instantiate a pseudometric space as a pseudoemetric space. Before we can state the instance, we need to show that the uniform structure coming from the edistance and the distance coincide. -/ /-- Expressing the uniformity in terms of `edist` -/ protected lemma pseudo_metric.uniformity_basis_edist : (𝓤 α).has_basis (λ ε:ℝ≥0∞, 0 < ε) (λ ε, {p | edist p.1 p.2 < ε}) := ⟨begin intro t, refine mem_uniformity_dist.trans ⟨_, _⟩; rintro ⟨ε, ε0, Hε⟩, { use [ennreal.of_real ε, ennreal.of_real_pos.2 ε0], rintros ⟨a, b⟩, simp only [edist_dist, ennreal.of_real_lt_of_real_iff ε0], exact Hε }, { rcases ennreal.lt_iff_exists_real_btwn.1 ε0 with ⟨ε', _, ε0', hε⟩, rw [ennreal.of_real_pos] at ε0', refine ⟨ε', ε0', λ a b h, Hε (lt_trans _ hε)⟩, rwa [edist_dist, ennreal.of_real_lt_of_real_iff ε0'] } end⟩ theorem metric.uniformity_edist : 𝓤 α = (⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε}) := pseudo_metric.uniformity_basis_edist.eq_binfi /-- A pseudometric space induces a pseudoemetric space -/ @[priority 100] -- see Note [lower instance priority] instance pseudo_metric_space.to_pseudo_emetric_space : pseudo_emetric_space α := { edist := edist, edist_self := by simp [edist_dist], edist_comm := by simp only [edist_dist, dist_comm]; simp, edist_triangle := assume x y z, begin simp only [edist_dist, ← ennreal.of_real_add, dist_nonneg], rw ennreal.of_real_le_of_real_iff _, { exact dist_triangle _ _ _ }, { simpa using add_le_add (dist_nonneg : 0 ≤ dist x y) dist_nonneg } end, uniformity_edist := metric.uniformity_edist, ..‹pseudo_metric_space α› } /-- In a pseudometric space, an open ball of infinite radius is the whole space -/ lemma metric.eball_top_eq_univ (x : α) : emetric.ball x ∞ = set.univ := set.eq_univ_iff_forall.mpr (λ y, edist_lt_top y x) /-- Balls defined using the distance or the edistance coincide -/ @[simp] lemma metric.emetric_ball {x : α} {ε : ℝ} : emetric.ball x (ennreal.of_real ε) = ball x ε := begin ext y, simp only [emetric.mem_ball, mem_ball, edist_dist], exact ennreal.of_real_lt_of_real_iff_of_nonneg dist_nonneg end /-- Balls defined using the distance or the edistance coincide -/ @[simp] lemma metric.emetric_ball_nnreal {x : α} {ε : ℝ≥0} : emetric.ball x ε = ball x ε := by { convert metric.emetric_ball, simp } /-- Closed balls defined using the distance or the edistance coincide -/ lemma metric.emetric_closed_ball {x : α} {ε : ℝ} (h : 0 ≤ ε) : emetric.closed_ball x (ennreal.of_real ε) = closed_ball x ε := by ext y; simp [edist_dist]; rw ennreal.of_real_le_of_real_iff h /-- Closed balls defined using the distance or the edistance coincide -/ @[simp] lemma metric.emetric_closed_ball_nnreal {x : α} {ε : ℝ≥0} : emetric.closed_ball x ε = closed_ball x ε := by { convert metric.emetric_closed_ball ε.2, simp } @[simp] lemma metric.emetric_ball_top (x : α) : emetric.ball x ⊤ = univ := eq_univ_of_forall $ λ y, edist_lt_top _ _ /-- Build a new pseudometric space from an old one where the bundled uniform structure is provably (but typically non-definitionaly) equal to some given uniform structure. See Note [forgetful inheritance]. -/ def pseudo_metric_space.replace_uniformity {α} [U : uniform_space α] (m : pseudo_metric_space α) (H : @uniformity _ U = @uniformity _ pseudo_emetric_space.to_uniform_space') : pseudo_metric_space α := { dist := @dist _ m.to_has_dist, dist_self := dist_self, dist_comm := dist_comm, dist_triangle := dist_triangle, edist := edist, edist_dist := edist_dist, to_uniform_space := U, uniformity_dist := H.trans pseudo_metric_space.uniformity_dist } /-- One gets a pseudometric space from an emetric space if the edistance is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the uniformity are defeq in the pseudometric space and the pseudoemetric space. In this definition, the distance is given separately, to be able to prescribe some expression which is not defeq to the push-forward of the edistance to reals. -/ def pseudo_emetric_space.to_pseudo_metric_space_of_dist {α : Type u} [e : pseudo_emetric_space α] (dist : α → α → ℝ) (edist_ne_top : ∀x y: α, edist x y ≠ ⊤) (h : ∀x y, dist x y = ennreal.to_real (edist x y)) : pseudo_metric_space α := let m : pseudo_metric_space α := { dist := dist, dist_self := λx, by simp [h], dist_comm := λx y, by simp [h, pseudo_emetric_space.edist_comm], dist_triangle := λx y z, begin simp only [h], rw [← ennreal.to_real_add (edist_ne_top _ _) (edist_ne_top _ _), ennreal.to_real_le_to_real (edist_ne_top _ _)], { exact edist_triangle _ _ _ }, { simp [ennreal.add_eq_top, edist_ne_top] } end, edist := λx y, edist x y, edist_dist := λx y, by simp [h, ennreal.of_real_to_real, edist_ne_top] } in m.replace_uniformity $ by { rw [uniformity_pseudoedist, metric.uniformity_edist], refl } /-- One gets a pseudometric space from an emetric space if the edistance is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the uniformity are defeq in the pseudometric space and the emetric space. -/ def pseudo_emetric_space.to_pseudo_metric_space {α : Type u} [e : emetric_space α] (h : ∀x y: α, edist x y ≠ ⊤) : pseudo_metric_space α := pseudo_emetric_space.to_pseudo_metric_space_of_dist (λx y, ennreal.to_real (edist x y)) h (λx y, rfl) /-- A very useful criterion to show that a space is complete is to show that all sequences which satisfy a bound of the form `dist (u n) (u m) < B N` for all `n m ≥ N` are converging. This is often applied for `B N = 2^{-N}`, i.e., with a very fast convergence to `0`, which makes it possible to use arguments of converging series, while this is impossible to do in general for arbitrary Cauchy sequences. -/ theorem metric.complete_of_convergent_controlled_sequences (B : ℕ → real) (hB : ∀n, 0 < B n) (H : ∀u : ℕ → α, (∀N n m : ℕ, N ≤ n → N ≤ m → dist (u n) (u m) < B N) → ∃x, tendsto u at_top (𝓝 x)) : complete_space α := begin -- this follows from the same criterion in emetric spaces. We just need to translate -- the convergence assumption from `dist` to `edist` apply emetric.complete_of_convergent_controlled_sequences (λn, ennreal.of_real (B n)), { simp [hB] }, { assume u Hu, apply H, assume N n m hn hm, rw [← ennreal.of_real_lt_of_real_iff (hB N), ← edist_dist], exact Hu N n m hn hm } end theorem metric.complete_of_cauchy_seq_tendsto : (∀ u : ℕ → α, cauchy_seq u → ∃a, tendsto u at_top (𝓝 a)) → complete_space α := emetric.complete_of_cauchy_seq_tendsto section real /-- Instantiate the reals as a pseudometric space. -/ instance real.pseudo_metric_space : pseudo_metric_space ℝ := { dist := λx y, abs (x - y), dist_self := by simp [abs_zero], dist_comm := assume x y, abs_sub_comm _ _, dist_triangle := assume x y z, abs_sub_le _ _ _ } theorem real.dist_eq (x y : ℝ) : dist x y = abs (x - y) := rfl theorem real.nndist_eq (x y : ℝ) : nndist x y = real.nnabs (x - y) := rfl theorem real.nndist_eq' (x y : ℝ) : nndist x y = real.nnabs (y - x) := nndist_comm _ _ theorem real.dist_0_eq_abs (x : ℝ) : dist x 0 = abs x := by simp [real.dist_eq] theorem real.dist_left_le_of_mem_interval {x y z : ℝ} (h : y ∈ interval x z) : dist x y ≤ dist x z := by simpa only [dist_comm x] using abs_sub_left_of_mem_interval h theorem real.dist_right_le_of_mem_interval {x y z : ℝ} (h : y ∈ interval x z) : dist y z ≤ dist x z := by simpa only [dist_comm _ z] using abs_sub_right_of_mem_interval h theorem real.dist_le_of_mem_interval {x y x' y' : ℝ} (hx : x ∈ interval x' y') (hy : y ∈ interval x' y') : dist x y ≤ dist x' y' := abs_sub_le_of_subinterval $ interval_subset_interval (by rwa interval_swap) (by rwa interval_swap) theorem real.dist_le_of_mem_Icc {x y x' y' : ℝ} (hx : x ∈ Icc x' y') (hy : y ∈ Icc x' y') : dist x y ≤ y' - x' := by simpa only [real.dist_eq, abs_of_nonpos (sub_nonpos.2 $ hx.1.trans hx.2), neg_sub] using real.dist_le_of_mem_interval (Icc_subset_interval hx) (Icc_subset_interval hy) theorem real.dist_le_of_mem_Icc_01 {x y : ℝ} (hx : x ∈ Icc (0:ℝ) 1) (hy : y ∈ Icc (0:ℝ) 1) : dist x y ≤ 1 := by simpa only [sub_zero] using real.dist_le_of_mem_Icc hx hy instance : order_topology ℝ := order_topology_of_nhds_abs $ λ x, by simp only [nhds_basis_ball.eq_binfi, ball, real.dist_eq, abs_sub_comm] lemma real.ball_eq (x r : ℝ) : ball x r = Ioo (x - r) (x + r) := set.ext $ λ y, by rw [mem_ball, dist_comm, real.dist_eq, abs_sub_lt_iff, mem_Ioo, ← sub_lt_iff_lt_add', sub_lt] lemma real.closed_ball_eq {x r : ℝ} : closed_ball x r = Icc (x - r) (x + r) := by ext y; rw [mem_closed_ball, dist_comm, real.dist_eq, abs_sub_le_iff, mem_Icc, ← sub_le_iff_le_add', sub_le] section metric_ordered variables [conditionally_complete_linear_order α] [order_topology α] lemma totally_bounded_Icc (a b : α) : totally_bounded (Icc a b) := is_compact_Icc.totally_bounded lemma totally_bounded_Ico (a b : α) : totally_bounded (Ico a b) := totally_bounded_subset Ico_subset_Icc_self (totally_bounded_Icc a b) lemma totally_bounded_Ioc (a b : α) : totally_bounded (Ioc a b) := totally_bounded_subset Ioc_subset_Icc_self (totally_bounded_Icc a b) lemma totally_bounded_Ioo (a b : α) : totally_bounded (Ioo a b) := totally_bounded_subset Ioo_subset_Icc_self (totally_bounded_Icc a b) end metric_ordered /-- Special case of the sandwich theorem; see `tendsto_of_tendsto_of_tendsto_of_le_of_le'` for the general case. -/ lemma squeeze_zero' {α} {f g : α → ℝ} {t₀ : filter α} (hf : ∀ᶠ t in t₀, 0 ≤ f t) (hft : ∀ᶠ t in t₀, f t ≤ g t) (g0 : tendsto g t₀ (nhds 0)) : tendsto f t₀ (𝓝 0) := tendsto_of_tendsto_of_tendsto_of_le_of_le' tendsto_const_nhds g0 hf hft /-- Special case of the sandwich theorem; see `tendsto_of_tendsto_of_tendsto_of_le_of_le` and `tendsto_of_tendsto_of_tendsto_of_le_of_le'` for the general case. -/ lemma squeeze_zero {α} {f g : α → ℝ} {t₀ : filter α} (hf : ∀t, 0 ≤ f t) (hft : ∀t, f t ≤ g t) (g0 : tendsto g t₀ (𝓝 0)) : tendsto f t₀ (𝓝 0) := squeeze_zero' (eventually_of_forall hf) (eventually_of_forall hft) g0 theorem metric.uniformity_eq_comap_nhds_zero : 𝓤 α = comap (λp:α×α, dist p.1 p.2) (𝓝 (0 : ℝ)) := by { ext s, simp [mem_uniformity_dist, (nhds_basis_ball.comap _).mem_iff, subset_def, real.dist_0_eq_abs] } lemma cauchy_seq_iff_tendsto_dist_at_top_0 [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ tendsto (λ (n : β × β), dist (u n.1) (u n.2)) at_top (𝓝 0) := by rw [cauchy_seq_iff_tendsto, metric.uniformity_eq_comap_nhds_zero, tendsto_comap_iff, prod.map_def] lemma tendsto_uniformity_iff_dist_tendsto_zero {ι : Type*} {f : ι → α × α} {p : filter ι} : tendsto f p (𝓤 α) ↔ tendsto (λ x, dist (f x).1 (f x).2) p (𝓝 0) := by rw [metric.uniformity_eq_comap_nhds_zero, tendsto_comap_iff] lemma filter.tendsto.congr_dist {ι : Type*} {f₁ f₂ : ι → α} {p : filter ι} {a : α} (h₁ : tendsto f₁ p (𝓝 a)) (h : tendsto (λ x, dist (f₁ x) (f₂ x)) p (𝓝 0)) : tendsto f₂ p (𝓝 a) := h₁.congr_uniformity $ tendsto_uniformity_iff_dist_tendsto_zero.2 h alias filter.tendsto.congr_dist ← tendsto_of_tendsto_of_dist lemma tendsto_iff_of_dist {ι : Type*} {f₁ f₂ : ι → α} {p : filter ι} {a : α} (h : tendsto (λ x, dist (f₁ x) (f₂ x)) p (𝓝 0)) : tendsto f₁ p (𝓝 a) ↔ tendsto f₂ p (𝓝 a) := uniform.tendsto_congr $ tendsto_uniformity_iff_dist_tendsto_zero.2 h end real section cauchy_seq variables [nonempty β] [semilattice_sup β] /-- In a pseudometric space, Cauchy sequences are characterized by the fact that, eventually, the distance between its elements is arbitrarily small -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem metric.cauchy_seq_iff {u : β → α} : cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, dist (u m) (u n) < ε := uniformity_basis_dist.cauchy_seq_iff /-- A variation around the pseudometric characterization of Cauchy sequences -/ theorem metric.cauchy_seq_iff' {u : β → α} : cauchy_seq u ↔ ∀ε>0, ∃N, ∀n≥N, dist (u n) (u N) < ε := uniformity_basis_dist.cauchy_seq_iff' /-- If the distance between `s n` and `s m`, `n, m ≥ N` is bounded above by `b N` and `b` converges to zero, then `s` is a Cauchy sequence. -/ lemma cauchy_seq_of_le_tendsto_0 {s : β → α} (b : β → ℝ) (h : ∀ n m N : β, N ≤ n → N ≤ m → dist (s n) (s m) ≤ b N) (h₀ : tendsto b at_top (nhds 0)) : cauchy_seq s := metric.cauchy_seq_iff.2 $ λ ε ε0, (metric.tendsto_at_top.1 h₀ ε ε0).imp $ λ N hN m n hm hn, calc dist (s m) (s n) ≤ b N : h m n N hm hn ... ≤ abs (b N) : le_abs_self _ ... = dist (b N) 0 : by rw real.dist_0_eq_abs; refl ... < ε : (hN _ (le_refl N)) /-- A Cauchy sequence on the natural numbers is bounded. -/ theorem cauchy_seq_bdd {u : ℕ → α} (hu : cauchy_seq u) : ∃ R > 0, ∀ m n, dist (u m) (u n) < R := begin rcases metric.cauchy_seq_iff'.1 hu 1 zero_lt_one with ⟨N, hN⟩, suffices : ∃ R > 0, ∀ n, dist (u n) (u N) < R, { rcases this with ⟨R, R0, H⟩, exact ⟨_, add_pos R0 R0, λ m n, lt_of_le_of_lt (dist_triangle_right _ _ _) (add_lt_add (H m) (H n))⟩ }, let R := finset.sup (finset.range N) (λ n, nndist (u n) (u N)), refine ⟨↑R + 1, add_pos_of_nonneg_of_pos R.2 zero_lt_one, λ n, _⟩, cases le_or_lt N n, { exact lt_of_lt_of_le (hN _ h) (le_add_of_nonneg_left R.2) }, { have : _ ≤ R := finset.le_sup (finset.mem_range.2 h), exact lt_of_le_of_lt this (lt_add_of_pos_right _ zero_lt_one) } end /-- Yet another metric characterization of Cauchy sequences on integers. This one is often the most efficient. -/ lemma cauchy_seq_iff_le_tendsto_0 {s : ℕ → α} : cauchy_seq s ↔ ∃ b : ℕ → ℝ, (∀ n, 0 ≤ b n) ∧ (∀ n m N : ℕ, N ≤ n → N ≤ m → dist (s n) (s m) ≤ b N) ∧ tendsto b at_top (𝓝 0) := ⟨λ hs, begin /- `s` is a Cauchy sequence. The sequence `b` will be constructed by taking the supremum of the distances between `s n` and `s m` for `n m ≥ N`. First, we prove that all these distances are bounded, as otherwise the Sup would not make sense. -/ let S := λ N, (λ(p : ℕ × ℕ), dist (s p.1) (s p.2)) '' {p | p.1 ≥ N ∧ p.2 ≥ N}, have hS : ∀ N, ∃ x, ∀ y ∈ S N, y ≤ x, { rcases cauchy_seq_bdd hs with ⟨R, R0, hR⟩, refine λ N, ⟨R, _⟩, rintro _ ⟨⟨m, n⟩, _, rfl⟩, exact le_of_lt (hR m n) }, have bdd : bdd_above (range (λ(p : ℕ × ℕ), dist (s p.1) (s p.2))), { rcases cauchy_seq_bdd hs with ⟨R, R0, hR⟩, use R, rintro _ ⟨⟨m, n⟩, rfl⟩, exact le_of_lt (hR m n) }, -- Prove that it bounds the distances of points in the Cauchy sequence have ub : ∀ m n N, N ≤ m → N ≤ n → dist (s m) (s n) ≤ Sup (S N) := λ m n N hm hn, le_cSup (hS N) ⟨⟨_, _⟩, ⟨hm, hn⟩, rfl⟩, have S0m : ∀ n, (0:ℝ) ∈ S n := λ n, ⟨⟨n, n⟩, ⟨le_refl _, le_refl _⟩, dist_self _⟩, have S0 := λ n, le_cSup (hS n) (S0m n), -- Prove that it tends to `0`, by using the Cauchy property of `s` refine ⟨λ N, Sup (S N), S0, ub, metric.tendsto_at_top.2 (λ ε ε0, _)⟩, refine (metric.cauchy_seq_iff.1 hs (ε/2) (half_pos ε0)).imp (λ N hN n hn, _), rw [real.dist_0_eq_abs, abs_of_nonneg (S0 n)], refine lt_of_le_of_lt (cSup_le ⟨_, S0m _⟩ _) (half_lt_self ε0), rintro _ ⟨⟨m', n'⟩, ⟨hm', hn'⟩, rfl⟩, exact le_of_lt (hN _ _ (le_trans hn hm') (le_trans hn hn')) end, λ ⟨b, _, b_bound, b_lim⟩, cauchy_seq_of_le_tendsto_0 b b_bound b_lim⟩ end cauchy_seq /-- Pseudometric space structure pulled back by a function. -/ def pseudo_metric_space.induced {α β} (f : α → β) (m : pseudo_metric_space β) : pseudo_metric_space α := { dist := λ x y, dist (f x) (f y), dist_self := λ x, dist_self _, dist_comm := λ x y, dist_comm _ _, dist_triangle := λ x y z, dist_triangle _ _ _, edist := λ x y, edist (f x) (f y), edist_dist := λ x y, edist_dist _ _, to_uniform_space := uniform_space.comap f m.to_uniform_space, uniformity_dist := begin apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, dist (f x) (f y)), refine λ s, mem_comap.trans _, split; intro H, { rcases H with ⟨r, ru, rs⟩, rcases mem_uniformity_dist.1 ru with ⟨ε, ε0, hε⟩, refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h }, { rcases H with ⟨ε, ε0, hε⟩, exact ⟨_, dist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ } end } /-- Pull back a pseudometric space structure by a uniform inducing map. This is a version of `pseudo_metric_space.induced` useful in case if the domain already has a `uniform_space` structure. -/ def uniform_inducing.comap_pseudo_metric_space {α β} [uniform_space α] [pseudo_metric_space β] (f : α → β) (h : uniform_inducing f) : pseudo_metric_space α := (pseudo_metric_space.induced f ‹_›).replace_uniformity h.comap_uniformity.symm instance subtype.psudo_metric_space {α : Type*} {p : α → Prop} [t : pseudo_metric_space α] : pseudo_metric_space (subtype p) := pseudo_metric_space.induced coe t theorem subtype.pseudo_dist_eq {p : α → Prop} (x y : subtype p) : dist x y = dist (x : α) y := rfl section nnreal instance : pseudo_metric_space ℝ≥0 := by unfold nnreal; apply_instance lemma nnreal.dist_eq (a b : ℝ≥0) : dist a b = abs ((a:ℝ) - b) := rfl lemma nnreal.nndist_eq (a b : ℝ≥0) : nndist a b = max (a - b) (b - a) := begin wlog h : a ≤ b, { apply nnreal.coe_eq.1, rw [nnreal.sub_eq_zero h, max_eq_right (zero_le $ b - a), ← dist_nndist, nnreal.dist_eq, nnreal.coe_sub h, abs_eq_max_neg, neg_sub], apply max_eq_right, linarith [nnreal.coe_le_coe.2 h] }, rwa [nndist_comm, max_comm] end end nnreal section prod instance prod.pseudo_metric_space_max [pseudo_metric_space β] : pseudo_metric_space (α × β) := { dist := λ x y, max (dist x.1 y.1) (dist x.2 y.2), dist_self := λ x, by simp, dist_comm := λ x y, by simp [dist_comm], dist_triangle := λ x y z, max_le (le_trans (dist_triangle _ _ _) (add_le_add (le_max_left _ _) (le_max_left _ _))) (le_trans (dist_triangle _ _ _) (add_le_add (le_max_right _ _) (le_max_right _ _))), edist := λ x y, max (edist x.1 y.1) (edist x.2 y.2), edist_dist := assume x y, begin have : monotone ennreal.of_real := assume x y h, ennreal.of_real_le_of_real h, rw [edist_dist, edist_dist, ← this.map_max] end, uniformity_dist := begin refine uniformity_prod.trans _, simp only [uniformity_basis_dist.eq_binfi, comap_infi], rw ← infi_inf_eq, congr, funext, rw ← infi_inf_eq, congr, funext, simp [inf_principal, ext_iff, max_lt_iff] end, to_uniform_space := prod.uniform_space } lemma prod.dist_eq [pseudo_metric_space β] {x y : α × β} : dist x y = max (dist x.1 y.1) (dist x.2 y.2) := rfl theorem ball_prod_same [pseudo_metric_space β] (x : α) (y : β) (r : ℝ) : (ball x r).prod (ball y r) = ball (x, y) r := ext $ λ z, by simp [prod.dist_eq] theorem closed_ball_prod_same [pseudo_metric_space β] (x : α) (y : β) (r : ℝ) : (closed_ball x r).prod (closed_ball y r) = closed_ball (x, y) r := ext $ λ z, by simp [prod.dist_eq] end prod theorem uniform_continuous_dist : uniform_continuous (λp:α×α, dist p.1 p.2) := metric.uniform_continuous_iff.2 (λ ε ε0, ⟨ε/2, half_pos ε0, begin suffices, { intros p q h, cases p with p₁ p₂, cases q with q₁ q₂, cases max_lt_iff.1 h with h₁ h₂, clear h, dsimp at h₁ h₂ ⊢, rw real.dist_eq, refine abs_sub_lt_iff.2 ⟨_, _⟩, { revert p₁ p₂ q₁ q₂ h₁ h₂, exact this }, { apply this; rwa dist_comm } }, intros p₁ p₂ q₁ q₂ h₁ h₂, have := add_lt_add (abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₁ q₁ p₂) h₁)).1 (abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₂ q₂ q₁) h₂)).1, rwa [add_halves, dist_comm p₂, sub_add_sub_cancel, dist_comm q₂] at this end⟩) theorem uniform_continuous.dist [uniform_space β] {f g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λb, dist (f b) (g b)) := uniform_continuous_dist.comp (hf.prod_mk hg) @[continuity] theorem continuous_dist : continuous (λp:α×α, dist p.1 p.2) := uniform_continuous_dist.continuous @[continuity] theorem continuous.dist [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λb, dist (f b) (g b)) := continuous_dist.comp (hf.prod_mk hg : _) theorem filter.tendsto.dist {f g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, dist (f x) (g x)) x (𝓝 (dist a b)) := (continuous_dist.tendsto (a, b)).comp (hf.prod_mk_nhds hg) lemma nhds_comap_dist (a : α) : (𝓝 (0 : ℝ)).comap (λa', dist a' a) = 𝓝 a := by simp only [@nhds_eq_comap_uniformity α, metric.uniformity_eq_comap_nhds_zero, comap_comap, (∘), dist_comm] lemma tendsto_iff_dist_tendsto_zero {f : β → α} {x : filter β} {a : α} : (tendsto f x (𝓝 a)) ↔ (tendsto (λb, dist (f b) a) x (𝓝 0)) := by rw [← nhds_comap_dist a, tendsto_comap_iff] lemma uniform_continuous_nndist : uniform_continuous (λp:α×α, nndist p.1 p.2) := uniform_continuous_subtype_mk uniform_continuous_dist _ lemma uniform_continuous.nndist [uniform_space β] {f g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λ b, nndist (f b) (g b)) := uniform_continuous_nndist.comp (hf.prod_mk hg) lemma continuous_nndist : continuous (λp:α×α, nndist p.1 p.2) := uniform_continuous_nndist.continuous lemma continuous.nndist [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λb, nndist (f b) (g b)) := continuous_nndist.comp (hf.prod_mk hg : _) theorem filter.tendsto.nndist {f g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, nndist (f x) (g x)) x (𝓝 (nndist a b)) := (continuous_nndist.tendsto (a, b)).comp (hf.prod_mk_nhds hg) namespace metric variables {x y z : α} {ε ε₁ ε₂ : ℝ} {s : set α} theorem is_closed_ball : is_closed (closed_ball x ε) := is_closed_le (continuous_id.dist continuous_const) continuous_const lemma is_closed_sphere : is_closed (sphere x ε) := is_closed_eq (continuous_id.dist continuous_const) continuous_const @[simp] theorem closure_closed_ball : closure (closed_ball x ε) = closed_ball x ε := is_closed_ball.closure_eq theorem closure_ball_subset_closed_ball : closure (ball x ε) ⊆ closed_ball x ε := closure_minimal ball_subset_closed_ball is_closed_ball theorem frontier_ball_subset_sphere : frontier (ball x ε) ⊆ sphere x ε := frontier_lt_subset_eq (continuous_id.dist continuous_const) continuous_const theorem frontier_closed_ball_subset_sphere : frontier (closed_ball x ε) ⊆ sphere x ε := frontier_le_subset_eq (continuous_id.dist continuous_const) continuous_const theorem ball_subset_interior_closed_ball : ball x ε ⊆ interior (closed_ball x ε) := interior_maximal ball_subset_closed_ball is_open_ball /-- ε-characterization of the closure in pseudometric spaces-/ theorem mem_closure_iff {α : Type u} [pseudo_metric_space α] {s : set α} {a : α} : a ∈ closure s ↔ ∀ε>0, ∃b ∈ s, dist a b < ε := (mem_closure_iff_nhds_basis nhds_basis_ball).trans $ by simp only [mem_ball, dist_comm] lemma mem_closure_range_iff {α : Type u} [pseudo_metric_space α] {e : β → α} {a : α} : a ∈ closure (range e) ↔ ∀ε>0, ∃ k : β, dist a (e k) < ε := by simp only [mem_closure_iff, exists_range_iff] lemma mem_closure_range_iff_nat {α : Type u} [pseudo_metric_space α] {e : β → α} {a : α} : a ∈ closure (range e) ↔ ∀n : ℕ, ∃ k : β, dist a (e k) < 1 / ((n : ℝ) + 1) := (mem_closure_iff_nhds_basis nhds_basis_ball_inv_nat_succ).trans $ by simp only [mem_ball, dist_comm, exists_range_iff, forall_const] theorem mem_of_closed' {α : Type u} [pseudo_metric_space α] {s : set α} (hs : is_closed s) {a : α} : a ∈ s ↔ ∀ε>0, ∃b ∈ s, dist a b < ε := by simpa only [hs.closure_eq] using @mem_closure_iff _ _ s a end metric section pi open finset variables {π : β → Type*} [fintype β] [∀b, pseudo_metric_space (π b)] /-- A finite product of pseudometric spaces is a pseudometric space, with the sup distance. -/ instance pseudo_metric_space_pi : pseudo_metric_space (Πb, π b) := begin /- we construct the instance from the pseudoemetric space instance to avoid checking again that the uniformity is the same as the product uniformity, but we register nevertheless a nice formula for the distance -/ refine pseudo_emetric_space.to_pseudo_metric_space_of_dist (λf g, ((sup univ (λb, nndist (f b) (g b)) : ℝ≥0) : ℝ)) _ _, show ∀ (x y : Π (b : β), π b), edist x y ≠ ⊤, { assume x y, rw ← lt_top_iff_ne_top, have : (⊥ : ℝ≥0∞) < ⊤ := ennreal.coe_lt_top, simp [edist_pi_def, finset.sup_lt_iff this, edist_lt_top] }, show ∀ (x y : Π (b : β), π b), ↑(sup univ (λ (b : β), nndist (x b) (y b))) = ennreal.to_real (sup univ (λ (b : β), edist (x b) (y b))), { assume x y, simp only [edist_nndist], norm_cast } end lemma nndist_pi_def (f g : Πb, π b) : nndist f g = sup univ (λb, nndist (f b) (g b)) := subtype.eta _ _ lemma dist_pi_def (f g : Πb, π b) : dist f g = (sup univ (λb, nndist (f b) (g b)) : ℝ≥0) := rfl @[simp] lemma dist_pi_const [nonempty β] (a b : α) : dist (λ x : β, a) (λ _, b) = dist a b := by simpa only [dist_edist] using congr_arg ennreal.to_real (edist_pi_const a b) @[simp] lemma nndist_pi_const [nonempty β] (a b : α) : nndist (λ x : β, a) (λ _, b) = nndist a b := nnreal.eq $ dist_pi_const a b lemma dist_pi_lt_iff {f g : Πb, π b} {r : ℝ} (hr : 0 < r) : dist f g < r ↔ ∀b, dist (f b) (g b) < r := begin lift r to ℝ≥0 using hr.le, simp [dist_pi_def, finset.sup_lt_iff (show ⊥ < r, from hr)], end lemma dist_pi_le_iff {f g : Πb, π b} {r : ℝ} (hr : 0 ≤ r) : dist f g ≤ r ↔ ∀b, dist (f b) (g b) ≤ r := begin lift r to ℝ≥0 using hr, simp [nndist_pi_def] end lemma nndist_le_pi_nndist (f g : Πb, π b) (b : β) : nndist (f b) (g b) ≤ nndist f g := by { rw [nndist_pi_def], exact finset.le_sup (finset.mem_univ b) } lemma dist_le_pi_dist (f g : Πb, π b) (b : β) : dist (f b) (g b) ≤ dist f g := by simp only [dist_nndist, nnreal.coe_le_coe, nndist_le_pi_nndist f g b] /-- An open ball in a product space is a product of open balls. See also `metric.ball_pi'` for a version assuming `nonempty β` instead of `0 < r`. -/ lemma ball_pi (x : Πb, π b) {r : ℝ} (hr : 0 < r) : ball x r = set.pi univ (λ b, ball (x b) r) := by { ext p, simp [dist_pi_lt_iff hr] } /-- An open ball in a product space is a product of open balls. See also `metric.ball_pi` for a version assuming `0 < r` instead of `nonempty β`. -/ lemma ball_pi' [nonempty β] (x : Π b, π b) (r : ℝ) : ball x r = set.pi univ (λ b, ball (x b) r) := (lt_or_le 0 r).elim (ball_pi x) $ λ hr, by simp [ball_eq_empty.2 hr] /-- A closed ball in a product space is a product of closed balls. See also `metric.closed_ball_pi'` for a version assuming `nonempty β` instead of `0 ≤ r`. -/ lemma closed_ball_pi (x : Πb, π b) {r : ℝ} (hr : 0 ≤ r) : closed_ball x r = set.pi univ (λ b, closed_ball (x b) r) := by { ext p, simp [dist_pi_le_iff hr] } /-- A closed ball in a product space is a product of closed balls. See also `metric.closed_ball_pi` for a version assuming `0 ≤ r` instead of `nonempty β`. -/ lemma closed_ball_pi' [nonempty β] (x : Π b, π b) (r : ℝ) : closed_ball x r = set.pi univ (λ b, closed_ball (x b) r) := (le_or_lt 0 r).elim (closed_ball_pi x) $ λ hr, by simp [closed_ball_eq_empty.2 hr] end pi section compact /-- Any compact set in a pseudometric space can be covered by finitely many balls of a given positive radius -/ lemma finite_cover_balls_of_compact {α : Type u} [pseudo_metric_space α] {s : set α} (hs : is_compact s) {e : ℝ} (he : 0 < e) : ∃t ⊆ s, finite t ∧ s ⊆ ⋃x∈t, ball x e := begin apply hs.elim_finite_subcover_image, { simp [is_open_ball] }, { intros x xs, simp, exact ⟨x, ⟨xs, by simpa⟩⟩ } end alias finite_cover_balls_of_compact ← is_compact.finite_cover_balls end compact section proper_space open metric /-- A pseudometric space is proper if all closed balls are compact. -/ class proper_space (α : Type u) [pseudo_metric_space α] : Prop := (compact_ball : ∀x:α, ∀r, is_compact (closed_ball x r)) /-- In a proper pseudometric space, all spheres are compact. -/ lemma is_compact_sphere {α : Type*} [pseudo_metric_space α] [proper_space α] (x : α) (r : ℝ) : is_compact (sphere x r) := compact_of_is_closed_subset (proper_space.compact_ball x r) is_closed_sphere sphere_subset_closed_ball /-- In a proper pseudometric space, any sphere is a `compact_space` when considered as a subtype. -/ instance {α : Type*} [pseudo_metric_space α] [proper_space α] (x : α) (r : ℝ) : compact_space (sphere x r) := is_compact_iff_compact_space.mp (is_compact_sphere _ _) /-- A proper pseudo metric space is sigma compact, and therefore second countable. -/ @[priority 100] -- see Note [lower instance priority] instance second_countable_of_proper [proper_space α] : second_countable_topology α := begin -- We already have `sigma_compact_space_of_locally_compact_second_countable`, so we don't -- add an instance for `sigma_compact_space`. suffices : sigma_compact_space α, by exactI emetric.second_countable_of_sigma_compact α, rcases em (nonempty α) with ⟨⟨x⟩⟩|hn, { exact ⟨⟨λ n, closed_ball x n, λ n, proper_space.compact_ball _ _, Union_closed_ball_nat _⟩⟩ }, { exact ⟨⟨λ n, ∅, λ n, is_compact_empty, Union_eq_univ_iff.2 $ λ x, (hn ⟨x⟩).elim⟩⟩ } end lemma tendsto_dist_right_cocompact_at_top [proper_space α] (x : α) : tendsto (λ y, dist y x) (cocompact α) at_top := (has_basis_cocompact.tendsto_iff at_top_basis).2 $ λ r hr, ⟨closed_ball x r, proper_space.compact_ball x r, λ y hy, (not_le.1 $ mt mem_closed_ball.2 hy).le⟩ lemma tendsto_dist_left_cocompact_at_top [proper_space α] (x : α) : tendsto (dist x) (cocompact α) at_top := by simpa only [dist_comm] using tendsto_dist_right_cocompact_at_top x /-- If all closed balls of large enough radius are compact, then the space is proper. Especially useful when the lower bound for the radius is 0. -/ lemma proper_space_of_compact_closed_ball_of_le (R : ℝ) (h : ∀x:α, ∀r, R ≤ r → is_compact (closed_ball x r)) : proper_space α := ⟨begin assume x r, by_cases hr : R ≤ r, { exact h x r hr }, { have : closed_ball x r = closed_ball x R ∩ closed_ball x r, { symmetry, apply inter_eq_self_of_subset_right, exact closed_ball_subset_closed_ball (le_of_lt (not_le.1 hr)) }, rw this, exact (h x R (le_refl _)).inter_right is_closed_ball } end⟩ /- A compact pseudometric space is proper -/ @[priority 100] -- see Note [lower instance priority] instance proper_of_compact [compact_space α] : proper_space α := ⟨assume x r, is_closed_ball.is_compact⟩ /-- A proper space is locally compact -/ @[priority 100] -- see Note [lower instance priority] instance locally_compact_of_proper [proper_space α] : locally_compact_space α := locally_compact_space_of_has_basis (λ x, nhds_basis_closed_ball) $ λ x ε ε0, proper_space.compact_ball _ _ /-- A proper space is complete -/ @[priority 100] -- see Note [lower instance priority] instance complete_of_proper [proper_space α] : complete_space α := ⟨begin intros f hf, /- We want to show that the Cauchy filter `f` is converging. It suffices to find a closed ball (therefore compact by properness) where it is nontrivial. -/ obtain ⟨t, t_fset, ht⟩ : ∃ t ∈ f, ∀ x y ∈ t, dist x y < 1 := (metric.cauchy_iff.1 hf).2 1 zero_lt_one, rcases hf.1.nonempty_of_mem t_fset with ⟨x, xt⟩, have : closed_ball x 1 ∈ f := mem_of_superset t_fset (λ y yt, (ht y x yt xt).le), rcases (compact_iff_totally_bounded_complete.1 (proper_space.compact_ball x 1)).2 f hf (le_principal_iff.2 this) with ⟨y, -, hy⟩, exact ⟨y, hy⟩ end⟩ /-- A finite product of proper spaces is proper. -/ instance pi_proper_space {π : β → Type*} [fintype β] [∀b, pseudo_metric_space (π b)] [h : ∀b, proper_space (π b)] : proper_space (Πb, π b) := begin refine proper_space_of_compact_closed_ball_of_le 0 (λx r hr, _), rw closed_ball_pi _ hr, apply is_compact_univ_pi (λb, _), apply (h b).compact_ball end variables [proper_space α] {x : α} {r : ℝ} {s : set α} /-- If a nonempty ball in a proper space includes a closed set `s`, then there exists a nonempty ball with the same center and a strictly smaller radius that includes `s`. -/ lemma exists_pos_lt_subset_ball (hr : 0 < r) (hs : is_closed s) (h : s ⊆ ball x r) : ∃ r' ∈ Ioo 0 r, s ⊆ ball x r' := begin unfreezingI { rcases eq_empty_or_nonempty s with rfl|hne }, { exact ⟨r / 2, ⟨half_pos hr, half_lt_self hr⟩, empty_subset _⟩ }, have : is_compact s, from compact_of_is_closed_subset (proper_space.compact_ball x r) hs (subset.trans h ball_subset_closed_ball), obtain ⟨y, hys, hy⟩ : ∃ y ∈ s, s ⊆ closed_ball x (dist y x), from this.exists_forall_ge hne (continuous_id.dist continuous_const).continuous_on, have hyr : dist y x < r, from h hys, rcases exists_between hyr with ⟨r', hyr', hrr'⟩, exact ⟨r', ⟨dist_nonneg.trans_lt hyr', hrr'⟩, subset.trans hy $ closed_ball_subset_ball hyr'⟩ end /-- If a ball in a proper space includes a closed set `s`, then there exists a ball with the same center and a strictly smaller radius that includes `s`. -/ lemma exists_lt_subset_ball (hs : is_closed s) (h : s ⊆ ball x r) : ∃ r' < r, s ⊆ ball x r' := begin cases le_or_lt r 0 with hr hr, { rw [ball_eq_empty.2 hr, subset_empty_iff] at h, unfreezingI { subst s }, exact (no_bot r).imp (λ r' hr', ⟨hr', empty_subset _⟩) }, { exact (exists_pos_lt_subset_ball hr hs h).imp (λ r' hr', ⟨hr'.fst.2, hr'.snd⟩) } end end proper_space namespace metric section second_countable open topological_space /-- A pseudometric space is second countable if, for every `ε > 0`, there is a countable set which is `ε`-dense. -/ lemma second_countable_of_almost_dense_set (H : ∀ε > (0 : ℝ), ∃ s : set α, countable s ∧ (∀x, ∃y ∈ s, dist x y ≤ ε)) : second_countable_topology α := begin refine emetric.second_countable_of_almost_dense_set (λ ε ε0, _), rcases ennreal.lt_iff_exists_nnreal_btwn.1 ε0 with ⟨ε', ε'0, ε'ε⟩, choose s hsc y hys hyx using H ε' (by exact_mod_cast ε'0), refine ⟨s, hsc, bUnion_eq_univ_iff.2 (λ x, ⟨y x, hys _, le_trans _ ε'ε.le⟩)⟩, exact_mod_cast hyx x end end second_countable end metric lemma lebesgue_number_lemma_of_metric {s : set α} {ι} {c : ι → set α} (hs : is_compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) : ∃ δ > 0, ∀ x ∈ s, ∃ i, ball x δ ⊆ c i := let ⟨n, en, hn⟩ := lebesgue_number_lemma hs hc₁ hc₂, ⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 en in ⟨δ, δ0, assume x hx, let ⟨i, hi⟩ := hn x hx in ⟨i, assume y hy, hi (hδ (mem_ball'.mp hy))⟩⟩ lemma lebesgue_number_lemma_of_metric_sUnion {s : set α} {c : set (set α)} (hs : is_compact s) (hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) : ∃ δ > 0, ∀ x ∈ s, ∃ t ∈ c, ball x δ ⊆ t := by rw sUnion_eq_Union at hc₂; simpa using lebesgue_number_lemma_of_metric hs (by simpa) hc₂ namespace metric /-- Boundedness of a subset of a pseudometric space. We formulate the definition to work even in the empty space. -/ def bounded (s : set α) : Prop := ∃C, ∀x y ∈ s, dist x y ≤ C section bounded variables {x : α} {s t : set α} {r : ℝ} @[simp] lemma bounded_empty : bounded (∅ : set α) := ⟨0, by simp⟩ lemma bounded_iff_mem_bounded : bounded s ↔ ∀ x ∈ s, bounded s := ⟨λ h _ _, h, λ H, s.eq_empty_or_nonempty.elim (λ hs, hs.symm ▸ bounded_empty) (λ ⟨x, hx⟩, H x hx)⟩ /-- Subsets of a bounded set are also bounded -/ lemma bounded.subset (incl : s ⊆ t) : bounded t → bounded s := Exists.imp $ λ C hC x y hx hy, hC x y (incl hx) (incl hy) /-- Closed balls are bounded -/ lemma bounded_closed_ball : bounded (closed_ball x r) := ⟨r + r, λ y z hy hz, begin simp only [mem_closed_ball] at *, calc dist y z ≤ dist y x + dist z x : dist_triangle_right _ _ _ ... ≤ r + r : add_le_add hy hz end⟩ /-- Open balls are bounded -/ lemma bounded_ball : bounded (ball x r) := bounded_closed_ball.subset ball_subset_closed_ball /-- Given a point, a bounded subset is included in some ball around this point -/ lemma bounded_iff_subset_ball (c : α) : bounded s ↔ ∃r, s ⊆ closed_ball c r := begin split; rintro ⟨C, hC⟩, { cases s.eq_empty_or_nonempty with h h, { subst s, exact ⟨0, by simp⟩ }, { rcases h with ⟨x, hx⟩, exact ⟨C + dist x c, λ y hy, calc dist y c ≤ dist y x + dist x c : dist_triangle _ _ _ ... ≤ C + dist x c : add_le_add_right (hC y x hy hx) _⟩ } }, { exact bounded_closed_ball.subset hC } end lemma bounded.subset_ball (h : bounded s) (c : α) : ∃ r, s ⊆ closed_ball c r := (bounded_iff_subset_ball c).1 h lemma bounded_closure_of_bounded (h : bounded s) : bounded (closure s) := let ⟨C, h⟩ := h in ⟨C, λ a b ha hb, (is_closed_le' C).closure_subset $ map_mem_closure2 continuous_dist ha hb h⟩ alias bounded_closure_of_bounded ← metric.bounded.closure @[simp] lemma bounded_closure_iff : bounded (closure s) ↔ bounded s := ⟨λ h, h.subset subset_closure, λ h, h.closure⟩ /-- The union of two bounded sets is bounded iff each of the sets is bounded -/ @[simp] lemma bounded_union : bounded (s ∪ t) ↔ bounded s ∧ bounded t := ⟨λh, ⟨h.subset (by simp), h.subset (by simp)⟩, begin rintro ⟨hs, ht⟩, refine bounded_iff_mem_bounded.2 (λ x _, _), rw bounded_iff_subset_ball x at hs ht ⊢, rcases hs with ⟨Cs, hCs⟩, rcases ht with ⟨Ct, hCt⟩, exact ⟨max Cs Ct, union_subset (subset.trans hCs $ closed_ball_subset_closed_ball $ le_max_left _ _) (subset.trans hCt $ closed_ball_subset_closed_ball $ le_max_right _ _)⟩, end⟩ /-- A finite union of bounded sets is bounded -/ lemma bounded_bUnion {I : set β} {s : β → set α} (H : finite I) : bounded (⋃i∈I, s i) ↔ ∀i ∈ I, bounded (s i) := finite.induction_on H (by simp) $ λ x I _ _ IH, by simp [or_imp_distrib, forall_and_distrib, IH] /-- A totally bounded set is bounded -/ lemma _root_.totally_bounded.bounded {s : set α} (h : totally_bounded s) : bounded s := -- We cover the totally bounded set by finitely many balls of radius 1, -- and then argue that a finite union of bounded sets is bounded let ⟨t, fint, subs⟩ := (totally_bounded_iff.mp h) 1 zero_lt_one in bounded.subset subs $ (bounded_bUnion fint).2 $ λ i hi, bounded_ball /-- A compact set is bounded -/ lemma _root_.is_compact.bounded {s : set α} (h : is_compact s) : bounded s := -- A compact set is totally bounded, thus bounded h.totally_bounded.bounded /-- A finite set is bounded -/ lemma bounded_of_finite {s : set α} (h : finite s) : bounded s := h.is_compact.bounded alias bounded_of_finite ← set.finite.bounded /-- A singleton is bounded -/ lemma bounded_singleton {x : α} : bounded ({x} : set α) := bounded_of_finite $ finite_singleton _ /-- Characterization of the boundedness of the range of a function -/ lemma bounded_range_iff {f : β → α} : bounded (range f) ↔ ∃C, ∀x y, dist (f x) (f y) ≤ C := exists_congr $ λ C, ⟨ λ H x y, H _ _ ⟨x, rfl⟩ ⟨y, rfl⟩, by rintro H _ _ ⟨x, rfl⟩ ⟨y, rfl⟩; exact H x y⟩ /-- In a compact space, all sets are bounded -/ lemma bounded_of_compact_space [compact_space α] : bounded s := compact_univ.bounded.subset (subset_univ _) /-- The Heine–Borel theorem: In a proper space, a set is compact if and only if it is closed and bounded -/ lemma compact_iff_closed_bounded [t2_space α] [proper_space α] : is_compact s ↔ is_closed s ∧ bounded s := ⟨λ h, ⟨h.is_closed, h.bounded⟩, begin rintro ⟨hc, hb⟩, cases s.eq_empty_or_nonempty with h h, {simp [h, is_compact_empty]}, rcases h with ⟨x, hx⟩, rcases (bounded_iff_subset_ball x).1 hb with ⟨r, hr⟩, exact compact_of_is_closed_subset (proper_space.compact_ball x r) hc hr end⟩ section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] [order_topology α] lemma bounded_Icc (a b : α) : bounded (Icc a b) := (totally_bounded_Icc a b).bounded lemma bounded_Ico (a b : α) : bounded (Ico a b) := (totally_bounded_Ico a b).bounded lemma bounded_Ioc (a b : α) : bounded (Ioc a b) := (totally_bounded_Ioc a b).bounded lemma bounded_Ioo (a b : α) : bounded (Ioo a b) := (totally_bounded_Ioo a b).bounded /-- In a pseudo metric space with a conditionally complete linear order such that the order and the metric structure give the same topology, any order-bounded set is metric-bounded. -/ lemma bounded_of_bdd_above_of_bdd_below {s : set α} (h₁ : bdd_above s) (h₂ : bdd_below s) : bounded s := let ⟨u, hu⟩ := h₁, ⟨l, hl⟩ := h₂ in bounded.subset (λ x hx, mem_Icc.mpr ⟨hl hx, hu hx⟩) (bounded_Icc l u) end conditionally_complete_linear_order end bounded section diam variables {s : set α} {x y z : α} /-- The diameter of a set in a metric space. To get controllable behavior even when the diameter should be infinite, we express it in terms of the emetric.diameter -/ def diam (s : set α) : ℝ := ennreal.to_real (emetric.diam s) /-- The diameter of a set is always nonnegative -/ lemma diam_nonneg : 0 ≤ diam s := ennreal.to_real_nonneg lemma diam_subsingleton (hs : s.subsingleton) : diam s = 0 := by simp only [diam, emetric.diam_subsingleton hs, ennreal.zero_to_real] /-- The empty set has zero diameter -/ @[simp] lemma diam_empty : diam (∅ : set α) = 0 := diam_subsingleton subsingleton_empty /-- A singleton has zero diameter -/ @[simp] lemma diam_singleton : diam ({x} : set α) = 0 := diam_subsingleton subsingleton_singleton -- Does not work as a simp-lemma, since {x, y} reduces to (insert y {x}) lemma diam_pair : diam ({x, y} : set α) = dist x y := by simp only [diam, emetric.diam_pair, dist_edist] -- Does not work as a simp-lemma, since {x, y, z} reduces to (insert z (insert y {x})) lemma diam_triple : metric.diam ({x, y, z} : set α) = max (max (dist x y) (dist x z)) (dist y z) := begin simp only [metric.diam, emetric.diam_triple, dist_edist], rw [ennreal.to_real_max, ennreal.to_real_max]; apply_rules [ne_of_lt, edist_lt_top, max_lt] end /-- If the distance between any two points in a set is bounded by some constant `C`, then `ennreal.of_real C` bounds the emetric diameter of this set. -/ lemma ediam_le_of_forall_dist_le {C : ℝ} (h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) : emetric.diam s ≤ ennreal.of_real C := emetric.diam_le $ λ x hx y hy, (edist_dist x y).symm ▸ ennreal.of_real_le_of_real (h x hx y hy) /-- If the distance between any two points in a set is bounded by some non-negative constant, this constant bounds the diameter. -/ lemma diam_le_of_forall_dist_le {C : ℝ} (h₀ : 0 ≤ C) (h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) : diam s ≤ C := ennreal.to_real_le_of_le_of_real h₀ (ediam_le_of_forall_dist_le h) /-- If the distance between any two points in a nonempty set is bounded by some constant, this constant bounds the diameter. -/ lemma diam_le_of_forall_dist_le_of_nonempty (hs : s.nonempty) {C : ℝ} (h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) : diam s ≤ C := have h₀ : 0 ≤ C, from let ⟨x, hx⟩ := hs in le_trans dist_nonneg (h x hx x hx), diam_le_of_forall_dist_le h₀ h /-- The distance between two points in a set is controlled by the diameter of the set. -/ lemma dist_le_diam_of_mem' (h : emetric.diam s ≠ ⊤) (hx : x ∈ s) (hy : y ∈ s) : dist x y ≤ diam s := begin rw [diam, dist_edist], rw ennreal.to_real_le_to_real (edist_ne_top _ _) h, exact emetric.edist_le_diam_of_mem hx hy end /-- Characterize the boundedness of a set in terms of the finiteness of its emetric.diameter. -/ lemma bounded_iff_ediam_ne_top : bounded s ↔ emetric.diam s ≠ ⊤ := iff.intro (λ ⟨C, hC⟩, ne_top_of_le_ne_top ennreal.of_real_ne_top (ediam_le_of_forall_dist_le $ λ x hx y hy, hC x y hx hy)) (λ h, ⟨diam s, λ x y hx hy, dist_le_diam_of_mem' h hx hy⟩) lemma bounded.ediam_ne_top (h : bounded s) : emetric.diam s ≠ ⊤ := bounded_iff_ediam_ne_top.1 h /-- The distance between two points in a set is controlled by the diameter of the set. -/ lemma dist_le_diam_of_mem (h : bounded s) (hx : x ∈ s) (hy : y ∈ s) : dist x y ≤ diam s := dist_le_diam_of_mem' h.ediam_ne_top hx hy lemma ediam_of_unbounded (h : ¬(bounded s)) : emetric.diam s = ∞ := by rwa [bounded_iff_ediam_ne_top, not_not] at h /-- An unbounded set has zero diameter. If you would prefer to get the value ∞, use `emetric.diam`. This lemma makes it possible to avoid side conditions in some situations -/ lemma diam_eq_zero_of_unbounded (h : ¬(bounded s)) : diam s = 0 := by rw [diam, ediam_of_unbounded h, ennreal.top_to_real] /-- If `s ⊆ t`, then the diameter of `s` is bounded by that of `t`, provided `t` is bounded. -/ lemma diam_mono {s t : set α} (h : s ⊆ t) (ht : bounded t) : diam s ≤ diam t := begin unfold diam, rw ennreal.to_real_le_to_real (bounded.subset h ht).ediam_ne_top ht.ediam_ne_top, exact emetric.diam_mono h end /-- The diameter of a union is controlled by the sum of the diameters, and the distance between any two points in each of the sets. This lemma is true without any side condition, since it is obviously true if `s ∪ t` is unbounded. -/ lemma diam_union {t : set α} (xs : x ∈ s) (yt : y ∈ t) : diam (s ∪ t) ≤ diam s + dist x y + diam t := begin by_cases H : bounded (s ∪ t), { have hs : bounded s, from H.subset (subset_union_left _ _), have ht : bounded t, from H.subset (subset_union_right _ _), rw [bounded_iff_ediam_ne_top] at H hs ht, rw [dist_edist, diam, diam, diam, ← ennreal.to_real_add, ← ennreal.to_real_add, ennreal.to_real_le_to_real]; repeat { apply ennreal.add_ne_top.2; split }; try { assumption }; try { apply edist_ne_top }, exact emetric.diam_union xs yt }, { rw [diam_eq_zero_of_unbounded H], apply_rules [add_nonneg, diam_nonneg, dist_nonneg] } end /-- If two sets intersect, the diameter of the union is bounded by the sum of the diameters. -/ lemma diam_union' {t : set α} (h : (s ∩ t).nonempty) : diam (s ∪ t) ≤ diam s + diam t := begin rcases h with ⟨x, ⟨xs, xt⟩⟩, simpa using diam_union xs xt end /-- The diameter of a closed ball of radius `r` is at most `2 r`. -/ lemma diam_closed_ball {r : ℝ} (h : 0 ≤ r) : diam (closed_ball x r) ≤ 2 * r := diam_le_of_forall_dist_le (mul_nonneg (le_of_lt zero_lt_two) h) $ λa ha b hb, calc dist a b ≤ dist a x + dist b x : dist_triangle_right _ _ _ ... ≤ r + r : add_le_add ha hb ... = 2 * r : by simp [mul_two, mul_comm] /-- The diameter of a ball of radius `r` is at most `2 r`. -/ lemma diam_ball {r : ℝ} (h : 0 ≤ r) : diam (ball x r) ≤ 2 * r := le_trans (diam_mono ball_subset_closed_ball bounded_closed_ball) (diam_closed_ball h) end diam end metric lemma comap_dist_right_at_top_le_cocompact (x : α) : comap (λ y, dist y x) at_top ≤ cocompact α := begin refine filter.has_basis_cocompact.ge_iff.2 (λ s hs, mem_comap.2 _), rcases hs.bounded.subset_ball x with ⟨r, hr⟩, exact ⟨Ioi r, Ioi_mem_at_top r, λ y hy hys, (mem_closed_ball.1 $ hr hys).not_lt hy⟩ end lemma comap_dist_left_at_top_le_cocompact (x : α) : comap (dist x) at_top ≤ cocompact α := by simpa only [dist_comm _ x] using comap_dist_right_at_top_le_cocompact x lemma comap_dist_right_at_top_eq_cocompact [proper_space α] (x : α) : comap (λ y, dist y x) at_top = cocompact α := (comap_dist_right_at_top_le_cocompact x).antisymm $ (tendsto_dist_right_cocompact_at_top x).le_comap lemma comap_dist_left_at_top_eq_cocompact [proper_space α] (x : α) : comap (dist x) at_top = cocompact α := (comap_dist_left_at_top_le_cocompact x).antisymm $ (tendsto_dist_left_cocompact_at_top x).le_comap lemma tendsto_cocompact_of_tendsto_dist_comp_at_top {f : β → α} {l : filter β} (x : α) (h : tendsto (λ y, dist (f y) x) l at_top) : tendsto f l (cocompact α) := by { refine tendsto.mono_right _ (comap_dist_right_at_top_le_cocompact x), rwa tendsto_comap_iff } namespace int open metric /-- Under the coercion from `ℤ` to `ℝ`, inverse images of compact sets are finite. -/ lemma tendsto_coe_cofinite : tendsto (coe : ℤ → ℝ) cofinite (cocompact ℝ) := begin refine tendsto_cocompact_of_tendsto_dist_comp_at_top (0 : ℝ) _, simp only [filter.tendsto_at_top, eventually_cofinite, not_le, ← mem_ball], change ∀ r : ℝ, finite (coe ⁻¹' (ball (0 : ℝ) r)), simp [real.ball_eq, Ioo_ℤ_finite] end end int /-- We now define `metric_space`, extending `pseudo_metric_space`. -/ class metric_space (α : Type u) extends pseudo_metric_space α : Type u := (eq_of_dist_eq_zero : ∀ {x y : α}, dist x y = 0 → x = y) /-- Construct a metric space structure whose underlying topological space structure (definitionally) agrees which a pre-existing topology which is compatible with a given distance function. -/ def metric_space.of_metrizable {α : Type*} [topological_space α] (dist : α → α → ℝ) (dist_self : ∀ x : α, dist x x = 0) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) (H : ∀ s : set α, is_open s ↔ ∀ x ∈ s, ∃ ε > 0, ∀ y, dist x y < ε → y ∈ s) (eq_of_dist_eq_zero : ∀ x y : α, dist x y = 0 → x = y) : metric_space α := { eq_of_dist_eq_zero := eq_of_dist_eq_zero, ..pseudo_metric_space.of_metrizable dist dist_self dist_comm dist_triangle H } variables {γ : Type w} [metric_space γ] theorem eq_of_dist_eq_zero {x y : γ} : dist x y = 0 → x = y := metric_space.eq_of_dist_eq_zero @[simp] theorem dist_eq_zero {x y : γ} : dist x y = 0 ↔ x = y := iff.intro eq_of_dist_eq_zero (assume : x = y, this ▸ dist_self _) @[simp] theorem zero_eq_dist {x y : γ} : 0 = dist x y ↔ x = y := by rw [eq_comm, dist_eq_zero] theorem dist_ne_zero {x y : γ} : dist x y ≠ 0 ↔ x ≠ y := by simpa only [not_iff_not] using dist_eq_zero @[simp] theorem dist_le_zero {x y : γ} : dist x y ≤ 0 ↔ x = y := by simpa [le_antisymm_iff, dist_nonneg] using @dist_eq_zero _ _ x y @[simp] theorem dist_pos {x y : γ} : 0 < dist x y ↔ x ≠ y := by simpa only [not_le] using not_congr dist_le_zero theorem eq_of_forall_dist_le {x y : γ} (h : ∀ ε > 0, dist x y ≤ ε) : x = y := eq_of_dist_eq_zero (eq_of_le_of_forall_le_of_dense dist_nonneg h) /--Deduce the equality of points with the vanishing of the nonnegative distance-/ theorem eq_of_nndist_eq_zero {x y : γ} : nndist x y = 0 → x = y := by simp only [← nnreal.eq_iff, ← dist_nndist, imp_self, nnreal.coe_zero, dist_eq_zero] /--Characterize the equality of points with the vanishing of the nonnegative distance-/ @[simp] theorem nndist_eq_zero {x y : γ} : nndist x y = 0 ↔ x = y := by simp only [← nnreal.eq_iff, ← dist_nndist, imp_self, nnreal.coe_zero, dist_eq_zero] @[simp] theorem zero_eq_nndist {x y : γ} : 0 = nndist x y ↔ x = y := by simp only [← nnreal.eq_iff, ← dist_nndist, imp_self, nnreal.coe_zero, zero_eq_dist] namespace metric variables {x : γ} {s : set γ} @[simp] lemma closed_ball_zero : closed_ball x 0 = {x} := set.ext $ λ y, dist_le_zero /-- A map between metric spaces is a uniform embedding if and only if the distance between `f x` and `f y` is controlled in terms of the distance between `x` and `y` and conversely. -/ theorem uniform_embedding_iff' [metric_space β] {f : γ → β} : uniform_embedding f ↔ (∀ ε > 0, ∃ δ > 0, ∀ {a b : γ}, dist a b < δ → dist (f a) (f b) < ε) ∧ (∀ δ > 0, ∃ ε > 0, ∀ {a b : γ}, dist (f a) (f b) < ε → dist a b < δ) := begin split, { assume h, exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1, (uniform_embedding_iff.1 h).2.2⟩ }, { rintros ⟨h₁, h₂⟩, refine uniform_embedding_iff.2 ⟨_, uniform_continuous_iff.2 h₁, h₂⟩, assume x y hxy, have : dist x y ≤ 0, { refine le_of_forall_lt' (λδ δpos, _), rcases h₂ δ δpos with ⟨ε, εpos, hε⟩, have : dist (f x) (f y) < ε, by simpa [hxy], exact hε this }, simpa using this } end @[priority 100] -- see Note [lower instance priority] instance metric_space.to_separated : separated_space γ := separated_def.2 $ λ x y h, eq_of_forall_dist_le $ λ ε ε0, le_of_lt (h _ (dist_mem_uniformity ε0)) /-- If a `pseudo_metric_space` is separated, then it is a `metric_space`. -/ def of_t2_pseudo_metric_space {α : Type*} [pseudo_metric_space α] (h : separated_space α) : metric_space α := { eq_of_dist_eq_zero := λ x y hdist, begin refine separated_def.1 h x y (λ s hs, _), obtain ⟨ε, hε, H⟩ := mem_uniformity_dist.1 hs, exact H (show dist x y < ε, by rwa [hdist]) end ..‹pseudo_metric_space α› } /-- A metric space induces an emetric space -/ @[priority 100] -- see Note [lower instance priority] instance metric_space.to_emetric_space : emetric_space γ := { eq_of_edist_eq_zero := assume x y h, by simpa [edist_dist] using h, ..pseudo_metric_space.to_pseudo_emetric_space, } end metric /-- Build a new metric space from an old one where the bundled uniform structure is provably (but typically non-definitionaly) equal to some given uniform structure. See Note [forgetful inheritance]. -/ def metric_space.replace_uniformity {γ} [U : uniform_space γ] (m : metric_space γ) (H : @uniformity _ U = @uniformity _ emetric_space.to_uniform_space') : metric_space γ := { eq_of_dist_eq_zero := @eq_of_dist_eq_zero _ _, ..pseudo_metric_space.replace_uniformity m.to_pseudo_metric_space H, } /-- One gets a metric space from an emetric space if the edistance is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the uniformity are defeq in the metric space and the emetric space. In this definition, the distance is given separately, to be able to prescribe some expression which is not defeq to the push-forward of the edistance to reals. -/ def emetric_space.to_metric_space_of_dist {α : Type u} [e : emetric_space α] (dist : α → α → ℝ) (edist_ne_top : ∀x y: α, edist x y ≠ ⊤) (h : ∀x y, dist x y = ennreal.to_real (edist x y)) : metric_space α := { dist := dist, eq_of_dist_eq_zero := λx y hxy, by simpa [h, ennreal.to_real_eq_zero_iff, edist_ne_top x y] using hxy, ..pseudo_emetric_space.to_pseudo_metric_space_of_dist dist edist_ne_top h, } /-- One gets a metric space from an emetric space if the edistance is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the uniformity are defeq in the metric space and the emetric space. -/ def emetric_space.to_metric_space {α : Type u} [e : emetric_space α] (h : ∀x y: α, edist x y ≠ ⊤) : metric_space α := emetric_space.to_metric_space_of_dist (λx y, ennreal.to_real (edist x y)) h (λx y, rfl) /-- Metric space structure pulled back by an injective function. Injectivity is necessary to ensure that `dist x y = 0` only if `x = y`. -/ def metric_space.induced {γ β} (f : γ → β) (hf : function.injective f) (m : metric_space β) : metric_space γ := { eq_of_dist_eq_zero := λ x y h, hf (dist_eq_zero.1 h), ..pseudo_metric_space.induced f m.to_pseudo_metric_space } /-- Pull back a metric space structure by a uniform embedding. This is a version of `metric_space.induced` useful in case if the domain already has a `uniform_space` structure. -/ def uniform_embedding.comap_metric_space {α β} [uniform_space α] [metric_space β] (f : α → β) (h : uniform_embedding f) : metric_space α := (metric_space.induced f h.inj ‹_›).replace_uniformity h.comap_uniformity.symm instance subtype.metric_space {α : Type*} {p : α → Prop} [t : metric_space α] : metric_space (subtype p) := metric_space.induced coe (λ x y, subtype.ext) t theorem subtype.dist_eq {p : α → Prop} (x y : subtype p) : dist x y = dist (x : α) y := rfl instance : metric_space empty := { dist := λ _ _, 0, dist_self := λ _, rfl, dist_comm := λ _ _, rfl, eq_of_dist_eq_zero := λ _ _ _, subsingleton.elim _ _, dist_triangle := λ _ _ _, show (0:ℝ) ≤ 0 + 0, by rw add_zero, } instance : metric_space punit := { dist := λ _ _, 0, dist_self := λ _, rfl, dist_comm := λ _ _, rfl, eq_of_dist_eq_zero := λ _ _ _, subsingleton.elim _ _, dist_triangle := λ _ _ _, show (0:ℝ) ≤ 0 + 0, by rw add_zero, } section real /-- Instantiate the reals as a metric space. -/ instance real.metric_space : metric_space ℝ := { eq_of_dist_eq_zero := λ x y h, by simpa [dist, sub_eq_zero] using h, ..real.pseudo_metric_space } end real section nnreal instance : metric_space ℝ≥0 := subtype.metric_space end nnreal section prod instance prod.metric_space_max [metric_space β] : metric_space (γ × β) := { eq_of_dist_eq_zero := λ x y h, begin cases max_le_iff.1 (le_of_eq h) with h₁ h₂, exact prod.ext_iff.2 ⟨dist_le_zero.1 h₁, dist_le_zero.1 h₂⟩ end, ..prod.pseudo_metric_space_max, } end prod section pi open finset variables {π : β → Type*} [fintype β] [∀b, metric_space (π b)] /-- A finite product of metric spaces is a metric space, with the sup distance. -/ instance metric_space_pi : metric_space (Πb, π b) := /- we construct the instance from the emetric space instance to avoid checking again that the uniformity is the same as the product uniformity, but we register nevertheless a nice formula for the distance -/ { eq_of_dist_eq_zero := assume f g eq0, begin have eq1 : edist f g = 0 := by simp only [edist_dist, eq0, ennreal.of_real_zero], have eq2 : sup univ (λ (b : β), edist (f b) (g b)) ≤ 0 := le_of_eq eq1, simp only [finset.sup_le_iff] at eq2, exact (funext $ assume b, edist_le_zero.1 $ eq2 b $ mem_univ b) end, ..pseudo_metric_space_pi } end pi namespace metric section second_countable open topological_space /-- A metric space space is second countable if one can reconstruct up to any `ε>0` any element of the space from countably many data. -/ lemma second_countable_of_countable_discretization {α : Type u} [metric_space α] (H : ∀ε > (0 : ℝ), ∃ (β : Type*) (_ : encodable β) (F : α → β), ∀x y, F x = F y → dist x y ≤ ε) : second_countable_topology α := begin cases (univ : set α).eq_empty_or_nonempty with hs hs, { haveI : compact_space α := ⟨by rw hs; exact is_compact_empty⟩, by apply_instance }, rcases hs with ⟨x0, hx0⟩, letI : inhabited α := ⟨x0⟩, refine second_countable_of_almost_dense_set (λε ε0, _), rcases H ε ε0 with ⟨β, fβ, F, hF⟩, resetI, let Finv := function.inv_fun F, refine ⟨range Finv, ⟨countable_range _, λx, _⟩⟩, let x' := Finv (F x), have : F x' = F x := function.inv_fun_eq ⟨x, rfl⟩, exact ⟨x', mem_range_self _, hF _ _ this.symm⟩ end end second_countable end metric section eq_rel /-- The canonical equivalence relation on a pseudometric space. -/ def pseudo_metric.dist_setoid (α : Type u) [pseudo_metric_space α] : setoid α := setoid.mk (λx y, dist x y = 0) begin unfold equivalence, repeat { split }, { exact pseudo_metric_space.dist_self }, { assume x y h, rwa pseudo_metric_space.dist_comm }, { assume x y z hxy hyz, refine le_antisymm _ dist_nonneg, calc dist x z ≤ dist x y + dist y z : pseudo_metric_space.dist_triangle _ _ _ ... = 0 + 0 : by rw [hxy, hyz] ... = 0 : by simp } end local attribute [instance] pseudo_metric.dist_setoid /-- The canonical quotient of a pseudometric space, identifying points at distance `0`. -/ @[reducible] definition pseudo_metric_quot (α : Type u) [pseudo_metric_space α] : Type* := quotient (pseudo_metric.dist_setoid α) instance has_dist_metric_quot {α : Type u} [pseudo_metric_space α] : has_dist (pseudo_metric_quot α) := { dist := quotient.lift₂ (λp q : α, dist p q) begin assume x y x' y' hxx' hyy', have Hxx' : dist x x' = 0 := hxx', have Hyy' : dist y y' = 0 := hyy', have A : dist x y ≤ dist x' y' := calc dist x y ≤ dist x x' + dist x' y : pseudo_metric_space.dist_triangle _ _ _ ... = dist x' y : by simp [Hxx'] ... ≤ dist x' y' + dist y' y : pseudo_metric_space.dist_triangle _ _ _ ... = dist x' y' : by simp [pseudo_metric_space.dist_comm, Hyy'], have B : dist x' y' ≤ dist x y := calc dist x' y' ≤ dist x' x + dist x y' : pseudo_metric_space.dist_triangle _ _ _ ... = dist x y' : by simp [pseudo_metric_space.dist_comm, Hxx'] ... ≤ dist x y + dist y y' : pseudo_metric_space.dist_triangle _ _ _ ... = dist x y : by simp [Hyy'], exact le_antisymm A B end } lemma pseudo_metric_quot_dist_eq {α : Type u} [pseudo_metric_space α] (p q : α) : dist ⟦p⟧ ⟦q⟧ = dist p q := rfl instance metric_space_quot {α : Type u} [pseudo_metric_space α] : metric_space (pseudo_metric_quot α) := { dist_self := begin refine quotient.ind (λy, _), exact pseudo_metric_space.dist_self _ end, eq_of_dist_eq_zero := λxc yc, by exact quotient.induction_on₂ xc yc (λx y H, quotient.sound H), dist_comm := λxc yc, quotient.induction_on₂ xc yc (λx y, pseudo_metric_space.dist_comm _ _), dist_triangle := λxc yc zc, quotient.induction_on₃ xc yc zc (λx y z, pseudo_metric_space.dist_triangle _ _ _) } end eq_rel
de1bcfce04117190c03b65688625c3f1eb190a33
6b45072eb2b3db3ecaace2a7a0241ce81f815787
/tools/tactic/examples.lean
573469a11c2994e55bec152c4be6a220728f9160
[]
no_license
avigad/library_dev
27b47257382667b5eb7e6476c4f5b0d685dd3ddc
9d8ac7c7798ca550874e90fed585caad030bbfac
refs/heads/master
1,610,452,468,791
1,500,712,839,000
1,500,713,478,000
69,311,142
1
0
null
1,474,942,903,000
1,474,942,902,000
null
UTF-8
Lean
false
false
1,694
lean
open tactic universe u variable {α : Type} example (s t u : set ℕ) (h : s ⊆ t ∩ u) (h' : u ⊆ s) : u ⊆ s → true := begin dunfold has_subset.subset has_inter.inter at *, -- trace_state, intro1, triv end example (s t u : set ℕ) (h : s ⊆ t ∩ u) (h' : u ⊆ s) : u ⊆ s → true := begin delta has_subset.subset has_inter.inter at *, -- trace_state, intro1, triv end example (x y z : ℕ) (h'' : true) (h : 0 + y = x) (h' : 0 + y = z) : x = z + 0 := begin simp at *, -- trace_state, rw [←h, ←h'] end example (x y z : ℕ) (h'' : true) (h : 0 + y = x) (h' : 0 + y = z) : x = z + 0 := begin simp at *, simp [h] at h', simp [*] end def my_id (x : α) := x def my_id_def (x : α) : my_id x = x := rfl example (x y z : ℕ) (h'' : true) (h : 0 + my_id y = x) (h' : 0 + y = z) : x = z + 0 := begin simp [my_id_def] at *, simp [h] at h', simp [*] end @[simp] lemma mem_set_of {a : α} {p : α → Prop} : a ∈ {a | p a} = p a := rfl -- TODO: write a tactic to unfold specific instances of generic notation? theorem subset_def {s t : set α} : (s ⊆ t) = ∀ x, x ∈ s → x ∈ t := rfl theorem union_def {s₁ s₂ : set α} : s₁ ∪ s₂ = {a | a ∈ s₁ ∨ a ∈ s₂} := rfl theorem inter_def {s₁ s₂ : set α} : s₁ ∩ s₂ = {a | a ∈ s₁ ∧ a ∈ s₂} := rfl theorem union_subset {s t r : set α} (sr : s ⊆ r) (tr : t ⊆ r) : s ∪ t ⊆ r := begin dsimp [subset_def, union_def] at *, intros x h, cases h; back_chaining_using_hs end theorem subset_inter {s t r : set α} (rs : r ⊆ s) (rt : r ⊆ t) : r ⊆ s ∩ t := begin dsimp [subset_def, inter_def] at *, intros x h, split; back_chaining_using_hs end
a53c4a71c8d7f82c4610e77e0d9e3ed226dea982
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/number_theory/dioph.lean
7cb13e17d1d05338cc57fe8432ba2f8d2467d1b5
[ "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
26,546
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.fin.fin2 import data.pfun import data.vector3 import number_theory.pell_matiyasevic /-! # Diophantine functions and Matiyasevic's theorem > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Hilbert's tenth problem asked whether there exists an algorithm which for a given integer polynomial determines whether this polynomial has integer solutions. It was answered in the negative in 1970, the final step being completed by Matiyasevic who showed that the power function is Diophantine. Here a function is called Diophantine if its graph is Diophantine as a set. A subset `S ⊆ ℕ ^ α` in turn is called Diophantine if there exists an integer polynomial on `α ⊕ β` such that `v ∈ S` iff there exists `t : ℕ^β` with `p (v, t) = 0`. ## Main definitions * `is_poly`: a predicate stating that a function is a multivariate integer polynomial. * `poly`: the type of multivariate integer polynomial functions. * `dioph`: a predicate stating that a set is Diophantine, i.e. a set `S ⊆ ℕ^α` is Diophantine if there exists a polynomial on `α ⊕ β` such that `v ∈ S` iff there exists `t : ℕ^β` with `p (v, t) = 0`. * `dioph_fn`: a predicate on a function stating that it is Diophantine in the sense that its graph is Diophantine as a set. ## Main statements * `pell_dioph` states that solutions to Pell's equation form a Diophantine set. * `pow_dioph` states that the power function is Diophantine, a version of Matiyasevic's theorem. ## References * [M. Carneiro, _A Lean formalization of Matiyasevic's theorem_][carneiro2018matiyasevic] * [M. Davis, _Hilbert's tenth problem is unsolvable_][MR317916] ## Tags Matiyasevic's theorem, Hilbert's tenth problem ## TODO * Finish the solution of Hilbert's tenth problem. * Connect `poly` to `mv_polynomial` -/ open fin2 function nat sum local infixr ` ::ₒ `:67 := option.elim local infixr ` ⊗ `:65 := sum.elim universe u /-! ### Multivariate integer polynomials Note that this duplicates `mv_polynomial`. -/ section polynomials variables {α β γ : Type*} /-- A predicate asserting that a function is a multivariate integer polynomial. (We are being a bit lazy here by allowing many representations for multiplication, rather than only allowing monomials and addition, but the definition is equivalent and this is easier to use.) -/ inductive is_poly : ((α → ℕ) → ℤ) → Prop | proj : ∀ i, is_poly (λ x : α → ℕ, x i) | const : Π (n : ℤ), is_poly (λ x : α → ℕ, n) | sub : Π {f g : (α → ℕ) → ℤ}, is_poly f → is_poly g → is_poly (λ x, f x - g x) | mul : Π {f g : (α → ℕ) → ℤ}, is_poly f → is_poly g → is_poly (λ x, f x * g x) lemma is_poly.neg {f : (α → ℕ) → ℤ} : is_poly f → is_poly (-f) := by { rw ←zero_sub, exact (is_poly.const 0).sub } lemma is_poly.add {f g : (α → ℕ) → ℤ} (hf : is_poly f) (hg : is_poly g) : is_poly (f + g) := by { rw ←sub_neg_eq_add, exact hf.sub hg.neg } /-- The type of multivariate integer polynomials -/ def poly (α : Type u) := {f : (α → ℕ) → ℤ // is_poly f} namespace poly section instance fun_like : fun_like (poly α) (α → ℕ) (λ _, ℤ) := ⟨subtype.val, subtype.val_injective⟩ /-- Helper instance for when there are too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (poly α) (λ _, (α → ℕ) → ℤ) := fun_like.has_coe_to_fun /-- The underlying function of a `poly` is a polynomial -/ protected lemma is_poly (f : poly α) : is_poly f := f.2 /-- Extensionality for `poly α` -/ @[ext] lemma ext {f g : poly α} : (∀ x, f x = g x) → f = g := fun_like.ext _ _ /-- The `i`th projection function, `x_i`. -/ def proj (i) : poly α := ⟨_, is_poly.proj i⟩ @[simp] lemma proj_apply (i : α) (x) : proj i x = x i := rfl /-- The constant function with value `n : ℤ`. -/ def const (n) : poly α := ⟨_, is_poly.const n⟩ @[simp] lemma const_apply (n) (x : α → ℕ) : const n x = n := rfl instance : has_zero (poly α) := ⟨const 0⟩ instance : has_one (poly α) := ⟨const 1⟩ instance : has_neg (poly α) := ⟨λ f, ⟨-f, f.2.neg⟩⟩ instance : has_add (poly α) := ⟨λ f g, ⟨f + g, f.2.add g.2⟩⟩ instance : has_sub (poly α) := ⟨λ f g, ⟨f - g, f.2.sub g.2⟩⟩ instance : has_mul (poly α) := ⟨λ f g, ⟨f * g, f.2.mul g.2⟩⟩ @[simp] lemma coe_zero : ⇑(0 : poly α) = const 0 := rfl @[simp] lemma coe_one : ⇑(1 : poly α) = const 1 := rfl @[simp] lemma coe_neg (f : poly α) : ⇑(-f) = -f := rfl @[simp] lemma coe_add (f g : poly α) : ⇑(f + g) = f + g := rfl @[simp] lemma coe_sub (f g : poly α) : ⇑(f - g) = f - g := rfl @[simp] lemma coe_mul (f g : poly α) : ⇑(f * g) = f * g := rfl @[simp] lemma zero_apply (x) : (0 : poly α) x = 0 := rfl @[simp] lemma one_apply (x) : (1 : poly α) x = 1 := rfl @[simp] lemma neg_apply (f : poly α) (x) : (-f) x = -f x := rfl @[simp] lemma add_apply (f g : poly α) (x : α → ℕ) : (f + g) x = f x + g x := rfl @[simp] lemma sub_apply (f g : poly α) (x : α → ℕ) : (f - g) x = f x - g x := rfl @[simp] lemma mul_apply (f g : poly α) (x : α → ℕ) : (f * g) x = f x * g x := rfl instance (α : Type*) : inhabited (poly α) := ⟨0⟩ instance : add_comm_group (poly α) := by refine_struct { add := ((+) : poly α → poly α → poly α), neg := (has_neg.neg : poly α → poly α), sub := (has_sub.sub), zero := 0, zsmul := @zsmul_rec _ ⟨(0 : poly α)⟩ ⟨(+)⟩ ⟨has_neg.neg⟩, nsmul := @nsmul_rec _ ⟨(0 : poly α)⟩ ⟨(+)⟩ }; intros; try { refl }; refine ext (λ _, _); simp [sub_eq_add_neg, add_comm, add_assoc] instance : add_group_with_one (poly α) := { one := 1, nat_cast := λ n, poly.const n, int_cast := poly.const, .. poly.add_comm_group } instance : comm_ring (poly α) := by refine_struct { add := ((+) : poly α → poly α → poly α), zero := 0, mul := (*), one := 1, npow := @npow_rec _ ⟨(1 : poly α)⟩ ⟨(*)⟩, .. poly.add_group_with_one, .. poly.add_comm_group }; intros; try { refl }; refine ext (λ _, _); simp [sub_eq_add_neg, mul_add, mul_left_comm, mul_comm, add_comm, add_assoc] lemma induction {C : poly α → Prop} (H1 : ∀i, C (proj i)) (H2 : ∀n, C (const n)) (H3 : ∀f g, C f → C g → C (f - g)) (H4 : ∀f g, C f → C g → C (f * g)) (f : poly α) : C f := begin cases f with f pf, induction pf with i n f g pf pg ihf ihg f g pf pg ihf ihg, apply H1, apply H2, apply H3 _ _ ihf ihg, apply H4 _ _ ihf ihg end /-- The sum of squares of a list of polynomials. This is relevant for Diophantine equations, because it means that a list of equations can be encoded as a single equation: `x = 0 ∧ y = 0 ∧ z = 0` is equivalent to `x^2 + y^2 + z^2 = 0`. -/ def sumsq : list (poly α) → poly α | [] := 0 | (p::ps) := p*p + sumsq ps lemma sumsq_nonneg (x : α → ℕ) : ∀ l, 0 ≤ sumsq l x | [] := le_refl 0 | (p::ps) := by rw sumsq; simp [-add_comm]; exact add_nonneg (mul_self_nonneg _) (sumsq_nonneg ps) lemma sumsq_eq_zero (x) : ∀ l, sumsq l x = 0 ↔ l.all₂ (λ a : poly α, a x = 0) | [] := eq_self_iff_true _ | (p::ps) := by rw [list.all₂_cons, ← sumsq_eq_zero ps]; rw sumsq; simp [-add_comm]; exact ⟨λ (h : p x * p x + sumsq ps x = 0), have p x = 0, from eq_zero_of_mul_self_eq_zero $ le_antisymm (by rw ← h; have t := add_le_add_left (sumsq_nonneg x ps) (p x * p x); rwa [add_zero] at t) (mul_self_nonneg _), ⟨this, by simp [this] at h; exact h⟩, λ ⟨h1, h2⟩, by rw [h1, h2]; refl⟩ end /-- Map the index set of variables, replacing `x_i` with `x_(f i)`. -/ def map {α β} (f : α → β) (g : poly α) : poly β := ⟨λ v, g $ v ∘ f, g.induction (λ i, by simp; apply is_poly.proj) (λ n, by simp; apply is_poly.const) (λ f g pf pg, by simp; apply is_poly.sub pf pg) (λ f g pf pg, by simp; apply is_poly.mul pf pg)⟩ @[simp] lemma map_apply {α β} (f : α → β) (g : poly α) (v) : map f g v = g (v ∘ f) := rfl end poly end polynomials /-! ### Diophantine sets -/ /-- A set `S ⊆ ℕ^α` is Diophantine if there exists a polynomial on `α ⊕ β` such that `v ∈ S` iff there exists `t : ℕ^β` with `p (v, t) = 0`. -/ def dioph {α : Type u} (S : set (α → ℕ)) : Prop := ∃ {β : Type u} (p : poly (α ⊕ β)), ∀ v, S v ↔ ∃ t, p (v ⊗ t) = 0 namespace dioph section variables {α β γ : Type u} {S S' : set (α → ℕ)} lemma ext (d : dioph S) (H : ∀ v, v ∈ S ↔ v ∈ S') : dioph S' := by rwa ←set.ext H lemma of_no_dummies (S : set (α → ℕ)) (p : poly α) (h : ∀ v, S v ↔ p v = 0) : dioph S := ⟨pempty, p.map inl, λ v, (h v).trans ⟨λ h, ⟨pempty.rec _, h⟩, λ ⟨t, ht⟩, ht⟩⟩ lemma inject_dummies_lem (f : β → γ) (g : γ → option β) (inv : ∀ x, g (f x) = some x) (p : poly (α ⊕ β)) (v : α → ℕ) : (∃ t, p (v ⊗ t) = 0) ↔ ∃ t, p.map (inl ⊗ inr ∘ f) (v ⊗ t) = 0 := begin dsimp, refine ⟨λ t, _, λ t, _⟩; cases t with t ht, { have : (v ⊗ (0 ::ₒ t) ∘ g) ∘ (inl ⊗ inr ∘ f) = v ⊗ t := funext (λ s, by cases s with a b; dsimp [(∘)]; try {rw inv}; refl), exact ⟨(0 ::ₒ t) ∘ g, by rwa this⟩ }, { have : v ⊗ t ∘ f = (v ⊗ t) ∘ (inl ⊗ inr ∘ f) := funext (λ s, by cases s with a b; refl), exact ⟨t ∘ f, by rwa this⟩ } end lemma inject_dummies (f : β → γ) (g : γ → option β) (inv : ∀ x, g (f x) = some x) (p : poly (α ⊕ β)) (h : ∀ v, S v ↔ ∃ t, p (v ⊗ t) = 0) : ∃ q : poly (α ⊕ γ), ∀ v, S v ↔ ∃ t, q (v ⊗ t) = 0 := ⟨p.map (inl ⊗ (inr ∘ f)), λ v, (h v).trans $ inject_dummies_lem f g inv _ _⟩ variables (β) lemma reindex_dioph (f : α → β) : Π (d : dioph S), dioph {v | v ∘ f ∈ S} | ⟨γ, p, pe⟩ := ⟨γ, p.map ((inl ∘ f) ⊗ inr), λ v, (pe _).trans $ exists_congr $ λ t, suffices v ∘ f ⊗ t = (v ⊗ t) ∘ (inl ∘ f ⊗ inr), by simp [this], funext $ λ s, by cases s with a b; refl⟩ variables {β} lemma dioph_list.all₂ (l : list (set $ α → ℕ)) (d : l.all₂ dioph) : dioph {v | l.all₂ (λ S : set (α → ℕ), v ∈ S)} := suffices ∃ β (pl : list (poly (α ⊕ β))), ∀ v, list.all₂ (λ S : set _, S v) l ↔ ∃ t, list.all₂ (λ p : poly (α ⊕ β), p (v ⊗ t) = 0) pl, from let ⟨β, pl, h⟩ := this in ⟨β, poly.sumsq pl, λ v, (h v).trans $ exists_congr $ λ t, (poly.sumsq_eq_zero _ _).symm⟩, begin induction l with S l IH, exact ⟨ulift empty, [], λ v, by simp; exact ⟨λ ⟨t⟩, empty.rec _ t, trivial⟩⟩, simp at d, exact let ⟨⟨β, p, pe⟩, dl⟩ := d, ⟨γ, pl, ple⟩ := IH dl in ⟨β ⊕ γ, p.map (inl ⊗ inr ∘ inl) :: pl.map (λ q, q.map (inl ⊗ (inr ∘ inr))), λ v, by simp; exact iff.trans (and_congr (pe v) (ple v)) ⟨λ ⟨⟨m, hm⟩, ⟨n, hn⟩⟩, ⟨m ⊗ n, by rw [ show (v ⊗ m ⊗ n) ∘ (inl ⊗ inr ∘ inl) = v ⊗ m, from funext $ λ s, by cases s with a b; refl]; exact hm, by { refine list.all₂.imp (λ q hq, _) hn, dsimp [(∘)], rw [show (λ (x : α ⊕ γ), (v ⊗ m ⊗ n) ((inl ⊗ λ (x : γ), inr (inr x)) x)) = v ⊗ n, from funext $ λ s, by cases s with a b; refl]; exact hq }⟩, λ ⟨t, hl, hr⟩, ⟨⟨t ∘ inl, by rwa [ show (v ⊗ t) ∘ (inl ⊗ inr ∘ inl) = v ⊗ t ∘ inl, from funext $ λ s, by cases s with a b; refl] at hl⟩, ⟨t ∘ inr, by { refine list.all₂.imp (λ q hq, _) hr, dsimp [(∘)] at hq, rwa [show (λ (x : α ⊕ γ), (v ⊗ t) ((inl ⊗ λ (x : γ), inr (inr x)) x)) = v ⊗ t ∘ inr, from funext $ λ s, by cases s with a b; refl] at hq }⟩⟩⟩⟩ end lemma inter (d : dioph S) (d' : dioph S') : dioph (S ∩ S') := dioph_list.all₂ [S, S'] ⟨d, d'⟩ lemma union : ∀ (d : dioph S) (d' : dioph S'), dioph (S ∪ S') | ⟨β, p, pe⟩ ⟨γ, q, qe⟩ := ⟨β ⊕ γ, p.map (inl ⊗ inr ∘ inl) * q.map (inl ⊗ inr ∘ inr), λ v, begin refine iff.trans (or_congr ((pe v).trans _) ((qe v).trans _)) (exists_or_distrib.symm.trans (exists_congr $ λ t, (@mul_eq_zero _ _ _ (p ((v ⊗ t) ∘ (inl ⊗ inr ∘ inl))) (q ((v ⊗ t) ∘ (inl ⊗ inr ∘ inr)))).symm)), exact inject_dummies_lem _ (some ⊗ (λ _, none)) (λ x, rfl) _ _, exact inject_dummies_lem _ ((λ _, none) ⊗ some) (λ x, rfl) _ _, end⟩ /-- A partial function is Diophantine if its graph is Diophantine. -/ def dioph_pfun (f : (α → ℕ) →. ℕ) : Prop := dioph {v : option α → ℕ | f.graph (v ∘ some, v none)} /-- A function is Diophantine if its graph is Diophantine. -/ def dioph_fn (f : (α → ℕ) → ℕ) : Prop := dioph {v : option α → ℕ | f (v ∘ some) = v none} lemma reindex_dioph_fn {f : (α → ℕ) → ℕ} (g : α → β) (d : dioph_fn f) : dioph_fn (λ v, f (v ∘ g)) := by convert reindex_dioph (option β) (option.map g) d lemma ex_dioph {S : set (α ⊕ β → ℕ)} : dioph S → dioph {v | ∃ x, v ⊗ x ∈ S} | ⟨γ, p, pe⟩ := ⟨β ⊕ γ, p.map ((inl ⊗ inr ∘ inl) ⊗ inr ∘ inr), λ v, ⟨λ ⟨x, hx⟩, let ⟨t, ht⟩ := (pe _).1 hx in ⟨x ⊗ t, by simp; rw [ show (v ⊗ x ⊗ t) ∘ ((inl ⊗ inr ∘ inl) ⊗ inr ∘ inr) = (v ⊗ x) ⊗ t, from funext $ λ s, by cases s with a b; try {cases a}; refl]; exact ht⟩, λ ⟨t, ht⟩, ⟨t ∘ inl, (pe _).2 ⟨t ∘ inr, by simp at ht; rwa [ show (v ⊗ t) ∘ ((inl ⊗ inr ∘ inl) ⊗ inr ∘ inr) = (v ⊗ t ∘ inl) ⊗ t ∘ inr, from funext $ λ s, by cases s with a b; try {cases a}; refl] at ht⟩⟩⟩⟩ lemma ex1_dioph {S : set (option α → ℕ)} : dioph S → dioph {v | ∃ x, x ::ₒ v ∈ S} | ⟨β, p, pe⟩ := ⟨option β, p.map (inr none ::ₒ inl ⊗ inr ∘ some), λ v, ⟨λ ⟨x, hx⟩, let ⟨t, ht⟩ := (pe _).1 hx in ⟨x ::ₒ t, by simp; rw [ show (v ⊗ x ::ₒ t) ∘ (inr none ::ₒ inl ⊗ inr ∘ some) = x ::ₒ v ⊗ t, from funext $ λ s, by cases s with a b; try {cases a}; refl]; exact ht⟩, λ ⟨t, ht⟩, ⟨t none, (pe _).2 ⟨t ∘ some, by simp at ht; rwa [ show (v ⊗ t) ∘ (inr none ::ₒ inl ⊗ inr ∘ some) = t none ::ₒ v ⊗ t ∘ some, from funext $ λ s, by cases s with a b; try {cases a}; refl] at ht⟩⟩⟩⟩ theorem dom_dioph {f : (α → ℕ) →. ℕ} (d : dioph_pfun f) : dioph f.dom := cast (congr_arg dioph $ set.ext $ λ v, (pfun.dom_iff_graph _ _).symm) (ex1_dioph d) theorem dioph_fn_iff_pfun (f : (α → ℕ) → ℕ) : dioph_fn f = @dioph_pfun α f := by refine congr_arg dioph (set.ext $ λ v, _); exact pfun.lift_graph.symm lemma abs_poly_dioph (p : poly α) : dioph_fn (λ v, (p v).nat_abs) := of_no_dummies _ ((p.map some - poly.proj none) * (p.map some + poly.proj none)) $ λ v, by { dsimp, exact int.eq_nat_abs_iff_mul_eq_zero } theorem proj_dioph (i : α) : dioph_fn (λ v, v i) := abs_poly_dioph (poly.proj i) theorem dioph_pfun_comp1 {S : set (option α → ℕ)} (d : dioph S) {f} (df : dioph_pfun f) : dioph {v : α → ℕ | ∃ h : f.dom v, f.fn v h ::ₒ v ∈ S} := ext (ex1_dioph (d.inter df)) $ λ v, ⟨λ ⟨x, hS, (h: Exists _)⟩, by rw [show (x ::ₒ v) ∘ some = v, from funext $ λ s, rfl] at h; cases h with hf h; refine ⟨hf, _⟩; rw [pfun.fn, h]; exact hS, λ ⟨x, hS⟩, ⟨f.fn v x, hS, show Exists _, by rw [show (f.fn v x ::ₒ v) ∘ some = v, from funext $ λ s, rfl]; exact ⟨x, rfl⟩⟩⟩ theorem dioph_fn_comp1 {S : set (option α → ℕ)} (d : dioph S) {f : (α → ℕ) → ℕ} (df : dioph_fn f) : dioph {v | f v ::ₒ v ∈ S} := ext (dioph_pfun_comp1 d $ cast (dioph_fn_iff_pfun f) df) $ λ v, ⟨λ ⟨_, h⟩, h, λ h, ⟨trivial, h⟩⟩ end section variables {α β : Type} {n : ℕ} open vector3 open_locale vector3 local attribute [reducible] vector3 lemma dioph_fn_vec_comp1 {S : set (vector3 ℕ (succ n))} (d : dioph S) {f : vector3 ℕ n → ℕ} (df : dioph_fn f) : dioph {v : vector3 ℕ n | f v :: v ∈ S} := ext (dioph_fn_comp1 (reindex_dioph _ (none :: some) d) df) $ λ v, by { dsimp, congr', ext x, cases x; refl } theorem vec_ex1_dioph (n) {S : set (vector3 ℕ (succ n))} (d : dioph S) : dioph {v : fin2 n → ℕ | ∃ x, x :: v ∈ S} := ext (ex1_dioph $ reindex_dioph _ (none :: some) d) $ λ v, exists_congr $ λ x, by { dsimp, rw [show option.elim x v ∘ cons none some = x :: v, from funext $ λ s, by cases s with a b; refl] } lemma dioph_fn_vec (f : vector3 ℕ n → ℕ) : dioph_fn f ↔ dioph {v | f (v ∘ fs) = v fz} := ⟨reindex_dioph _ (fz ::ₒ fs), reindex_dioph _ (none :: some)⟩ lemma dioph_pfun_vec (f : vector3 ℕ n →. ℕ) : dioph_pfun f ↔ dioph {v | f.graph (v ∘ fs, v fz)} := ⟨reindex_dioph _ (fz ::ₒ fs), reindex_dioph _ (none :: some)⟩ lemma dioph_fn_compn : ∀ {n} {S : set (α ⊕ fin2 n → ℕ)} (d : dioph S) {f : vector3 ((α → ℕ) → ℕ) n} (df : vector_allp dioph_fn f), dioph {v : α → ℕ | v ⊗ (λ i, f i v) ∈ S} | 0 S d f := λ df, ext (reindex_dioph _ (id ⊗ fin2.elim0) d) $ λ v, by { dsimp, congr', ext x, obtain (_ | _ | _) := x, refl } | (succ n) S d f := f.cons_elim $ λ f fl, by simp; exact λ df dfl, have dioph {v |v ∘ inl ⊗ f (v ∘ inl) :: v ∘ inr ∈ S}, from ext (dioph_fn_comp1 (reindex_dioph _ (some ∘ inl ⊗ none :: some ∘ inr) d) $ reindex_dioph_fn inl df) $ λ v, by { dsimp, congr', ext x, obtain (_ | _ | _) := x; refl }, have dioph {v | v ⊗ f v :: (λ (i : fin2 n), fl i v) ∈ S}, from @dioph_fn_compn n (λ v, S (v ∘ inl ⊗ f (v ∘ inl) :: v ∘ inr)) this _ dfl, ext this $ λ v, by { dsimp, congr', ext x, obtain _ | _ | _ := x; refl } lemma dioph_comp {S : set (vector3 ℕ n)} (d : dioph S) (f : vector3 ((α → ℕ) → ℕ) n) (df : vector_allp dioph_fn f) : dioph {v | (λ i, f i v) ∈ S} := dioph_fn_compn (reindex_dioph _ inr d) df lemma dioph_fn_comp {f : vector3 ℕ n → ℕ} (df : dioph_fn f) (g : vector3 ((α → ℕ) → ℕ) n) (dg : vector_allp dioph_fn g) : dioph_fn (λ v, f (λ i, g i v)) := dioph_comp ((dioph_fn_vec _).1 df) ((λ v, v none) :: λ i v, g i (v ∘ some)) $ by simp; exact ⟨proj_dioph none, (vector_allp_iff_forall _ _).2 $ λ i, reindex_dioph_fn _ $ (vector_allp_iff_forall _ _).1 dg _⟩ localized "notation (name := dioph.inter) x ` D∧ `:35 y := dioph.inter x y" in dioph localized "notation (name := dioph.union) x ` D∨ `:35 y := dioph.union x y" in dioph localized "notation (name := dioph.vec_ex1_dioph) `D∃`:30 := dioph.vec_ex1_dioph" in dioph localized "prefix (name := fin2.of_nat') `&`:max := fin2.of_nat'" in dioph theorem proj_dioph_of_nat {n : ℕ} (m : ℕ) [is_lt m n] : dioph_fn (λ v : vector3 ℕ n, v &m) := proj_dioph &m localized "prefix (name := proj_dioph_of_nat) `D&`:100 := dioph.proj_dioph_of_nat" in dioph theorem const_dioph (n : ℕ) : dioph_fn (const (α → ℕ) n) := abs_poly_dioph (poly.const n) localized "prefix (name := const_dioph) `D.`:100 := dioph.const_dioph" in dioph variables {f g : (α → ℕ) → ℕ} (df : dioph_fn f) (dg : dioph_fn g) include df dg lemma dioph_comp2 {S : ℕ → ℕ → Prop} (d : dioph (λ v:vector3 ℕ 2, S (v &0) (v &1))) : dioph (λ v, S (f v) (g v)) := dioph_comp d [f, g] (by exact ⟨df, dg⟩) lemma dioph_fn_comp2 {h : ℕ → ℕ → ℕ} (d : dioph_fn (λ v:vector3 ℕ 2, h (v &0) (v &1))) : dioph_fn (λ v, h (f v) (g v)) := dioph_fn_comp d [f, g] (by exact ⟨df, dg⟩) lemma eq_dioph : dioph (λ v, f v = g v) := dioph_comp2 df dg $ of_no_dummies _ (poly.proj &0 - poly.proj &1) (λ v, (int.coe_nat_eq_coe_nat_iff _ _).symm.trans ⟨@sub_eq_zero_of_eq ℤ _ (v &0) (v &1), eq_of_sub_eq_zero⟩) localized "infix (name := eq_dioph) ` D= `:50 := dioph.eq_dioph" in dioph lemma add_dioph : dioph_fn (λ v, f v + g v) := dioph_fn_comp2 df dg $ abs_poly_dioph (poly.proj &0 + poly.proj &1) localized "infix (name := add_dioph) ` D+ `:80 := dioph.add_dioph" in dioph lemma mul_dioph : dioph_fn (λ v, f v * g v) := dioph_fn_comp2 df dg $ abs_poly_dioph (poly.proj &0 * poly.proj &1) localized "infix (name := mul_dioph) ` D* `:90 := dioph.mul_dioph" in dioph lemma le_dioph : dioph {v | f v ≤ g v} := dioph_comp2 df dg $ ext (D∃2 $ D&1 D+ D&0 D= D&2) (λ v, ⟨λ ⟨x, hx⟩, le.intro hx, le.dest⟩) localized "infix (name := le_dioph) ` D≤ `:50 := dioph.le_dioph" in dioph lemma lt_dioph : dioph {v | f v < g v} := df D+ (D. 1) D≤ dg localized "infix (name := lt_dioph) ` D< `:50 := dioph.lt_dioph" in dioph lemma ne_dioph : dioph {v | f v ≠ g v} := ext (df D< dg D∨ dg D< df) $ λ v, by { dsimp, exact lt_or_lt_iff_ne } localized "infix (name := ne_dioph) ` D≠ `:50 := dioph.ne_dioph" in dioph lemma sub_dioph : dioph_fn (λ v, f v - g v) := dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ ext (D&1 D= D&0 D+ D&2 D∨ D&1 D≤ D&2 D∧ D&0 D= D.0) $ (vector_all_iff_forall _).1 $ λ x y z, show (y = x + z ∨ y ≤ z ∧ x = 0) ↔ y - z = x, from ⟨λ o, begin rcases o with ae | ⟨yz, x0⟩, { rw [ae, add_tsub_cancel_right] }, { rw [x0, tsub_eq_zero_iff_le.mpr yz] } end, begin rintro rfl, cases le_total y z with yz zy, { exact or.inr ⟨yz, tsub_eq_zero_iff_le.mpr yz⟩ }, { exact or.inl (tsub_add_cancel_of_le zy).symm }, end⟩ localized "infix (name := sub_dioph) ` D- `:80 := dioph.sub_dioph" in dioph lemma dvd_dioph : dioph (λ v, f v ∣ g v) := dioph_comp (D∃2 $ D&2 D= D&1 D* D&0) [f, g] (by exact ⟨df, dg⟩) localized "infix (name := dvd_dioph) ` D∣ `:50 := dioph.dvd_dioph" in dioph lemma mod_dioph : dioph_fn (λ v, f v % g v) := have dioph (λ v : vector3 ℕ 3, (v &2 = 0 ∨ v &0 < v &2) ∧ ∃ (x : ℕ), v &0 + v &2 * x = v &1), from (D&2 D= D.0 D∨ D&0 D< D&2) D∧ (D∃3 $ D&1 D+ D&3 D* D&0 D= D&2), dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ ext this $ (vector_all_iff_forall _).1 $ λ z x y, show ((y = 0 ∨ z < y) ∧ ∃ c, z + y * c = x) ↔ x % y = z, from ⟨λ ⟨h, c, hc⟩, begin rw ← hc; simp; cases h with x0 hl, rw [x0, mod_zero], exact mod_eq_of_lt hl end, λ e, by rw ← e; exact ⟨or_iff_not_imp_left.2 $ λ h, mod_lt _ (nat.pos_of_ne_zero h), x / y, mod_add_div _ _⟩⟩ localized "infix (name := mod_dioph) ` D% `:80 := dioph.mod_dioph" in dioph lemma modeq_dioph {h : (α → ℕ) → ℕ} (dh : dioph_fn h) : dioph (λ v, f v ≡ g v [MOD h v]) := df D% dh D= dg D% dh localized "notation (name := modeq_dioph) ` D≡ ` := dioph.modeq_dioph" in dioph lemma div_dioph : dioph_fn (λ v, f v / g v) := have dioph (λ v : vector3 ℕ 3, v &2 = 0 ∧ v &0 = 0 ∨ v &0 * v &2 ≤ v &1 ∧ v &1 < (v &0 + 1) * v &2), from (D&2 D= D.0 D∧ D&0 D= D.0) D∨ D&0 D* D&2 D≤ D&1 D∧ D&1 D< (D&0 D+ D.1) D* D&2, dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ ext this $ (vector_all_iff_forall _).1 $ λ z x y, show y = 0 ∧ z = 0 ∨ z * y ≤ x ∧ x < (z + 1) * y ↔ x / y = z, by refine iff.trans _ eq_comm; exact y.eq_zero_or_pos.elim (λ y0, by rw [y0, nat.div_zero]; exact ⟨λ o, (o.resolve_right $ λ ⟨_, h2⟩, nat.not_lt_zero _ h2).right, λ z0, or.inl ⟨rfl, z0⟩⟩) (λ ypos, iff.trans ⟨λ o, o.resolve_left $ λ ⟨h1, _⟩, ne_of_gt ypos h1, or.inr⟩ (le_antisymm_iff.trans $ and_congr (nat.le_div_iff_mul_le ypos) $ iff.trans ⟨lt_succ_of_le, le_of_lt_succ⟩ (div_lt_iff_lt_mul ypos)).symm) localized "infix (name := div_dioph) ` D/ `:80 := dioph.div_dioph" in dioph omit df dg open pell lemma pell_dioph : dioph (λ v:vector3 ℕ 4, ∃ h : 1 < v &0, xn h (v &1) = v &2 ∧ yn h (v &1) = v &3) := have dioph {v : vector3 ℕ 4 | 1 < v &0 ∧ v &1 ≤ v &3 ∧ (v &2 = 1 ∧ v &3 = 0 ∨ ∃ (u w s t b : ℕ), v &2 * v &2 - (v &0 * v &0 - 1) * v &3 * v &3 = 1 ∧ u * u - (v &0 * v &0 - 1) * w * w = 1 ∧ s * s - (b * b - 1) * t * t = 1 ∧ 1 < b ∧ (b ≡ 1 [MOD 4 * v &3]) ∧ (b ≡ v &0 [MOD u]) ∧ 0 < w ∧ v &3 * v &3 ∣ w ∧ (s ≡ v &2 [MOD u]) ∧ (t ≡ v &1 [MOD 4 * v &3]))}, from D.1 D< D&0 D∧ D&1 D≤ D&3 D∧ ((D&2 D= D.1 D∧ D&3 D= D.0) D∨ (D∃4 $ D∃5 $ D∃6 $ D∃7 $ D∃8 $ D&7 D* D&7 D- (D&5 D* D&5 D- D.1) D* D&8 D* D&8 D= D.1 D∧ D&4 D* D&4 D- (D&5 D* D&5 D- D.1) D* D&3 D* D&3 D= D.1 D∧ D&2 D* D&2 D- (D&0 D* D&0 D- D.1) D* D&1 D* D&1 D= D.1 D∧ D.1 D< D&0 D∧ (D≡ (D&0) (D.1) (D.4 D* D&8)) D∧ (D≡ (D&0) (D&5) D&4) D∧ D.0 D< D&3 D∧ D&8 D* D&8 D∣ D&3 D∧ (D≡ (D&2) (D&7) D&4) D∧ (D≡ (D&1) (D&6) (D.4 D* D&8)))), dioph.ext this $ λ v, matiyasevic.symm lemma xn_dioph : dioph_pfun (λ v:vector3 ℕ 2, ⟨1 < v &0, λ h, xn h (v &1)⟩) := have dioph (λ v:vector3 ℕ 3, ∃ y, ∃ h : 1 < v &1, xn h (v &2) = v &0 ∧ yn h (v &2) = y), from let D_pell := pell_dioph.reindex_dioph (fin2 4) [&2, &3, &1, &0] in D∃3 D_pell, (dioph_pfun_vec _).2 $ dioph.ext this $ λ v, ⟨λ ⟨y, h, xe, ye⟩, ⟨h, xe⟩, λ ⟨h, xe⟩, ⟨_, h, xe, rfl⟩⟩ include df dg /-- A version of **Matiyasevic's theorem** -/ theorem pow_dioph : dioph_fn (λ v, f v ^ g v) := have dioph {v : vector3 ℕ 3 | v &2 = 0 ∧ v &0 = 1 ∨ 0 < v &2 ∧ (v &1 = 0 ∧ v &0 = 0 ∨ 0 < v &1 ∧ ∃ (w a t z x y : ℕ), (∃ (a1 : 1 < a), xn a1 (v &2) = x ∧ yn a1 (v &2) = y) ∧ (x ≡ y * (a - v &1) + v &0 [MOD t]) ∧ 2 * a * v &1 = t + (v &1 * v &1 + 1) ∧ v &0 < t ∧ v &1 ≤ w ∧ v &2 ≤ w ∧ a * a - ((w + 1) * (w + 1) - 1) * (w * z) * (w * z) = 1)}, from let D_pell := pell_dioph.reindex_dioph (fin2 9) [&4, &8, &1, &0] in (D&2 D= D.0 D∧ D&0 D= D.1) D∨ (D.0 D< D&2 D∧ ((D&1 D= D.0 D∧ D&0 D= D.0) D∨ (D.0 D< D&1 D∧ (D∃3 $ D∃4 $ D∃5 $ D∃6 $ D∃7 $ D∃8 $ D_pell D∧ (D≡ (D&1) (D&0 D* (D&4 D- D&7) D+ D&6) (D&3)) D∧ D.2 D* D&4 D* D&7 D= D&3 D+ (D&7 D* D&7 D+ D.1) D∧ D&6 D< D&3 D∧ D&7 D≤ D&5 D∧ D&8 D≤ D&5 D∧ D&4 D* D&4 D- ((D&5 D+ D.1) D* (D&5 D+ D.1) D- D.1) D* (D&5 D* D&2) D* (D&5 D* D&2) D= D.1)))), dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ dioph.ext this $ λ v, iff.symm $ eq_pow_of_pell.trans $ or_congr iff.rfl $ and_congr iff.rfl $ or_congr iff.rfl $ and_congr iff.rfl $ ⟨λ ⟨w, a, t, z, a1, h⟩, ⟨w, a, t, z, _, _, ⟨a1, rfl, rfl⟩, h⟩, λ ⟨w, a, t, z, ._, ._, ⟨a1, rfl, rfl⟩, h⟩, ⟨w, a, t, z, a1, h⟩⟩ end end dioph
78c5e4b9c8587fd1d8a5b757a45d16e0f8e0cbff
2f8bf12144551bc7d8087a6320990c4621741f3d
/library/init/lean/compiler/ir/normids.lean
3a9225fe83810f0065e1f853351e7ce01dc0008f
[ "Apache-2.0" ]
permissive
jesse-michael-han/lean4
eb63a12960e69823749edceb4f23fd33fa2253ce
fa16920a6a7700cabc567aa629ce4ae2478a2f40
refs/heads/master
1,589,935,810,594
1,557,177,860,000
1,557,177,860,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,884
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.lean.compiler.ir.basic init.control.reader namespace Lean namespace IR namespace NormalizeIds abbrev M := ReaderT IndexRenaming Id def normIndex (x : Index) : M Index := λ m, match m.find x with | some y := y | none := x def normVar (x : VarId) : M VarId := VarId.mk <$> normIndex x.idx def normJP (x : JoinPointId) : M JoinPointId := JoinPointId.mk <$> normIndex x.idx def normArg : Arg → M Arg | (Arg.var x) := Arg.var <$> normVar x | other := pure other def normArgs (as : Array Arg) : M (Array Arg) := λ m, as.hmap $ λ a, normArg a m def normExpr : Expr → M Expr | (Expr.ctor c ys) m := Expr.ctor c (normArgs ys m) | (Expr.reset x) m := Expr.reset (normVar x m) | (Expr.reuse x c u ys) m := Expr.reuse (normVar x m) c u (normArgs ys m) | (Expr.proj i x) m := Expr.proj i (normVar x m) | (Expr.uproj i x) m := Expr.uproj i (normVar x m) | (Expr.sproj n o x) m := Expr.sproj n o (normVar x m) | (Expr.fap c ys) m := Expr.fap c (normArgs ys m) | (Expr.pap c ys) m := Expr.pap c (normArgs ys m) | (Expr.ap x ys) m := Expr.ap (normVar x m) (normArgs ys m) | (Expr.box t x) m := Expr.box t (normVar x m) | (Expr.unbox x) m := Expr.unbox (normVar x m) | (Expr.isShared x) m := Expr.isShared (normVar x m) | (Expr.isTaggedPtr x) m := Expr.isTaggedPtr (normVar x m) | e@(Expr.lit v) m := e abbrev N := ReaderT IndexRenaming (State Nat) def mkFresh : N Index := getModify (+1) @[inline] def withVar {α : Type} (x : VarId) (k : VarId → N α) : N α := λ m, do n ← getModify (+1), k { idx := n } (m.insert x.idx n) @[inline] def withJP {α : Type} (x : JoinPointId) (k : JoinPointId → N α) : N α := λ m, do n ← getModify (+1), k { idx := n } (m.insert x.idx n) @[inline] def withParams {α : Type} (ps : Array Param) (k : Array Param → N α) : N α := λ m, do m ← ps.mfoldl m (λ m p, do n ← getModify (+1), pure $ m.insert p.x.idx n), let ps := ps.hmap $ λ p, { x := normVar p.x m, .. p }, k ps m instance MtoN {α} : HasCoe (M α) (N α) := ⟨λ x m, pure $ x m⟩ local attribute [instance] monadInhabited partial def normFnBody : FnBody → N FnBody | (FnBody.vdecl x t v b) := do v ← normExpr v, withVar x $ λ x, FnBody.vdecl x t v <$> normFnBody b | (FnBody.jdecl j ys t v b) := do (ys, v) ← withParams ys $ λ ys, do { v ← normFnBody v, pure (ys, v) }, withJP j $ λ j, FnBody.jdecl j ys t v <$> normFnBody b | (FnBody.set x i y b) := do x ← normVar x, y ← normVar y, FnBody.set x i y <$> normFnBody b | (FnBody.uset x i y b) := do x ← normVar x, y ← normVar y, FnBody.uset x i y <$> normFnBody b | (FnBody.sset x i o y t b) := do x ← normVar x, y ← normVar y, FnBody.sset x i o y t <$> normFnBody b | (FnBody.release x i b) := do x ← normVar x, FnBody.release x i <$> normFnBody b | (FnBody.inc x n c b) := do x ← normVar x, FnBody.inc x n c <$> normFnBody b | (FnBody.dec x n c b) := do x ← normVar x, FnBody.dec x n c <$> normFnBody b | (FnBody.mdata d b) := FnBody.mdata d <$> normFnBody b | (FnBody.case tid x alts) := do x ← normVar x, alts ← alts.hmmap $ λ alt, alt.mmodifyBody normFnBody, pure $ FnBody.case tid x alts | (FnBody.jmp j ys) := FnBody.jmp <$> normJP j <*> normArgs ys | (FnBody.ret x) := FnBody.ret <$> normArg x | FnBody.unreachable := pure FnBody.unreachable def normDecl : Decl → N Decl | (Decl.fdecl f xs t b) := withParams xs $ λ xs, Decl.fdecl f xs t <$> normFnBody b | other := pure other end NormalizeIds def Decl.normalizeIds (d : Decl) : Decl := (NormalizeIds.normDecl d {}).run' 1 end IR end Lean
490b5c9f3ac362f5a0c10ba7a907e45c637e0b3c
398b53a5e02ce35196531591f84bb2f6b034ce5a
/tpil/chapter4.lean
491da5add3ef41d6329db232f896b431a7392aa0
[ "MIT" ]
permissive
crockeo/math-exercises
64f07a9371a72895bbd97f49a854dcb6821b18ab
cf9150ef9e025f1b7929ba070a783e7a71f24f31
refs/heads/master
1,607,910,221,030
1,581,231,762,000
1,581,231,762,000
234,595,189
0
0
null
null
null
null
UTF-8
Lean
false
false
12,775
lean
-- Exercise 1 -- -- Prove these equivalences: section variables (α : Type) (p q : α → Prop) example : (∀ x, p x ∧ q x) ↔ (∀ x, p x) ∧ (∀ x, q x) := begin split, { assume h, split, { assume hx, exact and.left (h hx), }, { assume hx, exact and.right (h hx), }, }, { assume h, assume hx, exact and.intro (and.left h hx) (and.right h hx), }, end example : (∀ x, p x → q x) → (∀ x, p x) → (∀ x, q x) := begin assume hpq, assume hp, assume x, exact hpq x (hp x), end example : (∀ x, p x) ∨ (∀ x, q x) → ∀ x, p x ∨ q x := begin have f : (∀ x, p x) → ∀ x, p x ∨ q x, { assume hpx, assume hx, exact or.intro_left (q hx) (hpx hx), }, have g : (∀ x, q x) → ∀ x, p x ∨ q x, { assume hqx, assume hx, exact or.intro_right (p hx) (hqx hx), }, assume h, exact or.elim h f g, -- NOTE: Not derivable because there exist situations in which -- (∀ x, p x ∨ q x) is true, but (∀ x, p x) ∨ (∀ x, q x) is not. The -- former can mix truthiness between the two, but the latter requires -- that p must hold for all x, or q must hold for all x. end end -- Exercise 2 -- -- It is often possible to bring a component of a formula outside a universal -- quantifier, when it does not depend on the quantified variable. Try proving -- these (one direction of the second of these requires classical logic): section universe u variables (α : Type u) (p q : α → Prop) variable r : Prop example : α → ((∀ x : α, r) ↔ r) := begin assume ha, split, assume har, exact har ha, assume hr, assume haa, exact hr, end variable x : α example : (∀ x, p x ∨ r) ↔ (∀ x, p x) ∨ r := begin split, -- hphx : p hx = evidence of the predicate p holding on an element of x -- p hx : Prop = a property that may or may not be true of hx { assume h, have pos : r → (∀ x, p x) ∨ r, { assume hr, exact or.inr hr, }, have neg : ¬r → (∀ x, p x) ∨ r, { assume hnr, apply or.inl, assume hx, exact or.elim (h hx) id (λ hr, absurd hr hnr), }, exact classical.by_cases pos neg, }, { assume h, assume hx, exact or.elim h (λ hl, or.intro_left r (hl hx)) (λ hr, or.intro_right (p hx) hr), }, end example : (∀ x, r → p x) ↔ (r → ∀ x, p x) := begin split, { assume h, assume hr, assume ha, exact (h ha) hr, }, { assume h, assume ha, assume hr, exact (h hr) ha, }, end end -- Exercise 3 -- -- Consider the “barber paradox,” that is, the claim that in a certain town -- there is a (male) barber that shaves all and only the men who do not shave -- themselves. Prove that this is a contradiction: section variables (men : Type) (barber : men) variable (shaves : men → men → Prop) variable (h : ∀ x : men, shaves barber x ↔ ¬ shaves x x) example (h : ∀ x : men, shaves barber x ↔ ¬ shaves x x) : false := begin have hiff : (shaves barber barber) ↔ ¬(shaves barber barber), from h barber, have f : shaves barber barber → false, { assume hf, exact (hiff.mp hf) hf, }, have g : ¬shaves barber barber → false, { assume hg, exact f (hiff.mpr hg), }, exact classical.by_cases f g, end end -- Exercise 4 -- -- Below, we have put definitions of divides and even in a special namespace to -- avoid conflicts with definitions in the library. The instance declaration -- makes it possible to use the notation m | n for divides m n. Don’t worry -- about how it works; you will learn about that later. namespace hidden def divides (m n : ℕ) : Prop := ∃ k, m * k = n instance : has_dvd nat := ⟨divides⟩ def even (n : ℕ) : Prop := 2 ∣ n -- You can enter the '∣' character by typing \mid section variables m n : ℕ #check m ∣ n #check m^n #check even (m^n +3) end end hidden -- Remember that, without any parameters, an expression of type Prop is just an -- assertion. Fill in the definitions of prime and Fermat_prime below, and -- construct the given assertion. For example, you can say that there are -- infinitely many primes by asserting that for every natural number n, there is -- a prime number greater than n. Goldbach’s weak conjecture states that every -- odd number greater than 5 is the sum of three primes. Look up the definition -- of a Fermat prime or any of the other statements, if necessary. section def prime (n : ℕ) : Prop := ¬∃m: ℕ, m < n ∧ hidden.divides m n def infinitely_many_primes : Prop := ∀x : ℕ, ∃y : ℕ, y > x ∧ prime y def Fermat_prime (n : ℕ) : Prop := ∃k : ℕ, n = 2^(2 ^ k) + 1 def infinitely_many_Fermat_primes : Prop := ∀x : ℕ, ∃y : ℕ, y > x ∧ Fermat_prime y def goldbach_conjecture : Prop := ∀x : ℕ, x > 2 → ∃y z : ℕ, x = y + z ∧ prime y ∧ prime z def Goldbach's_weak_conjecture : Prop := ∀x : ℕ, ¬hidden.even x ∧ x > 5 → ∃a b c : ℕ, x = a + b + c ∧ prime a ∧ prime b ∧ prime c def Fermat's_last_theorem : Prop := ¬∃a b c n : ℕ, n > 2 ∧ a^n = b^n + c^n end -- Exercise 5 -- -- Prove as many of the identities listed in Section 4.4 as you can. section open classical variables (α : Type) (p q : α → Prop) variable a : α variable r : Prop include a example : (∃ x : α, r) → r := begin assume h, have hq : (∀a : α, r → r), assume a, assume hr, exact hr, exact exists.elim h hq, end example : r → (∃ x : α, r) := begin assume hr, exact exists.intro a hr end example : (∃ x, p x ∧ r) ↔ (∃ x, p x) ∧ r := begin split, { assume h, have hq : ∀(a : α), p a ∧ r → (∃(x : α), p x) ∧ r, { assume ha, assume conj, apply and.intro, exact exists.intro ha (and.left conj), exact and.right conj, }, exact exists.elim h hq, }, { assume h, have hl, from and.left h, have hr, from and.right h, have hq : ∀(a : α), p a → (∃x : α, p x ∧ r), { assume ha, assume h', apply exists.intro, exact and.intro h' hr, }, exact exists.elim hl hq, }, end example (h : ∃ x, p x ∧ q x) : ∃ x, q x ∧ p x := match h with ⟨w, hw⟩ := ⟨w, hw.right, hw.left⟩ end example : (∃ x, p x ∨ q x) ↔ (∃ x, p x) ∨ (∃ x, q x) := begin split, { assume h, have f : Π a : α, p a → ∃ (x : α), p x, exact exists.intro, have g : Π a : α, q a → ∃ (x : α), q x, exact exists.intro, apply exists.elim h, assume ha, assume hor, exact or.elim hor (λ hpa, or.inl (f ha hpa)) (λ hqa, or.inr (g ha hqa)), }, { assume hor, have f : (∃ (x : α), p x) → ∃ (x : α), p x ∨ q x, assume hex, exact ( match hex with ⟨ha, hpx⟩ := ⟨ha, or.inl hpx⟩ end ), have g : (∃ (x : α), q x) → ∃ (x : α), p x ∨ q x, assume hex, exact ( match hex with ⟨ha, hqx⟩ := ⟨ha, or.inr hqx⟩ end ), exact or.elim hor f g, }, end example : (∀ x, p x) ↔ ¬ (∃ x, ¬ p x) := begin split, { assume hfa, assume hex, have f : (∀ (a : α), (λ (x : α), ¬p x) a → false), assume a, assume hnpa, exact hnpa (hfa a), exact exists.elim hex f, }, { assume hne, assume a, apply by_contradiction, assume hnpa, have he : ∃x : α, ¬p x, exact exists.intro a hnpa, exact hne he, }, end example : (∃ x, p x) ↔ ¬ (∀ x, ¬ p x) := begin split, { assume hex, assume hfa, have f : (∀ (a : α), (λ (x : α), p x) a → false), assume ha, assume hpa, exact (hfa ha) hpa, exact exists.elim hex f, }, { assume hnfa, apply by_contradiction, assume hnex, have hfa : ∀(x : α), ¬p x, assume ha, assume hpa, exact hnex (exists.intro ha hpa), exact hnfa hfa, }, end example : (¬ ∃ x, p x) ↔ (∀ x, ¬ p x) := begin split, { assume hnex, assume ha, assume hpa, have hex : ∃(x : α), p x, exact exists.intro ha hpa, exact hnex hex, }, { assume hfa, assume hex, have f : (∀ x : α, (λ a : α, p x) a → false), assume ha, assume hpa, exact (hfa ha) hpa, exact exists.elim hex f, }, end example : (¬ ∀ x, p x) ↔ (∃ x, ¬ p x) := begin split, { assume hnfa, apply by_contradiction, assume hnex, have hfa : ∀ (x : α), p x, assume ha, apply by_contradiction, assume hpnha, exact hnex ⟨ha, hpnha⟩, exact hnfa hfa, }, { assume hex, assume hfa, exact ( match hex with ⟨ha, hnpa⟩ := hnpa (hfa ha) end ), }, end example : (∀ x, p x → r) ↔ (∃ x, p x) → r := begin split, { assume hfa, assume hex, have f : (∀ (x : α), (λ (y : α), p y) x → r), assume ha, assume hpa, exact (hfa ha) hpa, exact exists.elim hex f, }, { assume h, assume ha, assume hpa, exact h (exists.intro ha hpa), }, end example : (∃ x, p x → r) ↔ (∀ x, p x) → r := begin split, { assume hex, assume hfa, have f : (∀ (a : α), (λ (x : α), p x → r) a → r), assume ha, assume hpar, apply hpar, exact hfa ha, exact exists.elim hex f, }, { assume h, eapply by_cases, assume hfa : ∀ (x : α), p x, exact ⟨a, (λ hpa, h hfa)⟩, assume hnfa, have hnex : ∃ (x : α), ¬p x, { apply by_contradiction, assume hnex, have hfa : ∀ (x : α), p x, { assume ha, apply by_contradiction, assume hnpa, exact hnex ⟨ha, hnpa⟩, }, exact hnfa hfa, }, exact ( match hnex with ⟨x, hnpx⟩ := ⟨x, (λ hpx : p x, absurd hpx hnpx)⟩ end ), }, end example : (∃ x, r → p x) ↔ (r → ∃ x, p x) := begin split, { assume hex, assume hr, have f : (∀ (a : α), (λ (x : α), r → p x) a → (∃ y : α, p y)), assume ha, assume hrpha, exact exists.intro ha (hrpha hr), exact exists.elim hex f, }, { assume h, eapply by_cases, assume hr : r, exact ( match h hr with ⟨ha, hpa⟩ := ⟨ha, (λ hr' : r, hpa)⟩ end ), assume hnr : ¬r, exact ⟨a, (λ hr : r, absurd hr hnr)⟩, }, end end -- Exercise 6 -- -- Give a calculational proof of the theorem log_mul below. section variables (real : Type) [ordered_ring real] variables (log exp : real → real) variable log_exp_eq : ∀ x, log (exp x) = x variable exp_log_eq : ∀ {x}, x > 0 → exp (log x) = x variable exp_pos : ∀ x, exp x > 0 variable exp_add : ∀ x y, exp (x + y) = exp x * exp y -- this ensures the assumptions are available in tactic proofs include log_exp_eq exp_log_eq exp_pos exp_add example (x y z : real) : exp (x + y + z) = exp x * exp y * exp z := by rw [exp_add, exp_add] example (y : real) (h : y > 0) : exp (log y) = y := exp_log_eq h theorem log_mul {x y : real} (hx : x > 0) (hy : y > 0) : log (x * y) = log x + log y := begin rw <- exp_log_eq hx, rw <- exp_log_eq hy, rw <- exp_add, repeat {rw log_exp_eq}, end end -- Exericse 7 -- -- Prove the theorem below, using only the ring properties of ℤ enumerated in -- Section 4.2 and the theorem sub_self. section #check sub_self example (x : ℤ) : x * 0 = 0 := begin -- NOTE: Is this supposed to be harder? I think that mul_zero is a property -- of rings. rw mul_zero, end end
448bc308e8f07f577e18d92561440f1d1721f396
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/fact_pi.lean
486fe5b0ef338be7a0cf61299347555d5221b550
[ "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
124
lean
@[class] def fact (p : Prop) := p example {P Q R : Prop} [fact (P → Q → R)] : fact (P → Q → R) := by apply_instance
de5eb65b2a288186086ace2879861509aabe94f9
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/compiler/uint_fold.lean
c989d63e6cb9bee40ca523a850b7534cd997ccf8
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
561
lean
@[noinline] def h (x : Nat) : UInt32 := UInt32.ofNat x def f (x y : UInt32) : UInt32 := let a1 : UInt32 := 128 * 100 - 100; let v : Nat := 10 + x.toNat; let a2 : UInt32 := x + a1; let a3 : UInt32 := 10; y + a2 + h v + a3 partial def g : UInt32 → UInt32 → UInt32 | x, y => if x = 0 then y else g (x-1) (y+2) def foo : UInt8 := let x : UInt8 := 100; x + x + x def main : IO UInt32 := IO.println (toString (f 10 20)) *> IO.println (toString (f 0 0)) *> IO.println (toString (g 3 5)) *> IO.println (toString (g 0 6)) *> IO.println (toString foo) *> pure 0
7045d712e2d8db633cd047afa173c887ca35cb40
491068d2ad28831e7dade8d6dff871c3e49d9431
/hott/eq2.hlean
1942e40ccaa30895ea1d9489181306f816115a62
[ "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
4,716
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Theorems about 2-dimensional paths -/ import .cubical.square open function namespace eq variables {A B C : Type} {f : A → B} {a a' a₁ a₂ a₃ a₄ : A} {b b' : B} theorem ap_is_constant_eq (p : Πx, f x = b) (q : a = a') : ap_is_constant p q = eq_con_inv_of_con_eq ((eq_of_square (square_of_pathover (apdo p q)))⁻¹ ⬝ whisker_left (p a) (ap_constant q b)) := begin induction q, esimp, generalize (p a), intro p, cases p, apply idpath idp end definition ap_inv2 {p q : a = a'} (r : p = q) : square (ap (ap f) (inverse2 r)) (inverse2 (ap (ap f) r)) (ap_inv f p) (ap_inv f q) := by induction r;exact hrfl definition ap_con2 {p₁ q₁ : a₁ = a₂} {p₂ q₂ : a₂ = a₃} (r₁ : p₁ = q₁) (r₂ : p₂ = q₂) : square (ap (ap f) (r₁ ◾ r₂)) (ap (ap f) r₁ ◾ ap (ap f) r₂) (ap_con f p₁ p₂) (ap_con f q₁ q₂) := by induction r₂;induction r₁;exact hrfl theorem ap_con_right_inv_sq {A B : Type} {a1 a2 : A} (f : A → B) (p : a1 = a2) : square (ap (ap f) (con.right_inv p)) (con.right_inv (ap f p)) (ap_con f p p⁻¹ ⬝ whisker_left _ (ap_inv f p)) idp := by cases p;apply hrefl theorem ap_con_left_inv_sq {A B : Type} {a1 a2 : A} (f : A → B) (p : a1 = a2) : square (ap (ap f) (con.left_inv p)) (con.left_inv (ap f p)) (ap_con f p⁻¹ p ⬝ whisker_right (ap_inv f p) _) idp := by cases p;apply vrefl theorem ap_ap_is_constant {A B C : Type} (g : B → C) {f : A → B} {b : B} (p : Πx, f x = b) {x y : A} (q : x = y) : square (ap (ap g) (ap_is_constant p q)) (ap_is_constant (λa, ap g (p a)) q) (ap_compose g f q)⁻¹ (!ap_con ⬝ whisker_left _ !ap_inv) := begin induction q, esimp, generalize (p x), intro p, cases p, apply ids -- induction q, rewrite [↑ap_compose,ap_inv], apply hinverse, apply ap_con_right_inv_sq, end theorem ap_ap_compose {A B C D : Type} (h : C → D) (g : B → C) (f : A → B) {x y : A} (p : x = y) : square (ap_compose (h ∘ g) f p) (ap (ap h) (ap_compose g f p)) (ap_compose h (g ∘ f) p) (ap_compose h g (ap f p)) := by induction p;exact ids theorem ap_compose_inv {A B C : Type} (g : B → C) (f : A → B) {x y : A} (p : x = y) : square (ap_compose g f p⁻¹) (inverse2 (ap_compose g f p) ⬝ (ap_inv g (ap f p))⁻¹) (ap_inv (g ∘ f) p) (ap (ap g) (ap_inv f p)) := by induction p;exact ids theorem ap_compose_con (g : B → C) (f : A → B) (p : a₁ = a₂) (q : a₂ = a₃) : square (ap_compose g f (p ⬝ q)) (ap_compose g f p ◾ ap_compose g f q ⬝ (ap_con g (ap f p) (ap f q))⁻¹) (ap_con (g ∘ f) p q) (ap (ap g) (ap_con f p q)) := by induction q;induction p;exact ids theorem ap_compose_natural {A B C : Type} (g : B → C) (f : A → B) {x y : A} {p q : x = y} (r : p = q) : square (ap (ap (g ∘ f)) r) (ap (ap g ∘ ap f) r) (ap_compose g f p) (ap_compose g f q) := natural_square (ap_compose g f) r theorem ap_eq_of_con_inv_eq_idp (f : A → B) {p q : a₁ = a₂} (r : p ⬝ q⁻¹ = idp) : ap02 f (eq_of_con_inv_eq_idp r) = eq_of_con_inv_eq_idp (whisker_left _ !ap_inv⁻¹ ⬝ !ap_con⁻¹ ⬝ ap02 f r) := by induction q;esimp at *;cases r;reflexivity theorem eq_of_con_inv_eq_idp_con2 {p p' q q' : a₁ = a₂} (r : p = p') (s : q = q') (t : p' ⬝ q'⁻¹ = idp) : eq_of_con_inv_eq_idp (r ◾ inverse2 s ⬝ t) = r ⬝ eq_of_con_inv_eq_idp t ⬝ s⁻¹ := by induction s;induction r;induction q;reflexivity -- definition naturality_apdo {A : Type} {B : A → Type} {a a₂ : A} {f g : Πa, B a} -- (H : f ~ g) (p : a = a₂) -- : squareover B vrfl (apdo f p) (apdo g p) -- (pathover_idp_of_eq (H a)) (pathover_idp_of_eq (H a₂)) := -- by induction p;esimp;exact hrflo definition naturality_apdo_eq {A : Type} {B : A → Type} {a a₂ : A} {f g : Πa, B a} (H : f ~ g) (p : a = a₂) : apdo f p = concato_eq (eq_concato (H a) (apdo g p)) (H a₂)⁻¹ := begin induction p, esimp, generalizes [H a, g a], intro ga Ha, induction Ha, reflexivity end theorem con_tr_idp {P : A → Type} {x y : A} (q : x = y) (u : P x) : con_tr idp q u = ap (λp, p ▸ u) (idp_con q) := by induction q;reflexivity end eq
38340b0c9e19ed718835fe3ff6a8167ab53d5381
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/algebra/free_algebra.lean
179509da0ecdbb04cc7d6dadf122a282453f305d
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
16,046
lean
/- Copyright (c) 2020 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Adam Topaz -/ import algebra.algebra.subalgebra import algebra.monoid_algebra.basic import linear_algebra import data.equiv.transfer_instance /-! # Free Algebras Given a commutative semiring `R`, and a type `X`, we construct the free unital, associative `R`-algebra on `X`. ## Notation 1. `free_algebra R X` is the free algebra itself. It is endowed with an `R`-algebra structure. 2. `free_algebra.ι R` is the function `X → free_algebra R X`. 3. Given a function `f : X → A` to an R-algebra `A`, `lift R f` is the lift of `f` to an `R`-algebra morphism `free_algebra R X → A`. ## Theorems 1. `ι_comp_lift` states that the composition `(lift R f) ∘ (ι R)` is identical to `f`. 2. `lift_unique` states that whenever an R-algebra morphism `g : free_algebra R X → A` is given whose composition with `ι R` is `f`, then one has `g = lift R f`. 3. `hom_ext` is a variant of `lift_unique` in the form of an extensionality theorem. 4. `lift_comp_ι` is a combination of `ι_comp_lift` and `lift_unique`. It states that the lift of the composition of an algebra morphism with `ι` is the algebra morphism itself. 5. `equiv_monoid_algebra_free_monoid : free_algebra R X ≃ₐ[R] monoid_algebra R (free_monoid X)` 6. An inductive principle `induction`. ## Implementation details We construct the free algebra on `X` as a quotient of an inductive type `free_algebra.pre` by an inductively defined relation `free_algebra.rel`. Explicitly, the construction involves three steps: 1. We construct an inductive type `free_algebra.pre R X`, the terms of which should be thought of as representatives for the elements of `free_algebra R X`. It is the free type with maps from `R` and `X`, and with two binary operations `add` and `mul`. 2. We construct an inductive relation `free_algebra.rel R X` on `free_algebra.pre R X`. This is the smallest relation for which the quotient is an `R`-algebra where addition resp. multiplication are induced by `add` resp. `mul` from 1., and for which the map from `R` is the structure map for the algebra. 3. The free algebra `free_algebra R X` is the quotient of `free_algebra.pre R X` by the relation `free_algebra.rel R X`. -/ variables (R : Type*) [comm_semiring R] variables (X : Type*) namespace free_algebra /-- This inductive type is used to express representatives of the free algebra. -/ inductive pre | of : X → pre | of_scalar : R → pre | add : pre → pre → pre | mul : pre → pre → pre namespace pre instance : inhabited (pre R X) := ⟨of_scalar 0⟩ -- Note: These instances are only used to simplify the notation. /-- Coercion from `X` to `pre R X`. Note: Used for notation only. -/ def has_coe_generator : has_coe X (pre R X) := ⟨of⟩ /-- Coercion from `R` to `pre R X`. Note: Used for notation only. -/ def has_coe_semiring : has_coe R (pre R X) := ⟨of_scalar⟩ /-- Multiplication in `pre R X` defined as `pre.mul`. Note: Used for notation only. -/ def has_mul : has_mul (pre R X) := ⟨mul⟩ /-- Addition in `pre R X` defined as `pre.add`. Note: Used for notation only. -/ def has_add : has_add (pre R X) := ⟨add⟩ /-- Zero in `pre R X` defined as the image of `0` from `R`. Note: Used for notation only. -/ def has_zero : has_zero (pre R X) := ⟨of_scalar 0⟩ /-- One in `pre R X` defined as the image of `1` from `R`. Note: Used for notation only. -/ def has_one : has_one (pre R X) := ⟨of_scalar 1⟩ /-- Scalar multiplication defined as multiplication by the image of elements from `R`. Note: Used for notation only. -/ def has_scalar : has_scalar R (pre R X) := ⟨λ r m, mul (of_scalar r) m⟩ end pre local attribute [instance] pre.has_coe_generator pre.has_coe_semiring pre.has_mul pre.has_add pre.has_zero pre.has_one pre.has_scalar /-- Given a function from `X` to an `R`-algebra `A`, `lift_fun` provides a lift of `f` to a function from `pre R X` to `A`. This is mainly used in the construction of `free_algebra.lift`. -/ def lift_fun {A : Type*} [semiring A] [algebra R A] (f : X → A) : pre R X → A := λ t, pre.rec_on t f (algebra_map _ _) (λ _ _, (+)) (λ _ _, (*)) /-- An inductively defined relation on `pre R X` used to force the initial algebra structure on the associated quotient. -/ inductive rel : (pre R X) → (pre R X) → Prop -- force `of_scalar` to be a central semiring morphism | add_scalar {r s : R} : rel ↑(r + s) (↑r + ↑s) | mul_scalar {r s : R} : rel ↑(r * s) (↑r * ↑s) | central_scalar {r : R} {a : pre R X} : rel (r * a) (a * r) -- commutative additive semigroup | add_assoc {a b c : pre R X} : rel (a + b + c) (a + (b + c)) | add_comm {a b : pre R X} : rel (a + b) (b + a) | zero_add {a : pre R X} : rel (0 + a) a -- multiplicative monoid | mul_assoc {a b c : pre R X} : rel (a * b * c) (a * (b * c)) | one_mul {a : pre R X} : rel (1 * a) a | mul_one {a : pre R X} : rel (a * 1) a -- distributivity | left_distrib {a b c : pre R X} : rel (a * (b + c)) (a * b + a * c) | right_distrib {a b c : pre R X} : rel ((a + b) * c) (a * c + b * c) -- other relations needed for semiring | zero_mul {a : pre R X} : rel (0 * a) 0 | mul_zero {a : pre R X} : rel (a * 0) 0 -- compatibility | add_compat_left {a b c : pre R X} : rel a b → rel (a + c) (b + c) | add_compat_right {a b c : pre R X} : rel a b → rel (c + a) (c + b) | mul_compat_left {a b c : pre R X} : rel a b → rel (a * c) (b * c) | mul_compat_right {a b c : pre R X} : rel a b → rel (c * a) (c * b) end free_algebra /-- The free algebra for the type `X` over the commutative semiring `R`. -/ def free_algebra := quot (free_algebra.rel R X) namespace free_algebra local attribute [instance] pre.has_coe_generator pre.has_coe_semiring pre.has_mul pre.has_add pre.has_zero pre.has_one pre.has_scalar instance : semiring (free_algebra R X) := { add := quot.map₂ (+) (λ _ _ _, rel.add_compat_right) (λ _ _ _, rel.add_compat_left), add_assoc := by { rintros ⟨⟩ ⟨⟩ ⟨⟩, exact quot.sound rel.add_assoc }, zero := quot.mk _ 0, zero_add := by { rintro ⟨⟩, exact quot.sound rel.zero_add }, add_zero := begin rintros ⟨⟩, change quot.mk _ _ = _, rw [quot.sound rel.add_comm, quot.sound rel.zero_add], end, add_comm := by { rintros ⟨⟩ ⟨⟩, exact quot.sound rel.add_comm }, mul := quot.map₂ (*) (λ _ _ _, rel.mul_compat_right) (λ _ _ _, rel.mul_compat_left), mul_assoc := by { rintros ⟨⟩ ⟨⟩ ⟨⟩, exact quot.sound rel.mul_assoc }, one := quot.mk _ 1, one_mul := by { rintros ⟨⟩, exact quot.sound rel.one_mul }, mul_one := by { rintros ⟨⟩, exact quot.sound rel.mul_one }, left_distrib := by { rintros ⟨⟩ ⟨⟩ ⟨⟩, exact quot.sound rel.left_distrib }, right_distrib := by { rintros ⟨⟩ ⟨⟩ ⟨⟩, exact quot.sound rel.right_distrib }, zero_mul := by { rintros ⟨⟩, exact quot.sound rel.zero_mul }, mul_zero := by { rintros ⟨⟩, exact quot.sound rel.mul_zero } } instance : inhabited (free_algebra R X) := ⟨0⟩ instance : has_scalar R (free_algebra R X) := { smul := λ r a, quot.lift_on a (λ x, quot.mk _ $ ↑r * x) $ λ a b h, quot.sound (rel.mul_compat_right h) } instance : algebra R (free_algebra R X) := { to_fun := λ r, quot.mk _ r, map_one' := rfl, map_mul' := λ _ _, quot.sound rel.mul_scalar, map_zero' := rfl, map_add' := λ _ _, quot.sound rel.add_scalar, commutes' := λ _, by { rintros ⟨⟩, exact quot.sound rel.central_scalar }, smul_def' := λ _ _, rfl } instance {S : Type*} [comm_ring S] : ring (free_algebra S X) := algebra.semiring_to_ring S variables {X} /-- The canonical function `X → free_algebra R X`. -/ def ι : X → free_algebra R X := λ m, quot.mk _ m @[simp] lemma quot_mk_eq_ι (m : X) : quot.mk (free_algebra.rel R X) m = ι R m := rfl variables {A : Type*} [semiring A] [algebra R A] /-- Internal definition used to define `lift` -/ private def lift_aux (f : X → A) : (free_algebra R X →ₐ[R] A) := { to_fun := λ a, quot.lift_on a (lift_fun _ _ f) $ λ a b h, begin induction h, { exact (algebra_map R A).map_add h_r h_s, }, { exact (algebra_map R A).map_mul h_r h_s }, { apply algebra.commutes }, { change _ + _ + _ = _ + (_ + _), rw add_assoc }, { change _ + _ = _ + _, rw add_comm, }, { change (algebra_map _ _ _) + lift_fun R X f _ = lift_fun R X f _, simp, }, { change _ * _ * _ = _ * (_ * _), rw mul_assoc }, { change (algebra_map _ _ _) * lift_fun R X f _ = lift_fun R X f _, simp, }, { change lift_fun R X f _ * (algebra_map _ _ _) = lift_fun R X f _, simp, }, { change _ * (_ + _) = _ * _ + _ * _, rw left_distrib, }, { change (_ + _) * _ = _ * _ + _ * _, rw right_distrib, }, { change (algebra_map _ _ _) * _ = algebra_map _ _ _, simp }, { change _ * (algebra_map _ _ _) = algebra_map _ _ _, simp }, repeat { change lift_fun R X f _ + lift_fun R X f _ = _, rw h_ih, refl, }, repeat { change lift_fun R X f _ * lift_fun R X f _ = _, rw h_ih, refl, }, end, map_one' := by { change algebra_map _ _ _ = _, simp }, map_mul' := by { rintros ⟨⟩ ⟨⟩, refl }, map_zero' := by { change algebra_map _ _ _ = _, simp }, map_add' := by { rintros ⟨⟩ ⟨⟩, refl }, commutes' := by tauto } /-- Given a function `f : X → A` where `A` is an `R`-algebra, `lift R f` is the unique lift of `f` to a morphism of `R`-algebras `free_algebra R X → A`. -/ def lift : (X → A) ≃ (free_algebra R X →ₐ[R] A) := { to_fun := lift_aux R, inv_fun := λ F, F ∘ (ι R), left_inv := λ f, by {ext, refl}, right_inv := λ F, by { ext x, rcases x, induction x, case pre.of : { change ((F : free_algebra R X → A) ∘ (ι R)) _ = _, refl }, case pre.of_scalar : { change algebra_map _ _ x = F (algebra_map _ _ x), rw alg_hom.commutes F x, }, case pre.add : a b ha hb { change lift_aux R (F ∘ ι R) (quot.mk _ _ + quot.mk _ _) = F (quot.mk _ _ + quot.mk _ _), rw [alg_hom.map_add, alg_hom.map_add, ha, hb], }, case pre.mul : a b ha hb { change lift_aux R (F ∘ ι R) (quot.mk _ _ * quot.mk _ _) = F (quot.mk _ _ * quot.mk _ _), rw [alg_hom.map_mul, alg_hom.map_mul, ha, hb], }, }, } @[simp] lemma lift_aux_eq (f : X → A) : lift_aux R f = lift R f := rfl @[simp] lemma lift_symm_apply (F : free_algebra R X →ₐ[R] A) : (lift R).symm F = F ∘ (ι R) := rfl variables {R X} @[simp] theorem ι_comp_lift (f : X → A) : (lift R f : free_algebra R X → A) ∘ (ι R) = f := by {ext, refl} @[simp] theorem lift_ι_apply (f : X → A) (x) : lift R f (ι R x) = f x := rfl @[simp] theorem lift_unique (f : X → A) (g : free_algebra R X →ₐ[R] A) : (g : free_algebra R X → A) ∘ (ι R) = f ↔ g = lift R f := (lift R).symm_apply_eq /-! At this stage we set the basic definitions as `@[irreducible]`, so from this point onwards one should only use the universal properties of the free algebra, and consider the actual implementation as a quotient of an inductive type as completely hidden. Of course, one still has the option to locally make these definitions `semireducible` if so desired, and Lean is still willing in some circumstances to do unification based on the underlying definition. -/ attribute [irreducible] ι lift -- Marking `free_algebra` irreducible makes `ring` instances inaccessible on quotients. -- https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/algebra.2Esemiring_to_ring.20breaks.20semimodule.20typeclass.20lookup/near/212580241 -- For now, we avoid this by not marking it irreducible. @[simp] theorem lift_comp_ι (g : free_algebra R X →ₐ[R] A) : lift R ((g : free_algebra R X → A) ∘ (ι R)) = g := by { rw ←lift_symm_apply, exact (lift R).apply_symm_apply g } /-- See note [partially-applied ext lemmas]. -/ @[ext] theorem hom_ext {f g : free_algebra R X →ₐ[R] A} (w : ((f : free_algebra R X → A) ∘ (ι R)) = ((g : free_algebra R X → A) ∘ (ι R))) : f = g := begin rw [←lift_symm_apply, ←lift_symm_apply] at w, exact (lift R).symm.injective w, end /-- The free algebra on `X` is "just" the monoid algebra on the free monoid on `X`. This would be useful when constructing linear maps out of a free algebra, for example. -/ noncomputable def equiv_monoid_algebra_free_monoid : free_algebra R X ≃ₐ[R] monoid_algebra R (free_monoid X) := alg_equiv.of_alg_hom (lift R (λ x, (monoid_algebra.of R (free_monoid X)) (free_monoid.of x))) ((monoid_algebra.lift R (free_monoid X) (free_algebra R X)) (free_monoid.lift (ι R))) begin apply monoid_algebra.alg_hom_ext, intro x, apply free_monoid.rec_on x, { simp, refl, }, { intros x y ih, simp at ih, simp [ih], } end (by { ext, simp, }) instance [nontrivial R] : nontrivial (free_algebra R X) := equiv_monoid_algebra_free_monoid.to_equiv.nontrivial section open_locale classical /-- The left-inverse of `algebra_map`. -/ def algebra_map_inv : free_algebra R X →ₐ[R] R := lift R (0 : X → R) lemma algebra_map_left_inverse : function.left_inverse algebra_map_inv (algebra_map R $ free_algebra R X) := λ x, by simp [algebra_map_inv] -- this proof is copied from the approach in `free_abelian_group.of_injective` lemma ι_injective [nontrivial R] : function.injective (ι R : X → free_algebra R X) := λ x y hoxy, classical.by_contradiction $ assume hxy : x ≠ y, let f : free_algebra R X →ₐ[R] R := lift R (λ z, if x = z then (1 : R) else 0) in have hfx1 : f (ι R x) = 1, from (lift_ι_apply _ _).trans $ if_pos rfl, have hfy1 : f (ι R y) = 1, from hoxy ▸ hfx1, have hfy0 : f (ι R y) = 0, from (lift_ι_apply _ _).trans $ if_neg hxy, one_ne_zero $ hfy1.symm.trans hfy0 end end free_algebra /- There is something weird in the above namespace that breaks the typeclass resolution of `has_coe_to_sort` below. Closing it and reopening it fixes it... -/ namespace free_algebra /-- An induction principle for the free algebra. If `C` holds for the `algebra_map` of `r : R` into `free_algebra R X`, the `ι` of `x : X`, and is preserved under addition and muliplication, then it holds for all of `free_algebra R X`. -/ @[elab_as_eliminator] lemma induction {C : free_algebra R X → Prop} (h_grade0 : ∀ r, C (algebra_map R (free_algebra R X) r)) (h_grade1 : ∀ x, C (ι R x)) (h_mul : ∀ a b, C a → C b → C (a * b)) (h_add : ∀ a b, C a → C b → C (a + b)) (a : free_algebra R X) : C a := begin -- the arguments are enough to construct a subalgebra, and a mapping into it from X let s : subalgebra R (free_algebra R X) := { carrier := C, mul_mem' := h_mul, add_mem' := h_add, algebra_map_mem' := h_grade0, }, let of : X → s := subtype.coind (ι R) h_grade1, -- the mapping through the subalgebra is the identity have of_id : alg_hom.id R (free_algebra R X) = s.val.comp (lift R of), { ext, simp [of, subtype.coind], }, -- finding a proof is finding an element of the subalgebra convert subtype.prop (lift R of a), simp [alg_hom.ext_iff] at of_id, exact of_id a, end /-- The star ring formed by reversing the elements of products -/ instance : star_ring (free_algebra R X) := { star := opposite.unop ∘ lift R (opposite.op ∘ ι R), star_involutive := λ x, by { unfold has_star.star, simp only [function.comp_apply], refine free_algebra.induction R X _ _ _ _ x; intros; simp [*] }, star_mul := λ a b, by simp, star_add := λ a b, by simp } @[simp] lemma star_ι (x : X) : star (ι R x) = (ι R x) := by simp [star, has_star.star] @[simp] lemma star_algebra_map (r : R) : star (algebra_map R (free_algebra R X) r) = (algebra_map R _ r) := by simp [star, has_star.star] /-- `star` as an `alg_equiv` -/ def star_hom : free_algebra R X ≃ₐ[R] (free_algebra R X)ᵒᵖ := { commutes' := λ r, by simp [star_algebra_map], ..star_ring_equiv } end free_algebra
2186ef1c29492866a94a6c7ddd370b6963cf01d9
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/topology/instances/real.lean
e3d1f10ada31a25ad323c51be8e2f878acb6f36a
[ "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
14,449
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import topology.metric_space.basic import topology.algebra.uniform_group import topology.algebra.ring import ring_theory.subring import group_theory.archimedean /-! # Topological properties of ℝ -/ noncomputable theory open classical set filter topological_space metric open_locale classical open_locale topological_space universes u v w variables {α : Type u} {β : Type v} {γ : Type w} instance : metric_space ℚ := metric_space.induced coe rat.cast_injective real.metric_space theorem rat.dist_eq (x y : ℚ) : dist x y = abs (x - y) := rfl @[norm_cast, simp] lemma rat.dist_cast (x y : ℚ) : dist (x : ℝ) y = dist x y := rfl section low_prio -- we want to ignore this instance for the next declaration local attribute [instance, priority 10] int.uniform_space instance : metric_space ℤ := begin letI M := metric_space.induced coe int.cast_injective real.metric_space, refine @metric_space.replace_uniformity _ int.uniform_space M (le_antisymm refl_le_uniformity $ λ r ru, mem_uniformity_dist.2 ⟨1, zero_lt_one, λ a b h, mem_principal_sets.1 ru $ dist_le_zero.1 (_ : (abs (a - b) : ℝ) ≤ 0)⟩), have : (abs (↑a - ↑b) : ℝ) < 1 := h, have : abs (a - b) < 1, by norm_cast at this; assumption, have : abs (a - b) ≤ 0 := (@int.lt_add_one_iff _ 0).mp this, norm_cast, assumption end end low_prio theorem int.dist_eq (x y : ℤ) : dist x y = abs (x - y) := rfl @[norm_cast, simp] theorem int.dist_cast_real (x y : ℤ) : dist (x : ℝ) y = dist x y := rfl @[norm_cast, simp] theorem int.dist_cast_rat (x y : ℤ) : dist (x : ℚ) y = dist x y := by rw [← int.dist_cast_real, ← rat.dist_cast]; congr' 1; norm_cast instance : proper_space ℤ := ⟨ begin intros x r, apply set.finite.is_compact, have : closed_ball x r = coe ⁻¹' (closed_ball (x:ℝ) r) := rfl, simp [this, closed_ball_Icc, set.Icc_ℤ_finite], end ⟩ theorem uniform_continuous_of_rat : uniform_continuous (coe : ℚ → ℝ) := uniform_continuous_comap theorem uniform_embedding_of_rat : uniform_embedding (coe : ℚ → ℝ) := uniform_embedding_comap rat.cast_injective theorem dense_embedding_of_rat : dense_embedding (coe : ℚ → ℝ) := uniform_embedding_of_rat.dense_embedding $ λ x, mem_closure_iff_nhds.2 $ λ t ht, let ⟨ε,ε0, hε⟩ := mem_nhds_iff.1 ht in let ⟨q, h⟩ := exists_rat_near x ε0 in ⟨_, hε (mem_ball'.2 h), q, rfl⟩ theorem embedding_of_rat : embedding (coe : ℚ → ℝ) := dense_embedding_of_rat.to_embedding theorem continuous_of_rat : continuous (coe : ℚ → ℝ) := uniform_continuous_of_rat.continuous theorem real.uniform_continuous_add : uniform_continuous (λp : ℝ × ℝ, p.1 + p.2) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_add_continuous_lemma abs ε0 in ⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ h₁ h₂⟩ -- TODO(Mario): Find a way to use rat_add_continuous_lemma theorem rat.uniform_continuous_add : uniform_continuous (λp : ℚ × ℚ, p.1 + p.2) := uniform_embedding_of_rat.to_uniform_inducing.uniform_continuous_iff.2 $ by simp [(∘)]; exact real.uniform_continuous_add.comp ((uniform_continuous_of_rat.comp uniform_continuous_fst).prod_mk (uniform_continuous_of_rat.comp uniform_continuous_snd)) theorem real.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℝ _) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h, by rw dist_comm at h; simpa [real.dist_eq] using h⟩ theorem rat.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℚ _) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h, by rw dist_comm at h; simpa [rat.dist_eq] using h⟩ instance : uniform_add_group ℝ := uniform_add_group.mk' real.uniform_continuous_add real.uniform_continuous_neg instance : uniform_add_group ℚ := uniform_add_group.mk' rat.uniform_continuous_add rat.uniform_continuous_neg -- short-circuit type class inference instance : topological_add_group ℝ := by apply_instance instance : topological_add_group ℚ := by apply_instance instance : order_topology ℚ := induced_order_topology _ (λ x y, rat.cast_lt) (@exists_rat_btwn _ _ _) instance : proper_space ℝ := { compact_ball := λx r, by { rw closed_ball_Icc, apply compact_Icc } } instance : second_countable_topology ℝ := second_countable_of_proper lemma real.is_topological_basis_Ioo_rat : @is_topological_basis ℝ _ (⋃(a b : ℚ) (h : a < b), {Ioo a b}) := is_topological_basis_of_open_of_nhds (by simp [is_open_Ioo] {contextual:=tt}) (assume a v hav hv, let ⟨l, u, ⟨hl, hu⟩, h⟩ := mem_nhds_iff_exists_Ioo_subset.mp (mem_nhds_sets hv hav), ⟨q, hlq, hqa⟩ := exists_rat_btwn hl, ⟨p, hap, hpu⟩ := exists_rat_btwn hu in ⟨Ioo q p, by { simp only [mem_Union], exact ⟨q, p, rat.cast_lt.1 $ hqa.trans hap, rfl⟩ }, ⟨hqa, hap⟩, assume a' ⟨hqa', ha'p⟩, h ⟨hlq.trans hqa', ha'p.trans hpu⟩⟩) /- TODO(Mario): Prove that these are uniform isomorphisms instead of uniform embeddings lemma uniform_embedding_add_rat {r : ℚ} : uniform_embedding (λp:ℚ, p + r) := _ lemma uniform_embedding_mul_rat {q : ℚ} (hq : q ≠ 0) : uniform_embedding ((*) q) := _ -/ lemma real.mem_closure_iff {s : set ℝ} {x : ℝ} : x ∈ closure s ↔ ∀ ε > 0, ∃ y ∈ s, abs (y - x) < ε := by simp [mem_closure_iff_nhds_basis nhds_basis_ball, real.dist_eq] lemma real.uniform_continuous_inv (s : set ℝ) {r : ℝ} (r0 : 0 < r) (H : ∀ x ∈ s, r ≤ abs x) : uniform_continuous (λp:s, p.1⁻¹) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_inv_continuous_lemma abs ε0 r0 in ⟨δ, δ0, λ a b h, Hδ (H _ a.2) (H _ b.2) h⟩ lemma real.uniform_continuous_abs : uniform_continuous (abs : ℝ → ℝ) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨ε, ε0, λ a b, lt_of_le_of_lt (abs_abs_sub_abs_le_abs_sub _ _)⟩ lemma rat.uniform_continuous_abs : uniform_continuous (abs : ℚ → ℚ) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨ε, ε0, λ a b h, lt_of_le_of_lt (by simpa [rat.dist_eq] using abs_abs_sub_abs_le_abs_sub _ _) h⟩ lemma real.tendsto_inv {r : ℝ} (r0 : r ≠ 0) : tendsto (λq, q⁻¹) (𝓝 r) (𝓝 r⁻¹) := by rw ← abs_pos at r0; exact tendsto_of_uniform_continuous_subtype (real.uniform_continuous_inv {x | abs r / 2 < abs x} (half_pos r0) (λ x h, le_of_lt h)) (mem_nhds_sets ((is_open_lt' (abs r / 2)).preimage continuous_abs) (half_lt_self r0)) lemma real.continuous_inv : continuous (λa:{r:ℝ // r ≠ 0}, a.val⁻¹) := continuous_iff_continuous_at.mpr $ assume ⟨r, hr⟩, tendsto.comp (real.tendsto_inv hr) (continuous_iff_continuous_at.mp continuous_subtype_val _) lemma real.continuous.inv [topological_space α] {f : α → ℝ} (h : ∀a, f a ≠ 0) (hf : continuous f) : continuous (λa, (f a)⁻¹) := show continuous ((has_inv.inv ∘ @subtype.val ℝ (λr, r ≠ 0)) ∘ λa, ⟨f a, h a⟩), from real.continuous_inv.comp (continuous_subtype_mk _ hf) lemma real.uniform_continuous_mul_const {x : ℝ} : uniform_continuous ((*) x) := metric.uniform_continuous_iff.2 $ λ ε ε0, begin cases no_top (abs x) with y xy, have y0 := lt_of_le_of_lt (abs_nonneg _) xy, refine ⟨_, div_pos ε0 y0, λ a b h, _⟩, rw [real.dist_eq, ← mul_sub, abs_mul, ← mul_div_cancel' ε (ne_of_gt y0)], exact mul_lt_mul' (le_of_lt xy) h (abs_nonneg _) y0 end lemma real.uniform_continuous_mul (s : set (ℝ × ℝ)) {r₁ r₂ : ℝ} (H : ∀ x ∈ s, abs (x : ℝ × ℝ).1 < r₁ ∧ abs x.2 < r₂) : uniform_continuous (λp:s, p.1.1 * p.1.2) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_mul_continuous_lemma abs ε0 in ⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ (H _ a.2).1 (H _ b.2).2 h₁ h₂⟩ protected lemma real.continuous_mul : continuous (λp : ℝ × ℝ, p.1 * p.2) := continuous_iff_continuous_at.2 $ λ ⟨a₁, a₂⟩, tendsto_of_uniform_continuous_subtype (real.uniform_continuous_mul ({x | abs x < abs a₁ + 1}.prod {x | abs x < abs a₂ + 1}) (λ x, id)) (mem_nhds_sets (((is_open_gt' (abs a₁ + 1)).preimage continuous_abs).prod ((is_open_gt' (abs a₂ + 1)).preimage continuous_abs )) ⟨lt_add_one (abs a₁), lt_add_one (abs a₂)⟩) instance : topological_ring ℝ := { continuous_mul := real.continuous_mul, ..real.topological_add_group } instance : topological_semiring ℝ := by apply_instance -- short-circuit type class inference lemma rat.continuous_mul : continuous (λp : ℚ × ℚ, p.1 * p.2) := embedding_of_rat.continuous_iff.2 $ by simp [(∘)]; exact real.continuous_mul.comp ((continuous_of_rat.comp continuous_fst).prod_mk (continuous_of_rat.comp continuous_snd)) instance : topological_ring ℚ := { continuous_mul := rat.continuous_mul, ..rat.topological_add_group } theorem real.ball_eq_Ioo (x ε : ℝ) : ball x ε = Ioo (x - ε) (x + ε) := set.ext $ λ y, by rw [mem_ball, real.dist_eq, abs_sub_lt_iff, sub_lt_iff_lt_add', and_comm, sub_lt]; refl theorem real.Ioo_eq_ball (x y : ℝ) : Ioo x y = ball ((x + y) / 2) ((y - x) / 2) := by rw [real.ball_eq_Ioo, ← sub_div, add_comm, ← sub_add, add_sub_cancel', add_self_div_two, ← add_div, add_assoc, add_sub_cancel'_right, add_self_div_two] instance : complete_space ℝ := begin apply complete_of_cauchy_seq_tendsto, intros u hu, let c : cau_seq ℝ abs := ⟨u, cauchy_seq_iff'.1 hu⟩, refine ⟨c.lim, λ s h, _⟩, rcases metric.mem_nhds_iff.1 h with ⟨ε, ε0, hε⟩, have := c.equiv_lim ε ε0, simp only [mem_map, mem_at_top_sets, mem_set_of_eq], refine this.imp (λ N hN n hn, hε (hN n hn)) end lemma real.totally_bounded_ball (x ε : ℝ) : totally_bounded (ball x ε) := by rw real.ball_eq_Ioo; apply totally_bounded_Ioo lemma rat.totally_bounded_Icc (a b : ℚ) : totally_bounded (Icc a b) := begin have := totally_bounded_preimage uniform_embedding_of_rat (totally_bounded_Icc a b), rwa (set.ext (λ q, _) : Icc _ _ = _), simp end section lemma closure_of_rat_image_lt {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q < x}) = {r | ↑q ≤ r} := subset.antisymm ((is_closed_ge' _).closure_subset_iff.2 (image_subset_iff.2 $ λ p h, le_of_lt $ (@rat.cast_lt ℝ _ _ _).2 h)) $ λ x hx, mem_closure_iff_nhds.2 $ λ t ht, let ⟨ε, ε0, hε⟩ := metric.mem_nhds_iff.1 ht in let ⟨p, h₁, h₂⟩ := exists_rat_btwn ((lt_add_iff_pos_right x).2 ε0) in ⟨_, hε (show abs _ < _, by rwa [abs_of_nonneg (le_of_lt $ sub_pos.2 h₁), sub_lt_iff_lt_add']), p, rat.cast_lt.1 (@lt_of_le_of_lt ℝ _ _ _ _ hx h₁), rfl⟩ /- TODO(Mario): Put these back only if needed later lemma closure_of_rat_image_le_eq {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q ≤ x}) = {r | ↑q ≤ r} := _ lemma closure_of_rat_image_le_le_eq {a b : ℚ} (hab : a ≤ b) : closure (of_rat '' {q:ℚ | a ≤ q ∧ q ≤ b}) = {r:ℝ | of_rat a ≤ r ∧ r ≤ of_rat b} := _-/ lemma real.bounded_iff_bdd_below_bdd_above {s : set ℝ} : bounded s ↔ bdd_below s ∧ bdd_above s := ⟨begin assume bdd, rcases (bounded_iff_subset_ball 0).1 bdd with ⟨r, hr⟩, -- hr : s ⊆ closed_ball 0 r rw closed_ball_Icc at hr, -- hr : s ⊆ Icc (0 - r) (0 + r) exact ⟨⟨-r, λy hy, by simpa using (hr hy).1⟩, ⟨r, λy hy, by simpa using (hr hy).2⟩⟩ end, begin rintros ⟨⟨m, hm⟩, ⟨M, hM⟩⟩, have I : s ⊆ Icc m M := λx hx, ⟨hm hx, hM hx⟩, have : Icc m M = closed_ball ((m+M)/2) ((M-m)/2) := by rw closed_ball_Icc; congr; ring, rw this at I, exact bounded.subset I bounded_closed_ball end⟩ lemma real.image_Icc {f : ℝ → ℝ} {a b : ℝ} (hab : a ≤ b) (h : continuous_on f $ Icc a b) : f '' Icc a b = Icc (Inf $ f '' Icc a b) (Sup $ f '' Icc a b) := eq_Icc_of_connected_compact ⟨(nonempty_Icc.2 hab).image f, is_preconnected_Icc.image f h⟩ (compact_Icc.image_of_continuous_on h) end section subgroups /-- Given a nontrivial subgroup `G ⊆ ℝ`, if `G ∩ ℝ_{>0}` has no minimum then `G` is dense. -/ lemma real.subgroup_dense_of_no_min {G : add_subgroup ℝ} {g₀ : ℝ} (g₀_in : g₀ ∈ G) (g₀_ne : g₀ ≠ 0) (H' : ¬ ∃ a : ℝ, is_least {g : ℝ | g ∈ G ∧ 0 < g} a) : dense (G : set ℝ) := begin let G_pos := {g : ℝ | g ∈ G ∧ 0 < g}, push_neg at H', intros x, suffices : ∀ ε > (0 : ℝ), ∃ g ∈ G, abs (x - g) < ε, by simpa only [real.mem_closure_iff, abs_sub], intros ε ε_pos, obtain ⟨g₁, g₁_in, g₁_pos⟩ : ∃ g₁ : ℝ, g₁ ∈ G ∧ 0 < g₁, { cases lt_or_gt_of_ne g₀_ne with Hg₀ Hg₀, { exact ⟨-g₀, G.neg_mem g₀_in, neg_pos.mpr Hg₀⟩ }, { exact ⟨g₀, g₀_in, Hg₀⟩ } }, obtain ⟨a, ha⟩ : ∃ a, is_glb G_pos a := ⟨Inf G_pos, is_glb_cInf ⟨g₁, g₁_in, g₁_pos⟩ ⟨0, λ _ hx, le_of_lt hx.2⟩⟩, have a_notin : a ∉ G_pos, { intros H, exact H' a ⟨H, ha.1⟩ }, obtain ⟨g₂, g₂_in, g₂_pos, g₂_lt⟩ : ∃ g₂ : ℝ, g₂ ∈ G ∧ 0 < g₂ ∧ g₂ < ε, { obtain ⟨b, hb, hb', hb''⟩ := ha.exists_between_self_add' a_notin ε_pos, obtain ⟨c, hc, hc', hc''⟩ := ha.exists_between_self_add' a_notin (sub_pos.2 hb'), refine ⟨b - c, G.sub_mem hb.1 hc.1, _, _⟩ ; linarith }, refine ⟨floor (x/g₂) * g₂, _, _⟩, { exact add_subgroup.int_mul_mem _ g₂_in }, { rw abs_of_nonneg (sub_floor_div_mul_nonneg x g₂_pos), linarith [sub_floor_div_mul_lt x g₂_pos] } end /-- Subgroups of `ℝ` are either dense or cyclic. See `real.subgroup_dense_of_no_min` and `subgroup_cyclic_of_min` for more precise statements. -/ lemma real.subgroup_dense_or_cyclic (G : add_subgroup ℝ) : dense (G : set ℝ) ∨ ∃ a : ℝ, G = add_subgroup.closure {a} := begin cases add_subgroup.bot_or_exists_ne_zero G with H H, { right, use 0, rw [H, add_subgroup.closure_singleton_zero] }, { let G_pos := {g : ℝ | g ∈ G ∧ 0 < g}, by_cases H' : ∃ a, is_least G_pos a, { right, rcases H' with ⟨a, ha⟩, exact ⟨a, add_subgroup.cyclic_of_min ha⟩ }, { left, rcases H with ⟨g₀, g₀_in, g₀_ne⟩, exact real.subgroup_dense_of_no_min g₀_in g₀_ne H' } } end end subgroups
ea354f9f1f9cec0017f4d7f47d3d5214a7ca50b9
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/equiv/encodable/basic_auto.lean
a734a42b073e73c2a2a59e72ffe59ca622b846e9
[]
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
15,766
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura, Mario Carneiro Type class for encodable Types. Note that every encodable Type is countable. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.equiv.nat import Mathlib.order.rel_iso import Mathlib.order.directed import Mathlib.PostPort universes u_1 l u_2 u_3 namespace Mathlib /-- An encodable type is a "constructively countable" type. This is where we have an explicit injection `encode : α → nat` and a partial inverse `decode : nat → option α`. This makes the range of `encode` decidable, although it is not decidable if `α` is finite or not. -/ class encodable (α : Type u_1) where encode : α → ℕ decode : ℕ → Option α encodek : ∀ (a : α), decode (encode a) = some a namespace encodable theorem encode_injective {α : Type u_1} [encodable α] : function.injective encode := sorry /- This is not set as an instance because this is usually not the best way to infer decidability. -/ def decidable_eq_of_encodable (α : Type u_1) [encodable α] : DecidableEq α := sorry def of_left_injection {α : Type u_1} {β : Type u_2} [encodable α] (f : β → α) (finv : α → Option β) (linv : ∀ (b : β), finv (f b) = some b) : encodable β := mk (fun (b : β) => encode (f b)) (fun (n : ℕ) => option.bind (decode α n) finv) sorry def of_left_inverse {α : Type u_1} {β : Type u_2} [encodable α] (f : β → α) (finv : α → β) (linv : ∀ (b : β), finv (f b) = b) : encodable β := of_left_injection f (some ∘ finv) sorry /-- If `α` is encodable and `β ≃ α`, then so is `β` -/ def of_equiv {β : Type u_2} (α : Type u_1) [encodable α] (e : β ≃ α) : encodable β := of_left_inverse (⇑e) (⇑(equiv.symm e)) (equiv.left_inv e) @[simp] theorem encode_of_equiv {α : Type u_1} {β : Type u_2} [encodable α] (e : β ≃ α) (b : β) : encode b = encode (coe_fn e b) := rfl @[simp] theorem decode_of_equiv {α : Type u_1} {β : Type u_2} [encodable α] (e : β ≃ α) (n : ℕ) : decode β n = option.map (⇑(equiv.symm e)) (decode α n) := rfl protected instance nat : encodable ℕ := mk id some sorry @[simp] theorem encode_nat (n : ℕ) : encode n = n := rfl @[simp] theorem decode_nat (n : ℕ) : decode ℕ n = some n := rfl protected instance empty : encodable empty := mk (fun (a : empty) => empty.rec (fun (a : empty) => ℕ) a) (fun (n : ℕ) => none) sorry protected instance unit : encodable PUnit := mk (fun (_x : PUnit) => 0) (fun (n : ℕ) => nat.cases_on n (some PUnit.unit) fun (_x : ℕ) => none) sorry @[simp] theorem encode_star : encode PUnit.unit = 0 := rfl @[simp] theorem decode_unit_zero : decode PUnit 0 = some PUnit.unit := rfl @[simp] theorem decode_unit_succ (n : ℕ) : decode PUnit (Nat.succ n) = none := rfl protected instance option {α : Type u_1} [h : encodable α] : encodable (Option α) := mk (fun (o : Option α) => option.cases_on o 0 fun (a : α) => Nat.succ (encode a)) (fun (n : ℕ) => nat.cases_on n (some none) fun (m : ℕ) => option.map some (decode α m)) sorry @[simp] theorem encode_none {α : Type u_1} [encodable α] : encode none = 0 := rfl @[simp] theorem encode_some {α : Type u_1} [encodable α] (a : α) : encode (some a) = Nat.succ (encode a) := rfl @[simp] theorem decode_option_zero {α : Type u_1} [encodable α] : decode (Option α) 0 = some none := rfl @[simp] theorem decode_option_succ {α : Type u_1} [encodable α] (n : ℕ) : decode (Option α) (Nat.succ n) = option.map some (decode α n) := rfl def decode2 (α : Type u_1) [encodable α] (n : ℕ) : Option α := option.bind (decode α n) (option.guard fun (a : α) => encode a = n) theorem mem_decode2' {α : Type u_1} [encodable α] {n : ℕ} {a : α} : a ∈ decode2 α n ↔ a ∈ decode α n ∧ encode a = n := sorry theorem mem_decode2 {α : Type u_1} [encodable α] {n : ℕ} {a : α} : a ∈ decode2 α n ↔ encode a = n := iff.trans mem_decode2' (and_iff_right_of_imp fun (e : encode a = n) => e ▸ encodek a) theorem decode2_is_partial_inv {α : Type u_1} [encodable α] : function.is_partial_inv encode (decode2 α) := fun (a : α) (n : ℕ) => mem_decode2 theorem decode2_inj {α : Type u_1} [encodable α] {n : ℕ} {a₁ : α} {a₂ : α} (h₁ : a₁ ∈ decode2 α n) (h₂ : a₂ ∈ decode2 α n) : a₁ = a₂ := encode_injective (Eq.trans (iff.mp mem_decode2 h₁) (Eq.symm (iff.mp mem_decode2 h₂))) theorem encodek2 {α : Type u_1} [encodable α] (a : α) : decode2 α (encode a) = some a := iff.mpr mem_decode2 rfl def decidable_range_encode (α : Type u_1) [encodable α] : decidable_pred (set.range encode) := fun (x : ℕ) => decidable_of_iff ↥(option.is_some (decode2 α x)) sorry def equiv_range_encode (α : Type u_1) [encodable α] : α ≃ ↥(set.range encode) := equiv.mk (fun (a : α) => { val := encode a, property := sorry }) (fun (n : ↥(set.range encode)) => option.get sorry) sorry sorry def encode_sum {α : Type u_1} {β : Type u_2} [encodable α] [encodable β] : α ⊕ β → ℕ := sorry def decode_sum {α : Type u_1} {β : Type u_2} [encodable α] [encodable β] (n : ℕ) : Option (α ⊕ β) := sorry protected instance sum {α : Type u_1} {β : Type u_2} [encodable α] [encodable β] : encodable (α ⊕ β) := mk encode_sum decode_sum sorry @[simp] theorem encode_inl {α : Type u_1} {β : Type u_2} [encodable α] [encodable β] (a : α) : encode (sum.inl a) = bit0 (encode a) := rfl @[simp] theorem encode_inr {α : Type u_1} {β : Type u_2} [encodable α] [encodable β] (b : β) : encode (sum.inr b) = bit1 (encode b) := rfl @[simp] theorem decode_sum_val {α : Type u_1} {β : Type u_2} [encodable α] [encodable β] (n : ℕ) : decode (α ⊕ β) n = decode_sum n := rfl protected instance bool : encodable Bool := of_equiv (Unit ⊕ Unit) equiv.bool_equiv_punit_sum_punit @[simp] theorem encode_tt : encode tt = 1 := rfl @[simp] theorem encode_ff : encode false = 0 := rfl @[simp] theorem decode_zero : decode Bool 0 = some false := rfl @[simp] theorem decode_one : decode Bool 1 = some tt := rfl theorem decode_ge_two (n : ℕ) (h : bit0 1 ≤ n) : decode Bool n = none := sorry def encode_sigma {α : Type u_1} {γ : α → Type u_3} [encodable α] [(a : α) → encodable (γ a)] : sigma γ → ℕ := sorry def decode_sigma {α : Type u_1} {γ : α → Type u_3} [encodable α] [(a : α) → encodable (γ a)] (n : ℕ) : Option (sigma γ) := sorry protected instance sigma {α : Type u_1} {γ : α → Type u_3} [encodable α] [(a : α) → encodable (γ a)] : encodable (sigma γ) := mk encode_sigma decode_sigma sorry @[simp] theorem decode_sigma_val {α : Type u_1} {γ : α → Type u_3} [encodable α] [(a : α) → encodable (γ a)] (n : ℕ) : decode (sigma γ) n = option.bind (decode α (prod.fst (nat.unpair n))) fun (a : α) => option.map (sigma.mk a) (decode (γ a) (prod.snd (nat.unpair n))) := sorry @[simp] theorem encode_sigma_val {α : Type u_1} {γ : α → Type u_3} [encodable α] [(a : α) → encodable (γ a)] (a : α) (b : γ a) : encode (sigma.mk a b) = nat.mkpair (encode a) (encode b) := rfl protected instance prod {α : Type u_1} {β : Type u_2} [encodable α] [encodable β] : encodable (α × β) := of_equiv (sigma fun (_x : α) => β) (equiv.symm (equiv.sigma_equiv_prod α β)) @[simp] theorem decode_prod_val {α : Type u_1} {β : Type u_2} [encodable α] [encodable β] (n : ℕ) : decode (α × β) n = option.bind (decode α (prod.fst (nat.unpair n))) fun (a : α) => option.map (Prod.mk a) (decode β (prod.snd (nat.unpair n))) := sorry @[simp] theorem encode_prod_val {α : Type u_1} {β : Type u_2} [encodable α] [encodable β] (a : α) (b : β) : encode (a, b) = nat.mkpair (encode a) (encode b) := rfl def encode_subtype {α : Type u_1} {P : α → Prop} [encA : encodable α] : (Subtype fun (a : α) => P a) → ℕ := sorry def decode_subtype {α : Type u_1} {P : α → Prop} [encA : encodable α] [decP : decidable_pred P] (v : ℕ) : Option (Subtype fun (a : α) => P a) := option.bind (decode α v) fun (a : α) => dite (P a) (fun (h : P a) => some { val := a, property := h }) fun (h : ¬P a) => none protected instance subtype {α : Type u_1} {P : α → Prop} [encA : encodable α] [decP : decidable_pred P] : encodable (Subtype fun (a : α) => P a) := mk encode_subtype decode_subtype sorry theorem subtype.encode_eq {α : Type u_1} {P : α → Prop} [encA : encodable α] [decP : decidable_pred P] (a : Subtype P) : encode a = encode (subtype.val a) := subtype.cases_on a fun (a_val : α) (a_property : P a_val) => Eq.refl (encode { val := a_val, property := a_property }) protected instance fin (n : ℕ) : encodable (fin n) := of_equiv (Subtype fun (m : ℕ) => m < n) (equiv.fin_equiv_subtype n) protected instance int : encodable ℤ := of_equiv ℕ equiv.int_equiv_nat protected instance ulift {α : Type u_1} [encodable α] : encodable (ulift α) := of_equiv α equiv.ulift protected instance plift {α : Type u_1} [encodable α] : encodable (plift α) := of_equiv α equiv.plift def of_inj {α : Type u_1} {β : Type u_2} [encodable β] (f : α → β) (hf : function.injective f) : encodable α := of_left_injection f (function.partial_inv f) sorry end encodable /-- `ulower α : Type 0` is an equivalent type in the lowest universe, given `encodable α`. -/ def ulower (α : Type u_1) [encodable α] := ↥(set.range encodable.encode) namespace ulower /-- The equivalence between the encodable type `α` and `ulower α : Type 0`. -/ def equiv (α : Type u_1) [encodable α] : α ≃ ulower α := encodable.equiv_range_encode α /-- Lowers an `a : α` into `ulower α`. -/ def down {α : Type u_1} [encodable α] (a : α) : ulower α := coe_fn (equiv α) a protected instance inhabited {α : Type u_1} [encodable α] [Inhabited α] : Inhabited (ulower α) := { default := down Inhabited.default } /-- Lifts an `a : ulower α` into `α`. -/ def up {α : Type u_1} [encodable α] (a : ulower α) : α := coe_fn (equiv.symm (equiv α)) a @[simp] theorem down_up {α : Type u_1} [encodable α] {a : ulower α} : down (up a) = a := equiv.right_inv (equiv α) a @[simp] theorem up_down {α : Type u_1} [encodable α] {a : α} : up (down a) = a := equiv.left_inv (equiv α) a @[simp] theorem up_eq_up {α : Type u_1} [encodable α] {a : ulower α} {b : ulower α} : up a = up b ↔ a = b := equiv.apply_eq_iff_eq (equiv.symm (equiv α)) @[simp] theorem down_eq_down {α : Type u_1} [encodable α] {a : α} {b : α} : down a = down b ↔ a = b := equiv.apply_eq_iff_eq (equiv α) protected theorem ext {α : Type u_1} [encodable α] {a : ulower α} {b : ulower α} : up a = up b → a = b := iff.mp up_eq_up end ulower /- Choice function for encodable types and decidable predicates. We provide the following API choose {α : Type*} {p : α → Prop} [c : encodable α] [d : decidable_pred p] : (∃ x, p x) → α := choose_spec {α : Type*} {p : α → Prop} [c : encodable α] [d : decidable_pred p] (ex : ∃ x, p x) : p (choose ex) := -/ namespace encodable def choose_x {α : Type u_1} {p : α → Prop} [encodable α] [decidable_pred p] (h : ∃ (x : α), p x) : Subtype fun (x : α) => p x := (fun (this : ∃ (n : ℕ), good p (decode α n)) => sorry) sorry def choose {α : Type u_1} {p : α → Prop} [encodable α] [decidable_pred p] (h : ∃ (x : α), p x) : α := subtype.val (choose_x h) theorem choose_spec {α : Type u_1} {p : α → Prop} [encodable α] [decidable_pred p] (h : ∃ (x : α), p x) : p (choose h) := subtype.property (choose_x h) theorem axiom_of_choice {α : Type u_1} {β : α → Type u_2} {R : (x : α) → β x → Prop} [(a : α) → encodable (β a)] [(x : α) → (y : β x) → Decidable (R x y)] (H : ∀ (x : α), ∃ (y : β x), R x y) : ∃ (f : (a : α) → β a), ∀ (x : α), R x (f x) := Exists.intro (fun (x : α) => choose (H x)) fun (x : α) => choose_spec (H x) theorem skolem {α : Type u_1} {β : α → Type u_2} {P : (x : α) → β x → Prop} [c : (a : α) → encodable (β a)] [d : (x : α) → (y : β x) → Decidable (P x y)] : (∀ (x : α), ∃ (y : β x), P x y) ↔ ∃ (f : (a : α) → β a), ∀ (x : α), P x (f x) := sorry /- There is a total ordering on the elements of an encodable type, induced by the map to ℕ. -/ /-- The `encode` function, viewed as an embedding. -/ def encode' (α : Type u_1) [encodable α] : α ↪ ℕ := function.embedding.mk encode encode_injective protected instance order.preimage.is_trans {α : Type u_1} [encodable α] : is_trans α (⇑(encode' α) ⁻¹'o LessEq) := rel_embedding.is_trans (rel_embedding.preimage (encode' α) LessEq) protected instance order.preimage.is_antisymm {α : Type u_1} [encodable α] : is_antisymm α (⇑(encode' α) ⁻¹'o LessEq) := rel_embedding.is_antisymm (rel_embedding.preimage (encode' α) LessEq) protected instance order.preimage.is_total {α : Type u_1} [encodable α] : is_total α (⇑(encode' α) ⁻¹'o LessEq) := rel_embedding.is_total (rel_embedding.preimage (encode' α) LessEq) end encodable namespace directed /-- Given a `directed r` function `f : α → β` defined on an encodable inhabited type, construct a noncomputable sequence such that `r (f (x n)) (f (x (n + 1)))` and `r (f a) (f (x (encode a + 1))`. -/ protected def sequence {α : Type u_1} {β : Type u_2} [encodable α] [Inhabited α] {r : β → β → Prop} (f : α → β) (hf : directed r f) : ℕ → α := sorry theorem sequence_mono_nat {α : Type u_1} {β : Type u_2} [encodable α] [Inhabited α] {r : β → β → Prop} {f : α → β} (hf : directed r f) (n : ℕ) : r (f (directed.sequence f hf n)) (f (directed.sequence f hf (n + 1))) := sorry theorem rel_sequence {α : Type u_1} {β : Type u_2} [encodable α] [Inhabited α] {r : β → β → Prop} {f : α → β} (hf : directed r f) (a : α) : r (f a) (f (directed.sequence f hf (encodable.encode a + 1))) := sorry theorem sequence_mono {α : Type u_1} {β : Type u_2} [encodable α] [Inhabited α] [preorder β] {f : α → β} (hf : directed LessEq f) : monotone (f ∘ directed.sequence f hf) := monotone_of_monotone_nat (sequence_mono_nat hf) theorem le_sequence {α : Type u_1} {β : Type u_2} [encodable α] [Inhabited α] [preorder β] {f : α → β} (hf : directed LessEq f) (a : α) : f a ≤ f (directed.sequence f hf (encodable.encode a + 1)) := rel_sequence hf a end directed /-- Representative of an equivalence class. This is a computable version of `quot.out` for a setoid on an encodable type. -/ def quotient.rep {α : Type u_1} {s : setoid α} [DecidableRel has_equiv.equiv] [encodable α] (q : quotient s) : α := encodable.choose (quotient.exists_rep q) theorem quotient.rep_spec {α : Type u_1} {s : setoid α} [DecidableRel has_equiv.equiv] [encodable α] (q : quotient s) : quotient.mk (quotient.rep q) = q := encodable.choose_spec (quotient.exists_rep q) /-- The quotient of an encodable space by a decidable equivalence relation is encodable. -/ def encodable_quotient {α : Type u_1} {s : setoid α} [DecidableRel has_equiv.equiv] [encodable α] : encodable (quotient s) := encodable.mk (fun (q : quotient s) => encodable.encode (quotient.rep q)) (fun (n : ℕ) => quotient.mk <$> encodable.decode α n) sorry end Mathlib
e6cc4d3090902f4eeb41240a1c8cd58803a237c1
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/algebra/squarefree.lean
6b678b07f0f380b5b35febdf027a993ed7f74965
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,728
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import ring_theory.unique_factorization_domain import ring_theory.int.basic import number_theory.divisors /-! # Squarefree elements of monoids An element of a monoid is squarefree when it is not divisible by any squares except the squares of units. ## Main Definitions - `squarefree r` indicates that `r` is only divisible by `x * x` if `x` is a unit. ## Main Results - `multiplicity.squarefree_iff_multiplicity_le_one`: `x` is `squarefree` iff for every `y`, either `multiplicity y x ≤ 1` or `is_unit y`. - `unique_factorization_monoid.squarefree_iff_nodup_factors`: A nonzero element `x` of a unique factorization monoid is squarefree iff `factors x` has no duplicate factors. - `nat.squarefree_iff_nodup_factors`: A positive natural number `x` is squarefree iff the list `factors x` has no duplicate factors. ## Tags squarefree, multiplicity -/ variables {R : Type*} /-- An element of a monoid is squarefree if the only squares that divide it are the squares of units. -/ def squarefree [monoid R] (r : R) : Prop := ∀ x : R, x * x ∣ r → is_unit x @[simp] lemma is_unit.squarefree [comm_monoid R] {x : R} (h : is_unit x) : squarefree x := λ y hdvd, is_unit_of_mul_is_unit_left (is_unit_of_dvd_unit hdvd h) @[simp] lemma squarefree_one [comm_monoid R] : squarefree (1 : R) := is_unit_one.squarefree @[simp] lemma not_squarefree_zero [monoid_with_zero R] [nontrivial R] : ¬ squarefree (0 : R) := begin erw [not_forall], exact ⟨0, (by simp)⟩, end @[simp] lemma irreducible.squarefree [comm_monoid R] {x : R} (h : irreducible x) : squarefree x := begin rintros y ⟨z, hz⟩, rw mul_assoc at hz, rcases h.is_unit_or_is_unit hz with hu | hu, { exact hu }, { apply is_unit_of_mul_is_unit_left hu }, end @[simp] lemma prime.squarefree [comm_cancel_monoid_with_zero R] {x : R} (h : prime x) : squarefree x := h.irreducible.squarefree lemma squarefree_of_dvd_of_squarefree [comm_monoid R] {x y : R} (hdvd : x ∣ y) (hsq : squarefree y) : squarefree x := λ a h, hsq _ (h.trans hdvd) namespace multiplicity variables [comm_monoid R] [decidable_rel (has_dvd.dvd : R → R → Prop)] lemma squarefree_iff_multiplicity_le_one (r : R) : squarefree r ↔ ∀ x : R, multiplicity x r ≤ 1 ∨ is_unit x := begin refine forall_congr (λ a, _), rw [← sq, pow_dvd_iff_le_multiplicity, or_iff_not_imp_left, not_le, imp_congr], swap, { refl }, convert enat.add_one_le_iff_lt (enat.coe_ne_top 1), norm_cast, end end multiplicity namespace unique_factorization_monoid variables [comm_cancel_monoid_with_zero R] [nontrivial R] [unique_factorization_monoid R] variables [normalization_monoid R] lemma squarefree_iff_nodup_normalized_factors [decidable_eq R] {x : R} (x0 : x ≠ 0) : squarefree x ↔ multiset.nodup (normalized_factors x) := begin have drel : decidable_rel (has_dvd.dvd : R → R → Prop), { classical, apply_instance, }, haveI := drel, rw [multiplicity.squarefree_iff_multiplicity_le_one, multiset.nodup_iff_count_le_one], split; intros h a, { by_cases hmem : a ∈ normalized_factors x, { have ha := irreducible_of_normalized_factor _ hmem, rcases h a with h | h, { rw ← normalize_normalized_factor _ hmem, rw [multiplicity_eq_count_normalized_factors ha x0] at h, assumption_mod_cast }, { have := ha.1, contradiction, } }, { simp [multiset.count_eq_zero_of_not_mem hmem] } }, { rw or_iff_not_imp_right, intro hu, by_cases h0 : a = 0, { simp [h0, x0] }, rcases wf_dvd_monoid.exists_irreducible_factor hu h0 with ⟨b, hib, hdvd⟩, apply le_trans (multiplicity.multiplicity_le_multiplicity_of_dvd_left hdvd), rw [multiplicity_eq_count_normalized_factors hib x0], specialize h (normalize b), assumption_mod_cast } end lemma dvd_pow_iff_dvd_of_squarefree {x y : R} {n : ℕ} (hsq : squarefree x) (h0 : n ≠ 0) : x ∣ y ^ n ↔ x ∣ y := begin classical, by_cases hx : x = 0, { simp [hx, pow_eq_zero_iff (nat.pos_of_ne_zero h0)] }, by_cases hy : y = 0, { simp [hy, zero_pow (nat.pos_of_ne_zero h0)] }, refine ⟨λ h, _, λ h, h.pow h0⟩, rw [dvd_iff_normalized_factors_le_normalized_factors hx (pow_ne_zero n hy), normalized_factors_pow, ((squarefree_iff_nodup_normalized_factors hx).1 hsq).le_nsmul_iff_le h0] at h, rwa dvd_iff_normalized_factors_le_normalized_factors hx hy, end end unique_factorization_monoid namespace nat lemma squarefree_iff_nodup_factors {n : ℕ} (h0 : n ≠ 0) : squarefree n ↔ n.factors.nodup := begin rw [unique_factorization_monoid.squarefree_iff_nodup_normalized_factors h0, nat.factors_eq], simp, end instance : decidable_pred (squarefree : ℕ → Prop) | 0 := is_false not_squarefree_zero | (n + 1) := decidable_of_iff _ (squarefree_iff_nodup_factors (nat.succ_ne_zero n)).symm open unique_factorization_monoid lemma divisors_filter_squarefree {n : ℕ} (h0 : n ≠ 0) : (n.divisors.filter squarefree).val = (unique_factorization_monoid.normalized_factors n).to_finset.powerset.val.map (λ x, x.val.prod) := begin rw multiset.nodup_ext (finset.nodup _) (multiset.nodup_map_on _ (finset.nodup _)), { intro a, simp only [multiset.mem_filter, id.def, multiset.mem_map, finset.filter_val, ← finset.mem_def, mem_divisors], split, { rintro ⟨⟨an, h0⟩, hsq⟩, use (unique_factorization_monoid.normalized_factors a).to_finset, simp only [id.def, finset.mem_powerset], rcases an with ⟨b, rfl⟩, rw mul_ne_zero_iff at h0, rw unique_factorization_monoid.squarefree_iff_nodup_normalized_factors h0.1 at hsq, rw [multiset.to_finset_subset, multiset.to_finset_val, hsq.erase_dup, ← associated_iff_eq, normalized_factors_mul h0.1 h0.2], exact ⟨multiset.subset_of_le (multiset.le_add_right _ _), normalized_factors_prod h0.1⟩ }, { rintro ⟨s, hs, rfl⟩, rw [finset.mem_powerset, ← finset.val_le_iff, multiset.to_finset_val] at hs, have hs0 : s.val.prod ≠ 0, { rw [ne.def, multiset.prod_eq_zero_iff], simp only [exists_prop, id.def, exists_eq_right], intro con, apply not_irreducible_zero (irreducible_of_normalized_factor 0 (multiset.mem_erase_dup.1 (multiset.mem_of_le hs con))) }, rw (normalized_factors_prod h0).symm.dvd_iff_dvd_right, refine ⟨⟨multiset.prod_dvd_prod (le_trans hs (multiset.erase_dup_le _)), h0⟩, _⟩, have h := unique_factorization_monoid.factors_unique irreducible_of_normalized_factor (λ x hx, irreducible_of_normalized_factor x (multiset.mem_of_le (le_trans hs (multiset.erase_dup_le _)) hx)) (normalized_factors_prod hs0), rw [associated_eq_eq, multiset.rel_eq] at h, rw [unique_factorization_monoid.squarefree_iff_nodup_normalized_factors hs0, h], apply s.nodup } }, { intros x hx y hy h, rw [← finset.val_inj, ← multiset.rel_eq, ← associated_eq_eq], rw [← finset.mem_def, finset.mem_powerset] at hx hy, apply unique_factorization_monoid.factors_unique _ _ (associated_iff_eq.2 h), { intros z hz, apply irreducible_of_normalized_factor z, rw ← multiset.mem_to_finset, apply hx hz }, { intros z hz, apply irreducible_of_normalized_factor z, rw ← multiset.mem_to_finset, apply hy hz } } end open_locale big_operators lemma sum_divisors_filter_squarefree {n : ℕ} (h0 : n ≠ 0) {α : Type*} [add_comm_monoid α] {f : ℕ → α} : ∑ i in (n.divisors.filter squarefree), f i = ∑ i in (unique_factorization_monoid.normalized_factors n).to_finset.powerset, f (i.val.prod) := by rw [finset.sum_eq_multiset_sum, divisors_filter_squarefree h0, multiset.map_map, finset.sum_eq_multiset_sum] lemma sq_mul_squarefree_of_pos {n : ℕ} (hn : 0 < n) : ∃ a b : ℕ, 0 < a ∧ 0 < b ∧ b ^ 2 * a = n ∧ squarefree a := begin let S := {s ∈ finset.range (n + 1) | s ∣ n ∧ ∃ x, s = x ^ 2}, have hSne : S.nonempty, { use 1, have h1 : 0 < n ∧ ∃ (x : ℕ), 1 = x ^ 2 := ⟨hn, ⟨1, (one_pow 2).symm⟩⟩, simpa [S] }, let s := finset.max' S hSne, have hs : s ∈ S := finset.max'_mem S hSne, simp only [finset.sep_def, S, finset.mem_filter, finset.mem_range] at hs, obtain ⟨hsn1, ⟨a, hsa⟩, ⟨b, hsb⟩⟩ := hs, rw hsa at hn, obtain ⟨hlts, hlta⟩ := canonically_ordered_comm_semiring.mul_pos.mp hn, rw hsb at hsa hn hlts, refine ⟨a, b, hlta, (pow_pos_iff zero_lt_two).mp hlts, hsa.symm, _⟩, rintro x ⟨y, hy⟩, rw nat.is_unit_iff, by_contra hx, refine lt_le_antisymm _ (finset.le_max' S ((b * x) ^ 2) _), { simp_rw [S, hsa, finset.sep_def, finset.mem_filter, finset.mem_range], refine ⟨lt_succ_iff.mpr (le_of_dvd hn _), _, ⟨b * x, rfl⟩⟩; use y; rw hy; ring }, { convert lt_mul_of_one_lt_right hlts (one_lt_pow 2 x zero_lt_two (one_lt_iff_ne_zero_and_ne_one.mpr ⟨λ h, by simp * at *, hx⟩)), rw mul_pow }, end lemma sq_mul_squarefree_of_pos' {n : ℕ} (h : 0 < n) : ∃ a b : ℕ, (b + 1) ^ 2 * (a + 1) = n ∧ squarefree (a + 1) := begin obtain ⟨a₁, b₁, ha₁, hb₁, hab₁, hab₂⟩ := sq_mul_squarefree_of_pos h, refine ⟨a₁.pred, b₁.pred, _, _⟩; simpa only [add_one, succ_pred_eq_of_pos, ha₁, hb₁], end lemma sq_mul_squarefree (n : ℕ) : ∃ a b : ℕ, b ^ 2 * a = n ∧ squarefree a := begin cases n, { exact ⟨1, 0, (by simp), squarefree_one⟩ }, { obtain ⟨a, b, -, -, h₁, h₂⟩ := sq_mul_squarefree_of_pos (succ_pos n), exact ⟨a, b, h₁, h₂⟩ }, end end nat
1431efa4ed5e340cb417a89f47066eb37ee7d0ea
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/IdempotentMultMagma.lean
8f9f6facbb6db25e1f6c7213551a5fa0dcd534d7
[]
no_license
ysharoda/Deriving-Definitions
3e149e6641fae440badd35ac110a0bd705a49ad2
dfecb27572022de3d4aa702cae8db19957523a59
refs/heads/master
1,679,127,857,700
1,615,939,007,000
1,615,939,007,000
229,785,731
4
0
null
null
null
null
UTF-8
Lean
false
false
6,534
lean
import init.data.nat.basic import init.data.fin.basic import data.vector import .Prelude open Staged open nat open fin open vector section IdempotentMultMagma structure IdempotentMultMagma (A : Type) : Type := (times : (A → (A → A))) (idempotent_times : (∀ {x : A} , (times x x) = x)) open IdempotentMultMagma structure Sig (AS : Type) : Type := (timesS : (AS → (AS → AS))) structure Product (A : Type) : Type := (timesP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (idempotent_timesP : (∀ {xP : (Prod A A)} , (timesP xP xP) = xP)) structure Hom {A1 : Type} {A2 : Type} (Id1 : (IdempotentMultMagma A1)) (Id2 : (IdempotentMultMagma A2)) : Type := (hom : (A1 → A2)) (pres_times : (∀ {x1 x2 : A1} , (hom ((times Id1) x1 x2)) = ((times Id2) (hom x1) (hom x2)))) structure RelInterp {A1 : Type} {A2 : Type} (Id1 : (IdempotentMultMagma A1)) (Id2 : (IdempotentMultMagma A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_times : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((times Id1) x1 x2) ((times Id2) y1 y2)))))) inductive IdempotentMultMagmaTerm : Type | timesL : (IdempotentMultMagmaTerm → (IdempotentMultMagmaTerm → IdempotentMultMagmaTerm)) open IdempotentMultMagmaTerm inductive ClIdempotentMultMagmaTerm (A : Type) : Type | sing : (A → ClIdempotentMultMagmaTerm) | timesCl : (ClIdempotentMultMagmaTerm → (ClIdempotentMultMagmaTerm → ClIdempotentMultMagmaTerm)) open ClIdempotentMultMagmaTerm inductive OpIdempotentMultMagmaTerm (n : ℕ) : Type | v : ((fin n) → OpIdempotentMultMagmaTerm) | timesOL : (OpIdempotentMultMagmaTerm → (OpIdempotentMultMagmaTerm → OpIdempotentMultMagmaTerm)) open OpIdempotentMultMagmaTerm inductive OpIdempotentMultMagmaTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpIdempotentMultMagmaTerm2) | sing2 : (A → OpIdempotentMultMagmaTerm2) | timesOL2 : (OpIdempotentMultMagmaTerm2 → (OpIdempotentMultMagmaTerm2 → OpIdempotentMultMagmaTerm2)) open OpIdempotentMultMagmaTerm2 def simplifyCl {A : Type} : ((ClIdempotentMultMagmaTerm A) → (ClIdempotentMultMagmaTerm A)) | (timesCl x1 x2) := (timesCl (simplifyCl x1) (simplifyCl x2)) | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpIdempotentMultMagmaTerm n) → (OpIdempotentMultMagmaTerm n)) | (timesOL x1 x2) := (timesOL (simplifyOpB x1) (simplifyOpB x2)) | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpIdempotentMultMagmaTerm2 n A) → (OpIdempotentMultMagmaTerm2 n A)) | (timesOL2 x1 x2) := (timesOL2 (simplifyOp x1) (simplifyOp x2)) | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((IdempotentMultMagma A) → (IdempotentMultMagmaTerm → A)) | Id (timesL x1 x2) := ((times Id) (evalB Id x1) (evalB Id x2)) def evalCl {A : Type} : ((IdempotentMultMagma A) → ((ClIdempotentMultMagmaTerm A) → A)) | Id (sing x1) := x1 | Id (timesCl x1 x2) := ((times Id) (evalCl Id x1) (evalCl Id x2)) def evalOpB {A : Type} {n : ℕ} : ((IdempotentMultMagma A) → ((vector A n) → ((OpIdempotentMultMagmaTerm n) → A))) | Id vars (v x1) := (nth vars x1) | Id vars (timesOL x1 x2) := ((times Id) (evalOpB Id vars x1) (evalOpB Id vars x2)) def evalOp {A : Type} {n : ℕ} : ((IdempotentMultMagma A) → ((vector A n) → ((OpIdempotentMultMagmaTerm2 n A) → A))) | Id vars (v2 x1) := (nth vars x1) | Id vars (sing2 x1) := x1 | Id vars (timesOL2 x1 x2) := ((times Id) (evalOp Id vars x1) (evalOp Id vars x2)) def inductionB {P : (IdempotentMultMagmaTerm → Type)} : ((∀ (x1 x2 : IdempotentMultMagmaTerm) , ((P x1) → ((P x2) → (P (timesL x1 x2))))) → (∀ (x : IdempotentMultMagmaTerm) , (P x))) | ptimesl (timesL x1 x2) := (ptimesl _ _ (inductionB ptimesl x1) (inductionB ptimesl x2)) def inductionCl {A : Type} {P : ((ClIdempotentMultMagmaTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClIdempotentMultMagmaTerm A)) , ((P x1) → ((P x2) → (P (timesCl x1 x2))))) → (∀ (x : (ClIdempotentMultMagmaTerm A)) , (P x)))) | psing ptimescl (sing x1) := (psing x1) | psing ptimescl (timesCl x1 x2) := (ptimescl _ _ (inductionCl psing ptimescl x1) (inductionCl psing ptimescl x2)) def inductionOpB {n : ℕ} {P : ((OpIdempotentMultMagmaTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpIdempotentMultMagmaTerm n)) , ((P x1) → ((P x2) → (P (timesOL x1 x2))))) → (∀ (x : (OpIdempotentMultMagmaTerm n)) , (P x)))) | pv ptimesol (v x1) := (pv x1) | pv ptimesol (timesOL x1 x2) := (ptimesol _ _ (inductionOpB pv ptimesol x1) (inductionOpB pv ptimesol x2)) def inductionOp {n : ℕ} {A : Type} {P : ((OpIdempotentMultMagmaTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpIdempotentMultMagmaTerm2 n A)) , ((P x1) → ((P x2) → (P (timesOL2 x1 x2))))) → (∀ (x : (OpIdempotentMultMagmaTerm2 n A)) , (P x))))) | pv2 psing2 ptimesol2 (v2 x1) := (pv2 x1) | pv2 psing2 ptimesol2 (sing2 x1) := (psing2 x1) | pv2 psing2 ptimesol2 (timesOL2 x1 x2) := (ptimesol2 _ _ (inductionOp pv2 psing2 ptimesol2 x1) (inductionOp pv2 psing2 ptimesol2 x2)) def stageB : (IdempotentMultMagmaTerm → (Staged IdempotentMultMagmaTerm)) | (timesL x1 x2) := (stage2 timesL (codeLift2 timesL) (stageB x1) (stageB x2)) def stageCl {A : Type} : ((ClIdempotentMultMagmaTerm A) → (Staged (ClIdempotentMultMagmaTerm A))) | (sing x1) := (Now (sing x1)) | (timesCl x1 x2) := (stage2 timesCl (codeLift2 timesCl) (stageCl x1) (stageCl x2)) def stageOpB {n : ℕ} : ((OpIdempotentMultMagmaTerm n) → (Staged (OpIdempotentMultMagmaTerm n))) | (v x1) := (const (code (v x1))) | (timesOL x1 x2) := (stage2 timesOL (codeLift2 timesOL) (stageOpB x1) (stageOpB x2)) def stageOp {n : ℕ} {A : Type} : ((OpIdempotentMultMagmaTerm2 n A) → (Staged (OpIdempotentMultMagmaTerm2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | (timesOL2 x1 x2) := (stage2 timesOL2 (codeLift2 timesOL2) (stageOp x1) (stageOp x2)) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (timesT : ((Repr A) → ((Repr A) → (Repr A)))) end IdempotentMultMagma
673bafd211605f15b2b3419aa05c5f333349dc17
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Compiler/IR/Borrow.lean
d5500fc3bd167364b498002aea8bcdefd26e4ffe
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
10,891
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Compiler.ExportAttr import Lean.Compiler.IR.CompilerM import Lean.Compiler.IR.NormIds namespace Lean namespace IR namespace Borrow namespace OwnedSet abbrev Key := FunId × Index def beq : Key → Key → Bool | (f₁, x₁), (f₂, x₂) => f₁ == f₂ && x₁ == x₂ instance : BEq Key := ⟨beq⟩ def getHash : Key → UInt64 | (f, x) => mixHash (hash f) (hash x) instance : Hashable Key := ⟨getHash⟩ end OwnedSet open OwnedSet (Key) in abbrev OwnedSet := HashMap Key Unit def OwnedSet.insert (s : OwnedSet) (k : OwnedSet.Key) : OwnedSet := HashMap.insert s k () def OwnedSet.contains (s : OwnedSet) (k : OwnedSet.Key) : Bool := HashMap.contains s k /-! We perform borrow inference in a block of mutually recursive functions. Join points are viewed as local functions, and are identified using their local id + the name of the surrounding function. We keep a mapping from function and joint points to parameters (`Array Param`). Recall that `Param` contains the field `borrow`. -/ namespace ParamMap inductive Key where | decl (name : FunId) | jp (name : FunId) (jpid : JoinPointId) deriving BEq def getHash : Key → UInt64 | Key.decl n => hash n | Key.jp n id => mixHash (hash n) (hash id) instance : Hashable Key := ⟨getHash⟩ end ParamMap open ParamMap (Key) abbrev ParamMap := HashMap Key (Array Param) def ParamMap.fmt (map : ParamMap) : Format := let fmts := map.fold (fun fmt k ps => let k := match k with | ParamMap.Key.decl n => format n | ParamMap.Key.jp n id => format n ++ ":" ++ format id fmt ++ Format.line ++ k ++ " -> " ++ formatParams ps) Format.nil "{" ++ (Format.nest 1 fmts) ++ "}" instance : ToFormat ParamMap := ⟨ParamMap.fmt⟩ instance : ToString ParamMap := ⟨fun m => Format.pretty (format m)⟩ namespace InitParamMap /-- Mark parameters that take a reference as borrow -/ def initBorrow (ps : Array Param) : Array Param := ps.map fun p => { p with borrow := p.ty.isObj } /-- We do perform borrow inference for constants marked as `export`. Reason: we current write wrappers in C++ for using exported functions. These wrappers use smart pointers such as `object_ref`. When writing a new wrapper we need to know whether an argument is a borrow inference or not. We can revise this decision when we implement code for generating the wrappers automatically. -/ def initBorrowIfNotExported (exported : Bool) (ps : Array Param) : Array Param := if exported then ps else initBorrow ps partial def visitFnBody (fnid : FunId) : FnBody → StateM ParamMap Unit | FnBody.jdecl j xs v b => do modify fun m => m.insert (ParamMap.Key.jp fnid j) (initBorrow xs) visitFnBody fnid v visitFnBody fnid b | FnBody.case _ _ _ alts => alts.forM fun alt => visitFnBody fnid alt.body | e => do unless e.isTerminal do let (_, b) := e.split visitFnBody fnid b def visitDecls (env : Environment) (decls : Array Decl) : StateM ParamMap Unit := decls.forM fun decl => match decl with | .fdecl (f := f) (xs := xs) (body := b) .. => do let exported := isExport env f modify fun m => m.insert (ParamMap.Key.decl f) (initBorrowIfNotExported exported xs) visitFnBody f b | _ => pure () end InitParamMap def mkInitParamMap (env : Environment) (decls : Array Decl) : ParamMap := (InitParamMap.visitDecls env decls *> get).run' {} /-! Apply the inferred borrow annotations stored at `ParamMap` to a block of mutually recursive functions. -/ namespace ApplyParamMap partial def visitFnBody (fn : FunId) (paramMap : ParamMap) : FnBody → FnBody | FnBody.jdecl j _ v b => let v := visitFnBody fn paramMap v let b := visitFnBody fn paramMap b match paramMap.find? (ParamMap.Key.jp fn j) with | some ys => FnBody.jdecl j ys v b | none => unreachable! | FnBody.case tid x xType alts => FnBody.case tid x xType <| alts.map fun alt => alt.modifyBody (visitFnBody fn paramMap) | e => if e.isTerminal then e else let (instr, b) := e.split let b := visitFnBody fn paramMap b instr.setBody b def visitDecls (decls : Array Decl) (paramMap : ParamMap) : Array Decl := decls.map fun decl => match decl with | Decl.fdecl f _ ty b info => let b := visitFnBody f paramMap b match paramMap.find? (ParamMap.Key.decl f) with | some xs => Decl.fdecl f xs ty b info | none => unreachable! | other => other end ApplyParamMap def applyParamMap (decls : Array Decl) (map : ParamMap) : Array Decl := ApplyParamMap.visitDecls decls map structure BorrowInfCtx where env : Environment decls : Array Decl -- block of mutually recursive functions currFn : FunId := default -- Function being analyzed. paramSet : IndexSet := {} -- Set of all function parameters in scope. This is used to implement the heuristic at `ownArgsUsingParams` structure BorrowInfState where /-- Set of variables that must be `owned`. -/ owned : OwnedSet := {} modified : Bool := false paramMap : ParamMap abbrev M := ReaderT BorrowInfCtx (StateM BorrowInfState) def getCurrFn : M FunId := do let ctx ← read pure ctx.currFn def markModified : M Unit := modify fun s => { s with modified := true } def ownVar (x : VarId) : M Unit := do let currFn ← getCurrFn modify fun s => if s.owned.contains (currFn, x.idx) then s else { s with owned := s.owned.insert (currFn, x.idx), modified := true } def ownArg (x : Arg) : M Unit := match x with | Arg.var x => ownVar x | _ => pure () def ownArgs (xs : Array Arg) : M Unit := xs.forM ownArg def isOwned (x : VarId) : M Bool := do let currFn ← getCurrFn let s ← get return s.owned.contains (currFn, x.idx) /-- Updates `map[k]` using the current set of `owned` variables. -/ def updateParamMap (k : ParamMap.Key) : M Unit := do let s ← get match s.paramMap.find? k with | some ps => do let ps ← ps.mapM fun (p : Param) => do if !p.borrow then pure p else if (← isOwned p.x) then markModified pure { p with borrow := false } else pure p modify fun s => { s with paramMap := s.paramMap.insert k ps } | none => pure () def getParamInfo (k : ParamMap.Key) : M (Array Param) := do let s ← get match s.paramMap.find? k with | some ps => pure ps | none => match k with | ParamMap.Key.decl fn => do let ctx ← read match findEnvDecl ctx.env fn with | some decl => pure decl.params | none => unreachable! | _ => unreachable! /-- For each ps[i], if ps[i] is owned, then mark xs[i] as owned. -/ def ownArgsUsingParams (xs : Array Arg) (ps : Array Param) : M Unit := xs.size.forM fun i => do let x := xs[i]! let p := ps[i]! unless p.borrow do ownArg x /-- For each xs[i], if xs[i] is owned, then mark ps[i] as owned. We use this action to preserve tail calls. That is, if we have a tail call `f xs`, if the i-th parameter is borrowed, but `xs[i]` is owned we would have to insert a `dec xs[i]` after `f xs` and consequently "break" the tail call. -/ def ownParamsUsingArgs (xs : Array Arg) (ps : Array Param) : M Unit := xs.size.forM fun i => do let x := xs[i]! let p := ps[i]! match x with | Arg.var x => if (← isOwned x) then ownVar p.x | _ => pure () /-- Mark `xs[i]` as owned if it is one of the parameters `ps`. We use this action to mark function parameters that are being "packed" inside constructors. This is a heuristic, and is not related with the effectiveness of the reset/reuse optimization. It is useful for code such as ``` def f (x y : obj) := let z := ctor_1 x y; ret z ``` -/ def ownArgsIfParam (xs : Array Arg) : M Unit := do let ctx ← read xs.forM fun x => do match x with | Arg.var x => if ctx.paramSet.contains x.idx then ownVar x | _ => pure () def collectExpr (z : VarId) : Expr → M Unit | Expr.reset _ x => ownVar z *> ownVar x | Expr.reuse x _ _ ys => ownVar z *> ownVar x *> ownArgsIfParam ys | Expr.ctor _ xs => ownVar z *> ownArgsIfParam xs | Expr.proj _ x => do if (← isOwned x) then ownVar z if (← isOwned z) then ownVar x | Expr.fap g xs => do let ps ← getParamInfo (ParamMap.Key.decl g) ownVar z *> ownArgsUsingParams xs ps | Expr.ap x ys => ownVar z *> ownVar x *> ownArgs ys | Expr.pap _ xs => ownVar z *> ownArgs xs | _ => pure () def preserveTailCall (x : VarId) (v : Expr) (b : FnBody) : M Unit := do let ctx ← read match v, b with | (Expr.fap g ys), (FnBody.ret (Arg.var z)) => if ctx.decls.any (·.name == g) && x == z then let ps ← getParamInfo (ParamMap.Key.decl g) ownParamsUsingArgs ys ps | _, _ => pure () def updateParamSet (ctx : BorrowInfCtx) (ps : Array Param) : BorrowInfCtx := { ctx with paramSet := ps.foldl (fun s p => s.insert p.x.idx) ctx.paramSet } partial def collectFnBody : FnBody → M Unit | FnBody.jdecl j ys v b => do withReader (fun ctx => updateParamSet ctx ys) (collectFnBody v) let ctx ← read updateParamMap (ParamMap.Key.jp ctx.currFn j) collectFnBody b | FnBody.vdecl x _ v b => collectFnBody b *> collectExpr x v *> preserveTailCall x v b | FnBody.jmp j ys => do let ctx ← read let ps ← getParamInfo (ParamMap.Key.jp ctx.currFn j) ownArgsUsingParams ys ps -- for making sure the join point can reuse ownParamsUsingArgs ys ps -- for making sure the tail call is preserved | FnBody.case _ _ _ alts => alts.forM fun alt => collectFnBody alt.body | e => do unless e.isTerminal do collectFnBody e.body partial def collectDecl : Decl → M Unit | .fdecl (f := f) (xs := ys) (body := b) .. => withReader (fun ctx => let ctx := updateParamSet ctx ys; { ctx with currFn := f }) do collectFnBody b updateParamMap (ParamMap.Key.decl f) | _ => pure () /-- Keep executing `x` until it reaches a fixpoint -/ partial def whileModifing (x : M Unit) : M Unit := do modify fun s => { s with modified := false } x let s ← get if s.modified then whileModifing x else pure () def collectDecls : M ParamMap := do whileModifing ((← read).decls.forM collectDecl) let s ← get pure s.paramMap def infer (env : Environment) (decls : Array Decl) : ParamMap := collectDecls { env, decls } |>.run' { paramMap := mkInitParamMap env decls } end Borrow def inferBorrow (decls : Array Decl) : CompilerM (Array Decl) := do let env ← getEnv let paramMap := Borrow.infer env decls pure (Borrow.applyParamMap decls paramMap) end IR end Lean
fd748a2b29b2c8e2f5390d036ed0114f36443692
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/sym/basic.lean
dd8cd026c6e605893cda391aad1907c90cfa26ad
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
8,706
lean
/- Copyright (c) 2020 Kyle Miller All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import data.multiset.basic import data.vector.basic import data.setoid.basic import tactic.apply_fun /-! # Symmetric powers This file defines symmetric powers of a type. The nth symmetric power consists of homogeneous n-tuples modulo permutations by the symmetric group. The special case of 2-tuples is called the symmetric square, which is addressed in more detail in `data.sym.sym2`. TODO: This was created as supporting material for `sym2`; it needs a fleshed-out interface. ## Tags symmetric powers -/ universes u /-- The nth symmetric power is n-tuples up to permutation. We define it as a subtype of `multiset` since these are well developed in the library. We also give a definition `sym.sym'` in terms of vectors, and we show these are equivalent in `sym.sym_equiv_sym'`. -/ def sym (α : Type u) (n : ℕ) := {s : multiset α // s.card = n} instance sym.has_coe (α : Type*) (n : ℕ) : has_coe (sym α n) (multiset α) := coe_subtype /-- This is the `list.perm` setoid lifted to `vector`. See note [reducible non-instances]. -/ @[reducible] def vector.perm.is_setoid (α : Type u) (n : ℕ) : setoid (vector α n) := (list.is_setoid α).comap subtype.val local attribute [instance] vector.perm.is_setoid namespace sym variables {α : Type u} {n : ℕ} {s : sym α n} {a b : α} /-- The unique element in `sym α 0`. -/ @[pattern] def nil : sym α 0 := ⟨0, multiset.card_zero⟩ /-- Inserts an element into the term of `sym α n`, increasing the length by one. -/ @[pattern] def cons (a : α) (s : sym α n) : sym α (nat.succ n) := ⟨a ::ₘ s.1, by rw [multiset.card_cons, s.2]⟩ notation a :: b := cons a b @[simp] lemma cons_inj_right (a : α) (s s' : sym α n) : a :: s = a :: s' ↔ s = s' := subtype.ext_iff.trans $ (multiset.cons_inj_right _).trans subtype.ext_iff.symm @[simp] lemma cons_inj_left (a a' : α) (s : sym α n) : a :: s = a' :: s ↔ a = a' := subtype.ext_iff.trans $ multiset.cons_inj_left _ lemma cons_swap (a b : α) (s : sym α n) : a :: b :: s = b :: a :: s := subtype.ext $ multiset.cons_swap a b s.1 /-- This is the quotient map that takes a list of n elements as an n-tuple and produces an nth symmetric power. -/ instance : has_lift (vector α n) (sym α n) := { lift := λ x, ⟨↑x.val, (multiset.coe_card _).trans x.2⟩ } @[simp] lemma of_vector_nil : ↑(vector.nil : vector α 0) = (sym.nil : sym α 0) := rfl @[simp] lemma of_vector_cons (a : α) (v : vector α n) : ↑(vector.cons a v) = a :: (↑v : sym α n) := by { cases v, refl } /-- `α ∈ s` means that `a` appears as one of the factors in `s`. -/ instance : has_mem α (sym α n) := ⟨λ a s, a ∈ s.1⟩ instance decidable_mem [decidable_eq α] (a : α) (s : sym α n) : decidable (a ∈ s) := s.1.decidable_mem _ @[simp] lemma mem_cons {a b : α} {s : sym α n} : a ∈ b :: s ↔ a = b ∨ a ∈ s := multiset.mem_cons lemma mem_cons_of_mem {a b : α} {s : sym α n} (h : a ∈ s) : a ∈ b :: s := multiset.mem_cons_of_mem h @[simp] lemma mem_cons_self (a : α) (s : sym α n) : a ∈ a :: s := multiset.mem_cons_self a s.1 lemma cons_of_coe_eq (a : α) (v : vector α n) : a :: (↑v : sym α n) = ↑(a ::ᵥ v) := subtype.ext $ by { cases v, refl } lemma sound {a b : vector α n} (h : a.val ~ b.val) : (↑a : sym α n) = ↑b := subtype.ext $ quotient.sound h /-- `erase s a h` is the sym that subtracts 1 from the multiplicity of `a` if a is present in the sym. -/ def erase [decidable_eq α] (s : sym α (n + 1)) (a : α) (h : a ∈ s) : sym α n := ⟨s.val.erase a, (multiset.card_erase_of_mem h).trans $ s.property.symm ▸ n.pred_succ⟩ @[simp] lemma cons_erase [decidable_eq α] (s : sym α (n + 1)) (a : α) (h : a ∈ s) : a :: s.erase a h = s := subtype.ext $ multiset.cons_erase h /-- Another definition of the nth symmetric power, using vectors modulo permutations. (See `sym`.) -/ def sym' (α : Type u) (n : ℕ) := quotient (vector.perm.is_setoid α n) /-- This is `cons` but for the alternative `sym'` definition. -/ def cons' {α : Type u} {n : ℕ} : α → sym' α n → sym' α (nat.succ n) := λ a, quotient.map (vector.cons a) (λ ⟨l₁, h₁⟩ ⟨l₂, h₂⟩ h, list.perm.cons _ h) notation a :: b := cons' a b /-- Multisets of cardinality n are equivalent to length-n vectors up to permutations. -/ def sym_equiv_sym' {α : Type u} {n : ℕ} : sym α n ≃ sym' α n := equiv.subtype_quotient_equiv_quotient_subtype _ _ (λ _, by refl) (λ _ _, by refl) lemma cons_equiv_eq_equiv_cons (α : Type u) (n : ℕ) (a : α) (s : sym α n) : a :: sym_equiv_sym' s = sym_equiv_sym' (a :: s) := by { rcases s with ⟨⟨l⟩, _⟩, refl, } instance : has_zero (sym α 0) := ⟨⟨0, rfl⟩⟩ instance : has_emptyc (sym α 0) := ⟨0⟩ lemma eq_nil_of_card_zero (s : sym α 0) : s = nil := subtype.ext $ multiset.card_eq_zero.1 s.2 instance unique_zero : unique (sym α 0) := ⟨⟨nil⟩, eq_nil_of_card_zero⟩ /-- `repeat a n` is the sym containing only `a` with multiplicity `n`. -/ def repeat (a : α) (n : ℕ) : sym α n := ⟨multiset.repeat a n, multiset.card_repeat _ _⟩ lemma repeat_succ {a : α} {n : ℕ} : repeat a n.succ = a :: repeat a n := rfl lemma coe_repeat : (repeat a n : multiset α) = multiset.repeat a n := rfl @[simp] lemma mem_repeat : b ∈ repeat a n ↔ n ≠ 0 ∧ b = a := multiset.mem_repeat lemma eq_repeat_iff : s = repeat a n ↔ ∀ b ∈ s, b = a := begin rw [subtype.ext_iff, coe_repeat], convert multiset.eq_repeat', exact s.2.symm, end lemma exists_mem (s : sym α n.succ) : ∃ a, a ∈ s := multiset.card_pos_iff_exists_mem.1 $ s.2.symm ▸ n.succ_pos lemma exists_eq_cons_of_succ (s : sym α n.succ) : ∃ (a : α) (s' : sym α n), s = a :: s' := begin obtain ⟨a, ha⟩ := exists_mem s, classical, exact ⟨a, s.erase a ha, (s.cons_erase _ _).symm⟩, end lemma eq_repeat {a : α} {n : ℕ} {s : sym α n} : s = repeat a n ↔ ∀ b ∈ s, b = a := subtype.ext_iff.trans $ multiset.eq_repeat.trans $ and_iff_right s.prop lemma eq_repeat_of_subsingleton [subsingleton α] (a : α) {n : ℕ} (s : sym α n) : s = repeat a n := eq_repeat.2 $ λ b hb, subsingleton.elim _ _ instance [subsingleton α] (n : ℕ) : subsingleton (sym α n) := ⟨begin cases n, { simp, }, { intros s s', obtain ⟨b, -⟩ := exists_mem s, rw [eq_repeat_of_subsingleton b s', eq_repeat_of_subsingleton b s], }, end⟩ instance inhabited_sym [inhabited α] (n : ℕ) : inhabited (sym α n) := ⟨repeat default n⟩ instance inhabited_sym' [inhabited α] (n : ℕ) : inhabited (sym' α n) := ⟨quotient.mk' (vector.repeat default n)⟩ instance (n : ℕ) [is_empty α] : is_empty (sym α n.succ) := ⟨λ s, by { obtain ⟨a, -⟩ := exists_mem s, exact is_empty_elim a }⟩ instance (n : ℕ) [unique α] : unique (sym α n) := unique.mk' _ lemma repeat_left_inj {a b : α} {n : ℕ} (h : n ≠ 0) : repeat a n = repeat b n ↔ a = b := subtype.ext_iff.trans (multiset.repeat_left_inj h) lemma repeat_left_injective {n : ℕ} (h : n ≠ 0) : function.injective (λ x : α, repeat x n) := λ a b, (repeat_left_inj h).1 instance (n : ℕ) [nontrivial α] : nontrivial (sym α (n + 1)) := (repeat_left_injective n.succ_ne_zero).nontrivial /-- A function `α → β` induces a function `sym α n → sym β n` by applying it to every element of the underlying `n`-tuple. -/ def map {α β : Type*} {n : ℕ} (f : α → β) (x : sym α n) : sym β n := ⟨x.val.map f, by simpa [multiset.card_map] using x.property⟩ @[simp] lemma mem_map {α β : Type*} {n : ℕ} {f : α → β} {b : β} {l : sym α n} : b ∈ sym.map f l ↔ ∃ a, a ∈ l ∧ f a = b := multiset.mem_map @[simp] lemma map_id {α : Type*} {n : ℕ} (s : sym α n) : sym.map id s = s := by simp [sym.map] @[simp] lemma map_map {α β γ : Type*} {n : ℕ} (g : β → γ) (f : α → β) (s : sym α n) : sym.map g (sym.map f s) = sym.map (g ∘ f) s := by simp [sym.map] @[simp] lemma map_zero {α β : Type*} (f : α → β) : sym.map f (0 : sym α 0) = (0 : sym β 0) := rfl @[simp] lemma map_cons {α β : Type*} {n : ℕ} (f : α → β) (a : α) (s : sym α n) : (a :: s).map f = (f a) :: s.map f := by simp [map, cons] /-- Mapping an equivalence `α ≃ β` using `sym.map` gives an equivalence between `sym α n` and `sym β n`. -/ @[simps] def equiv_congr {β : Type u} (e : α ≃ β) : sym α n ≃ sym β n := { to_fun := map e, inv_fun := map e.symm, left_inv := λ x, by rw [map_map, equiv.symm_comp_self, map_id], right_inv := λ x, by rw [map_map, equiv.self_comp_symm, map_id] } end sym
bbe30d50435686786d8b849727a482968b1ab9ba
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/tests/lean/run/n5.lean
cc17a3bb742c020e34084981f66daf52e7da3acd
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
422
lean
constant N : Type.{1} constant f : N → N → N → N constant g : N → N → N constant h : N → N → N → N constant s : N → N → N → N → N precedence `*`:75 precedence `|`:75 notation a * b:prev | c:prev := f a b c notation a * b := g a b notation a * b * c:prev := h a b c notation a * b | c * d:prev := s a b c d constants a b c d e : N check a * b check a * b | d check a * b * c check a * b | d * e
0c2d6f14b4dc9cffacd0c44cb0a7840e674246a1
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebraic_topology/dold_kan/projections.lean
6838b6958d465a9dc48964eb94d8f618a295e09f
[ "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,952
lean
/- Copyright (c) 2022 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import algebraic_topology.dold_kan.faces import category_theory.idempotents.basic /-! # Construction of projections for the Dold-Kan correspondence TODO (@joelriou) continue adding the various files referenced below In this file, we construct endomorphisms `P q : K[X] ⟶ K[X]` for all `q : ℕ`. We study how they behave with respect to face maps with the lemmas `higher_faces_vanish.of_P`, `higher_faces_vanish.comp_P_eq_self` and `comp_P_eq_self_iff`. Then, we show that they are projections (see `P_f_idem` and `P_idem`). They are natural transformations (see `nat_trans_P` and `P_f_naturality`) and are compatible with the application of additive functors (see `map_P`). By passing to the limit, these endomorphisms `P q` shall be used in `p_infty.lean` in order to define `P_infty : K[X] ⟶ K[X]`, see `equivalence.lean` for the general strategy of proof of the Dold-Kan equivalence. -/ open category_theory category_theory.category category_theory.limits category_theory.preadditive category_theory.simplicial_object opposite category_theory.idempotents open_locale simplicial dold_kan noncomputable theory namespace algebraic_topology namespace dold_kan variables {C : Type*} [category C] [preadditive C] {X : simplicial_object C} /-- This is the inductive definition of the projections `P q : K[X] ⟶ K[X]`, with `P 0 := 𝟙 _` and `P (q+1) := P q ≫ (𝟙 _ + Hσ q)`. -/ noncomputable def P : ℕ → (K[X] ⟶ K[X]) | 0 := 𝟙 _ | (q+1) := P q ≫ (𝟙 _ + Hσ q) /-- All the `P q` coincide with `𝟙 _` in degree 0. -/ @[simp] lemma P_f_0_eq (q : ℕ) : ((P q).f 0 : X _[0] ⟶ X _[0]) = 𝟙 _ := begin induction q with q hq, { refl, }, { unfold P, simp only [homological_complex.add_f_apply, homological_complex.comp_f, homological_complex.id_f, id_comp, hq, Hσ_eq_zero, add_zero], }, end /-- `Q q` is the complement projection associated to `P q` -/ def Q (q : ℕ) : K[X] ⟶ K[X] := 𝟙 _ - P q lemma P_add_Q (q : ℕ) : P q + Q q = 𝟙 K[X] := by { rw Q, abel, } lemma P_add_Q_f (q n : ℕ) : (P q).f n + (Q q).f n = 𝟙 (X _[n]) := homological_complex.congr_hom (P_add_Q q) n @[simp] lemma Q_eq_zero : (Q 0 : K[X] ⟶ _) = 0 := sub_self _ lemma Q_eq (q : ℕ) : (Q (q+1) : K[X] ⟶ _) = Q q - P q ≫ Hσ q := by { unfold Q P, simp only [comp_add, comp_id], abel, } /-- All the `Q q` coincide with `0` in degree 0. -/ @[simp] lemma Q_f_0_eq (q : ℕ) : ((Q q).f 0 : X _[0] ⟶ X _[0]) = 0 := by simp only [homological_complex.sub_f_apply, homological_complex.id_f, Q, P_f_0_eq, sub_self] namespace higher_faces_vanish /-- This lemma expresses the vanishing of `(P q).f (n+1) ≫ X.δ k : X _[n+1] ⟶ X _[n]` when `k≠0` and `k≥n-q+2` -/ lemma of_P : Π (q n : ℕ), higher_faces_vanish q (((P q).f (n+1) : X _[n+1] ⟶ X _[n+1])) | 0 := λ n j hj₁, by { exfalso, have hj₂ := fin.is_lt j, linarith, } | (q+1) := λ n, by { unfold P, exact (of_P q n).induction, } @[reassoc] lemma comp_P_eq_self {Y : C} {n q : ℕ} {φ : Y ⟶ X _[n+1]} (v : higher_faces_vanish q φ) : φ ≫ (P q).f (n+1) = φ := begin induction q with q hq, { unfold P, apply comp_id, }, { unfold P, simp only [comp_add, homological_complex.comp_f, homological_complex.add_f_apply, comp_id, ← assoc, hq v.of_succ, add_right_eq_self], by_cases hqn : n<q, { exact v.of_succ.comp_Hσ_eq_zero hqn, }, { cases nat.le.dest (not_lt.mp hqn) with a ha, have hnaq : n=a+q := by linarith, simp only [v.of_succ.comp_Hσ_eq hnaq, neg_eq_zero, ← assoc], have eq := v ⟨a, by linarith⟩ (by simp only [hnaq, fin.coe_mk, nat.succ_eq_add_one, add_assoc]), simp only [fin.succ_mk] at eq, simp only [eq, zero_comp], }, }, end end higher_faces_vanish lemma comp_P_eq_self_iff {Y : C} {n q : ℕ} {φ : Y ⟶ X _[n+1]} : φ ≫ (P q).f (n+1) = φ ↔ higher_faces_vanish q φ := begin split, { intro hφ, rw ← hφ, apply higher_faces_vanish.of_comp, apply higher_faces_vanish.of_P, }, { exact higher_faces_vanish.comp_P_eq_self, }, end @[simp, reassoc] lemma P_f_idem (q n : ℕ) : ((P q).f n : X _[n] ⟶ _) ≫ ((P q).f n) = (P q).f n := begin cases n, { rw [P_f_0_eq q, comp_id], }, { exact (higher_faces_vanish.of_P q n).comp_P_eq_self, } end @[simp, reassoc] lemma Q_f_idem (q n : ℕ) : ((Q q).f n : X _[n] ⟶ _) ≫ ((Q q).f n) = (Q q).f n := idem_of_id_sub_idem _ (P_f_idem q n) @[simp, reassoc] lemma P_idem (q : ℕ) : (P q : K[X] ⟶ K[X]) ≫ P q = P q := by { ext n, exact P_f_idem q n, } @[simp, reassoc] lemma Q_idem (q : ℕ) : (Q q : K[X] ⟶ K[X]) ≫ Q q = Q q := by { ext n, exact Q_f_idem q n, } /-- For each `q`, `P q` is a natural transformation. -/ @[simps] def nat_trans_P (q : ℕ) : alternating_face_map_complex C ⟶ alternating_face_map_complex C := { app := λ X, P q, naturality' := λ X Y f, begin induction q with q hq, { unfold P, dsimp only [alternating_face_map_complex], rw [id_comp, comp_id], }, { unfold P, simp only [add_comp, comp_add, assoc, comp_id, hq], congr' 1, rw [← assoc, hq, assoc], congr' 1, exact (nat_trans_Hσ q).naturality' f, } end } @[simp, reassoc] lemma P_f_naturality (q n : ℕ) {X Y : simplicial_object C} (f : X ⟶ Y) : f.app (op [n]) ≫ (P q).f n = (P q).f n ≫ f.app (op [n]) := homological_complex.congr_hom ((nat_trans_P q).naturality f) n @[simp, reassoc] lemma Q_f_naturality (q n : ℕ) {X Y : simplicial_object C} (f : X ⟶ Y) : f.app (op [n]) ≫ (Q q).f n = (Q q).f n ≫ f.app (op [n]) := begin simp only [Q, homological_complex.sub_f_apply, homological_complex.id_f, comp_sub, P_f_naturality, sub_comp, sub_left_inj], dsimp, simp only [comp_id, id_comp], end /-- For each `q`, `Q q` is a natural transformation. -/ @[simps] def nat_trans_Q (q : ℕ) : alternating_face_map_complex C ⟶ alternating_face_map_complex C := { app := λ X, Q q, } lemma map_P {D : Type*} [category D] [preadditive D] (G : C ⥤ D) [G.additive] (X : simplicial_object C) (q n : ℕ) : G.map ((P q : K[X] ⟶ _).f n) = (P q : K[((whiskering C D).obj G).obj X] ⟶ _).f n := begin induction q with q hq, { unfold P, apply G.map_id, }, { unfold P, simp only [comp_add, homological_complex.comp_f, homological_complex.add_f_apply, comp_id, functor.map_add, functor.map_comp, hq, map_Hσ], } end lemma map_Q {D : Type*} [category D] [preadditive D] (G : C ⥤ D) [G.additive] (X : simplicial_object C) (q n : ℕ) : G.map ((Q q : K[X] ⟶ _).f n) = (Q q : K[((whiskering C D).obj G).obj X] ⟶ _).f n := begin rw [← add_right_inj (G.map ((P q : K[X] ⟶ _).f n)), ← G.map_add, map_P G X q n, P_add_Q_f, P_add_Q_f], apply G.map_id, end end dold_kan end algebraic_topology
4dfa8f3587b4768002379fe7ecfe406c64294332
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/measure_theory/haar_measure.lean
b715a401c7b68145cf31254dc47773269ba17fd3
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
29,882
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import measure_theory.content import measure_theory.group /-! # Haar measure In this file we prove the existence of Haar measure for a locally compact Hausdorff topological group. For the construction, we follow the write-up by Jonathan Gleason, *Existence and Uniqueness of Haar Measure*. This is essentially the same argument as in https://en.wikipedia.org/wiki/Haar_measure#A_construction_using_compact_subsets. We construct the Haar measure first on compact sets. For this we define `(K : U)` as the (smallest) number of left-translates of `U` are needed to cover `K` (`index` in the formalization). Then we define the Haar measure on compact sets as `lim_U (K : U) / (K₀ : U)`, where `U` ranges over open neighborhoods of `1`, and `K₀` is a fixed compact set with nonempty interior. This is `chaar` in the formalization, and we prove that the limit exists by Tychonoff's theorem. The Haar measure on compact sets forms a content, which we can extend to an outer measure (`haar_outer_measure`), and obtain the Haar measure from that (`haar_measure`). We normalize the Haar measure so that the measure of `K₀` is `1`. ## Main Declarations * `haar_measure`: the Haar measure on a locally compact Hausdorff group. This is a left invariant regular measure. It takes as argument a compact set of the group (with non-empty interior), and is normalized so that the measure of the given set is 1. * `haar_measure_self`: the Haar measure is normalized. * `is_left_invariant_haar_measure`: the Haar measure is left invariant. * `regular_haar_measure`: the Haar measure is a regular measure. ## References * Paul Halmos (1950), Measure Theory, §53 * Jonathan Gleason, Existence and Uniqueness of Haar Measure - Note: step 9, page 8 contains a mistake: the last defined `μ` does not extend the `μ` on compact sets, see Halmos (1950) p. 233, bottom of the page. This makes some other steps (like step 11) invalid. * https://en.wikipedia.org/wiki/Haar_measure -/ noncomputable theory open set has_inv function topological_space measurable_space open_locale nnreal classical variables {G : Type*} [group G] namespace measure_theory namespace measure /-! We put the internal functions in the construction of the Haar measure in a namespace, so that the chosen names don't clash with other declarations. We first define a couple of the functions before proving the properties (that require that `G` is a topological group). -/ namespace haar /-- The index or Haar covering number or ratio of `K` w.r.t. `V`, denoted `(K : V)`: it is the smallest number of (left) translates of `V` that is necessary to cover `K`. It is defined to be 0 if no finite number of translates cover `K`. -/ def index (K V : set G) : ℕ := Inf $ finset.card '' {t : finset G | K ⊆ ⋃ g ∈ t, (λ h, g * h) ⁻¹' V } lemma index_empty {V : set G} : index ∅ V = 0 := begin simp only [index, nat.Inf_eq_zero], left, use ∅, simp only [finset.card_empty, empty_subset, mem_set_of_eq, eq_self_iff_true, and_self], end variables [topological_space G] /-- `prehaar K₀ U K` is a weighted version of the index, defined as `(K : U)/(K₀ : U)`. In the applications `K₀` is compact with non-empty interior, `U` is open containing `1`, and `K` is any compact set. The argument `K` is a (bundled) compact set, so that we can consider `prehaar K₀ U` as an element of `haar_product` (below). -/ def prehaar (K₀ U : set G) (K : compacts G) : ℝ := (index K.1 U : ℝ) / index K₀ U lemma prehaar_empty (K₀ : positive_compacts G) {U : set G} : prehaar K₀.1 U ⊥ = 0 := by { simp only [prehaar, compacts.bot_val, index_empty, nat.cast_zero, zero_div] } lemma prehaar_nonneg (K₀ : positive_compacts G) {U : set G} (K : compacts G) : 0 ≤ prehaar K₀.1 U K := by apply div_nonneg; norm_cast; apply zero_le /-- `haar_product K₀` is the product of intervals `[0, (K : K₀)]`, for all compact sets `K`. For all `U`, we can show that `prehaar K₀ U ∈ haar_product K₀`. -/ def haar_product (K₀ : set G) : set (compacts G → ℝ) := pi univ (λ K, Icc 0 $ index K.1 K₀) @[simp] lemma mem_prehaar_empty {K₀ : set G} {f : compacts G → ℝ} : f ∈ haar_product K₀ ↔ ∀ K : compacts G, f K ∈ Icc (0 : ℝ) (index K.1 K₀) := by simp only [haar_product, pi, forall_prop_of_true, mem_univ, mem_set_of_eq] /-- The closure of the collection of elements of the form `prehaar K₀ U`, for `U` open neighbourhoods of `1`, contained in `V`. The closure is taken in the space `compacts G → ℝ`, with the topology of pointwise convergence. We show that the intersection of all these sets is nonempty, and the Haar measure on compact sets is defined to be an element in the closure of this intersection. -/ def cl_prehaar (K₀ : set G) (V : open_nhds_of (1 : G)) : set (compacts G → ℝ) := closure $ prehaar K₀ '' { U : set G | U ⊆ V.1 ∧ is_open U ∧ (1 : G) ∈ U } variables [topological_group G] /-! ### Lemmas about `index` -/ /-- If `K` is compact and `V` has nonempty interior, then the index `(K : V)` is well-defined, there is a finite set `t` satisfying the desired properties. -/ lemma index_defined {K V : set G} (hK : is_compact K) (hV : (interior V).nonempty) : ∃ n : ℕ, n ∈ finset.card '' {t : finset G | K ⊆ ⋃ g ∈ t, (λ h, g * h) ⁻¹' V } := by { rcases compact_covered_by_mul_left_translates hK hV with ⟨t, ht⟩, exact ⟨t.card, t, ht, rfl⟩ } lemma index_elim {K V : set G} (hK : is_compact K) (hV : (interior V).nonempty) : ∃ (t : finset G), K ⊆ (⋃ g ∈ t, (λ h, g * h) ⁻¹' V) ∧ finset.card t = index K V := by { have := nat.Inf_mem (index_defined hK hV), rwa [mem_image] at this } lemma le_index_mul (K₀ : positive_compacts G) (K : compacts G) {V : set G} (hV : (interior V).nonempty) : index K.1 V ≤ index K.1 K₀.1 * index K₀.1 V := begin rcases index_elim K.2 K₀.2.2 with ⟨s, h1s, h2s⟩, rcases index_elim K₀.2.1 hV with ⟨t, h1t, h2t⟩, rw [← h2s, ← h2t, mul_comm], refine le_trans _ finset.mul_card_le, apply nat.Inf_le, refine ⟨_, _, rfl⟩, rw [mem_set_of_eq], refine subset.trans h1s _, apply bUnion_subset, intros g₁ hg₁, rw preimage_subset_iff, intros g₂ hg₂, have := h1t hg₂, rcases this with ⟨_, ⟨g₃, rfl⟩, A, ⟨hg₃, rfl⟩, h2V⟩, rw [mem_preimage, ← mul_assoc] at h2V, exact mem_bUnion (finset.mul_mem_mul hg₃ hg₁) h2V end lemma index_pos (K : positive_compacts G) {V : set G} (hV : (interior V).nonempty) : 0 < index K.1 V := begin unfold index, rw [nat.Inf_def, nat.find_pos, mem_image], { rintro ⟨t, h1t, h2t⟩, rw [finset.card_eq_zero] at h2t, subst h2t, cases K.2.2 with g hg, show g ∈ (∅ : set G), convert h1t (interior_subset hg), symmetry, apply bUnion_empty }, { exact index_defined K.2.1 hV } end lemma index_mono {K K' V : set G} (hK' : is_compact K') (h : K ⊆ K') (hV : (interior V).nonempty) : index K V ≤ index K' V := begin rcases index_elim hK' hV with ⟨s, h1s, h2s⟩, apply nat.Inf_le, rw [mem_image], refine ⟨s, subset.trans h h1s, h2s⟩ end lemma index_union_le (K₁ K₂ : compacts G) {V : set G} (hV : (interior V).nonempty) : index (K₁.1 ∪ K₂.1) V ≤ index K₁.1 V + index K₂.1 V := begin rcases index_elim K₁.2 hV with ⟨s, h1s, h2s⟩, rcases index_elim K₂.2 hV with ⟨t, h1t, h2t⟩, rw [← h2s, ← h2t], refine le_trans _ (finset.card_union_le _ _), apply nat.Inf_le, refine ⟨_, _, rfl⟩, rw [mem_set_of_eq], apply union_subset; refine subset.trans (by assumption) _; apply bUnion_subset_bUnion_left; intros g hg; simp only [mem_def] at hg; simp only [mem_def, multiset.mem_union, finset.union_val, hg, or_true, true_or] end lemma index_union_eq (K₁ K₂ : compacts G) {V : set G} (hV : (interior V).nonempty) (h : disjoint (K₁.1 * V⁻¹) (K₂.1 * V⁻¹)) : index (K₁.1 ∪ K₂.1) V = index K₁.1 V + index K₂.1 V := begin apply le_antisymm (index_union_le K₁ K₂ hV), rcases index_elim (K₁.2.union K₂.2) hV with ⟨s, h1s, h2s⟩, rw [← h2s], have : ∀(K : set G) , K ⊆ (⋃ g ∈ s, (λ h, g * h) ⁻¹' V) → index K V ≤ (s.filter (λ g, ((λ (h : G), g * h) ⁻¹' V ∩ K).nonempty)).card, { intros K hK, apply nat.Inf_le, refine ⟨_, _, rfl⟩, rw [mem_set_of_eq], intros g hg, rcases hK hg with ⟨_, ⟨g₀, rfl⟩, _, ⟨h1g₀, rfl⟩, h2g₀⟩, simp only [mem_preimage] at h2g₀, simp only [mem_Union], use g₀, split, { simp only [finset.mem_filter, h1g₀, true_and], use g, simp only [hg, h2g₀, mem_inter_eq, mem_preimage, and_self] }, exact h2g₀ }, refine le_trans (add_le_add (this K₁.1 $ subset.trans (subset_union_left _ _) h1s) (this K₂.1 $ subset.trans (subset_union_right _ _) h1s)) _, rw [← finset.card_union_eq, finset.filter_union_right], { apply finset.card_le_of_subset, apply finset.filter_subset }, apply finset.disjoint_filter.mpr, rintro g₁ h1g₁ ⟨g₂, h1g₂, h2g₂⟩ ⟨g₃, h1g₃, h2g₃⟩, simp only [mem_preimage] at h1g₃ h1g₂, apply @h g₁⁻¹, split; simp only [set.mem_inv, set.mem_mul, exists_exists_and_eq_and, exists_and_distrib_left], { refine ⟨_, h2g₂, (g₁ * g₂)⁻¹, _, _⟩, simp only [inv_inv, h1g₂], simp only [mul_inv_rev, mul_inv_cancel_left] }, { refine ⟨_, h2g₃, (g₁ * g₃)⁻¹, _, _⟩, simp only [inv_inv, h1g₃], simp only [mul_inv_rev, mul_inv_cancel_left] } end lemma mul_left_index_le {K : set G} (hK : is_compact K) {V : set G} (hV : (interior V).nonempty) (g : G) : index ((λ h, g * h) '' K) V ≤ index K V := begin rcases index_elim hK hV with ⟨s, h1s, h2s⟩, rw [← h2s], apply nat.Inf_le, rw [mem_image], refine ⟨s.map (equiv.mul_right g⁻¹).to_embedding, _, finset.card_map _⟩, { simp only [mem_set_of_eq], refine subset.trans (image_subset _ h1s) _, rintro _ ⟨g₁, ⟨_, ⟨g₂, rfl⟩, ⟨_, ⟨hg₂, rfl⟩, hg₁⟩⟩, rfl⟩, simp only [mem_preimage] at hg₁, simp only [exists_prop, mem_Union, finset.mem_map, equiv.coe_mul_right, exists_exists_and_eq_and, mem_preimage, equiv.to_embedding_coe_fn], refine ⟨_, hg₂, _⟩, simp only [mul_assoc, hg₁, inv_mul_cancel_left] } end lemma is_left_invariant_index {K : set G} (hK : is_compact K) {V : set G} (hV : (interior V).nonempty) (g : G) : index ((λ h, g * h) '' K) V = index K V := begin refine le_antisymm (mul_left_index_le hK hV g) _, convert mul_left_index_le (hK.image $ continuous_mul_left g) hV g⁻¹, rw [image_image], symmetry, convert image_id' _, ext h, apply inv_mul_cancel_left end /-! ### Lemmas about `prehaar` -/ lemma prehaar_le_index (K₀ : positive_compacts G) {U : set G} (K : compacts G) (hU : (interior U).nonempty) : prehaar K₀.1 U K ≤ index K.1 K₀.1 := begin unfold prehaar, rw [div_le_iff]; norm_cast, { apply le_index_mul K₀ K hU }, { exact index_pos K₀ hU } end lemma prehaar_pos (K₀ : positive_compacts G) {U : set G} (hU : (interior U).nonempty) {K : set G} (h1K : is_compact K) (h2K : (interior K).nonempty) : 0 < prehaar K₀.1 U ⟨K, h1K⟩ := by { apply div_pos; norm_cast, apply index_pos ⟨K, h1K, h2K⟩ hU, exact index_pos K₀ hU } lemma prehaar_mono {K₀ : positive_compacts G} {U : set G} (hU : (interior U).nonempty) {K₁ K₂ : compacts G} (h : K₁.1 ⊆ K₂.1) : prehaar K₀.1 U K₁ ≤ prehaar K₀.1 U K₂ := begin simp only [prehaar], rw [div_le_div_right], exact_mod_cast index_mono K₂.2 h hU, exact_mod_cast index_pos K₀ hU end lemma prehaar_self {K₀ : positive_compacts G} {U : set G} (hU : (interior U).nonempty) : prehaar K₀.1 U ⟨K₀.1, K₀.2.1⟩ = 1 := by { simp only [prehaar], rw [div_self], apply ne_of_gt, exact_mod_cast index_pos K₀ hU } lemma prehaar_sup_le {K₀ : positive_compacts G} {U : set G} (K₁ K₂ : compacts G) (hU : (interior U).nonempty) : prehaar K₀.1 U (K₁ ⊔ K₂) ≤ prehaar K₀.1 U K₁ + prehaar K₀.1 U K₂ := begin simp only [prehaar], rw [div_add_div_same, div_le_div_right], exact_mod_cast index_union_le K₁ K₂ hU, exact_mod_cast index_pos K₀ hU end lemma prehaar_sup_eq {K₀ : positive_compacts G} {U : set G} {K₁ K₂ : compacts G} (hU : (interior U).nonempty) (h : disjoint (K₁.1 * U⁻¹) (K₂.1 * U⁻¹)) : prehaar K₀.1 U (K₁ ⊔ K₂) = prehaar K₀.1 U K₁ + prehaar K₀.1 U K₂ := by { simp only [prehaar], rw [div_add_div_same], congr', exact_mod_cast index_union_eq K₁ K₂ hU h } lemma is_left_invariant_prehaar {K₀ : positive_compacts G} {U : set G} (hU : (interior U).nonempty) {K : compacts G} {g : G} : prehaar K₀.1 U (K.map _ $ continuous_mul_left g) = prehaar K₀.1 U K := by simp only [prehaar, compacts.map_val, is_left_invariant_index K.2 hU] /-! ### Lemmas about `haar_product` -/ lemma prehaar_mem_haar_product (K₀ : positive_compacts G) {U : set G} (hU : (interior U).nonempty) : prehaar K₀.1 U ∈ haar_product K₀.1 := by { rintro ⟨K, hK⟩ h2K, rw [mem_Icc], exact ⟨prehaar_nonneg K₀ _, prehaar_le_index K₀ _ hU⟩ } lemma nonempty_Inter_cl_prehaar (K₀ : positive_compacts G) : (haar_product K₀.1 ∩ ⋂ (V : open_nhds_of (1 : G)), cl_prehaar K₀.1 V).nonempty := begin have : is_compact (haar_product K₀.1), { apply compact_univ_pi, intro K, apply compact_Icc }, refine this.inter_Inter_nonempty (cl_prehaar K₀.1) (λ s, is_closed_closure) (λ t, _), let V₀ := ⋂ (V ∈ t), (V : open_nhds_of 1).1, have h1V₀ : is_open V₀, { apply is_open_bInter, apply finite_mem_finset, rintro ⟨V, hV⟩ h2V, exact hV.1 }, have h2V₀ : (1 : G) ∈ V₀, { simp only [mem_Inter], rintro ⟨V, hV⟩ h2V, exact hV.2 }, refine ⟨prehaar K₀.1 V₀, _⟩, split, { apply prehaar_mem_haar_product K₀, use 1, rwa h1V₀.interior_eq }, { simp only [mem_Inter], rintro ⟨V, hV⟩ h2V, apply subset_closure, apply mem_image_of_mem, rw [mem_set_of_eq], exact ⟨subset.trans (Inter_subset _ ⟨V, hV⟩) (Inter_subset _ h2V), h1V₀, h2V₀⟩ }, end /-! ### The Haar measure on compact sets -/ /-- The Haar measure on compact sets, defined to be an arbitrary element in the intersection of all the sets `cl_prehaar K₀ V` in `haar_product K₀`. -/ def chaar (K₀ : positive_compacts G) (K : compacts G) : ℝ := classical.some (nonempty_Inter_cl_prehaar K₀) K lemma chaar_mem_haar_product (K₀ : positive_compacts G) : chaar K₀ ∈ haar_product K₀.1 := (classical.some_spec (nonempty_Inter_cl_prehaar K₀)).1 lemma chaar_mem_cl_prehaar (K₀ : positive_compacts G) (V : open_nhds_of (1 : G)) : chaar K₀ ∈ cl_prehaar K₀.1 V := by { have := (classical.some_spec (nonempty_Inter_cl_prehaar K₀)).2, rw [mem_Inter] at this, exact this V } lemma chaar_nonneg (K₀ : positive_compacts G) (K : compacts G) : 0 ≤ chaar K₀ K := by { have := chaar_mem_haar_product K₀ K (mem_univ _), rw mem_Icc at this, exact this.1 } lemma chaar_empty (K₀ : positive_compacts G) : chaar K₀ ⊥ = 0 := begin let eval : (compacts G → ℝ) → ℝ := λ f, f ⊥, have : continuous eval := continuous_apply ⊥, show chaar K₀ ∈ eval ⁻¹' {(0 : ℝ)}, apply mem_of_subset_of_mem _ (chaar_mem_cl_prehaar K₀ ⟨set.univ, is_open_univ, mem_univ _⟩), unfold cl_prehaar, rw is_closed.closure_subset_iff, { rintro _ ⟨U, ⟨h1U, h2U, h3U⟩, rfl⟩, apply prehaar_empty }, { apply continuous_iff_is_closed.mp this, exact is_closed_singleton }, end lemma chaar_self (K₀ : positive_compacts G) : chaar K₀ ⟨K₀.1, K₀.2.1⟩ = 1 := begin let eval : (compacts G → ℝ) → ℝ := λ f, f ⟨K₀.1, K₀.2.1⟩, have : continuous eval := continuous_apply _, show chaar K₀ ∈ eval ⁻¹' {(1 : ℝ)}, apply mem_of_subset_of_mem _ (chaar_mem_cl_prehaar K₀ ⟨set.univ, is_open_univ, mem_univ _⟩), unfold cl_prehaar, rw is_closed.closure_subset_iff, { rintro _ ⟨U, ⟨h1U, h2U, h3U⟩, rfl⟩, apply prehaar_self, rw h2U.interior_eq, exact ⟨1, h3U⟩ }, { apply continuous_iff_is_closed.mp this, exact is_closed_singleton } end lemma chaar_mono {K₀ : positive_compacts G} {K₁ K₂ : compacts G} (h : K₁.1 ⊆ K₂.1) : chaar K₀ K₁ ≤ chaar K₀ K₂ := begin let eval : (compacts G → ℝ) → ℝ := λ f, f K₂ - f K₁, have : continuous eval := continuous_sub.comp (continuous.prod_mk (continuous_apply K₂) (@continuous_apply _ (λ _, ℝ) _ K₁)), rw [← sub_nonneg], show chaar K₀ ∈ eval ⁻¹' (Ici (0 : ℝ)), apply mem_of_subset_of_mem _ (chaar_mem_cl_prehaar K₀ ⟨set.univ, is_open_univ, mem_univ _⟩), unfold cl_prehaar, rw is_closed.closure_subset_iff, { rintro _ ⟨U, ⟨h1U, h2U, h3U⟩, rfl⟩, simp only [mem_preimage, mem_Ici, eval, sub_nonneg], apply prehaar_mono _ h, rw h2U.interior_eq, exact ⟨1, h3U⟩ }, { apply continuous_iff_is_closed.mp this, exact is_closed_Ici }, end lemma chaar_sup_le {K₀ : positive_compacts G} (K₁ K₂ : compacts G) : chaar K₀ (K₁ ⊔ K₂) ≤ chaar K₀ K₁ + chaar K₀ K₂ := begin let eval : (compacts G → ℝ) → ℝ := λ f, f K₁ + f K₂ - f (K₁ ⊔ K₂), have : continuous eval := continuous_sub.comp (continuous.prod_mk (continuous_add.comp (continuous.prod_mk (continuous_apply K₁) (@continuous_apply _ (λ _, ℝ) _ K₂))) (@continuous_apply _ (λ _, ℝ) _(K₁ ⊔ K₂))), rw [← sub_nonneg], show chaar K₀ ∈ eval ⁻¹' (Ici (0 : ℝ)), apply mem_of_subset_of_mem _ (chaar_mem_cl_prehaar K₀ ⟨set.univ, is_open_univ, mem_univ _⟩), unfold cl_prehaar, rw is_closed.closure_subset_iff, { rintro _ ⟨U, ⟨h1U, h2U, h3U⟩, rfl⟩, simp only [mem_preimage, mem_Ici, eval, sub_nonneg], apply prehaar_sup_le, rw h2U.interior_eq, exact ⟨1, h3U⟩ }, { apply continuous_iff_is_closed.mp this, exact is_closed_Ici }, end lemma chaar_sup_eq [t2_space G] {K₀ : positive_compacts G} {K₁ K₂ : compacts G} (h : disjoint K₁.1 K₂.1) : chaar K₀ (K₁ ⊔ K₂) = chaar K₀ K₁ + chaar K₀ K₂ := begin rcases compact_compact_separated K₁.2 K₂.2 (disjoint_iff.mp h) with ⟨U₁, U₂, h1U₁, h1U₂, h2U₁, h2U₂, hU⟩, rw [← disjoint_iff_inter_eq_empty] at hU, rcases compact_open_separated_mul K₁.2 h1U₁ h2U₁ with ⟨V₁, h1V₁, h2V₁, h3V₁⟩, rcases compact_open_separated_mul K₂.2 h1U₂ h2U₂ with ⟨V₂, h1V₂, h2V₂, h3V₂⟩, let eval : (compacts G → ℝ) → ℝ := λ f, f K₁ + f K₂ - f (K₁ ⊔ K₂), have : continuous eval := continuous_sub.comp (continuous.prod_mk (continuous_add.comp (continuous.prod_mk (continuous_apply K₁) (@continuous_apply _ (λ _, ℝ) _ K₂))) (@continuous_apply _ (λ _, ℝ) _(K₁ ⊔ K₂))), rw [eq_comm, ← sub_eq_zero], show chaar K₀ ∈ eval ⁻¹' {(0 : ℝ)}, let V := V₁ ∩ V₂, apply mem_of_subset_of_mem _ (chaar_mem_cl_prehaar K₀ ⟨V⁻¹, continuous_inv V (is_open_inter h1V₁ h1V₂), by simp only [mem_inv, one_inv, h2V₁, h2V₂, V, mem_inter_eq, true_and]⟩), unfold cl_prehaar, rw is_closed.closure_subset_iff, { rintro _ ⟨U, ⟨h1U, h2U, h3U⟩, rfl⟩, simp only [mem_preimage, eval, sub_eq_zero, mem_singleton_iff], rw [eq_comm], apply prehaar_sup_eq, { rw h2U.interior_eq, exact ⟨1, h3U⟩ }, { refine disjoint_of_subset _ _ hU, { refine subset.trans (mul_subset_mul subset.rfl _) h3V₁, exact subset.trans (inv_subset.mpr h1U) (inter_subset_left _ _) }, { refine subset.trans (mul_subset_mul subset.rfl _) h3V₂, exact subset.trans (inv_subset.mpr h1U) (inter_subset_right _ _) }}}, { apply continuous_iff_is_closed.mp this, exact is_closed_singleton }, end lemma is_left_invariant_chaar {K₀ : positive_compacts G} {K : compacts G} {g : G} : chaar K₀ (K.map _ $ continuous_mul_left g) = chaar K₀ K := begin let eval : (compacts G → ℝ) → ℝ := λ f, f (K.map _ $ continuous_mul_left g) - f K, have : continuous eval := continuous_sub.comp (continuous.prod_mk (continuous_apply (K.map _ _)) (@continuous_apply _ (λ _, ℝ) _ K)), rw [← sub_eq_zero], show chaar K₀ ∈ eval ⁻¹' {(0 : ℝ)}, apply mem_of_subset_of_mem _ (chaar_mem_cl_prehaar K₀ ⟨set.univ, is_open_univ, mem_univ _⟩), unfold cl_prehaar, rw is_closed.closure_subset_iff, { rintro _ ⟨U, ⟨h1U, h2U, h3U⟩, rfl⟩, simp only [mem_singleton_iff, mem_preimage, eval, sub_eq_zero], apply is_left_invariant_prehaar, rw h2U.interior_eq, exact ⟨1, h3U⟩ }, { apply continuous_iff_is_closed.mp this, exact is_closed_singleton }, end /-- The function `chaar` interpreted in `ennreal` -/ @[reducible] def echaar (K₀ : positive_compacts G) (K : compacts G) : ennreal := show nnreal, from ⟨chaar K₀ K, chaar_nonneg _ _⟩ /-- The variant of `chaar_sup_le` for `echaar` -/ lemma echaar_sup_le {K₀ : positive_compacts G} (K₁ K₂ : compacts G) : echaar K₀ (K₁ ⊔ K₂) ≤ echaar K₀ K₁ + echaar K₀ K₂ := by { norm_cast, simp only [←nnreal.coe_le_coe, nnreal.coe_add, subtype.coe_mk, chaar_sup_le]} /-- The variant of `chaar_mono` for `echaar` -/ lemma echaar_mono {K₀ : positive_compacts G} ⦃K₁ K₂ : compacts G⦄ (h : K₁.1 ⊆ K₂.1) : echaar K₀ K₁ ≤ echaar K₀ K₂ := by { norm_cast, simp only [←nnreal.coe_le_coe, subtype.coe_mk, chaar_mono, h] } end haar open haar /-! ### The Haar outer measure -/ variables [topological_space G] [t2_space G] [topological_group G] /-- The Haar outer measure on `G`. It is not normalized, and is mainly used to construct `haar_measure`, which is a normalized measure. -/ def haar_outer_measure (K₀ : positive_compacts G) : outer_measure G := outer_measure.of_content (echaar K₀) $ by { rw echaar, norm_cast, rw [←nnreal.coe_eq, nnreal.coe_zero, subtype.coe_mk, chaar_empty] } lemma haar_outer_measure_eq_infi (K₀ : positive_compacts G) (A : set G) : haar_outer_measure K₀ A = ⨅ (U : set G) (hU : is_open U) (h : A ⊆ U), inner_content (echaar K₀) ⟨U, hU⟩ := outer_measure.of_content_eq_infi echaar_sup_le A lemma chaar_le_haar_outer_measure {K₀ : positive_compacts G} (K : compacts G) : (show ℝ≥0, from ⟨chaar K₀ K, chaar_nonneg K₀ K⟩ : ennreal) ≤ haar_outer_measure K₀ K.1 := outer_measure.le_of_content_compacts echaar_sup_le K lemma haar_outer_measure_of_is_open {K₀ : positive_compacts G} (U : set G) (hU : is_open U) : haar_outer_measure K₀ U = inner_content (λ K, show ℝ≥0, from ⟨chaar K₀ K, chaar_nonneg K₀ K⟩) ⟨U, hU⟩ := outer_measure.of_content_opens echaar_sup_le ⟨U, hU⟩ lemma haar_outer_measure_le_chaar {K₀ : positive_compacts G} {U : set G} (hU : is_open U) (K : compacts G) (h : U ⊆ K.1) : haar_outer_measure K₀ U ≤ show ℝ≥0, from ⟨chaar K₀ K, chaar_nonneg K₀ K⟩ := begin rw haar_outer_measure_of_is_open U hU, refine inner_content_le _ _ K h, intros K₁ K₂ hK, norm_cast, rw [← nnreal.coe_le_coe], exact chaar_mono hK end lemma haar_outer_measure_exists_open {K₀ : positive_compacts G} {A : set G} (hA : haar_outer_measure K₀ A < ⊤) {ε : ℝ≥0} (hε : 0 < ε) : ∃ U : opens G, A ⊆ U ∧ haar_outer_measure K₀ U ≤ haar_outer_measure K₀ A + ε := outer_measure.of_content_exists_open echaar_sup_le hA hε lemma haar_outer_measure_exists_compact {K₀ : positive_compacts G} {U : opens G} (hU : haar_outer_measure K₀ U < ⊤) {ε : ℝ≥0} (hε : 0 < ε) : ∃ K : compacts G, K.1 ⊆ U ∧ haar_outer_measure K₀ U ≤ haar_outer_measure K₀ K.1 + ε := outer_measure.of_content_exists_compact echaar_sup_le hU hε lemma haar_outer_measure_caratheodory {K₀ : positive_compacts G} (A : set G) : (haar_outer_measure K₀).caratheodory.is_measurable A ↔ ∀ (U : opens G), haar_outer_measure K₀ (U ∩ A) + haar_outer_measure K₀ (U \ A) ≤ haar_outer_measure K₀ U := outer_measure.of_content_caratheodory echaar_sup_le A lemma one_le_haar_outer_measure_self {K₀ : positive_compacts G} : 1 ≤ haar_outer_measure K₀ K₀.1 := begin rw [haar_outer_measure_eq_infi], refine le_binfi _, intros U hU, refine le_infi _, intros h2U, refine le_trans _ (le_supr _ ⟨K₀.1, K₀.2.1⟩), refine le_trans _ (le_supr _ h2U), simp only [←nnreal.coe_le_coe, subtype.coe_mk, ennreal.one_le_coe_iff, nnreal.coe_one], rw [chaar_self] end lemma haar_outer_measure_pos_of_is_open {K₀ : positive_compacts G} {U : set G} (hU : is_open U) (h2U : U.nonempty) : 0 < haar_outer_measure K₀ U := begin refine outer_measure.of_content_pos_of_is_open echaar_sup_le _ ⟨K₀.1, K₀.2.1⟩ _ hU h2U, { intros g K, simpa only [ennreal.coe_eq_coe, ←nnreal.coe_eq] using is_left_invariant_chaar }, simp only [ennreal.coe_pos, ←nnreal.coe_pos, chaar_self, zero_lt_one, subtype.coe_mk] end lemma haar_outer_measure_self_pos {K₀ : positive_compacts G} : 0 < haar_outer_measure K₀ K₀.1 := lt_of_lt_of_le (haar_outer_measure_pos_of_is_open is_open_interior K₀.2.2) ((haar_outer_measure K₀).mono interior_subset) lemma haar_outer_measure_lt_top_of_is_compact [locally_compact_space G] {K₀ : positive_compacts G} {K : set G} (hK : is_compact K) : haar_outer_measure K₀ K < ⊤ := begin rcases exists_compact_superset hK with ⟨F, h1F, h2F⟩, refine lt_of_le_of_lt ((haar_outer_measure K₀).mono h2F) _, refine lt_of_le_of_lt (haar_outer_measure_le_chaar is_open_interior ⟨F, h1F⟩ interior_subset) ennreal.coe_lt_top end variables [S : measurable_space G] [borel_space G] include S lemma haar_caratheodory_measurable (K₀ : positive_compacts G) : S ≤ (haar_outer_measure K₀).caratheodory := begin rw [@borel_space.measurable_eq G _ _], refine generate_from_le _, intros U hU, rw haar_outer_measure_caratheodory, intro U', rw haar_outer_measure_of_is_open ((U' : set G) ∩ U) (is_open_inter U'.prop hU), simp only [inner_content, supr_subtype'], rw [opens.coe_mk], haveI : nonempty {L : compacts G // L.1 ⊆ U' ∩ U} := ⟨⟨⊥, empty_subset _⟩⟩, rw [ennreal.supr_add], refine supr_le _, rintro ⟨L, hL⟩, simp only [subset_inter_iff] at hL, have : ↑U' \ U ⊆ U' \ L.1 := diff_subset_diff_right hL.2, refine le_trans (add_le_add_left ((haar_outer_measure K₀).mono' this) _) _, rw haar_outer_measure_of_is_open (↑U' \ L.1) (is_open_diff U'.2 L.2.is_closed), simp only [inner_content, supr_subtype'], rw [opens.coe_mk], haveI : nonempty {M : compacts G // M.1 ⊆ ↑U' \ L.1} := ⟨⟨⊥, empty_subset _⟩⟩, rw [ennreal.add_supr], refine supr_le _, rintro ⟨M, hM⟩, simp only [subset_diff] at hM, have : (L ⊔ M).1 ⊆ U', { simp only [union_subset_iff, compacts.sup_val, hM, hL, and_self] }, rw haar_outer_measure_of_is_open ↑U' U'.2, refine le_trans (ge_of_eq _) (le_inner_content _ _ this), norm_cast, simp only [←nnreal.coe_eq, nnreal.coe_add, subtype.coe_mk], exact chaar_sup_eq hM.2.symm end /-! ### The Haar measure -/ /-- the Haar measure on `G`, scaled so that `haar_measure K₀ K₀ = 1`. -/ def haar_measure (K₀ : positive_compacts G) : measure G := (haar_outer_measure K₀ K₀.1)⁻¹ • (haar_outer_measure K₀).to_measure (haar_caratheodory_measurable K₀) lemma haar_measure_apply {K₀ : positive_compacts G} {s : set G} (hs : is_measurable s) : haar_measure K₀ s = haar_outer_measure K₀ s / haar_outer_measure K₀ K₀.1 := by { simp only [haar_measure, hs, ennreal.div_def, mul_comm, to_measure_apply, algebra.id.smul_eq_mul, pi.smul_apply, measure.coe_smul] } lemma is_left_invariant_haar_measure (K₀ : positive_compacts G) : is_left_invariant (haar_measure K₀) := begin intros g A hA, rw [haar_measure_apply hA, haar_measure_apply], { congr' 1, refine outer_measure.is_left_invariant_of_content echaar_sup_le _ g A, intros g K, simpa only [ennreal.coe_eq_coe, ←nnreal.coe_eq] using is_left_invariant_chaar }, { exact measurable_mul_left g hA } end lemma haar_measure_self [locally_compact_space G] {K₀ : positive_compacts G} : haar_measure K₀ K₀.1 = 1 := begin rw [haar_measure_apply K₀.2.1.is_measurable, ennreal.div_self], { rw [← zero_lt_iff_ne_zero], exact haar_outer_measure_self_pos }, { exact ne_of_lt (haar_outer_measure_lt_top_of_is_compact K₀.2.1) } end lemma haar_measure_pos_of_is_open [locally_compact_space G] {K₀ : positive_compacts G} {U : set G} (hU : is_open U) (h2U : U.nonempty) : 0 < haar_measure K₀ U := begin rw [haar_measure_apply hU.is_measurable, ennreal.div_pos_iff], refine ⟨_, ne_of_lt $ haar_outer_measure_lt_top_of_is_compact K₀.2.1⟩, rw [← zero_lt_iff_ne_zero], apply haar_outer_measure_pos_of_is_open hU h2U end lemma regular_haar_measure [locally_compact_space G] {K₀ : positive_compacts G} : (haar_measure K₀).regular := begin apply measure.regular.smul, split, { intros K hK, rw [to_measure_apply _ _ hK.is_measurable], apply haar_outer_measure_lt_top_of_is_compact hK }, { intros A hA, rw [to_measure_apply _ _ hA, haar_outer_measure_eq_infi], refine binfi_le_binfi _, intros U hU, refine infi_le_infi _, intro h2U, rw [to_measure_apply _ _ hU.is_measurable, haar_outer_measure_of_is_open U hU], refl' }, { intros U hU, rw [to_measure_apply _ _ hU.is_measurable, haar_outer_measure_of_is_open U hU], dsimp only [inner_content], refine bsupr_le (λ K hK, _), refine le_supr_of_le K.1 _, refine le_supr_of_le K.2 _, refine le_supr_of_le hK _, rw [to_measure_apply _ _ K.2.is_measurable], apply chaar_le_haar_outer_measure }, { rw ennreal.inv_lt_top, apply haar_outer_measure_self_pos } end end measure end measure_theory
ee7c52470d150d1bcb1f5f2104c87a1fc44f4c7a
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/stage0/src/Lean/Meta/TransparencyMode.lean
3a36af4b7fa67fc5ff95eb1861e3628fb31f7e1c
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
817
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 -/ namespace Lean.Meta inductive TransparencyMode where | all | default | reducible | instances deriving Inhabited, BEq, Repr namespace TransparencyMode def hash : TransparencyMode → UInt64 | all => 7 | default => 11 | reducible => 13 | instances => 17 instance : Hashable TransparencyMode := ⟨hash⟩ def lt : TransparencyMode → TransparencyMode → Bool | reducible, default => true | reducible, all => true | reducible, instances => true | instances, default => true | instances, all => true | default, all => true | _, _ => false end TransparencyMode end Lean.Meta
8454cb1d373a5c15ca77de62d6ad86d8fdbe8d8c
c777c32c8e484e195053731103c5e52af26a25d1
/src/analysis/calculus/bump_function_inner.lean
f236cbd0c333399c682678e075c402072b8e7197
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
23,869
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Floris van Doorn -/ import analysis.calculus.iterated_deriv import analysis.inner_product_space.calculus import measure_theory.integral.set_integral /-! # Infinitely smooth bump function In this file we construct several infinitely smooth functions with properties that an analytic function cannot have: * `exp_neg_inv_glue` is equal to zero for `x ≤ 0` and is strictly positive otherwise; it is given by `x ↦ exp (-1/x)` for `x > 0`; * `real.smooth_transition` is equal to zero for `x ≤ 0` and is equal to one for `x ≥ 1`; it is given by `exp_neg_inv_glue x / (exp_neg_inv_glue x + exp_neg_inv_glue (1 - x))`; * `f : cont_diff_bump c`, where `c` is a point in a real vector space, is a bundled smooth function such that - `f` is equal to `1` in `metric.closed_ball c f.r`; - `support f = metric.ball c f.R`; - `0 ≤ f x ≤ 1` for all `x`. The structure `cont_diff_bump` contains the data required to construct the function: real numbers `r`, `R`, and proofs of `0 < r < R`. The function itself is available through `coe_fn`. * If `f : cont_diff_bump c` and `μ` is a measure on the domain of `f`, then `f.normed μ` is a smooth bump function with integral `1` w.r.t. `μ`. -/ noncomputable theory open_locale classical topology open polynomial real filter set function open_locale polynomial /-- `exp_neg_inv_glue` is the real function given by `x ↦ exp (-1/x)` for `x > 0` and `0` for `x ≤ 0`. It is a basic building block to construct smooth partitions of unity. Its main property is that it vanishes for `x ≤ 0`, it is positive for `x > 0`, and the junction between the two behaviors is flat enough to retain smoothness. The fact that this function is `C^∞` is proved in `exp_neg_inv_glue.smooth`. -/ def exp_neg_inv_glue (x : ℝ) : ℝ := if x ≤ 0 then 0 else exp (-x⁻¹) namespace exp_neg_inv_glue /-- Our goal is to prove that `exp_neg_inv_glue` is `C^∞`. For this, we compute its successive derivatives for `x > 0`. The `n`-th derivative is of the form `P_aux n (x) exp(-1/x) / x^(2 n)`, where `P_aux n` is computed inductively. -/ noncomputable def P_aux : ℕ → ℝ[X] | 0 := 1 | (n+1) := X^2 * (P_aux n).derivative + (1 - C ↑(2 * n) * X) * (P_aux n) /-- Formula for the `n`-th derivative of `exp_neg_inv_glue`, as an auxiliary function `f_aux`. -/ def f_aux (n : ℕ) (x : ℝ) : ℝ := if x ≤ 0 then 0 else (P_aux n).eval x * exp (-x⁻¹) / x^(2 * n) /-- The `0`-th auxiliary function `f_aux 0` coincides with `exp_neg_inv_glue`, by definition. -/ lemma f_aux_zero_eq : f_aux 0 = exp_neg_inv_glue := begin ext x, by_cases h : x ≤ 0, { simp [exp_neg_inv_glue, f_aux, h] }, { simp [h, exp_neg_inv_glue, f_aux, ne_of_gt (not_le.1 h), P_aux] } end /-- For positive values, the derivative of the `n`-th auxiliary function `f_aux n` (given in this statement in unfolded form) is the `n+1`-th auxiliary function, since the polynomial `P_aux (n+1)` was chosen precisely to ensure this. -/ lemma f_aux_deriv (n : ℕ) (x : ℝ) (hx : x ≠ 0) : has_deriv_at (λx, (P_aux n).eval x * exp (-x⁻¹) / x^(2 * n)) ((P_aux (n+1)).eval x * exp (-x⁻¹) / x^(2 * (n + 1))) x := begin simp only [P_aux, eval_add, eval_sub, eval_mul, eval_pow, eval_X, eval_C, eval_one], convert (((P_aux n).has_deriv_at x).mul (((has_deriv_at_exp _).comp x (has_deriv_at_inv hx).neg))).div (has_deriv_at_pow (2 * n) x) (pow_ne_zero _ hx) using 1, rw div_eq_div_iff, { have := pow_ne_zero 2 hx, field_simp only, cases n, { simp only [mul_zero, nat.cast_zero, mul_one], ring }, { rw (id rfl : 2 * n.succ - 1 = 2 * n + 1), ring_exp } }, all_goals { apply_rules [pow_ne_zero] }, end /-- For positive values, the derivative of the `n`-th auxiliary function `f_aux n` is the `n+1`-th auxiliary function. -/ lemma f_aux_deriv_pos (n : ℕ) (x : ℝ) (hx : 0 < x) : has_deriv_at (f_aux n) ((P_aux (n+1)).eval x * exp (-x⁻¹) / x^(2 * (n + 1))) x := begin apply (f_aux_deriv n x (ne_of_gt hx)).congr_of_eventually_eq, filter_upwards [lt_mem_nhds hx] with _ hy, simp [f_aux, hy.not_le] end /-- To get differentiability at `0` of the auxiliary functions, we need to know that their limit is `0`, to be able to apply general differentiability extension theorems. This limit is checked in this lemma. -/ lemma f_aux_limit (n : ℕ) : tendsto (λx, (P_aux n).eval x * exp (-x⁻¹) / x^(2 * n)) (𝓝[>] 0) (𝓝 0) := begin have A : tendsto (λx, (P_aux n).eval x) (𝓝[>] 0) (𝓝 ((P_aux n).eval 0)) := (P_aux n).continuous_within_at, have B : tendsto (λx, exp (-x⁻¹) / x^(2 * n)) (𝓝[>] 0) (𝓝 0), { convert (tendsto_pow_mul_exp_neg_at_top_nhds_0 (2 * n)).comp tendsto_inv_zero_at_top, ext x, field_simp }, convert A.mul B; simp [mul_div_assoc] end /-- Deduce from the limiting behavior at `0` of its derivative and general differentiability extension theorems that the auxiliary function `f_aux n` is differentiable at `0`, with derivative `0`. -/ lemma f_aux_deriv_zero (n : ℕ) : has_deriv_at (f_aux n) 0 0 := begin -- we check separately differentiability on the left and on the right have A : has_deriv_within_at (f_aux n) (0 : ℝ) (Iic 0) 0, { apply (has_deriv_at_const (0 : ℝ) (0 : ℝ)).has_deriv_within_at.congr, { assume y hy, simp at hy, simp [f_aux, hy] }, { simp [f_aux, le_refl] } }, have B : has_deriv_within_at (f_aux n) (0 : ℝ) (Ici 0) 0, { have diff : differentiable_on ℝ (f_aux n) (Ioi 0) := λx hx, (f_aux_deriv_pos n x hx).differentiable_at.differentiable_within_at, -- next line is the nontrivial bit of this proof, appealing to differentiability -- extension results. apply has_deriv_at_interval_left_endpoint_of_tendsto_deriv diff _ self_mem_nhds_within, { refine (f_aux_limit (n+1)).congr' _, apply mem_of_superset self_mem_nhds_within (λx hx, _), simp [(f_aux_deriv_pos n x hx).deriv] }, { have : f_aux n 0 = 0, by simp [f_aux, le_refl], simp only [continuous_within_at, this], refine (f_aux_limit n).congr' _, apply mem_of_superset self_mem_nhds_within (λx hx, _), have : ¬(x ≤ 0), by simpa using hx, simp [f_aux, this] } }, simpa using A.union B, end /-- At every point, the auxiliary function `f_aux n` has a derivative which is equal to `f_aux (n+1)`. -/ lemma f_aux_has_deriv_at (n : ℕ) (x : ℝ) : has_deriv_at (f_aux n) (f_aux (n+1) x) x := begin -- check separately the result for `x < 0`, where it is trivial, for `x > 0`, where it is done -- in `f_aux_deriv_pos`, and for `x = 0`, done in -- `f_aux_deriv_zero`. rcases lt_trichotomy x 0 with hx|hx|hx, { have : f_aux (n+1) x = 0, by simp [f_aux, le_of_lt hx], rw this, apply (has_deriv_at_const x (0 : ℝ)).congr_of_eventually_eq, filter_upwards [gt_mem_nhds hx] with _ hy, simp [f_aux, hy.le] }, { have : f_aux (n + 1) 0 = 0, by simp [f_aux, le_refl], rw [hx, this], exact f_aux_deriv_zero n }, { have : f_aux (n+1) x = (P_aux (n+1)).eval x * exp (-x⁻¹) / x^(2 * (n+1)), by simp [f_aux, not_le_of_gt hx], rw this, exact f_aux_deriv_pos n x hx }, end /-- The successive derivatives of the auxiliary function `f_aux 0` are the functions `f_aux n`, by induction. -/ lemma f_aux_iterated_deriv (n : ℕ) : iterated_deriv n (f_aux 0) = f_aux n := begin induction n with n IH, { simp }, { simp [iterated_deriv_succ, IH], ext x, exact (f_aux_has_deriv_at n x).deriv } end /-- The function `exp_neg_inv_glue` is smooth. -/ protected theorem cont_diff {n} : cont_diff ℝ n exp_neg_inv_glue := begin rw ← f_aux_zero_eq, apply cont_diff_of_differentiable_iterated_deriv (λ m hm, _), rw f_aux_iterated_deriv m, exact λ x, (f_aux_has_deriv_at m x).differentiable_at end /-- The function `exp_neg_inv_glue` vanishes on `(-∞, 0]`. -/ lemma zero_of_nonpos {x : ℝ} (hx : x ≤ 0) : exp_neg_inv_glue x = 0 := by simp [exp_neg_inv_glue, hx] /-- The function `exp_neg_inv_glue` is positive on `(0, +∞)`. -/ lemma pos_of_pos {x : ℝ} (hx : 0 < x) : 0 < exp_neg_inv_glue x := by simp [exp_neg_inv_glue, not_le.2 hx, exp_pos] /-- The function exp_neg_inv_glue` is nonnegative. -/ lemma nonneg (x : ℝ) : 0 ≤ exp_neg_inv_glue x := begin cases le_or_gt x 0, { exact ge_of_eq (zero_of_nonpos h) }, { exact le_of_lt (pos_of_pos h) } end end exp_neg_inv_glue /-- An infinitely smooth function `f : ℝ → ℝ` such that `f x = 0` for `x ≤ 0`, `f x = 1` for `1 ≤ x`, and `0 < f x < 1` for `0 < x < 1`. -/ def real.smooth_transition (x : ℝ) : ℝ := exp_neg_inv_glue x / (exp_neg_inv_glue x + exp_neg_inv_glue (1 - x)) namespace real namespace smooth_transition variables {x : ℝ} open exp_neg_inv_glue lemma pos_denom (x) : 0 < exp_neg_inv_glue x + exp_neg_inv_glue (1 - x) := (zero_lt_one.lt_or_lt x).elim (λ hx, add_pos_of_pos_of_nonneg (pos_of_pos hx) (nonneg _)) (λ hx, add_pos_of_nonneg_of_pos (nonneg _) (pos_of_pos $ sub_pos.2 hx)) lemma one_of_one_le (h : 1 ≤ x) : smooth_transition x = 1 := (div_eq_one_iff_eq $ (pos_denom x).ne').2 $ by rw [zero_of_nonpos (sub_nonpos.2 h), add_zero] lemma zero_of_nonpos (h : x ≤ 0) : smooth_transition x = 0 := by rw [smooth_transition, zero_of_nonpos h, zero_div] @[simp] protected lemma zero : smooth_transition 0 = 0 := zero_of_nonpos le_rfl @[simp] protected lemma one : smooth_transition 1 = 1 := one_of_one_le le_rfl lemma le_one (x : ℝ) : smooth_transition x ≤ 1 := (div_le_one (pos_denom x)).2 $ le_add_of_nonneg_right (nonneg _) lemma nonneg (x : ℝ) : 0 ≤ smooth_transition x := div_nonneg (exp_neg_inv_glue.nonneg _) (pos_denom x).le lemma lt_one_of_lt_one (h : x < 1) : smooth_transition x < 1 := (div_lt_one $ pos_denom x).2 $ lt_add_of_pos_right _ $ pos_of_pos $ sub_pos.2 h lemma pos_of_pos (h : 0 < x) : 0 < smooth_transition x := div_pos (exp_neg_inv_glue.pos_of_pos h) (pos_denom x) protected lemma cont_diff {n} : cont_diff ℝ n smooth_transition := exp_neg_inv_glue.cont_diff.div (exp_neg_inv_glue.cont_diff.add $ exp_neg_inv_glue.cont_diff.comp $ cont_diff_const.sub cont_diff_id) $ λ x, (pos_denom x).ne' protected lemma cont_diff_at {x n} : cont_diff_at ℝ n smooth_transition x := smooth_transition.cont_diff.cont_diff_at protected lemma continuous : continuous smooth_transition := (@smooth_transition.cont_diff 0).continuous end smooth_transition end real variables {E X : Type*} /-- `f : cont_diff_bump c`, where `c` is a point in a normed vector space, is a bundled smooth function such that - `f` is equal to `1` in `metric.closed_ball c f.r`; - `support f = metric.ball c f.R`; - `0 ≤ f x ≤ 1` for all `x`. The structure `cont_diff_bump` contains the data required to construct the function: real numbers `r`, `R`, and proofs of `0 < r < R`. The function itself is available through `coe_fn` when the space is nice enough, i.e., satisfies the `has_cont_diff_bump` typeclass. -/ structure cont_diff_bump (c : E) := (r R : ℝ) (r_pos : 0 < r) (r_lt_R : r < R) /-- The base function from which one will construct a family of bump functions. One could add more properties if they are useful and satisfied in the examples of inner product spaces and finite dimensional vector spaces, notably derivative norm control in terms of `R - 1`. -/ @[nolint has_nonempty_instance] structure cont_diff_bump_base (E : Type*) [normed_add_comm_group E] [normed_space ℝ E] := (to_fun : ℝ → E → ℝ) (mem_Icc : ∀ (R : ℝ) (x : E), to_fun R x ∈ Icc (0 : ℝ) 1) (symmetric : ∀ (R : ℝ) (x : E), to_fun R (-x) = to_fun R x) (smooth : cont_diff_on ℝ ⊤ (uncurry to_fun) ((Ioi (1 : ℝ)) ×ˢ (univ : set E))) (eq_one : ∀ (R : ℝ) (hR : 1 < R) (x : E) (hx : ‖x‖ ≤ 1), to_fun R x = 1) (support : ∀ (R : ℝ) (hR : 1 < R), support (to_fun R) = metric.ball (0 : E) R) /-- A class registering that a real vector space admits bump functions. This will be instantiated first for inner product spaces, and then for finite-dimensional normed spaces. We use a specific class instead of `nonempty (cont_diff_bump_base E)` for performance reasons. -/ class has_cont_diff_bump (E : Type*) [normed_add_comm_group E] [normed_space ℝ E] : Prop := (out : nonempty (cont_diff_bump_base E)) /-- In a space with `C^∞` bump functions, register some function that will be used as a basis to construct bump functions of arbitrary size around any point. -/ def some_cont_diff_bump_base (E : Type*) [normed_add_comm_group E] [normed_space ℝ E] [hb : has_cont_diff_bump E] : cont_diff_bump_base E := nonempty.some hb.out /-- Any inner product space has smooth bump functions. -/ @[priority 100] instance has_cont_diff_bump_of_inner_product_space (E : Type*) [normed_add_comm_group E] [inner_product_space ℝ E] : has_cont_diff_bump E := let e : cont_diff_bump_base E := { to_fun := λ R x, real.smooth_transition ((R - ‖x‖) / (R - 1)), mem_Icc := λ R x, ⟨real.smooth_transition.nonneg _, real.smooth_transition.le_one _⟩, symmetric := λ R x, by simp only [norm_neg], smooth := begin rintros ⟨R, x⟩ ⟨(hR : 1 < R), hx⟩, apply cont_diff_at.cont_diff_within_at, rcases eq_or_ne x 0 with rfl|hx, { have : (λ (p : ℝ × E), real.smooth_transition ((p.1 - ‖p.2‖) / (p.1 - 1))) =ᶠ[𝓝 (R, 0)] (λ p, 1), { have A : tendsto (λ (p : ℝ × E), (p.1 - ‖p.2‖) / (p.1 - 1)) (𝓝 (R, 0)) (𝓝 ((R - ‖(0 : E)‖) / (R - 1))), { rw nhds_prod_eq, apply (tendsto_fst.sub tendsto_snd.norm).div (tendsto_fst.sub tendsto_const_nhds), exact (sub_pos.2 hR).ne' }, have : ∀ᶠ (p : ℝ × E) in 𝓝 (R, 0), 1 < (p.1 - ‖p.2‖) / (p.1 - 1), { apply (tendsto_order.1 A).1, apply (one_lt_div (sub_pos.2 hR)).2, simp only [norm_zero, tsub_zero, sub_lt_self_iff, zero_lt_one] }, filter_upwards [this] with q hq, exact real.smooth_transition.one_of_one_le hq.le }, exact cont_diff_at_const.congr_of_eventually_eq this }, { refine real.smooth_transition.cont_diff_at.comp _ _, refine cont_diff_at.div _ _ (sub_pos.2 hR).ne', { exact cont_diff_at_fst.sub (cont_diff_at_snd.norm ℝ hx) }, { exact cont_diff_at_fst.sub cont_diff_at_const } } end, eq_one := λ R hR x hx, real.smooth_transition.one_of_one_le $ (one_le_div (sub_pos.2 hR)).2 (sub_le_sub_left hx _), support := λ R hR, begin apply subset.antisymm, { assume x hx, simp only [mem_support] at hx, contrapose! hx, simp only [mem_ball_zero_iff, not_lt] at hx, apply real.smooth_transition.zero_of_nonpos, apply div_nonpos_of_nonpos_of_nonneg; linarith }, { assume x hx, simp only [mem_ball_zero_iff] at hx, apply (real.smooth_transition.pos_of_pos _).ne', apply div_pos; linarith } end, } in ⟨⟨e⟩⟩ namespace cont_diff_bump lemma R_pos {c : E} (f : cont_diff_bump c) : 0 < f.R := f.r_pos.trans f.r_lt_R lemma one_lt_R_div_r {c : E} (f : cont_diff_bump c) : 1 < f.R / f.r := begin rw one_lt_div f.r_pos, exact f.r_lt_R end instance (c : E) : inhabited (cont_diff_bump c) := ⟨⟨1, 2, zero_lt_one, one_lt_two⟩⟩ variables [normed_add_comm_group E] [normed_space ℝ E] [normed_add_comm_group X] [normed_space ℝ X] [has_cont_diff_bump E] {c : E} (f : cont_diff_bump c) {x : E} {n : ℕ∞} /-- The function defined by `f : cont_diff_bump c`. Use automatic coercion to function instead. -/ def to_fun {c : E} (f : cont_diff_bump c) : E → ℝ := λ x, (some_cont_diff_bump_base E).to_fun (f.R / f.r) (f.r⁻¹ • (x - c)) instance : has_coe_to_fun (cont_diff_bump c) (λ _, E → ℝ) := ⟨to_fun⟩ protected lemma «def» (x : E) : f x = (some_cont_diff_bump_base E).to_fun (f.R / f.r) (f.r⁻¹ • (x - c)) := rfl protected lemma sub (x : E) : f (c - x) = f (c + x) := by simp [f.def, cont_diff_bump_base.symmetric] protected lemma neg (f : cont_diff_bump (0 : E)) (x : E) : f (- x) = f x := by simp_rw [← zero_sub, f.sub, zero_add] open metric lemma one_of_mem_closed_ball (hx : x ∈ closed_ball c f.r) : f x = 1 := begin apply cont_diff_bump_base.eq_one _ _ f.one_lt_R_div_r, simpa only [norm_smul, norm_eq_abs, abs_inv, abs_of_nonneg f.r_pos.le, ← div_eq_inv_mul, div_le_one f.r_pos] using mem_closed_ball_iff_norm.1 hx end lemma nonneg : 0 ≤ f x := (cont_diff_bump_base.mem_Icc ((some_cont_diff_bump_base E)) _ _).1 /-- A version of `cont_diff_bump.nonneg` with `x` explicit -/ lemma nonneg' (x : E) : 0 ≤ f x := f.nonneg lemma le_one : f x ≤ 1 := (cont_diff_bump_base.mem_Icc ((some_cont_diff_bump_base E)) _ _).2 lemma pos_of_mem_ball (hx : x ∈ ball c f.R) : 0 < f x := begin refine lt_iff_le_and_ne.2 ⟨f.nonneg, ne.symm _⟩, change (f.r)⁻¹ • (x - c) ∈ support ((some_cont_diff_bump_base E).to_fun (f.R / f.r)), rw cont_diff_bump_base.support _ _ f.one_lt_R_div_r, simp only [dist_eq_norm, mem_ball] at hx, simpa only [norm_smul, mem_ball_zero_iff, norm_eq_abs, abs_inv, abs_of_nonneg f.r_pos.le, ← div_eq_inv_mul] using (div_lt_div_right f.r_pos).2 hx, end lemma zero_of_le_dist (hx : f.R ≤ dist x c) : f x = 0 := begin rw dist_eq_norm at hx, suffices H : (f.r)⁻¹ • (x - c) ∉ support ((some_cont_diff_bump_base E).to_fun (f.R / f.r)), by simpa only [mem_support, not_not] using H, rw cont_diff_bump_base.support _ _ f.one_lt_R_div_r, simp [norm_smul, norm_eq_abs, abs_inv, abs_of_nonneg f.r_pos.le, ← div_eq_inv_mul], exact div_le_div_of_le f.r_pos.le hx, end lemma support_eq : support (f : E → ℝ) = metric.ball c f.R := begin ext x, suffices : f x ≠ 0 ↔ dist x c < f.R, by simpa [mem_support], cases lt_or_le (dist x c) f.R with hx hx, { simp only [hx, (f.pos_of_mem_ball hx).ne', ne.def, not_false_iff]}, { simp only [hx.not_lt, f.zero_of_le_dist hx, ne.def, eq_self_iff_true, not_true] } end lemma tsupport_eq : tsupport f = closed_ball c f.R := by simp_rw [tsupport, f.support_eq, closure_ball _ f.R_pos.ne'] protected lemma has_compact_support [finite_dimensional ℝ E] : has_compact_support f := by simp_rw [has_compact_support, f.tsupport_eq, is_compact_closed_ball] lemma eventually_eq_one_of_mem_ball (h : x ∈ ball c f.r) : f =ᶠ[𝓝 x] 1 := ((is_open_lt (continuous_id.dist continuous_const) continuous_const).eventually_mem h).mono $ λ z hz, f.one_of_mem_closed_ball (le_of_lt hz) lemma eventually_eq_one : f =ᶠ[𝓝 c] 1 := f.eventually_eq_one_of_mem_ball (mem_ball_self f.r_pos) /-- `cont_diff_bump` is `𝒞ⁿ` in all its arguments. -/ protected lemma _root_.cont_diff_at.cont_diff_bump {c g : X → E} {f : ∀ x, cont_diff_bump (c x)} {x : X} (hc : cont_diff_at ℝ n c x) (hr : cont_diff_at ℝ n (λ x, (f x).r) x) (hR : cont_diff_at ℝ n (λ x, (f x).R) x) (hg : cont_diff_at ℝ n g x) : cont_diff_at ℝ n (λ x, f x (g x)) x := begin rcases eq_or_ne (g x) (c x) with hx|hx, { have : (λ x, f x (g x)) =ᶠ[𝓝 x] (λ x, 1), { have : dist (g x) (c x) < (f x).r, { simp_rw [hx, dist_self, (f x).r_pos] }, have := continuous_at.eventually_lt (hg.continuous_at.dist hc.continuous_at) hr.continuous_at this, exact eventually_of_mem this (λ x hx, (f x).one_of_mem_closed_ball (mem_set_of_eq.mp hx).le) }, exact cont_diff_at_const.congr_of_eventually_eq this }, { change cont_diff_at ℝ n ((uncurry (some_cont_diff_bump_base E).to_fun) ∘ (λ (x : X), ((f x).R / (f x).r, ((f x).r)⁻¹ • (g x - c x)))) x, have A : ((f x).R / (f x).r, ((f x).r)⁻¹ • (g x - c x)) ∈ Ioi (1 : ℝ) ×ˢ (univ : set E), by simpa only [prod_mk_mem_set_prod_eq, mem_univ, and_true] using (f x).one_lt_R_div_r, have B : Ioi (1 : ℝ) ×ˢ (univ : set E) ∈ 𝓝 ((f x).R / (f x).r, (f x).r⁻¹ • (g x - c x)), from (is_open_Ioi.prod is_open_univ).mem_nhds A, apply ((((some_cont_diff_bump_base E).smooth.cont_diff_within_at A).cont_diff_at B) .of_le le_top).comp x _, exact (hR.div hr (f x).r_pos.ne').prod ((hr.inv (f x).r_pos.ne').smul (hg.sub hc)) } end lemma _root_.cont_diff.cont_diff_bump {c g : X → E} {f : ∀ x, cont_diff_bump (c x)} (hc : cont_diff ℝ n c) (hr : cont_diff ℝ n (λ x, (f x).r)) (hR : cont_diff ℝ n (λ x, (f x).R)) (hg : cont_diff ℝ n g) : cont_diff ℝ n (λ x, f x (g x)) := by { rw [cont_diff_iff_cont_diff_at] at *, exact λ x, (hc x).cont_diff_bump (hr x) (hR x) (hg x) } protected lemma cont_diff : cont_diff ℝ n f := cont_diff_const.cont_diff_bump cont_diff_const cont_diff_const cont_diff_id protected lemma cont_diff_at : cont_diff_at ℝ n f x := f.cont_diff.cont_diff_at protected lemma cont_diff_within_at {s : set E} : cont_diff_within_at ℝ n f s x := f.cont_diff_at.cont_diff_within_at protected lemma continuous : continuous f := cont_diff_zero.mp f.cont_diff open measure_theory variables [measurable_space E] {μ : measure E} /-- A bump function normed so that `∫ x, f.normed μ x ∂μ = 1`. -/ protected def normed (μ : measure E) : E → ℝ := λ x, f x / ∫ x, f x ∂μ lemma normed_def {μ : measure E} (x : E) : f.normed μ x = f x / ∫ x, f x ∂μ := rfl lemma nonneg_normed (x : E) : 0 ≤ f.normed μ x := div_nonneg f.nonneg $ integral_nonneg f.nonneg' lemma cont_diff_normed {n : ℕ∞} : cont_diff ℝ n (f.normed μ) := f.cont_diff.div_const _ lemma continuous_normed : continuous (f.normed μ) := f.continuous.div_const _ lemma normed_sub (x : E) : f.normed μ (c - x) = f.normed μ (c + x) := by simp_rw [f.normed_def, f.sub] lemma normed_neg (f : cont_diff_bump (0 : E)) (x : E) : f.normed μ (- x) = f.normed μ x := by simp_rw [f.normed_def, f.neg] variables [borel_space E] [finite_dimensional ℝ E] [is_locally_finite_measure μ] protected lemma integrable : integrable f μ := f.continuous.integrable_of_has_compact_support f.has_compact_support protected lemma integrable_normed : integrable (f.normed μ) μ := f.integrable.div_const _ variables [μ .is_open_pos_measure] lemma integral_pos : 0 < ∫ x, f x ∂μ := begin refine (integral_pos_iff_support_of_nonneg f.nonneg' f.integrable).mpr _, rw [f.support_eq], refine is_open_ball.measure_pos _ (nonempty_ball.mpr f.R_pos) end lemma integral_normed : ∫ x, f.normed μ x ∂μ = 1 := begin simp_rw [cont_diff_bump.normed, div_eq_mul_inv, mul_comm (f _), ← smul_eq_mul, integral_smul], exact inv_mul_cancel (f.integral_pos.ne') end lemma support_normed_eq : support (f.normed μ) = metric.ball c f.R := by simp_rw [cont_diff_bump.normed, support_div, f.support_eq, support_const f.integral_pos.ne', inter_univ] lemma tsupport_normed_eq : tsupport (f.normed μ) = metric.closed_ball c f.R := by simp_rw [tsupport, f.support_normed_eq, closure_ball _ f.R_pos.ne'] lemma has_compact_support_normed : has_compact_support (f.normed μ) := by simp_rw [has_compact_support, f.tsupport_normed_eq, is_compact_closed_ball] lemma tendsto_support_normed_small_sets {ι} {φ : ι → cont_diff_bump c} {l : filter ι} (hφ : tendsto (λ i, (φ i).R) l (𝓝 0)) : tendsto (λ i, support (λ x, (φ i).normed μ x)) l (𝓝 c).small_sets := begin simp_rw [normed_add_comm_group.tendsto_nhds_zero, real.norm_eq_abs, abs_eq_self.mpr (φ _).R_pos.le] at hφ, rw [tendsto_small_sets_iff], intros t ht, rcases metric.mem_nhds_iff.mp ht with ⟨ε, hε, ht⟩, refine (hφ ε hε).mono (λ i hi, subset_trans _ ht), simp_rw [(φ i).support_normed_eq], exact ball_subset_ball hi.le end variable (μ) lemma integral_normed_smul [complete_space X] (z : X) : ∫ x, f.normed μ x • z ∂μ = z := by simp_rw [integral_smul_const, f.integral_normed, one_smul] end cont_diff_bump
7162c7b12f692ab6e702c381839bdcbc6afa6bf6
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/tactic/interval_cases.lean
47b3a1811d6a128318bc2580d5b293bad153fcda
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,033
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import data.fin.interval import data.int.interval import data.pnat.interval import tactic.fin_cases /-! # Case bash on variables in finite intervals This file provides the tactic `interval_cases`. `interval_cases n` will: 1. inspect hypotheses looking for lower and upper bounds of the form `a ≤ n` and `n < b` (in `ℕ`, `ℤ`, `ℕ+`, bounds of the form `a < n` and `n ≤ b` are also allowed), and also makes use of lower and upper bounds found via `le_top` and `bot_le` (so for example if `n : ℕ`, then the bound `0 ≤ n` is automatically found). 2. call `fin_cases` on the synthesised hypothesis `n ∈ set.Ico a b`, assuming an appropriate `fintype` instance can be found for the type of `n`. The variable `n` can belong to any type `α`, with the following restrictions: * only bounds on which `expr.to_rat` succeeds will be considered "explicit" (TODO: generalise this?) * an instance of `decidable_eq α` is available, * an explicit lower bound can be found among the hypotheses, or from `bot_le n`, * an explicit upper bound can be found among the hypotheses, or from `le_top n`, * if multiple bounds are located, an instance of `linear_order α` is available, and * an instance of `fintype set.Ico l u` is available for the relevant bounds. You can also explicitly specify a lower and upper bound to use, as `interval_cases using hl hu`, where the hypotheses should be of the form `hl : a ≤ n` and `hu : n < b`. In that case, `interval_cases` calls `fin_cases` on the resulting hypothesis `h : n ∈ set.Ico a b`. -/ open set namespace tactic namespace interval_cases /-- If `e` easily implies `(%%n < %%b)` for some explicit `b`, return that proof. -/ -- We use `expr.to_rat` merely to decide if an `expr` is an explicit number. -- It would be more natural to use `expr.to_int`, but that hasn't been implemented. meta def gives_upper_bound (n e : expr) : tactic expr := do t ← infer_type e, match t with | `(%%n' < %%b) := do guard (n = n'), b ← b.to_rat, return e | `(%%b > %%n') := do guard (n = n'), b ← b.to_rat, return e | `(%%n' ≤ %%b) := do guard (n = n'), b ← b.to_rat, tn ← infer_type n, match tn with | `(ℕ) := to_expr ``(nat.lt_add_one_iff.mpr %%e) | `(ℕ+) := to_expr ``(pnat.lt_add_one_iff.mpr %%e) | `(ℤ) := to_expr ``(int.lt_add_one_iff.mpr %%e) | _ := failed end | `(%%b ≥ %%n') := do guard (n = n'), b ← b.to_rat, tn ← infer_type n, match tn with | `(ℕ) := to_expr ``(nat.lt_add_one_iff.mpr %%e) | `(ℕ+) := to_expr ``(pnat.lt_add_one_iff.mpr %%e) | `(ℤ) := to_expr ``(int.lt_add_one_iff.mpr %%e) | _ := failed end | _ := failed end /-- If `e` easily implies `(%%n ≥ %%b)` for some explicit `b`, return that proof. -/ meta def gives_lower_bound (n e : expr) : tactic expr := do t ← infer_type e, match t with | `(%%n' ≥ %%b) := do guard (n = n'), b ← b.to_rat, return e | `(%%b ≤ %%n') := do guard (n = n'), b ← b.to_rat, return e | `(%%n' > %%b) := do guard (n = n'), b ← b.to_rat, tn ← infer_type n, match tn with | `(ℕ) := to_expr ``(nat.add_one_le_iff.mpr %%e) | `(ℕ+) := to_expr ``(pnat.add_one_le_iff.mpr %%e) | `(ℤ) := to_expr ``(int.add_one_le_iff.mpr %%e) | _ := failed end | `(%%b < %%n') := do guard (n = n'), b ← b.to_rat, tn ← infer_type n, match tn with | `(ℕ) := to_expr ``(nat.add_one_le_iff.mpr %%e) | `(ℕ+) := to_expr ``(pnat.add_one_le_iff.mpr %%e) | `(ℤ) := to_expr ``(int.add_one_le_iff.mpr %%e) | _ := failed end | _ := failed end /-- Combine two upper bounds. -/ meta def combine_upper_bounds : option expr → option expr → tactic (option expr) | none none := return none | (some prf) none := return $ some prf | none (some prf) := return $ some prf | (some prf₁) (some prf₂) := do option.some <$> to_expr ``(lt_min %%prf₁ %%prf₂) /-- Combine two lower bounds. -/ meta def combine_lower_bounds : option expr → option expr → tactic (option expr) | none none := return $ none | (some prf) none := return $ some prf | none (some prf) := return $ some prf | (some prf₁) (some prf₂) := do option.some <$> to_expr ``(max_le %%prf₂ %%prf₁) /-- Inspect a given expression, using it to update a set of upper and lower bounds on `n`. -/ meta def update_bounds (n : expr) (bounds : option expr × option expr) (e : expr) : tactic (option expr × option expr) := do nlb ← try_core $ gives_lower_bound n e, nub ← try_core $ gives_upper_bound n e, clb ← combine_lower_bounds bounds.1 nlb, cub ← combine_upper_bounds bounds.2 nub, return (clb, cub) /-- Attempt to find a lower bound for the variable `n`, by evaluating `bot_le n`. -/ meta def initial_lower_bound (n : expr) : tactic expr := do e ← to_expr ``(@bot_le _ _ %%n), t ← infer_type e, match t with | `(%%b ≤ %%n) := do return e | _ := failed end /-- Attempt to find an upper bound for the variable `n`, by evaluating `le_top n`. -/ meta def initial_upper_bound (n : expr) : tactic expr := do e ← to_expr ``(@le_top _ _ %%n), match e with | `(%%n ≤ %%b) := do tn ← infer_type n, e ← match tn with | `(ℕ) := to_expr ``(nat.add_one_le_iff.mpr %%e) | `(ℕ+) := to_expr ``(pnat.add_one_le_iff.mpr %%e) | `(ℤ) := to_expr ``(int.add_one_le_iff.mpr %%e) | _ := failed end, return e | _ := failed end /-- Inspect the local hypotheses for upper and lower bounds on a variable `n`. -/ meta def get_bounds (n : expr) : tactic (expr × expr) := do hl ← try_core (initial_lower_bound n), hu ← try_core (initial_upper_bound n), lc ← local_context, r ← lc.mfoldl (update_bounds n) (hl, hu), match r with | (_, none) := fail "No upper bound located." | (none, _) := fail "No lower bound located." | (some lb_prf, some ub_prf) := return (lb_prf, ub_prf) end /-- The finset of elements of a set `s` for which we have `fintype s`. -/ def set_elems {α} [decidable_eq α] (s : set α) [fintype s] : finset α := (fintype.elems s).image subtype.val /-- Each element of `s` is a member of `set_elems s`. -/ lemma mem_set_elems {α} [decidable_eq α] (s : set α) [fintype s] {a : α} (h : a ∈ s) : a ∈ set_elems s := finset.mem_image.2 ⟨⟨a, h⟩, fintype.complete _, rfl⟩ end interval_cases open interval_cases /-- Call `fin_cases` on membership of the finset built from an `Ico` interval corresponding to a lower and an upper bound. Here `hl` should be an expression of the form `a ≤ n`, for some explicit `a`, and `hu` should be of the form `n < b`, for some explicit `b`. By default `interval_cases_using` automatically generates a name for the new hypothesis. The name can be specified via the optional argument `n`. -/ meta def interval_cases_using (hl hu : expr) (n : option name) : tactic unit := to_expr ``(mem_set_elems (Ico _ _) ⟨%%hl, %%hu⟩) >>= (if hn : n.is_some then note (option.get hn) else note_anon none) >>= fin_cases_at none setup_tactic_parser namespace interactive local postfix `?`:9001 := optional /-- `interval_cases n` searches for upper and lower bounds on a variable `n`, and if bounds are found, splits into separate cases for each possible value of `n`. As an example, in ``` example (n : ℕ) (w₁ : n ≥ 3) (w₂ : n < 5) : n = 3 ∨ n = 4 := begin interval_cases n, all_goals {simp} end ``` after `interval_cases n`, the goals are `3 = 3 ∨ 3 = 4` and `4 = 3 ∨ 4 = 4`. You can also explicitly specify a lower and upper bound to use, as `interval_cases using hl hu`. The hypotheses should be in the form `hl : a ≤ n` and `hu : n < b`, in which case `interval_cases` calls `fin_cases` on the resulting fact `n ∈ set.Ico a b`. You can specify a name `h` for the new hypothesis, as `interval_cases n with h` or `interval_cases n using hl hu with h`. -/ meta def interval_cases (n : parse texpr?) (bounds : parse (tk "using" *> (prod.mk <$> ident <*> ident))?) (lname : parse (tk "with" *> ident)?) : tactic unit := do if h : n.is_some then (do guard bounds.is_none <|> fail "Do not use the `using` keyword if specifying the variable explicitly.", n ← to_expr (option.get h), (hl, hu) ← get_bounds n, tactic.interval_cases_using hl hu lname) else if h' : bounds.is_some then (do [hl, hu] ← [(option.get h').1, (option.get h').2].mmap get_local, tactic.interval_cases_using hl hu lname) else fail ("Call `interval_cases n` (specifying a variable), or `interval_cases lb ub`\n" ++ "(specifying a lower bound and upper bound on the same variable).") /-- `interval_cases n` searches for upper and lower bounds on a variable `n`, and if bounds are found, splits into separate cases for each possible value of `n`. As an example, in ``` example (n : ℕ) (w₁ : n ≥ 3) (w₂ : n < 5) : n = 3 ∨ n = 4 := begin interval_cases n, all_goals {simp} end ``` after `interval_cases n`, the goals are `3 = 3 ∨ 3 = 4` and `4 = 3 ∨ 4 = 4`. You can also explicitly specify a lower and upper bound to use, as `interval_cases using hl hu`. The hypotheses should be in the form `hl : a ≤ n` and `hu : n < b`, in which case `interval_cases` calls `fin_cases` on the resulting fact `n ∈ set.Ico a b`. You can also explicitly specify a name to use for the hypothesis added, as `interval_cases n with hn` or `interval_cases n using hl hu with hn`. In particular, `interval_cases n` 1) inspects hypotheses looking for lower and upper bounds of the form `a ≤ n` and `n < b` (although in `ℕ`, `ℤ`, and `ℕ+` bounds of the form `a < n` and `n ≤ b` are also allowed), and also makes use of lower and upper bounds found via `le_top` and `bot_le` (so for example if `n : ℕ`, then the bound `0 ≤ n` is found automatically), then 2) calls `fin_cases` on the synthesised hypothesis `n ∈ set.Ico a b`, assuming an appropriate `fintype` instance can be found for the type of `n`. The variable `n` can belong to any type `α`, with the following restrictions: * only bounds on which `expr.to_rat` succeeds will be considered "explicit" (TODO: generalise this?) * an instance of `decidable_eq α` is available, * an explicit lower bound can be found amongst the hypotheses, or from `bot_le n`, * an explicit upper bound can be found amongst the hypotheses, or from `le_top n`, * if multiple bounds are located, an instance of `linear_order α` is available, and * an instance of `fintype set.Ico l u` is available for the relevant bounds. -/ add_tactic_doc { name := "interval_cases", category := doc_category.tactic, decl_names := [`tactic.interactive.interval_cases], tags := ["case bashing"] } end interactive end tactic
ecfa0213bf86d257a6b7426676a5d31d9ee04f35
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/tactic/simps.lean
3a986891347ba85da8e0ff9c6cd67113fd86279d
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
8,642
lean
/- Copyright (c) 2019 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import tactic.core /-! # simps attribute This file defines the `@[simps]` attribute, to automatically generate simp-lemmas reducing a definition when projections are applied to it. ## Tags structures, projections, simp, simplifier, generates declarations -/ open tactic expr /-- Add a lemma with `nm` stating that `lhs = rhs`. `type` is the type of both `lhs` and `rhs`, `args` is the list of local constants occurring, and `univs` is the list of universe variables. If `add_simp` then we make the resulting lemma a simp-lemma. -/ meta def simps_add_projection (nm : name) (type lhs rhs : expr) (args : list expr) (univs : list name) (add_simp : bool) : tactic unit := do eq_ap ← mk_mapp `eq $ [type, lhs, rhs].map some, refl_ap ← mk_app `eq.refl [type, lhs], decl_name ← get_unused_decl_name nm, let decl_type := eq_ap.pis args, let decl_value := refl_ap.lambdas args, let decl := declaration.thm decl_name univs decl_type (pure decl_value), add_decl decl <|> fail format!"failed to add projection lemma {decl_name}.", when add_simp $ set_basic_attribute `simp decl_name tt >> set_basic_attribute `_refl_lemma decl_name tt /-- Derive lemmas specifying the projections of the declaration. If `todo` is non-empty, it will generate exactly the names in `todo`. -/ meta def simps_add_projections : ∀(e : environment) (nm : name) (suffix : string) (type lhs rhs : expr) (args : list expr) (univs : list name) (add_simp must_be_str short_nm : bool) (todo : list string), tactic unit | e nm suffix type lhs rhs args univs add_simp must_be_str short_nm todo := do (type_args, tgt) ← mk_local_pis_whnf type, tgt ← whnf tgt, let new_args := args ++ type_args, let lhs_ap := lhs.mk_app type_args, let rhs_ap := rhs.instantiate_lambdas_or_apps type_args, let str := tgt.get_app_fn.const_name, if e.is_structure str then do projs ← e.structure_fields_full str, [intro] ← return $ e.constructors_of str | fail "unreachable code (3)", let params := get_app_args tgt, -- the parameters of the structure if is_constant_of (get_app_fn rhs_ap) intro then do -- if the value is a constructor application guard ((get_app_args rhs_ap).take params.length = params) <|> fail "unreachable code (1)", let rhs_args := (get_app_args rhs_ap).drop params.length, -- the fields of the structure guard (rhs_args.length = projs.length) <|> fail "unreachable code (2)", let pairs := projs.zip rhs_args, eta ← expr.is_eta_expansion_aux rhs_ap pairs, -- check whether `rhs_ap` is an eta-expansion let rhs_ap := eta.lhoare rhs_ap, -- eta-reduce `rhs_ap` /- we want to generate the current projection if it is in `todo` or when `rhs_ap` was an eta-expansion -/ when ("" ∈ todo ∨ (todo = [] ∧ eta.is_some)) $ simps_add_projection (nm.append_suffix suffix) tgt lhs_ap rhs_ap new_args univs add_simp, -- if `rhs_ap` was an eta-expansion and `todo` is empty, we stop when ¬(todo = [""] ∨ (eta.is_some ∧ todo = [])) $ do /- remove "" from todo. This allows a to generate lemmas + nested version of them. This is not very useful, but this does improve error messages. -/ let todo := todo.filter $ (≠ ""), -- check whether all elements in `todo` have a projection as prefix guard (todo.all $ λ x, projs.any $ λ proj, ("_" ++ proj.last).is_prefix_of x) <|> let x := (todo.find $ λ x, projs.all $ λ proj, ¬ ("_" ++ proj.last).is_prefix_of x).iget, simp_lemma := nm.append_suffix $ suffix ++ x, needed_proj := (x.split_on '_').tail.head in fail format!"Invalid simp-lemma {simp_lemma}. Projection {needed_proj} doesn't exist.", pairs.mmap' $ λ ⟨proj, new_rhs⟩, do new_type ← infer_type new_rhs, let new_todo := todo.filter_map $ λ x, string.get_rest x $ "_" ++ proj.last, b ← is_prop new_type, -- we only continue with this field if it is non-propositional or mentioned in todo when ((¬ b ∧ todo = []) ∨ (todo ≠ [] ∧ new_todo ≠ [])) $ do -- cannot use `mk_app` here, since the resulting application might still be a function. new_lhs ← mk_mapp proj $ (params ++ [lhs_ap]).map some, let new_suffix := if short_nm then "_" ++ proj.last else suffix ++ "_" ++ proj.last, simps_add_projections e nm new_suffix new_type new_lhs new_rhs new_args univs add_simp ff short_nm new_todo else do when must_be_str $ fail "Invalid `simps` attribute. Body is not a constructor application", when (todo ≠ [] ∧ todo ≠ [""]) $ fail format!"Invalid simp-lemma {nm.append_suffix $ suffix ++ todo.head}. Too many projections given.", simps_add_projection (nm.append_suffix suffix) tgt lhs_ap rhs_ap new_args univs add_simp else do when must_be_str $ fail "Invalid `simps` attribute. Target is not a structure", when (todo ≠ [] ∧ todo ≠ [""]) $ fail format!"Invalid simp-lemma {nm.append_suffix $ suffix ++ todo.head}. Too many projections given.", simps_add_projection (nm.append_suffix suffix) tgt lhs_ap rhs_ap new_args univs add_simp /-- `simps_tac` derives simp-lemmas for all (nested) non-Prop projections of the declaration. If `todo` is non-empty, it will generate exactly the names in `todo`. If `short_nm` is true, the generated names will only use the last projection name. -/ meta def simps_tac (nm : name) (add_simp : bool) (short_nm : bool := ff) (todo : list string := []) : tactic unit := do e ← get_env, d ← e.get nm, let lhs : expr := const d.to_name (d.univ_params.map level.param), let todo := todo.erase_dup.map $ λ proj, "_" ++ proj, simps_add_projections e nm "" d.type lhs d.value [] d.univ_params add_simp tt short_nm todo reserve notation `lemmas_only` reserve notation `short_name` setup_tactic_parser /-- The parser for simps. Pattern: `'lemmas_only'? ident*` -/ meta def simps_parser : parser (bool × bool × list string) := /- note: we currently don't check whether the user has written a nonsense namespace as arguments. -/ prod.mk <$> (option.is_none <$> (tk "lemmas_only")?) <*> (prod.mk <$> (option.is_some <$> (tk "short_name")?) <*> many (name.last <$> ident)) /-- The `@[simps]` attribute automatically derives lemmas specifying the projections of this declaration. Example: (note that the forward and reverse functions are specified differently!) ```lean @[simps] def refl (α) : α ≃ α := ⟨id, λ x, x, λ x, rfl, λ x, rfl⟩ ``` derives two simp-lemmas: ```lean @[simp] lemma refl_to_fun (α) (x : α) : (refl α).to_fun x = id x @[simp] lemma refl_inv_fun (α) (x : α) : (refl α).inv_fun x = x ``` * It does not derive simp-lemmas for the prop-valued projections. * It will automatically reduce newly created beta-redexes, but not unfold any definitions. * If one of the fields itself is a structure, this command will recursively create simp-lemmas for all fields in that structure. * You can use `@[simps proj1 proj2 ...]` to only generate the projection lemmas for the specified projections. For example: ```lean attribute [simps to_fun] refl ``` * If one of the values is an eta-expanded structure, we will eta-reduce this structure. * You can use `@[simps lemmas_only]` to derive the lemmas, but not mark them as simp-lemmas. * You can use `@[simps short_name]` to only use the name of the last projection for the name of the generated lemmas. * The precise syntax is `('simps' 'lemmas_only'? 'short_name'? ident*)`. * If one of the projections is marked as a coercion, the generated lemmas do *not* use this coercion. * `@[simps]` reduces let-expressions where necessary. * If one of the fields is a partially applied constructor, we will eta-expand it (this likely never happens). -/ @[user_attribute] meta def simps_attr : user_attribute unit (bool × bool × list string) := { name := `simps, descr := "Automatically derive lemmas specifying the projections of this declaration.", parser := simps_parser, after_set := some $ λ n _ _, do (add_simp, short_nm, todo) ← simps_attr.get_param n, simps_tac n add_simp short_nm todo } add_tactic_doc { name := "simps", category := doc_category.attr, decl_names := [`simps_attr], tags := ["simplification"] }
aad3982384a8e4f11e54a10dff9c06e15594747e
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Server/Snapshots.lean
f49e5db56449274b68ec7cdd6a322cc8b45b80a0
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
6,896
lean
/- Copyright (c) 2020 Wojciech Nawrocki. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki -/ import Init.System.IO import Lean.Elab.Import import Lean.Elab.Command import Lean.Widget.InteractiveDiagnostic /-! One can think of this module as being a partial reimplementation of Lean.Elab.Frontend which also stores a snapshot of the world after each command. Importantly, we allow (re)starting compilation from any snapshot/position in the file for interactive editing purposes. -/ namespace Lean.Server.Snapshots open Elab /- For `Inhabited Snapshot` -/ builtin_initialize dummyTacticCache : IO.Ref Tactic.Cache ← IO.mkRef {} /-- What Lean knows about the world after the header and each command. -/ structure Snapshot where /-- Where the command which produced this snapshot begins. Note that neighbouring snapshots are *not* necessarily attached beginning-to-end, since inputs outside the grammar advance the parser but do not produce snapshots. -/ beginPos : String.Pos stx : Syntax mpState : Parser.ModuleParserState cmdState : Command.State /-- We cache interactive diagnostics in order not to invoke the pretty-printer again on messages from previous snapshots when publishing diagnostics for every new snapshot (this is quadratic), as well as not to invoke it once again when handling `$/lean/interactiveDiagnostics`. -/ interactiveDiags : PersistentArray Widget.InteractiveDiagnostic tacticCache : IO.Ref Tactic.Cache namespace Snapshot def endPos (s : Snapshot) : String.Pos := s.mpState.pos def env (s : Snapshot) : Environment := s.cmdState.env def msgLog (s : Snapshot) : MessageLog := s.cmdState.messages def diagnostics (s : Snapshot) : PersistentArray Lsp.Diagnostic := s.interactiveDiags.map fun d => d.toDiagnostic def infoTree (s : Snapshot) : InfoTree := -- the parser returns exactly one command per snapshot, and the elaborator creates exactly one node per command assert! s.cmdState.infoState.trees.size == 1 s.cmdState.infoState.trees[0]! def isAtEnd (s : Snapshot) : Bool := Parser.isTerminalCommand s.stx open Command in /-- Use the command state in the given snapshot to run a `CommandElabM`.-/ def runCommandElabM (snap : Snapshot) (meta : DocumentMeta) (c : CommandElabM α) : EIO Exception α := do let ctx : Command.Context := { cmdPos := snap.beginPos, fileName := meta.uri, fileMap := meta.text, tacticCache? := snap.tacticCache, } c.run ctx |>.run' snap.cmdState /-- Run a `CoreM` computation using the data in the given snapshot.-/ def runCoreM (snap : Snapshot) (meta : DocumentMeta) (c : CoreM α) : EIO Exception α := snap.runCommandElabM meta <| Command.liftCoreM c /-- Run a `TermElabM` computation using the data in the given snapshot.-/ def runTermElabM (snap : Snapshot) (meta : DocumentMeta) (c : TermElabM α) : EIO Exception α := snap.runCommandElabM meta <| Command.liftTermElabM c end Snapshot /-- Parses the next command occurring after the given snapshot without elaborating it. -/ def parseNextCmd (inputCtx : Parser.InputContext) (snap : Snapshot) : IO Syntax := do let cmdState := snap.cmdState let scope := cmdState.scopes.head! let pmctx := { env := cmdState.env, options := scope.opts, currNamespace := scope.currNamespace, openDecls := scope.openDecls } let (cmdStx, _, _) := Parser.parseCommand inputCtx pmctx snap.mpState snap.msgLog return cmdStx register_builtin_option server.stderrAsMessages : Bool := { defValue := true group := "server" descr := "(server) capture output to the Lean stderr channel (such as from `dbg_trace`) during elaboration of a command as a diagnostic message" } /-- Compiles the next command occurring after the given snapshot. If there is no next command (file ended), `Snapshot.isAtEnd` will hold of the return value. -/ -- NOTE: This code is really very similar to Elab.Frontend. But generalizing it -- over "store snapshots"/"don't store snapshots" would likely result in confusing -- isServer? conditionals and not be worth it due to how short it is. def compileNextCmd (inputCtx : Parser.InputContext) (snap : Snapshot) (hasWidgets : Bool) : IO Snapshot := do let cmdState := snap.cmdState let scope := cmdState.scopes.head! let pmctx := { env := cmdState.env, options := scope.opts, currNamespace := scope.currNamespace, openDecls := scope.openDecls } let (cmdStx, cmdParserState, msgLog) := Parser.parseCommand inputCtx pmctx snap.mpState snap.msgLog let cmdPos := cmdStx.getPos?.get! let cmdStateRef ← IO.mkRef { snap.cmdState with messages := msgLog } /- The same snapshot may be executed by different tasks. So, to make sure `elabCommandTopLevel` has exclusive access to the cache, we create a fresh reference here. Before this change, the following `snap.tacticCache.modify` would reset the tactic post cache while another snapshot was still using it. -/ let tacticCacheNew ← IO.mkRef (← snap.tacticCache.get) let cmdCtx : Elab.Command.Context := { cmdPos := snap.endPos fileName := inputCtx.fileName fileMap := inputCtx.fileMap tacticCache? := some tacticCacheNew } let (output, _) ← IO.FS.withIsolatedStreams (isolateStderr := server.stderrAsMessages.get scope.opts) <| liftM (m := BaseIO) do Elab.Command.catchExceptions (getResetInfoTrees *> Elab.Command.elabCommandTopLevel cmdStx) cmdCtx cmdStateRef let postNew := (← tacticCacheNew.get).post snap.tacticCache.modify fun _ => { pre := postNew, post := {} } let mut postCmdState ← cmdStateRef.get if !output.isEmpty then postCmdState := { postCmdState with messages := postCmdState.messages.add { fileName := inputCtx.fileName severity := MessageSeverity.information pos := inputCtx.fileMap.toPosition snap.endPos data := output } } let postCmdSnap : Snapshot := { beginPos := cmdPos stx := cmdStx mpState := cmdParserState cmdState := postCmdState interactiveDiags := ← withNewInteractiveDiags postCmdState.messages tacticCache := (← IO.mkRef {}) } return postCmdSnap where /-- Compute the current interactive diagnostics log by finding a "diff" relative to the parent snapshot. We need to do this because unlike the `MessageLog` itself, interactive diags are not part of the command state. -/ withNewInteractiveDiags (msgLog : MessageLog) : IO (PersistentArray Widget.InteractiveDiagnostic) := do let newMsgCount := msgLog.msgs.size - snap.msgLog.msgs.size let mut ret := snap.interactiveDiags for i in List.iota newMsgCount do let newMsg := msgLog.msgs.get! (msgLog.msgs.size - i) ret := ret.push (← Widget.msgToInteractiveDiagnostic inputCtx.fileMap newMsg hasWidgets) return ret end Lean.Server.Snapshots
509615332e6ad974fc21ec8fa6c7ec156c45c5e9
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/category_theory/limits/shapes/pullbacks.lean
eaf73e71dd838563119e69033e43832f7a5952b8
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
26,294
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Markus Himmel, Bhavik Mehta -/ import category_theory.limits.shapes.wide_pullbacks import category_theory.limits.shapes.binary_products /-! # Pullbacks We define a category `walking_cospan` (resp. `walking_span`), which is the index category for the given data for a pullback (resp. pushout) diagram. Convenience methods `cospan f g` and `span f g` construct functors from the walking (co)span, hitting the given morphisms. We define `pullback f g` and `pushout f g` as limits and colimits of such functors. -/ open category_theory namespace category_theory.limits universes v u local attribute [tidy] tactic.case_bash /-- The type of objects for the diagram indexing a pullback, defined as a special case of `wide_pullback_shape`. -/ abbreviation walking_cospan : Type v := wide_pullback_shape walking_pair /-- The left point of the walking cospan. -/ abbreviation walking_cospan.left : walking_cospan := some walking_pair.left /-- The right point of the walking cospan. -/ abbreviation walking_cospan.right : walking_cospan := some walking_pair.right /-- The central point of the walking cospan. -/ abbreviation walking_cospan.one : walking_cospan := none /-- The type of objects for the diagram indexing a pushout, defined as a special case of `wide_pushout_shape`. -/ abbreviation walking_span : Type v := wide_pushout_shape walking_pair /-- The left point of the walking span. -/ abbreviation walking_span.left : walking_span := some walking_pair.left /-- The right point of the walking span. -/ abbreviation walking_span.right : walking_span := some walking_pair.right /-- The central point of the walking span. -/ abbreviation walking_span.zero : walking_span := none namespace walking_cospan /-- The type of arrows for the diagram indexing a pullback. -/ abbreviation hom : walking_cospan → walking_cospan → Type v := wide_pullback_shape.hom /-- The left arrow of the walking cospan. -/ abbreviation hom.inl : left ⟶ one := wide_pullback_shape.hom.term _ /-- The right arrow of the walking cospan. -/ abbreviation hom.inr : right ⟶ one := wide_pullback_shape.hom.term _ /-- The identity arrows of the walking cospan. -/ abbreviation hom.id (X : walking_cospan) : X ⟶ X := wide_pullback_shape.hom.id X instance (X Y : walking_cospan) : subsingleton (X ⟶ Y) := by tidy end walking_cospan namespace walking_span /-- The type of arrows for the diagram indexing a pushout. -/ abbreviation hom : walking_span → walking_span → Type v := wide_pushout_shape.hom /-- The left arrow of the walking span. -/ abbreviation hom.fst : zero ⟶ left := wide_pushout_shape.hom.init _ /-- The right arrow of the walking span. -/ abbreviation hom.snd : zero ⟶ right := wide_pushout_shape.hom.init _ /-- The identity arrows of the walking span. -/ abbreviation hom.id (X : walking_span) : X ⟶ X := wide_pushout_shape.hom.id X instance (X Y : walking_span) : subsingleton (X ⟶ Y) := by tidy end walking_span open walking_span.hom walking_cospan.hom wide_pullback_shape.hom wide_pushout_shape.hom variables {C : Type u} [category.{v} C] /-- `cospan f g` is the functor from the walking cospan hitting `f` and `g`. -/ def cospan {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : walking_cospan ⥤ C := wide_pullback_shape.wide_cospan Z (λ j, walking_pair.cases_on j X Y) (λ j, walking_pair.cases_on j f g) /-- `span f g` is the functor from the walking span hitting `f` and `g`. -/ def span {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : walking_span ⥤ C := wide_pushout_shape.wide_span X (λ j, walking_pair.cases_on j Y Z) (λ j, walking_pair.cases_on j f g) @[simp] lemma cospan_left {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).obj walking_cospan.left = X := rfl @[simp] lemma span_left {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).obj walking_span.left = Y := rfl @[simp] lemma cospan_right {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).obj walking_cospan.right = Y := rfl @[simp] lemma span_right {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).obj walking_span.right = Z := rfl @[simp] lemma cospan_one {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).obj walking_cospan.one = Z := rfl @[simp] lemma span_zero {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).obj walking_span.zero = X := rfl @[simp] lemma cospan_map_inl {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).map walking_cospan.hom.inl = f := rfl @[simp] lemma span_map_fst {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).map walking_span.hom.fst = f := rfl @[simp] lemma cospan_map_inr {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).map walking_cospan.hom.inr = g := rfl @[simp] lemma span_map_snd {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).map walking_span.hom.snd = g := rfl lemma cospan_map_id {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) (w : walking_cospan) : (cospan f g).map (walking_cospan.hom.id w) = 𝟙 _ := rfl lemma span_map_id {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) (w : walking_span) : (span f g).map (walking_span.hom.id w) = 𝟙 _ := rfl /-- Every diagram indexing an pullback is naturally isomorphic (actually, equal) to a `cospan` -/ def diagram_iso_cospan (F : walking_cospan ⥤ C) : F ≅ cospan (F.map inl) (F.map inr) := nat_iso.of_components (λ j, eq_to_iso (by tidy)) (by tidy) /-- Every diagram indexing a pushout is naturally isomorphic (actually, equal) to a `span` -/ def diagram_iso_span (F : walking_span ⥤ C) : F ≅ span (F.map fst) (F.map snd) := nat_iso.of_components (λ j, eq_to_iso (by tidy)) (by tidy) variables {X Y Z : C} /-- A pullback cone is just a cone on the cospan formed by two morphisms `f : X ⟶ Z` and `g : Y ⟶ Z`.-/ abbreviation pullback_cone (f : X ⟶ Z) (g : Y ⟶ Z) := cone (cospan f g) namespace pullback_cone variables {f : X ⟶ Z} {g : Y ⟶ Z} /-- The first projection of a pullback cone. -/ abbreviation fst (t : pullback_cone f g) : t.X ⟶ X := t.π.app walking_cospan.left /-- The second projection of a pullback cone. -/ abbreviation snd (t : pullback_cone f g) : t.X ⟶ Y := t.π.app walking_cospan.right /-- This is a slightly more convenient method to verify that a pullback cone is a limit cone. It only asks for a proof of facts that carry any mathematical content -/ def is_limit_aux (t : pullback_cone f g) (lift : Π (s : cone (cospan f g)), s.X ⟶ t.X) (fac_left : ∀ (s : pullback_cone f g), lift s ≫ t.fst = s.fst) (fac_right : ∀ (s : pullback_cone f g), lift s ≫ t.snd = s.snd) (uniq : ∀ (s : pullback_cone f g) (m : s.X ⟶ t.X) (w : ∀ j : walking_cospan, m ≫ t.π.app j = s.π.app j), m = lift s) : is_limit t := { lift := lift, fac' := λ s j, option.cases_on j (by { rw [← s.w inl, ← t.w inl, ←category.assoc], congr, exact fac_left s, } ) (λ j', walking_pair.cases_on j' (fac_left s) (fac_right s)), uniq' := uniq } /-- This is another convenient method to verify that a pullback cone is a limit cone. It only asks for a proof of facts that carry any mathematical content, and allows access to the same `s` for all parts. -/ def is_limit_aux' (t : pullback_cone f g) (create : Π (s : pullback_cone f g), {l // l ≫ t.fst = s.fst ∧ l ≫ t.snd = s.snd ∧ ∀ {m}, m ≫ t.fst = s.fst → m ≫ t.snd = s.snd → m = l}) : limits.is_limit t := pullback_cone.is_limit_aux t (λ s, (create s).1) (λ s, (create s).2.1) (λ s, (create s).2.2.1) (λ s m w, (create s).2.2.2 (w walking_cospan.left) (w walking_cospan.right)) /-- A pullback cone on `f` and `g` is determined by morphisms `fst : W ⟶ X` and `snd : W ⟶ Y` such that `fst ≫ f = snd ≫ g`. -/ @[simps] def mk {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : pullback_cone f g := { X := W, π := { app := λ j, option.cases_on j (fst ≫ f) (λ j', walking_pair.cases_on j' fst snd) } } @[simp] lemma mk_π_app_left {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).π.app walking_cospan.left = fst := rfl @[simp] lemma mk_π_app_right {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).π.app walking_cospan.right = snd := rfl @[simp] lemma mk_π_app_one {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).π.app walking_cospan.one = fst ≫ f := rfl @[simp] lemma mk_fst {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).fst = fst := rfl @[simp] lemma mk_snd {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).snd = snd := rfl @[reassoc] lemma condition (t : pullback_cone f g) : fst t ≫ f = snd t ≫ g := (t.w inl).trans (t.w inr).symm /-- To check whether a morphism is equalized by the maps of a pullback cone, it suffices to check it for `fst t` and `snd t` -/ lemma equalizer_ext (t : pullback_cone f g) {W : C} {k l : W ⟶ t.X} (h₀ : k ≫ fst t = l ≫ fst t) (h₁ : k ≫ snd t = l ≫ snd t) : ∀ (j : walking_cospan), k ≫ t.π.app j = l ≫ t.π.app j | (some walking_pair.left) := h₀ | (some walking_pair.right) := h₁ | none := by rw [← t.w inl, reassoc_of h₀] lemma is_limit.hom_ext {t : pullback_cone f g} (ht : is_limit t) {W : C} {k l : W ⟶ t.X} (h₀ : k ≫ fst t = l ≫ fst t) (h₁ : k ≫ snd t = l ≫ snd t) : k = l := ht.hom_ext $ equalizer_ext _ h₀ h₁ /-- If `t` is a limit pullback cone over `f` and `g` and `h : W ⟶ X` and `k : W ⟶ Y` are such that `h ≫ f = k ≫ g`, then we have `l : W ⟶ t.X` satisfying `l ≫ fst t = h` and `l ≫ snd t = k`. -/ def is_limit.lift' {t : pullback_cone f g} (ht : is_limit t) {W : C} (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : {l : W ⟶ t.X // l ≫ fst t = h ∧ l ≫ snd t = k} := ⟨ht.lift $ pullback_cone.mk _ _ w, ht.fac _ _, ht.fac _ _⟩ /-- This is a more convenient formulation to show that a `pullback_cone` constructed using `pullback_cone.mk` is a limit cone. -/ def is_limit.mk {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) (lift : Π (s : pullback_cone f g), s.X ⟶ W) (fac_left : ∀ (s : pullback_cone f g), lift s ≫ fst = s.fst) (fac_right : ∀ (s : pullback_cone f g), lift s ≫ snd = s.snd) (uniq : ∀ (s : pullback_cone f g) (m : s.X ⟶ W) (w_fst : m ≫ fst = s.fst) (w_snd : m ≫ snd = s.snd), m = lift s) : is_limit (mk fst snd eq) := is_limit_aux _ lift fac_left fac_right (λ s m w, uniq s m (w walking_cospan.left) (w walking_cospan.right)) /-- The flip of a pullback square is a pullback square. -/ def flip_is_limit {W : C} {h : W ⟶ X} {k : W ⟶ Y} {comm : h ≫ f = k ≫ g} (t : is_limit (mk _ _ comm.symm)) : is_limit (mk _ _ comm) := is_limit_aux' _ $ λ s, begin refine ⟨(is_limit.lift' t _ _ s.condition.symm).1, (is_limit.lift' t _ _ _).2.2, (is_limit.lift' t _ _ _).2.1, λ m m₁ m₂, t.hom_ext _⟩, apply (mk k h _).equalizer_ext, { rwa (is_limit.lift' t _ _ _).2.1 }, { rwa (is_limit.lift' t _ _ _).2.2 }, end end pullback_cone /-- A pushout cocone is just a cocone on the span formed by two morphisms `f : X ⟶ Y` and `g : X ⟶ Z`.-/ abbreviation pushout_cocone (f : X ⟶ Y) (g : X ⟶ Z) := cocone (span f g) namespace pushout_cocone variables {f : X ⟶ Y} {g : X ⟶ Z} /-- The first inclusion of a pushout cocone. -/ abbreviation inl (t : pushout_cocone f g) : Y ⟶ t.X := t.ι.app walking_span.left /-- The second inclusion of a pushout cocone. -/ abbreviation inr (t : pushout_cocone f g) : Z ⟶ t.X := t.ι.app walking_span.right /-- This is a slightly more convenient method to verify that a pushout cocone is a colimit cocone. It only asks for a proof of facts that carry any mathematical content -/ def is_colimit_aux (t : pushout_cocone f g) (desc : Π (s : pushout_cocone f g), t.X ⟶ s.X) (fac_left : ∀ (s : pushout_cocone f g), t.inl ≫ desc s = s.inl) (fac_right : ∀ (s : pushout_cocone f g), t.inr ≫ desc s = s.inr) (uniq : ∀ (s : pushout_cocone f g) (m : t.X ⟶ s.X) (w : ∀ j : walking_span, t.ι.app j ≫ m = s.ι.app j), m = desc s) : is_colimit t := { desc := desc, fac' := λ s j, option.cases_on j (by { simp [← s.w fst, ← t.w fst, fac_left s] } ) (λ j', walking_pair.cases_on j' (fac_left s) (fac_right s)), uniq' := uniq } /-- This is another convenient method to verify that a pushout cocone is a colimit cocone. It only asks for a proof of facts that carry any mathematical content, and allows access to the same `s` for all parts. -/ def is_colimit_aux' (t : pushout_cocone f g) (create : Π (s : pushout_cocone f g), {l // t.inl ≫ l = s.inl ∧ t.inr ≫ l = s.inr ∧ ∀ {m}, t.inl ≫ m = s.inl → t.inr ≫ m = s.inr → m = l}) : is_colimit t := is_colimit_aux t (λ s, (create s).1) (λ s, (create s).2.1) (λ s, (create s).2.2.1) (λ s m w, (create s).2.2.2 (w walking_cospan.left) (w walking_cospan.right)) /-- A pushout cocone on `f` and `g` is determined by morphisms `inl : Y ⟶ W` and `inr : Z ⟶ W` such that `f ≫ inl = g ↠ inr`. -/ @[simps] def mk {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : pushout_cocone f g := { X := W, ι := { app := λ j, option.cases_on j (f ≫ inl) (λ j', walking_pair.cases_on j' inl inr) } } @[simp] lemma mk_ι_app_left {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).ι.app walking_span.left = inl := rfl @[simp] lemma mk_ι_app_right {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).ι.app walking_span.right = inr := rfl @[simp] lemma mk_ι_app_zero {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).ι.app walking_span.zero = f ≫ inl := rfl @[simp] lemma mk_inl {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).inl = inl := rfl @[simp] lemma mk_inr {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).inr = inr := rfl @[reassoc] lemma condition (t : pushout_cocone f g) : f ≫ (inl t) = g ≫ (inr t) := (t.w fst).trans (t.w snd).symm /-- To check whether a morphism is coequalized by the maps of a pushout cocone, it suffices to check it for `inl t` and `inr t` -/ lemma coequalizer_ext (t : pushout_cocone f g) {W : C} {k l : t.X ⟶ W} (h₀ : inl t ≫ k = inl t ≫ l) (h₁ : inr t ≫ k = inr t ≫ l) : ∀ (j : walking_span), t.ι.app j ≫ k = t.ι.app j ≫ l | (some walking_pair.left) := h₀ | (some walking_pair.right) := h₁ | none := by rw [← t.w fst, category.assoc, category.assoc, h₀] lemma is_colimit.hom_ext {t : pushout_cocone f g} (ht : is_colimit t) {W : C} {k l : t.X ⟶ W} (h₀ : inl t ≫ k = inl t ≫ l) (h₁ : inr t ≫ k = inr t ≫ l) : k = l := ht.hom_ext $ coequalizer_ext _ h₀ h₁ /-- If `t` is a colimit pushout cocone over `f` and `g` and `h : Y ⟶ W` and `k : Z ⟶ W` are morphisms satisfying `f ≫ h = g ≫ k`, then we have a factorization `l : t.X ⟶ W` such that `inl t ≫ l = h` and `inr t ≫ l = k`. -/ def is_colimit.desc' {t : pushout_cocone f g} (ht : is_colimit t) {W : C} (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : {l : t.X ⟶ W // inl t ≫ l = h ∧ inr t ≫ l = k } := ⟨ht.desc $ pushout_cocone.mk _ _ w, ht.fac _ _, ht.fac _ _⟩ /-- This is a more convenient formulation to show that a `pushout_cocone` constructed using `pushout_cocone.mk` is a colimit cocone. -/ def is_colimit.mk {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) (desc : Π (s : pushout_cocone f g), W ⟶ s.X) (fac_left : ∀ (s : pushout_cocone f g), inl ≫ desc s = s.inl) (fac_right : ∀ (s : pushout_cocone f g), inr ≫ desc s = s.inr) (uniq : ∀ (s : pushout_cocone f g) (m : W ⟶ s.X) (w_inl : inl ≫ m = s.inl) (w_inr : inr ≫ m = s.inr), m = desc s) : is_colimit (mk inl inr eq) := is_colimit_aux _ desc fac_left fac_right (λ s m w, uniq s m (w walking_cospan.left) (w walking_cospan.right)) /-- The flip of a pushout square is a pushout square. -/ def flip_is_colimit {W : C} {h : Y ⟶ W} {k : Z ⟶ W} {comm : f ≫ h = g ≫ k} (t : is_colimit (mk _ _ comm.symm)) : is_colimit (mk _ _ comm) := is_colimit_aux' _ $ λ s, begin refine ⟨(is_colimit.desc' t _ _ s.condition.symm).1, (is_colimit.desc' t _ _ _).2.2, (is_colimit.desc' t _ _ _).2.1, λ m m₁ m₂, t.hom_ext _⟩, apply (mk k h _).coequalizer_ext, { rwa (is_colimit.desc' t _ _ _).2.1 }, { rwa (is_colimit.desc' t _ _ _).2.2 }, end end pushout_cocone /-- This is a helper construction that can be useful when verifying that a category has all pullbacks. Given `F : walking_cospan ⥤ C`, which is really the same as `cospan (F.map inl) (F.map inr)`, and a pullback cone on `F.map inl` and `F.map inr`, we get a cone on `F`. If you're thinking about using this, have a look at `has_pullbacks_of_has_limit_cospan`, which you may find to be an easier way of achieving your goal. -/ @[simps] def cone.of_pullback_cone {F : walking_cospan ⥤ C} (t : pullback_cone (F.map inl) (F.map inr)) : cone F := { X := t.X, π := t.π ≫ (diagram_iso_cospan F).inv } /-- This is a helper construction that can be useful when verifying that a category has all pushout. Given `F : walking_span ⥤ C`, which is really the same as `span (F.map fst) (F.mal snd)`, and a pushout cocone on `F.map fst` and `F.map snd`, we get a cocone on `F`. If you're thinking about using this, have a look at `has_pushouts_of_has_colimit_span`, which you may find to be an easiery way of achieving your goal. -/ @[simps] def cocone.of_pushout_cocone {F : walking_span ⥤ C} (t : pushout_cocone (F.map fst) (F.map snd)) : cocone F := { X := t.X, ι := (diagram_iso_span F).hom ≫ t.ι } /-- Given `F : walking_cospan ⥤ C`, which is really the same as `cospan (F.map inl) (F.map inr)`, and a cone on `F`, we get a pullback cone on `F.map inl` and `F.map inr`. -/ @[simps] def pullback_cone.of_cone {F : walking_cospan ⥤ C} (t : cone F) : pullback_cone (F.map inl) (F.map inr) := { X := t.X, π := t.π ≫ (diagram_iso_cospan F).hom } /-- Given `F : walking_span ⥤ C`, which is really the same as `span (F.map fst) (F.map snd)`, and a cocone on `F`, we get a pushout cocone on `F.map fst` and `F.map snd`. -/ @[simps] def pushout_cocone.of_cocone {F : walking_span ⥤ C} (t : cocone F) : pushout_cocone (F.map fst) (F.map snd) := { X := t.X, ι := (diagram_iso_span F).inv ≫ t.ι } /-- `has_pullback f g` represents a particular choice of limiting cone for the pair of morphisms `f : X ⟶ Z` and `g : Y ⟶ Z`. -/ abbreviation has_pullback {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) := has_limit (cospan f g) /-- `has_pushout f g` represents a particular choice of colimiting cocone for the pair of morphisms `f : X ⟶ Y` and `g : X ⟶ Z`. -/ abbreviation has_pushout {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) := has_colimit (span f g) /-- `pullback f g` computes the pullback of a pair of morphisms with the same target. -/ abbreviation pullback {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) [has_pullback f g] := limit (cospan f g) /-- `pushout f g` computes the pushout of a pair of morphisms with the same source. -/ abbreviation pushout {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) [has_pushout f g] := colimit (span f g) /-- The first projection of the pullback of `f` and `g`. -/ abbreviation pullback.fst {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] : pullback f g ⟶ X := limit.π (cospan f g) walking_cospan.left /-- The second projection of the pullback of `f` and `g`. -/ abbreviation pullback.snd {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] : pullback f g ⟶ Y := limit.π (cospan f g) walking_cospan.right /-- The first inclusion into the pushout of `f` and `g`. -/ abbreviation pushout.inl {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] : Y ⟶ pushout f g := colimit.ι (span f g) walking_span.left /-- The second inclusion into the pushout of `f` and `g`. -/ abbreviation pushout.inr {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] : Z ⟶ pushout f g := colimit.ι (span f g) walking_span.right /-- A pair of morphisms `h : W ⟶ X` and `k : W ⟶ Y` satisfying `h ≫ f = k ≫ g` induces a morphism `pullback.lift : W ⟶ pullback f g`. -/ abbreviation pullback.lift {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : W ⟶ pullback f g := limit.lift _ (pullback_cone.mk h k w) /-- A pair of morphisms `h : Y ⟶ W` and `k : Z ⟶ W` satisfying `f ≫ h = g ≫ k` induces a morphism `pushout.desc : pushout f g ⟶ W`. -/ abbreviation pushout.desc {W X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : pushout f g ⟶ W := colimit.desc _ (pushout_cocone.mk h k w) @[simp, reassoc] lemma pullback.lift_fst {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : pullback.lift h k w ≫ pullback.fst = h := limit.lift_π _ _ @[simp, reassoc] lemma pullback.lift_snd {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : pullback.lift h k w ≫ pullback.snd = k := limit.lift_π _ _ @[simp, reassoc] lemma pushout.inl_desc {W X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : pushout.inl ≫ pushout.desc h k w = h := colimit.ι_desc _ _ @[simp, reassoc] lemma pushout.inr_desc {W X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : pushout.inr ≫ pushout.desc h k w = k := colimit.ι_desc _ _ /-- A pair of morphisms `h : W ⟶ X` and `k : W ⟶ Y` satisfying `h ≫ f = k ≫ g` induces a morphism `l : W ⟶ pullback f g` such that `l ≫ pullback.fst = h` and `l ≫ pullback.snd = k`. -/ def pullback.lift' {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : {l : W ⟶ pullback f g // l ≫ pullback.fst = h ∧ l ≫ pullback.snd = k} := ⟨pullback.lift h k w, pullback.lift_fst _ _ _, pullback.lift_snd _ _ _⟩ /-- A pair of morphisms `h : Y ⟶ W` and `k : Z ⟶ W` satisfying `f ≫ h = g ≫ k` induces a morphism `l : pushout f g ⟶ W` such that `pushout.inl ≫ l = h` and `pushout.inr ≫ l = k`. -/ def pullback.desc' {W X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : {l : pushout f g ⟶ W // pushout.inl ≫ l = h ∧ pushout.inr ≫ l = k} := ⟨pushout.desc h k w, pushout.inl_desc _ _ _, pushout.inr_desc _ _ _⟩ @[reassoc] lemma pullback.condition {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] : (pullback.fst : pullback f g ⟶ X) ≫ f = pullback.snd ≫ g := pullback_cone.condition _ @[reassoc] lemma pushout.condition {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] : f ≫ (pushout.inl : Y ⟶ pushout f g) = g ≫ pushout.inr := pushout_cocone.condition _ /-- Two morphisms into a pullback are equal if their compositions with the pullback morphisms are equal -/ @[ext] lemma pullback.hom_ext {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] {W : C} {k l : W ⟶ pullback f g} (h₀ : k ≫ pullback.fst = l ≫ pullback.fst) (h₁ : k ≫ pullback.snd = l ≫ pullback.snd) : k = l := limit.hom_ext $ pullback_cone.equalizer_ext _ h₀ h₁ /-- The pullback of a monomorphism is a monomorphism -/ instance pullback.fst_of_mono {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] [mono g] : mono (pullback.fst : pullback f g ⟶ X) := ⟨λ W u v h, pullback.hom_ext h $ (cancel_mono g).1 $ by simp [← pullback.condition, reassoc_of h]⟩ /-- The pullback of a monomorphism is a monomorphism -/ instance pullback.snd_of_mono {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] [mono f] : mono (pullback.snd : pullback f g ⟶ Y) := ⟨λ W u v h, pullback.hom_ext ((cancel_mono f).1 $ by simp [pullback.condition, reassoc_of h]) h⟩ /-- Two morphisms out of a pushout are equal if their compositions with the pushout morphisms are equal -/ @[ext] lemma pushout.hom_ext {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] {W : C} {k l : pushout f g ⟶ W} (h₀ : pushout.inl ≫ k = pushout.inl ≫ l) (h₁ : pushout.inr ≫ k = pushout.inr ≫ l) : k = l := colimit.hom_ext $ pushout_cocone.coequalizer_ext _ h₀ h₁ /-- The pushout of an epimorphism is an epimorphism -/ instance pushout.inl_of_epi {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] [epi g] : epi (pushout.inl : Y ⟶ pushout f g) := ⟨λ W u v h, pushout.hom_ext h $ (cancel_epi g).1 $ by simp [← pushout.condition_assoc, h] ⟩ /-- The pushout of an epimorphism is an epimorphism -/ instance pushout.inr_of_epi {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] [epi f] : epi (pushout.inr : Z ⟶ pushout f g) := ⟨λ W u v h, pushout.hom_ext ((cancel_epi f).1 $ by simp [pushout.condition_assoc, h]) h⟩ variables (C) /-- `has_pullbacks` represents a choice of pullback for every pair of morphisms -/ abbreviation has_pullbacks := has_limits_of_shape walking_cospan C /-- `has_pushouts` represents a choice of pushout for every pair of morphisms -/ abbreviation has_pushouts := has_colimits_of_shape walking_span C /-- If `C` has all limits of diagrams `cospan f g`, then it has all pullbacks -/ def has_pullbacks_of_has_limit_cospan [Π {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z}, has_limit (cospan f g)] : has_pullbacks C := { has_limit := λ F, has_limit_of_iso (diagram_iso_cospan F).symm } /-- If `C` has all colimits of diagrams `span f g`, then it has all pushouts -/ def has_pushouts_of_has_colimit_span [Π {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z}, has_colimit (span f g)] : has_pushouts C := { has_colimit := λ F, has_colimit_of_iso (diagram_iso_span F) } end category_theory.limits
162a8a03725332850e171ad0d114834e41581ba1
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/qpf/multivariate/constructions/prj.lean
959e3d1617b7c1003d3d060b3b05d492f121f9b5
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
1,634
lean
/- Copyright (c) 2020 Simon Hudon All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import control.functor.multivariate import data.qpf.multivariate.basic /-! > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Projection functors are QPFs. The `n`-ary projection functors on `i` is an `n`-ary functor `F` such that `F (α₀..αᵢ₋₁, αᵢ, αᵢ₊₁..αₙ₋₁) = αᵢ` -/ universes u v namespace mvqpf open_locale mvfunctor variables {n : ℕ} (i : fin2 n) /-- The projection `i` functor -/ def prj (v : typevec.{u} n) : Type u := v i instance prj.inhabited {v : typevec.{u} n} [inhabited (v i)] : inhabited (prj i v) := ⟨ (default : v i) ⟩ /-- `map` on functor `prj i` -/ def prj.map ⦃α β : typevec n⦄ (f : α ⟹ β) : prj i α → prj i β := f _ instance prj.mvfunctor : mvfunctor (prj i) := { map := prj.map i } /-- Polynomial representation of the projection functor -/ def prj.P : mvpfunctor.{u} n := { A := punit, B := λ _ j, ulift $ plift $ i = j } /-- Abstraction function of the `qpf` instance -/ def prj.abs ⦃α : typevec n⦄ : (prj.P i).obj α → prj i α | ⟨x, f⟩ := f _ ⟨⟨rfl⟩⟩ /-- Representation function of the `qpf` instance -/ def prj.repr ⦃α : typevec n⦄ : prj i α → (prj.P i).obj α := λ x : α i, ⟨ ⟨ ⟩, λ j ⟨⟨h⟩⟩, (h.rec x : α j) ⟩ instance prj.mvqpf : mvqpf (prj i) := { P := prj.P i, abs := prj.abs i, repr := prj.repr i, abs_repr := by intros; refl, abs_map := by intros; cases p; refl } end mvqpf
e27e7c9b0975e127337b0efb2341ff3e3e98f1d6
64874bd1010548c7f5a6e3e8902efa63baaff785
/library/data/nat/default.lean
958b36316e39d64572caf3cc3d93f31cc1b02960
[ "Apache-2.0" ]
permissive
tjiaqi/lean
4634d729795c164664d10d093f3545287c76628f
d0ce4cf62f4246b0600c07e074d86e51f2195e30
refs/heads/master
1,622,323,796,480
1,422,643,069,000
1,422,643,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
217
lean
-- Copyright (c) 2014 Microsoft Corporation. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Jeremy Avigad import .basic .order .sub .div .bquant .comm_semiring
e08f915205429c6f6e11333ffceff0d7fd3329f0
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/ring_theory/perfection.lean
5751c59126e97172f2880359afaf1840e2c9255f
[ "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
24,319
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.char_p import algebra.ring.pi import analysis.special_functions.pow import field_theory.perfect_closure import ring_theory.localization import ring_theory.subring import ring_theory.valuation.integers /-! # Ring Perfection and Tilt In this file we define the perfection of a ring of characteristic p, and the tilt of a field given a valuation to `ℝ≥0`. ## TODO Define the valuation on the tilt, and define a characteristic predicate for the tilt. -/ universes u₁ u₂ u₃ u₄ open_locale nnreal /-- The perfection of a monoid `M`, defined to be the projective limit of `M` using the `p`-th power maps `M → M` indexed by the natural numbers, implemented as `{ f : ℕ → M | ∀ n, f (n + 1) ^ p = f n }`. -/ def monoid.perfection (M : Type u₁) [comm_monoid M] (p : ℕ) : submonoid (ℕ → M) := { carrier := { f | ∀ n, f (n + 1) ^ p = f n }, one_mem' := λ n, one_pow _, mul_mem' := λ f g hf hg n, (mul_pow _ _ _).trans $ congr_arg2 _ (hf n) (hg n) } /-- The perfection of a ring `R` with characteristic `p`, defined to be the projective limit of `R` using the Frobenius maps `R → R` indexed by the natural numbers, implemented as `{ f : ℕ → R | ∀ n, f (n + 1) ^ p = f n }`. -/ def ring.perfection (R : Type u₁) [comm_semiring R] (p : ℕ) [hp : fact p.prime] [char_p R p] : subsemiring (ℕ → R) := { zero_mem' := λ n, zero_pow $ hp.1.pos, add_mem' := λ f g hf hg n, (frobenius_add R p _ _).trans $ congr_arg2 _ (hf n) (hg n), .. monoid.perfection R p } namespace perfection variables (R : Type u₁) [comm_semiring R] (p : ℕ) [hp : fact p.prime] [char_p R p] include hp /-- The `n`-th coefficient of an element of the perfection. -/ def coeff (n : ℕ) : ring.perfection R p →+* R := { to_fun := λ f, f.1 n, map_one' := rfl, map_mul' := λ f g, rfl, map_zero' := rfl, map_add' := λ f g, rfl } variables {R p} @[ext] lemma ext {f g : ring.perfection R p} (h : ∀ n, coeff R p n f = coeff R p n g) : f = g := subtype.eq $ funext h variables (R p) /-- The `p`-th root of an element of the perfection. -/ def pth_root : ring.perfection R p →+* ring.perfection R p := { to_fun := λ f, ⟨λ n, coeff R p (n + 1) f, λ n, f.2 _⟩, map_one' := rfl, map_mul' := λ f g, rfl, map_zero' := rfl, map_add' := λ f g, rfl } variables {R p} @[simp] lemma coeff_mk (f : ℕ → R) (hf) (n : ℕ) : coeff R p n ⟨f, hf⟩ = f n := rfl lemma coeff_pth_root (f : ring.perfection R p) (n : ℕ) : coeff R p n (pth_root R p f) = coeff R p (n + 1) f := rfl lemma coeff_pow_p (f : ring.perfection R p) (n : ℕ) : coeff R p (n + 1) (f ^ p) = coeff R p n f := by { rw ring_hom.map_pow, exact f.2 n } lemma coeff_pow_p' (f : ring.perfection R p) (n : ℕ) : coeff R p (n + 1) f ^ p = coeff R p n f := f.2 n lemma coeff_frobenius (f : ring.perfection R p) (n : ℕ) : coeff R p (n + 1) (frobenius _ p f) = coeff R p n f := by apply coeff_pow_p f n -- `coeff_pow_p f n` also works but is slow! lemma coeff_iterate_frobenius (f : ring.perfection R p) (n m : ℕ) : coeff R p (n + m) (frobenius _ p ^[m] f) = coeff R p n f := nat.rec_on m rfl $ λ m ih, by erw [function.iterate_succ_apply', coeff_frobenius, ih] lemma coeff_iterate_frobenius' (f : ring.perfection R p) (n m : ℕ) (hmn : m ≤ n) : coeff R p n (frobenius _ p ^[m] f) = coeff R p (n - m) f := eq.symm $ (coeff_iterate_frobenius _ _ m).symm.trans $ (nat.sub_add_cancel hmn).symm ▸ rfl lemma pth_root_frobenius : (pth_root R p).comp (frobenius _ p) = ring_hom.id _ := ring_hom.ext $ λ x, ext $ λ n, by rw [ring_hom.comp_apply, ring_hom.id_apply, coeff_pth_root, coeff_frobenius] lemma frobenius_pth_root : (frobenius _ p).comp (pth_root R p) = ring_hom.id _ := ring_hom.ext $ λ x, ext $ λ n, by rw [ring_hom.comp_apply, ring_hom.id_apply, ring_hom.map_frobenius, coeff_pth_root, ← ring_hom.map_frobenius, coeff_frobenius] lemma coeff_add_ne_zero {f : ring.perfection R p} {n : ℕ} (hfn : coeff R p n f ≠ 0) (k : ℕ) : coeff R p (n + k) f ≠ 0 := nat.rec_on k hfn $ λ k ih h, ih $ by erw [← coeff_pow_p, ring_hom.map_pow, h, zero_pow hp.1.pos] lemma coeff_ne_zero_of_le {f : ring.perfection R p} {m n : ℕ} (hfm : coeff R p m f ≠ 0) (hmn : m ≤ n) : coeff R p n f ≠ 0 := let ⟨k, hk⟩ := nat.exists_eq_add_of_le hmn in hk.symm ▸ coeff_add_ne_zero hfm k variables (R p) instance perfect_ring : perfect_ring (ring.perfection R p) p := { pth_root' := pth_root R p, frobenius_pth_root' := congr_fun $ congr_arg ring_hom.to_fun $ @frobenius_pth_root R _ p _ _, pth_root_frobenius' := congr_fun $ congr_arg ring_hom.to_fun $ @pth_root_frobenius R _ p _ _ } instance ring (R : Type u₁) [comm_ring R] [char_p R p] : ring (ring.perfection R p) := ((ring.perfection R p).to_subring $ λ n, by simp_rw [← frobenius_def, pi.neg_apply, pi.one_apply, ring_hom.map_neg, ring_hom.map_one]).to_ring instance comm_ring (R : Type u₁) [comm_ring R] [char_p R p] : comm_ring (ring.perfection R p) := ((ring.perfection R p).to_subring $ λ n, by simp_rw [← frobenius_def, pi.neg_apply, pi.one_apply, ring_hom.map_neg, ring_hom.map_one]).to_comm_ring /-- Given rings `R` and `S` of characteristic `p`, with `R` being perfect, any homomorphism `R →+* S` can be lifted to a homomorphism `R →+* perfection S p`. -/ @[simps] def lift (R : Type u₁) [comm_semiring R] [char_p R p] [perfect_ring R p] (S : Type u₂) [comm_semiring S] [char_p S p] : (R →+* S) ≃ (R →+* ring.perfection S p) := { to_fun := λ f, { to_fun := λ r, ⟨λ n, f $ _root_.pth_root R p ^[n] r, λ n, by rw [← f.map_pow, function.iterate_succ_apply', pth_root_pow_p]⟩, map_one' := ext $ λ n, (congr_arg f $ ring_hom.iterate_map_one _ _).trans f.map_one, map_mul' := λ x y, ext $ λ n, (congr_arg f $ ring_hom.iterate_map_mul _ _ _ _).trans $ f.map_mul _ _, map_zero' := ext $ λ n, (congr_arg f $ ring_hom.iterate_map_zero _ _).trans f.map_zero, map_add' := λ x y, ext $ λ n, (congr_arg f $ ring_hom.iterate_map_add _ _ _ _).trans $ f.map_add _ _ }, inv_fun := ring_hom.comp $ coeff S p 0, left_inv := λ f, ring_hom.ext $ λ r, rfl, right_inv := λ f, ring_hom.ext $ λ r, ext $ λ n, show coeff S p 0 (f (_root_.pth_root R p ^[n] r)) = coeff S p n (f r), by rw [← coeff_iterate_frobenius _ 0 n, zero_add, ← ring_hom.map_iterate_frobenius, right_inverse_pth_root_frobenius.iterate] } lemma hom_ext {R : Type u₁} [comm_semiring R] [char_p R p] [perfect_ring R p] {S : Type u₂} [comm_semiring S] [char_p S p] {f g : R →+* ring.perfection S p} (hfg : ∀ x, coeff S p 0 (f x) = coeff S p 0 (g x)) : f = g := (lift p R S).symm.injective $ ring_hom.ext hfg variables {R} {S : Type u₂} [comm_semiring S] [char_p S p] /-- A ring homomorphism `R →+* S` induces `perfection R p →+* perfection S p` -/ @[simps] def map (φ : R →+* S) : ring.perfection R p →+* ring.perfection S p := { to_fun := λ f, ⟨λ n, φ (coeff R p n f), λ n, by rw [← φ.map_pow, coeff_pow_p']⟩, map_one' := subtype.eq $ funext $ λ n, φ.map_one, map_mul' := λ f g, subtype.eq $ funext $ λ n, φ.map_mul _ _, map_zero' := subtype.eq $ funext $ λ n, φ.map_zero, map_add' := λ f g, subtype.eq $ funext $ λ n, φ.map_add _ _ } lemma coeff_map (φ : R →+* S) (f : ring.perfection R p) (n : ℕ) : coeff S p n (map p φ f) = φ (coeff R p n f) := rfl end perfection /-- A perfection map to a ring of characteristic `p` is a map that is isomorphic to its perfection. -/ @[nolint has_inhabited_instance] structure perfection_map (p : ℕ) [fact p.prime] {R : Type u₁} [comm_semiring R] [char_p R p] {P : Type u₂} [comm_semiring P] [char_p P p] [perfect_ring P p] (π : P →+* R) : Prop := (injective : ∀ ⦃x y : P⦄, (∀ n, π (pth_root P p ^[n] x) = π (pth_root P p ^[n] y)) → x = y) (surjective : ∀ f : ℕ → R, (∀ n, f (n + 1) ^ p = f n) → ∃ x : P, ∀ n, π (pth_root P p ^[n] x) = f n) namespace perfection_map variables {p : ℕ} [fact p.prime] variables {R : Type u₁} [comm_semiring R] [char_p R p] variables {P : Type u₃} [comm_semiring P] [char_p P p] [perfect_ring P p] /-- Create a `perfection_map` from an isomorphism to the perfection. -/ @[simps] lemma mk' {f : P →+* R} (g : P ≃+* ring.perfection R p) (hfg : perfection.lift p P R f = g) : perfection_map p f := { injective := λ x y hxy, g.injective $ (ring_hom.ext_iff.1 hfg x).symm.trans $ eq.symm $ (ring_hom.ext_iff.1 hfg y).symm.trans $ perfection.ext $ λ n, (hxy n).symm, surjective := λ y hy, let ⟨x, hx⟩ := g.surjective ⟨y, hy⟩ in ⟨x, λ n, show perfection.coeff R p n (perfection.lift p P R f x) = perfection.coeff R p n ⟨y, hy⟩, by rw [hfg, ← coe_fn_coe_base, hx]⟩ } variables (p R P) /-- The canonical perfection map from the perfection of a ring. -/ lemma of : perfection_map p (perfection.coeff R p 0) := mk' (ring_equiv.refl _) $ (equiv.apply_eq_iff_eq_symm_apply _).2 rfl /-- For a perfect ring, it itself is the perfection. -/ lemma id [perfect_ring R p] : perfection_map p (ring_hom.id R) := { injective := λ x y hxy, hxy 0, surjective := λ f hf, ⟨f 0, λ n, show pth_root R p ^[n] (f 0) = f n, from nat.rec_on n rfl $ λ n ih, injective_pow_p p $ by rw [function.iterate_succ_apply', pth_root_pow_p _, ih, hf]⟩ } variables {p R P} /-- A perfection map induces an isomorphism to the prefection. -/ noncomputable def equiv {π : P →+* R} (m : perfection_map p π) : P ≃+* ring.perfection R p := ring_equiv.of_bijective (perfection.lift p P R π) ⟨λ x y hxy, m.injective $ λ n, (congr_arg (perfection.coeff R p n) hxy : _), λ f, let ⟨x, hx⟩ := m.surjective f.1 f.2 in ⟨x, perfection.ext $ hx⟩⟩ lemma equiv_apply {π : P →+* R} (m : perfection_map p π) (x : P) : m.equiv x = perfection.lift p P R π x := rfl lemma comp_equiv {π : P →+* R} (m : perfection_map p π) (x : P) : perfection.coeff R p 0 (m.equiv x) = π x := rfl lemma comp_equiv' {π : P →+* R} (m : perfection_map p π) : (perfection.coeff R p 0).comp ↑m.equiv = π := ring_hom.ext $ λ x, rfl lemma comp_symm_equiv {π : P →+* R} (m : perfection_map p π) (f : ring.perfection R p) : π (m.equiv.symm f) = perfection.coeff R p 0 f := (m.comp_equiv _).symm.trans $ congr_arg _ $ m.equiv.apply_symm_apply f lemma comp_symm_equiv' {π : P →+* R} (m : perfection_map p π) : π.comp ↑m.equiv.symm = perfection.coeff R p 0 := ring_hom.ext m.comp_symm_equiv variables (p R P) /-- Given rings `R` and `S` of characteristic `p`, with `R` being perfect, any homomorphism `R →+* S` can be lifted to a homomorphism `R →+* P`, where `P` is any perfection of `S`. -/ @[simps] noncomputable def lift [perfect_ring R p] (S : Type u₂) [comm_semiring S] [char_p S p] (P : Type u₃) [comm_semiring P] [char_p P p] [perfect_ring P p] (π : P →+* S) (m : perfection_map p π) : (R →+* S) ≃ (R →+* P) := { to_fun := λ f, ring_hom.comp ↑m.equiv.symm $ perfection.lift p R S f, inv_fun := λ f, π.comp f, left_inv := λ f, by { simp_rw [← ring_hom.comp_assoc, comp_symm_equiv'], exact (perfection.lift p R S).symm_apply_apply f }, right_inv := λ f, ring_hom.ext $ λ x, m.equiv.injective $ (m.equiv.apply_symm_apply _).trans $ show perfection.lift p R S (π.comp f) x = ring_hom.comp ↑m.equiv f x, from ring_hom.ext_iff.1 ((perfection.lift p R S).apply_eq_iff_eq_symm_apply.2 rfl) _ } variables {R p} lemma hom_ext [perfect_ring R p] {S : Type u₂} [comm_semiring S] [char_p S p] {P : Type u₃} [comm_semiring P] [char_p P p] [perfect_ring P p] (π : P →+* S) (m : perfection_map p π) {f g : R →+* P} (hfg : ∀ x, π (f x) = π (g x)) : f = g := (lift p R S P π m).symm.injective $ ring_hom.ext hfg variables {R P} (p) {S : Type u₂} [comm_semiring S] [char_p S p] variables {Q : Type u₄} [comm_semiring Q] [char_p Q p] [perfect_ring Q p] /-- A ring homomorphism `R →+* S` induces `P →+* Q`, a map of the respective perfections. -/ @[nolint unused_arguments] noncomputable def map {π : P →+* R} (m : perfection_map p π) {σ : Q →+* S} (n : perfection_map p σ) (φ : R →+* S) : P →+* Q := lift p P S Q σ n $ φ.comp π lemma comp_map {π : P →+* R} (m : perfection_map p π) {σ : Q →+* S} (n : perfection_map p σ) (φ : R →+* S) : σ.comp (map p m n φ) = φ.comp π := (lift p P S Q σ n).symm_apply_apply _ lemma map_map {π : P →+* R} (m : perfection_map p π) {σ : Q →+* S} (n : perfection_map p σ) (φ : R →+* S) (x : P) : σ (map p m n φ x) = φ (π x) := ring_hom.ext_iff.1 (comp_map p m n φ) x -- Why is this slow? lemma map_eq_map (φ : R →+* S) : @map p _ R _ _ _ _ _ _ S _ _ _ _ _ _ _ (of p R) _ (of p S) φ = perfection.map p φ := hom_ext _ (of p S) $ λ f, by rw [map_map, perfection.coeff_map] end perfection_map section perfectoid variables (K : Type u₁) [field K] (v : valuation K ℝ≥0) variables (O : Type u₂) [comm_ring O] [algebra O K] (hv : v.integers O) variables (p : ℕ) include hv /-- `O/(p)` for `O`, ring of integers of `K`. -/ @[nolint unused_arguments has_inhabited_instance] def mod_p := (ideal.span {p} : ideal O).quotient variables [hp : fact p.prime] [hvp : fact (v p ≠ 1)] namespace mod_p instance : comm_ring (mod_p K v O hv p) := ideal.quotient.comm_ring _ include hp hvp instance : char_p (mod_p K v O hv p) p := char_p.quotient O p $ mt hv.one_of_is_unit $ ((algebra_map O K).map_nat_cast p).symm ▸ hvp.1 instance : nontrivial (mod_p K v O hv p) := char_p.nontrivial_of_char_ne_one hp.1.ne_one section classical local attribute [instance] classical.dec omit hp hvp /-- For a field `K` with valuation `v : K → ℝ≥0` and ring of integers `O`, a function `O/(p) → ℝ≥0` that sends `0` to `0` and `x + (p)` to `v(x)` as long as `x ∉ (p)`. -/ noncomputable def pre_val (x : mod_p K v O hv p) : ℝ≥0 := if x = 0 then 0 else v (algebra_map O K x.out') variables {K v O hv p} lemma pre_val_mk {x : O} (hx : (ideal.quotient.mk _ x : mod_p K v O hv p) ≠ 0) : pre_val K v O hv p (ideal.quotient.mk _ x) = v (algebra_map O K x) := begin obtain ⟨r, hr⟩ := ideal.mem_span_singleton'.1 (ideal.quotient.eq.1 $ quotient.sound' $ @quotient.mk_out' O (ideal.span {p} : ideal O).quotient_rel x), refine (if_neg hx).trans (v.map_eq_of_sub_lt $ lt_of_not_ge' _), erw [← ring_hom.map_sub, ← hr, hv.le_iff_dvd], exact λ hprx, hx (ideal.quotient.eq_zero_iff_mem.2 $ ideal.mem_span_singleton.2 $ dvd_of_mul_left_dvd hprx), end lemma pre_val_zero : pre_val K v O hv p 0 = 0 := if_pos rfl lemma pre_val_mul {x y : mod_p K v O hv p} (hxy0 : x * y ≠ 0) : pre_val K v O hv p (x * y) = pre_val K v O hv p x * pre_val K v O hv p y := begin have hx0 : x ≠ 0 := mt (by { rintro rfl, rw zero_mul }) hxy0, have hy0 : y ≠ 0 := mt (by { rintro rfl, rw mul_zero }) hxy0, obtain ⟨r, rfl⟩ := ideal.quotient.mk_surjective x, obtain ⟨s, rfl⟩ := ideal.quotient.mk_surjective y, rw ← ring_hom.map_mul at hxy0 ⊢, rw [pre_val_mk hx0, pre_val_mk hy0, pre_val_mk hxy0, ring_hom.map_mul, v.map_mul] end lemma pre_val_add (x y : mod_p K v O hv p) : pre_val K v O hv p (x + y) ≤ max (pre_val K v O hv p x) (pre_val K v O hv p y) := begin by_cases hx0 : x = 0, { rw [hx0, zero_add], exact le_max_right _ _ }, by_cases hy0 : y = 0, { rw [hy0, add_zero], exact le_max_left _ _ }, by_cases hxy0 : x + y = 0, { rw [hxy0, pre_val_zero], exact zero_le _ }, obtain ⟨r, rfl⟩ := ideal.quotient.mk_surjective x, obtain ⟨s, rfl⟩ := ideal.quotient.mk_surjective y, rw ← ring_hom.map_add at hxy0 ⊢, rw [pre_val_mk hx0, pre_val_mk hy0, pre_val_mk hxy0, ring_hom.map_add], exact v.map_add _ _ end lemma v_p_lt_pre_val {x : mod_p K v O hv p} : v p < pre_val K v O hv p x ↔ x ≠ 0 := begin refine ⟨λ h hx, by { rw [hx, pre_val_zero] at h, exact not_lt_zero' h }, λ h, lt_of_not_ge' $ λ hp, h _⟩, obtain ⟨r, rfl⟩ := ideal.quotient.mk_surjective x, rw [pre_val_mk h, ← (algebra_map O K).map_nat_cast p, hv.le_iff_dvd] at hp, rw [ideal.quotient.eq_zero_iff_mem, ideal.mem_span_singleton], exact hp end lemma pre_val_eq_zero {x : mod_p K v O hv p} : pre_val K v O hv p x = 0 ↔ x = 0 := ⟨λ hvx, classical.by_contradiction $ λ hx0 : x ≠ 0, by { rw [← v_p_lt_pre_val, hvx] at hx0, exact not_lt_zero' hx0 }, λ hx, hx.symm ▸ pre_val_zero⟩ variables (hv hvp) lemma v_p_lt_val {x : O} : v p < v (algebra_map O K x) ↔ (ideal.quotient.mk _ x : mod_p K v O hv p) ≠ 0 := by rw [lt_iff_not_ge', not_iff_not, ← (algebra_map O K).map_nat_cast p, hv.le_iff_dvd, ideal.quotient.eq_zero_iff_mem, ideal.mem_span_singleton] open nnreal variables {hv} [hvp] include hp lemma mul_ne_zero_of_pow_p_ne_zero {x y : mod_p K v O hv p} (hx : x ^ p ≠ 0) (hy : y ^ p ≠ 0) : x * y ≠ 0 := begin obtain ⟨r, rfl⟩ := ideal.quotient.mk_surjective x, obtain ⟨s, rfl⟩ := ideal.quotient.mk_surjective y, have h1p : (0 : ℝ) < 1 / p := one_div_pos.2 (nat.cast_pos.2 hp.1.pos), rw ← ring_hom.map_mul, rw ← ring_hom.map_pow at hx hy, rw ← v_p_lt_val hv at hx hy ⊢, rw [ring_hom.map_pow, v.map_pow, ← rpow_lt_rpow_iff h1p, ← rpow_nat_cast, ← rpow_mul, mul_one_div_cancel (nat.cast_ne_zero.2 hp.1.ne_zero : (p : ℝ) ≠ 0), rpow_one] at hx hy, rw [ring_hom.map_mul, v.map_mul], refine lt_of_le_of_lt _ (mul_lt_mul'''' hx hy), by_cases hvp : v p = 0, { rw hvp, exact zero_le _ }, replace hvp := zero_lt_iff.2 hvp, conv_lhs { rw ← rpow_one (v p) }, rw ← rpow_add (ne_of_gt hvp), refine rpow_le_rpow_of_exponent_ge hvp ((algebra_map O K).map_nat_cast p ▸ hv.2 _) _, rw [← add_div, div_le_one (nat.cast_pos.2 hp.1.pos : 0 < (p : ℝ))], exact_mod_cast hp.1.two_le end end classical end mod_p include hp hvp /-- Perfection of `O/(p)` where `O` is the ring of integers of `K`. -/ @[nolint has_inhabited_instance] def pre_tilt := ring.perfection (mod_p K v O hv p) p namespace pre_tilt instance : comm_ring (pre_tilt K v O hv p) := perfection.comm_ring p _ section classical local attribute [instance] classical.dec open perfection /-- The valuation `Perfection(O/(p)) → ℝ≥0` as a function. Given `f ∈ Perfection(O/(p))`, if `f = 0` then output `0`; otherwise output `pre_val(f(n))^(p^n)` for any `n` such that `f(n) ≠ 0`. -/ noncomputable def val_aux (f : pre_tilt K v O hv p) : ℝ≥0 := if h : ∃ n, coeff _ _ n f ≠ 0 then mod_p.pre_val K v O hv p (coeff _ _ (nat.find h) f) ^ (p ^ nat.find h) else 0 variables {K v O hv p} lemma coeff_nat_find_add_ne_zero {f : pre_tilt K v O hv p} {h : ∃ n, coeff _ _ n f ≠ 0} (k : ℕ) : coeff _ _ (nat.find h + k) f ≠ 0 := coeff_add_ne_zero (nat.find_spec h) k lemma val_aux_eq {f : pre_tilt K v O hv p} {n : ℕ} (hfn : coeff _ _ n f ≠ 0) : val_aux K v O hv p f = mod_p.pre_val K v O hv p (coeff _ _ n f) ^ (p ^ n) := begin have h : ∃ n, coeff _ _ n f ≠ 0 := ⟨n, hfn⟩, rw [val_aux, dif_pos h], obtain ⟨k, rfl⟩ := nat.exists_eq_add_of_le (nat.find_min' h hfn), induction k with k ih, { refl }, obtain ⟨x, hx⟩ := ideal.quotient.mk_surjective (coeff _ _ (nat.find h + k + 1) f), have h1 : (ideal.quotient.mk _ x : mod_p K v O hv p) ≠ 0 := hx.symm ▸ hfn, have h2 : (ideal.quotient.mk _ (x ^ p) : mod_p K v O hv p) ≠ 0, by { erw [ring_hom.map_pow, hx, ← ring_hom.map_pow, coeff_pow_p], exact coeff_nat_find_add_ne_zero k }, erw [ih (coeff_nat_find_add_ne_zero k), ← hx, ← coeff_pow_p, ring_hom.map_pow, ← hx, ← ring_hom.map_pow, mod_p.pre_val_mk h1, mod_p.pre_val_mk h2, ring_hom.map_pow, v.map_pow, ← pow_mul, pow_succ], refl end lemma val_aux_zero : val_aux K v O hv p 0 = 0 := dif_neg $ λ ⟨n, hn⟩, hn rfl lemma val_aux_one : val_aux K v O hv p 1 = 1 := (val_aux_eq $ show coeff (mod_p K v O hv p) p 0 1 ≠ 0, from one_ne_zero).trans $ by { rw [pow_zero, pow_one, ring_hom.map_one, ← (ideal.quotient.mk _).map_one, mod_p.pre_val_mk, ring_hom.map_one, v.map_one], exact @one_ne_zero (mod_p K v O hv p) _ _ } lemma val_aux_mul (f g : pre_tilt K v O hv p) : val_aux K v O hv p (f * g) = val_aux K v O hv p f * val_aux K v O hv p g := begin by_cases hf : f = 0, { rw [hf, zero_mul, val_aux_zero, zero_mul] }, by_cases hg : g = 0, { rw [hg, mul_zero, val_aux_zero, mul_zero] }, replace hf : ∃ n, coeff _ _ n f ≠ 0 := not_forall.1 (λ h, hf $ perfection.ext h), replace hg : ∃ n, coeff _ _ n g ≠ 0 := not_forall.1 (λ h, hg $ perfection.ext h), obtain ⟨m, hm⟩ := hf, obtain ⟨n, hn⟩ := hg, replace hm := coeff_ne_zero_of_le hm (le_max_left m n), replace hn := coeff_ne_zero_of_le hn (le_max_right m n), have hfg : coeff _ _ (max m n + 1) (f * g) ≠ 0, { rw ring_hom.map_mul, refine mod_p.mul_ne_zero_of_pow_p_ne_zero _ _; rw [← ring_hom.map_pow, coeff_pow_p]; assumption }, rw [val_aux_eq (coeff_add_ne_zero hm 1), val_aux_eq (coeff_add_ne_zero hn 1), val_aux_eq hfg], rw ring_hom.map_mul at hfg ⊢, rw [mod_p.pre_val_mul hfg, mul_pow] end lemma val_aux_add (f g : pre_tilt K v O hv p) : val_aux K v O hv p (f + g) ≤ max (val_aux K v O hv p f) (val_aux K v O hv p g) := begin by_cases hf : f = 0, { rw [hf, zero_add, val_aux_zero, max_eq_right], exact zero_le _ }, by_cases hg : g = 0, { rw [hg, add_zero, val_aux_zero, max_eq_left], exact zero_le _ }, by_cases hfg : f + g = 0, { rw [hfg, val_aux_zero], exact zero_le _ }, replace hf : ∃ n, coeff _ _ n f ≠ 0 := not_forall.1 (λ h, hf $ perfection.ext h), replace hg : ∃ n, coeff _ _ n g ≠ 0 := not_forall.1 (λ h, hg $ perfection.ext h), replace hfg : ∃ n, coeff _ _ n (f + g) ≠ 0 := not_forall.1 (λ h, hfg $ perfection.ext h), obtain ⟨m, hm⟩ := hf, obtain ⟨n, hn⟩ := hg, obtain ⟨k, hk⟩ := hfg, replace hm := coeff_ne_zero_of_le hm (le_trans (le_max_left m n) (le_max_left _ k)), replace hn := coeff_ne_zero_of_le hn (le_trans (le_max_right m n) (le_max_left _ k)), replace hk := coeff_ne_zero_of_le hk (le_max_right (max m n) k), rw [val_aux_eq hm, val_aux_eq hn, val_aux_eq hk, ring_hom.map_add], cases le_max_iff.1 (mod_p.pre_val_add (coeff _ _ (max (max m n) k) f) (coeff _ _ (max (max m n) k) g)) with h h, { exact le_max_left_of_le (canonically_ordered_semiring.pow_le_pow_of_le_left h _) }, { exact le_max_right_of_le (canonically_ordered_semiring.pow_le_pow_of_le_left h _) } end variables (K v O hv p) /-- The valuation `Perfection(O/(p)) → ℝ≥0`. Given `f ∈ Perfection(O/(p))`, if `f = 0` then output `0`; otherwise output `pre_val(f(n))^(p^n)` for any `n` such that `f(n) ≠ 0`. -/ noncomputable def val : valuation (pre_tilt K v O hv p) ℝ≥0 := { to_fun := val_aux K v O hv p, map_one' := val_aux_one, map_mul' := val_aux_mul, map_zero' := val_aux_zero, map_add' := val_aux_add } variables {K v O hv p} lemma map_eq_zero {f : pre_tilt K v O hv p} : val K v O hv p f = 0 ↔ f = 0 := begin by_cases hf0 : f = 0, { rw hf0, exact iff_of_true (valuation.map_zero _) rfl }, obtain ⟨n, hn⟩ : ∃ n, coeff _ _ n f ≠ 0 := not_forall.1 (λ h, hf0 $ perfection.ext h), show val_aux K v O hv p f = 0 ↔ f = 0, refine iff_of_false (λ hvf, hn _) hf0, rw val_aux_eq hn at hvf, replace hvf := pow_eq_zero hvf, rwa mod_p.pre_val_eq_zero at hvf end end classical instance : integral_domain (pre_tilt K v O hv p) := { exists_pair_ne := (char_p.nontrivial_of_char_ne_one hp.1.ne_one).1, eq_zero_or_eq_zero_of_mul_eq_zero := λ f g hfg, by { simp_rw ← map_eq_zero at hfg ⊢, contrapose! hfg, rw valuation.map_mul, exact mul_ne_zero hfg.1 hfg.2 }, .. (infer_instance : comm_ring (pre_tilt K v O hv p)) } end pre_tilt /-- The tilt of a field, as defined in Perfectoid Spaces by Peter Scholze, as in [scholze2011perfectoid]. Given a field `K` with valuation `K → ℝ≥0` and ring of integers `O`, this is implemented as the fraction field of the perfection of `O/(p)`. -/ @[nolint has_inhabited_instance] def tilt := fraction_ring (pre_tilt K v O hv p) namespace tilt noncomputable instance : field (tilt K v O hv p) := fraction_ring.field end tilt end perfectoid
c8e8106354b2d51cfdeb6ff427f7cdc48133a453
b24beef0a8b1a8e92be756a25aa78e24908b2b14
/src/exercises_sources/wednesday/afternoon/algebraic_hierarchy.lean
6b71c1a1b82b526086af3b89f83dde37c6b50f82
[]
permissive
ChristopheMargerin/lftcm2020
14967e74cbe92a7b61d32d8130f32cfa09b5172b
589180047fa4fdfb3179636db58b0b0320549871
refs/heads/master
1,668,536,269,632
1,594,891,664,000
1,594,891,664,000
280,112,730
0
0
MIT
1,594,891,963,000
1,594,891,962,000
null
UTF-8
Lean
false
false
18,878
lean
/- This is a sorry-free file covering the material on Wednesday afternoon at LFTCM2020. It's how to build some algebraic structures in Lean -/ import data.rat.basic -- we'll need the rationals at the end of this file /- As a mathematician I essentially always start my Lean files with the following line: -/ import tactic /- That gives me access to all Lean's tactics (see https://leanprover-community.github.io/mathlib_docs/tactics.html) -/ /- ## The point of this file The idea of this file is to show how to build in Lean what the computer scientists call "an algebraic heirarchy", and what mathematicians call "groups, rings, fields, modules etc". Firstly, we will define groups, and develop a basic interface for groups. Then we will define rings, fields, modules, vector spaces, and just demonstrate that they are usable, rather than making a complete interface for all of them. Let's start with the theory of groups. Unfortunately Lean has groups already, so we will have to do everything in a namespace -/ namespace lftcm /- ... which means that now when we define `group`, it will actually be called `lftcm.group`. ## Notation typeclasses To make a term of type `has_mul G`, you need to give a map G^2 → G (or more precisely, a map `has_mul.mul : G → G → G`. Lean's notation `g * h` is notation for `has_mul.mul g h`. Furthermore, `has_mul` is a class. In short, this means that if you write `[has_mul G]` then `G` will magically have a multiplication called `*` (satisfying no axioms). Similarly `[has_one G]` gives you `has_one.one : G` with notation `1 : G`, and `[has_inv G]` gives you `has_inv.inv : G → G` with notation `g⁻¹ : G` ## Definition of a group If `G` is a type, equipped with `* : G^2 → G`, `1 : G` and `⁻¹ : G → G` then it's a group if it satisfies the group axioms. -/ -- `group G` is the type of group structures on a type `G`. -- first we ask for the structure class group (G : Type) extends has_mul G, has_one G, has_inv G := -- and then we ask for the axioms (mul_assoc : ∀ (a b c : G), a * b * c = a * (b * c)) (one_mul : ∀ (a : G), 1 * a = a) (mul_left_inv : ∀ (a : G), a⁻¹ * a = 1) /- Advantages of this approach: axioms look lovely. Disadvantage: what if I want the group law to be `+`?? I have embedded `has_mul` in the definition. Lean's solution: develop a `to_additive` metaprogram which translates all theorems about `group`s (with group law `*`) to theorems about `add_group`s (with group law `+`). We will not go into details here. -/ namespace group -- let G be a group variables {G : Type} [group G] /- Lemmas about groups are proved in this namespace. We already have some! All the group axioms are theorems in this namespace. Indeed we have just defined `group.mul_assoc : ∀ (a b c : G), a * b * c = a * (b * c)` `group.one_mul : ∀ (a : G), 1 * a = a` `group.mul_left_inv : ∀ (a : G), a⁻¹ * a = 1` Because we are in the `group` namespace, we don't need to write `group.` everywhere. Let's put some more theorems into the `group` namespace. We definitely need `mul_one` and `mul_right_inv`, and it's a fun exercise to get them. Here is a route: `mul_left_cancel : ∀ (a b c : G), a * b = a * c → b = c` `mul_eq_of_eq_inv_mul {a x y : G} : x = a⁻¹ * y → a * x = y` `mul_one (a : G) : a * 1 = a` `mul_right_inv (a : G) : a * a⁻¹ = 1` -/ lemma mul_left_cancel (a b c : G) (Habac : a * b = a * c) : b = c := calc b = 1 * b : by rw one_mul ... = (a⁻¹ * a) * b : by rw mul_left_inv ... = a⁻¹ * (a * b) : by sorry ... = a⁻¹ * (a * c) : by sorry ... = (a⁻¹ * a) * c : by sorry ... = 1 * c : by sorry ... = c : by sorry lemma mul_eq_of_eq_inv_mul {a x y : G} (h : x = a⁻¹ * y) : a * x = y := begin apply mul_left_cancel a⁻¹, -- ⊢ a⁻¹ * (a * x) = a⁻¹ * y sorry end /- So now we can finally prove `mul_one` and `mul_right_inv`. But before we start, let's learn a little bit about the simplifier. ## The `simp` tactic -- Lean's simplifier We have the theorems (axioms) `one_mul g : 1 * g = g` and `mul_left_inv g : g⁻¹ * g = 1`. Both of these theorems are of the form `A = B`, with `A` more complicated than `B`. This means that they are *perfect* theorems for the simplifier. Let's teach those theorems to the simplifier, by adding the `@[simp]` attribute to them. An "attribute" is just a tag which we attach to a theorem (or definition). -/ attribute [simp] one_mul mul_left_inv /- Now let's prove `mul_one` using the simplifier. This also a perfect `simp` lemma, so let's also add the `simp` tag to it. -/ @[simp] theorem mul_one (a : G) : a * 1 = a := begin apply mul_eq_of_eq_inv_mul, -- ⊢ 1 = a⁻¹ * a simp, end /- The simplifier solved `1 = a⁻¹ * a` because it knew `mul_left_inv`. Feel free to comment out the `attribute [simp] one_mul mul_left_inv` line above, and observe that the proof breaks. -/ -- see if you can get the simplifier to do this one too @[simp] theorem mul_right_inv (a : G) : a * a⁻¹ = 1 := begin sorry end -- Now here's a question. Can we train the simplifier to solve the following problem: --example (a b c d : G) : -- ((a * b)⁻¹ * a * 1⁻¹⁻¹⁻¹ * b⁻¹ * b * b * 1 * 1⁻¹)⁻¹ = (c⁻¹⁻¹ * d * d⁻¹ * 1⁻¹⁻¹ * c⁻¹⁻¹⁻¹)⁻¹⁻¹ := --by simp -- Remove the --'s and see that it fails. Let's see if we can get it to work. -- We start with two very natural `simp` lemmas. @[simp] lemma one_inv : (1 : G)⁻¹ = 1 := begin sorry end @[simp] lemma inv_inv (a : G) : a⁻¹⁻¹ = a := begin sorry end -- Here is a riskier looking `[simp]` lemma. attribute [simp] mul_assoc -- recall this says (a * b) * c = a * (b * c) -- The simplifier will now push all brackets to the right, which means -- that it's worth proving the following two lemmas and tagging -- them `[simp]`, so that we can still cancel a with a⁻¹ in these situations. @[simp] lemma inv_mul_cancel_left (a b : G) : a⁻¹ * (a * b) = b := begin sorry end @[simp] lemma mul_inv_cancel_left (a b : G) : a * (a⁻¹ * b) = b := begin sorry end -- Finally, let's make a `simp` lemma which enables us to -- reduce all inverses to inverses of variables @[simp] lemma mul_inv_rev (a b : G) : (a * b)⁻¹ = b⁻¹ * a⁻¹ := begin sorry end /- If you solved them all -- congratulations! You have just turned Lean's simplifier into a normalising confluent rewriting system for groups, following Knuth-Bendix. https://en.wikipedia.org/wiki/Confluence_(abstract_rewriting)#Motivating_examples In other words, the simplifier will now put any element of a free group into a canonical normal form, and can hence solve the word problem for free groups. -/ example (a b c d : G) : ((a * b)⁻¹ * a * 1⁻¹⁻¹⁻¹ * b⁻¹ * b * b * 1 * 1⁻¹)⁻¹ = (c⁻¹⁻¹ * d * d⁻¹ * 1⁻¹⁻¹ * c⁻¹⁻¹⁻¹)⁻¹⁻¹ := by simp -- Abstract example of the power of classes: we can define products of groups with instances instance (G : Type) [group G] (H : Type) [group H] : group (G × H) := { mul := λ k l, (k.1*l.1, k.2*l.2), one := (1,1), inv := λ k, (k.1⁻¹, k.2⁻¹), mul_assoc := begin intros a b c, cases a, cases b, cases c, ext; simp, end, one_mul := begin sorry end, mul_left_inv := begin sorry end } -- the type class inference system now knows that products of groups are groups example (G H K : Type) [group G] [group H] [group K] : group (G × H × K) := by apply_instance end group -- let's make a group of order two. -- First the elements {+1, -1} inductive mu2 | p1 : mu2 | m1 : mu2 namespace mu2 -- Now let's do some CS stuff: -- 1) prove it has decidable equality attribute [derive decidable_eq] mu2 -- 2) prove it is finite instance : fintype mu2 := ⟨⟨[mu2.p1, mu2.m1], by simp⟩, λ x, by cases x; simp⟩ -- now back to the maths. -- Define multiplication by doing all cases def mul : mu2 → mu2 → mu2 | p1 p1 := p1 | p1 m1 := m1 | m1 p1 := m1 | m1 m1 := p1 instance : has_mul mu2 := ⟨mul⟩ -- identity def one : mu2 := p1 -- notation instance : has_one mu2 := ⟨one⟩ -- inverse def inv : mu2 → mu2 := id -- notation instance : has_inv mu2 := ⟨inv⟩ -- currently we have notation but no axioms example : p1 * m1 * m1 = p1⁻¹ * p1 := rfl -- all true by definition -- now let's make it a group instance : group mu2 := begin -- first define the structure refine_struct { mul := mul, one := one, inv := inv }, -- now we have three goals (the axioms) all_goals {exact dec_trivial} end end mu2 -- Now let's build rings and modules and stuff (via monoids and add_comm_groups) -- a monoid is a group without inverses class monoid (M : Type) extends has_mul M, has_one M := (mul_assoc : ∀ (a b c : M), a * b * c = a * (b * c)) (one_mul : ∀ (a : M), 1 * a = a) (mul_one : ∀ (a : M), a * 1 = a) -- additive commutative groups from first principles class add_comm_group (A : Type) extends has_add A, has_zero A, has_neg A := (add_assoc : ∀ (a b c : A), a + b + c = a + (b + c)) (zero_add : ∀ (a : A), 0 + a = a) (add_left_neg : ∀ (a : A), -a + a = 0) (add_comm : ∀ a b : A, a + b = b + a) -- Notation for subtraction is handy to have; define a - b to be a + (-b) instance (A : Type) [add_comm_group A] : has_sub A := ⟨λ a b, a + -b⟩ -- rings are additive abelian groups and multiplicative monoids, -- with distributivity class ring (R : Type) extends monoid R, add_comm_group R := (mul_add : ∀ (a b c : R), a * (b + c) = a * b + a * c) (add_mul : ∀ (a b c : R), (a + b) * c = a * c + b * c) -- for commutative rings, add commutativity of multiplication class comm_ring (R : Type) extends ring R := (mul_comm : ∀ a b : R, a * b = b * a) /-- Typeclass for types with a scalar multiplication operation, denoted `•` (`\bu`) -/ class has_scalar (R : Type) (M : Type) := (smul : R → M → M) infixr ` • `:73 := has_scalar.smul -- modules for a ring class module (R : Type) [ring R] (M : Type) [add_comm_group M] extends has_scalar R M := (smul_add : ∀(r : R) (x y : M), r • (x + y) = r • x + r • y) (add_smul : ∀(r s : R) (x : M), (r + s) • x = r • x + s • x) (mul_smul : ∀ (r s : R) (x : M), (r * s) • x = r • s • x) (one_smul : ∀ x : M, (1 : R) • x = x) -- for fields we let ⁻¹ be defined on the entire field, and demand 0⁻¹ = 0 -- and that a⁻¹ * a = 1 for non-zero a. This is merely for convenience; -- one can easily check that it's mathematically equivalent to the usual -- definition of a field. class field (K : Type) extends comm_ring K, has_inv K := (zero_ne_one : (0 : K) ≠ 1) (mul_inv_cancel : ∀ {a : K}, a ≠ 0 → a * a⁻¹ = 1) (inv_zero : (0 : K)⁻¹ = 0) -- the type of vector spaces def vector_space (K : Type) [field K] (V : Type) [add_comm_group V] := module K V /- Exercise for the reader: define manifolds, schemes, perfectoid spaces in Lean. All have been done! As you can see, it is clearly *feasible*, although it does sometimes take time to get it right. It is all very much work in progress. The extraordinary thing is that although these computer theorem provers have been around for about 50 years, there has never been a serious effort to make the standard definitions used all over modern mathematics in one of them, and this is why these systems are rarely used in mathematics departments. Changing this is one of the goals of the Leanprover community. -/ /- Let's check that we can make the rational numbers into a field. Of course they are already a field in Lean, but remember that when we say `field` below, we mean our just-defined structure `lftcm.field`. -/ -- the rationals are a field (easy because all the work is done in the import) instance : field ℚ := { mul := (*), one := 1, mul_assoc := rat.mul_assoc, one_mul := rat.one_mul, mul_one := rat.mul_one, add := (+), zero := 0, neg := has_neg.neg, -- no () trickery for unary operators add_assoc := rat.add_assoc, zero_add := rat.zero_add, add_left_neg := rat.add_left_neg, add_comm := rat.add_comm, mul_add := rat.mul_add, add_mul := rat.add_mul, mul_comm := rat.mul_comm, inv := has_inv.inv, -- see neg zero_ne_one := rat.zero_ne_one, mul_inv_cancel := rat.mul_inv_cancel, inv_zero := inv_zero -- I don't know why rat.inv_zero was never explicitly defined } /- Below is evidence that we can prove basic theorems about these structures. Note however that it is a *complete pain* because we are *re-implementing* everything; `add_comm` defaults to Lean's version for Lean's `add_comm_group`s, so we have to explicitly write `add_comm_group.add_comm` to use our own version. The mathlib versions of these proofs are less ugly. -/ variables {A : Type} [add_comm_group A] lemma add_comm_group.add_left_cancel (a b c : A) (Habac : a + b = a + c) : b = c := begin rw ←add_comm_group.zero_add b, rw ←add_comm_group.add_left_neg a, rw add_comm_group.add_assoc, rw Habac, rw ←add_comm_group.add_assoc, rw add_comm_group.add_left_neg, rw add_comm_group.zero_add, end lemma add_comm_group.add_right_neg (a : A) : a + -a = 0 := begin rw add_comm_group.add_comm, rw add_comm_group.add_left_neg, end lemma add_comm_group.sub_eq_add_neg (a b : A) : a - b = a + -b := begin -- this is just our definition of subtraction refl end lemma add_comm_group.sub_self (a : A) : a - a = 0 := begin rw add_comm_group.sub_eq_add_neg, rw add_comm_group.add_comm, rw add_comm_group.add_left_neg, end lemma add_comm_group.neg_eq_of_add_eq_zero (a b : A) (h : a + b = 0) : -a = b := begin apply add_comm_group.add_left_cancel a, rw h, rw add_comm_group.add_right_neg, end lemma add_comm_group.add_zero (a : A) : a + 0 = a := begin rw add_comm_group.add_comm, rw add_comm_group.zero_add, end -- Now see if you can do some ring lemmas. variables {R : Type} [ring R] -- Note that annoyingly, because we have two conflicting `add_zero`s, -- Lean's and ours, we have to explicitly direct Lean to ours. lemma ring.mul_zero (r : R) : r * 0 = 0 := begin apply add_comm_group.add_left_cancel (r * 0), rw ←ring.mul_add, rw add_comm_group.add_zero, rw add_comm_group.add_zero, end lemma ring.mul_neg (a b : R) : a * -b = -(a * b) := begin sorry end lemma ring.mul_sub (R : Type) [comm_ring R] (r a b : R) : r * (a - b) = r * a - r * b := begin sorry end lemma comm_ring.sub_mul (R : Type) [comm_ring R] (r a b : R) : (a - b) * r = a * r - b * r := begin sorry end -- etc etc, for thousands of lines of mathlib, which develop the interface -- abelian groups, rings, commutative rings, modules, fields, vector spaces etc. end lftcm /- ## Advertisement Finished the natural number game? Have Lean installed? Want more games/exercises? Take a look at the following projects, many of which are ongoing but the first three of which are pretty much ready: *) The complex number game (complete, needs to be played within VS Code) https://github.com/ImperialCollegeLondon/complex-number-game To install, type `leanproject get ImperialCollegeLondon/complex-number-game` and then just open the levels in `src/complex`. *) Undergraduate level mathematics Lean puzzles (plenty of stuff here, and more appearing over the summer): https://github.com/ImperialCollegeLondon/Example-Lean-Projects `leanproject get ImperialCollegeLondon/Example-Lean-Projects` *) The max mini-game (a simple browser game like the natural number game) http://wwwf.imperial.ac.uk/~buzzard/xena/max_minigame/ (this is part of what will become the real number game, a game to teach series, sequences and limits etc like the natural number game): `leanproject get ImperialCollegeLondon/real-number-game` *) Some commutative algebra experiments (ongoing work to prove the Nullstellensatz, going slowly because I'm busy): https://github.com/ImperialCollegeLondon/M4P33/blob/1a179372db71ad6802d11eacbc1f02f327d55f8f/src/for_mathlib/commutative_algebra/Zariski_lemma.lean#L80-L81 `leanproject get ImperialCollegeLondon/M4P33` *) The group theory game (work in progress, expect more progress over the summer, as a couple of undergraduates are working on it) https://github.com/ImperialCollegeLondon/group-theory-game `leanproject get ImperialCollegeLondon/group-theory-game` *) Galois theory experiments https://github.com/ImperialCollegeLondon/P11-Galois-Theory `leanproject get ImperialCollegeLondon/P11-Galois-Theory` *) Beginnings of the theory of condensed sets (currently on hold because we need a good interface for abelian categories in mathlib) https://github.com/ImperialCollegeLondon/condensed-sets `leanproject get ImperialCollegeLondon/condensed-sets` ## The Xena Project Why do these projects exist? I (Kevin Buzzard) am interested in teaching undergraduates how to use Lean. I have been running a club at Imperial College London called the Xena Project for the last three years, I am proud that many Imperial mathematics undegraduates have contributed to Lean's maths library, and three of them (Chris Hughes, Kenny Lau, Amelia Livingston) have each contributed over 5,000 lines of code. It is non-trivial to get your work into such a polished state that it is acceptable to the mathlib maintainers. It is also very good practice. I am running Lean summer projects this summer, on a Discord server. If you know of any undergraduates who you think might be interested in Lean, please direct them to the Xena Project Discord! https://discord.gg/BgyVYgJ Undergraduates use Discord for lots of things, and seem to be more likely to use a Discord server than the Zulip chat. The Discord server is chaotic and full of off-topic material -- quite unlike the Lean Zulip server, which is professional and focussed. If you have a serious question about Lean, ask it on the Zulip chat! But if you know an undergraduate who is interested in Lean, they might be interested in the Discord server. We have meetings every Thursday evening (UK time), with live Lean coding and streaming, speedruns, there is music, people posting pictures of cats, Haikus, and so on. To a large extent it is run by undergraduates and PhD students. Over the summer (July and August 2020) there are also live Twitch talks at https://www.twitch.tv/kbuzzard , on Tuesdays 10am and Thursdays 4pm UK time (UTC+1), aimed at mathematics undergraduates. It is an informal place for undergraduates to hang out and meet other undergraduates who are interested in Lean. I believe that it is crucial to make undergraduates aware of computer proof verification systems, because one day (possibly a long time in the future, but one day) these things will cause a paradigm shift in the way mathematics is done, and the sooner young mathematicians learn about them, the sooner it will happen. Prove a theorem. Write a function. @XenaProject https://twitter.com/XenaProject -/
247ff0fdfe8862890d0eff5a77b8b8f8787aa59c
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/tactic/simps.lean
8b0279f2be0470a974dfc16cc76b016bee5dbf40
[ "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
46,720
lean
/- Copyright (c) 2019 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import algebra.group.to_additive import tactic.protected import data.sum /-! # simps attribute This file defines the `@[simps]` attribute, to automatically generate `simp` lemmas reducing a definition when projections are applied to it. ## Implementation Notes There are three attributes being defined here * `@[simps]` is the attribute for objects of a structure or instances of a class. It will automatically generate simplification lemmas for each projection of the object/instance that contains data. See the doc strings for `simps_attr` and `simps_cfg` for more details and configuration options. * `@[_simps_str]` is automatically added to structures that have been used in `@[simps]` at least once. This attribute contains the data of the projections used for this structure by all following invocations of `@[simps]`. * `@[notation_class]` should be added to all classes that define notation, like `has_mul` and `has_zero`. This specifies that the projections that `@[simps]` used are the projections from these notation classes instead of the projections of the superclasses. Example: if `has_mul` is tagged with `@[notation_class]` then the projection used for `semigroup` will be `λ α hα, @has_mul.mul α (@semigroup.to_has_mul α hα)` instead of `@semigroup.mul`. ## Tags structures, projections, simp, simplifier, generates declarations -/ open tactic expr option sum setup_tactic_parser declare_trace simps.verbose declare_trace simps.debug /-- Projection data for a single projection of a structure, consisting of the following fields: - the name used in the generated `simp` lemmas - an expression used by simps for the projection. It must be definitionally equal to an original projection (or a composition of multiple projections). These expressions can contain the universe parameters specified in the first argument of `simps_str_attr`. - a list of natural numbers, which is the projection number(s) that have to be applied to the expression. For example the list `[0, 1]` corresponds to applying the first projection of the structure, and then the second projection of the resulting structure (this assumes that the target of the first projection is a structure with at least two projections). The composition of these projections is required to be definitionally equal to the provided expression. - A boolean specifying whether `simp` lemmas are generated for this projection by default. - A boolean specifying whether this projection is written as prefix. -/ @[protect_proj, derive [has_reflect, inhabited]] meta structure projection_data := (name : name) (expr : expr) (proj_nrs : list ℕ) (is_default : bool) (is_prefix : bool) /-- Temporary projection data parsed from `initialize_simps_projections` before the expression matching this projection has been found. Only used internally in `simps_get_raw_projections`. -/ meta structure parsed_projection_data := (orig_name : name) -- name for this projection used in the structure definition (new_name : name) -- name for this projection used in the generated `simp` lemmas (is_default : bool) (is_prefix : bool) section open format meta instance : has_to_tactic_format projection_data := ⟨λ ⟨a, b, c, d, e⟩, (λ x, group $ nest 1 $ to_fmt "⟨" ++ to_fmt a ++ to_fmt "," ++ line ++ x ++ to_fmt "," ++ line ++ to_fmt c ++ to_fmt "," ++ line ++ to_fmt d ++ to_fmt "," ++ line ++ to_fmt e ++ to_fmt "⟩") <$> pp b⟩ meta instance : has_to_format parsed_projection_data := ⟨λ ⟨a, b, c, d⟩, group $ nest 1 $ to_fmt "⟨" ++ to_fmt a ++ to_fmt "," ++ line ++ to_fmt b ++ to_fmt "," ++ line ++ to_fmt c ++ to_fmt "," ++ line ++ to_fmt d ++ to_fmt "⟩"⟩ end /-- The type of rules that specify how metadata for projections in changes. See `initialize_simps_projection`. -/ abbreviation projection_rule := (name × name ⊕ name) × bool /-- The `@[_simps_str]` attribute specifies the preferred projections of the given structure, used by the `@[simps]` attribute. - This will usually be tagged by the `@[simps]` tactic. - You can also generate this with the command `initialize_simps_projections`. - To change the default value, see Note [custom simps projection]. - You are strongly discouraged to add this attribute manually. - The first argument is the list of names of the universe variables used in the structure - The second argument is a list that consists of the projection data for each projection. -/ @[user_attribute] meta def simps_str_attr : user_attribute unit (list name × list projection_data) := { name := `_simps_str, descr := "An attribute specifying the projection of the given structure.", parser := failed } /-- The `@[notation_class]` attribute specifies that this is a notation class, and this notation should be used instead of projections by @[simps]. * The first argument `tt` for notation classes and `ff` for classes applied to the structure, like `has_coe_to_sort` and `has_coe_to_fun` * The second argument is the name of the projection (by default it is the first projection of the structure) -/ @[user_attribute] meta def notation_class_attr : user_attribute unit (bool × option name) := { name := `notation_class, descr := "An attribute specifying that this is a notation class. Used by @[simps].", parser := prod.mk <$> (option.is_none <$> (tk "*")?) <*> ident? } attribute [notation_class] has_zero has_one has_add has_mul has_inv has_neg has_sub has_div has_dvd has_mod has_le has_lt has_append has_andthen has_union has_inter has_sdiff has_equiv has_subset has_ssubset has_emptyc has_insert has_singleton has_sep has_mem has_pow attribute [notation_class* coe_sort] has_coe_to_sort attribute [notation_class* coe_fn] has_coe_to_fun /-- Returns the projection information of a structure. -/ meta def projections_info (l : list projection_data) (pref : string) (str : name) : tactic format := do ⟨defaults, nondefaults⟩ ← return $ l.partition_map $ λ s, if s.is_default then inl s else inr s, to_print ← defaults.mmap $ λ s, to_string <$> let prefix_str := if s.is_prefix then "(prefix) " else "" in pformat!"Projection {prefix_str}{s.name}: {s.expr}", let print2 := string.join $ (nondefaults.map (λ nm : projection_data, to_string nm.1)).intersperse ", ", let to_print := to_print ++ if nondefaults.length = 0 then [] else ["No lemmas are generated for the projections: " ++ print2 ++ "."], let to_print := string.join $ to_print.intersperse "\n > ", return format!"[simps] > {pref} {str}:\n > {to_print}" /-- Auxiliary function of `get_composite_of_projections`. -/ meta def get_composite_of_projections_aux : Π (str : name) (proj : string) (x : expr) (pos : list ℕ) (args : list expr), tactic (expr × list ℕ) | str proj x pos args := do e ← get_env, projs ← e.structure_fields str, let proj_info := projs.map_with_index $ λ n p, (λ x, (x, n, p)) <$> proj.get_rest ("_" ++ p.last), when (proj_info.filter_map id = []) $ fail!"Failed to find constructor {proj.popn 1} in structure {str}.", (proj_rest, index, proj_nm) ← return (proj_info.filter_map id).ilast, str_d ← e.get str, let proj_e : expr := const (str ++ proj_nm) str_d.univ_levels, proj_d ← e.get (str ++ proj_nm), type ← infer_type x, let params := get_app_args type, let univs := proj_d.univ_params.zip type.get_app_fn.univ_levels, let new_x := (proj_e.instantiate_univ_params univs).mk_app $ params ++ [x], let new_pos := pos ++ [index], if proj_rest.is_empty then return (new_x.lambdas args, new_pos) else do type ← infer_type new_x, (type_args, tgt) ← open_pis_whnf type, let new_str := tgt.get_app_fn.const_name, get_composite_of_projections_aux new_str proj_rest (new_x.mk_app type_args) new_pos (args ++ type_args) /-- Given a structure `str` and a projection `proj`, that could be multiple nested projections (separated by `_`), returns an expression that is the composition of these projections and a list of natural numbers, that are the projection numbers of the applied projections. -/ meta def get_composite_of_projections (str : name) (proj : string) : tactic (expr × list ℕ) := do e ← get_env, str_d ← e.get str, let str_e : expr := const str str_d.univ_levels, type ← infer_type str_e, (type_args, tgt) ← open_pis_whnf type, let str_ap := str_e.mk_app type_args, x ← mk_local' `x binder_info.default str_ap, get_composite_of_projections_aux str ("_" ++ proj) x [] $ type_args ++ [x] /-- Get the projections used by `simps` associated to a given structure `str`. The returned information is also stored in a parameter of the attribute `@[_simps_str]`, which is given to `str`. If `str` already has this attribute, the information is read from this attribute instead. See the documentation for this attribute for the data this tactic returns. The returned universe levels are the universe levels of the structure. For the projections there are three cases * If the declaration `{structure_name}.simps.{projection_name}` has been declared, then the value of this declaration is used (after checking that it is definitionally equal to the actual projection. If you rename the projection name, the declaration should have the *new* projection name. * You can also declare a custom projection that is a composite of multiple projections. * Otherwise, for every class with the `notation_class` attribute, and the structure has an instance of that notation class, then the projection of that notation class is used for the projection that is definitionally equal to it (if there is such a projection). This means in practice that coercions to function types and sorts will be used instead of a projection, if this coercion is definitionally equal to a projection. Furthermore, for notation classes like `has_mul` and `has_zero` those projections are used instead of the corresponding projection. Projections for coercions and notation classes are not automatically generated if they are composites of multiple projections (for example when you use `extend` without the `old_structure_cmd`). * Otherwise, the projection of the structure is chosen. For example: ``simps_get_raw_projections env `prod`` gives the default projections ``` ([u, v], [prod.fst.{u v}, prod.snd.{u v}]) ``` while ``simps_get_raw_projections env `equiv`` gives ``` ([u_1, u_2], [λ α β, coe_fn, λ {α β} (e : α ≃ β), ⇑(e.symm), left_inv, right_inv]) ``` after declaring the coercion from `equiv` to function and adding the declaration ``` def equiv.simps.inv_fun {α β} (e : α ≃ β) : β → α := e.symm ``` Optionally, this command accepts three optional arguments: * If `trace_if_exists` the command will always generate a trace message when the structure already has the attribute `@[_simps_str]`. * The `rules` argument accepts a list of pairs `sum.inl (old_name, new_name)`. This is used to change the projection name `old_name` to the custom projection name `new_name`. Example: for the structure `equiv` the projection `to_fun` could be renamed `apply`. This name will be used for parsing and generating projection names. This argument is ignored if the structure already has an existing attribute. If an element of `rules` is of the form `sum.inr name`, this means that the projection `name` will not be applied by default. * if `trc` is true, this tactic will trace information. -/ -- if performance becomes a problem, possible heuristic: use the names of the projections to -- skip all classes that don't have the corresponding field. meta def simps_get_raw_projections (e : environment) (str : name) (trace_if_exists : bool := ff) (rules : list projection_rule := []) (trc := ff) : tactic (list name × list projection_data) := do let trc := trc || is_trace_enabled_for `simps.verbose, has_attr ← has_attribute' `_simps_str str, if has_attr then do data ← simps_str_attr.get_param str, -- We always print the projections when they already exists and are called by -- `initialize_simps_projections`. when (trace_if_exists || is_trace_enabled_for `simps.verbose) $ projections_info data.2 "Already found projection information for structure" str >>= trace, return data else do when trc trace!"[simps] > generating projection information for structure {str}.", when_tracing `simps.debug trace!"[simps] > Applying the rules {rules}.", d_str ← e.get str, let raw_univs := d_str.univ_params, let raw_levels := level.param <$> raw_univs, /- Figure out projections, including renamings. The information for a projection is (before we figure out the `expr` of the projection: `(original name, given name, is default, is prefix)`. The first projections are always the actual projections of the structure, but `rules` could specify custom projections that are compositions of multiple projections. -/ projs ← e.structure_fields str, let projs : list parsed_projection_data := projs.map $ λ nm, ⟨nm, nm, tt, ff⟩, let projs : list parsed_projection_data := rules.foldl (λ projs rule, match rule with | (inl (old_nm, new_nm), is_prefix) := if old_nm ∈ projs.map (λ x, x.new_name) then projs.map $ λ proj, if proj.new_name = old_nm then { new_name := new_nm, is_prefix := is_prefix, ..proj } else proj else projs ++ [⟨old_nm, new_nm, tt, is_prefix⟩] | (inr nm, is_prefix) := if nm ∈ projs.map (λ x, x.new_name) then projs.map $ λ proj, if proj.new_name = nm then { is_default := ff, is_prefix := is_prefix, ..proj } else proj else projs ++ [⟨nm, nm, ff, is_prefix⟩] end) projs, when_tracing `simps.debug trace!"[simps] > Projection info after applying the rules: {projs}.", when ¬ (projs.map $ λ x, x.new_name : list name).nodup $ fail $ "Invalid projection names. Two projections have the same name. This is likely because a custom composition of projections was given the same name as an " ++ "existing projection. Solution: rename the existing projection (before renaming the custom " ++ "projection).", /- Define the raw expressions for the projections, by default as the projections (as an expression), but this can be overriden by the user. -/ raw_exprs_and_nrs ← projs.mmap $ λ ⟨orig_nm, new_nm, _, _⟩, do { (raw_expr, nrs) ← get_composite_of_projections str orig_nm.last, custom_proj ← do { decl ← e.get (str ++ `simps ++ new_nm.last), let custom_proj := decl.value.instantiate_univ_params $ decl.univ_params.zip raw_levels, when trc trace! "[simps] > found custom projection for {new_nm}:\n > {custom_proj}", return custom_proj } <|> return raw_expr, is_def_eq custom_proj raw_expr <|> -- if the type of the expression is different, we show a different error message, because -- that is more likely going to be helpful. do { custom_proj_type ← infer_type custom_proj, raw_expr_type ← infer_type raw_expr, b ← succeeds (is_def_eq custom_proj_type raw_expr_type), if b then fail!"Invalid custom projection:\n {custom_proj} Expression is not definitionally equal to\n {raw_expr}" else fail!"Invalid custom projection:\n {custom_proj} Expression has different type than {str ++ orig_nm}. Given type:\n {custom_proj_type} Expected type:\n {raw_expr_type}" }, return (custom_proj, nrs) }, let raw_exprs := raw_exprs_and_nrs.map prod.fst, /- Check for other coercions and type-class arguments to use as projections instead. -/ (args, _) ← open_pis d_str.type, let e_str := (expr.const str raw_levels).mk_app args, automatic_projs ← attribute.get_instances `notation_class, raw_exprs ← automatic_projs.mfoldl (λ (raw_exprs : list expr) class_nm, do { (is_class, proj_nm) ← notation_class_attr.get_param class_nm, proj_nm ← proj_nm <|> (e.structure_fields_full class_nm).map list.head, /- For this class, find the projection. `raw_expr` is the projection found applied to `args`, and `lambda_raw_expr` has the arguments `args` abstracted. -/ (raw_expr, lambda_raw_expr) ← if is_class then (do guard $ args.length = 1, let e_inst_type := (const class_nm raw_levels).mk_app args, (hyp, e_inst) ← try_for 1000 (mk_conditional_instance e_str e_inst_type), raw_expr ← mk_mapp proj_nm [args.head, e_inst], clear hyp, -- Note: `expr.bind_lambda` doesn't give the correct type raw_expr_lambda ← lambdas [hyp] raw_expr, return (raw_expr, raw_expr_lambda.lambdas args)) else (do e_inst_type ← to_expr (((const class_nm []).app (pexpr.of_expr e_str)).app ``(_)), e_inst ← try_for 1000 (mk_instance e_inst_type), raw_expr ← mk_mapp proj_nm [e_str, none, e_inst], return (raw_expr, raw_expr.lambdas args)), raw_expr_whnf ← whnf raw_expr, let relevant_proj := raw_expr_whnf.binding_body.get_app_fn.const_name, /- Use this as projection, if the function reduces to a projection, and this projection has not been overrriden by the user. -/ guard $ projs.any $ λ x, x.1 = relevant_proj.last ∧ ¬ e.contains (str ++ `simps ++ x.new_name.last), let pos := projs.find_index (λ x, x.1 = relevant_proj.last), when trc trace! " > using {proj_nm} instead of the default projection {relevant_proj.last}.", when_tracing `simps.debug trace!"[simps] > The raw projection is:\n {lambda_raw_expr}", return $ raw_exprs.update_nth pos lambda_raw_expr } <|> return raw_exprs) raw_exprs, let positions := raw_exprs_and_nrs.map prod.snd, let proj_names := projs.map (λ x, x.new_name), let defaults := projs.map (λ x, x.is_default), let prefixes := projs.map (λ x, x.is_prefix), let projs := proj_names.zip_with5 projection_data.mk raw_exprs positions defaults prefixes, /- make all proof non-default. -/ projs ← projs.mmap $ λ proj, is_proof proj.expr >>= λ b, return $ if b then { is_default := ff, .. proj } else proj, when trc $ projections_info projs "generated projections for" str >>= trace, simps_str_attr.set str (raw_univs, projs) tt, when_tracing `simps.debug trace! "[simps] > Generated raw projection data: \n{(raw_univs, projs)}", return (raw_univs, projs) /-- Parse a rule for `initialize_simps_projections`. It is either `<name>→<name>` or `-<name>`, possibly following by `as_prefix`.-/ meta def simps_parse_rule : parser projection_rule := prod.mk <$> ((λ x y, inl (x, y)) <$> ident <*> (tk "->" >> ident) <|> inr <$> (tk "-" >> ident)) <*> is_some <$> (tk "as_prefix")? /-- You can specify custom projections for the `@[simps]` attribute. To do this for the projection `my_structure.original_projection` by adding a declaration `my_structure.simps.my_projection` that is definitionally equal to `my_structure.original_projection` but has the projection in the desired (simp-normal) form. Then you can call ``` initialize_simps_projections (original_projection → my_projection, ...) ``` to register this projection. See `initialize_simps_projections_cmd` for more information. You can also specify custom projections that are definitionally equal to a composite of multiple projections. This is often desirable when extending structures (without `old_structure_cmd`). `has_coe_to_fun` and notation class (like `has_mul`) instances will be automatically used, if they are definitionally equal to a projection of the structure (but not when they are equal to the composite of multiple projections). -/ library_note "custom simps projection" /-- This command specifies custom names and custom projections for the simp attribute `simps_attr`. * You can specify custom names by writing e.g. `initialize_simps_projections equiv (to_fun → apply, inv_fun → symm_apply)`. * See Note [custom simps projection] and the examples below for information how to declare custom projections. * If no custom projection is specified, the projection will be `coe_fn`/`⇑` if a `has_coe_to_fun` instance has been declared, or the notation of a notation class (like `has_mul`) if such an instance is available. If none of these cases apply, the projection itself will be used. * You can disable a projection by default by running `initialize_simps_projections equiv (-inv_fun)` This will ensure that no simp lemmas are generated for this projection, unless this projection is explicitly specified by the user. * If you want the projection name added as a prefix in the generated lemma name, you can add the `as_prefix` modifier: `initialize_simps_projections equiv (to_fun → coe as_prefix)` Note that this does not influence the parsing of projection names: if you have a declaration `foo` and you want to apply the projections `snd`, `coe` (which is a prefix) and `fst`, in that order you can run `@[simps snd_coe_fst] def foo ...` and this will generate a lemma with the name `coe_foo_snd_fst`. * Run `initialize_simps_projections?` (or `set_option trace.simps.verbose true`) to see the generated projections. * You can declare a new name for a projection that is the composite of multiple projections, e.g. ``` structure A := (proj : ℕ) structure B extends A initialize_simps_projections? B (to_A_proj → proj, -to_A) ``` You can also make your custom projection that is definitionally equal to a composite of projections. In this case, coercions and notation classes are not automatically recognized, and should be manually given by giving a custom projection. This is especially useful when extending a structure (without `old_structure_cmd`). In the above example, it is desirable to add `-to_A`, so that `@[simps]` doesn't automatically apply the `B.to_A` projection and then recursively the `A.proj` projection in the lemmas it generates. If you want to get both the `foo_proj` and `foo_to_A` simp lemmas, you can use `@[simps, simps to_A]`. * Running `initialize_simps_projections my_struc` without arguments is not necessary, it has the same effect if you just add `@[simps]` to a declaration. * If you do anything to change the default projections, make sure to call either `@[simps]` or `initialize_simps_projections` in the same file as the structure declaration. Otherwise, you might have a file that imports the structure, but not your custom projections. Some common uses: * If you define a new homomorphism-like structure (like `mul_hom`) you can just run `initialize_simps_projections` after defining the `has_coe_to_fun` instance ``` instance {mM : has_mul M} {mN : has_mul N} : has_coe_to_fun (mul_hom M N) := ... initialize_simps_projections mul_hom (to_fun → apply) ``` This will generate `foo_apply` lemmas for each declaration `foo`. * If you prefer `coe_foo` lemmas that state equalities between functions, use `initialize_simps_projections mul_hom (to_fun → coe as_prefix)` In this case you have to use `@[simps {fully_applied := ff}]` or equivalently `@[simps as_fn]` whenever you call `@[simps]`. * You can also initialize to use both, in which case you have to choose which one to use by default, by using either of the following ``` initialize_simps_projections mul_hom (to_fun → apply, to_fun → coe, -coe as_prefix) initialize_simps_projections mul_hom (to_fun → apply, to_fun → coe as_prefix, -apply) ``` In the first case, you can get both lemmas using `@[simps, simps coe as_fn]` and in the second case you can get both lemmas using `@[simps as_fn, simps apply]`. * If your new homomorphism-like structure extends another structure (without `old_structure_cmd`) (like `rel_embedding`), then you have to specify explicitly that you want to use a coercion as a custom projection. For example ``` def rel_embedding.simps.apply (h : r ↪r s) : α → β := h initialize_simps_projections rel_embedding (to_embedding_to_fun → apply, -to_embedding) ``` * If you have an isomorphism-like structure (like `equiv`) you often want to define a custom projection for the inverse: ``` def equiv.simps.symm_apply (e : α ≃ β) : β → α := e.symm initialize_simps_projections equiv (to_fun → apply, inv_fun → symm_apply) ``` -/ @[user_command] meta def initialize_simps_projections_cmd (_ : parse $ tk "initialize_simps_projections") : parser unit := do env ← get_env, trc ← is_some <$> (tk "?")?, ns ← (prod.mk <$> ident <*> (tk "(" >> sep_by (tk ",") simps_parse_rule <* tk ")")?)*, ns.mmap' $ λ data, do nm ← resolve_constant data.1, simps_get_raw_projections env nm tt (data.2.get_or_else []) trc add_tactic_doc { name := "initialize_simps_projections", category := doc_category.cmd, decl_names := [`initialize_simps_projections_cmd], tags := ["simplification"] } /-- Configuration options for the `@[simps]` attribute. * `attrs` specifies the list of attributes given to the generated lemmas. Default: ``[`simp]``. The attributes can be either basic attributes, or user attributes without parameters. There are two attributes which `simps` might add itself: * If ``[`simp]`` is in the list, then ``[`_refl_lemma]`` is added automatically if appropriate. * If the definition is marked with `@[to_additive ...]` then all generated lemmas are marked with `@[to_additive]`. This is governed by the `add_additive` configuration option. * if `simp_rhs` is `tt` then the right-hand-side of the generated lemmas will be put in simp-normal form. More precisely: `dsimp, simp` will be called on all these expressions. See note [dsimp, simp]. * `type_md` specifies how aggressively definitions are unfolded in the type of expressions for the purposes of finding out whether the type is a function type. Default: `instances`. This will unfold coercion instances (so that a coercion to a function type is recognized as a function type), but not declarations like `set`. * `rhs_md` specifies how aggressively definition in the declaration are unfolded for the purposes of finding out whether it is a constructor. Default: `none` Exception: `@[simps]` will automatically add the options `{rhs_md := semireducible, simp_rhs := tt}` if the given definition is not a constructor with the given reducibility setting for `rhs_md`. * If `fully_applied` is `ff` then the generated `simp` lemmas will be between non-fully applied terms, i.e. equalities between functions. This does not restrict the recursive behavior of `@[simps]`, so only the "final" projection will be non-fully applied. However, it can be used in combination with explicit field names, to get a partially applied intermediate projection. * The option `not_recursive` contains the list of names of types for which `@[simps]` doesn't recursively apply projections. For example, given an equivalence `α × β ≃ β × α` one usually wants to only apply the projections for `equiv`, and not also those for `×`. This option is only relevant if no explicit projection names are given as argument to `@[simps]`. * The option `trace` is set to `tt` when you write `@[simps?]`. In this case, the attribute will print all generated lemmas. It is almost the same as setting the option `trace.simps.verbose`, except that it doesn't print information about the found projections. * if `add_additive` is `some nm` then `@[to_additive]` is added to the generated lemma. This option is automatically set to `tt` when the original declaration was tagged with `@[to_additive, simps]` (in that order), where `nm` is the additive name of the original declaration. -/ @[derive [has_reflect, inhabited]] structure simps_cfg := (attrs := [`simp]) (simp_rhs := ff) (type_md := transparency.instances) (rhs_md := transparency.none) (fully_applied := tt) (not_recursive := [`prod, `pprod]) (trace := ff) (add_additive := @none name) /-- A common configuration for `@[simps]`: generate equalities between functions instead equalities between fully applied expressions. -/ def as_fn : simps_cfg := {fully_applied := ff} /-- A common configuration for `@[simps]`: don't tag the generated lemmas with `@[simp]`. -/ def lemmas_only : simps_cfg := {attrs := []} /-- Get the projections of a structure used by `@[simps]` applied to the appropriate arguments. Returns a list of tuples ``` (corresponding right-hand-side, given projection name, projection expression, projection numbers, used by default, is prefix) ``` (where all fields except the first are packed in a `projection_data` structure) one for each projection. The given projection name is the name for the projection used by the user used to generate (and parse) projection names. For example, in the structure Example 1: ``simps_get_projection_exprs env `(α × β) `(⟨x, y⟩)`` will give the output ``` [(`(x), `fst, `(@prod.fst.{u v} α β), [0], tt, ff), (`(y), `snd, `(@prod.snd.{u v} α β), [1], tt, ff)] ``` Example 2: ``simps_get_projection_exprs env `(α ≃ α) `(⟨id, id, λ _, rfl, λ _, rfl⟩)`` will give the output ``` [(`(id), `apply, `(coe), [0], tt, ff), (`(id), `symm_apply, `(λ f, ⇑f.symm), [1], tt, ff), ..., ...] ``` -/ meta def simps_get_projection_exprs (e : environment) (tgt : expr) (rhs : expr) (cfg : simps_cfg) : tactic $ list $ expr × projection_data := do let params := get_app_args tgt, -- the parameters of the structure (params.zip $ (get_app_args rhs).take params.length).mmap' (λ ⟨a, b⟩, is_def_eq a b) <|> fail "unreachable code (1)", let str := tgt.get_app_fn.const_name, let rhs_args := (get_app_args rhs).drop params.length, -- the fields of the object (raw_univs, proj_data) ← simps_get_raw_projections e str ff [] cfg.trace, let univs := raw_univs.zip tgt.get_app_fn.univ_levels, let new_proj_data : list $ expr × projection_data := proj_data.map $ λ proj, (rhs_args.inth proj.proj_nrs.head, { expr := (proj.expr.instantiate_univ_params univs).instantiate_lambdas_or_apps params, proj_nrs := proj.proj_nrs.tail, .. proj }), return new_proj_data /-- Add a lemma with `nm` stating that `lhs = rhs`. `type` is the type of both `lhs` and `rhs`, `args` is the list of local constants occurring, and `univs` is the list of universe variables. -/ meta def simps_add_projection (nm : name) (type lhs rhs : expr) (args : list expr) (univs : list name) (cfg : simps_cfg) : tactic unit := do when_tracing `simps.debug trace! "[simps] > Planning to add the equality\n > {lhs} = ({rhs} : {type})", lvl ← get_univ_level type, -- simplify `rhs` if `cfg.simp_rhs` is true (rhs, prf) ← do { guard cfg.simp_rhs, rhs' ← rhs.dsimp {fail_if_unchanged := ff}, when_tracing `simps.debug $ when (rhs ≠ rhs') trace! "[simps] > `dsimp` simplified rhs to\n > {rhs'}", (rhsprf1, rhsprf2, ns) ← rhs'.simp {fail_if_unchanged := ff}, when_tracing `simps.debug $ when (rhs' ≠ rhsprf1) trace! "[simps] > `simp` simplified rhs to\n > {rhsprf1}", return (prod.mk rhsprf1 rhsprf2) } <|> return (rhs, const `eq.refl [lvl] type lhs), let eq_ap := const `eq [lvl] type lhs rhs, decl_name ← get_unused_decl_name nm, let decl_type := eq_ap.pis args, let decl_value := prf.lambdas args, let decl := declaration.thm decl_name univs decl_type (pure decl_value), when cfg.trace trace! "[simps] > adding projection {decl_name}:\n > {decl_type}", decorate_error ("Failed to add projection lemma " ++ decl_name.to_string ++ ". Nested error:") $ add_decl decl, b ← succeeds $ is_def_eq lhs rhs, when (b ∧ `simp ∈ cfg.attrs) (set_basic_attribute `_refl_lemma decl_name tt), cfg.attrs.mmap' $ λ nm, set_attribute nm decl_name tt, when cfg.add_additive.is_some $ to_additive.attr.set decl_name ⟨ff, cfg.trace, cfg.add_additive.iget, none, tt⟩ tt /-- Derive lemmas specifying the projections of the declaration. If `todo` is non-empty, it will generate exactly the names in `todo`. `to_apply` is non-empty after a custom projection that is a composition of multiple projections was just used. In that case we need to apply these projections before we continue changing lhs. -/ meta def simps_add_projections : Π (e : environment) (nm : name) (type lhs rhs : expr) (args : list expr) (univs : list name) (must_be_str : bool) (cfg : simps_cfg) (todo : list string) (to_apply : list ℕ), tactic unit | e nm type lhs rhs args univs must_be_str cfg todo to_apply := do -- we don't want to unfold non-reducible definitions (like `set`) to apply more arguments when_tracing `simps.debug trace! "[simps] > Type of the expression before normalizing: {type}", (type_args, tgt) ← open_pis_whnf type cfg.type_md, when_tracing `simps.debug trace!"[simps] > Type after removing pi's: {tgt}", tgt ← whnf tgt, when_tracing `simps.debug trace!"[simps] > Type after reduction: {tgt}", let new_args := args ++ type_args, let lhs_ap := lhs.instantiate_lambdas_or_apps type_args, let rhs_ap := rhs.instantiate_lambdas_or_apps type_args, let str := tgt.get_app_fn.const_name, /- We want to generate the current projection if it is in `todo` -/ let todo_next := todo.filter (≠ ""), /- Don't recursively continue if `str` is not a structure or if the structure is in `not_recursive`. -/ if e.is_structure str ∧ ¬(todo = [] ∧ str ∈ cfg.not_recursive ∧ ¬must_be_str) then do [intro] ← return $ e.constructors_of str | fail "unreachable code (3)", rhs_whnf ← whnf rhs_ap cfg.rhs_md, (rhs_ap, todo_now) ← -- `todo_now` means that we still have to generate the current simp lemma if ¬ is_constant_of rhs_ap.get_app_fn intro ∧ is_constant_of rhs_whnf.get_app_fn intro then /- If this was a desired projection, we want to apply it before taking the whnf. However, if the current field is an eta-expansion (see below), we first want to eta-reduce it and only then construct the projection. This makes the flow of this function messy. -/ when ("" ∈ todo ∧ to_apply = []) (if cfg.fully_applied then simps_add_projection nm tgt lhs_ap rhs_ap new_args univs cfg else simps_add_projection nm type lhs rhs args univs cfg) >> return (rhs_whnf, ff) else return (rhs_ap, "" ∈ todo ∧ to_apply = []), if is_constant_of (get_app_fn rhs_ap) intro then do -- if the value is a constructor application proj_info ← simps_get_projection_exprs e tgt rhs_ap cfg, when_tracing `simps.debug trace!"[simps] > Raw projection information:\n {proj_info}", eta ← rhs_ap.is_eta_expansion, -- check whether `rhs_ap` is an eta-expansion let rhs_ap := eta.lhoare rhs_ap, -- eta-reduce `rhs_ap` /- As a special case, we want to automatically generate the current projection if `rhs_ap` was an eta-expansion. Also, when this was a desired projection, we need to generate the current projection if we haven't done it above. -/ when (todo_now ∨ (todo = [] ∧ eta.is_some ∧ to_apply = [])) $ if cfg.fully_applied then simps_add_projection nm tgt lhs_ap rhs_ap new_args univs cfg else simps_add_projection nm type lhs rhs args univs cfg, /- If we are in the middle of a composite projection. -/ when (to_apply ≠ []) $ do { ⟨new_rhs, proj, proj_expr, proj_nrs, is_default, is_prefix⟩ ← return $ proj_info.inth to_apply.head, new_type ← infer_type new_rhs, when_tracing `simps.debug trace!"[simps] > Applying a custom composite projection. Current lhs: > {lhs_ap}", simps_add_projections e nm new_type lhs_ap new_rhs new_args univs ff cfg todo to_apply.tail }, /- We stop if no further projection is specified or if we just reduced an eta-expansion and we automatically choose projections -/ when ¬(to_apply ≠ [] ∨ todo = [""] ∨ (eta.is_some ∧ todo = [])) $ do let projs : list name := proj_info.map $ λ x, x.snd.name, let todo := if to_apply = [] then todo_next else todo, -- check whether all elements in `todo` have a projection as prefix guard (todo.all $ λ x, projs.any $ λ proj, ("_" ++ proj.last).is_prefix_of x) <|> let x := (todo.find $ λ x, projs.all $ λ proj, ¬ ("_" ++ proj.last).is_prefix_of x).iget, simp_lemma := nm.append_suffix x, needed_proj := (x.split_on '_').tail.head in fail! "Invalid simp lemma {simp_lemma}. Structure {str} does not have projection {needed_proj}. The known projections are: {projs} You can also see this information by running `initialize_simps_projections? {str}`. Note: these projection names might not correspond to the projection names of the structure.", proj_info.mmap_with_index' $ λ proj_nr ⟨new_rhs, proj, proj_expr, proj_nrs, is_default, is_prefix⟩, do new_type ← infer_type new_rhs, let new_todo := todo.filter_map $ λ x, x.get_rest ("_" ++ proj.last), -- we only continue with this field if it is non-propositional or mentioned in todo when ((is_default ∧ todo = []) ∨ new_todo ≠ []) $ do let new_lhs := proj_expr.instantiate_lambdas_or_apps [lhs_ap], let new_nm := nm.append_to_last proj.last is_prefix, let new_cfg := { add_additive := cfg.add_additive.map $ λ nm, nm.append_to_last (to_additive.guess_name proj.last) is_prefix, ..cfg }, when_tracing `simps.debug trace!"[simps] > Recursively add projections for: > {new_lhs}", simps_add_projections e new_nm new_type new_lhs new_rhs new_args univs ff new_cfg new_todo proj_nrs -- if I'm about to run into an error, try to set the transparency for `rhs_md` higher. else if cfg.rhs_md = transparency.none ∧ (must_be_str ∨ todo_next ≠ [] ∨ to_apply ≠ []) then do when cfg.trace trace! "[simps] > The given definition is not a constructor application: > {rhs_ap} > Retrying with the options {{ rhs_md := semireducible, simp_rhs := tt}.", simps_add_projections e nm type lhs rhs args univs must_be_str { rhs_md := semireducible, simp_rhs := tt, ..cfg} todo to_apply else do when (to_apply ≠ []) $ fail!"Invalid simp lemma {nm}. The given definition is not a constructor application:\n {rhs_ap}", when must_be_str $ fail!"Invalid `simps` attribute. The body is not a constructor application:\n {rhs_ap}", when (todo_next ≠ []) $ fail!"Invalid simp lemma {nm.append_suffix todo_next.head}. The given definition is not a constructor application:\n {rhs_ap}", if cfg.fully_applied then simps_add_projection nm tgt lhs_ap rhs_ap new_args univs cfg else simps_add_projection nm type lhs rhs args univs cfg else do when must_be_str $ fail!"Invalid `simps` attribute. Target {str} is not a structure", when (todo_next ≠ [] ∧ str ∉ cfg.not_recursive) $ let first_todo := todo_next.head in fail!"Invalid simp lemma {nm.append_suffix first_todo}. Projection {(first_todo.split_on '_').tail.head} doesn't exist, because target is not a structure.", if cfg.fully_applied then simps_add_projection nm tgt lhs_ap rhs_ap new_args univs cfg else simps_add_projection nm type lhs rhs args univs cfg /-- `simps_tac` derives `simp` lemmas for all (nested) non-Prop projections of the declaration. If `todo` is non-empty, it will generate exactly the names in `todo`. If `short_nm` is true, the generated names will only use the last projection name. If `trc` is true, trace as if `trace.simps.verbose` is true. -/ meta def simps_tac (nm : name) (cfg : simps_cfg := {}) (todo : list string := []) (trc := ff) : tactic unit := do e ← get_env, d ← e.get nm, let lhs : expr := const d.to_name d.univ_levels, let todo := todo.erase_dup.map $ λ proj, "_" ++ proj, let cfg := { trace := cfg.trace || is_trace_enabled_for `simps.verbose || trc, ..cfg }, b ← has_attribute' `to_additive nm, cfg ← if b then do { dict ← to_additive.aux_attr.get_cache, when cfg.trace trace!"[simps] > @[to_additive] will be added to all generated lemmas.", return { add_additive := dict.find nm, ..cfg } } else return cfg, simps_add_projections e nm d.type lhs d.value [] d.univ_params tt cfg todo [] /-- The parser for the `@[simps]` attribute. -/ meta def simps_parser : parser (bool × list string × simps_cfg) := do /- note: we don't check whether the user has written a nonsense namespace in an argument. -/ prod.mk <$> is_some <$> (tk "?")? <*> (prod.mk <$> many (name.last <$> ident) <*> (do some e ← parser.pexpr? | return {}, eval_pexpr simps_cfg e)) /-- The `@[simps]` attribute automatically derives lemmas specifying the projections of this declaration. Example: ```lean @[simps] def foo : ℕ × ℤ := (1, 2) ``` derives two `simp` lemmas: ```lean @[simp] lemma foo_fst : foo.fst = 1 @[simp] lemma foo_snd : foo.snd = 2 ``` * It does not derive `simp` lemmas for the prop-valued projections. * It will automatically reduce newly created beta-redexes, but will not unfold any definitions. * If the structure has a coercion to either sorts or functions, and this is defined to be one of the projections, then this coercion will be used instead of the projection. * If the structure is a class that has an instance to a notation class, like `has_mul`, then this notation is used instead of the corresponding projection. * You can specify custom projections, by giving a declaration with name `{structure_name}.simps.{projection_name}`. See Note [custom simps projection]. Example: ```lean def equiv.simps.inv_fun (e : α ≃ β) : β → α := e.symm @[simps] def equiv.trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ := ⟨e₂ ∘ e₁, e₁.symm ∘ e₂.symm⟩ ``` generates ``` @[simp] lemma equiv.trans_to_fun : ∀ {α β γ} (e₁ e₂) (a : α), ⇑(e₁.trans e₂) a = (⇑e₂ ∘ ⇑e₁) a @[simp] lemma equiv.trans_inv_fun : ∀ {α β γ} (e₁ e₂) (a : γ), ⇑((e₁.trans e₂).symm) a = (⇑(e₁.symm) ∘ ⇑(e₂.symm)) a ``` * You can specify custom projection names, by specifying the new projection names using `initialize_simps_projections`. Example: `initialize_simps_projections equiv (to_fun → apply, inv_fun → symm_apply)`. See `initialize_simps_projections_cmd` for more information. * If one of the fields itself is a structure, this command will recursively create `simp` lemmas for all fields in that structure. * Exception: by default it will not recursively create `simp` lemmas for fields in the structures `prod` and `pprod`. You can give explicit projection names or change the value of `simps_cfg.not_recursive` to override this behavior. Example: ```lean structure my_prod (α β : Type*) := (fst : α) (snd : β) @[simps] def foo : prod ℕ ℕ × my_prod ℕ ℕ := ⟨⟨1, 2⟩, 3, 4⟩ ``` generates ```lean @[simp] lemma foo_fst : foo.fst = (1, 2) @[simp] lemma foo_snd_fst : foo.snd.fst = 3 @[simp] lemma foo_snd_snd : foo.snd.snd = 4 ``` * You can use `@[simps proj1 proj2 ...]` to only generate the projection lemmas for the specified projections. * Recursive projection names can be specified using `proj1_proj2_proj3`. This will create a lemma of the form `foo.proj1.proj2.proj3 = ...`. Example: ```lean structure my_prod (α β : Type*) := (fst : α) (snd : β) @[simps fst fst_fst snd] def foo : prod ℕ ℕ × my_prod ℕ ℕ := ⟨⟨1, 2⟩, 3, 4⟩ ``` generates ```lean @[simp] lemma foo_fst : foo.fst = (1, 2) @[simp] lemma foo_fst_fst : foo.fst.fst = 1 @[simp] lemma foo_snd : foo.snd = {fst := 3, snd := 4} ``` * If one of the values is an eta-expanded structure, we will eta-reduce this structure. Example: ```lean structure equiv_plus_data (α β) extends α ≃ β := (data : bool) @[simps] def bar {α} : equiv_plus_data α α := { data := tt, ..equiv.refl α } ``` generates the following: ```lean @[simp] lemma bar_to_equiv : ∀ {α : Sort*}, bar.to_equiv = equiv.refl α @[simp] lemma bar_data : ∀ {α : Sort*}, bar.data = tt ``` This is true, even though Lean inserts an eta-expanded version of `equiv.refl α` in the definition of `bar`. * For configuration options, see the doc string of `simps_cfg`. * The precise syntax is `('simps' ident* e)`, where `e` is an expression of type `simps_cfg`. * `@[simps]` reduces let-expressions where necessary. * When option `trace.simps.verbose` is true, `simps` will print the projections it finds and the lemmas it generates. The same can be achieved by using `@[simps?]`, except that in this case it will not print projection information. * Use `@[to_additive, simps]` to apply both `to_additive` and `simps` to a definition, making sure that `simps` comes after `to_additive`. This will also generate the additive versions of all `simp` lemmas. -/ /- If one of the fields is a partially applied constructor, we will eta-expand it (this likely never happens, so is not included in the official doc). -/ @[user_attribute] meta def simps_attr : user_attribute unit (bool × list string × simps_cfg) := { name := `simps, descr := "Automatically derive lemmas specifying the projections of this declaration.", parser := simps_parser, after_set := some $ λ n _ persistent, do guard persistent <|> fail "`simps` currently cannot be used as a local attribute", (trc, todo, cfg) ← simps_attr.get_param n, simps_tac n cfg todo trc } add_tactic_doc { name := "simps", category := doc_category.attr, decl_names := [`simps_attr], tags := ["simplification"] }
ad24faa32673bb70b7e93f509ebf3716776670ee
63abd62053d479eae5abf4951554e1064a4c45b4
/src/category_theory/limits/cones.lean
7f43d1265ac03771d3de85f948dfceda864f709b
[ "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
28,947
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stephen Morgan, Scott Morrison, Floris van Doorn -/ import category_theory.const import category_theory.discrete_category import category_theory.yoneda import category_theory.reflects_isomorphisms universes v u u' -- declare the `v`'s first; see `category_theory.category` for an explanation open category_theory variables {J : Type v} [small_category J] variables {C : Type u} [category.{v} C] open category_theory open category_theory.category open category_theory.functor open opposite namespace category_theory namespace functor variables {J C} (F : J ⥤ C) /-- `F.cones` is the functor assigning to an object `X` the type of natural transformations from the constant functor with value `X` to `F`. An object representing this functor is a limit of `F`. -/ def cones : Cᵒᵖ ⥤ Type v := (const J).op ⋙ (yoneda.obj F) lemma cones_obj (X : Cᵒᵖ) : F.cones.obj X = ((const J).obj (unop X) ⟶ F) := rfl @[simp] lemma cones_map_app {X₁ X₂ : Cᵒᵖ} (f : X₁ ⟶ X₂) (t : F.cones.obj X₁) (j : J) : (F.cones.map f t).app j = f.unop ≫ t.app j := rfl /-- `F.cocones` is the functor assigning to an object `X` the type of natural transformations from `F` to the constant functor with value `X`. An object corepresenting this functor is a colimit of `F`. -/ def cocones : C ⥤ Type v := const J ⋙ coyoneda.obj (op F) lemma cocones_obj (X : C) : F.cocones.obj X = (F ⟶ (const J).obj X) := rfl @[simp] lemma cocones_map_app {X₁ X₂ : C} (f : X₁ ⟶ X₂) (t : F.cocones.obj X₁) (j : J) : (F.cocones.map f t).app j = t.app j ≫ f := rfl end functor section variables (J C) /-- Functorially associated to each functor `J ⥤ C`, we have the `C`-presheaf consisting of cones with a given cone point. -/ @[simps] def cones : (J ⥤ C) ⥤ (Cᵒᵖ ⥤ Type v) := { obj := functor.cones, map := λ F G f, whisker_left (const J).op (yoneda.map f) } /-- Contravariantly associated to each functor `J ⥤ C`, we have the `C`-copresheaf consisting of cocones with a given cocone point. -/ @[simps] def cocones : (J ⥤ C)ᵒᵖ ⥤ (C ⥤ Type v) := { obj := λ F, functor.cocones (unop F), map := λ F G f, whisker_left (const J) (coyoneda.map f) } end namespace limits /-- A `c : cone F` is: * an object `c.X` and * a natural transformation `c.π : c.X ⟶ F` from the constant `c.X` functor to `F`. `cone F` is equivalent, via `cone.equiv` below, to `Σ X, F.cones.obj X`. -/ structure cone (F : J ⥤ C) := (X : C) (π : (const J).obj X ⟶ F) instance inhabited_cone (F : discrete punit ⥤ C) : inhabited (cone F) := ⟨{ X := F.obj punit.star, π := { app := λ X, match X with | punit.star := 𝟙 _ end } }⟩ @[simp, reassoc] lemma cone.w {F : J ⥤ C} (c : cone F) {j j' : J} (f : j ⟶ j') : c.π.app j ≫ F.map f = c.π.app j' := by { rw ← (c.π.naturality f), apply id_comp } /-- A `c : cocone F` is * an object `c.X` and * a natural transformation `c.ι : F ⟶ c.X` from `F` to the constant `c.X` functor. `cocone F` is equivalent, via `cone.equiv` below, to `Σ X, F.cocones.obj X`. -/ structure cocone (F : J ⥤ C) := (X : C) (ι : F ⟶ (const J).obj X) instance inhabited_cocone (F : discrete punit ⥤ C) : inhabited (cocone F) := ⟨{ X := F.obj punit.star, ι := { app := λ X, match X with | punit.star := 𝟙 _ end } }⟩ @[simp, reassoc] lemma cocone.w {F : J ⥤ C} (c : cocone F) {j j' : J} (f : j ⟶ j') : F.map f ≫ c.ι.app j' = c.ι.app j := by { rw (c.ι.naturality f), apply comp_id } variables {F : J ⥤ C} namespace cone /-- The isomorphism between a cone on `F` and an element of the functor `F.cones`. -/ def equiv (F : J ⥤ C) : cone F ≅ Σ X, F.cones.obj X := { hom := λ c, ⟨op c.X, c.π⟩, inv := λ c, { X := unop c.1, π := c.2 }, hom_inv_id' := begin ext, cases x, refl, end, inv_hom_id' := begin ext, cases x, refl, end } /-- A map to the vertex of a cone naturally induces a cone by composition. -/ @[simp] def extensions (c : cone F) : yoneda.obj c.X ⟶ F.cones := { app := λ X f, (const J).map f ≫ c.π } /-- A map to the vertex of a cone induces a cone by composition. -/ @[simp] def extend (c : cone F) {X : C} (f : X ⟶ c.X) : cone F := { X := X, π := c.extensions.app (op X) f } @[simp] lemma extend_π (c : cone F) {X : Cᵒᵖ} (f : unop X ⟶ c.X) : (extend c f).π = c.extensions.app X f := rfl /-- Whisker a cone by precomposition of a functor. -/ @[simps] def whisker {K : Type v} [small_category K] (E : K ⥤ J) (c : cone F) : cone (E ⋙ F) := { X := c.X, π := whisker_left E c.π } end cone namespace cocone /-- The isomorphism between a cocone on `F` and an element of the functor `F.cocones`. -/ def equiv (F : J ⥤ C) : cocone F ≅ Σ X, F.cocones.obj X := { hom := λ c, ⟨c.X, c.ι⟩, inv := λ c, { X := c.1, ι := c.2 }, hom_inv_id' := begin ext, cases x, refl, end, inv_hom_id' := begin ext, cases x, refl, end } /-- A map from the vertex of a cocone naturally induces a cocone by composition. -/ @[simp] def extensions (c : cocone F) : coyoneda.obj (op c.X) ⟶ F.cocones := { app := λ X f, c.ι ≫ (const J).map f } /-- A map from the vertex of a cocone induces a cocone by composition. -/ @[simp] def extend (c : cocone F) {X : C} (f : c.X ⟶ X) : cocone F := { X := X, ι := c.extensions.app X f } @[simp] lemma extend_ι (c : cocone F) {X : C} (f : c.X ⟶ X) : (extend c f).ι = c.extensions.app X f := rfl /-- Whisker a cocone by precomposition of a functor. See `whiskering` for a functorial version. -/ @[simps] def whisker {K : Type v} [small_category K] (E : K ⥤ J) (c : cocone F) : cocone (E ⋙ F) := { X := c.X, ι := whisker_left E c.ι } end cocone /-- A cone morphism between two cones for the same diagram is a morphism of the cone points which commutes with the cone legs. -/ @[ext] structure cone_morphism (A B : cone F) := (hom : A.X ⟶ B.X) (w' : ∀ j : J, hom ≫ B.π.app j = A.π.app j . obviously) restate_axiom cone_morphism.w' attribute [simp, reassoc] cone_morphism.w instance inhabited_cone_morphism (A : cone F) : inhabited (cone_morphism A A) := ⟨{ hom := 𝟙 _}⟩ /-- The category of cones on a given diagram. -/ @[simps] instance cone.category : category.{v} (cone F) := { hom := λ A B, cone_morphism A B, comp := λ X Y Z f g, { hom := f.hom ≫ g.hom }, id := λ B, { hom := 𝟙 B.X } } namespace cones /-- To give an isomorphism between cones, it suffices to give an isomorphism between their vertices which commutes with the cone maps. -/ @[ext, simps] def ext {c c' : cone F} (φ : c.X ≅ c'.X) (w : ∀ j, c.π.app j = φ.hom ≫ c'.π.app j) : c ≅ c' := { hom := { hom := φ.hom }, inv := { hom := φ.inv, w' := λ j, φ.inv_comp_eq.mpr (w j) } } /-- Given a cone morphism whose object part is an isomorphism, produce an isomorphism of cones. -/ def cone_iso_of_hom_iso {K : J ⥤ C} {c d : cone K} (f : c ⟶ d) [i : is_iso f.hom] : is_iso f := { inv := { hom := i.inv, w' := λ j, (as_iso f.hom).inv_comp_eq.2 (f.w j).symm } } /-- Functorially postcompose a cone for `F` by a natural transformation `F ⟶ G` to give a cone for `G`. -/ @[simps] def postcompose {G : J ⥤ C} (α : F ⟶ G) : cone F ⥤ cone G := { obj := λ c, { X := c.X, π := c.π ≫ α }, map := λ c₁ c₂ f, { hom := f.hom, w' := by intro; erw ← category.assoc; simp [-category.assoc] } } /-- Postcomposing a cone by the composite natural transformation `α ≫ β` is the same as postcomposing by `α` and then by `β`. -/ def postcompose_comp {G H : J ⥤ C} (α : F ⟶ G) (β : G ⟶ H) : postcompose (α ≫ β) ≅ postcompose α ⋙ postcompose β := nat_iso.of_components (λ s, cones.ext (iso.refl _) (by tidy)) (by tidy) /-- Postcomposing by the identity does not change the cone up to isomorphism. -/ def postcompose_id : postcompose (𝟙 F) ≅ 𝟭 (cone F) := nat_iso.of_components (λ s, cones.ext (iso.refl _) (by tidy)) (by tidy) /-- If `F` and `G` are naturally isomorphic functors, then they have equivalent categories of cones. -/ @[simps] def postcompose_equivalence {G : J ⥤ C} (α : F ≅ G) : cone F ≌ cone G := { functor := postcompose α.hom, inverse := postcompose α.inv, unit_iso := nat_iso.of_components (λ s, cones.ext (iso.refl _) (by tidy)) (by tidy), counit_iso := nat_iso.of_components (λ s, cones.ext (iso.refl _) (by tidy)) (by tidy) } /-- Whiskering on the left by `E : K ⥤ J` gives a functor from `cone F` to `cone (E ⋙ F)`. -/ @[simps] def whiskering {K : Type v} [small_category K] (E : K ⥤ J) : cone F ⥤ cone (E ⋙ F) := { obj := λ c, c.whisker E, map := λ c c' f, { hom := f.hom, } } /-- Whiskering by an equivalence gives an equivalence between categories of cones. -/ @[simps] def whiskering_equivalence {K : Type v} [small_category K] (e : K ≌ J) : cone F ≌ cone (e.functor ⋙ F) := { functor := whiskering e.functor, inverse := whiskering e.inverse ⋙ postcompose ((functor.associator _ _ _).inv ≫ (whisker_right (e.counit_iso).hom F) ≫ (functor.left_unitor F).hom), unit_iso := nat_iso.of_components (λ s, cones.ext (iso.refl _) (by tidy)) (by tidy), counit_iso := nat_iso.of_components (λ s, cones.ext (iso.refl _) (begin intro k, have t := s.π.naturality (e.unit_inv.app k), dsimp at t, simp only [←e.counit_app_functor k, id_comp] at t, dsimp, simp [t], end)) (by tidy), } /-- The categories of cones over `F` and `G` are equivalent if `F` and `G` are naturally isomorphic (possibly after changing the indexing category by an equivalence). -/ def equivalence_of_reindexing {K : Type v} [small_category K] {G : K ⥤ C} (e : K ≌ J) (α : e.functor ⋙ F ≅ G) : cone F ≌ cone G := (whiskering_equivalence e).trans (postcompose_equivalence α) @[simp] lemma equivalence_of_reindexing_functor_obj {K : Type v} [small_category K] {G : K ⥤ C} (e : K ≌ J) (α : e.functor ⋙ F ≅ G) (c : cone F) : (equivalence_of_reindexing e α).functor.obj c = (postcompose α.hom).obj (cone.whisker e.functor c) := rfl section variable (F) /-- Forget the cone structure and obtain just the cone point. -/ @[simps] def forget : cone F ⥤ C := { obj := λ t, t.X, map := λ s t f, f.hom } variables {D : Type u'} [category.{v} D] (G : C ⥤ D) /-- A functor `G : C ⥤ D` sends cones over `F` to cones over `F ⋙ G` functorially. -/ @[simps] def functoriality : cone F ⥤ cone (F ⋙ G) := { obj := λ A, { X := G.obj A.X, π := { app := λ j, G.map (A.π.app j), naturality' := by intros; erw ←G.map_comp; tidy } }, map := λ X Y f, { hom := G.map f.hom, w' := by intros; rw [←functor.map_comp, f.w] } } instance functoriality_full [full G] [faithful G] : full (functoriality F G) := { preimage := λ X Y t, { hom := G.preimage t.hom, w' := λ j, G.map_injective (by simpa using t.w j) } } instance functoriality_faithful [faithful G] : faithful (cones.functoriality F G) := { map_injective' := λ X Y f g e, by { ext1, injection e, apply G.map_injective h_1 } } /-- If `e : C ≌ D` is an equivalence of categories, then `functoriality F e.functor` induces an equivalence between cones over `F` and cones over `F ⋙ e.functor`. -/ @[simps] def functoriality_equivalence (e : C ≌ D) : cone F ≌ cone (F ⋙ e.functor) := let f : (F ⋙ e.functor) ⋙ e.inverse ≅ F := functor.associator _ _ _ ≪≫ iso_whisker_left _ (e.unit_iso).symm ≪≫ functor.right_unitor _ in { functor := functoriality F e.functor, inverse := (functoriality (F ⋙ e.functor) e.inverse) ⋙ (postcompose_equivalence f).functor, unit_iso := nat_iso.of_components (λ c, cones.ext (e.unit_iso.app _) (by tidy)) (by tidy), counit_iso := nat_iso.of_components (λ c, cones.ext (e.counit_iso.app _) (by tidy)) (by tidy), } /-- If `F` reflects isomorphisms, then `cones.functoriality F` reflects isomorphisms as well. -/ instance reflects_cone_isomorphism (F : C ⥤ D) [reflects_isomorphisms F] (K : J ⥤ C) : reflects_isomorphisms (cones.functoriality K F) := begin constructor, introsI, haveI : is_iso (F.map f.hom) := (cones.forget (K ⋙ F)).map_is_iso ((cones.functoriality K F).map f), haveI := reflects_isomorphisms.reflects F f.hom, apply cone_iso_of_hom_iso end end end cones /-- A cocone morphism between two cocones for the same diagram is a morphism of the cocone points which commutes with the cocone legs. -/ @[ext] structure cocone_morphism (A B : cocone F) := (hom : A.X ⟶ B.X) (w' : ∀ j : J, A.ι.app j ≫ hom = B.ι.app j . obviously) instance inhabited_cocone_morphism (A : cocone F) : inhabited (cocone_morphism A A) := ⟨{ hom := 𝟙 _ }⟩ restate_axiom cocone_morphism.w' attribute [simp, reassoc] cocone_morphism.w @[simps] instance cocone.category : category.{v} (cocone F) := { hom := λ A B, cocone_morphism A B, comp := λ _ _ _ f g, { hom := f.hom ≫ g.hom }, id := λ B, { hom := 𝟙 B.X } } namespace cocones /-- To give an isomorphism between cocones, it suffices to give an isomorphism between their vertices which commutes with the cocone maps. -/ @[ext, simps] def ext {c c' : cocone F} (φ : c.X ≅ c'.X) (w : ∀ j, c.ι.app j ≫ φ.hom = c'.ι.app j) : c ≅ c' := { hom := { hom := φ.hom }, inv := { hom := φ.inv, w' := λ j, φ.comp_inv_eq.mpr (w j).symm } } /-- Given a cocone morphism whose object part is an isomorphism, produce an isomorphism of cocones. -/ def cocone_iso_of_hom_iso {K : J ⥤ C} {c d : cocone K} (f : c ⟶ d) [i : is_iso f.hom] : is_iso f := { inv := { hom := i.inv, w' := λ j, (as_iso f.hom).comp_inv_eq.2 (f.w j).symm } } /-- Functorially precompose a cocone for `F` by a natural transformation `G ⟶ F` to give a cocone for `G`. -/ @[simps] def precompose {G : J ⥤ C} (α : G ⟶ F) : cocone F ⥤ cocone G := { obj := λ c, { X := c.X, ι := α ≫ c.ι }, map := λ c₁ c₂ f, { hom := f.hom } } /-- Precomposing a cocone by the composite natural transformation `α ≫ β` is the same as precomposing by `β` and then by `α`. -/ def precompose_comp {G H : J ⥤ C} (α : F ⟶ G) (β : G ⟶ H) : precompose (α ≫ β) ≅ precompose β ⋙ precompose α := nat_iso.of_components (λ s, cocones.ext (iso.refl _) (by tidy)) (by tidy) /-- Precomposing by the identity does not change the cocone up to isomorphism. -/ def precompose_id : precompose (𝟙 F) ≅ 𝟭 (cocone F) := nat_iso.of_components (λ s, cocones.ext (iso.refl _) (by tidy)) (by tidy) /-- If `F` and `G` are naturally isomorphic functors, then they have equivalent categories of cocones. -/ @[simps] def precompose_equivalence {G : J ⥤ C} (α : G ≅ F) : cocone F ≌ cocone G := { functor := precompose α.hom, inverse := precompose α.inv, unit_iso := nat_iso.of_components (λ s, cocones.ext (iso.refl _) (by tidy)) (by tidy), counit_iso := nat_iso.of_components (λ s, cocones.ext (iso.refl _) (by tidy)) (by tidy) } /-- Whiskering on the left by `E : K ⥤ J` gives a functor from `cocone F` to `cocone (E ⋙ F)`. -/ @[simps] def whiskering {K : Type v} [small_category K] (E : K ⥤ J) : cocone F ⥤ cocone (E ⋙ F) := { obj := λ c, c.whisker E, map := λ c c' f, { hom := f.hom, } } /-- Whiskering by an equivalence gives an equivalence between categories of cones. -/ @[simps] def whiskering_equivalence {K : Type v} [small_category K] (e : K ≌ J) : cocone F ≌ cocone (e.functor ⋙ F) := { functor := whiskering e.functor, inverse := whiskering e.inverse ⋙ precompose ((functor.left_unitor F).inv ≫ (whisker_right (e.counit_iso).inv F) ≫ (functor.associator _ _ _).inv), unit_iso := nat_iso.of_components (λ s, cocones.ext (iso.refl _) (by tidy)) (by tidy), counit_iso := nat_iso.of_components (λ s, cocones.ext (iso.refl _) (begin intro k, have t := s.ι.naturality (e.unit.app k), dsimp at t, simp only [←e.counit_inv_app_functor k, comp_id] at t, dsimp, simp [t], end)) (by tidy), } /-- The categories of cocones over `F` and `G` are equivalent if `F` and `G` are naturally isomorphic (possibly after changing the indexing category by an equivalence). -/ def equivalence_of_reindexing {K : Type v} [small_category K] {G : K ⥤ C} (e : K ≌ J) (α : e.functor ⋙ F ≅ G) : cocone F ≌ cocone G := (whiskering_equivalence e).trans (precompose_equivalence α.symm) @[simp] lemma equivalence_of_reindexing_functor_obj {K : Type v} [small_category K] {G : K ⥤ C} (e : K ≌ J) (α : e.functor ⋙ F ≅ G) (c : cocone F) : (equivalence_of_reindexing e α).functor.obj c = (precompose α.inv).obj (cocone.whisker e.functor c) := rfl section variable (F) /-- Forget the cocone structure and obtain just the cocone point. -/ @[simps] def forget : cocone F ⥤ C := { obj := λ t, t.X, map := λ s t f, f.hom } variables {D : Type u'} [category.{v} D] (G : C ⥤ D) /-- A functor `G : C ⥤ D` sends cocones over `F` to cocones over `F ⋙ G` functorially. -/ @[simps] def functoriality : cocone F ⥤ cocone (F ⋙ G) := { obj := λ A, { X := G.obj A.X, ι := { app := λ j, G.map (A.ι.app j), naturality' := by intros; erw ←G.map_comp; tidy } }, map := λ _ _ f, { hom := G.map f.hom, w' := by intros; rw [←functor.map_comp, cocone_morphism.w] } } instance functoriality_full [full G] [faithful G] : full (functoriality F G) := { preimage := λ X Y t, { hom := G.preimage t.hom, w' := λ j, G.map_injective (by simpa using t.w j) } } instance functoriality_faithful [faithful G] : faithful (functoriality F G) := { map_injective' := λ X Y f g e, by { ext1, injection e, apply G.map_injective h_1 } } /-- If `e : C ≌ D` is an equivalence of categories, then `functoriality F e.functor` induces an equivalence between cocones over `F` and cocones over `F ⋙ e.functor`. -/ @[simps] def functoriality_equivalence (e : C ≌ D) : cocone F ≌ cocone (F ⋙ e.functor) := let f : (F ⋙ e.functor) ⋙ e.inverse ≅ F := functor.associator _ _ _ ≪≫ iso_whisker_left _ (e.unit_iso).symm ≪≫ functor.right_unitor _ in { functor := functoriality F e.functor, inverse := (functoriality (F ⋙ e.functor) e.inverse) ⋙ (precompose_equivalence f.symm).functor, unit_iso := nat_iso.of_components (λ c, cocones.ext (e.unit_iso.app _) (by tidy)) (by tidy), counit_iso := nat_iso.of_components (λ c, cocones.ext (e.counit_iso.app _) begin -- Unfortunately this doesn't work by `tidy`. -- In this configuration `simp` reaches a dead-end and needs help. intros j, dsimp, simp only [←equivalence.counit_inv_app_functor, iso.inv_hom_id_app, map_comp, equivalence.fun_inv_map, assoc, id_comp, iso.inv_hom_id_app_assoc], dsimp, simp, -- See note [dsimp, simp]. end) (by tidy), } /-- If `F` reflects isomorphisms, then `cocones.functoriality F` reflects isomorphisms as well. -/ instance reflects_cocone_isomorphism (F : C ⥤ D) [reflects_isomorphisms F] (K : J ⥤ C) : reflects_isomorphisms (cocones.functoriality K F) := begin constructor, introsI, haveI : is_iso (F.map f.hom) := (cocones.forget (K ⋙ F)).map_is_iso ((cocones.functoriality K F).map f), haveI := reflects_isomorphisms.reflects F f.hom, apply cocone_iso_of_hom_iso end end end cocones end limits namespace functor variables {D : Type u'} [category.{v} D] variables {F : J ⥤ C} {G : J ⥤ C} (H : C ⥤ D) open category_theory.limits /-- The image of a cone in C under a functor G : C ⥤ D is a cone in D. -/ def map_cone (c : cone F) : cone (F ⋙ H) := (cones.functoriality F H).obj c /-- The image of a cocone in C under a functor G : C ⥤ D is a cocone in D. -/ def map_cocone (c : cocone F) : cocone (F ⋙ H) := (cocones.functoriality F H).obj c @[simp] lemma map_cone_X (c : cone F) : (H.map_cone c).X = H.obj c.X := rfl @[simp] lemma map_cocone_X (c : cocone F) : (H.map_cocone c).X = H.obj c.X := rfl /-- Given a cone morphism `c ⟶ c'`, construct a cone morphism on the mapped cones functorially. -/ def map_cone_morphism {c c' : cone F} (f : c ⟶ c') : H.map_cone c ⟶ H.map_cone c' := (cones.functoriality F H).map f /-- Given a cocone morphism `c ⟶ c'`, construct a cocone morphism on the mapped cocones functorially. -/ def map_cocone_morphism {c c' : cocone F} (f : c ⟶ c') : H.map_cocone c ⟶ H.map_cocone c' := (cocones.functoriality F H).map f @[simp] lemma map_cone_π (c : cone F) (j : J) : (map_cone H c).π.app j = H.map (c.π.app j) := rfl @[simp] lemma map_cocone_ι (c : cocone F) (j : J) : (map_cocone H c).ι.app j = H.map (c.ι.app j) := rfl /-- If `H` is an equivalence, we invert `H.map_cone` and get a cone for `F` from a cone for `F ⋙ H`.-/ def map_cone_inv [is_equivalence H] (c : cone (F ⋙ H)) : cone F := (limits.cones.functoriality_equivalence F (as_equivalence H)).inverse.obj c /-- `map_cone` is the left inverse to `map_cone_inv`. -/ def map_cone_map_cone_inv {F : J ⥤ D} (H : D ⥤ C) [is_equivalence H] (c : cone (F ⋙ H)) : map_cone H (map_cone_inv H c) ≅ c := (limits.cones.functoriality_equivalence F (as_equivalence H)).counit_iso.app c /-- `map_cone` is the right inverse to `map_cone_inv`. -/ def map_cone_inv_map_cone {F : J ⥤ D} (H : D ⥤ C) [is_equivalence H] (c : cone F) : map_cone_inv H (map_cone H c) ≅ c := (limits.cones.functoriality_equivalence F (as_equivalence H)).unit_iso.symm.app c /-- If `H` is an equivalence, we invert `H.map_cone` and get a cone for `F` from a cone for `F ⋙ H`.-/ def map_cocone_inv [is_equivalence H] (c : cocone (F ⋙ H)) : cocone F := (limits.cocones.functoriality_equivalence F (as_equivalence H)).inverse.obj c /-- `map_cocone` is the left inverse to `map_cocone_inv`. -/ def map_cocone_map_cocone_inv {F : J ⥤ D} (H : D ⥤ C) [is_equivalence H] (c : cocone (F ⋙ H)) : map_cocone H (map_cocone_inv H c) ≅ c := (limits.cocones.functoriality_equivalence F (as_equivalence H)).counit_iso.app c /-- `map_cocone` is the right inverse to `map_cocone_inv`. -/ def map_cocone_inv_map_cocone {F : J ⥤ D} (H : D ⥤ C) [is_equivalence H] (c : cocone F) : map_cocone_inv H (map_cocone H c) ≅ c := (limits.cocones.functoriality_equivalence F (as_equivalence H)).unit_iso.symm.app c /-- `map_cone` commutes with `postcompose` -/ @[simps {rhs_md:=semireducible}] def map_cone_postcompose {α : F ⟶ G} {c} : H.map_cone ((cones.postcompose α).obj c) ≅ (cones.postcompose (whisker_right α H : _)).obj (H.map_cone c) := cones.ext (iso.refl _) (by tidy) /-- `map_cone` commutes with `postcompose_equivalence` -/ @[simps {rhs_md:=semireducible}] def map_cone_postcompose_equivalence_functor {α : F ≅ G} {c} : H.map_cone ((cones.postcompose_equivalence α).functor.obj c) ≅ (cones.postcompose_equivalence (iso_whisker_right α H : _)).functor.obj (H.map_cone c) := cones.ext (iso.refl _) (by tidy) /-- `map_cocone` commutes with `precompose` -/ @[simps {rhs_md:=semireducible}] def map_cocone_precompose {α : F ⟶ G} {c} : H.map_cocone ((cocones.precompose α).obj c) ≅ (cocones.precompose (whisker_right α H : _)).obj (H.map_cocone c) := cocones.ext (iso.refl _) (by tidy) /-- `map_cocone` commutes with `precompose_equivalence` -/ @[simps {rhs_md:=semireducible}] def map_cocone_precompose_equivalence_functor {α : F ≅ G} {c} : H.map_cocone ((cocones.precompose_equivalence α).functor.obj c) ≅ (cocones.precompose_equivalence (iso_whisker_right α H : _)).functor.obj (H.map_cocone c) := cocones.ext (iso.refl _) (by tidy) variables {K : Type v} [small_category K] /-- `map_cone` commutes with `whisker` -/ @[simps {rhs_md:=semireducible}] def map_cone_whisker {E : K ⥤ J} {c : cone F} : H.map_cone (c.whisker E) ≅ (H.map_cone c).whisker E := cones.ext (iso.refl _) (by tidy) /-- `map_cocone` commutes with `whisker` -/ @[simps {rhs_md:=semireducible}] def map_cocone_whisker {E : K ⥤ J} {c : cocone F} : H.map_cocone (c.whisker E) ≅ (H.map_cocone c).whisker E := cocones.ext (iso.refl _) (by tidy) end functor end category_theory namespace category_theory.limits section variables {F : J ⥤ C} /-- Change a `cocone F` into a `cone F.op`. -/ @[simps] def cocone.op (c : cocone F) : cone F.op := { X := op c.X, π := { app := λ j, (c.ι.app (unop j)).op, naturality' := λ j j' f, has_hom.hom.unop_inj (by tidy) } } /-- Change a `cone F` into a `cocone F.op`. -/ @[simps] def cone.op (c : cone F) : cocone F.op := { X := op c.X, ι := { app := λ j, (c.π.app (unop j)).op, naturality' := λ j j' f, has_hom.hom.unop_inj (by tidy) } } /-- Change a `cocone F.op` into a `cone F`. -/ @[simps] def cocone.unop (c : cocone F.op) : cone F := { X := unop c.X, π := { app := λ j, (c.ι.app (op j)).unop, naturality' := λ j j' f, has_hom.hom.op_inj begin dsimp, simp only [comp_id], exact (c.w f.op).symm, end } } /-- Change a `cone F.op` into a `cocone F`. -/ @[simps] def cone.unop (c : cone F.op) : cocone F := { X := unop c.X, ι := { app := λ j, (c.π.app (op j)).unop, naturality' := λ j j' f, has_hom.hom.op_inj begin dsimp, simp only [id_comp], exact (c.w f.op), end } } variables (F) /-- The category of cocones on `F` is equivalent to the opposite category of the category of cones on the opposite of `F`. -/ @[simps] def cocone_equivalence_op_cone_op : cocone F ≌ (cone F.op)ᵒᵖ := { functor := { obj := λ c, op (cocone.op c), map := λ X Y f, has_hom.hom.op { hom := f.hom.op, w' := λ j, by { apply has_hom.hom.unop_inj, dsimp, simp, }, } }, inverse := { obj := λ c, cone.unop (unop c), map := λ X Y f, { hom := f.unop.hom.unop, w' := λ j, by { apply has_hom.hom.op_inj, dsimp, simp, }, } }, unit_iso := nat_iso.of_components (λ c, cocones.ext (iso.refl _) (by tidy)) (by tidy), counit_iso := nat_iso.of_components (λ c, by { op_induction c, dsimp, apply iso.op, exact cones.ext (iso.refl _) (by tidy), }) begin intros, have hX : X = op (unop X) := rfl, revert hX, generalize : unop X = X', rintro rfl, have hY : Y = op (unop Y) := rfl, revert hY, generalize : unop Y = Y', rintro rfl, apply has_hom.hom.unop_inj, apply cone_morphism.ext, dsimp, simp, end, functor_unit_iso_comp' := λ c, begin apply has_hom.hom.unop_inj, ext, dsimp, simp, end } end section variables {F : J ⥤ Cᵒᵖ} /-- Change a cocone on `F.left_op : Jᵒᵖ ⥤ C` to a cocone on `F : J ⥤ Cᵒᵖ`. -/ -- Here and below we only automatically generate the `@[simp]` lemma for the `X` field, -- as we can write a simpler `rfl` lemma for the components of the natural transformation by hand. @[simps X] def cone_of_cocone_left_op (c : cocone F.left_op) : cone F := { X := op c.X, π := nat_trans.remove_left_op (c.ι ≫ (const.op_obj_unop (op c.X)).hom) } @[simp] lemma cone_of_cocone_left_op_π_app (c : cocone F.left_op) (j) : (cone_of_cocone_left_op c).π.app j = (c.ι.app (op j)).op := by { dsimp [cone_of_cocone_left_op], simp } /-- Change a cone on `F : J ⥤ Cᵒᵖ` to a cocone on `F.left_op : Jᵒᵖ ⥤ C`. -/ @[simps X] def cocone_left_op_of_cone (c : cone F) : cocone (F.left_op) := { X := unop c.X, ι := nat_trans.left_op c.π } @[simp] lemma cocone_left_op_of_cone_ι_app (c : cone F) (j) : (cocone_left_op_of_cone c).ι.app j = (c.π.app (unop j)).unop := by { dsimp [cocone_left_op_of_cone], simp } /-- Change a cone on `F.left_op : Jᵒᵖ ⥤ C` to a cocone on `F : J ⥤ Cᵒᵖ`. -/ @[simps X] def cocone_of_cone_left_op (c : cone F.left_op) : cocone F := { X := op c.X, ι := nat_trans.remove_left_op ((const.op_obj_unop (op c.X)).hom ≫ c.π) } @[simp] lemma cocone_of_cone_left_op_ι_app (c : cone F.left_op) (j) : (cocone_of_cone_left_op c).ι.app j = (c.π.app (op j)).op := by { dsimp [cocone_of_cone_left_op], simp } /-- Change a cocone on `F : J ⥤ Cᵒᵖ` to a cone on `F.left_op : Jᵒᵖ ⥤ C`. -/ @[simps X] def cone_left_op_of_cocone (c : cocone F) : cone (F.left_op) := { X := unop c.X, π := nat_trans.left_op c.ι } @[simp] lemma cone_left_op_of_cocone_π_app (c : cocone F) (j) : (cone_left_op_of_cocone c).π.app j = (c.ι.app (unop j)).unop := by { dsimp [cone_left_op_of_cocone], simp } end end category_theory.limits namespace category_theory.functor open category_theory.limits variables {F : J ⥤ C} variables {D : Type u'} [category.{v} D] section variables (G : C ⥤ D) /-- The opposite cocone of the image of a cone is the image of the opposite cocone. -/ def map_cone_op (t : cone F) : (G.map_cone t).op ≅ (G.op.map_cocone t.op) := cocones.ext (iso.refl _) (by tidy) /-- The opposite cone of the image of a cocone is the image of the opposite cone. -/ def map_cocone_op {t : cocone F} : (G.map_cocone t).op ≅ (G.op.map_cone t.op) := cones.ext (iso.refl _) (by tidy) end end category_theory.functor
d67c59dbbfa0b13181c7ccf6d6f83bfcabd85faa
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/tactic/rewrite_all/basic.lean
ce2d621de0d9360e7df0dd6e0a27b6e37325754d
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
1,961
lean
/- Copyright (c) 2018 Keeley Hoek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Keeley Hoek, Scott Morrison -/ import data.option.defs data.mllist tactic.core open tactic @[derive decidable_eq, derive inhabited] inductive side | L | R def side.other : side → side | side.L := side.R | side.R := side.L def side.to_string : side → string | side.L := "L" | side.R := "R" instance : has_to_string side := ⟨side.to_string⟩ namespace tactic.rewrite_all meta structure cfg extends rewrite_cfg := (try_simp : bool := ff) (discharger : tactic unit := skip) -- Warning: rewrite_search can't produce tactic scripts when the simplifier is used. (simplifier : expr → tactic (expr × expr) := λ e, failed) meta structure tracked_rewrite := (exp : expr) (proof : tactic expr) -- If `addr` is not provided by the underlying implementation of `rewrite_all` (i.e. kabstract) -- `rewrite_search` will not be able to produce tactic scripts. (addr : option (list side)) namespace tracked_rewrite meta def eval (rw : tracked_rewrite) : tactic (expr × expr) := do prf ← rw.proof, return (rw.exp, prf) meta def replace_target (rw : tracked_rewrite) : tactic unit := do (exp, prf) ← rw.eval, tactic.replace_target exp prf private meta def replace_target_side (new_target lam : pexpr) (prf : expr) : tactic unit := do new_target ← to_expr new_target tt ff, prf' ← to_expr ``(congr_arg %%lam %%prf) tt ff, tactic.replace_target new_target prf' meta def replace_target_lhs (rw : tracked_rewrite) : tactic unit := do (new_lhs, prf) ← rw.eval, `(%%_ = %%rhs) ← target, replace_target_side ``(%%new_lhs = %%rhs) ``(λ L, L = %%rhs) prf meta def replace_target_rhs (rw : tracked_rewrite) : tactic unit := do (new_rhs, prf) ← rw.eval, `(%%lhs = %%_) ← target, replace_target_side ``(%%lhs = %%new_rhs) ``(λ R, %%lhs = R) prf end tracked_rewrite end tactic.rewrite_all
8cb259b9a05b5dd849f229a85892b6dfeed5a499
7a76361040c55ae1eba5856c1a637593117a6556
/src/lectures/love03_forward_proofs_demo.lean
89abc0d760b8fa7d82157cb4e8783c384a0d268a
[]
no_license
rgreenblatt/fpv2021
c2cbe7b664b648cef7d240a654d6bdf97a559272
c65d72e48c8fa827d2040ed6ea86c2be62db36fa
refs/heads/main
1,692,245,693,819
1,633,364,621,000
1,633,364,621,000
407,231,487
0
0
null
1,631,808,608,000
1,631,808,608,000
null
UTF-8
Lean
false
false
10,685
lean
import .love01_definitions_and_statements_demo /-! # LoVe Demo 3: Forward Proofs When developing a proof, often it makes sense to work __forward__: to start with what we already know and proceed step by step towards our goal. Lean's structured proofs and raw proof terms are two styles that support forward reasoning. -/ set_option pp.beta true set_option pp.generalized_field_notation false namespace LoVe namespace forward_proofs /-! ## Structured Constructs Structured proofs are syntactic sugar sprinkled on top of Lean's __proof terms__. The simplest kind of structured proof is the name of a lemma, possibly with arguments. -/ lemma add_comm (i j : ℕ) : add i j = add j i := sorry lemma add_comm_zero_left (n : ℕ) : add 0 n = add n 0 := add_comm 0 n lemma add_comm_zero_left₂ (n : ℕ) : add 0 n = add n 0 := by exact add_comm 0 n /-! `fix` and `assume` move `∀`-quantified variables and assumptions from the goal into the local context. They can be seen as structured versions of the `intros` tactic. `show` repeats the goal to prove. It is useful as documentation or to rephrase the goal (up to computation). -/ lemma fst_of_two_props : ∀a b : Prop, a → b → a := fix a b : Prop, assume ha : a, assume hb : b, show a, from ha lemma fst_of_two_props₂ (a b : Prop) (ha : a) (hb : b) : a := show a, from begin exact ha end #print fst_of_two_props #print fst_of_two_props₂ lemma fst_of_two_props₃ (a b : Prop) (ha : a) (hb : b) : a := ha /-! `have` proves an intermediate lemma, which can refer to the local context. -/ lemma prop_comp (a b c : Prop) (hab : a → b) (hbc : b → c) : a → c := assume ha : a, have hb : b := hab ha, have hc : c := hbc hb, show c, from hc lemma prop_comp₂ (a b c : Prop) (hab : a → b) (hbc : b → c) : a → c := assume ha : a, show c, from hbc (hab ha) /-! ## Forward Reasoning about Connectives and Quantifiers -/ lemma and_swap (a b : Prop) : a ∧ b → b ∧ a := assume hab : a ∧ b, have ha : a := and.elim_left hab, have hb : b := and.elim_right hab, show b ∧ a, from and.intro hb ha lemma or_swap (a b : Prop) : a ∨ b → b ∨ a := assume hab : a ∨ b, show b ∨ a, from or.elim hab (assume ha : a, show b ∨ a, from or.intro_right b ha) (assume hb : b, show b ∨ a, from or.intro_left a hb) def double (n : ℕ) : ℕ := n + n lemma nat_exists_double_iden : ∃n : ℕ, double n = n := exists.intro 0 (show double 0 = 0, from by refl) lemma nat_exists_double_iden₂ : ∃n : ℕ, double n = n := exists.intro 0 (by refl) lemma modus_ponens (a b : Prop) : (a → b) → a → b := assume hab : a → b, assume ha : a, show b, from hab ha lemma not_not_intro (a : Prop) : a → ¬¬ a := assume ha : a, assume hna : ¬ a, show false, from hna ha lemma forall.one_point {α : Type} (t : α) (p : α → Prop) : (∀x, x = t → p x) ↔ p t := iff.intro (assume hall : ∀x, x = t → p x, show p t, from begin apply hall t, refl end) (assume hp : p t, fix x, assume heq : x = t, show p x, from begin rw heq, exact hp end) lemma beast_666 (beast : ℕ) : (∀n, n = 666 → beast ≥ n) ↔ beast ≥ 666 := forall.one_point _ _ #print beast_666 lemma exists.one_point {α : Type} (t : α) (p : α → Prop) : (∃x : α, x = t ∧ p x) ↔ p t := iff.intro (assume hex : ∃x, x = t ∧ p x, show p t, from exists.elim hex (fix x, assume hand : x = t ∧ p x, show p t, from by cc)) (assume hp : p t, show ∃x : α, x = t ∧ p x, from exists.intro t (show t = t ∧ p t, from by cc)) /-! ## Calculational Proofs In informal mathematics, we often use transitive chains of equalities, inequalities, or equivalences (e.g., `a ≥ b ≥ c`). In Lean, such calculational proofs are supported by `calc`. Syntax: calc _term₀_ _op₁_ _term₁_ : _proof₁_ ... _op₂_ _term₂_ : _proof₂_ ⋮ ... _opN_ _termN_ : _proofN_ -/ lemma two_mul_example (m n : ℕ) : 2 * m + n = m + n + m := calc 2 * m + n = (m + m) + n : by rw two_mul ... = m + n + m : by cc /-! `calc` saves some repetition, some `have` labels, and some transitive reasoning: -/ lemma two_mul_example₂ (m n : ℕ) : 2 * m + n = m + n + m := have h₁ : 2 * m + n = (m + m) + n := by rw two_mul, have h₂ : (m + m) + n = m + n + m := by cc, show _, from eq.trans h₁ h₂ /-! ## Forward Reasoning with Tactics The `have`, `let`, and `calc` structured proof commands are also available as a tactic. Even in tactic mode, it can be useful to state intermediate results and definitions in a forward fashion. Observe that the syntax for the tactic `let` is slightly different than for the structured proof command `let`, with `,` instead of `in`. -/ lemma prop_comp₃ (a b c : Prop) (hab : a → b) (hbc : b → c) : a → c := begin intro ha, have hb : b := hab ha, let c' := c, have hc : c' := hbc hb, exact hc end /-! ## Dependent Types Dependent types are the defining feature of the dependent type theory family of logics. Consider a function `pick` that take a number `n : ℕ` and that returns a number between 0 and `n`. Conceptually, `pick` has a dependent type, namely `(n : ℕ) → {i : ℕ // i ≤ n}` We can think of this type as a `ℕ`-indexed family, where each member's type may depend on the index: `pick n : {i : ℕ // i ≤ n}` But a type may also depend on another type, e.g., `list` (or `λα, list α`) and `λα, α → α`. A term may depend on a type, e.g., `λα, λx : α, x` (a polymorphic identity function). Of course, a term may also depend on a term. Unless otherwise specified, a __dependent type__ means a type depending on a term. This is what we mean when we say that simple type theory does not support dependent types. In summary, there are four cases for `λx, t` in the calculus of inductive constructions (cf. Barendregt's `λ`-cube): Body (`t`) | | Argument (`x`) | Description ---------- | ------------ | -------------- | ------------------------------ A term | depending on | a term | Simply typed `λ`-expression A type | depending on | a term | Dependent type (strictly speaking) A term | depending on | a type | Polymorphic term A type | depending on | a type | Type constructor Revised typing rules: C ⊢ t : (x : σ) → τ[x] C ⊢ u : σ ———————————————————————————————————— App' C ⊢ t u : τ[u] C, x : σ ⊢ t : τ[x] ———————————————————————————————— Lam' C ⊢ (λx : σ, t) : (x : σ) → τ[x] These two rules degenerate to `App` and `Lam` if `x` does not occur in `τ[x]` Example of `App'`: ⊢ pick : (x : ℕ) → {y : ℕ // y ≤ x} ⊢ 5 : ℕ ——————————————————————————————————————————————— App' ⊢ pick 5 : {y : ℕ // y ≤ 5} Example of `Lam'`: α : Type, x : α ⊢ x : α ——————————————————————————————— Lam or Lam' α : Type ⊢ (λx : α, x) : α → α ————————————————————————————————————————————— Lam' ⊢ (λα : Type, λx : α, x) : (α : Type) → α → α Regrettably, the intuitive syntax `(x : σ) → τ` is not available in Lean. Instead, we must write `∀x : σ, τ` to specify a dependent type. Aliases: `σ → τ` := `∀_ : σ, τ` `Π` := `∀` ## The PAT Principle `→` is used both as the implication symbol and as the type constructor of functions. Similarly, `∀` is used both as a quantifier and in dependent types. The two pairs of concepts not only look the same, they are the same, by the PAT principle: * PAT = propositions as types; * PAT = proofs as terms. Types: * `σ → τ` is the type of total functions from `σ` to `τ`; * `∀x : σ, τ[x]` is the dependent function type from `x : σ` to `τ[x]`. Propositions: * `P → Q` can be read as "`P` implies `Q`", or as the type of functions mapping proofs of `P` to proofs of `Q`. * `∀x : σ, Q[x]` can be read as "for all `x`, `Q[x]`", or as the type of functions mapping values `x` of type `σ` to proofs of `Q[x]`. Terms: * A constant is a term. * A variable is a term. * `t u` is the application of function `t` to value `u`. * `λx, t[x]` is a function mapping `x` to `t[x]`. Proofs: * A lemma or hypothesis name is a proof. * `H t`, which instantiates the leading parameter or quantifier of proof `H`' statement with term `t`, is a proof. * `H G`, which discharges the leading assumption of `H`'s statement with proof `G`, is a proof. * `λh : P, H[h]` is a proof of `P → Q`, assuming `H[h]` is a proof of `Q` for `h : P`. * `λx : σ, H[x]` is a proof of `∀x : σ, Q[x]`, assuming `H[x]` is a proof of `Q[x]` for `x : σ`. -/ lemma and_swap₃ (a b : Prop) : a ∧ b → b ∧ a := λhab : a ∧ b, and.intro (and.elim_right hab) (and.elim_left hab) lemma and_swap₄ (a b : Prop) : a ∧ b → b ∧ a := begin intro hab, apply and.intro, apply and.elim_right, exact hab, apply and.elim_left, exact hab end /-! Tactical proofs are reduced to proof terms. -/ #print and_swap₃ #print and_swap₄ end forward_proofs /-! ## Induction by Pattern Matching By the PAT principle, a proof by induction is the same as a recursively specified proof term. Thus, as alternative to the `induction'` tactic, induction can also be done by pattern matching: * the induction hypothesis is then available under the name of the lemma we are proving; * well-foundedness of the argument is often proved automatically. -/ #check reverse lemma reverse_append {α : Type} : ∀xs ys : list α, reverse (xs ++ ys) = reverse ys ++ reverse xs | [] ys := by simp [reverse] | (x :: xs) ys := by simp [reverse, reverse_append xs] lemma reverse_append₂ {α : Type} (xs ys : list α) : reverse (xs ++ ys) = reverse ys ++ reverse xs := begin induction' xs, { simp [reverse] }, { simp [reverse, ih] } end lemma reverse_reverse {α : Type} : ∀xs : list α, reverse (reverse xs) = xs | [] := by refl | (x :: xs) := by simp [reverse, reverse_append, reverse_reverse xs] end LoVe
2bec2bf4166bd96c9d8720f19db6f1183d18035e
1a61aba1b67cddccce19532a9596efe44be4285f
/library/data/sum.lean
570d428d3f799f672de9b28990bcff4aa922bafa
[ "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,930
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 The sum type, aka disjoint union. -/ import logic.connectives open inhabited eq.ops notation A ⊎ B := sum A B namespace sum notation A + B := sum A B namespace low_precedence_plus reserve infixr `+`:25 -- conflicts with notation for addition infixr `+` := sum end low_precedence_plus variables {A B : Type} definition inl_ne_inr (a : A) (b : B) : inl a ≠ inr b := by contradiction definition inr_ne_inl (b : B) (a : A) : inr b ≠ inl a := by contradiction definition inl_inj {a₁ a₂ : A} : intro_left B a₁ = intro_left B a₂ → a₁ = a₂ := assume H, by injection H; assumption definition inr_inj {b₁ b₂ : B} : intro_right A b₁ = intro_right A b₂ → b₁ = b₂ := assume H, by injection H; assumption protected definition is_inhabited_left [instance] [h : inhabited A] : inhabited (A + B) := inhabited.mk (inl (default A)) protected definition is_inhabited_right [instance] [h : inhabited B] : inhabited (A + B) := inhabited.mk (inr (default B)) protected definition has_decidable_eq [instance] [h₁ : decidable_eq A] [h₂ : decidable_eq B] : ∀ s₁ s₂ : A + B, decidable (s₁ = s₂) | has_decidable_eq (inl a₁) (inl a₂) := match h₁ a₁ a₂ with | decidable.inl hp := by left; congruence; assumption | decidable.inr hn := by right; intro h; injection h; contradiction end | has_decidable_eq (inl a₁) (inr b₂) := by right; contradiction | has_decidable_eq (inr b₁) (inl a₂) := by right; contradiction | has_decidable_eq (inr b₁) (inr b₂) := match h₂ b₁ b₂ with | decidable.inl hp := by left; congruence; assumption | decidable.inr hn := by right; intro h; injection h; contradiction end end sum
46b5dc6bb8df442125f747d16816ea46529074ea
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/data/multiset.lean
90f94dbde5deff21c182dae8d804b236b7f6b736
[ "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
133,509
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Multisets. -/ import logic.function order.boolean_algebra data.equiv.basic data.list.basic data.list.perm data.list.sort data.quot data.string algebra.order_functions algebra.group_power algebra.ordered_group category.traversable.lemmas tactic.interactive category.traversable.instances category.basic open list subtype nat lattice variables {α : Type*} {β : Type*} {γ : Type*} local infix ` • ` := add_monoid.smul /-- `multiset α` is the quotient of `list α` by list permutation. The result is a type of finite sets with duplicates allowed. -/ def {u} multiset (α : Type u) : Type u := quotient (list.is_setoid α) namespace multiset instance : has_coe (list α) (multiset α) := ⟨quot.mk _⟩ @[simp] theorem quot_mk_to_coe (l : list α) : @eq (multiset α) ⟦l⟧ l := rfl @[simp] theorem quot_mk_to_coe' (l : list α) : @eq (multiset α) (quot.mk (≈) l) l := rfl @[simp] theorem quot_mk_to_coe'' (l : list α) : @eq (multiset α) (quot.mk setoid.r l) l := rfl @[simp] theorem coe_eq_coe {l₁ l₂ : list α} : (l₁ : multiset α) = l₂ ↔ l₁ ~ l₂ := quotient.eq instance has_decidable_eq [decidable_eq α] : decidable_eq (multiset α) | s₁ s₂ := quotient.rec_on_subsingleton₂ s₁ s₂ $ λ l₁ l₂, decidable_of_iff' _ quotient.eq /- empty multiset -/ /-- `0 : multiset α` is the empty set -/ protected def zero : multiset α := @nil α instance : has_zero (multiset α) := ⟨multiset.zero⟩ instance : has_emptyc (multiset α) := ⟨0⟩ instance : inhabited (multiset α) := ⟨0⟩ @[simp] theorem coe_nil_eq_zero : (@nil α : multiset α) = 0 := rfl @[simp] theorem empty_eq_zero : (∅ : multiset α) = 0 := rfl theorem coe_eq_zero (l : list α) : (l : multiset α) = 0 ↔ l = [] := iff.trans coe_eq_coe perm_nil /- cons -/ /-- `cons a s` is the multiset which contains `s` plus one more instance of `a`. -/ def cons (a : α) (s : multiset α) : multiset α := quot.lift_on s (λ l, (a :: l : multiset α)) (λ l₁ l₂ p, quot.sound ((perm_cons a).2 p)) notation a :: b := cons a b instance : has_insert α (multiset α) := ⟨cons⟩ @[simp] theorem insert_eq_cons (a : α) (s : multiset α) : insert a s = a::s := rfl @[simp] theorem cons_coe (a : α) (l : list α) : (a::l : multiset α) = (a::l : list α) := rfl theorem singleton_coe (a : α) : (a::0 : multiset α) = ([a] : list α) := rfl @[simp] theorem cons_inj_left {a b : α} (s : multiset α) : a::s = b::s ↔ a = b := ⟨quot.induction_on s $ λ l e, have [a] ++ l ~ [b] ++ l, from quotient.exact e, eq_singleton_of_perm $ (perm_app_right_iff _).1 this, congr_arg _⟩ @[simp] theorem cons_inj_right (a : α) : ∀{s t : multiset α}, a::s = a::t ↔ s = t := by rintros ⟨l₁⟩ ⟨l₂⟩; simp [perm_cons] @[recursor 5] protected theorem induction {p : multiset α → Prop} (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a :: s)) : ∀s, p s := by rintros ⟨l⟩; induction l with _ _ ih; [exact h₁, exact h₂ ih] @[elab_as_eliminator] protected theorem induction_on {p : multiset α → Prop} (s : multiset α) (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a :: s)) : p s := multiset.induction h₁ h₂ s theorem cons_swap (a b : α) (s : multiset α) : a :: b :: s = b :: a :: s := quot.induction_on s $ λ l, quotient.sound $ perm.swap _ _ _ section rec variables {C : multiset α → Sort*} /-- Dependent recursor on multisets. TODO: should be @[recursor 6], but then the definition of `multiset.pi` failes with a stack overflow in `whnf`. -/ protected def rec (C_0 : C 0) (C_cons : Πa m, C m → C (a::m)) (C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)) (m : multiset α) : C m := quotient.hrec_on m (@list.rec α (λl, C ⟦l⟧) C_0 (λa l b, C_cons a ⟦l⟧ b)) $ assume l l' h, list.rec_heq_of_perm h (assume a l l' b b' hl, have ⟦l⟧ = ⟦l'⟧, from quot.sound hl, by cc) (assume a a' l, C_cons_heq a a' ⟦l⟧) @[elab_as_eliminator] protected def rec_on (m : multiset α) (C_0 : C 0) (C_cons : Πa m, C m → C (a::m)) (C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)) : C m := multiset.rec C_0 C_cons C_cons_heq m variables {C_0 : C 0} {C_cons : Πa m, C m → C (a::m)} {C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)} @[simp] lemma rec_on_0 : @multiset.rec_on α C (0:multiset α) C_0 C_cons C_cons_heq = C_0 := rfl @[simp] lemma rec_on_cons (a : α) (m : multiset α) : (a :: m).rec_on C_0 C_cons C_cons_heq = C_cons a m (m.rec_on C_0 C_cons C_cons_heq) := quotient.induction_on m $ assume l, rfl end rec section mem /-- `a ∈ s` means that `a` has nonzero multiplicity in `s`. -/ def mem (a : α) (s : multiset α) : Prop := quot.lift_on s (λ l, a ∈ l) (λ l₁ l₂ (e : l₁ ~ l₂), propext $ mem_of_perm e) instance : has_mem α (multiset α) := ⟨mem⟩ @[simp] lemma mem_coe {a : α} {l : list α} : a ∈ (l : multiset α) ↔ a ∈ l := iff.rfl instance decidable_mem [decidable_eq α] (a : α) (s : multiset α) : decidable (a ∈ s) := quot.rec_on_subsingleton s $ list.decidable_mem a @[simp] theorem mem_cons {a b : α} {s : multiset α} : a ∈ b :: s ↔ a = b ∨ a ∈ s := quot.induction_on s $ λ l, iff.rfl lemma mem_cons_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ b :: s := mem_cons.2 $ or.inr h @[simp] theorem mem_cons_self (a : α) (s : multiset α) : a ∈ a :: s := mem_cons.2 (or.inl rfl) theorem exists_cons_of_mem {s : multiset α} {a : α} : a ∈ s → ∃ t, s = a :: t := quot.induction_on s $ λ l (h : a ∈ l), let ⟨l₁, l₂, e⟩ := mem_split h in e.symm ▸ ⟨(l₁++l₂ : list α), quot.sound perm_middle⟩ @[simp] theorem not_mem_zero (a : α) : a ∉ (0 : multiset α) := id theorem eq_zero_of_forall_not_mem {s : multiset α} : (∀x, x ∉ s) → s = 0 := quot.induction_on s $ λ l H, by rw eq_nil_iff_forall_not_mem.mpr H; refl theorem exists_mem_of_ne_zero {s : multiset α} : s ≠ 0 → ∃ a : α, a ∈ s := quot.induction_on s $ assume l hl, match l, hl with | [] := assume h, false.elim $ h rfl | (a :: l) := assume _, ⟨a, by simp⟩ end @[simp] lemma zero_ne_cons {a : α} {m : multiset α} : 0 ≠ a :: m := assume h, have a ∈ (0:multiset α), from h.symm ▸ mem_cons_self _ _, not_mem_zero _ this @[simp] lemma cons_ne_zero {a : α} {m : multiset α} : a :: m ≠ 0 := zero_ne_cons.symm lemma cons_eq_cons {a b : α} {as bs : multiset α} : a :: as = b :: bs ↔ ((a = b ∧ as = bs) ∨ (a ≠ b ∧ ∃cs, as = b :: cs ∧ bs = a :: cs)) := begin haveI : decidable_eq α := classical.dec_eq α, split, { assume eq, by_cases a = b, { subst h, simp * at * }, { have : a ∈ b :: bs, from eq ▸ mem_cons_self _ _, have : a ∈ bs, by simpa [h], rcases exists_cons_of_mem this with ⟨cs, hcs⟩, simp [h, hcs], have : a :: as = b :: a :: cs, by simp [eq, hcs], have : a :: as = a :: b :: cs, by rwa [cons_swap], simpa using this } }, { assume h, rcases h with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩, { simp * }, { simp [*, cons_swap a b] } } end end mem /- subset -/ section subset /-- `s ⊆ t` is the lift of the list subset relation. It means that any element with nonzero multiplicity in `s` has nonzero multiplicity in `t`, but it does not imply that the multiplicity of `a` in `s` is less or equal than in `t`; see `s ≤ t` for this relation. -/ protected def subset (s t : multiset α) : Prop := ∀ ⦃a : α⦄, a ∈ s → a ∈ t instance : has_subset (multiset α) := ⟨multiset.subset⟩ @[simp] theorem coe_subset {l₁ l₂ : list α} : (l₁ : multiset α) ⊆ l₂ ↔ l₁ ⊆ l₂ := iff.rfl @[simp] theorem subset.refl (s : multiset α) : s ⊆ s := λ a h, h theorem subset.trans {s t u : multiset α} : s ⊆ t → t ⊆ u → s ⊆ u := λ h₁ h₂ a m, h₂ (h₁ m) theorem subset_iff {s t : multiset α} : s ⊆ t ↔ (∀⦃x⦄, x ∈ s → x ∈ t) := iff.rfl theorem mem_of_subset {s t : multiset α} {a : α} (h : s ⊆ t) : a ∈ s → a ∈ t := @h _ @[simp] theorem zero_subset (s : multiset α) : 0 ⊆ s := λ a, (not_mem_nil a).elim @[simp] theorem cons_subset {a : α} {s t : multiset α} : (a :: s) ⊆ t ↔ a ∈ t ∧ s ⊆ t := by simp [subset_iff, or_imp_distrib, forall_and_distrib] theorem eq_zero_of_subset_zero {s : multiset α} (h : s ⊆ 0) : s = 0 := eq_zero_of_forall_not_mem h theorem subset_zero {s : multiset α} : s ⊆ 0 ↔ s = 0 := ⟨eq_zero_of_subset_zero, λ xeq, xeq.symm ▸ subset.refl 0⟩ end subset /- multiset order -/ /-- `s ≤ t` means that `s` is a sublist of `t` (up to permutation). Equivalently, `s ≤ t` means that `count a s ≤ count a t` for all `a`. -/ protected def le (s t : multiset α) : Prop := quotient.lift_on₂ s t (<+~) $ λ v₁ v₂ w₁ w₂ p₁ p₂, propext (p₂.subperm_left.trans p₁.subperm_right) instance : partial_order (multiset α) := { le := multiset.le, le_refl := by rintros ⟨l⟩; exact subperm.refl _, le_trans := by rintros ⟨l₁⟩ ⟨l₂⟩ ⟨l₃⟩; exact @subperm.trans _ _ _ _, le_antisymm := by rintros ⟨l₁⟩ ⟨l₂⟩ h₁ h₂; exact quot.sound (subperm.antisymm h₁ h₂) } theorem subset_of_le {s t : multiset α} : s ≤ t → s ⊆ t := quotient.induction_on₂ s t $ λ l₁ l₂, subset_of_subperm theorem mem_of_le {s t : multiset α} {a : α} (h : s ≤ t) : a ∈ s → a ∈ t := mem_of_subset (subset_of_le h) @[simp] theorem coe_le {l₁ l₂ : list α} : (l₁ : multiset α) ≤ l₂ ↔ l₁ <+~ l₂ := iff.rfl @[elab_as_eliminator] theorem le_induction_on {C : multiset α → multiset α → Prop} {s t : multiset α} (h : s ≤ t) (H : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → C l₁ l₂) : C s t := quotient.induction_on₂ s t (λ l₁ l₂ ⟨l, p, s⟩, (show ⟦l⟧ = ⟦l₁⟧, from quot.sound p) ▸ H s) h theorem zero_le (s : multiset α) : 0 ≤ s := quot.induction_on s $ λ l, subperm_of_sublist $ nil_sublist l theorem le_zero {s : multiset α} : s ≤ 0 ↔ s = 0 := ⟨λ h, le_antisymm h (zero_le _), le_of_eq⟩ theorem lt_cons_self (s : multiset α) (a : α) : s < a :: s := quot.induction_on s $ λ l, suffices l <+~ a :: l ∧ (¬l ~ a :: l), by simpa [lt_iff_le_and_ne], ⟨subperm_of_sublist (sublist_cons _ _), λ p, ne_of_lt (lt_succ_self (length l)) (perm_length p)⟩ theorem le_cons_self (s : multiset α) (a : α) : s ≤ a :: s := le_of_lt $ lt_cons_self _ _ theorem cons_le_cons_iff (a : α) {s t : multiset α} : a :: s ≤ a :: t ↔ s ≤ t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_cons a theorem cons_le_cons (a : α) {s t : multiset α} : s ≤ t → a :: s ≤ a :: t := (cons_le_cons_iff a).2 theorem le_cons_of_not_mem {a : α} {s t : multiset α} (m : a ∉ s) : s ≤ a :: t ↔ s ≤ t := begin refine ⟨_, λ h, le_trans h $ le_cons_self _ _⟩, suffices : ∀ {t'} (_ : s ≤ t') (_ : a ∈ t'), a :: s ≤ t', { exact λ h, (cons_le_cons_iff a).1 (this h (mem_cons_self _ _)) }, introv h, revert m, refine le_induction_on h _, introv s m₁ m₂, rcases mem_split m₂ with ⟨r₁, r₂, rfl⟩, exact perm_middle.subperm_left.2 ((subperm_cons _).2 $ subperm_of_sublist $ (sublist_or_mem_of_sublist s).resolve_right m₁) end /- cardinality -/ /-- The cardinality of a multiset is the sum of the multiplicities of all its elements, or simply the length of the underlying list. -/ def card (s : multiset α) : ℕ := quot.lift_on s length $ λ l₁ l₂, perm_length @[simp] theorem coe_card (l : list α) : card (l : multiset α) = length l := rfl @[simp] theorem card_zero : @card α 0 = 0 := rfl @[simp] theorem card_cons (a : α) (s : multiset α) : card (a :: s) = card s + 1 := quot.induction_on s $ λ l, rfl @[simp] theorem card_singleton (a : α) : card (a::0) = 1 := by simp theorem card_le_of_le {s t : multiset α} (h : s ≤ t) : card s ≤ card t := le_induction_on h $ λ l₁ l₂, length_le_of_sublist theorem eq_of_le_of_card_le {s t : multiset α} (h : s ≤ t) : card t ≤ card s → s = t := le_induction_on h $ λ l₁ l₂ s h₂, congr_arg coe $ eq_of_sublist_of_length_le s h₂ theorem card_lt_of_lt {s t : multiset α} (h : s < t) : card s < card t := lt_of_not_ge $ λ h₂, ne_of_lt h $ eq_of_le_of_card_le (le_of_lt h) h₂ theorem lt_iff_cons_le {s t : multiset α} : s < t ↔ ∃ a, a :: s ≤ t := ⟨quotient.induction_on₂ s t $ λ l₁ l₂ h, subperm.exists_of_length_lt (le_of_lt h) (card_lt_of_lt h), λ ⟨a, h⟩, lt_of_lt_of_le (lt_cons_self _ _) h⟩ @[simp] theorem card_eq_zero {s : multiset α} : card s = 0 ↔ s = 0 := ⟨λ h, (eq_of_le_of_card_le (zero_le _) (le_of_eq h)).symm, λ e, by simp [e]⟩ theorem card_pos {s : multiset α} : 0 < card s ↔ s ≠ 0 := pos_iff_ne_zero.trans $ not_congr card_eq_zero theorem card_pos_iff_exists_mem {s : multiset α} : 0 < card s ↔ ∃ a, a ∈ s := quot.induction_on s $ λ l, length_pos_iff_exists_mem @[elab_as_eliminator] def strong_induction_on {p : multiset α → Sort*} : ∀ (s : multiset α), (∀ s, (∀t < s, p t) → p s) → p s | s := λ ih, ih s $ λ t h, have card t < card s, from card_lt_of_lt h, strong_induction_on t ih using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf card⟩]} theorem strong_induction_eq {p : multiset α → Sort*} (s : multiset α) (H) : @strong_induction_on _ p s H = H s (λ t h, @strong_induction_on _ p t H) := by rw [strong_induction_on] @[elab_as_eliminator] lemma case_strong_induction_on {p : multiset α → Prop} (s : multiset α) (h₀ : p 0) (h₁ : ∀ a s, (∀t ≤ s, p t) → p (a :: s)) : p s := multiset.strong_induction_on s $ assume s, multiset.induction_on s (λ _, h₀) $ λ a s _ ih, h₁ _ _ $ λ t h, ih _ $ lt_of_le_of_lt h $ lt_cons_self _ _ /- singleton -/ @[simp] theorem singleton_eq_singleton (a : α) : singleton a = a::0 := rfl @[simp] theorem mem_singleton {a b : α} : b ∈ a::0 ↔ b = a := by simp theorem mem_singleton_self (a : α) : a ∈ (a::0 : multiset α) := mem_cons_self _ _ theorem singleton_inj {a b : α} : a::0 = b::0 ↔ a = b := cons_inj_left _ @[simp] theorem singleton_ne_zero (a : α) : a::0 ≠ 0 := ne_of_gt (lt_cons_self _ _) @[simp] theorem singleton_le {a : α} {s : multiset α} : a::0 ≤ s ↔ a ∈ s := ⟨λ h, mem_of_le h (mem_singleton_self _), λ h, let ⟨t, e⟩ := exists_cons_of_mem h in e.symm ▸ cons_le_cons _ (zero_le _)⟩ theorem card_eq_one {s : multiset α} : card s = 1 ↔ ∃ a, s = a::0 := ⟨quot.induction_on s $ λ l h, (list.length_eq_one.1 h).imp $ λ a, congr_arg coe, λ ⟨a, e⟩, e.symm ▸ rfl⟩ /- add -/ /-- The sum of two multisets is the lift of the list append operation. This adds the multiplicities of each element, i.e. `count a (s + t) = count a s + count a t`. -/ protected def add (s₁ s₂ : multiset α) : multiset α := quotient.lift_on₂ s₁ s₂ (λ l₁ l₂, ((l₁ ++ l₂ : list α) : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_app p₁ p₂ instance : has_add (multiset α) := ⟨multiset.add⟩ @[simp] theorem coe_add (s t : list α) : (s + t : multiset α) = (s ++ t : list α) := rfl protected theorem add_comm (s t : multiset α) : s + t = t + s := quotient.induction_on₂ s t $ λ l₁ l₂, quot.sound perm_app_comm protected theorem zero_add (s : multiset α) : 0 + s = s := quot.induction_on s $ λ l, rfl theorem singleton_add (a : α) (s : multiset α) : ↑[a] + s = a::s := rfl protected theorem add_le_add_left (s) {t u : multiset α} : s + t ≤ s + u ↔ t ≤ u := quotient.induction_on₃ s t u $ λ l₁ l₂ l₃, subperm_app_left _ protected theorem add_left_cancel (s) {t u : multiset α} (h : s + t = s + u) : t = u := le_antisymm ((multiset.add_le_add_left _).1 (le_of_eq h)) ((multiset.add_le_add_left _).1 (le_of_eq h.symm)) instance : ordered_cancel_comm_monoid (multiset α) := { zero := 0, add := (+), add_comm := multiset.add_comm, add_assoc := λ s₁ s₂ s₃, quotient.induction_on₃ s₁ s₂ s₃ $ λ l₁ l₂ l₃, congr_arg coe $ append_assoc l₁ l₂ l₃, zero_add := multiset.zero_add, add_zero := λ s, by rw [multiset.add_comm, multiset.zero_add], add_left_cancel := multiset.add_left_cancel, add_right_cancel := λ s₁ s₂ s₃ h, multiset.add_left_cancel s₂ $ by simpa [multiset.add_comm] using h, add_le_add_left := λ s₁ s₂ h s₃, (multiset.add_le_add_left _).2 h, le_of_add_le_add_left := λ s₁ s₂ s₃, (multiset.add_le_add_left _).1, ..@multiset.partial_order α } @[simp] theorem cons_add (a : α) (s t : multiset α) : a :: s + t = a :: (s + t) := by rw [← singleton_add, ← singleton_add, add_assoc] @[simp] theorem add_cons (a : α) (s t : multiset α) : s + a :: t = a :: (s + t) := by rw [add_comm, cons_add, add_comm] theorem le_add_right (s t : multiset α) : s ≤ s + t := by simpa using add_le_add_left (zero_le t) s theorem le_add_left (s t : multiset α) : s ≤ t + s := by simpa using add_le_add_right (zero_le t) s @[simp] theorem card_add (s t : multiset α) : card (s + t) = card s + card t := quotient.induction_on₂ s t length_append lemma card_smul (s : multiset α) (n : ℕ) : (n • s).card = n * s.card := by induction n; simp [succ_smul, *, nat.succ_mul] @[simp] theorem mem_add {a : α} {s t : multiset α} : a ∈ s + t ↔ a ∈ s ∨ a ∈ t := quotient.induction_on₂ s t $ λ l₁ l₂, mem_append theorem le_iff_exists_add {s t : multiset α} : s ≤ t ↔ ∃ u, t = s + u := ⟨λ h, le_induction_on h $ λ l₁ l₂ s, let ⟨l, p⟩ := exists_perm_append_of_sublist s in ⟨l, quot.sound p⟩, λ⟨u, e⟩, e.symm ▸ le_add_right s u⟩ instance : canonically_ordered_monoid (multiset α) := { lt_of_add_lt_add_left := @lt_of_add_lt_add_left _ _, le_iff_exists_add := @le_iff_exists_add _, bot := 0, bot_le := multiset.zero_le, ..multiset.ordered_cancel_comm_monoid } /- repeat -/ /-- `repeat a n` is the multiset containing only `a` with multiplicity `n`. -/ def repeat (a : α) (n : ℕ) : multiset α := repeat a n @[simp] lemma repeat_zero (a : α) : repeat a 0 = 0 := rfl @[simp] lemma repeat_succ (a : α) (n) : repeat a (n+1) = a :: repeat a n := by simp [repeat] @[simp] lemma repeat_one (a : α) : repeat a 1 = a :: 0 := by simp @[simp] lemma card_repeat : ∀ (a : α) n, card (repeat a n) = n := length_repeat theorem eq_of_mem_repeat {a b : α} {n} : b ∈ repeat a n → b = a := eq_of_mem_repeat theorem eq_repeat' {a : α} {s : multiset α} : s = repeat a s.card ↔ ∀ b ∈ s, b = a := quot.induction_on s $ λ l, iff.trans ⟨λ h, (perm_repeat.1 $ (quotient.exact h).symm).symm, congr_arg coe⟩ eq_repeat' theorem eq_repeat_of_mem {a : α} {s : multiset α} : (∀ b ∈ s, b = a) → s = repeat a s.card := eq_repeat'.2 theorem eq_repeat {a : α} {n} {s : multiset α} : s = repeat a n ↔ card s = n ∧ ∀ b ∈ s, b = a := ⟨λ h, h.symm ▸ ⟨card_repeat _ _, λ b, eq_of_mem_repeat⟩, λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩ theorem repeat_subset_singleton : ∀ (a : α) n, repeat a n ⊆ a::0 := repeat_subset_singleton theorem repeat_le_coe {a : α} {n} {l : list α} : repeat a n ≤ l ↔ list.repeat a n <+ l := ⟨λ ⟨l', p, s⟩, (perm_repeat.1 p.symm).symm ▸ s, subperm_of_sublist⟩ /- range -/ /-- `range n` is the multiset lifted from the list `range n`, that is, the set `{0, 1, ..., n-1}`. -/ def range (n : ℕ) : multiset ℕ := range n @[simp] theorem range_zero : range 0 = 0 := rfl @[simp] theorem range_succ (n : ℕ) : range (succ n) = n :: range n := by rw [range, range_concat, ← coe_add, add_comm]; refl @[simp] theorem card_range (n : ℕ) : card (range n) = n := length_range _ theorem range_subset {m n : ℕ} : range m ⊆ range n ↔ m ≤ n := range_subset @[simp] theorem mem_range {m n : ℕ} : m ∈ range n ↔ m < n := mem_range @[simp] theorem not_mem_range_self {n : ℕ} : n ∉ range n := not_mem_range_self /- erase -/ section erase variables [decidable_eq α] {s t : multiset α} {a b : α} /-- `erase s a` is the multiset that subtracts 1 from the multiplicity of `a`. -/ def erase (s : multiset α) (a : α) : multiset α := quot.lift_on s (λ l, (l.erase a : multiset α)) (λ l₁ l₂ p, quot.sound (erase_perm_erase a p)) @[simp] theorem coe_erase (l : list α) (a : α) : erase (l : multiset α) a = l.erase a := rfl @[simp] theorem erase_zero (a : α) : (0 : multiset α).erase a = 0 := rfl @[simp] theorem erase_cons_head (a : α) (s : multiset α) : (a :: s).erase a = s := quot.induction_on s $ λ l, congr_arg coe $ erase_cons_head a l @[simp] theorem erase_cons_tail {a b : α} (s : multiset α) (h : b ≠ a) : (b::s).erase a = b :: s.erase a := quot.induction_on s $ λ l, congr_arg coe $ erase_cons_tail l h @[simp] theorem erase_of_not_mem {a : α} {s : multiset α} : a ∉ s → s.erase a = s := quot.induction_on s $ λ l h, congr_arg coe $ erase_of_not_mem h @[simp] theorem cons_erase {s : multiset α} {a : α} : a ∈ s → a :: s.erase a = s := quot.induction_on s $ λ l h, quot.sound (perm_erase h).symm theorem le_cons_erase (s : multiset α) (a : α) : s ≤ a :: s.erase a := if h : a ∈ s then le_of_eq (cons_erase h).symm else by rw erase_of_not_mem h; apply le_cons_self @[simp] theorem card_erase_of_mem {a : α} {s : multiset α} : a ∈ s → card (s.erase a) = pred (card s) := quot.induction_on s $ λ l, length_erase_of_mem theorem erase_add_left_pos {a : α} {s : multiset α} (t) : a ∈ s → (s + t).erase a = s.erase a + t := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_left l₂ h theorem erase_add_right_pos {a : α} (s) {t : multiset α} (h : a ∈ t) : (s + t).erase a = s + t.erase a := by rw [add_comm, erase_add_left_pos s h, add_comm] theorem erase_add_right_neg {a : α} {s : multiset α} (t) : a ∉ s → (s + t).erase a = s + t.erase a := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_right l₂ h theorem erase_add_left_neg {a : α} (s) {t : multiset α} (h : a ∉ t) : (s + t).erase a = s.erase a + t := by rw [add_comm, erase_add_right_neg s h, add_comm] theorem erase_le (a : α) (s : multiset α) : s.erase a ≤ s := quot.induction_on s $ λ l, subperm_of_sublist (erase_sublist a l) @[simp] theorem erase_lt {a : α} {s : multiset α} : s.erase a < s ↔ a ∈ s := ⟨λ h, not_imp_comm.1 erase_of_not_mem (ne_of_lt h), λ h, by simpa [h] using lt_cons_self (s.erase a) a⟩ theorem erase_subset (a : α) (s : multiset α) : s.erase a ⊆ s := subset_of_le (erase_le a s) theorem mem_erase_of_ne {a b : α} {s : multiset α} (ab : a ≠ b) : a ∈ s.erase b ↔ a ∈ s := quot.induction_on s $ λ l, list.mem_erase_of_ne ab theorem mem_of_mem_erase {a b : α} {s : multiset α} : a ∈ s.erase b → a ∈ s := mem_of_subset (erase_subset _ _) theorem erase_comm (s : multiset α) (a b : α) : (s.erase a).erase b = (s.erase b).erase a := quot.induction_on s $ λ l, congr_arg coe $ l.erase_comm a b theorem erase_le_erase {s t : multiset α} (a : α) (h : s ≤ t) : s.erase a ≤ t.erase a := le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist (erase_sublist_erase _ h) theorem erase_le_iff_le_cons {s t : multiset α} {a : α} : s.erase a ≤ t ↔ s ≤ a :: t := ⟨λ h, le_trans (le_cons_erase _ _) (cons_le_cons _ h), λ h, if m : a ∈ s then by rw ← cons_erase m at h; exact (cons_le_cons_iff _).1 h else le_trans (erase_le _ _) ((le_cons_of_not_mem m).1 h)⟩ end erase @[simp] theorem coe_reverse (l : list α) : (reverse l : multiset α) = l := quot.sound $ reverse_perm _ /- map -/ /-- `map f s` is the lift of the list `map` operation. The multiplicity of `b` in `map f s` is the number of `a ∈ s` (counting multiplicity) such that `f a = b`. -/ def map (f : α → β) (s : multiset α) : multiset β := quot.lift_on s (λ l : list α, (l.map f : multiset β)) (λ l₁ l₂ p, quot.sound (perm_map f p)) @[simp] theorem coe_map (f : α → β) (l : list α) : map f ↑l = l.map f := rfl @[simp] theorem map_zero (f : α → β) : map f 0 = 0 := rfl @[simp] theorem map_cons (f : α → β) (a s) : map f (a::s) = f a :: map f s := quot.induction_on s $ λ l, rfl @[simp] lemma map_singleton (f : α → β) (a : α) : ({a} : multiset α).map f = {f a} := rfl @[simp] theorem map_add (f : α → β) (s t) : map f (s + t) = map f s + map f t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ map_append _ _ _ instance (f : α → β) : is_add_monoid_hom (map f) := { map_add := map_add _, map_zero := map_zero _ } @[simp] theorem mem_map {f : α → β} {b : β} {s : multiset α} : b ∈ map f s ↔ ∃ a, a ∈ s ∧ f a = b := quot.induction_on s $ λ l, mem_map @[simp] theorem card_map (f : α → β) (s) : card (map f s) = card s := quot.induction_on s $ λ l, length_map _ _ theorem mem_map_of_mem (f : α → β) {a : α} {s : multiset α} (h : a ∈ s) : f a ∈ map f s := mem_map.2 ⟨_, h, rfl⟩ @[simp] theorem mem_map_of_inj {f : α → β} (H : function.injective f) {a : α} {s : multiset α} : f a ∈ map f s ↔ a ∈ s := quot.induction_on s $ λ l, mem_map_of_inj H @[simp] theorem map_map (g : β → γ) (f : α → β) (s : multiset α) : map g (map f s) = map (g ∘ f) s := quot.induction_on s $ λ l, congr_arg coe $ list.map_map _ _ _ @[simp] theorem map_id (s : multiset α) : map id s = s := quot.induction_on s $ λ l, congr_arg coe $ map_id _ @[simp] lemma map_id' (s : multiset α) : map (λx, x) s = s := map_id s @[simp] theorem map_const (s : multiset α) (b : β) : map (function.const α b) s = repeat b s.card := quot.induction_on s $ λ l, congr_arg coe $ map_const _ _ @[congr] theorem map_congr {f g : α → β} {s : multiset α} : (∀ x ∈ s, f x = g x) → map f s = map g s := quot.induction_on s $ λ l H, congr_arg coe $ map_congr H lemma map_hcongr {β' : Type*} {m : multiset α} {f : α → β} {f' : α → β'} (h : β = β') (hf : ∀a∈m, f a == f' a) : map f m == map f' m := begin subst h, simp at hf, simp [map_congr hf] end theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ := eq_of_mem_repeat $ by rwa map_const at h @[simp] theorem map_le_map {f : α → β} {s t : multiset α} (h : s ≤ t) : map f s ≤ map f t := le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist $ map_sublist_map f h @[simp] theorem map_subset_map {f : α → β} {s t : multiset α} (H : s ⊆ t) : map f s ⊆ map f t := λ b m, let ⟨a, h, e⟩ := mem_map.1 m in mem_map.2 ⟨a, H h, e⟩ /- fold -/ /-- `foldl f H b s` is the lift of the list operation `foldl f b l`, which folds `f` over the multiset. It is well defined when `f` is right-commutative, that is, `f (f b a₁) a₂ = f (f b a₂) a₁`. -/ def foldl (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : β := quot.lift_on s (λ l, foldl f b l) (λ l₁ l₂ p, foldl_eq_of_perm H p b) @[simp] theorem foldl_zero (f : β → α → β) (H b) : foldl f H b 0 = b := rfl @[simp] theorem foldl_cons (f : β → α → β) (H b a s) : foldl f H b (a :: s) = foldl f H (f b a) s := quot.induction_on s $ λ l, rfl @[simp] theorem foldl_add (f : β → α → β) (H b s t) : foldl f H b (s + t) = foldl f H (foldl f H b s) t := quotient.induction_on₂ s t $ λ l₁ l₂, foldl_append _ _ _ _ /-- `foldr f H b s` is the lift of the list operation `foldr f b l`, which folds `f` over the multiset. It is well defined when `f` is left-commutative, that is, `f a₁ (f a₂ b) = f a₂ (f a₁ b)`. -/ def foldr (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : β := quot.lift_on s (λ l, foldr f b l) (λ l₁ l₂ p, foldr_eq_of_perm H p b) @[simp] theorem foldr_zero (f : α → β → β) (H b) : foldr f H b 0 = b := rfl @[simp] theorem foldr_cons (f : α → β → β) (H b a s) : foldr f H b (a :: s) = f a (foldr f H b s) := quot.induction_on s $ λ l, rfl @[simp] theorem foldr_add (f : α → β → β) (H b s t) : foldr f H b (s + t) = foldr f H (foldr f H b t) s := quotient.induction_on₂ s t $ λ l₁ l₂, foldr_append _ _ _ _ @[simp] theorem coe_foldr (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) : foldr f H b l = l.foldr f b := rfl @[simp] theorem coe_foldl (f : β → α → β) (H : right_commutative f) (b : β) (l : list α) : foldl f H b l = l.foldl f b := rfl theorem coe_foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) : foldr f H b l = l.foldl (λ x y, f y x) b := (congr_arg (foldr f H b) (coe_reverse l)).symm.trans $ foldr_reverse _ _ _ theorem foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : foldr f H b s = foldl (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s := quot.induction_on s $ λ l, coe_foldr_swap _ _ _ _ theorem foldl_swap (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : foldl f H b s = foldr (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s := (foldr_swap _ _ _ _).symm /-- Product of a multiset given a commutative monoid structure on `α`. `prod {a, b, c} = a * b * c` -/ def prod [comm_monoid α] : multiset α → α := foldr (*) (λ x y z, by simp [mul_left_comm]) 1 attribute [to_additive multiset.sum._proof_1] prod._proof_1 attribute [to_additive multiset.sum] prod @[to_additive multiset.sum_eq_foldr] theorem prod_eq_foldr [comm_monoid α] (s : multiset α) : prod s = foldr (*) (λ x y z, by simp [mul_left_comm]) 1 s := rfl @[to_additive multiset.sum_eq_foldl] theorem prod_eq_foldl [comm_monoid α] (s : multiset α) : prod s = foldl (*) (λ x y z, by simp [mul_right_comm]) 1 s := (foldr_swap _ _ _ _).trans (by simp [mul_comm]) @[simp, to_additive multiset.coe_sum] theorem coe_prod [comm_monoid α] (l : list α) : prod ↑l = l.prod := prod_eq_foldl _ @[simp, to_additive multiset.sum_zero] theorem prod_zero [comm_monoid α] : @prod α _ 0 = 1 := rfl @[simp, to_additive multiset.sum_cons] theorem prod_cons [comm_monoid α] (a : α) (s) : prod (a :: s) = a * prod s := foldr_cons _ _ _ _ _ @[to_additive multiset.sum_singleton] theorem prod_singleton [comm_monoid α] (a : α) : prod (a :: 0) = a := by simp @[simp, to_additive multiset.sum_add] theorem prod_add [comm_monoid α] (s t : multiset α) : prod (s + t) = prod s * prod t := quotient.induction_on₂ s t $ λ l₁ l₂, by simp instance sum.is_add_monoid_hom [add_comm_monoid α] : is_add_monoid_hom (sum : multiset α → α) := { map_add := sum_add, map_zero := sum_zero } lemma prod_smul {α : Type*} [comm_monoid α] (m : multiset α) : ∀n, (add_monoid.smul n m).prod = m.prod ^ n | 0 := rfl | (n + 1) := by rw [add_monoid.add_smul, add_monoid.one_smul, _root_.pow_add, _root_.pow_one, prod_add, prod_smul n] @[simp] theorem prod_repeat [comm_monoid α] (a : α) (n : ℕ) : prod (multiset.repeat a n) = a ^ n := by simp [repeat, list.prod_repeat] @[simp] theorem sum_repeat [add_comm_monoid α] : ∀ (a : α) (n : ℕ), sum (multiset.repeat a n) = n • a := @prod_repeat (multiplicative α) _ attribute [to_additive multiset.sum_repeat] prod_repeat @[simp] lemma prod_map_one [comm_monoid γ] {m : multiset α} : prod (m.map (λa, (1 : γ))) = (1 : γ) := multiset.induction_on m (by simp) (by simp) @[simp] lemma sum_map_zero [add_comm_monoid γ] {m : multiset α} : sum (m.map (λa, (0 : γ))) = (0 : γ) := multiset.induction_on m (by simp) (by simp) attribute [to_additive multiset.sum_map_zero] prod_map_one @[simp, to_additive multiset.sum_map_add] lemma prod_map_mul [comm_monoid γ] {m : multiset α} {f g : α → γ} : prod (m.map $ λa, f a * g a) = prod (m.map f) * prod (m.map g) := multiset.induction_on m (by simp) (assume a m ih, by simp [ih]; cc) lemma prod_map_prod_map [comm_monoid γ] (m : multiset α) (n : multiset β) {f : α → β → γ} : prod (m.map $ λa, prod $ n.map $ λb, f a b) = prod (n.map $ λb, prod $ m.map $ λa, f a b) := multiset.induction_on m (by simp) (assume a m ih, by simp [ih]) lemma sum_map_sum_map [add_comm_monoid γ] : ∀ (m : multiset α) (n : multiset β) {f : α → β → γ}, sum (m.map $ λa, sum $ n.map $ λb, f a b) = sum (n.map $ λb, sum $ m.map $ λa, f a b) := @prod_map_prod_map _ _ (multiplicative γ) _ attribute [to_additive multiset.sum_map_sum_map] prod_map_prod_map lemma sum_map_mul_left [semiring β] {b : β} {s : multiset α} {f : α → β} : sum (s.map (λa, b * f a)) = b * sum (s.map f) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, mul_add]) lemma sum_map_mul_right [semiring β] {b : β} {s : multiset α} {f : α → β} : sum (s.map (λa, f a * b)) = sum (s.map f) * b := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, add_mul]) lemma prod_hom [comm_monoid α] [comm_monoid β] (f : α → β) [is_monoid_hom f] (s : multiset α) : (s.map f).prod = f s.prod := multiset.induction_on s (by simp [is_monoid_hom.map_one f]) (by simp [is_monoid_hom.map_mul f] {contextual := tt}) lemma dvd_prod [comm_semiring α] {a : α} {s : multiset α} : a ∈ s → a ∣ s.prod := quotient.induction_on s (λ l a h, by simpa using list.dvd_prod h) a lemma sum_hom [add_comm_monoid α] [add_comm_monoid β] (f : α → β) [is_add_monoid_hom f] (s : multiset α) : (s.map f).sum = f s.sum := multiset.induction_on s (by simp [is_add_monoid_hom.map_zero f]) (by simp [is_add_monoid_hom.map_add f] {contextual := tt}) attribute [to_additive multiset.sum_hom] multiset.prod_hom lemma le_sum_of_subadditive [add_comm_monoid α] [ordered_comm_monoid β] (f : α → β) (h_zero : f 0 = 0) (h_add : ∀x y, f (x + y) ≤ f x + f y) (s : multiset α) : f s.sum ≤ (s.map f).sum := multiset.induction_on s (le_of_eq h_zero) $ assume a s ih, by rw [sum_cons, map_cons, sum_cons]; from le_trans (h_add a s.sum) (add_le_add_left' ih) lemma abs_sum_le_sum_abs [discrete_linear_ordered_field α] {s : multiset α} : abs s.sum ≤ (s.map abs).sum := le_sum_of_subadditive _ abs_zero abs_add s /- join -/ /-- `join S`, where `S` is a multiset of multisets, is the lift of the list join operation, that is, the union of all the sets. join {{1, 2}, {1, 2}, {0, 1}} = {0, 1, 1, 1, 2, 2} -/ def join : multiset (multiset α) → multiset α := sum theorem coe_join : ∀ L : list (list α), join (L.map (@coe _ (multiset α) _) : multiset (multiset α)) = L.join | [] := rfl | (l :: L) := congr_arg (λ s : multiset α, ↑l + s) (coe_join L) @[simp] theorem join_zero : @join α 0 = 0 := rfl @[simp] theorem join_cons (s S) : @join α (s :: S) = s + join S := sum_cons _ _ @[simp] theorem join_add (S T) : @join α (S + T) = join S + join T := sum_add _ _ @[simp] theorem mem_join {a S} : a ∈ @join α S ↔ ∃ s ∈ S, a ∈ s := multiset.induction_on S (by simp) $ by simp [or_and_distrib_right, exists_or_distrib] {contextual := tt} @[simp] theorem card_join (S) : card (@join α S) = sum (map card S) := multiset.induction_on S (by simp) (by simp) /- bind -/ /-- `bind s f` is the monad bind operation, defined as `join (map f s)`. It is the union of `f a` as `a` ranges over `s`. -/ def bind (s : multiset α) (f : α → multiset β) : multiset β := join (map f s) @[simp] theorem coe_bind (l : list α) (f : α → list β) : @bind α β l (λ a, f a) = l.bind f := by rw [list.bind, ← coe_join, list.map_map]; refl @[simp] theorem zero_bind (f : α → multiset β) : bind 0 f = 0 := rfl @[simp] theorem cons_bind (a s) (f : α → multiset β) : bind (a::s) f = f a + bind s f := by simp [bind] @[simp] theorem add_bind (s t) (f : α → multiset β) : bind (s + t) f = bind s f + bind t f := by simp [bind] @[simp] theorem bind_zero (s : multiset α) : bind s (λa, 0 : α → multiset β) = 0 := by simp [bind, -map_const, join] @[simp] theorem bind_add (s : multiset α) (f g : α → multiset β) : bind s (λa, f a + g a) = bind s f + bind s g := by simp [bind, join] @[simp] theorem bind_cons (s : multiset α) (f : α → β) (g : α → multiset β) : bind s (λa, f a :: g a) = map f s + bind s g := multiset.induction_on s (by simp) (by simp {contextual := tt}) @[simp] theorem mem_bind {b s} {f : α → multiset β} : b ∈ bind s f ↔ ∃ a ∈ s, b ∈ f a := by simp [bind]; simp [-exists_and_distrib_right, exists_and_distrib_right.symm]; rw exists_swap; simp [and_assoc] @[simp] theorem card_bind (s) (f : α → multiset β) : card (bind s f) = sum (map (card ∘ f) s) := by simp [bind] lemma bind_congr {f g : α → multiset β} {m : multiset α} : (∀a∈m, f a = g a) → bind m f = bind m g := by simp [bind] {contextual := tt} lemma bind_hcongr {β' : Type*} {m : multiset α} {f : α → multiset β} {f' : α → multiset β'} (h : β = β') (hf : ∀a∈m, f a == f' a) : bind m f == bind m f' := begin subst h, simp at hf, simp [bind_congr hf] end lemma map_bind (m : multiset α) (n : α → multiset β) (f : β → γ) : map f (bind m n) = bind m (λa, map f (n a)) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_map (m : multiset α) (n : β → multiset γ) (f : α → β) : bind (map f m) n = bind m (λa, n (f a)) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_assoc {s : multiset α} {f : α → multiset β} {g : β → multiset γ} : (s.bind f).bind g = s.bind (λa, (f a).bind g) := multiset.induction_on s (by simp) (by simp {contextual := tt}) lemma bind_bind (m : multiset α) (n : multiset β) {f : α → β → multiset γ} : (bind m $ λa, bind n $ λb, f a b) = (bind n $ λb, bind m $ λa, f a b) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_map_comm (m : multiset α) (n : multiset β) {f : α → β → γ} : (bind m $ λa, n.map $ λb, f a b) = (bind n $ λb, m.map $ λa, f a b) := multiset.induction_on m (by simp) (by simp {contextual := tt}) @[simp, to_additive multiset.sum_bind] lemma prod_bind [comm_monoid β] (s : multiset α) (t : α → multiset β) : prod (bind s t) = prod (s.map $ λa, prod (t a)) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, cons_bind]) /- product -/ /-- The multiplicity of `(a, b)` in `product s t` is the product of the multiplicity of `a` in `s` and `b` in `t`. -/ def product (s : multiset α) (t : multiset β) : multiset (α × β) := s.bind $ λ a, t.map $ prod.mk a @[simp] theorem coe_product (l₁ : list α) (l₂ : list β) : @product α β l₁ l₂ = l₁.product l₂ := by rw [product, list.product, ← coe_bind]; simp @[simp] theorem zero_product (t) : @product α β 0 t = 0 := rfl @[simp] theorem cons_product (a : α) (s : multiset α) (t : multiset β) : product (a :: s) t = map (prod.mk a) t + product s t := by simp [product] @[simp] theorem product_singleton (a : α) (b : β) : product (a::0) (b::0) = (a,b)::0 := rfl @[simp] theorem add_product (s t : multiset α) (u : multiset β) : product (s + t) u = product s u + product t u := by simp [product] @[simp] theorem product_add (s : multiset α) : ∀ t u : multiset β, product s (t + u) = product s t + product s u := multiset.induction_on s (λ t u, rfl) $ λ a s IH t u, by rw [cons_product, IH]; simp @[simp] theorem mem_product {s t} : ∀ {p : α × β}, p ∈ @product α β s t ↔ p.1 ∈ s ∧ p.2 ∈ t | (a, b) := by simp [product, and.left_comm] @[simp] theorem card_product (s : multiset α) (t : multiset β) : card (product s t) = card s * card t := by simp [product, repeat, (∘), mul_comm] /- sigma -/ section variable {σ : α → Type*} /-- `sigma s t` is the dependent version of `product`. It is the sum of `(a, b)` as `a` ranges over `s` and `b` ranges over `t a`. -/ protected def sigma (s : multiset α) (t : Π a, multiset (σ a)) : multiset (Σ a, σ a) := s.bind $ λ a, (t a).map $ sigma.mk a @[simp] theorem coe_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) : @multiset.sigma α σ l₁ (λ a, l₂ a) = l₁.sigma l₂ := by rw [multiset.sigma, list.sigma, ← coe_bind]; simp @[simp] theorem zero_sigma (t) : @multiset.sigma α σ 0 t = 0 := rfl @[simp] theorem cons_sigma (a : α) (s : multiset α) (t : Π a, multiset (σ a)) : (a :: s).sigma t = map (sigma.mk a) (t a) + s.sigma t := by simp [multiset.sigma] @[simp] theorem sigma_singleton (a : α) (b : α → β) : (a::0).sigma (λ a, b a::0) = ⟨a, b a⟩::0 := rfl @[simp] theorem add_sigma (s t : multiset α) (u : Π a, multiset (σ a)) : (s + t).sigma u = s.sigma u + t.sigma u := by simp [multiset.sigma] @[simp] theorem sigma_add (s : multiset α) : ∀ t u : Π a, multiset (σ a), s.sigma (λ a, t a + u a) = s.sigma t + s.sigma u := multiset.induction_on s (λ t u, rfl) $ λ a s IH t u, by rw [cons_sigma, IH]; simp @[simp] theorem mem_sigma {s t} : ∀ {p : Σ a, σ a}, p ∈ @multiset.sigma α σ s t ↔ p.1 ∈ s ∧ p.2 ∈ t p.1 | ⟨a, b⟩ := by simp [multiset.sigma, and_assoc, and.left_comm] @[simp] theorem card_sigma (s : multiset α) (t : Π a, multiset (σ a)) : card (s.sigma t) = sum (map (λ a, card (t a)) s) := by simp [multiset.sigma, (∘)] end /- map for partial functions -/ /-- Lift of the list `pmap` operation. Map a partial function `f` over a multiset `s` whose elements are all in the domain of `f`. -/ def pmap {p : α → Prop} (f : Π a, p a → β) (s : multiset α) : (∀ a ∈ s, p a) → multiset β := quot.rec_on s (λ l H, ↑(pmap f l H)) $ λ l₁ l₂ (pp : l₁ ~ l₂), funext $ λ (H₂ : ∀ a ∈ l₂, p a), have H₁ : ∀ a ∈ l₁, p a, from λ a h, H₂ a ((mem_of_perm pp).1 h), have ∀ {s₂ e H}, @eq.rec (multiset α) l₁ (λ s, (∀ a ∈ s, p a) → multiset β) (λ _, ↑(pmap f l₁ H₁)) s₂ e H = ↑(pmap f l₁ H₁), by intros s₂ e _; subst e, this.trans $ quot.sound $ perm_pmap f pp @[simp] theorem coe_pmap {p : α → Prop} (f : Π a, p a → β) (l : list α) (H : ∀ a ∈ l, p a) : pmap f l H = l.pmap f H := rfl @[simp] lemma pmap_zero {p : α → Prop} (f : Π a, p a → β) (h : ∀a∈(0:multiset α), p a) : pmap f 0 h = 0 := rfl @[simp] lemma pmap_cons {p : α → Prop} (f : Π a, p a → β) (a : α) (m : multiset α) : ∀(h : ∀b∈a::m, p b), pmap f (a :: m) h = f a (h a (mem_cons_self a m)) :: pmap f m (λa ha, h a $ mem_cons_of_mem ha) := quotient.induction_on m $ assume l h, rfl /-- "Attach" a proof that `a ∈ s` to each element `a` in `s` to produce a multiset on `{x // x ∈ s}`. -/ def attach (s : multiset α) : multiset {x // x ∈ s} := pmap subtype.mk s (λ a, id) @[simp] theorem coe_attach (l : list α) : @eq (multiset {x // x ∈ l}) (@attach α l) l.attach := rfl theorem pmap_eq_map (p : α → Prop) (f : α → β) (s : multiset α) : ∀ H, @pmap _ _ p (λ a _, f a) s H = map f s := quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map p f l H theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β} (s : multiset α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) : pmap f s H₁ = pmap g s H₂ := quot.induction_on s (λ l H₁ H₂, congr_arg coe $ pmap_congr l h) H₁ H₂ theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β) (s) : ∀ H, map g (pmap f s H) = pmap (λ a h, g (f a h)) s H := quot.induction_on s $ λ l H, congr_arg coe $ map_pmap g f l H theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β) (s) : ∀ H, pmap f s H = s.attach.map (λ x, f x.1 (H _ x.2)) := quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map_attach f l H theorem attach_map_val (s : multiset α) : s.attach.map subtype.val = s := quot.induction_on s $ λ l, congr_arg coe $ attach_map_val l @[simp] theorem mem_attach (s : multiset α) : ∀ x, x ∈ s.attach := quot.induction_on s $ λ l, mem_attach _ @[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β} {s H b} : b ∈ pmap f s H ↔ ∃ a (h : a ∈ s), f a (H a h) = b := quot.induction_on s (λ l H, mem_pmap) H @[simp] theorem card_pmap {p : α → Prop} (f : Π a, p a → β) (s H) : card (pmap f s H) = card s := quot.induction_on s (λ l H, length_pmap) H @[simp] theorem card_attach {m : multiset α} : card (attach m) = card m := card_pmap _ _ _ @[simp] lemma attach_zero : (0 : multiset α).attach = 0 := rfl lemma attach_cons (a : α) (m : multiset α) : (a :: m).attach = ⟨a, mem_cons_self a m⟩ :: (m.attach.map $ λp, ⟨p.1, mem_cons_of_mem p.2⟩) := quotient.induction_on m $ assume l, congr_arg coe $ congr_arg (list.cons _) $ by rw [list.map_pmap]; exact list.pmap_congr _ (assume a' h₁ h₂, subtype.eq rfl) section decidable_pi_exists variables {m : multiset α} protected def decidable_forall_multiset {p : α → Prop} [hp : ∀a, decidable (p a)] : decidable (∀a∈m, p a) := quotient.rec_on_subsingleton m (λl, decidable_of_iff (∀a∈l, p a) $ by simp) instance decidable_dforall_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] : decidable (∀a (h : a ∈ m), p a h) := decidable_of_decidable_of_iff (@multiset.decidable_forall_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _) (iff.intro (assume h a ha, h ⟨a, ha⟩ (mem_attach _ _)) (assume h ⟨a, ha⟩ _, h _ _)) /-- decidable equality for functions whose domain is bounded by multisets -/ instance decidable_eq_pi_multiset {β : α → Type*} [h : ∀a, decidable_eq (β a)] : decidable_eq (Πa∈m, β a) := assume f g, decidable_of_iff (∀a (h : a ∈ m), f a h = g a h) (by simp [function.funext_iff]) def decidable_exists_multiset {p : α → Prop} [decidable_pred p] : decidable (∃ x ∈ m, p x) := quotient.rec_on_subsingleton m list.decidable_exists_mem instance decidable_dexists_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] : decidable (∃a (h : a ∈ m), p a h) := decidable_of_decidable_of_iff (@multiset.decidable_exists_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _) (iff.intro (λ ⟨⟨a, ha₁⟩, _, ha₂⟩, ⟨a, ha₁, ha₂⟩) (λ ⟨a, ha₁, ha₂⟩, ⟨⟨a, ha₁⟩, mem_attach _ _, ha₂⟩)) end decidable_pi_exists /- subtraction -/ section variables [decidable_eq α] {s t u : multiset α} {a b : α} /-- `s - t` is the multiset such that `count a (s - t) = count a s - count a t` for all `a`. -/ protected def sub (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.diff l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_diff_right w₁ p₂ ▸ perm_diff_left _ p₁ instance : has_sub (multiset α) := ⟨multiset.sub⟩ @[simp] theorem coe_sub (s t : list α) : (s - t : multiset α) = (s.diff t : list α) := rfl theorem sub_eq_fold_erase (s t : multiset α) : s - t = foldl erase erase_comm s t := quotient.induction_on₂ s t $ λ l₁ l₂, show ↑(l₁.diff l₂) = foldl erase erase_comm ↑l₁ ↑l₂, by rw diff_eq_foldl l₁ l₂; exact foldl_hom _ _ _ _ (λ x y, rfl) _ @[simp] theorem sub_zero (s : multiset α) : s - 0 = s := quot.induction_on s $ λ l, rfl @[simp] theorem sub_cons (a : α) (s t : multiset α) : s - a::t = s.erase a - t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ diff_cons _ _ _ theorem add_sub_of_le (h : s ≤ t) : s + (t - s) = t := begin revert t, refine multiset.induction_on s (by simp) (λ a s IH t h, _), have := cons_erase (mem_of_le h (mem_cons_self _ _)), rw [cons_add, sub_cons, IH, this], exact (cons_le_cons_iff a).1 (this.symm ▸ h) end theorem sub_add' : s - (t + u) = s - t - u := quotient.induction_on₃ s t u $ λ l₁ l₂ l₃, congr_arg coe $ diff_append _ _ _ theorem sub_add_cancel (h : t ≤ s) : s - t + t = s := by rw [add_comm, add_sub_of_le h] @[simp] theorem add_sub_cancel_left (s : multiset α) : ∀ t, s + t - s = t := multiset.induction_on s (by simp) (λ a s IH t, by rw [cons_add, sub_cons, erase_cons_head, IH]) @[simp] theorem add_sub_cancel (s t : multiset α) : s + t - t = s := by rw [add_comm, add_sub_cancel_left] theorem sub_le_sub_right (h : s ≤ t) (u) : s - u ≤ t - u := by revert s t h; exact multiset.induction_on u (by simp {contextual := tt}) (λ a u IH s t h, by simp [IH, erase_le_erase a h]) theorem sub_le_sub_left (h : s ≤ t) : ∀ u, u - t ≤ u - s := le_induction_on h $ λ l₁ l₂ h, begin induction h with l₁ l₂ a s IH l₁ l₂ a s IH; intro u, { refl }, { rw [← cons_coe, sub_cons], exact le_trans (sub_le_sub_right (erase_le _ _) _) (IH u) }, { rw [← cons_coe, sub_cons, ← cons_coe, sub_cons], exact IH _ } end theorem sub_le_iff_le_add : s - t ≤ u ↔ s ≤ u + t := by revert s; exact multiset.induction_on t (by simp) (λ a t IH s, by simp [IH, erase_le_iff_le_cons]) theorem le_sub_add (s t : multiset α) : s ≤ s - t + t := sub_le_iff_le_add.1 (le_refl _) theorem sub_le_self (s t : multiset α) : s - t ≤ s := sub_le_iff_le_add.2 (le_add_right _ _) @[simp] theorem card_sub {s t : multiset α} (h : t ≤ s) : card (s - t) = card s - card t := (nat.sub_eq_of_eq_add $ by rw [add_comm, ← card_add, sub_add_cancel h]).symm /- union -/ /-- `s ∪ t` is the lattice join operation with respect to the multiset `≤`. The multiplicity of `a` in `s ∪ t` is the maximum of the multiplicities in `s` and `t`. -/ def union (s t : multiset α) : multiset α := s - t + t instance : has_union (multiset α) := ⟨union⟩ theorem union_def (s t : multiset α) : s ∪ t = s - t + t := rfl theorem le_union_left (s t : multiset α) : s ≤ s ∪ t := le_sub_add _ _ theorem le_union_right (s t : multiset α) : t ≤ s ∪ t := le_add_left _ _ theorem eq_union_left : t ≤ s → s ∪ t = s := sub_add_cancel theorem union_le_union_right (h : s ≤ t) (u) : s ∪ u ≤ t ∪ u := add_le_add_right (sub_le_sub_right h _) u theorem union_le (h₁ : s ≤ u) (h₂ : t ≤ u) : s ∪ t ≤ u := by rw ← eq_union_left h₂; exact union_le_union_right h₁ t @[simp] theorem mem_union : a ∈ s ∪ t ↔ a ∈ s ∨ a ∈ t := ⟨λ h, (mem_add.1 h).imp_left (mem_of_le $ sub_le_self _ _), or.rec (mem_of_le $ le_union_left _ _) (mem_of_le $ le_union_right _ _)⟩ @[simp] theorem map_union [decidable_eq β] {f : α → β} (finj : function.injective f) {s t : multiset α} : map f (s ∪ t) = map f s ∪ map f t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe (by rw [list.map_append f, list.map_diff finj]) /- inter -/ /-- `s ∩ t` is the lattice meet operation with respect to the multiset `≤`. The multiplicity of `a` in `s ∩ t` is the minimum of the multiplicities in `s` and `t`. -/ def inter (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.bag_inter l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_bag_inter_right w₁ p₂ ▸ perm_bag_inter_left _ p₁ instance : has_inter (multiset α) := ⟨inter⟩ @[simp] theorem inter_zero (s : multiset α) : s ∩ 0 = 0 := quot.induction_on s $ λ l, congr_arg coe l.bag_inter_nil @[simp] theorem zero_inter (s : multiset α) : 0 ∩ s = 0 := quot.induction_on s $ λ l, congr_arg coe l.nil_bag_inter @[simp] theorem cons_inter_of_pos {a} (s : multiset α) {t} : a ∈ t → (a :: s) ∩ t = a :: s ∩ t.erase a := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ cons_bag_inter_of_pos _ h @[simp] theorem cons_inter_of_neg {a} (s : multiset α) {t} : a ∉ t → (a :: s) ∩ t = s ∩ t := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ cons_bag_inter_of_neg _ h theorem inter_le_left (s t : multiset α) : s ∩ t ≤ s := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_of_sublist $ bag_inter_sublist_left _ _ theorem inter_le_right (s : multiset α) : ∀ t, s ∩ t ≤ t := multiset.induction_on s (λ t, (zero_inter t).symm ▸ zero_le _) $ λ a s IH t, if h : a ∈ t then by simpa [h] using cons_le_cons a (IH (t.erase a)) else by simp [h, IH] theorem le_inter (h₁ : s ≤ t) (h₂ : s ≤ u) : s ≤ t ∩ u := begin revert s u, refine multiset.induction_on t _ (λ a t IH, _); intros, { simp [h₁] }, by_cases a ∈ u, { rw [cons_inter_of_pos _ h, ← erase_le_iff_le_cons], exact IH (erase_le_iff_le_cons.2 h₁) (erase_le_erase _ h₂) }, { rw cons_inter_of_neg _ h, exact IH ((le_cons_of_not_mem $ mt (mem_of_le h₂) h).1 h₁) h₂ } end @[simp] theorem mem_inter : a ∈ s ∩ t ↔ a ∈ s ∧ a ∈ t := ⟨λ h, ⟨mem_of_le (inter_le_left _ _) h, mem_of_le (inter_le_right _ _) h⟩, λ ⟨h₁, h₂⟩, by rw [← cons_erase h₁, cons_inter_of_pos _ h₂]; apply mem_cons_self⟩ instance : lattice (multiset α) := { sup := (∪), sup_le := @union_le _ _, le_sup_left := le_union_left, le_sup_right := le_union_right, inf := (∩), le_inf := @le_inter _ _, inf_le_left := inter_le_left, inf_le_right := inter_le_right, ..@multiset.partial_order α } @[simp] theorem sup_eq_union (s t : multiset α) : s ⊔ t = s ∪ t := rfl @[simp] theorem inf_eq_inter (s t : multiset α) : s ⊓ t = s ∩ t := rfl @[simp] theorem le_inter_iff : s ≤ t ∩ u ↔ s ≤ t ∧ s ≤ u := le_inf_iff @[simp] theorem union_le_iff : s ∪ t ≤ u ↔ s ≤ u ∧ t ≤ u := sup_le_iff instance : semilattice_inf_bot (multiset α) := { bot := 0, bot_le := zero_le, ..multiset.lattice.lattice } theorem union_comm (s t : multiset α) : s ∪ t = t ∪ s := sup_comm theorem inter_comm (s t : multiset α) : s ∩ t = t ∩ s := inf_comm theorem eq_union_right (h : s ≤ t) : s ∪ t = t := by rw [union_comm, eq_union_left h] theorem union_le_union_left (h : s ≤ t) (u) : u ∪ s ≤ u ∪ t := sup_le_sup_left h _ theorem union_le_add (s t : multiset α) : s ∪ t ≤ s + t := union_le (le_add_right _ _) (le_add_left _ _) theorem union_add_distrib (s t u : multiset α) : (s ∪ t) + u = (s + u) ∪ (t + u) := by simpa [(∪), union, eq_comm] using show s + u - (t + u) = s - t, by rw [add_comm t, sub_add', add_sub_cancel] theorem add_union_distrib (s t u : multiset α) : s + (t ∪ u) = (s + t) ∪ (s + u) := by rw [add_comm, union_add_distrib, add_comm s, add_comm s] theorem cons_union_distrib (a : α) (s t : multiset α) : a :: (s ∪ t) = (a :: s) ∪ (a :: t) := by simpa using add_union_distrib (a::0) s t theorem inter_add_distrib (s t u : multiset α) : (s ∩ t) + u = (s + u) ∩ (t + u) := begin by_contra h, cases lt_iff_cons_le.1 (lt_of_le_of_ne (le_inter (add_le_add_right (inter_le_left s t) u) (add_le_add_right (inter_le_right s t) u)) h) with a hl, rw ← cons_add at hl, exact not_le_of_lt (lt_cons_self (s ∩ t) a) (le_inter (le_of_add_le_add_right (le_trans hl (inter_le_left _ _))) (le_of_add_le_add_right (le_trans hl (inter_le_right _ _)))) end theorem add_inter_distrib (s t u : multiset α) : s + (t ∩ u) = (s + t) ∩ (s + u) := by rw [add_comm, inter_add_distrib, add_comm s, add_comm s] theorem cons_inter_distrib (a : α) (s t : multiset α) : a :: (s ∩ t) = (a :: s) ∩ (a :: t) := by simp theorem union_add_inter (s t : multiset α) : s ∪ t + s ∩ t = s + t := begin apply le_antisymm, { rw union_add_distrib, refine union_le (add_le_add_left (inter_le_right _ _) _) _, rw add_comm, exact add_le_add_right (inter_le_left _ _) _ }, { rw [add_comm, add_inter_distrib], refine le_inter (add_le_add_right (le_union_right _ _) _) _, rw add_comm, exact add_le_add_right (le_union_left _ _) _ } end theorem sub_add_inter (s t : multiset α) : s - t + s ∩ t = s := begin rw [inter_comm], revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _), by_cases a ∈ s, { rw [cons_inter_of_pos _ h, sub_cons, add_cons, IH, cons_erase h] }, { rw [cons_inter_of_neg _ h, sub_cons, erase_of_not_mem h, IH] } end theorem sub_inter (s t : multiset α) : s - (s ∩ t) = s - t := add_right_cancel $ by rw [sub_add_inter s t, sub_add_cancel (inter_le_left _ _)] end /- filter -/ section variables {p : α → Prop} [decidable_pred p] /-- `filter p s` returns the elements in `s` (with the same multiplicities) which satisfy `p`, and removes the rest. -/ def filter (p : α → Prop) [h : decidable_pred p] (s : multiset α) : multiset α := quot.lift_on s (λ l, (filter p l : multiset α)) (λ l₁ l₂ h, quot.sound $ perm_filter p h) @[simp] theorem coe_filter (p : α → Prop) [h : decidable_pred p] (l : list α) : filter p (↑l) = l.filter p := rfl @[simp] theorem filter_zero (p : α → Prop) [h : decidable_pred p] : filter p 0 = 0 := rfl @[simp] theorem filter_cons_of_pos {a : α} (s) : p a → filter p (a::s) = a :: filter p s := quot.induction_on s $ λ l h, congr_arg coe $ filter_cons_of_pos l h @[simp] theorem filter_cons_of_neg {a : α} (s) : ¬ p a → filter p (a::s) = filter p s := quot.induction_on s $ λ l h, @congr_arg _ _ _ _ coe $ filter_cons_of_neg l h lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q] {s : multiset α} : (∀ x ∈ s, p x ↔ q x) → filter p s = filter q s := quot.induction_on s $ λ l h, congr_arg coe $ filter_congr h @[simp] theorem filter_add (s t : multiset α) : filter p (s + t) = filter p s + filter p t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ filter_append _ _ @[simp] theorem filter_le (s : multiset α) : filter p s ≤ s := quot.induction_on s $ λ l, subperm_of_sublist $ filter_sublist _ @[simp] theorem filter_subset (s : multiset α) : filter p s ⊆ s := subset_of_le $ filter_le _ @[simp] theorem mem_filter {a : α} {s} : a ∈ filter p s ↔ a ∈ s ∧ p a := quot.induction_on s $ λ l, mem_filter theorem of_mem_filter {a : α} {s} (h : a ∈ filter p s) : p a := (mem_filter.1 h).2 theorem mem_of_mem_filter {a : α} {s} (h : a ∈ filter p s) : a ∈ s := (mem_filter.1 h).1 theorem mem_filter_of_mem {a : α} {l} (m : a ∈ l) (h : p a) : a ∈ filter p l := mem_filter.2 ⟨m, h⟩ theorem filter_eq_self {s} : filter p s = s ↔ ∀ a ∈ s, p a := quot.induction_on s $ λ l, iff.trans ⟨λ h, eq_of_sublist_of_length_eq (filter_sublist _) (@congr_arg _ _ _ _ card h), congr_arg coe⟩ filter_eq_self theorem filter_eq_nil {s} : filter p s = 0 ↔ ∀ a ∈ s, ¬p a := quot.induction_on s $ λ l, iff.trans ⟨λ h, eq_nil_of_length_eq_zero (@congr_arg _ _ _ _ card h), congr_arg coe⟩ filter_eq_nil theorem filter_le_filter {s t} (h : s ≤ t) : filter p s ≤ filter p t := le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist $ filter_sublist_filter h theorem le_filter {s t} : s ≤ filter p t ↔ s ≤ t ∧ ∀ a ∈ s, p a := ⟨λ h, ⟨le_trans h (filter_le _), λ a m, of_mem_filter (mem_of_le h m)⟩, λ ⟨h, al⟩, filter_eq_self.2 al ▸ filter_le_filter h⟩ @[simp] theorem filter_sub [decidable_eq α] (s t : multiset α) : filter p (s - t) = filter p s - filter p t := begin revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _), rw [sub_cons, IH], by_cases p a, { rw [filter_cons_of_pos _ h, sub_cons], congr, by_cases m : a ∈ s, { rw [← cons_inj_right a, ← filter_cons_of_pos _ h, cons_erase (mem_filter_of_mem m h), cons_erase m] }, { rw [erase_of_not_mem m, erase_of_not_mem (mt mem_of_mem_filter m)] } }, { rw [filter_cons_of_neg _ h], by_cases m : a ∈ s, { rw [(by rw filter_cons_of_neg _ h : filter p (erase s a) = filter p (a :: erase s a)), cons_erase m] }, { rw [erase_of_not_mem m] } } end @[simp] theorem filter_union [decidable_eq α] (s t : multiset α) : filter p (s ∪ t) = filter p s ∪ filter p t := by simp [(∪), union] @[simp] theorem filter_inter [decidable_eq α] (s t : multiset α) : filter p (s ∩ t) = filter p s ∩ filter p t := le_antisymm (le_inter (filter_le_filter $ inter_le_left _ _) (filter_le_filter $ inter_le_right _ _)) $ le_filter.2 ⟨inf_le_inf (filter_le _) (filter_le _), λ a h, of_mem_filter (mem_of_le (inter_le_left _ _) h)⟩ @[simp] theorem filter_filter {q} [decidable_pred q] (s : multiset α) : filter p (filter q s) = filter (λ a, p a ∧ q a) s := quot.induction_on s $ λ l, congr_arg coe $ filter_filter l theorem filter_add_filter {q} [decidable_pred q] (s : multiset α) : filter p s + filter q s = filter (λ a, p a ∨ q a) s + filter (λ a, p a ∧ q a) s := multiset.induction_on s rfl $ λ a s IH, by by_cases p a; by_cases q a; simp * theorem filter_add_not (s : multiset α) : filter p s + filter (λ a, ¬ p a) s = s := by rw [filter_add_filter, filter_eq_self.2, filter_eq_nil.2]; simp [decidable.em] /- filter_map -/ /-- `filter_map f s` is a combination filter/map operation on `s`. The function `f : α → option β` is applied to each element of `s`; if `f a` is `some b` then `b` is added to the result, otherwise `a` is removed from the resulting multiset. -/ def filter_map (f : α → option β) (s : multiset α) : multiset β := quot.lift_on s (λ l, (filter_map f l : multiset β)) (λ l₁ l₂ h, quot.sound $perm_filter_map f h) @[simp] theorem coe_filter_map (f : α → option β) (l : list α) : filter_map f l = l.filter_map f := rfl @[simp] theorem filter_map_zero (f : α → option β) : filter_map f 0 = 0 := rfl @[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (s : multiset α) (h : f a = none) : filter_map f (a :: s) = filter_map f s := quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_none a l h @[simp] theorem filter_map_cons_some (f : α → option β) (a : α) (s : multiset α) {b : β} (h : f a = some b) : filter_map f (a :: s) = b :: filter_map f s := quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_some f a l h theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f := funext $ λ s, quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_map f) l theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] : filter_map (option.guard p) = filter p := funext $ λ s, quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_filter p) l theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (s : multiset α) : filter_map g (filter_map f s) = filter_map (λ x, (f x).bind g) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter_map f g l theorem map_filter_map (f : α → option β) (g : β → γ) (s : multiset α) : map g (filter_map f s) = filter_map (λ x, (f x).map g) s := quot.induction_on s $ λ l, congr_arg coe $ map_filter_map f g l theorem filter_map_map (f : α → β) (g : β → option γ) (s : multiset α) : filter_map g (map f s) = filter_map (g ∘ f) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_map f g l theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (s : multiset α) : filter p (filter_map f s) = filter_map (λ x, (f x).filter p) s := quot.induction_on s $ λ l, congr_arg coe $ filter_filter_map f p l theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (s : multiset α) : filter_map f (filter p s) = filter_map (λ x, if p x then f x else none) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter p f l @[simp] theorem filter_map_some (s : multiset α) : filter_map some s = s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_some l @[simp] theorem mem_filter_map (f : α → option β) (s : multiset α) {b : β} : b ∈ filter_map f s ↔ ∃ a, a ∈ s ∧ f a = some b := quot.induction_on s $ λ l, mem_filter_map f l theorem map_filter_map_of_inv (f : α → option β) (g : β → α) (H : ∀ x : α, (f x).map g = some x) (s : multiset α) : map g (filter_map f s) = s := quot.induction_on s $ λ l, congr_arg coe $ map_filter_map_of_inv f g H l theorem filter_map_le_filter_map (f : α → option β) {s t : multiset α} (h : s ≤ t) : filter_map f s ≤ filter_map f t := le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist $ filter_map_sublist_filter_map _ h /- powerset -/ def powerset_aux (l : list α) : list (multiset α) := 0 :: sublists_aux l (λ x y, x :: y) theorem powerset_aux_eq_map_coe {l : list α} : powerset_aux l = (sublists l).map coe := by simp [powerset_aux, sublists]; rw [← show @sublists_aux₁ α (multiset α) l (λ x, [↑x]) = sublists_aux l (λ x, list.cons ↑x), from sublists_aux₁_eq_sublists_aux _ _, sublists_aux_cons_eq_sublists_aux₁, ← bind_ret_eq_map, sublists_aux₁_bind]; refl @[simp] theorem mem_powerset_aux {l : list α} {s} : s ∈ powerset_aux l ↔ s ≤ ↑l := quotient.induction_on s $ by simp [powerset_aux_eq_map_coe, subperm, and.comm] def powerset_aux' (l : list α) : list (multiset α) := (sublists' l).map coe theorem powerset_aux_perm_powerset_aux' {l : list α} : powerset_aux l ~ powerset_aux' l := by rw powerset_aux_eq_map_coe; exact perm_map _ (sublists_perm_sublists' _) @[simp] theorem powerset_aux'_nil : powerset_aux' (@nil α) = [0] := rfl @[simp] theorem powerset_aux'_cons (a : α) (l : list α) : powerset_aux' (a::l) = powerset_aux' l ++ list.map (cons a) (powerset_aux' l) := by simp [powerset_aux']; refl theorem powerset_aux'_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : powerset_aux' l₁ ~ powerset_aux' l₂ := begin induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp}, { simp, exact perm_app IH (perm_map _ IH) }, { simp, apply perm_app_right, rw [← append_assoc, ← append_assoc, (by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)], exact perm_app_left _ perm_app_comm }, { exact IH₁.trans IH₂ } end theorem powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : powerset_aux l₁ ~ powerset_aux l₂ := powerset_aux_perm_powerset_aux'.trans $ (powerset_aux'_perm p).trans powerset_aux_perm_powerset_aux'.symm def powerset (s : multiset α) : multiset (multiset α) := quot.lift_on s (λ l, (powerset_aux l : multiset (multiset α))) (λ l₁ l₂ h, quot.sound (powerset_aux_perm h)) theorem powerset_coe (l : list α) : @powerset α l = ((sublists l).map coe : list (multiset α)) := congr_arg coe powerset_aux_eq_map_coe @[simp] theorem powerset_coe' (l : list α) : @powerset α l = ((sublists' l).map coe : list (multiset α)) := quot.sound powerset_aux_perm_powerset_aux' @[simp] theorem powerset_zero : @powerset α 0 = 0::0 := rfl @[simp] theorem powerset_cons (a : α) (s) : powerset (a::s) = powerset s + map (cons a) (powerset s) := quotient.induction_on s $ λ l, by simp; refl @[simp] theorem mem_powerset {s t : multiset α} : s ∈ powerset t ↔ s ≤ t := quotient.induction_on₂ s t $ by simp [subperm, and.comm] theorem map_single_le_powerset (s : multiset α) : s.map (λ a, a::0) ≤ powerset s := quotient.induction_on s $ λ l, begin simp [powerset_coe], show l.map (coe ∘ list.ret) <+~ (sublists l).map coe, rw ← list.map_map, exact subperm_of_sublist (map_sublist_map _ (map_ret_sublist_sublists _)) end @[simp] theorem card_powerset (s : multiset α) : card (powerset s) = 2 ^ card s := quotient.induction_on s $ by simp /- antidiagonal -/ theorem revzip_powerset_aux {l : list α} ⦃x⦄ (h : x ∈ revzip (powerset_aux l)) : x.1 + x.2 = ↑l := begin rw [revzip, powerset_aux_eq_map_coe, ← map_reverse, zip_map, ← revzip] at h, simp at h, rcases h with ⟨l₁, l₂, h, rfl, rfl⟩, exact quot.sound (revzip_sublists _ _ _ h) end theorem revzip_powerset_aux' {l : list α} ⦃x⦄ (h : x ∈ revzip (powerset_aux' l)) : x.1 + x.2 = ↑l := begin rw [revzip, powerset_aux', ← map_reverse, zip_map, ← revzip] at h, simp at h, rcases h with ⟨l₁, l₂, h, rfl, rfl⟩, exact quot.sound (revzip_sublists' _ _ _ h) end theorem revzip_powerset_aux_lemma [decidable_eq α] (l : list α) {l' : list (multiset α)} (H : ∀ ⦃x : _ × _⦄, x ∈ revzip l' → x.1 + x.2 = ↑l) : revzip l' = l'.map (λ x, (x, ↑l - x)) := begin have : forall₂ (λ (p : multiset α × multiset α) (s : multiset α), p = (s, ↑l - s)) (revzip l') ((revzip l').map prod.fst), { rw forall₂_map_right_iff, apply forall₂_same, rintro ⟨s, t⟩ h, dsimp, rw [← H h, add_sub_cancel_left] }, rw [← forall₂_eq_eq_eq, forall₂_map_right_iff], simpa end theorem revzip_powerset_aux_perm_aux' {l : list α} : revzip (powerset_aux l) ~ revzip (powerset_aux' l) := begin haveI := classical.dec_eq α, rw [revzip_powerset_aux_lemma l revzip_powerset_aux, revzip_powerset_aux_lemma l revzip_powerset_aux'], exact perm_map _ powerset_aux_perm_powerset_aux', end theorem revzip_powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : revzip (powerset_aux l₁) ~ revzip (powerset_aux l₂) := begin haveI := classical.dec_eq α, simp [λ l:list α, revzip_powerset_aux_lemma l revzip_powerset_aux, coe_eq_coe.2 p], exact perm_map _ (powerset_aux_perm p) end /-- The antidiagonal of a multiset `s` consists of all pairs `(t₁, t₂)` such that `t₁ + t₂ = s`. These pairs are counted with multiplicities. -/ def antidiagonal (s : multiset α) : multiset (multiset α × multiset α) := quot.lift_on s (λ l, (revzip (powerset_aux l) : multiset (multiset α × multiset α))) (λ l₁ l₂ h, quot.sound (revzip_powerset_aux_perm h)) theorem antidiagonal_coe (l : list α) : @antidiagonal α l = revzip (powerset_aux l) := rfl @[simp] theorem antidiagonal_coe' (l : list α) : @antidiagonal α l = revzip (powerset_aux' l) := quot.sound revzip_powerset_aux_perm_aux' /-- A pair `(t₁, t₂)` of multisets is contained in `antidiagonal s` if and only if `t₁ + t₂ = s`. -/ @[simp] theorem mem_antidiagonal {s : multiset α} {x : multiset α × multiset α} : x ∈ antidiagonal s ↔ x.1 + x.2 = s := quotient.induction_on s $ λ l, begin simp [antidiagonal_coe], refine ⟨λ h, revzip_powerset_aux h, λ h, _⟩, haveI := classical.dec_eq α, simp [revzip_powerset_aux_lemma l revzip_powerset_aux, h.symm], cases x with x₁ x₂, exact ⟨_, le_add_right _ _, by rw add_sub_cancel_left _ _⟩ end @[simp] theorem antidiagonal_map_fst (s : multiset α) : (antidiagonal s).map prod.fst = powerset s := quotient.induction_on s $ λ l, by simp [powerset_aux'] @[simp] theorem antidiagonal_map_snd (s : multiset α) : (antidiagonal s).map prod.snd = powerset s := quotient.induction_on s $ λ l, by simp [powerset_aux'] @[simp] theorem antidiagonal_zero : @antidiagonal α 0 = (0, 0)::0 := rfl @[simp] theorem antidiagonal_cons (a : α) (s) : antidiagonal (a::s) = map (prod.map id (cons a)) (antidiagonal s) + map (prod.map (cons a) id) (antidiagonal s) := quotient.induction_on s $ λ l, begin simp [revzip, reverse_append], rw [← zip_map, ← zip_map, zip_append, (_ : _++_=_)], {congr; simp}, {simp} end @[simp] theorem card_antidiagonal (s : multiset α) : card (antidiagonal s) = 2 ^ card s := by have := card_powerset s; rwa [← antidiagonal_map_fst, card_map] at this lemma prod_map_add [comm_semiring β] {s : multiset α} {f g : α → β} : prod (s.map (λa, f a + g a)) = sum ((antidiagonal s).map (λp, (p.1.map f).prod * (p.2.map g).prod)) := begin refine s.induction_on _ _, { simp }, { assume a s ih, simp [ih, add_mul, mul_comm, mul_left_comm, mul_assoc, sum_map_mul_left.symm] }, end /- powerset_len -/ def powerset_len_aux (n : ℕ) (l : list α) : list (multiset α) := sublists_len_aux n l coe [] theorem powerset_len_aux_eq_map_coe {n} {l : list α} : powerset_len_aux n l = (sublists_len n l).map coe := by rw [powerset_len_aux, sublists_len_aux_eq, append_nil] @[simp] theorem mem_powerset_len_aux {n} {l : list α} {s} : s ∈ powerset_len_aux n l ↔ s ≤ ↑l ∧ card s = n := quotient.induction_on s $ by simp [powerset_len_aux_eq_map_coe, subperm]; exact λ l₁, ⟨λ ⟨l₂, ⟨s, e⟩, p⟩, ⟨⟨_, p, s⟩, (perm_length p.symm).trans e⟩, λ ⟨⟨l₂, p, s⟩, e⟩, ⟨_, ⟨s, (perm_length p).trans e⟩, p⟩⟩ @[simp] theorem powerset_len_aux_zero (l : list α) : powerset_len_aux 0 l = [0] := by simp [powerset_len_aux_eq_map_coe] @[simp] theorem powerset_len_aux_nil (n : ℕ) : powerset_len_aux (n+1) (@nil α) = [] := rfl @[simp] theorem powerset_len_aux_cons (n : ℕ) (a : α) (l : list α) : powerset_len_aux (n+1) (a::l) = powerset_len_aux (n+1) l ++ list.map (cons a) (powerset_len_aux n l) := by simp [powerset_len_aux_eq_map_coe]; refl theorem powerset_len_aux_perm {n} {l₁ l₂ : list α} (p : l₁ ~ l₂) : powerset_len_aux n l₁ ~ powerset_len_aux n l₂ := begin induction n with n IHn generalizing l₁ l₂, {simp}, induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {refl}, { simp, exact perm_app IH (perm_map _ (IHn p)) }, { simp, apply perm_app_right, cases n, {simp, apply perm.swap}, simp, rw [← append_assoc, ← append_assoc, (by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)], exact perm_app_left _ perm_app_comm }, { exact IH₁.trans IH₂ } end def powerset_len (n : ℕ) (s : multiset α) : multiset (multiset α) := quot.lift_on s (λ l, (powerset_len_aux n l : multiset (multiset α))) (λ l₁ l₂ h, quot.sound (powerset_len_aux_perm h)) theorem powerset_len_coe' (n) (l : list α) : @powerset_len α n l = powerset_len_aux n l := rfl theorem powerset_len_coe (n) (l : list α) : @powerset_len α n l = ((sublists_len n l).map coe : list (multiset α)) := congr_arg coe powerset_len_aux_eq_map_coe @[simp] theorem powerset_len_zero_left (s : multiset α) : powerset_len 0 s = 0::0 := quotient.induction_on s $ λ l, by simp [powerset_len_coe']; refl @[simp] theorem powerset_len_zero_right (n : ℕ) : @powerset_len α (n + 1) 0 = 0 := rfl @[simp] theorem powerset_len_cons (n : ℕ) (a : α) (s) : powerset_len (n + 1) (a::s) = powerset_len (n + 1) s + map (cons a) (powerset_len n s) := quotient.induction_on s $ λ l, by simp [powerset_len_coe']; refl @[simp] theorem mem_powerset_len {n : ℕ} {s t : multiset α} : s ∈ powerset_len n t ↔ s ≤ t ∧ card s = n := quotient.induction_on t $ λ l, by simp [powerset_len_coe'] @[simp] theorem card_powerset_len (n : ℕ) (s : multiset α) : card (powerset_len n s) = nat.choose (card s) n := quotient.induction_on s $ by simp [powerset_len_coe] theorem powerset_len_le_powerset (n : ℕ) (s : multiset α) : powerset_len n s ≤ powerset s := quotient.induction_on s $ λ l, by simp [powerset_len_coe]; exact subperm_of_sublist (map_sublist_map _ (sublists_len_sublist_sublists' _ _)) theorem powerset_len_mono (n : ℕ) {s t : multiset α} (h : s ≤ t) : powerset_len n s ≤ powerset_len n t := le_induction_on h $ λ l₁ l₂ h, by simp [powerset_len_coe]; exact subperm_of_sublist (map_sublist_map _ (sublists_len_sublist_of_sublist _ h)) /- countp -/ /-- `countp p s` counts the number of elements of `s` (with multiplicity) that satisfy `p`. -/ def countp (p : α → Prop) [decidable_pred p] (s : multiset α) : ℕ := quot.lift_on s (countp p) (λ l₁ l₂, perm_countp p) @[simp] theorem coe_countp (l : list α) : countp p l = l.countp p := rfl @[simp] theorem countp_zero (p : α → Prop) [decidable_pred p] : countp p 0 = 0 := rfl @[simp] theorem countp_cons_of_pos {a : α} (s) : p a → countp p (a::s) = countp p s + 1 := quot.induction_on s countp_cons_of_pos @[simp] theorem countp_cons_of_neg {a : α} (s) : ¬ p a → countp p (a::s) = countp p s := quot.induction_on s countp_cons_of_neg theorem countp_eq_card_filter (s) : countp p s = card (filter p s) := quot.induction_on s $ λ l, countp_eq_length_filter _ @[simp] theorem countp_add (s t) : countp p (s + t) = countp p s + countp p t := by simp [countp_eq_card_filter] instance countp.is_add_monoid_hom : is_add_monoid_hom (countp p : multiset α → ℕ) := { map_add := countp_add, map_zero := countp_zero _ } theorem countp_pos {s} : 0 < countp p s ↔ ∃ a ∈ s, p a := by simp [countp_eq_card_filter, card_pos_iff_exists_mem] @[simp] theorem countp_sub [decidable_eq α] {s t : multiset α} (h : t ≤ s) : countp p (s - t) = countp p s - countp p t := by simp [countp_eq_card_filter, h, filter_le_filter] theorem countp_pos_of_mem {s a} (h : a ∈ s) (pa : p a) : 0 < countp p s := countp_pos.2 ⟨_, h, pa⟩ theorem countp_le_of_le {s t} (h : s ≤ t) : countp p s ≤ countp p t := by simpa [countp_eq_card_filter] using card_le_of_le (filter_le_filter h) @[simp] theorem countp_filter {q} [decidable_pred q] (s : multiset α) : countp p (filter q s) = countp (λ a, p a ∧ q a) s := by simp [countp_eq_card_filter] end /- count -/ section variable [decidable_eq α] /-- `count a s` is the multiplicity of `a` in `s`. -/ def count (a : α) : multiset α → ℕ := countp (eq a) @[simp] theorem coe_count (a : α) (l : list α) : count a (↑l) = l.count a := coe_countp _ @[simp] theorem count_zero (a : α) : count a 0 = 0 := rfl @[simp] theorem count_cons_self (a : α) (s : multiset α) : count a (a::s) = succ (count a s) := countp_cons_of_pos _ rfl @[simp] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (s : multiset α) : count a (b::s) = count a s := countp_cons_of_neg _ h theorem count_le_of_le (a : α) {s t} : s ≤ t → count a s ≤ count a t := countp_le_of_le theorem count_le_count_cons (a b : α) (s : multiset α) : count a s ≤ count a (b :: s) := count_le_of_le _ (le_cons_self _ _) theorem count_singleton (a : α) : count a (a::0) = 1 := by simp @[simp] theorem count_add (a : α) : ∀ s t, count a (s + t) = count a s + count a t := countp_add instance count.is_add_monoid_hom (a : α) : is_add_monoid_hom (count a : multiset α → ℕ) := countp.is_add_monoid_hom @[simp] theorem count_smul (a : α) (n s) : count a (n • s) = n * count a s := by induction n; simp [*, succ_smul', succ_mul] theorem count_pos {a : α} {s : multiset α} : 0 < count a s ↔ a ∈ s := by simp [count, countp_pos] @[simp] theorem count_eq_zero_of_not_mem {a : α} {s : multiset α} (h : a ∉ s) : count a s = 0 := by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h') theorem count_eq_zero {a : α} {s : multiset α} : count a s = 0 ↔ a ∉ s := iff_not_comm.1 $ count_pos.symm.trans pos_iff_ne_zero @[simp] theorem count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n := by simp [repeat] @[simp] theorem count_erase_self (a : α) (s : multiset α) : count a (erase s a) = pred (count a s) := begin by_cases a ∈ s, { rw [(by rw cons_erase h : count a s = count a (a::erase s a)), count_cons_self]; refl }, { rw [erase_of_not_mem h, count_eq_zero.2 h]; refl } end @[simp] theorem count_erase_of_ne {a b : α} (ab : a ≠ b) (s : multiset α) : count a (erase s b) = count a s := begin by_cases b ∈ s, { rw [← count_cons_of_ne ab, cons_erase h] }, { rw [erase_of_not_mem h] } end @[simp] theorem count_sub (a : α) (s t : multiset α) : count a (s - t) = count a s - count a t := begin revert s, refine multiset.induction_on t (by simp) (λ b t IH s, _), rw [sub_cons, IH], by_cases ab : a = b, { subst b, rw [count_erase_self, count_cons_self, sub_succ, pred_sub] }, { rw [count_erase_of_ne ab, count_cons_of_ne ab] } end @[simp] theorem count_union (a : α) (s t : multiset α) : count a (s ∪ t) = max (count a s) (count a t) := by simp [(∪), union, sub_add_eq_max, -add_comm] @[simp] theorem count_inter (a : α) (s t : multiset α) : count a (s ∩ t) = min (count a s) (count a t) := begin apply @nat.add_left_cancel (count a (s - t)), rw [← count_add, sub_add_inter, count_sub, sub_add_min], end lemma count_bind {m : multiset β} {f : β → multiset α} {a : α} : count a (bind m f) = sum (m.map $ λb, count a $ f b) := multiset.induction_on m (by simp) (by simp) theorem le_count_iff_repeat_le {a : α} {s : multiset α} {n : ℕ} : n ≤ count a s ↔ repeat a n ≤ s := quot.induction_on s $ λ l, le_count_iff_repeat_sublist.trans repeat_le_coe.symm @[simp] theorem count_filter {p} [decidable_pred p] {a} {s : multiset α} (h : p a) : count a (filter p s) = count a s := quot.induction_on s $ λ l, count_filter h theorem ext {s t : multiset α} : s = t ↔ ∀ a, count a s = count a t := quotient.induction_on₂ s t $ λ l₁ l₂, quotient.eq.trans perm_iff_count @[extensionality] theorem ext' {s t : multiset α} : (∀ a, count a s = count a t) → s = t := ext.2 @[simp] theorem coe_inter (s t : list α) : (s ∩ t : multiset α) = (s.bag_inter t : list α) := by ext; simp theorem le_iff_count {s t : multiset α} : s ≤ t ↔ ∀ a, count a s ≤ count a t := ⟨λ h a, count_le_of_le a h, λ al, by rw ← (ext.2 (λ a, by simp [max_eq_right (al a)]) : s ∪ t = t); apply le_union_left⟩ instance : distrib_lattice (multiset α) := { le_sup_inf := λ s t u, le_of_eq $ eq.symm $ ext.2 $ λ a, by simp only [max_min_distrib_left, multiset.count_inter, multiset.sup_eq_union, multiset.count_union, multiset.inf_eq_inter], ..multiset.lattice.lattice } instance : semilattice_sup_bot (multiset α) := { bot := 0, bot_le := zero_le, ..multiset.lattice.lattice } end /- relator -/ section rel /-- `rel r s t` -- lift the relation `r` between two elements to a relation between `s` and `t`, s.t. there is a one-to-one mapping betweem elements in `s` and `t` following `r`. -/ inductive rel (r : α → β → Prop) : multiset α → multiset β → Prop | zero {} : rel 0 0 | cons {a b as bs} : r a b → rel as bs → rel (a :: as) (b :: bs) run_cmd tactic.mk_iff_of_inductive_prop `multiset.rel `multiset.rel_iff variables {δ : Type*} {r : α → β → Prop} {p : γ → δ → Prop} private lemma rel_flip_aux {s t} (h : rel r s t) : rel (flip r) t s := rel.rec_on h rel.zero (assume _ _ _ _ h₀ h₁ ih, rel.cons h₀ ih) lemma rel_flip {s t} : rel (flip r) s t ↔ rel r t s := ⟨rel_flip_aux, rel_flip_aux⟩ lemma rel_eq_refl {s : multiset α} : rel (=) s s := multiset.induction_on s rel.zero (assume a s, rel.cons rfl) lemma rel_eq {s t : multiset α} : rel (=) s t ↔ s = t := begin split, { assume h, induction h; simp * }, { assume h, subst h, exact rel_eq_refl } end lemma rel.mono {p : α → β → Prop} {s t} (h : ∀a b, r a b → p a b) (hst : rel r s t) : rel p s t := begin induction hst, case rel.zero { exact rel.zero }, case rel.cons : a b s t hab hst ih { exact ih.cons (h a b hab) } end lemma rel.add {s t u v} (hst : rel r s t) (huv : rel r u v) : rel r (s + u) (t + v) := begin induction hst, case rel.zero { simpa using huv }, case rel.cons : a b s t hab hst ih { simpa using ih.cons hab } end lemma rel_flip_eq {s t : multiset α} : rel (λa b, b = a) s t ↔ s = t := show rel (flip (=)) s t ↔ s = t, by rw [rel_flip, rel_eq, eq_comm] @[simp] lemma rel_zero_left {b : multiset β} : rel r 0 b ↔ b = 0 := by rw [rel_iff]; simp @[simp] lemma rel_zero_right {a : multiset α} : rel r a 0 ↔ a = 0 := by rw [rel_iff]; simp lemma rel_cons_left {a as bs} : rel r (a :: as) bs ↔ (∃b bs', r a b ∧ rel r as bs' ∧ bs = b :: bs') := begin split, { generalize hm : a :: as = m, assume h, induction h generalizing as, case rel.zero { simp at hm, contradiction }, case rel.cons : a' b as' bs ha'b h ih { rcases cons_eq_cons.1 hm with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩, { subst eq₁, subst eq₂, exact ⟨b, bs, ha'b, h, rfl⟩ }, { rcases ih eq₂.symm with ⟨b', bs', h₁, h₂, eq⟩, exact ⟨b', b::bs', h₁, eq₁.symm ▸ rel.cons ha'b h₂, eq.symm ▸ cons_swap _ _ _⟩ } } }, { exact assume ⟨b, bs', hab, h, eq⟩, eq.symm ▸ rel.cons hab h } end lemma rel_cons_right {as b bs} : rel r as (b :: bs) ↔ (∃a as', r a b ∧ rel r as' bs ∧ as = a :: as') := begin rw [← rel_flip, rel_cons_left], apply exists_congr, assume a, apply exists_congr, assume as', rw [rel_flip, flip] end lemma rel_add_left {as₀ as₁} : ∀{bs}, rel r (as₀ + as₁) bs ↔ (∃bs₀ bs₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ bs = bs₀ + bs₁) := multiset.induction_on as₀ (by simp) begin assume a s ih bs, simp only [ih, cons_add, rel_cons_left], split, { assume h, rcases h with ⟨b, bs', hab, h, rfl⟩, rcases h with ⟨bs₀, bs₁, h₀, h₁, rfl⟩, exact ⟨b :: bs₀, bs₁, ⟨b, bs₀, hab, h₀, rfl⟩, h₁, by simp⟩ }, { assume h, rcases h with ⟨bs₀, bs₁, h, h₁, rfl⟩, rcases h with ⟨b, bs, hab, h₀, rfl⟩, exact ⟨b, bs + bs₁, hab, ⟨bs, bs₁, h₀, h₁, rfl⟩, by simp⟩ } end lemma rel_add_right {as bs₀ bs₁} : rel r as (bs₀ + bs₁) ↔ (∃as₀ as₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ as = as₀ + as₁) := by rw [← rel_flip, rel_add_left]; simp [rel_flip] lemma rel_map_left {s : multiset γ} {f : γ → α} : ∀{t}, rel r (s.map f) t ↔ rel (λa b, r (f a) b) s t := multiset.induction_on s (by simp) (by simp [rel_cons_left] {contextual := tt}) lemma rel_map_right {s : multiset α} {t : multiset γ} {f : γ → β} : rel r s (t.map f) ↔ rel (λa b, r a (f b)) s t := by rw [← rel_flip, rel_map_left, ← rel_flip]; refl lemma rel_join {s t} (h : rel (rel r) s t) : rel r s.join t.join := begin induction h, case rel.zero { simp }, case rel.cons : a b s t hab hst ih { simpa using hab.add ih } end lemma rel_map {p : γ → δ → Prop} {s t} {f : α → γ} {g : β → δ} (h : (r ⇒ p) f g) (hst : rel r s t) : rel p (s.map f) (t.map g) := by rw [rel_map_left, rel_map_right]; exact hst.mono (assume a b, h) lemma rel_bind {p : γ → δ → Prop} {s t} {f : α → multiset γ} {g : β → multiset δ} (h : (r ⇒ rel p) f g) (hst : rel r s t) : rel p (s.bind f) (t.bind g) := by apply rel_join; apply rel_map; assumption lemma card_eq_card_of_rel {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) : card s = card t := by induction h; simp [*] lemma exists_mem_of_rel_of_mem {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) : ∀ {a : α} (ha : a ∈ s), ∃ b ∈ t, r a b := begin induction h with x y s t hxy hst ih, { simp }, { assume a ha, cases mem_cons.1 ha with ha ha, { exact ⟨y, mem_cons_self _ _, ha.symm ▸ hxy⟩ }, { rcases ih ha with ⟨b, hbt, hab⟩, exact ⟨b, mem_cons.2 (or.inr hbt), hab⟩ } } end end rel section map theorem map_eq_map {f : α → β} (hf : function.injective f) {s t : multiset α} : s.map f = t.map f ↔ s = t := by rw [← rel_eq, ← rel_eq, rel_map_left, rel_map_right]; simp [hf.eq_iff] theorem injective_map {f : α → β} (hf : function.injective f) : function.injective (multiset.map f) := assume x y, (map_eq_map hf).1 end map section quot theorem map_mk_eq_map_mk_of_rel {r : α → α → Prop} {s t : multiset α} (hst : s.rel r t) : s.map (quot.mk r) = t.map (quot.mk r) := rel.rec_on hst rfl $ assume a b s t hab hst ih, by simp [ih, quot.sound hab] theorem exists_multiset_eq_map_quot_mk {r : α → α → Prop} (s : multiset (quot r)) : ∃t:multiset α, s = t.map (quot.mk r) := multiset.induction_on s ⟨0, rfl⟩ $ assume a s ⟨t, ht⟩, quot.induction_on a $ assume a, ht.symm ▸ ⟨a::t, (map_cons _ _ _).symm⟩ theorem induction_on_multiset_quot {r : α → α → Prop} {p : multiset (quot r) → Prop} (s : multiset (quot r)) : (∀s:multiset α, p (s.map (quot.mk r))) → p s := match s, exists_multiset_eq_map_quot_mk s with _, ⟨t, rfl⟩ := assume h, h _ end end quot /- disjoint -/ /-- `disjoint s t` means that `s` and `t` have no elements in common. -/ def disjoint (s t : multiset α) : Prop := ∀ ⦃a⦄, a ∈ s → a ∈ t → false @[simp] theorem coe_disjoint (l₁ l₂ : list α) : @disjoint α l₁ l₂ ↔ l₁.disjoint l₂ := iff.rfl theorem disjoint.symm {s t : multiset α} (d : disjoint s t) : disjoint t s | a i₂ i₁ := d i₁ i₂ @[simp] theorem disjoint_comm {s t : multiset α} : disjoint s t ↔ disjoint t s := ⟨disjoint.symm, disjoint.symm⟩ theorem disjoint_left {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := iff.rfl theorem disjoint_right {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s := disjoint_comm theorem disjoint_iff_ne {s t : multiset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b := by simp [disjoint_left, imp_not_comm] theorem disjoint_of_subset_left {s t u : multiset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t | x m₁ := d (h m₁) theorem disjoint_of_subset_right {s t u : multiset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t | x m m₁ := d m (h m₁) theorem disjoint_of_le_left {s t u : multiset α} (h : s ≤ u) : disjoint u t → disjoint s t := disjoint_of_subset_left (subset_of_le h) theorem disjoint_of_le_right {s t u : multiset α} (h : t ≤ u) : disjoint s u → disjoint s t := disjoint_of_subset_right (subset_of_le h) @[simp] theorem zero_disjoint (l : multiset α) : disjoint 0 l | a := (not_mem_nil a).elim @[simp] theorem singleton_disjoint {l : multiset α} {a : α} : disjoint (a::0) l ↔ a ∉ l := by simp [disjoint]; refl @[simp] theorem disjoint_singleton {l : multiset α} {a : α} : disjoint l (a::0) ↔ a ∉ l := by rw disjoint_comm; simp @[simp] theorem disjoint_add_left {s t u : multiset α} : disjoint (s + t) u ↔ disjoint s u ∧ disjoint t u := by simp [disjoint, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_add_right {s t u : multiset α} : disjoint s (t + u) ↔ disjoint s t ∧ disjoint s u := disjoint_comm.trans $ by simp [disjoint_append_left] @[simp] theorem disjoint_cons_left {a : α} {s t : multiset α} : disjoint (a::s) t ↔ a ∉ t ∧ disjoint s t := (@disjoint_add_left _ (a::0) s t).trans $ by simp @[simp] theorem disjoint_cons_right {a : α} {s t : multiset α} : disjoint s (a::t) ↔ a ∉ s ∧ disjoint s t := disjoint_comm.trans $ by simp [disjoint_cons_left] theorem inter_eq_zero_iff_disjoint [decidable_eq α] {s t : multiset α} : s ∩ t = 0 ↔ disjoint s t := by rw ← subset_zero; simp [subset_iff, disjoint] @[simp] theorem disjoint_union_left [decidable_eq α] {s t u : multiset α} : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := by simp [disjoint, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_union_right [decidable_eq α] {s t u : multiset α} : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := by simp [disjoint, or_imp_distrib, forall_and_distrib] lemma disjoint_map_map {f : α → γ} {g : β → γ} {s : multiset α} {t : multiset β} : disjoint (s.map f) (t.map g) ↔ (∀a∈s, ∀b∈t, f a ≠ g b) := begin simp [disjoint], split, from assume h a ha b hb eq, h _ ha rfl _ hb eq.symm, from assume h c a ha eq₁ b hb eq₂, h _ ha _ hb (eq₂.symm ▸ eq₁) end /-- `pairwise r m` states that there exists a list of the elements s.t. `r` holds pairwise on this list. -/ def pairwise (r : α → α → Prop) (m : multiset α) : Prop := ∃l:list α, m = l ∧ l.pairwise r lemma pairwise_coe_iff_pairwise {r : α → α → Prop} (hr : symmetric r) {l : list α} : multiset.pairwise r l ↔ l.pairwise r := iff.intro (assume ⟨l', eq, h⟩, (list.perm_pairwise hr (quotient.exact eq)).2 h) (assume h, ⟨l, rfl, h⟩) /- nodup -/ /-- `nodup s` means that `s` has no duplicates, i.e. the multiplicity of any element is at most 1. -/ def nodup (s : multiset α) : Prop := quot.lift_on s nodup (λ s t p, propext $ perm_nodup p) @[simp] theorem coe_nodup {l : list α} : @nodup α l ↔ l.nodup := iff.rfl @[simp] theorem forall_mem_ne {a : α} {l : list α} : (∀ (a' : α), a' ∈ l → ¬a = a') ↔ a ∉ l := ⟨λ h m, h _ m rfl, λ h a' m e, h (e.symm ▸ m)⟩ @[simp] theorem nodup_zero : @nodup α 0 := pairwise.nil @[simp] theorem nodup_cons {a : α} {s : multiset α} : nodup (a::s) ↔ a ∉ s ∧ nodup s := quot.induction_on s $ λ l, nodup_cons theorem nodup_cons_of_nodup {a : α} {s : multiset α} (m : a ∉ s) (n : nodup s) : nodup (a::s) := nodup_cons.2 ⟨m, n⟩ theorem nodup_singleton : ∀ a : α, nodup (a::0) := nodup_singleton theorem nodup_of_nodup_cons {a : α} {s : multiset α} (h : nodup (a::s)) : nodup s := (nodup_cons.1 h).2 theorem not_mem_of_nodup_cons {a : α} {s : multiset α} (h : nodup (a::s)) : a ∉ s := (nodup_cons.1 h).1 theorem nodup_of_le {s t : multiset α} (h : s ≤ t) : nodup t → nodup s := le_induction_on h $ λ l₁ l₂, nodup_of_sublist theorem not_nodup_pair : ∀ a : α, ¬ nodup (a::a::0) := not_nodup_pair theorem nodup_iff_le {s : multiset α} : nodup s ↔ ∀ a : α, ¬ a::a::0 ≤ s := quot.induction_on s $ λ l, nodup_iff_sublist.trans $ forall_congr $ λ a, not_congr (@repeat_le_coe _ a 2 _).symm theorem nodup_iff_count_le_one [decidable_eq α] {s : multiset α} : nodup s ↔ ∀ a, count a s ≤ 1 := quot.induction_on s $ λ l, nodup_iff_count_le_one @[simp] theorem count_eq_one_of_mem [decidable_eq α] {a : α} {s : multiset α} (d : nodup s) (h : a ∈ s) : count a s = 1 := le_antisymm (nodup_iff_count_le_one.1 d a) (count_pos.2 h) lemma pairwise_of_nodup {r : α → α → Prop} {s : multiset α} : (∀a∈s, ∀b∈s, a ≠ b → r a b) → nodup s → pairwise r s := quotient.induction_on s $ assume l h hl, ⟨l, rfl, hl.imp_of_mem $ assume a b ha hb, h a ha b hb⟩ lemma forall_of_pairwise {r : α → α → Prop} (H : symmetric r) {s : multiset α} (hs : pairwise r s) : (∀a∈s, ∀b∈s, a ≠ b → r a b) := let ⟨l, hl₁, hl₂⟩ := hs in hl₁.symm ▸ list.forall_of_pairwise H hl₂ theorem nodup_add {s t : multiset α} : nodup (s + t) ↔ nodup s ∧ nodup t ∧ disjoint s t := quotient.induction_on₂ s t $ λ l₁ l₂, nodup_append theorem disjoint_of_nodup_add {s t : multiset α} (d : nodup (s + t)) : disjoint s t := (nodup_add.1 d).2.2 theorem nodup_add_of_nodup {s t : multiset α} (d₁ : nodup s) (d₂ : nodup t) : nodup (s + t) ↔ disjoint s t := by simp [nodup_add, d₁, d₂] theorem nodup_of_nodup_map (f : α → β) {s : multiset α} : nodup (map f s) → nodup s := quot.induction_on s $ λ l, nodup_of_nodup_map f theorem nodup_map_on {f : α → β} {s : multiset α} : (∀x∈s, ∀y∈s, f x = f y → x = y) → nodup s → nodup (map f s) := quot.induction_on s $ λ l, nodup_map_on theorem nodup_map {f : α → β} {s : multiset α} (hf : function.injective f) : nodup s → nodup (map f s) := nodup_map_on (λ x _ y _ h, hf h) theorem nodup_filter (p : α → Prop) [decidable_pred p] {s} : nodup s → nodup (filter p s) := quot.induction_on s $ λ l, nodup_filter p @[simp] theorem nodup_attach {s : multiset α} : nodup (attach s) ↔ nodup s := quot.induction_on s $ λ l, nodup_attach theorem nodup_pmap {p : α → Prop} {f : Π a, p a → β} {s : multiset α} {H} (hf : ∀ a ha b hb, f a ha = f b hb → a = b) : nodup s → nodup (pmap f s H) := quot.induction_on s (λ l H, nodup_pmap hf) H instance nodup_decidable [decidable_eq α] (s : multiset α) : decidable (nodup s) := quotient.rec_on_subsingleton s $ λ l, l.nodup_decidable theorem nodup_erase_eq_filter [decidable_eq α] (a : α) {s} : nodup s → s.erase a = filter (≠ a) s := quot.induction_on s $ λ l d, congr_arg coe $ nodup_erase_eq_filter a d theorem nodup_erase_of_nodup [decidable_eq α] (a : α) {l} : nodup l → nodup (l.erase a) := nodup_of_le (erase_le _ _) theorem mem_erase_iff_of_nodup [decidable_eq α] {a b : α} {l} (d : nodup l) : a ∈ l.erase b ↔ a ≠ b ∧ a ∈ l := by rw nodup_erase_eq_filter b d; simp [and_comm] theorem mem_erase_of_nodup [decidable_eq α] {a : α} {l} (h : nodup l) : a ∉ l.erase a := by rw mem_erase_iff_of_nodup h; simp theorem nodup_product {s : multiset α} {t : multiset β} : nodup s → nodup t → nodup (product s t) := quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, by simp [nodup_product d₁ d₂] theorem nodup_sigma {σ : α → Type*} {s : multiset α} {t : Π a, multiset (σ a)} : nodup s → (∀ a, nodup (t a)) → nodup (s.sigma t) := quot.induction_on s $ assume l₁, begin choose f hf using assume a, quotient.exists_rep (t a), rw show t = λ a, f a, from (eq.symm $ funext $ λ a, hf a), simpa using nodup_sigma end theorem nodup_filter_map (f : α → option β) {s : multiset α} (H : ∀ (a a' : α) (b : β), b ∈ f a → b ∈ f a' → a = a') : nodup s → nodup (filter_map f s) := quot.induction_on s $ λ l, nodup_filter_map H theorem nodup_range (n : ℕ) : nodup (range n) := nodup_range _ theorem nodup_inter_left [decidable_eq α] {s : multiset α} (t) : nodup s → nodup (s ∩ t) := nodup_of_le $ inter_le_left _ _ theorem nodup_inter_right [decidable_eq α] (s) {t : multiset α} : nodup t → nodup (s ∩ t) := nodup_of_le $ inter_le_right _ _ @[simp] theorem nodup_union [decidable_eq α] {s t : multiset α} : nodup (s ∪ t) ↔ nodup s ∧ nodup t := ⟨λ h, ⟨nodup_of_le (le_union_left _ _) h, nodup_of_le (le_union_right _ _) h⟩, λ ⟨h₁, h₂⟩, nodup_iff_count_le_one.2 $ λ a, by rw [count_union]; exact max_le (nodup_iff_count_le_one.1 h₁ a) (nodup_iff_count_le_one.1 h₂ a)⟩ @[simp] theorem nodup_powerset {s : multiset α} : nodup (powerset s) ↔ nodup s := ⟨λ h, nodup_of_nodup_map _ (nodup_of_le (map_single_le_powerset _) h), quotient.induction_on s $ λ l h, by simp; refine list.nodup_map_on _ (nodup_sublists'.2 h); exact λ x sx y sy e, (perm_ext_sublist_nodup h (mem_sublists'.1 sx) (mem_sublists'.1 sy)).1 (quotient.exact e)⟩ theorem nodup_powerset_len {n : ℕ} {s : multiset α} (h : nodup s) : nodup (powerset_len n s) := nodup_of_le (powerset_len_le_powerset _ _) (nodup_powerset.2 h) @[simp] lemma nodup_bind {s : multiset α} {t : α → multiset β} : nodup (bind s t) ↔ ((∀a∈s, nodup (t a)) ∧ (s.pairwise (λa b, disjoint (t a) (t b)))) := have h₁ : ∀a, ∃l:list β, t a = l, from assume a, quot.induction_on (t a) $ assume l, ⟨l, rfl⟩, let ⟨t', h'⟩ := classical.axiom_of_choice h₁ in have t = λa, t' a, from funext h', have hd : symmetric (λa b, list.disjoint (t' a) (t' b)), from assume a b h, h.symm, quot.induction_on s $ by simp [this, list.nodup_bind, pairwise_coe_iff_pairwise hd] theorem nodup_ext {s t : multiset α} : nodup s → nodup t → (s = t ↔ ∀ a, a ∈ s ↔ a ∈ t) := quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, quotient.eq.trans $ perm_ext d₁ d₂ theorem le_iff_subset {s t : multiset α} : nodup s → (s ≤ t ↔ s ⊆ t) := quotient.induction_on₂ s t $ λ l₁ l₂ d, ⟨subset_of_le, subperm_of_subset_nodup d⟩ theorem range_le {m n : ℕ} : range m ≤ range n ↔ m ≤ n := (le_iff_subset (nodup_range _)).trans range_subset theorem mem_sub_of_nodup [decidable_eq α] {a : α} {s t : multiset α} (d : nodup s) : a ∈ s - t ↔ a ∈ s ∧ a ∉ t := ⟨λ h, ⟨mem_of_le (sub_le_self _ _) h, λ h', by refine count_eq_zero.1 _ h; rw [count_sub a s t, nat.sub_eq_zero_iff_le]; exact le_trans (nodup_iff_count_le_one.1 d _) (count_pos.2 h')⟩, λ ⟨h₁, h₂⟩, or.resolve_right (mem_add.1 $ mem_of_le (le_sub_add _ _) h₁) h₂⟩ section variable [decidable_eq α] /- erase_dup -/ /-- `erase_dup s` removes duplicates from `s`, yielding a `nodup` multiset. -/ def erase_dup (s : multiset α) : multiset α := quot.lift_on s (λ l, (l.erase_dup : multiset α)) (λ s t p, quot.sound (perm_erase_dup_of_perm p)) @[simp] theorem coe_erase_dup (l : list α) : @erase_dup α _ l = l.erase_dup := rfl @[simp] theorem erase_dup_zero : @erase_dup α _ 0 = 0 := rfl @[simp] theorem mem_erase_dup {a : α} {s : multiset α} : a ∈ erase_dup s ↔ a ∈ s := quot.induction_on s $ λ l, mem_erase_dup @[simp] theorem erase_dup_cons_of_mem {a : α} {s : multiset α} : a ∈ s → erase_dup (a::s) = erase_dup s := quot.induction_on s $ λ l m, @congr_arg _ _ _ _ coe $ erase_dup_cons_of_mem m @[simp] theorem erase_dup_cons_of_not_mem {a : α} {s : multiset α} : a ∉ s → erase_dup (a::s) = a :: erase_dup s := quot.induction_on s $ λ l m, congr_arg coe $ erase_dup_cons_of_not_mem m theorem erase_dup_le (s : multiset α) : erase_dup s ≤ s := quot.induction_on s $ λ l, subperm_of_sublist $ erase_dup_sublist _ theorem erase_dup_subset (s : multiset α) : erase_dup s ⊆ s := subset_of_le $ erase_dup_le _ theorem subset_erase_dup (s : multiset α) : s ⊆ erase_dup s := λ a, mem_erase_dup.2 @[simp] theorem erase_dup_subset' {s t : multiset α} : erase_dup s ⊆ t ↔ s ⊆ t := ⟨subset.trans (subset_erase_dup _), subset.trans (erase_dup_subset _)⟩ @[simp] theorem subset_erase_dup' {s t : multiset α} : s ⊆ erase_dup t ↔ s ⊆ t := ⟨λ h, subset.trans h (erase_dup_subset _), λ h, subset.trans h (subset_erase_dup _)⟩ @[simp] theorem nodup_erase_dup (s : multiset α) : nodup (erase_dup s) := quot.induction_on s nodup_erase_dup theorem erase_dup_eq_self {s : multiset α} : erase_dup s = s ↔ nodup s := ⟨λ e, e ▸ nodup_erase_dup s, quot.induction_on s $ λ l h, congr_arg coe $ erase_dup_eq_self.2 h⟩ theorem erase_dup_eq_zero {s : multiset α} : erase_dup s = 0 ↔ s = 0 := ⟨λ h, eq_zero_of_subset_zero $ h ▸ subset_erase_dup _, λ h, h.symm ▸ erase_dup_zero⟩ @[simp] theorem erase_dup_singleton {a : α} : erase_dup (a :: 0) = a :: 0 := erase_dup_eq_self.2 $ nodup_singleton _ theorem le_erase_dup {s t : multiset α} : s ≤ erase_dup t ↔ s ≤ t ∧ nodup s := ⟨λ h, ⟨le_trans h (erase_dup_le _), nodup_of_le h (nodup_erase_dup _)⟩, λ ⟨l, d⟩, (le_iff_subset d).2 $ subset.trans (subset_of_le l) (subset_erase_dup _)⟩ theorem erase_dup_ext {s t : multiset α} : erase_dup s = erase_dup t ↔ ∀ a, a ∈ s ↔ a ∈ t := by simp [nodup_ext] theorem erase_dup_map_erase_dup_eq [decidable_eq β] (f : α → β) (s : multiset α) : erase_dup (map f (erase_dup s)) = erase_dup (map f s) := by simp [erase_dup_ext] /- finset insert -/ /-- `ndinsert a s` is the lift of the list `insert` operation. This operation does not respect multiplicities, unlike `cons`, but it is suitable as an insert operation on `finset`. -/ def ndinsert (a : α) (s : multiset α) : multiset α := quot.lift_on s (λ l, (l.insert a : multiset α)) (λ s t p, quot.sound (perm_insert a p)) @[simp] theorem coe_ndinsert (a : α) (l : list α) : ndinsert a l = (insert a l : list α) := rfl @[simp] theorem ndinsert_zero (a : α) : ndinsert a 0 = a::0 := rfl @[simp] theorem ndinsert_of_mem {a : α} {s : multiset α} : a ∈ s → ndinsert a s = s := quot.induction_on s $ λ l h, congr_arg coe $ insert_of_mem h @[simp] theorem ndinsert_of_not_mem {a : α} {s : multiset α} : a ∉ s → ndinsert a s = a :: s := quot.induction_on s $ λ l h, congr_arg coe $ insert_of_not_mem h @[simp] theorem mem_ndinsert {a b : α} {s : multiset α} : a ∈ ndinsert b s ↔ a = b ∨ a ∈ s := quot.induction_on s $ λ l, mem_insert_iff @[simp] theorem le_ndinsert_self (a : α) (s : multiset α) : s ≤ ndinsert a s := quot.induction_on s $ λ l, subperm_of_sublist $ sublist_of_suffix $ suffix_insert _ _ @[simp] theorem mem_ndinsert_self (a : α) (s : multiset α) : a ∈ ndinsert a s := mem_ndinsert.2 (or.inl rfl) @[simp] theorem mem_ndinsert_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ ndinsert b s := mem_ndinsert.2 (or.inr h) @[simp] theorem length_ndinsert_of_mem {a : α} [decidable_eq α] {s : multiset α} (h : a ∈ s) : card (ndinsert a s) = card s := by simp [h] @[simp] theorem length_ndinsert_of_not_mem {a : α} [decidable_eq α] {s : multiset α} (h : a ∉ s) : card (ndinsert a s) = card s + 1 := by simp [h] theorem erase_dup_cons {a : α} {s : multiset α} : erase_dup (a::s) = ndinsert a (erase_dup s) := by by_cases a ∈ s; simp [h] theorem nodup_ndinsert (a : α) {s : multiset α} : nodup s → nodup (ndinsert a s) := quot.induction_on s $ λ l, nodup_insert theorem ndinsert_le {a : α} {s t : multiset α} : ndinsert a s ≤ t ↔ s ≤ t ∧ a ∈ t := ⟨λ h, ⟨le_trans (le_ndinsert_self _ _) h, mem_of_le h (mem_ndinsert_self _ _)⟩, λ ⟨l, m⟩, if h : a ∈ s then by simp [h, l] else by rw [ndinsert_of_not_mem h, ← cons_erase m, cons_le_cons_iff, ← le_cons_of_not_mem h, cons_erase m]; exact l⟩ lemma attach_ndinsert (a : α) (s : multiset α) : (s.ndinsert a).attach = ndinsert ⟨a, mem_ndinsert_self a s⟩ (s.attach.map $ λp, ⟨p.1, mem_ndinsert_of_mem p.2⟩) := have eq : ∀h : ∀(p : {x // x ∈ s}), p.1 ∈ s, (λ (p : {x // x ∈ s}), ⟨p.val, h p⟩ : {x // x ∈ s} → {x // x ∈ s}) = id, from assume h, funext $ assume p, subtype.eq rfl, have ∀t (eq : s.ndinsert a = t), t.attach = ndinsert ⟨a, eq ▸ mem_ndinsert_self a s⟩ (s.attach.map $ λp, ⟨p.1, eq ▸ mem_ndinsert_of_mem p.2⟩), begin intros t ht, by_cases a ∈ s, { rw [ndinsert_of_mem h] at ht, subst ht, rw [eq, map_id, ndinsert_of_mem (mem_attach _ _)] }, { rw [ndinsert_of_not_mem h] at ht, subst ht, simp [attach_cons, h] } end, this _ rfl @[simp] theorem disjoint_ndinsert_left {a : α} {s t : multiset α} : disjoint (ndinsert a s) t ↔ a ∉ t ∧ disjoint s t := iff.trans (by simp [disjoint]) disjoint_cons_left @[simp] theorem disjoint_ndinsert_right {a : α} {s t : multiset α} : disjoint s (ndinsert a t) ↔ a ∉ s ∧ disjoint s t := disjoint_comm.trans $ by simp /- finset union -/ /-- `ndunion s t` is the lift of the list `union` operation. This operation does not respect multiplicities, unlike `s ∪ t`, but it is suitable as a union operation on `finset`. (`s ∪ t` would also work as a union operation on finset, but this is more efficient.) -/ def ndunion (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.union l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_union p₁ p₂ @[simp] theorem coe_ndunion (l₁ l₂ : list α) : @ndunion α _ l₁ l₂ = (l₁ ∪ l₂ : list α) := rfl @[simp] theorem zero_ndunion (s : multiset α) : ndunion 0 s = s := quot.induction_on s $ λ l, rfl @[simp] theorem cons_ndunion (s t : multiset α) (a : α) : ndunion (a :: s) t = ndinsert a (ndunion s t) := quotient.induction_on₂ s t $ λ l₁ l₂, rfl @[simp] theorem mem_ndunion {s t : multiset α} {a : α} : a ∈ ndunion s t ↔ a ∈ s ∨ a ∈ t := quotient.induction_on₂ s t $ λ l₁ l₂, list.mem_union theorem le_ndunion_right (s t : multiset α) : t ≤ ndunion s t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_of_sublist $ sublist_of_suffix $ suffix_union_right _ _ theorem ndunion_le_add (s t : multiset α) : ndunion s t ≤ s + t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_of_sublist $ union_sublist_append _ _ theorem ndunion_le {s t u : multiset α} : ndunion s t ≤ u ↔ s ⊆ u ∧ t ≤ u := multiset.induction_on s (by simp) (by simp [ndinsert_le, and_comm, and.left_comm] {contextual := tt}) theorem subset_ndunion_left (s t : multiset α) : s ⊆ ndunion s t := λ a h, mem_ndunion.2 $ or.inl h theorem le_ndunion_left {s} (t : multiset α) (d : nodup s) : s ≤ ndunion s t := (le_iff_subset d).2 $ subset_ndunion_left _ _ theorem ndunion_le_union (s t : multiset α) : ndunion s t ≤ s ∪ t := ndunion_le.2 ⟨subset_of_le (le_union_left _ _), le_union_right _ _⟩ theorem nodup_ndunion (s : multiset α) {t : multiset α} : nodup t → nodup (ndunion s t) := quotient.induction_on₂ s t $ λ l₁ l₂, list.nodup_union _ @[simp] theorem ndunion_eq_union {s t : multiset α} (d : nodup s) : ndunion s t = s ∪ t := le_antisymm (ndunion_le_union _ _) $ union_le (le_ndunion_left _ d) (le_ndunion_right _ _) theorem erase_dup_add (s t : multiset α) : erase_dup (s + t) = ndunion s (erase_dup t) := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ erase_dup_append _ _ /- finset inter -/ /-- `ndinter s t` is the lift of the list `∩` operation. This operation does not respect multiplicities, unlike `s ∩ t`, but it is suitable as an intersection operation on `finset`. (`s ∩ t` would also work as a union operation on finset, but this is more efficient.) -/ def ndinter (s t : multiset α) : multiset α := filter (∈ t) s @[simp] theorem coe_ndinter (l₁ l₂ : list α) : @ndinter α _ l₁ l₂ = (l₁ ∩ l₂ : list α) := rfl @[simp] theorem zero_ndinter (s : multiset α) : ndinter 0 s = 0 := rfl @[simp] theorem cons_ndinter_of_mem {a : α} (s : multiset α) {t : multiset α} (h : a ∈ t) : ndinter (a::s) t = a :: (ndinter s t) := by simp [ndinter, h] @[simp] theorem ndinter_cons_of_not_mem {a : α} (s : multiset α) {t : multiset α} (h : a ∉ t) : ndinter (a::s) t = ndinter s t := by simp [ndinter, h] @[simp] theorem mem_ndinter {s t : multiset α} {a : α} : a ∈ ndinter s t ↔ a ∈ s ∧ a ∈ t := mem_filter theorem nodup_ndinter {s : multiset α} (t : multiset α) : nodup s → nodup (ndinter s t) := nodup_filter _ theorem le_ndinter {s t u : multiset α} : s ≤ ndinter t u ↔ s ≤ t ∧ s ⊆ u := by simp [ndinter, le_filter, subset_iff] theorem ndinter_le_left (s t : multiset α) : ndinter s t ≤ s := (le_ndinter.1 (le_refl _)).1 theorem ndinter_subset_right (s t : multiset α) : ndinter s t ⊆ t := (le_ndinter.1 (le_refl _)).2 theorem ndinter_le_right {s} (t : multiset α) (d : nodup s) : ndinter s t ≤ t := (le_iff_subset $ nodup_ndinter _ d).2 (ndinter_subset_right _ _) theorem inter_le_ndinter (s t : multiset α) : s ∩ t ≤ ndinter s t := le_ndinter.2 ⟨inter_le_left _ _, subset_of_le $ inter_le_right _ _⟩ @[simp] theorem ndinter_eq_inter {s t : multiset α} (d : nodup s) : ndinter s t = s ∩ t := le_antisymm (le_inter (ndinter_le_left _ _) (ndinter_le_right _ d)) (inter_le_ndinter _ _) theorem ndinter_eq_zero_iff_disjoint {s t : multiset α} : ndinter s t = 0 ↔ disjoint s t := by rw ← subset_zero; simp [subset_iff, disjoint] end /- fold -/ section fold variables (op : α → α → α) [hc : is_commutative α op] [ha : is_associative α op] local notation a * b := op a b include hc ha /-- `fold op b s` folds a commutative associative operation `op` over the multiset `s`. -/ def fold : α → multiset α → α := foldr op (left_comm _ hc.comm ha.assoc) theorem fold_eq_foldr (b : α) (s : multiset α) : fold op b s = foldr op (left_comm _ hc.comm ha.assoc) b s := rfl @[simp] theorem coe_fold_r (b : α) (l : list α) : fold op b l = l.foldr op b := rfl theorem coe_fold_l (b : α) (l : list α) : fold op b l = l.foldl op b := (coe_foldr_swap op _ b l).trans $ by simp [hc.comm] theorem fold_eq_foldl (b : α) (s : multiset α) : fold op b s = foldl op (right_comm _ hc.comm ha.assoc) b s := quot.induction_on s $ λ l, coe_fold_l _ _ _ @[simp] theorem fold_zero (b : α) : (0 : multiset α).fold op b = b := rfl @[simp] theorem fold_cons_left : ∀ (b a : α) (s : multiset α), (a :: s).fold op b = a * s.fold op b := foldr_cons _ _ theorem fold_cons_right (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op b * a := by simp [hc.comm] theorem fold_cons'_right (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op (b * a) := by rw [fold_eq_foldl, foldl_cons, ← fold_eq_foldl] theorem fold_cons'_left (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op (a * b) := by rw [fold_cons'_right, hc.comm] theorem fold_add (b₁ b₂ : α) (s₁ s₂ : multiset α) : (s₁ + s₂).fold op (b₁ * b₂) = s₁.fold op b₁ * s₂.fold op b₂ := multiset.induction_on s₂ (by rw [add_zero, fold_zero, ← fold_cons'_right, ← fold_cons_right op]) (by simp {contextual := tt}; cc) theorem fold_singleton (b a : α) : (a::0 : multiset α).fold op b = a * b := by simp theorem fold_distrib {f g : β → α} (u₁ u₂ : α) (s : multiset β) : (s.map (λx, f x * g x)).fold op (u₁ * u₂) = (s.map f).fold op u₁ * (s.map g).fold op u₂ := multiset.induction_on s (by simp) (by simp {contextual := tt}; cc) theorem fold_hom {op' : β → β → β} [is_commutative β op'] [is_associative β op'] {m : α → β} (hm : ∀x y, m (op x y) = op' (m x) (m y)) (b : α) (s : multiset α) : (s.map m).fold op' (m b) = m (s.fold op b) := multiset.induction_on s (by simp) (by simp [hm] {contextual := tt}) theorem fold_union_inter [decidable_eq α] (s₁ s₂ : multiset α) (b₁ b₂ : α) : (s₁ ∪ s₂).fold op b₁ * (s₁ ∩ s₂).fold op b₂ = s₁.fold op b₁ * s₂.fold op b₂ := by rw [← fold_add op, union_add_inter, fold_add op] @[simp] theorem fold_erase_dup_idem [decidable_eq α] [hi : is_idempotent α op] (s : multiset α) (b : α) : (erase_dup s).fold op b = s.fold op b := multiset.induction_on s (by simp) $ λ a s IH, begin by_cases a ∈ s; simp [IH, h], show fold op b s = op a (fold op b s), rw [← cons_erase h, fold_cons_left, ← ha.assoc, hi.idempotent], end end fold theorem le_smul_erase_dup [decidable_eq α] (s : multiset α) : ∃ n : ℕ, s ≤ n • erase_dup s := ⟨(s.map (λ a, count a s)).fold max 0, le_iff_count.2 $ λ a, begin rw count_smul, by_cases a ∈ s, { refine le_trans _ (mul_le_mul_left _ $ count_pos.2 $ mem_erase_dup.2 h), have : count a s ≤ fold max 0 (map (λ a, count a s) (a :: erase s a)); [simp [le_max_left], simpa [cons_erase h]] }, { simp [count_eq_zero.2 h, nat.zero_le] } end⟩ section sup variables [semilattice_sup_bot α] /-- Supremum of a multiset: `sup {a, b, c} = a ⊔ b ⊔ c` -/ def sup (s : multiset α) : α := s.fold (⊔) ⊥ @[simp] lemma sup_zero : (0 : multiset α).sup = ⊥ := fold_zero _ _ @[simp] lemma sup_cons (a : α) (s : multiset α) : (a :: s).sup = a ⊔ s.sup := fold_cons_left _ _ _ _ @[simp] lemma sup_singleton {a : α} : (a::0).sup = a := by simp @[simp] lemma sup_add (s₁ s₂ : multiset α) : (s₁ + s₂).sup = s₁.sup ⊔ s₂.sup := eq.trans (by simp [sup]) (fold_add _ _ _ _ _) variables [decidable_eq α] @[simp] lemma sup_erase_dup (s : multiset α) : (erase_dup s).sup = s.sup := fold_erase_dup_idem _ _ _ @[simp] lemma sup_ndunion (s₁ s₂ : multiset α) : (ndunion s₁ s₂).sup = s₁.sup ⊔ s₂.sup := by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_add]; simp @[simp] lemma sup_union (s₁ s₂ : multiset α) : (s₁ ∪ s₂).sup = s₁.sup ⊔ s₂.sup := by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_add]; simp @[simp] lemma sup_ndinsert (a : α) (s : multiset α) : (ndinsert a s).sup = a ⊔ s.sup := by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_cons]; simp lemma sup_le {s : multiset α} {a : α} : s.sup ≤ a ↔ (∀b ∈ s, b ≤ a) := multiset.induction_on s (by simp) (by simp [or_imp_distrib, forall_and_distrib] {contextual := tt}) lemma le_sup {s : multiset α} {a : α} (h : a ∈ s) : a ≤ s.sup := sup_le.1 (le_refl _) _ h lemma sup_mono {s₁ s₂ : multiset α} (h : s₁ ⊆ s₂) : s₁.sup ≤ s₂.sup := sup_le.2 $ assume b hb, le_sup (h hb) end sup section inf variables [semilattice_inf_top α] /-- Infimum of a multiset: `inf {a, b, c} = a ⊓ b ⊓ c` -/ def inf (s : multiset α) : α := s.fold (⊓) ⊤ @[simp] lemma inf_zero : (0 : multiset α).inf = ⊤ := fold_zero _ _ @[simp] lemma inf_cons (a : α) (s : multiset α) : (a :: s).inf = a ⊓ s.inf := fold_cons_left _ _ _ _ @[simp] lemma inf_singleton {a : α} : (a::0).inf = a := by simp @[simp] lemma inf_add (s₁ s₂ : multiset α) : (s₁ + s₂).inf = s₁.inf ⊓ s₂.inf := eq.trans (by simp [inf]) (fold_add _ _ _ _ _) variables [decidable_eq α] @[simp] lemma inf_erase_dup (s : multiset α) : (erase_dup s).inf = s.inf := fold_erase_dup_idem _ _ _ @[simp] lemma inf_ndunion (s₁ s₂ : multiset α) : (ndunion s₁ s₂).inf = s₁.inf ⊓ s₂.inf := by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_add]; simp @[simp] lemma inf_union (s₁ s₂ : multiset α) : (s₁ ∪ s₂).inf = s₁.inf ⊓ s₂.inf := by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_add]; simp @[simp] lemma inf_ndinsert (a : α) (s : multiset α) : (ndinsert a s).inf = a ⊓ s.inf := by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_cons]; simp lemma le_inf {s : multiset α} {a : α} : a ≤ s.inf ↔ (∀b ∈ s, a ≤ b) := multiset.induction_on s (by simp) (by simp [or_imp_distrib, forall_and_distrib] {contextual := tt}) lemma inf_le {s : multiset α} {a : α} (h : a ∈ s) : s.inf ≤ a := le_inf.1 (le_refl _) _ h lemma inf_mono {s₁ s₂ : multiset α} (h : s₁ ⊆ s₂) : s₂.inf ≤ s₁.inf := le_inf.2 $ assume b hb, inf_le (h hb) end inf section sort variables (r : α → α → Prop) [decidable_rel r] [is_trans α r] [is_antisymm α r] [is_total α r] /-- `sort s` constructs a sorted list from the multiset `s`. (Uses merge sort algorithm.) -/ def sort (s : multiset α) : list α := quot.lift_on s (merge_sort r) $ λ a b h, eq_of_sorted_of_perm ((perm_merge_sort _ _).trans $ h.trans (perm_merge_sort _ _).symm) (sorted_merge_sort r _) (sorted_merge_sort r _) @[simp] theorem coe_sort (l : list α) : sort r l = merge_sort r l := rfl @[simp] theorem sort_sorted (s : multiset α) : sorted r (sort r s) := quot.induction_on s $ λ l, sorted_merge_sort r _ @[simp] theorem sort_eq (s : multiset α) : ↑(sort r s) = s := quot.induction_on s $ λ l, quot.sound $ perm_merge_sort _ _ @[simp] theorem mem_sort {s : multiset α} {a : α} : a ∈ sort r s ↔ a ∈ s := by rw [← mem_coe, sort_eq] @[simp] theorem length_sort {s : multiset α} : (sort r s).length = s.card := quot.induction_on s $ length_merge_sort _ end sort instance [has_repr α] : has_repr (multiset α) := ⟨λ s, "{" ++ string.intercalate ", " ((s.map repr).sort (≤)) ++ "}"⟩ section sections def sections (s : multiset (multiset α)) : multiset (multiset α) := multiset.rec_on s {0} (λs _ c, s.bind $ λa, c.map ((::) a)) (assume a₀ a₁ s pi, by simp [map_bind, bind_bind a₀ a₁, cons_swap]) @[simp] lemma sections_zero : sections (0 : multiset (multiset α)) = 0::0 := rfl @[simp] lemma sections_cons (s : multiset (multiset α)) (m : multiset α) : sections (m :: s) = m.bind (λa, (sections s).map ((::) a)) := rec_on_cons m s lemma coe_sections : ∀(l : list (list α)), sections ((l.map (λl:list α, (l : multiset α))) : multiset (multiset α)) = ((l.sections.map (λl:list α, (l : multiset α))) : multiset (multiset α)) | [] := rfl | (a :: l) := begin simp, rw [← cons_coe, sections_cons, bind_map_comm, coe_sections l], simp [list.sections, (∘), list.bind] end @[simp] lemma sections_add (s t : multiset (multiset α)) : sections (s + t) = (sections s).bind (λm, (sections t).map ((+) m)) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, bind_assoc, map_bind, bind_map, -add_comm]) lemma mem_sections {s : multiset (multiset α)} : ∀{a}, a ∈ sections s ↔ s.rel (λs a, a ∈ s) a := multiset.induction_on s (by simp) (assume a s ih a', by simp [ih, rel_cons_left, -exists_and_distrib_left, exists_and_distrib_left.symm, eq_comm]) lemma card_sections {s : multiset (multiset α)} : card (sections s) = prod (s.map card) := multiset.induction_on s (by simp) (by simp {contextual := tt}) lemma prod_map_sum [comm_semiring α] {s : multiset (multiset α)} : prod (s.map sum) = sum ((sections s).map prod) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, map_bind, sum_map_mul_left, sum_map_mul_right]) end sections section pi variables [decidable_eq α] {δ : α → Type*} open function def pi.cons (m : multiset α) (a : α) (b : δ a) (f : Πa∈m, δ a) : Πa'∈a::m, δ a' := λa' ha', if h : a' = a then eq.rec b h.symm else f a' $ (mem_cons.1 ha').resolve_left h def pi.empty (δ : α → Type*) : (Πa∈(0:multiset α), δ a) . lemma pi.cons_same {m : multiset α} {a : α} {b : δ a} {f : Πa∈m, δ a} (h : a ∈ a :: m) : pi.cons m a b f a h = b := dif_pos rfl lemma pi.cons_ne {m : multiset α} {a a' : α} {b : δ a} {f : Πa∈m, δ a} (h' : a' ∈ a :: m) (h : a' ≠ a) : pi.cons m a b f a' h' = f a' ((mem_cons.1 h').resolve_left h) := dif_neg h lemma pi.cons_swap {a a' : α} {b : δ a} {b' : δ a'} {m : multiset α} {f : Πa∈m, δ a} (h : a ≠ a') : pi.cons (a' :: m) a b (pi.cons m a' b' f) == pi.cons (a :: m) a' b' (pi.cons m a b f) := begin apply hfunext, { refl }, intros a'' _ h, subst h, apply hfunext, { rw [cons_swap] }, intros ha₁ ha₂ h, by_cases h₁ : a'' = a; by_cases h₂ : a'' = a'; simp [*, pi.cons_same, pi.cons_ne] at *, { subst h₁, rw [pi.cons_same, pi.cons_same] }, { subst h₂, rw [pi.cons_same, pi.cons_same] } end /-- `pi m t` constructs the Cartesian product over `t` indexed by `m`. -/ def pi (m : multiset α) (t : Πa, multiset (δ a)) : multiset (Πa∈m, δ a) := m.rec_on {pi.empty δ} (λa m (p : multiset (Πa∈m, δ a)), (t a).bind $ λb, p.map $ pi.cons m a b) begin intros a a' m n, by_cases eq : a = a', { subst eq }, { simp [map_bind, bind_bind (t a') (t a)], apply bind_hcongr, { rw [cons_swap a a'] }, intros b hb, apply bind_hcongr, { rw [cons_swap a a'] }, intros b' hb', apply map_hcongr, { rw [cons_swap a a'] }, intros f hf, exact pi.cons_swap eq } end @[simp] lemma pi_zero (t : Πa, multiset (δ a)) : pi 0 t = pi.empty δ :: 0 := rfl @[simp] lemma pi_cons (m : multiset α) (t : Πa, multiset (δ a)) (a : α) : pi (a :: m) t = ((t a).bind $ λb, (pi m t).map $ pi.cons m a b) := rec_on_cons a m lemma injective_pi_cons {a : α} {b : δ a} {s : multiset α} (hs : a ∉ s) : function.injective (pi.cons s a b) := assume f₁ f₂ eq, funext $ assume a', funext $ assume h', have ne : a ≠ a', from assume h, hs $ h.symm ▸ h', have a' ∈ a :: s, from mem_cons_of_mem h', calc f₁ a' h' = pi.cons s a b f₁ a' this : by rw [pi.cons_ne this ne.symm] ... = pi.cons s a b f₂ a' this : by rw [eq] ... = f₂ a' h' : by rw [pi.cons_ne this ne.symm] lemma card_pi (m : multiset α) (t : Πa, multiset (δ a)) : card (pi m t) = prod (m.map $ λa, card (t a)) := multiset.induction_on m (by simp) (by simp [mul_comm] {contextual := tt}) lemma nodup_pi {s : multiset α} {t : Πa, multiset (δ a)} : nodup s → (∀a∈s, nodup (t a)) → nodup (pi s t) := multiset.induction_on s (assume _ _, nodup_singleton _) begin assume a s ih hs ht, have has : a ∉ s, by simp at hs; exact hs.1, have hs : nodup s, by simp at hs; exact hs.2, simp, split, { assume b hb, from nodup_map (injective_pi_cons has) (ih hs $ assume a' h', ht a' $ mem_cons_of_mem h') }, { apply pairwise_of_nodup _ (ht a $ mem_cons_self _ _), from assume b₁ hb₁ b₂ hb₂ neb, disjoint_map_map.2 (assume f hf g hg eq, have pi.cons s a b₁ f a (mem_cons_self _ _) = pi.cons s a b₂ g a (mem_cons_self _ _), by rw [eq], neb $ show b₁ = b₂, by rwa [pi.cons_same, pi.cons_same] at this) } end lemma mem_pi (m : multiset α) (t : Πa, multiset (δ a)) : ∀f:Πa∈m, δ a, (f ∈ pi m t) ↔ (∀a (h : a ∈ m), f a h ∈ t a) := begin refine multiset.induction_on m (λ f, _) (λ a m ih f, _), { simpa using show f = pi.empty δ, by funext a ha; exact ha.elim }, simp, split, { rintro ⟨b, hb, f', hf', rfl⟩ a' ha', rw [ih] at hf', by_cases a' = a, { subst h, rwa [pi.cons_same] }, { rw [pi.cons_ne _ h], apply hf' } }, { intro hf, refine ⟨_, hf a (mem_cons_self a _), λa ha, f a (mem_cons_of_mem ha), (ih _).2 (λ a' h', hf _ _), _⟩, funext a' h', by_cases a' = a, { subst h, rw [pi.cons_same] }, { rw [pi.cons_ne _ h] } } end end pi end multiset namespace multiset instance : functor multiset := { map := @map } instance : is_lawful_functor multiset := by refine { .. }; intros; simp open is_lawful_traversable is_comm_applicative variables {F : Type u_1 → Type u_1} [applicative F] [is_comm_applicative F] variables {α' β' : Type u_1} (f : α' → F β') def traverse : multiset α' → F (multiset β') := quotient.lift (functor.map coe ∘ traversable.traverse f) begin introv p, unfold function.comp, induction p, case perm.nil { refl }, case perm.skip { have : multiset.cons <$> f p_x <*> (coe <$> traverse f p_l₁) = multiset.cons <$> f p_x <*> (coe <$> traverse f p_l₂), { rw [p_ih] }, simpa with functor_norm }, case perm.swap { have : (λa b (l:list β'), (↑(a :: b :: l) : multiset β')) <$> f p_y <*> f p_x = (λa b l, ↑(a :: b :: l)) <$> f p_x <*> f p_y, { rw [is_comm_applicative.commutative_map], congr, funext a b l, simpa [flip] using perm.swap b a l }, simp [(∘), this] with functor_norm }, case perm.trans { simp [*] } end instance : monad multiset := { pure := λ α x, x::0, bind := @bind, .. multiset.functor } instance : is_lawful_monad multiset := { bind_pure_comp_eq_map := λ α β f s, multiset.induction_on s rfl $ λ a s ih, by rw [bind_cons, map_cons, bind_zero, add_zero], pure_bind := λ α β x f, by simp only [cons_bind, zero_bind, add_zero], bind_assoc := @bind_assoc } open functor open traversable is_lawful_traversable @[simp] lemma lift_beta {α β : Type*} (x : list α) (f : list α → β) (h : ∀ a b : list α, a ≈ b → f a = f b) : quotient.lift f h (x : multiset α) = f x := quotient.lift_beta _ _ _ @[simp] lemma map_comp_coe {α β} (h : α → β) : functor.map h ∘ coe = (coe ∘ functor.map h : list α → multiset β) := by funext; simp [functor.map] lemma id_traverse {α : Type*} (x : multiset α) : traverse id.mk x = x := quotient.induction_on x (by { intro, rw [traverse,quotient.lift_beta,function.comp], simp, congr }) lemma comp_traverse {G H : Type* → Type*} [applicative G] [applicative H] [is_comm_applicative G] [is_comm_applicative H] {α β γ : Type*} (g : α → G β) (h : β → H γ) (x : multiset α) : traverse (comp.mk ∘ functor.map h ∘ g) x = comp.mk (functor.map (traverse h) (traverse g x)) := quotient.induction_on x (by intro; simp [traverse,comp_traverse] with functor_norm; simp [(<$>),(∘)] with functor_norm) lemma map_traverse {G : Type* → Type*} [applicative G] [is_comm_applicative G] {α β γ : Type*} (g : α → G β) (h : β → γ) (x : multiset α) : functor.map (functor.map h) (traverse g x) = traverse (functor.map h ∘ g) x := quotient.induction_on x (by intro; simp [traverse] with functor_norm; rw [comp_map,map_traverse]) lemma traverse_map {G : Type* → Type*} [applicative G] [is_comm_applicative G] {α β γ : Type*} (g : α → β) (h : β → G γ) (x : multiset α) : traverse h (map g x) = traverse (h ∘ g) x := quotient.induction_on x (by intro; simp [traverse]; rw [← traversable.traverse_map h g]; [ refl, apply_instance ]) lemma naturality {G H : Type* → Type*} [applicative G] [applicative H] [is_comm_applicative G] [is_comm_applicative H] (eta : applicative_transformation G H) {α β : Type*} (f : α → G β) (x : multiset α) : eta (traverse f x) = traverse (@eta _ ∘ f) x := quotient.induction_on x (by intro; simp [traverse,is_lawful_traversable.naturality] with functor_norm) section choose variables (p : α → Prop) [decidable_pred p] (l : multiset α) def choose_x : Π hp : (∃! a, a ∈ l ∧ p a), { a // a ∈ l ∧ p a } := quotient.rec_on l (λ l' ex_unique, list.choose_x p l' (exists_of_exists_unique ex_unique)) begin intros, funext hp, suffices all_equal : ∀ x y : { t // t ∈ b ∧ p t }, x = y, { apply all_equal }, { rintros ⟨x, px⟩ ⟨y, py⟩, rcases hp with ⟨z, ⟨z_mem_l, pz⟩, z_unique⟩, congr, calc x = z : z_unique x px ... = y : (z_unique y py).symm } end def choose (hp : ∃! a, a ∈ l ∧ p a) : α := choose_x p l hp lemma choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) := (choose_x p l hp).property lemma choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1 lemma choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2 end choose /- Ico -/ /-- `Ico n m` is the multiset lifted from the list `Ico n m`, e.g. the set `{n, n+1, ..., m-1}`. -/ def Ico (n m : ℕ) : multiset ℕ := Ico n m namespace Ico theorem map_add (n m k : ℕ) : (Ico n m).map ((+) k) = Ico (n + k) (m + k) := congr_arg coe $ list.Ico.map_add _ _ _ theorem map_sub (n m k : ℕ) (h : k ≤ n) : (Ico n m).map (λ x, x - k) = Ico (n - k) (m - k) := congr_arg coe $ list.Ico.map_sub _ _ _ h theorem zero_bot (n : ℕ) : Ico 0 n = range n := congr_arg coe $ list.Ico.zero_bot _ @[simp] theorem card (n m : ℕ) : (Ico n m).card = m - n := list.Ico.length _ _ theorem nodup (n m : ℕ) : nodup (Ico n m) := Ico.nodup _ _ @[simp] theorem mem {n m l : ℕ} : l ∈ Ico n m ↔ n ≤ l ∧ l < m := list.Ico.mem theorem eq_zero_of_le {n m : ℕ} (h : m ≤ n) : Ico n m = 0 := congr_arg coe $ list.Ico.eq_nil_of_le h @[simp] theorem self_eq_zero {n : ℕ} : Ico n n = 0 := eq_zero_of_le $ le_refl n @[simp] theorem eq_zero_iff {n m : ℕ} : Ico n m = 0 ↔ m ≤ n := iff.trans (coe_eq_zero _) list.Ico.eq_empty_iff lemma add_consecutive {n m l : ℕ} (hnm : n ≤ m) (hml : m ≤ l) : Ico n m + Ico m l = Ico n l := congr_arg coe $ list.Ico.append_consecutive hnm hml @[simp] lemma inter_consecutive (n m l : ℕ) : Ico n m ∩ Ico m l = 0 := congr_arg coe $ list.Ico.bag_inter_consecutive n m l @[simp] theorem succ_singleton {n : ℕ} : Ico n (n+1) = {n} := congr_arg coe $ list.Ico.succ_singleton theorem succ_top {n m : ℕ} (h : n ≤ m) : Ico n (m + 1) = m :: Ico n m := by rw [Ico, list.Ico.succ_top h, ← coe_add, add_comm]; refl theorem eq_cons {n m : ℕ} (h : n < m) : Ico n m = n :: Ico (n + 1) m := congr_arg coe $ list.Ico.eq_cons h @[simp] theorem pred_singleton {m : ℕ} (h : m > 0) : Ico (m - 1) m = {m - 1} := congr_arg coe $ list.Ico.pred_singleton h @[simp] theorem not_mem_top {n m : ℕ} : m ∉ Ico n m := list.Ico.not_mem_top lemma filter_lt_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, x < l) = Ico n m := congr_arg coe $ list.Ico.filter_lt_of_top_le hml lemma filter_lt_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, x < l) = ∅ := congr_arg coe $ list.Ico.filter_lt_of_le_bot hln lemma filter_lt_of_ge {n m l : ℕ} (hlm : l ≤ m) : (Ico n m).filter (λ x, x < l) = Ico n l := congr_arg coe $ list.Ico.filter_lt_of_ge hlm @[simp] lemma filter_lt (n m l : ℕ) : (Ico n m).filter (λ x, x < l) = Ico n (min m l) := congr_arg coe $ list.Ico.filter_lt n m l lemma filter_ge_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, x ≥ l) = Ico n m := congr_arg coe $ list.Ico.filter_ge_of_le_bot hln lemma filter_ge_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, x ≥ l) = ∅ := congr_arg coe $ list.Ico.filter_ge_of_top_le hml lemma filter_ge_of_ge {n m l : ℕ} (hnl : n ≤ l) : (Ico n m).filter (λ x, x ≥ l) = Ico l m := congr_arg coe $ list.Ico.filter_ge_of_ge hnl @[simp] lemma filter_ge (n m l : ℕ) : (Ico n m).filter (λ x, x ≥ l) = Ico (max n l) m := congr_arg coe $ list.Ico.filter_ge n m l end Ico variable (α) def subsingleton_equiv [subsingleton α] : list α ≃ multiset α := { to_fun := coe, inv_fun := quot.lift id $ λ (a b : list α) (h : a ~ b), list.ext_le (perm_length h) $ λ n h₁ h₂, subsingleton.elim _ _, left_inv := λ l, rfl, right_inv := λ m, quot.induction_on m $ λ l, rfl } namespace nat /-- The antidiagonal of a natural number `n` is the multiset of pairs `(i,j)` such that `i+j = n`. -/ def antidiagonal (n : ℕ) : multiset (ℕ × ℕ) := list.nat.antidiagonal n /-- A pair (i,j) is contained in the antidiagonal of `n` if and only if `i+j=n`. -/ @[simp] lemma mem_antidiagonal {n : ℕ} {x : ℕ × ℕ} : x ∈ antidiagonal n ↔ x.1 + x.2 = n := by rw [antidiagonal, mem_coe, list.nat.mem_antidiagonal] /-- The cardinality of the antidiagonal of `n` is `n+1`. -/ @[simp] lemma card_antidiagonal (n : ℕ) : (antidiagonal n).card = n+1 := by rw [antidiagonal, coe_card, list.nat.length_antidiagonal] /-- The antidiagonal of `0` is the list `[(0,0)]` -/ @[simp] lemma antidiagonal_zero : antidiagonal 0 = {(0, 0)} := by { rw [antidiagonal, list.nat.antidiagonal_zero], refl } /-- The antidiagonal of `n` does not contain duplicate entries. -/ lemma nodup_antidiagonal (n : ℕ) : nodup (antidiagonal n) := coe_nodup.2 $ list.nat.nodup_antidiagonal n end nat end multiset
9d74e4eb8010a674c82bb40c997491aaabe18e7a
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/run/allGoals.lean
58074ff0cdcbc88e121488f51b06b3449bac3f5e
[ "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
1,690
lean
inductive Weekday where | sunday : Weekday | monday : Weekday | tuesday : Weekday | wednesday : Weekday | thursday : Weekday | friday : Weekday | saturday : Weekday def Weekday.next : Weekday -> Weekday := fun d => match d with | sunday => monday | monday => tuesday | tuesday => wednesday | wednesday => thursday | thursday => friday | friday => saturday | saturday => sunday def Weekday.previous : Weekday -> Weekday | sunday => saturday | monday => sunday | tuesday => monday | wednesday => tuesday | thursday => wednesday | friday => thursday | saturday => friday theorem Weekday.nextOfPrevious (d : Weekday) : next (previous d) = d := by cases d all_goals rfl theorem Weekday.nextOfPrevious' (d : Weekday) : previous (next d) = d ∧ next (previous d) = d := by apply And.intro cases d <;> rfl cases d <;> rfl theorem Weekday.nextOfPrevious'' (d : Weekday) : previous (next d) = d ∧ next (previous d) = d := by apply And.intro <;> cases d <;> rfl open Lean.Parser.Tactic in macro "rwd " x:term : tactic => `(rw [$x:term]; done) theorem ex (a b c : α) (h₁ : a = b) (h₂ : a = c) : b = a ∧ c = a := by apply And.intro <;> first | rwd h₁ | rwd h₂ theorem idEq (a : α) : id a = a := rfl theorem Weekday.test (d : Weekday) : next (previous d) = id d := by cases d trace_state all_goals rw [idEq] trace_state all_goals rfl theorem Weekday.test2 (d : Weekday) : next (previous d) = id d := by cases d <;> rw [idEq] trace_state all_goals rfl def bug {a b c : Nat} (h₁ : a = b) (h₂ : b = c) : a = c := by apply Eq.trans <;> assumption
e898f9a91f2f77052eaa6c271c025342163baf40
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/LeftLoop.lean
a3fc09f415f48714ac1f5c9a50c82f80889932c7
[]
no_license
ysharoda/Deriving-Definitions
3e149e6641fae440badd35ac110a0bd705a49ad2
dfecb27572022de3d4aa702cae8db19957523a59
refs/heads/master
1,679,127,857,700
1,615,939,007,000
1,615,939,007,000
229,785,731
4
0
null
null
null
null
UTF-8
Lean
false
false
9,556
lean
import init.data.nat.basic import init.data.fin.basic import data.vector import .Prelude open Staged open nat open fin open vector section LeftLoop structure LeftLoop (A : Type) : Type := (op : (A → (A → A))) (e : A) (runit_e : (∀ {x : A} , (op x e) = x)) (linv : (A → (A → A))) (leftCancel : (∀ {x y : A} , (op x (linv x y)) = y)) (lefCancelOp : (∀ {x y : A} , (linv x (op x y)) = y)) open LeftLoop structure Sig (AS : Type) : Type := (opS : (AS → (AS → AS))) (eS : AS) (linvS : (AS → (AS → AS))) structure Product (A : Type) : Type := (opP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (eP : (Prod A A)) (linvP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (runit_eP : (∀ {xP : (Prod A A)} , (opP xP eP) = xP)) (leftCancelP : (∀ {xP yP : (Prod A A)} , (opP xP (linvP xP yP)) = yP)) (lefCancelOpP : (∀ {xP yP : (Prod A A)} , (linvP xP (opP xP yP)) = yP)) structure Hom {A1 : Type} {A2 : Type} (Le1 : (LeftLoop A1)) (Le2 : (LeftLoop A2)) : Type := (hom : (A1 → A2)) (pres_op : (∀ {x1 x2 : A1} , (hom ((op Le1) x1 x2)) = ((op Le2) (hom x1) (hom x2)))) (pres_e : (hom (e Le1)) = (e Le2)) (pres_linv : (∀ {x1 x2 : A1} , (hom ((linv Le1) x1 x2)) = ((linv Le2) (hom x1) (hom x2)))) structure RelInterp {A1 : Type} {A2 : Type} (Le1 : (LeftLoop A1)) (Le2 : (LeftLoop A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_op : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((op Le1) x1 x2) ((op Le2) y1 y2)))))) (interp_e : (interp (e Le1) (e Le2))) (interp_linv : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((linv Le1) x1 x2) ((linv Le2) y1 y2)))))) inductive LeftLoopLTerm : Type | opL : (LeftLoopLTerm → (LeftLoopLTerm → LeftLoopLTerm)) | eL : LeftLoopLTerm | linvL : (LeftLoopLTerm → (LeftLoopLTerm → LeftLoopLTerm)) open LeftLoopLTerm inductive ClLeftLoopClTerm (A : Type) : Type | sing : (A → ClLeftLoopClTerm) | opCl : (ClLeftLoopClTerm → (ClLeftLoopClTerm → ClLeftLoopClTerm)) | eCl : ClLeftLoopClTerm | linvCl : (ClLeftLoopClTerm → (ClLeftLoopClTerm → ClLeftLoopClTerm)) open ClLeftLoopClTerm inductive OpLeftLoopOLTerm (n : ℕ) : Type | v : ((fin n) → OpLeftLoopOLTerm) | opOL : (OpLeftLoopOLTerm → (OpLeftLoopOLTerm → OpLeftLoopOLTerm)) | eOL : OpLeftLoopOLTerm | linvOL : (OpLeftLoopOLTerm → (OpLeftLoopOLTerm → OpLeftLoopOLTerm)) open OpLeftLoopOLTerm inductive OpLeftLoopOL2Term2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpLeftLoopOL2Term2) | sing2 : (A → OpLeftLoopOL2Term2) | opOL2 : (OpLeftLoopOL2Term2 → (OpLeftLoopOL2Term2 → OpLeftLoopOL2Term2)) | eOL2 : OpLeftLoopOL2Term2 | linvOL2 : (OpLeftLoopOL2Term2 → (OpLeftLoopOL2Term2 → OpLeftLoopOL2Term2)) open OpLeftLoopOL2Term2 def simplifyCl {A : Type} : ((ClLeftLoopClTerm A) → (ClLeftLoopClTerm A)) | (opCl x eCl) := x | (opCl x1 x2) := (opCl (simplifyCl x1) (simplifyCl x2)) | eCl := eCl | (linvCl x1 x2) := (linvCl (simplifyCl x1) (simplifyCl x2)) | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpLeftLoopOLTerm n) → (OpLeftLoopOLTerm n)) | (opOL x eOL) := x | (opOL x1 x2) := (opOL (simplifyOpB x1) (simplifyOpB x2)) | eOL := eOL | (linvOL x1 x2) := (linvOL (simplifyOpB x1) (simplifyOpB x2)) | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpLeftLoopOL2Term2 n A) → (OpLeftLoopOL2Term2 n A)) | (opOL2 x eOL2) := x | (opOL2 x1 x2) := (opOL2 (simplifyOp x1) (simplifyOp x2)) | eOL2 := eOL2 | (linvOL2 x1 x2) := (linvOL2 (simplifyOp x1) (simplifyOp x2)) | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((LeftLoop A) → (LeftLoopLTerm → A)) | Le (opL x1 x2) := ((op Le) (evalB Le x1) (evalB Le x2)) | Le eL := (e Le) | Le (linvL x1 x2) := ((linv Le) (evalB Le x1) (evalB Le x2)) def evalCl {A : Type} : ((LeftLoop A) → ((ClLeftLoopClTerm A) → A)) | Le (sing x1) := x1 | Le (opCl x1 x2) := ((op Le) (evalCl Le x1) (evalCl Le x2)) | Le eCl := (e Le) | Le (linvCl x1 x2) := ((linv Le) (evalCl Le x1) (evalCl Le x2)) def evalOpB {A : Type} {n : ℕ} : ((LeftLoop A) → ((vector A n) → ((OpLeftLoopOLTerm n) → A))) | Le vars (v x1) := (nth vars x1) | Le vars (opOL x1 x2) := ((op Le) (evalOpB Le vars x1) (evalOpB Le vars x2)) | Le vars eOL := (e Le) | Le vars (linvOL x1 x2) := ((linv Le) (evalOpB Le vars x1) (evalOpB Le vars x2)) def evalOp {A : Type} {n : ℕ} : ((LeftLoop A) → ((vector A n) → ((OpLeftLoopOL2Term2 n A) → A))) | Le vars (v2 x1) := (nth vars x1) | Le vars (sing2 x1) := x1 | Le vars (opOL2 x1 x2) := ((op Le) (evalOp Le vars x1) (evalOp Le vars x2)) | Le vars eOL2 := (e Le) | Le vars (linvOL2 x1 x2) := ((linv Le) (evalOp Le vars x1) (evalOp Le vars x2)) def inductionB {P : (LeftLoopLTerm → Type)} : ((∀ (x1 x2 : LeftLoopLTerm) , ((P x1) → ((P x2) → (P (opL x1 x2))))) → ((P eL) → ((∀ (x1 x2 : LeftLoopLTerm) , ((P x1) → ((P x2) → (P (linvL x1 x2))))) → (∀ (x : LeftLoopLTerm) , (P x))))) | popl pel plinvl (opL x1 x2) := (popl _ _ (inductionB popl pel plinvl x1) (inductionB popl pel plinvl x2)) | popl pel plinvl eL := pel | popl pel plinvl (linvL x1 x2) := (plinvl _ _ (inductionB popl pel plinvl x1) (inductionB popl pel plinvl x2)) def inductionCl {A : Type} {P : ((ClLeftLoopClTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClLeftLoopClTerm A)) , ((P x1) → ((P x2) → (P (opCl x1 x2))))) → ((P eCl) → ((∀ (x1 x2 : (ClLeftLoopClTerm A)) , ((P x1) → ((P x2) → (P (linvCl x1 x2))))) → (∀ (x : (ClLeftLoopClTerm A)) , (P x)))))) | psing popcl pecl plinvcl (sing x1) := (psing x1) | psing popcl pecl plinvcl (opCl x1 x2) := (popcl _ _ (inductionCl psing popcl pecl plinvcl x1) (inductionCl psing popcl pecl plinvcl x2)) | psing popcl pecl plinvcl eCl := pecl | psing popcl pecl plinvcl (linvCl x1 x2) := (plinvcl _ _ (inductionCl psing popcl pecl plinvcl x1) (inductionCl psing popcl pecl plinvcl x2)) def inductionOpB {n : ℕ} {P : ((OpLeftLoopOLTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpLeftLoopOLTerm n)) , ((P x1) → ((P x2) → (P (opOL x1 x2))))) → ((P eOL) → ((∀ (x1 x2 : (OpLeftLoopOLTerm n)) , ((P x1) → ((P x2) → (P (linvOL x1 x2))))) → (∀ (x : (OpLeftLoopOLTerm n)) , (P x)))))) | pv popol peol plinvol (v x1) := (pv x1) | pv popol peol plinvol (opOL x1 x2) := (popol _ _ (inductionOpB pv popol peol plinvol x1) (inductionOpB pv popol peol plinvol x2)) | pv popol peol plinvol eOL := peol | pv popol peol plinvol (linvOL x1 x2) := (plinvol _ _ (inductionOpB pv popol peol plinvol x1) (inductionOpB pv popol peol plinvol x2)) def inductionOp {n : ℕ} {A : Type} {P : ((OpLeftLoopOL2Term2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpLeftLoopOL2Term2 n A)) , ((P x1) → ((P x2) → (P (opOL2 x1 x2))))) → ((P eOL2) → ((∀ (x1 x2 : (OpLeftLoopOL2Term2 n A)) , ((P x1) → ((P x2) → (P (linvOL2 x1 x2))))) → (∀ (x : (OpLeftLoopOL2Term2 n A)) , (P x))))))) | pv2 psing2 popol2 peol2 plinvol2 (v2 x1) := (pv2 x1) | pv2 psing2 popol2 peol2 plinvol2 (sing2 x1) := (psing2 x1) | pv2 psing2 popol2 peol2 plinvol2 (opOL2 x1 x2) := (popol2 _ _ (inductionOp pv2 psing2 popol2 peol2 plinvol2 x1) (inductionOp pv2 psing2 popol2 peol2 plinvol2 x2)) | pv2 psing2 popol2 peol2 plinvol2 eOL2 := peol2 | pv2 psing2 popol2 peol2 plinvol2 (linvOL2 x1 x2) := (plinvol2 _ _ (inductionOp pv2 psing2 popol2 peol2 plinvol2 x1) (inductionOp pv2 psing2 popol2 peol2 plinvol2 x2)) def stageB : (LeftLoopLTerm → (Staged LeftLoopLTerm)) | (opL x1 x2) := (stage2 opL (codeLift2 opL) (stageB x1) (stageB x2)) | eL := (Now eL) | (linvL x1 x2) := (stage2 linvL (codeLift2 linvL) (stageB x1) (stageB x2)) def stageCl {A : Type} : ((ClLeftLoopClTerm A) → (Staged (ClLeftLoopClTerm A))) | (sing x1) := (Now (sing x1)) | (opCl x1 x2) := (stage2 opCl (codeLift2 opCl) (stageCl x1) (stageCl x2)) | eCl := (Now eCl) | (linvCl x1 x2) := (stage2 linvCl (codeLift2 linvCl) (stageCl x1) (stageCl x2)) def stageOpB {n : ℕ} : ((OpLeftLoopOLTerm n) → (Staged (OpLeftLoopOLTerm n))) | (v x1) := (const (code (v x1))) | (opOL x1 x2) := (stage2 opOL (codeLift2 opOL) (stageOpB x1) (stageOpB x2)) | eOL := (Now eOL) | (linvOL x1 x2) := (stage2 linvOL (codeLift2 linvOL) (stageOpB x1) (stageOpB x2)) def stageOp {n : ℕ} {A : Type} : ((OpLeftLoopOL2Term2 n A) → (Staged (OpLeftLoopOL2Term2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | (opOL2 x1 x2) := (stage2 opOL2 (codeLift2 opOL2) (stageOp x1) (stageOp x2)) | eOL2 := (Now eOL2) | (linvOL2 x1 x2) := (stage2 linvOL2 (codeLift2 linvOL2) (stageOp x1) (stageOp x2)) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (opT : ((Repr A) → ((Repr A) → (Repr A)))) (eT : (Repr A)) (linvT : ((Repr A) → ((Repr A) → (Repr A)))) end LeftLoop
cdb2c4a1a68eb0a3fa4cc9efaa54bfb26be97bf8
48eee836fdb5c613d9a20741c17db44c8e12e61c
/src/util/index.lean
d2907d47eb49628fb192f1cf615155b66332af42
[ "Apache-2.0" ]
permissive
fgdorais/lean-universal
06430443a4abe51e303e602684c2977d1f5c0834
9259b0f7fb3aa83a9e0a7a3eaa44c262e42cc9b1
refs/heads/master
1,592,479,744,136
1,589,473,399,000
1,589,473,399,000
196,287,552
1
1
null
null
null
null
UTF-8
Lean
false
false
22,492
lean
-- Copyright © 2019 François G. Dorais. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. import .basic import .relation @[derive decidable_eq] inductive {u} index {α : Type u} : list α → Type u | head (x : α) (xs : list α) : index (x :: xs) | tail (x : α) (xs : list α) : index xs → index (x :: xs) namespace index variable {α : Type*} @[reducible] definition val : Π {xs : list α}, index xs → α | _ (index.head x _) := x | _ (index.tail _ _ i) := val i @[simp] theorem val_head (x : α) (xs : list α) : val (index.head x xs) = x := rfl @[simp] theorem val_tail (x : α) (xs : list α) (i : index xs) : val (index.tail x xs i) = val i := rfl definition nil_elim {C : Sort*} : Π (i : index (@list.nil α)), C . @[simp] theorem val_eq_rec : Π {xs ys : list α} (h : xs = ys) (i : index xs), val (eq.rec_on h i : index ys) = i.val | _ _ rfl _ := rfl section map variables {β : Type*} (f : α → β) definition map : Π {xs : list α}, index xs → index (xs.map f) | _ (index.head _ _) := index.head _ _ | _ (index.tail _ _ i) := index.tail _ _ (map i) @[simp] theorem map_head (x : α) (xs : list α) : map f (index.head x xs) = index.head (f x) (xs.map f) := rfl @[simp] theorem map_tail (x : α) (xs : list α) (i : index xs) : map f (index.tail x xs i) = index.tail (f x) (xs.map f) (map f i) := rfl @[simp] theorem val_map : ∀ {xs : list α} (i : index xs), (i.map f).val = f i.val | _ (index.head _ _) := rfl | _ (index.tail _ _ i) := val_map i definition unmap : Π {xs : list α}, index (xs.map f) → index xs | (_::_) (index.head _ _) := index.head _ _ | (_::_) (index.tail _ _ i) := index.tail _ _ (unmap i) @[simp] theorem map_unmap : ∀ {xs : list α} (i : index (xs.map f)), map f (unmap f i) = i | (_::_) (index.head _ _) := rfl | (_::_) (index.tail _ _ i) := congr_arg (index.tail _ _) (map_unmap i) @[simp] theorem unmap_map : ∀ {xs : list α} (i : index xs), unmap f (map f i) = i | _ (index.head _ _) := rfl | _ (index.tail _ _ i) := congr_arg (index.tail _ _) (unmap_map i) end map section append definition append_left : Π (xs ys : list α), index xs → index (xs ++ ys) | (x::xs) ys (index.head _ _) := index.head x (xs ++ ys) | (x::xs) ys (index.tail _ _ i) := index.tail x (xs ++ ys) (append_left xs ys i) @[simp] theorem append_left_val : ∀ (xs ys : list α) (i : index xs), (append_left xs ys i).val = i.val | (x::xs) ys (index.head _ _) := rfl | (x::xs) ys (index.tail _ _ i) := append_left_val xs ys i definition append_right : Π (xs ys : list α), index ys → index (xs ++ ys) | [] ys i := i | (x::xs) ys i := index.tail x (xs ++ ys) (append_right xs ys i) @[simp] theorem append_right_val : ∀ (xs ys : list α) (i : index ys), (append_right xs ys i).val = i.val | [] ys _ := rfl | (x::xs) ys i := append_right_val xs ys i end append section join definition join_map : Π (xss : list (list α)) (i : index xss), index i.val → index xss.join | (xs::xss) (index.head _ _) j := append_left xs xss.join j | (xs::xss) (index.tail _ _ i) j := append_right xs xss.join $ join_map xss i j @[simp] theorem join_map_val : ∀ (xss : list (list α)) (i : index xss) (j : index i.val), (join_map xss i j).val = j.val | (xs::xss) (index.head _ _) j := append_left_val xs xss.join j | (xs::xss) (index.tail _ _ i) j := eq.trans (append_right_val xs xss.join (join_map xss i j)) (join_map_val xss i j) end join definition iota : Π (xs : list α), list (index xs) | [] := [] | (x :: xs) := (index.head x xs) :: list.map (index.tail x xs) (iota xs) definition iota_index : Π {xs : list α}, index xs → index (iota xs) | _ (index.head _ _) := index.head _ _ | _ (index.tail _ _ i) := index.tail _ _ (map _ $ iota_index i) @[simp] theorem iota_index_val : Π {xs : list α} (i : index xs), (iota_index i).val = i | _ (index.head _ _) := rfl | _ (index.tail x xs i) := by rw [iota_index, val_tail, val_map, iota_index_val i] definition to_fin : Π {xs : list α}, index xs → fin xs.length | _ (index.head x xs) := eq.rec_on (eq.symm $ list.length_cons x xs) 0 | _ (index.tail x xs i) := eq.rec_on (eq.symm $ list.length_cons x xs) (fin.succ $ to_fin i) definition of_fin : Π {xs : list α}, fin xs.length → index xs | [] ⟨i, hi⟩ := absurd hi (nat.not_lt_zero i) | (x :: xs) ⟨0, _⟩ := index.head x xs | (x :: xs) ⟨i+1, hi⟩ := index.tail x xs (of_fin ⟨i, nat.lt_of_succ_lt_succ hi⟩) abbreviation to_nat {xs : list α} (i : index xs) : nat := (to_fin i).val theorem to_nat_lt_lenth {xs : list α} (i : index xs) : i.to_nat < xs.length := (to_fin i).is_lt definition of_nat {xs : list α} (i : nat) : option (index xs) := if hi : i < xs.length then some (of_fin ⟨i, hi⟩) else none abbreviation of_nat_lt_length {xs : list α} (i : nat) : i < xs.length → index xs := λ hi, of_fin ⟨i, hi⟩ abbreviation dtup {xs : list α} (β : index xs → Sort*) := Π i, β i namespace dtup section nil variable {β : index (@list.nil α) → Sort*} definition nil : Π i, β i . @[simp] theorem eq_nil (t : Π i, β i) : t = nil := funext $ λ i, nil i theorem eq_of_nil (t₁ t₂ : Π i, β i) : t₁ = t₂ := by rw [dtup.eq_nil t₁, dtup.eq_nil t₂] end nil section cons variables {x : α} {xs : list α} {β : index (x :: xs) → Sort*} abbreviation head : (Π i, β i) → β (index.head x xs) := λ t, t (index.head x xs) abbreviation tail : (Π i, β i) → (Π i, β (index.tail x xs i)) := λ t i, t (index.tail x xs i) definition cons : head β → (Π i, tail β i) → (Π i, β i) | h _ (index.head _ _) := h | _ t (index.tail _ _ i) := t i @[simp] theorem cons_head_tail (t : Π i, β i) : cons (head t) (tail t) = t := funext $ λ i, match i with | (index.head _ _) := rfl | (index.tail _ _ i) := rfl end variables (h : head β) (t : Π i, tail β i) @[simp] theorem cons_of_index_head : cons h t (index.head x xs) = h := rfl @[simp] theorem cons_of_index_tail (i : index xs) : cons h t (index.tail x xs i) = t i := rfl @[simp] theorem head_cons : head (cons h t) = h := rfl @[simp] theorem tail_cons : tail (cons h t) = t := rfl end cons section enum variables {xs : list α} {β : index xs → Type*} (t : Π i, β i) abbreviation enum : list (sigma β) := list.map (λ i, ⟨i, t i⟩) (iota xs) abbreviation enum_index : index xs → index (enum t) := λ i, map _ (iota_index i) @[simp] theorem enum_index_val (i : index xs) : (enum_index t i).val = ⟨i, t i⟩ := by rw [val_map, iota_index_val] end enum abbreviation to_list {xs : list α} {β : Type*} (t : index xs → β) : list β := list.map (λ (z : sigma (λ _, β)), sigma.snd z) (enum t) abbreviation to_list_index {xs : list α} {β : Type*} (t : index xs → β) : index xs → index (to_list t) := λ i, index.map (λ (z : sigma (λ _, β)), sigma.snd z) (enum_index t i) @[simp] theorem to_list_index_val {xs : list α} {β : Type*} (t : index xs → β) (i : index xs) : (to_list_index t i).val = t i := by rw [val_map, enum_index_val] section fold definition foldl : Π {xs : list α} {β : index xs → Sort*} {γ : Sort*} (f : Π {{i}}, γ → β i → γ), γ → (Π i, β i) → γ | [] _ _ _ z _ := z | (_::_) _ _ f z t := f (foldl (tail f) z (tail t)) (head t) definition foldr : Π {xs : list α} {β : index xs → Sort*} {γ : Sort*} (f : Π {{i}}, β i → γ → γ), γ → (Π i, β i) → γ | [] _ _ _ z _ := z | (_::_) _ _ f z t := f (head t) (foldr (tail f) z (tail t)) @[simp] theorem foldl_nil {β : index (@list.nil α) → Sort*} {γ : Sort*} (f : Π {{i}}, γ → β i → γ) (z : γ) : foldl f z nil = z := rfl @[simp] theorem foldr_nil {β : index (@list.nil α) → Sort*} {γ : Sort*} (f : Π {{i}}, β i → γ → γ) (z : γ) : foldr f z nil = z := rfl variables {x : α} {xs : list α} {β : index (x :: xs) → Sort*} {γ : Sort*} @[simp] theorem foldl_cons (f : Π {{i}}, γ → β i → γ) (z : γ) (h : head β) (t : Π i, tail β i) : foldl f z (cons h t) = f (foldl (tail f) z t) h := rfl @[simp] theorem foldr_cons (f : Π {{i}}, β i → γ → γ) (z : γ) (h : head β) (t : Π i, tail β i) : foldr f z (cons h t) = f h (foldr (tail f) z t) := rfl @[simp] theorem foldl_head_tail (f : Π {{i}}, γ → β i → γ) (z : γ) (t : Π i, β i) : foldl f z t = f (foldl (tail f) z (tail t)) (head t) := rfl @[simp] theorem foldr_head_tail (f : Π {{i}}, β i → γ → γ) (z : γ) (t : Π i, β i) : foldr f z t = f (head t) (foldr (tail f) z (tail t)) := rfl end fold end dtup definition decidable_exists_def : Π {xs : list α} (p : index xs → Prop) (dp : ∀ i, decidable (p i)), decidable (∃ i, p i) | [] _ _ := decidable.is_false (λ ⟨i,_⟩, nil_elim i) | (_::_) p dp := match decidable_exists_def (dtup.tail p) (dtup.tail dp) with | decidable.is_true ht := decidable.is_true (exists.elim ht $ λ i hi, ⟨_, hi⟩) | decidable.is_false ht := match dtup.head dp with | decidable.is_true hh := decidable.is_true ⟨_, hh⟩ | decidable.is_false hh := have ¬ ∃ i, p i, begin intro h, cases h with i hi, cases i, exact hh hi, exact ht ⟨_, hi⟩, end, decidable.is_false this end end instance decidable_exists {xs : list α} (p : index xs → Prop) [dp : Π i, decidable (p i)] : decidable (∃ i, p i) := decidable_exists_def p dp definition decidable_forall_def : Π {xs : list α} (p : index xs → Prop) (dp : ∀ i, decidable (p i)), decidable (∀ i, p i) | [] _ _ := decidable.is_true (λ i, nil_elim i) | (_::_) p dp := match decidable_forall_def (dtup.tail p) (dtup.tail dp) with | decidable.is_false ht := decidable.is_false (λ h, ht (dtup.tail h)) | decidable.is_true ht := match dtup.head dp with | decidable.is_false hh := decidable.is_false (λ h, hh (dtup.head h)) | decidable.is_true hh := decidable.is_true (dtup.cons hh ht) end end instance decidable_forall {xs : list α} (p : index xs → Prop) [dp : Π i, decidable (p i)] : decidable (∀ i, p i) := decidable_forall_def p dp theorem choice : ∀ {xs : list α} {β : index xs → Sort*}, (∀ i, nonempty (β i)) → nonempty (Π i, β i) | [] _ _ := nonempty.intro dtup.nil | (_::_) C H := have Hh : nonempty (dtup.head C), from dtup.head H, have Ht : nonempty (Π i, dtup.tail C i), from choice (dtup.tail H), nonempty.elim Hh $ λ h, nonempty.elim Ht $ λ t, nonempty.intro (dtup.cons h t) section relation open relation theorem ec_of_ec_tail {x : α} {xs : list α} {β : index (x :: xs) → Sort*} {r : Π i, β i → β i → Prop} (hhr : reflexive (dtup.head r)) {h : dtup.head β} {t₁ t₂ : Π i, dtup.tail β i} : ec (pi (dtup.tail r)) t₁ t₂ → ec (pi r) (dtup.cons h t₁) (dtup.cons h t₂) := λ e, ec.rec_on e (λ _ _ hxy, ec.base $ dtup.cons (hhr h) hxy) (λ _, ec.refl _) (λ _ _ _ _ _ hxy hxz, ec.eucl hxy hxz) theorem ec_of_ec_head {x : α} {xs : list α} {β : index (x :: xs) → Sort*} {r : Π i, β i → β i → Prop} (htr : reflexive (pi (dtup.tail r))) {h₁ h₂ : dtup.head β} {t : Π i, dtup.tail β i} : ec (dtup.head r) h₁ h₂ → ec (pi r) (dtup.cons h₁ t) (dtup.cons h₂ t) := λ e, ec.rec_on e (λ _ _ hxy, ec.base $ dtup.cons hxy (htr _)) (λ _, ec.refl _) (λ _ _ _ _ _ hxy hxz, ec.eucl hxy hxz) theorem ec_of_ec_head_tail {x : α} {xs : list α} {β : index (x :: xs) → Sort*} {r : Π i, β i → β i → Prop} (hr : ∀ i, reflexive (r i)) {h₁ h₂ : dtup.head β} {t₁ t₂ : Π i, dtup.tail β i} : ec (dtup.head r) h₁ h₂ → ec (pi (dtup.tail r)) t₁ t₂ → ec (pi r) (dtup.cons h₁ t₁) (dtup.cons h₂ t₂) := λ eh et, have hhr : reflexive (dtup.head r), from dtup.head hr, have htr : reflexive (pi (dtup.tail r)), from pi_reflexive (dtup.tail hr), have e₁ : ec (pi r) (dtup.cons h₁ t₁) (dtup.cons h₂ t₁), from ec_of_ec_head htr eh, have e₂ : ec (pi r) (dtup.cons h₂ t₁) (dtup.cons h₂ t₂), from ec_of_ec_tail hhr et, ec.trans e₁ e₂ theorem ec_pi_of_pi_ec : ∀ {xs : list α} {β : index xs → Sort*} {r : Π i, β i → β i → Prop} (hr : ∀ i, reflexive (r i)) {t₁ t₂ : Π i, β i}, pi (λ i, ec (r i)) t₁ t₂ → ec (pi r) t₁ t₂ | [] _ _ _ t₁ t₂ _ := by { rw [dtup.eq_nil t₁, dtup.eq_nil t₂], apply ec.refl _ } | (_::_) _ r hr t₁ t₂ h := have eh : ec (dtup.head r) (dtup.head t₁) (dtup.head t₂), from dtup.head h, have et : ec (pi (dtup.tail r)) (dtup.tail t₁) (dtup.tail t₂), from ec_pi_of_pi_ec (dtup.tail hr) (dtup.tail h), by {rw [← dtup.cons_head_tail t₁, ← dtup.cons_head_tail t₂], exact ec_of_ec_head_tail hr eh et } variables {xs : list α} {β : index xs → Sort*} {r : Π i, β i → β i → Prop} (hr : ∀ i, reflexive (r i)) theorem pi_ec_iff_ec_pi (t₁ t₂ : Π i, β i) : pi (λ i, ec (r i)) t₁ t₂ ↔ ec (pi r) t₁ t₂ := ⟨ec_pi_of_pi_ec hr, pi_ec_of_ec_pi⟩ theorem pi_ec_eq_ec_pi : pi (λ i, ec (r i)) = ec (pi r) := funext $ λ t₁, funext $ λ t₂, propext $ pi_ec_iff_ec_pi hr t₁ t₂ end relation section setoid instance setoid {xs : list α} (β : index xs → Sort*) [Π i, setoid (β i)] : setoid (Π i, β i) := { r := λ x y, ∀ i, x i ≈ y i , iseqv := mk_equivalence _ (λ x i, setoid.refl (x i)) (λ _ _ h i, setoid.symm (h i)) (λ _ _ _ hxy hyz i, setoid.trans (hxy i) (hyz i)) } theorem setoid.r_iff {xs : list α} {C : index xs → Sort*} [Π i, setoid (C i)] (t₁ t₂ : Π i, C i) : t₁ ≈ t₂ ↔ (∀ i, t₁ i ≈ t₂ i) := iff.rfl theorem setoid.r_cons_iff {x : α} {xs : list α} {C : index (x :: xs) → Sort*} [Π i, setoid (C i)] (t₁ t₂ : Π i, C i) : t₁ ≈ t₂ ↔ dtup.head t₁ ≈ dtup.head t₂ ∧ dtup.tail t₁ ≈ dtup.tail t₂ := ⟨ λ h, have h : ∀ i, t₁ i ≈ t₂ i, from (setoid.r_iff t₁ t₂).mp h, ⟨dtup.head h, dtup.tail h⟩ , λ ⟨hh, ht⟩, have h : ∀ i, t₁ i ≈ t₂ i, from dtup.cons hh ht, (setoid.r_iff t₁ t₂).mpr h ⟩ theorem setoid.r_cons {x : α} {xs : list α} {C : index (x :: xs) → Sort*} [Π i, setoid (C i)] (h₁ h₂ : dtup.head C) (t₁ t₂ : Π i, dtup.tail C i) : h₁ ≈ h₂ → t₁ ≈ t₂ → dtup.cons h₁ t₁ ≈ dtup.cons h₂ t₂ := begin intros eh et, rw setoid.r_cons_iff, simp only [dtup.head_cons, dtup.tail_cons], split; assumption end end setoid end index namespace quot open index open relation variable {α : Type*} abbreviation index_mk {xs : list α} {β : index xs → Sort*} (r : Π i, β i → β i → Prop) (t : Π i, β i) : Π i, quot (r i) := λ i, quot.mk (r i) (t i) @[elab_as_eliminator] theorem index_ind : ∀ {xs : list α} {β : index xs → Sort*} {r : Π i, β i → β i → Prop} (hr : ∀ i, reflexive (r i)) {P : (Π i, quot (r i)) → Prop}, (∀ (t : Π i, β i), P (λ i, quot.mk (r i) (t i))) → ∀ q, P q | [] β r hr P H q := by { rw [dtup.eq_nil q, ← dtup.eq_nil (λ i, @quot.mk (β i) (r i) (dtup.nil i))], apply H } | (x::xs) β r hr P H q := have ∀ (h : dtup.head β) (t : Π i, dtup.tail β i), (λ i, quot.mk (r i) (dtup.cons h t i)) = dtup.cons (quot.mk (dtup.head r) h) (λ i, quot.mk (dtup.tail r i) (t i)), by { intros, funext i, cases i; reflexivity }, have IH : ∀ (h : dtup.head β) (q : Π i, quot (dtup.tail r i)), P (dtup.cons (quot.mk (dtup.head r) h) q), from λ h q, index_ind (dtup.tail hr) (by {introv, rw ← this, apply H}) q, begin rw [← dtup.cons_head_tail q], induction (dtup.head q) using quot.ind with h, apply IH, end @[elab_as_eliminator] theorem index_induction_on {xs : list α} {β : index xs → Sort*} {r : Π i, β i → β i → Prop} (hr : ∀ i, reflexive (r i)) {P : (Π i, quot (r i)) → Prop} (q : Π i, quot (r i)) : (∀ (t : Π i, β i), P (λ i, quot.mk (r i) (t i))) → P q := λ H, index_ind hr H q def index_map {xs : list α} {β : index xs → Sort*} (r : Π i, β i → β i → Prop) : quot (pi r) → Π i, quot (r i) := quot.lift (λ (t : Π i, β i) (i : index xs), quot.mk (r i) (t i)) $ λ (t₁ t₂ : Π i, β i) (h : pi r t₁ t₂), funext $ λ i, quot.sound (h i) def index_map_beta {xs : list α} {β : index xs → Sort*} {r : Π i, β i → β i → Prop} (t : Π i, β i) : index_map r (quot.mk (pi r) t) = λ i, quot.mk (r i) (t i) := rfl section index_cons variables {x : α} {xs : list α} {β : index (x :: xs) → Sort*} {r : Π i, β i → β i → Prop} def index_cons_func (hr : reflexive (dtup.head r)) : dtup.head β → quot (pi (dtup.tail r)) → quot (pi r) := λ h, quot.lift (λ t, quot.mk (pi r) (dtup.cons h t)) $ λ t₁ t₂ ht, quot.sound (dtup.cons (hr h) ht) theorem index_cons_func_beta {hr : reflexive (dtup.head r)} (h : dtup.head β) (t : Π i, dtup.tail β i) : index_cons_func hr h (quot.mk (pi (dtup.tail r)) t) = quot.mk (pi r) (dtup.cons h t) := rfl def index_cons (hr : ∀ i, reflexive (r i)) : quot (dtup.head r) → quot (pi (dtup.tail r)) → quot (pi r) := quot.lift (index_cons_func (dtup.head hr)) $ begin intros h₁ h₂ hh, funext t, induction t using quot.ind, rw index_cons_func_beta, rw index_cons_func_beta, apply quot.sound, apply dtup.cons, exact hh, exact pi_reflexive (dtup.tail hr) t, end theorem index_cons_beta {hr : ∀ i, reflexive (r i)} (h : dtup.head β) (t : Π i, dtup.tail β i) : index_cons hr (quot.mk (dtup.head r) h) (quot.mk (pi (dtup.tail r)) t) = quot.mk (pi r) (dtup.cons h t) := rfl end index_cons def index_inv : Π {xs : list α} {β : index xs → Sort*} {r : Π i, β i → β i → Prop} (hr : Π i, reflexive (r i)), (Π i, quot (r i)) → quot (pi r) | [] _ r _ _ := quot.mk (pi r) dtup.nil | (_::_) _ _ hr q := index_cons hr (dtup.head q) (index_inv (dtup.tail hr) (dtup.tail q)) theorem index_inv_nil {β : index (@list.nil α) → Sort*} {r : Π i, β i → β i → Prop} {hr : Π i, reflexive (r i)} : index_inv hr dtup.nil = quot.mk (pi r) dtup.nil := rfl theorem index_inv_cons {x : α} {xs : list α} {β : index (x :: xs) → Sort*} {r : Π i, β i → β i → Prop} {hr : Π i, reflexive (r i)} (h : quot (dtup.head r)) (t : Π i, quot (dtup.tail r i)) : index_inv hr (dtup.cons h t) = index_cons hr h (index_inv (dtup.tail hr) t) := rfl theorem index_inv_head_tail {x : α} {xs : list α} {β : index (x :: xs) → Sort*} {r : Π i, β i → β i → Prop} {hr : Π i, reflexive (r i)} (q : Π i, quot (r i)) : index_inv hr q = index_cons hr (dtup.head q) (index_inv (dtup.tail hr) (dtup.tail q)) := rfl theorem index_inv_beta : Π {xs : list α} {β : index xs → Sort*} {r : Π i, β i → β i → Prop} {hr : Π i, reflexive (r i)} (t : Π i, β i), index_inv hr (λ i, quot.mk (r i) (t i)) = quot.mk (pi r) t | [] _ _ _ t := by { rw [dtup.eq_nil t], reflexivity } | (x::xs) β r hr t := by { rw [index_inv_head_tail, index_inv_beta, index_cons_beta], simp } theorem index_inv_map {xs : list α} {β : index xs → Sort*} {r : Π i, β i → β i → Prop} {hr : ∀ i, reflexive (r i)} : ∀ (q : quot (pi r)), index_inv hr (index_map r q) = q := quot.ind (by intro; rw [index_map_beta, index_inv_beta]) theorem index_map_inv {xs : list α} {β : index xs → Sort*} {r : Π i, β i → β i → Prop} {hr : ∀ i, reflexive (r i)} : ∀ (q : Π i, quot (r i)), index_map r (index_inv hr q) = q := quot.index_ind hr (by intro; rw [index_inv_beta, index_map_beta]) @[elab_as_eliminator, reducible] def index_lift {xs : list α} {β : index xs → Sort*} {r : Π i, β i → β i → Prop} (hr : Π i, reflexive (r i)) {γ : Sort*} (f : (Π i, β i) → γ) : (∀ t₁ t₂, pi r t₁ t₂ → f t₁ = f t₂) → (Π i, quot (r i)) → γ := λ H q, quot.lift f H (index_inv hr q) @[elab_as_eliminator, reducible] abbreviation index_lift_on {xs : list α} {β : index xs → Sort*} {r : Π i, β i → β i → Prop} (hr : Π i, reflexive (r i)) (q : Π i, quot (r i)) {γ : Sort*} (f : (Π i, β i) → γ) : (∀ t₁ t₂, pi r t₁ t₂ → f t₁ = f t₂) → γ := λ H, index_lift hr f H q theorem index_lift_def {xs : list α} {β : index xs → Sort*} {r : Π i, β i → β i → Prop} {hr : Π i, reflexive (r i)} {γ : Sort*} (f : (Π i, β i) → γ) {H : ∀ t₁ t₂, pi r t₁ t₂ → f t₁ = f t₂} (q : Π i, quot (r i)) : index_lift hr f H q = quot.lift f H (index_inv hr q) := rfl theorem index_lift_map {xs : list α} {β : index xs → Sort*} {r : Π i, β i → β i → Prop} {hr : Π i, reflexive (r i)} {γ : Sort*} (f : (Π i, β i) → γ) {H : ∀ t₁ t₂, pi r t₁ t₂ → f t₁ = f t₂} (q : quot (pi r)) : index_lift hr f H (index_map r q) = quot.lift f H q := by rw [← index_inv_map q] {occs:=occurrences.pos[2]} theorem index_lift_beta {xs : list α} {β : index xs → Sort*} {r : Π i, β i → β i → Prop} {hr : Π i, reflexive (r i)} {γ : Sort*} (f : (Π i, β i) → γ) {H : ∀ t₁ t₂, pi r t₁ t₂ → f t₁ = f t₂} (t : Π i, β i) : index_lift hr f H (λ i, quot.mk (r i) (t i)) = f t := by rw [← index_map_beta, index_lift_map] end quot namespace quotient open index variables {α : Type*} {xs : list α} {β : index xs → Sort*} [s : Π i, setoid (β i)] include s definition index_lift {γ : Sort*} (f : (Π i, β i) → γ) : (∀ (t₁ t₂ : Π i, β i), (∀ i, t₁ i ≈ t₂ i) → f t₁ = f t₂) → (Π i, quotient (s i)) → γ := have hr : ∀ i, reflexive (setoid.r : β i → β i → Prop), from λ i, (s i).iseqv.refl, quot.index_lift hr f theorem index_lift_beta {γ : Sort*} (f : (Π i, β i) → γ) {H : ∀ (t₁ t₂ : Π i, β i), (∀ i, t₁ i ≈ t₂ i) → f t₁ = f t₂} : ∀ (t : Π i, β i), index_lift f H (λ i, ⟦t i⟧) = f t := have hr : ∀ i, reflexive (setoid.r : β i → β i → Prop), from λ i, (s i).iseqv.refl, begin intro, dunfold index_lift, apply quot.index_lift_beta, end theorem index_ind {P : (Π i, quotient (s i)) → Prop} : (∀ (t : Π i, β i), P (λ i, ⟦t i⟧)) → ∀ q, P q := have hr : ∀ i, reflexive (setoid.r : β i → β i → Prop), from λ i, (s i).iseqv.refl, λ H, quot.index_ind hr H theorem index_induction_on {P : (Π i, quotient (s i)) → Prop} (q : Π i, quotient (s i)) : (∀ (t : Π i, β i), P (λ i, ⟦t i⟧)) → P q := λ H, index_ind H q end quotient namespace list variable {α : Type*} theorem mem_join (x : α) : Π {xss : list (list α)} (i : index xss), x ∈ i.val → x ∈ xss.join | _ (index.head xs xss) hi := show x ∈ xs ++ xss.join, by { rw mem_append, left, exact hi } | _ (index.tail xs xss i) hi := show x ∈ xs ++ xss.join, by { rw mem_append, right, exact mem_join i hi } end list
21bc146fa95c931af75882b7e2ead9bc772aa4ef
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/normed_space/completion.lean
d575ce664cc02a297107fa7aa68f4d5da41eb513
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
3,820
lean
/- Copyright (c) 2022 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import analysis.normed.group.completion import analysis.normed_space.operator_norm import topology.algebra.uniform_ring /-! # Normed space structure on the completion of a normed space > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. If `E` is a normed space over `𝕜`, then so is `uniform_space.completion E`. In this file we provide necessary instances and define `uniform_space.completion.to_complₗᵢ` - coercion `E → uniform_space.completion E` as a bundled linear isometry. We also show that if `A` is a normed algebra over `𝕜`, then so is `uniform_space.completion A`. TODO: Generalise the results here from the concrete `completion` to any `abstract_completion`. -/ noncomputable theory namespace uniform_space namespace completion variables (𝕜 E : Type*) [normed_field 𝕜] [normed_add_comm_group E] [normed_space 𝕜 E] @[priority 100] instance normed_space.to_has_uniform_continuous_const_smul : has_uniform_continuous_const_smul 𝕜 E := ⟨λ c, (lipschitz_with_smul c).uniform_continuous⟩ instance : normed_space 𝕜 (completion E) := { smul := (•), norm_smul_le := λ c x, induction_on x (is_closed_le (continuous_const_smul _).norm (continuous_const.mul continuous_norm)) $ λ y, by simp only [← coe_smul, norm_coe, norm_smul], .. completion.module } variables {𝕜 E} /-- Embedding of a normed space to its completion as a linear isometry. -/ def to_complₗᵢ : E →ₗᵢ[𝕜] completion E := { to_fun := coe, map_smul' := coe_smul, norm_map' := norm_coe, .. to_compl } @[simp] lemma coe_to_complₗᵢ : ⇑(to_complₗᵢ : E →ₗᵢ[𝕜] completion E) = coe := rfl /-- Embedding of a normed space to its completion as a continuous linear map. -/ def to_complL : E →L[𝕜] completion E := to_complₗᵢ.to_continuous_linear_map @[simp] lemma coe_to_complL : ⇑(to_complL : E →L[𝕜] completion E) = coe := rfl @[simp] lemma norm_to_complL {𝕜 E : Type*} [nontrivially_normed_field 𝕜] [normed_add_comm_group E] [normed_space 𝕜 E] [nontrivial E] : ‖(to_complL : E →L[𝕜] completion E)‖ = 1 := (to_complₗᵢ : E →ₗᵢ[𝕜] completion E).norm_to_continuous_linear_map section algebra variables (𝕜) (A : Type*) instance [semi_normed_ring A] : normed_ring (completion A) := { dist_eq := λ x y, begin apply completion.induction_on₂ x y; clear x y, { refine is_closed_eq (completion.uniform_continuous_extension₂ _).continuous _, exact continuous.comp completion.continuous_extension continuous_sub }, { intros x y, rw [← completion.coe_sub, norm_coe, completion.dist_eq, dist_eq_norm] } end, norm_mul := λ x y, begin apply completion.induction_on₂ x y; clear x y, { exact is_closed_le (continuous.comp (continuous_norm) continuous_mul) (continuous.comp real.continuous_mul (continuous.prod_map continuous_norm continuous_norm)) }, { intros x y, simp only [← coe_mul, norm_coe], exact norm_mul_le x y, } end, ..completion.ring, ..completion.metric_space } instance [semi_normed_comm_ring A] [normed_algebra 𝕜 A] [has_uniform_continuous_const_smul 𝕜 A] : normed_algebra 𝕜 (completion A) := { norm_smul_le := λ r x, begin apply completion.induction_on x; clear x, { exact is_closed_le (continuous.comp (continuous_norm) (continuous_const_smul r)) (continuous.comp (continuous_mul_left _) continuous_norm), }, { intros x, simp only [← coe_smul, norm_coe], exact norm_smul_le r x } end, ..completion.algebra A 𝕜} end algebra end completion end uniform_space
786e9e89663450309592688dfb3f3204d304078b
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/W/basic.lean
98e0919dbef24f4fa7655e334e64d67a131316c8
[ "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
6,824
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad -/ import logic.equiv.list /-! # W types > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Given `α : Type` and `β : α → Type`, the W type determined by this data, `W_type β`, is the inductively defined type of trees where the nodes are labeled by elements of `α` and the children of a node labeled `a` are indexed by elements of `β a`. This file is currently a stub, awaiting a full development of the theory. Currently, the main result is that if `α` is an encodable fintype and `β a` is encodable for every `a : α`, then `W_type β` is encodable. This can be used to show the encodability of other inductive types, such as those that are commonly used to formalize syntax, e.g. terms and expressions in a given language. The strategy is illustrated in the example found in the file `prop_encodable` in the `archive/examples` folder of mathlib. ## Implementation details While the name `W_type` is somewhat verbose, it is preferable to putting a single character identifier `W` in the root namespace. -/ /-- Given `β : α → Type*`, `W_type β` is the type of finitely branching trees where nodes are labeled by elements of `α` and the children of a node labeled `a` are indexed by elements of `β a`. -/ inductive W_type {α : Type*} (β : α → Type*) | mk (a : α) (f : β a → W_type) : W_type instance : inhabited (W_type (λ (_ : unit), empty)) := ⟨W_type.mk unit.star empty.elim⟩ namespace W_type variables {α : Type*} {β : α → Type*} /-- The canonical map to the corresponding sigma type, returning the label of a node as an element `a` of `α`, and the children of the node as a function `β a → W_type β`. -/ def to_sigma : W_type β → Σ a : α, β a → W_type β | ⟨a, f⟩ := ⟨a, f⟩ /-- The canonical map from the sigma type into a `W_type`. Given a node `a : α`, and its children as a function `β a → W_type β`, return the corresponding tree. -/ def of_sigma : (Σ a : α, β a → W_type β) → W_type β | ⟨a, f⟩ := W_type.mk a f @[simp] lemma of_sigma_to_sigma : Π (w : W_type β), of_sigma (to_sigma w) = w | ⟨a, f⟩ := rfl @[simp] lemma to_sigma_of_sigma : Π (s : Σ a : α, β a → W_type β), to_sigma (of_sigma s) = s | ⟨a, f⟩ := rfl variable (β) /-- The canonical bijection with the sigma type, showing that `W_type` is a fixed point of the polynomial functor `X ↦ Σ a : α, β a → X`. -/ @[simps] def equiv_sigma : W_type β ≃ Σ a : α, β a → W_type β := { to_fun := to_sigma, inv_fun := of_sigma, left_inv := of_sigma_to_sigma, right_inv := to_sigma_of_sigma } variable {β} /-- The canonical map from `W_type β` into any type `γ` given a map `(Σ a : α, β a → γ) → γ`. -/ def elim (γ : Type*) (fγ : (Σ a : α, β a → γ) → γ) : W_type β → γ | ⟨a, f⟩ := fγ ⟨a, λ b, elim (f b)⟩ lemma elim_injective (γ : Type*) (fγ : (Σ a : α, β a → γ) → γ) (fγ_injective : function.injective fγ) : function.injective (elim γ fγ) | ⟨a₁, f₁⟩ ⟨a₂, f₂⟩ h := begin obtain ⟨rfl, h⟩ := sigma.mk.inj (fγ_injective h), congr' with x, exact elim_injective (congr_fun (eq_of_heq h) x : _), end instance [hα : is_empty α] : is_empty (W_type β) := ⟨λ w, W_type.rec_on w (is_empty.elim hα)⟩ lemma infinite_of_nonempty_of_is_empty (a b : α) [ha : nonempty (β a)] [he : is_empty (β b)] : infinite (W_type β) := ⟨begin introsI hf, have hba : b ≠ a, from λ h, ha.elim (is_empty.elim' (show is_empty (β a), from h ▸ he)), refine not_injective_infinite_finite (λ n : ℕ, show W_type β, from nat.rec_on n ⟨b, is_empty.elim' he⟩ (λ n ih, ⟨a, λ _, ih⟩)) _, intros n m h, induction n with n ih generalizing m h, { cases m with m; simp * at * }, { cases m with m, { simp * at * }, { refine congr_arg nat.succ (ih _), simp [function.funext_iff, *] at * } } end⟩ variables [Π a : α, fintype (β a)] /-- The depth of a finitely branching tree. -/ def depth : W_type β → ℕ | ⟨a, f⟩ := finset.sup finset.univ (λ n, depth (f n)) + 1 lemma depth_pos (t : W_type β) : 0 < t.depth := by { cases t, apply nat.succ_pos } lemma depth_lt_depth_mk (a : α) (f : β a → W_type β) (i : β a) : depth (f i) < depth ⟨a, f⟩ := nat.lt_succ_of_le (finset.le_sup (finset.mem_univ i)) /- Show that W types are encodable when `α` is an encodable fintype and for every `a : α`, `β a` is encodable. We define an auxiliary type `W_type' β n` of trees of depth at most `n`, and then we show by induction on `n` that these are all encodable. These auxiliary constructions are not interesting in and of themselves, so we mark them as `private`. -/ @[reducible] private def W_type' {α : Type*} (β : α → Type*) [Π a : α, fintype (β a)] [Π a : α, encodable (β a)] (n : ℕ) := { t : W_type β // t.depth ≤ n} variables [Π a : α, encodable (β a)] private def encodable_zero : encodable (W_type' β 0) := let f : W_type' β 0 → empty := λ ⟨x, h⟩, false.elim $ not_lt_of_ge h (W_type.depth_pos _), finv : empty → W_type' β 0 := by { intro x, cases x} in have ∀ x, finv (f x) = x, from λ ⟨x, h⟩, false.elim $ not_lt_of_ge h (W_type.depth_pos _), encodable.of_left_inverse f finv this private def f (n : ℕ) : W_type' β (n + 1) → Σ a : α, β a → W_type' β n | ⟨t, h⟩ := begin cases t with a f, have h₀ : ∀ i : β a, W_type.depth (f i) ≤ n, from λ i, nat.le_of_lt_succ (lt_of_lt_of_le (W_type.depth_lt_depth_mk a f i) h), exact ⟨a, λ i : β a, ⟨f i, h₀ i⟩⟩ end private def finv (n : ℕ) : (Σ a : α, β a → W_type' β n) → W_type' β (n + 1) | ⟨a, f⟩ := let f' := λ i : β a, (f i).val in have W_type.depth ⟨a, f'⟩ ≤ n + 1, from add_le_add_right (finset.sup_le (λ b h, (f b).2)) 1, ⟨⟨a, f'⟩, this⟩ variables [encodable α] private def encodable_succ (n : nat) (h : encodable (W_type' β n)) : encodable (W_type' β (n + 1)) := encodable.of_left_inverse (f n) (finv n) (by { rintro ⟨⟨_, _⟩, _⟩, refl }) /-- `W_type` is encodable when `α` is an encodable fintype and for every `a : α`, `β a` is encodable. -/ instance : encodable (W_type β) := begin haveI h' : Π n, encodable (W_type' β n) := λ n, nat.rec_on n encodable_zero encodable_succ, let f : W_type β → Σ n, W_type' β n := λ t, ⟨t.depth, ⟨t, le_rfl⟩⟩, let finv : (Σ n, W_type' β n) → W_type β := λ p, p.2.1, have : ∀ t, finv (f t) = t, from λ t, rfl, exact encodable.of_left_inverse f finv this end end W_type
cc542fe0cdc06b2e08d24a446a8989be88535ee5
5756a081670ba9c1d1d3fca7bd47cb4e31beae66
/Mathport/Syntax/Translate/Tactic.lean
da69ca11e08f12ea73156553cbc4a461dd81c6b3
[ "Apache-2.0" ]
permissive
leanprover-community/mathport
2c9bdc8292168febf59799efdc5451dbf0450d4a
13051f68064f7638970d39a8fecaede68ffbf9e1
refs/heads/master
1,693,841,364,079
1,693,813,111,000
1,693,813,111,000
379,357,010
27
10
Apache-2.0
1,691,309,132,000
1,624,384,521,000
Lean
UTF-8
Lean
false
false
2,394
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathport.Syntax.Translate.Tactic.Lean3 import Mathport.Syntax.Translate.Tactic.Mathlib open Lean open Lean.Elab.Tactic (Location) namespace Mathport namespace Translate namespace Tactic open AST3 Parser Lean.Elab.Command open Lean.Elab.Command def mkTacMap (l : Array (Name × TacM Syntax.Tactic)) : M (NameMap (Array (Spanned AST3.Param) → CommandElabM Syntax.Tactic)) := do let mut tacs := {} for (n, tac) in l do tacs := tacs.insert n $ ← fun c s => pure fun a => return ⟨← tac.run n a c s⟩ pure tacs def mkConvMap (l : Array (Name × TacM Syntax.Conv)) : M (NameMap (Array (Spanned AST3.Param) → CommandElabM Syntax.Conv)) := do let mut tacs := {} for (n, tac) in l do tacs := tacs.insert n $ ← fun c s => pure fun a => return ⟨← tac.run n a c s⟩ pure tacs def mkTermMap (l : Array (Name × TacM Syntax.Term)) : M (NameMap (Array (Spanned AST3.Param) → CommandElabM Syntax.Term)) := do let mut tacs := {} for (n, tac) in l do tacs := tacs.insert n $ ← fun c s => pure fun a => return ⟨← tac.run n a c s⟩ pure tacs def mkAttrMap (l : Array (Name × Parse1 Syntax.Attr)) : M (NameMap (Array (Spanned AST3.Param) → CommandElabM Syntax.Attr)) := do let mut tacs := {} for (n, tac) in l do tacs := tacs.insert n $ ← fun c s => pure fun a => return ⟨← tac.run.run n a c s⟩ pure tacs def mkNITacMap (l : Array (Name × (AST3.Expr → M Syntax.Tactic))) : M (NameMap (AST3.Expr → CommandElabM Syntax.Tactic)) := do let mut tacs := {} for (n, tac) in l do tacs := tacs.insert n $ ← fun c s => pure fun a => return ⟨← tac a c s⟩ pure tacs def mkCmdMap (l : Array (Name × (Modifiers → Parse1 Unit))) : M (NameMap (Modifiers → Array (Spanned AST3.Param) → CommandElabM Unit)) := do let mut tacs := {} for (n, tac) in l do tacs := tacs.insert n $ ← fun c s => pure fun mod a => (tac mod).run.run n a c s pure tacs def builtinTactics := mkTacMap tr_tactics% def builtinNITactics := mkNITacMap tr_ni_tactics% def builtinConvs := mkConvMap tr_convs% def builtinUserNotation := mkTermMap tr_user_notas% def builtinUserAttrs := mkAttrMap tr_user_attrs% def builtinUserCmds := mkCmdMap tr_user_cmds%
0bdaac4e849ed3eaaf21a42d449caab4542e9d03
6b45072eb2b3db3ecaace2a7a0241ce81f815787
/algebra/lattice/basic_experiment.lean
9d44ed3b9bd825841fab5361a3965db65807be24
[]
no_license
avigad/library_dev
27b47257382667b5eb7e6476c4f5b0d685dd3ddc
9d8ac7c7798ca550874e90fed585caad030bbfac
refs/heads/master
1,610,452,468,791
1,500,712,839,000
1,500,713,478,000
69,311,142
1
0
null
1,474,942,903,000
1,474,942,902,000
null
UTF-8
Lean
false
false
9,731
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl Defines the inf/sup (semi)-lattice with optionally top/bot type class hierarchy. -/ import ..order tools.auto.finish open auto set_option old_structure_cmd true universes u v w -- TODO: move this eventually, if we decide to use them attribute [ematch] le_trans lt_of_le_of_lt lt_of_lt_of_le lt_trans section variable {α : Type u} -- TODO: this seems crazy, but it also seems to work reasonably well @[ematch] lemma le_antisymm' [weak_order α] : ∀ {a b : α}, (: a ≤ b :) → b ≤ a → a = b := weak_order.le_antisymm end /- TODO: automatic construction of dual definitions / theorems -/ namespace lattice reserve infixl ` ⊓ `:70 reserve infixl ` ⊔ `:65 class has_top (α : Type u) := (top : α) class has_bot (α : Type u) := (bot : α) class has_sup (α : Type u) := (sup : α → α → α) class has_inf (α : Type u) := (inf : α → α → α) class has_imp (α : Type u) := (imp : α → α → α) /- Better name -/ def imp {α : Type u} [has_imp α] : α → α → α := has_imp.imp infix ⊔ := has_sup.sup infix ⊓ := has_inf.inf notation `⊤` := has_top.top _ notation `⊥` := has_bot.bot _ class order_top (α : Type u) extends has_top α, weak_order α := (le_top : ∀ a : α, a ≤ ⊤) section order_top variables {α : Type u} [order_top α] {a : α} @[simp] lemma le_top : a ≤ ⊤ := order_top.le_top a lemma top_unique (h : ⊤ ≤ a) : a = ⊤ := le_antisymm le_top h -- TODO: delete in favor of the next? lemma eq_top_iff : a = ⊤ ↔ ⊤ ≤ a := ⟨assume eq, eq^.symm ▸ le_refl ⊤, top_unique⟩ @[simp] lemma top_le_iff : ⊤ ≤ a ↔ a = ⊤ := ⟨top_unique, λ h, h.symm ▸ le_refl ⊤⟩ end order_top class order_bot (α : Type u) extends has_bot α, weak_order α := (bot_le : ∀ a : α, ⊥ ≤ a) section order_bot variables {α : Type u} [order_bot α] {a : α} @[simp] lemma bot_le : ⊥ ≤ a := order_bot.bot_le a lemma bot_unique (h : a ≤ ⊥) : a = ⊥ := le_antisymm h bot_le -- TODO: delete? lemma eq_bot_iff : a = ⊥ ↔ a ≤ ⊥ := ⟨assume eq, eq^.symm ▸ le_refl ⊥, bot_unique⟩ @[simp] lemma le_bot_iff : a ≤ ⊥ ↔ a = ⊥ := ⟨bot_unique, assume h, h.symm ▸ le_refl ⊥⟩ lemma neq_bot_of_le_neq_bot {a b : α} (hb : b ≠ ⊥) (hab : b ≤ a) : a ≠ ⊥ := assume ha, hb $ bot_unique $ ha ▸ hab end order_bot class semilattice_sup (α : Type u) extends has_sup α, weak_order α := (le_sup_left : ∀ a b : α, a ≤ a ⊔ b) (le_sup_right : ∀ a b : α, b ≤ a ⊔ b) (sup_le : ∀ a b c : α, a ≤ c → b ≤ c → a ⊔ b ≤ c) section semilattice_sup variables {α : Type u} [semilattice_sup α] {a b c d : α} lemma le_sup_left : a ≤ a ⊔ b := semilattice_sup.le_sup_left a b @[ematch] lemma le_sup_left' : a ≤ (: a ⊔ b :) := semilattice_sup.le_sup_left a b lemma le_sup_right : b ≤ a ⊔ b := semilattice_sup.le_sup_right a b @[ematch] lemma le_sup_right' : b ≤ (: a ⊔ b :) := semilattice_sup.le_sup_right a b lemma le_sup_left_of_le (h : c ≤ a) : c ≤ a ⊔ b := by finish lemma le_sup_right_of_le (h : c ≤ b) : c ≤ a ⊔ b := by finish lemma sup_le : a ≤ c → b ≤ c → a ⊔ b ≤ c := semilattice_sup.sup_le a b c @[simp] lemma sup_le_iff : a ⊔ b ≤ c ↔ a ≤ c ∧ b ≤ c := ⟨assume h : a ⊔ b ≤ c, ⟨le_trans le_sup_left h, le_trans le_sup_right h⟩, assume ⟨h₁, h₂⟩, sup_le h₁ h₂⟩ -- TODO: if we just write le_antisymm, Lean doesn't know which ≤ we want to use -- Can we do anything about that? lemma sup_of_le_left (h : b ≤ a) : a ⊔ b = a := by apply @le_antisymm; finish lemma sup_of_le_right (h : a ≤ b) : a ⊔ b = b := by apply @le_antisymm α _ ; finish lemma sup_le_sup (h₁ : a ≤ b) (h₂ : c ≤ d) : a ⊔ c ≤ b ⊔ d := by finish lemma le_of_sup_eq (h : a ⊔ b = b) : a ≤ b := by finish @[simp] lemma sup_idem : a ⊔ a = a := by apply @le_antisymm; finish lemma sup_comm : a ⊔ b = b ⊔ a := by apply @le_antisymm; finish instance semilattice_sup_to_is_commutative [semilattice_sup α] : is_commutative α (⊔) := ⟨@sup_comm _ _⟩ lemma sup_assoc : a ⊔ b ⊔ c = a ⊔ (b ⊔ c) := by apply @le_antisymm; finish /- old proof: le_antisymm (sup_le (sup_le le_sup_left (le_sup_right_of_le le_sup_left)) (le_sup_right_of_le le_sup_right)) (sup_le (le_sup_left_of_le le_sup_left) (sup_le (le_sup_left_of_le le_sup_right) le_sup_right)) -/ instance semilattice_sup_to_is_associative [semilattice_sup α] : is_associative α (⊔) := ⟨@sup_assoc _ _⟩ end semilattice_sup class semilattice_inf (α : Type u) extends has_inf α, weak_order α := (inf_le_left : ∀ a b : α, a ⊓ b ≤ a) (inf_le_right : ∀ a b : α, a ⊓ b ≤ b) (le_inf : ∀ a b c : α, a ≤ b → a ≤ c → a ≤ b ⊓ c) section semilattice_inf variables {α : Type u} [semilattice_inf α] {a b c d : α} lemma inf_le_left : a ⊓ b ≤ a := semilattice_inf.inf_le_left a b @[ematch] lemma inf_le_left' : (: a ⊓ b :) ≤ a := semilattice_inf.inf_le_left a b lemma inf_le_right : a ⊓ b ≤ b := semilattice_inf.inf_le_right a b @[ematch] lemma inf_le_right' : (: a ⊓ b :) ≤ b := semilattice_inf.inf_le_right a b lemma le_inf : a ≤ b → a ≤ c → a ≤ b ⊓ c := semilattice_inf.le_inf a b c lemma inf_le_left_of_le (h : a ≤ c) : a ⊓ b ≤ c := le_trans inf_le_left h lemma inf_le_right_of_le (h : b ≤ c) : a ⊓ b ≤ c := le_trans inf_le_right h @[simp] lemma le_inf_iff : a ≤ b ⊓ c ↔ a ≤ b ∧ a ≤ c := ⟨assume h : a ≤ b ⊓ c, ⟨le_trans h inf_le_left, le_trans h inf_le_right⟩, assume ⟨h₁, h₂⟩, le_inf h₁ h₂⟩ lemma inf_of_le_left (h : a ≤ b) : a ⊓ b = a := by apply @le_antisymm; finish /- old proof: le_antisymm inf_le_left (le_inf (le_refl _) h) -/ lemma inf_of_le_right (h : b ≤ a) : a ⊓ b = b := by apply @le_antisymm; finish lemma inf_le_inf (h₁ : a ≤ b) (h₂ : c ≤ d) : a ⊓ c ≤ b ⊓ d := by finish lemma le_of_inf_eq (h : a ⊓ b = a) : a ≤ b := by finish @[simp] lemma inf_idem : a ⊓ a = a := by apply @le_antisymm; finish lemma inf_comm : a ⊓ b = b ⊓ a := by apply @le_antisymm; finish instance semilattice_inf_to_is_commutative [semilattice_inf α] : is_commutative α (⊓) := ⟨@inf_comm _ _⟩ set_option pp.all true lemma inf_assoc : a ⊓ b ⊓ c = a ⊓ (b ⊓ c) := by apply @le_antisymm; finish /- old proof: le_antisymm (le_inf (inf_le_left_of_le inf_le_left) (le_inf (inf_le_left_of_le inf_le_right) inf_le_right)) (le_inf (le_inf inf_le_left (inf_le_right_of_le inf_le_left)) (inf_le_right_of_le inf_le_right)) -/ instance semilattice_inf_to_is_associative [semilattice_inf α] : is_associative α (⊓) := ⟨@inf_assoc _ _⟩ end semilattice_inf class semilattice_sup_top (α : Type u) extends order_top α, semilattice_sup α section semilattice_sup_top variables {α : Type u} [semilattice_sup_top α] {a : α} @[simp] lemma top_sup_eq : ⊤ ⊔ a = ⊤ := sup_of_le_left le_top @[simp] lemma sup_top_eq : a ⊔ ⊤ = ⊤ := sup_of_le_right le_top end semilattice_sup_top class semilattice_sup_bot (α : Type u) extends order_bot α, semilattice_sup α section semilattice_sup_bot variables {α : Type u} [semilattice_sup_bot α] {a b : α} @[simp] lemma bot_sup_eq : ⊥ ⊔ a = a := sup_of_le_right bot_le @[simp] lemma sup_bot_eq : a ⊔ ⊥ = a := sup_of_le_left bot_le @[simp] lemma sup_eq_bot_iff : a ⊔ b = ⊥ ↔ (a = ⊥ ∧ b = ⊥) := by rw [eq_bot_iff, sup_le_iff]; simp end semilattice_sup_bot class semilattice_inf_top (α : Type u) extends order_top α, semilattice_inf α section semilattice_inf_top variables {α : Type u} [semilattice_inf_top α] {a b : α} @[simp] lemma top_inf_eq : ⊤ ⊓ a = a := inf_of_le_right le_top @[simp] lemma inf_top_eq : a ⊓ ⊤ = a := inf_of_le_left le_top @[simp] lemma inf_eq_top_iff : a ⊓ b = ⊤ ↔ (a = ⊤ ∧ b = ⊤) := by rw [eq_top_iff, le_inf_iff]; simp end semilattice_inf_top class semilattice_inf_bot (α : Type u) extends order_bot α, semilattice_inf α section semilattice_inf_bot variables {α : Type u} [semilattice_inf_bot α] {a : α} @[simp] lemma bot_inf_eq : ⊥ ⊓ a = ⊥ := inf_of_le_left bot_le @[simp] lemma inf_bot_eq : a ⊓ ⊥ = ⊥ := inf_of_le_right bot_le end semilattice_inf_bot /- Lattices -/ class lattice (α : Type u) extends semilattice_sup α, semilattice_inf α section lattice variables {α : Type u} [lattice α] {a b c d : α} /- Distributivity laws -/ /- TODO: better names? -/ lemma sup_inf_le : a ⊔ (b ⊓ c) ≤ (a ⊔ b) ⊓ (a ⊔ c) := by finish /- old proof sup_le (le_inf le_sup_left le_sup_left) $ le_inf (inf_le_left_of_le le_sup_right) (inf_le_right_of_le le_sup_right) -/ lemma le_inf_sup : (a ⊓ b) ⊔ (a ⊓ c) ≤ a ⊓ (b ⊔ c) := by finish /- old proof le_inf (sup_le inf_le_left inf_le_left) $ sup_le (le_sup_left_of_le inf_le_right) (le_sup_right_of_le inf_le_right) -/ lemma inf_sup_self : a ⊓ (a ⊔ b) = a := le_antisymm (by finish) (by finish) /- old proof le_antisymm inf_le_left (le_inf (le_refl a) le_sup_left) -/ lemma sup_inf_self : a ⊔ (a ⊓ b) = a := le_antisymm (by finish) (by finish) end lattice /- Lattices derived from linear orders -/ instance lattice_of_decidable_linear_order {α : Type u} [o : decidable_linear_order α] : lattice α := { o with sup := max, le_sup_left := le_max_left, le_sup_right := le_max_right, sup_le := assume a b c, max_le, inf := min, inf_le_left := min_le_left, inf_le_right := min_le_right, le_inf := assume a b c, le_min } end lattice
5a897db5bbd728d3d94fb4375ac70ca32c37de4f
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/order/category/omega_complete_partial_order.lean
39f650f57afc27ee48ef40a9273bf6fe9ac8376d
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,971
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import order.omega_complete_partial_order import order.category.Preorder import category_theory.limits.shapes.products import category_theory.limits.shapes.equalizers import category_theory.limits.constructions.limits_of_products_and_equalizers /-! # Category of types with a omega complete partial order In this file, we bundle the class `omega_complete_partial_order` into a concrete category and prove that continuous functions also form a `omega_complete_partial_order`. ## Main definitions * `ωCPO` * an instance of `category` and `concrete_category` -/ open category_theory universes u v /-- The category of types with a omega complete partial order. -/ def ωCPO : Type (u+1) := bundled omega_complete_partial_order namespace ωCPO open omega_complete_partial_order instance : bundled_hom @continuous_hom := { to_fun := @continuous_hom.to_fun, id := @continuous_hom.id, comp := @continuous_hom.comp, hom_ext := @continuous_hom.coe_inj } attribute [derive [has_coe_to_sort, large_category, concrete_category]] ωCPO /-- Construct a bundled ωCPO from the underlying type and typeclass. -/ def of (α : Type*) [omega_complete_partial_order α] : ωCPO := bundled.of α instance : inhabited ωCPO := ⟨of punit⟩ instance (α : ωCPO) : omega_complete_partial_order α := α.str section open category_theory.limits namespace has_products /-- The pi-type gives a cone for a product. -/ def product {J : Type v} (f : J → ωCPO.{v}) : fan f := fan.mk (of (Π j, f j)) (λ j, continuous_hom.of_mono (pi.eval_preorder_hom j) (λ c, rfl)) /-- The pi-type is a limit cone for the product. -/ def is_product (J : Type v) (f : J → ωCPO) : is_limit (product f) := { lift := λ s, ⟨λ t j, s.π.app j t, λ x y h j, (s.π.app j).monotone h, λ x, funext (λ j, (s.π.app j).continuous x)⟩, uniq' := λ s m w, begin ext t j, change m t j = s.π.app j t, rw ← w j, refl, end }. instance (J : Type v) (f : J → ωCPO.{v}) : has_product f := has_limit.mk ⟨_, is_product _ f⟩ end has_products instance omega_complete_partial_order_equalizer {α β : Type*} [omega_complete_partial_order α] [omega_complete_partial_order β] (f g : α →𝒄 β) : omega_complete_partial_order {a : α // f a = g a} := omega_complete_partial_order.subtype _ $ λ c hc, begin rw [f.continuous, g.continuous], congr' 1, ext, apply hc _ ⟨_, rfl⟩, end namespace has_equalizers /-- The equalizer inclusion function as a `continuous_hom`. -/ def equalizer_ι {α β : Type*} [omega_complete_partial_order α] [omega_complete_partial_order β] (f g : α →𝒄 β) : {a : α // f a = g a} →𝒄 α := continuous_hom.of_mono (preorder_hom.subtype.val _) (λ c, rfl) /-- A construction of the equalizer fork. -/ def equalizer {X Y : ωCPO.{v}} (f g : X ⟶ Y) : fork f g := @fork.of_ι _ _ _ _ _ _ (ωCPO.of {a // f a = g a}) (equalizer_ι f g) (continuous_hom.ext _ _ (λ x, x.2)) /-- The equalizer fork is a limit. -/ def is_equalizer {X Y : ωCPO.{v}} (f g : X ⟶ Y) : is_limit (equalizer f g) := fork.is_limit.mk' _ $ λ s, ⟨{ to_fun := λ x, ⟨s.ι x, by apply continuous_hom.congr_fun s.condition⟩, monotone' := λ x y h, s.ι.monotone h, cont := λ x, subtype.ext (s.ι.continuous x) }, by { ext, refl }, λ m hm, begin ext, apply continuous_hom.congr_fun hm, end⟩ end has_equalizers instance : has_products ωCPO.{v} := λ J, { has_limit := λ F, has_limit_of_iso discrete.nat_iso_functor.symm } instance {X Y : ωCPO.{v}} (f g : X ⟶ Y) : has_limit (parallel_pair f g) := has_limit.mk ⟨_, has_equalizers.is_equalizer f g⟩ instance : has_equalizers ωCPO.{v} := has_equalizers_of_has_limit_parallel_pair _ instance : has_limits ωCPO.{v} := limits_from_equalizers_and_products end end ωCPO
726ae78822583f4be5aef9d848ce8a84fb3907fb
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/structure_test.lean
d2ea0389bb82e6de7f7e52cbee143f78de92d3a7
[ "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
709
lean
import logic data.sigma inductive point (A B : Type) := mk : Π (x : A) (y : B), point A B inductive color [class] := red | green | blue constant foo.{l} (A : Type.{l}) [H : decidable_eq A] : Type.{l} constants a : num section universe variable l variable A : Type.{l} variable Ha : decidable_eq A include Ha variable E : Type₂ include E -- include Ha structure point3d_color (B C : Type) (D : B → Type) extends point (foo A) B, sigma D renaming pr1→y pr2→w := mk :: (c : color) (H : x == y) check point3d_color.c check point3d_color.to_point end section universe l parameters A : Type.{l} parameters B : Type.{l} structure tst := mk :: (a : A) (b : B) end
6b679676a3c40fa9abac29a0051bce509bb1ccd0
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/run/depElim1.lean
76779c329b24acf13c6b22501b6ae6e09d23ef2e
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,940
lean
import Lean.Meta.Match new_frontend open Lean open Lean.Meta open Lean.Meta.Match /- Infrastructure for testing -/ universes u v def check (x : Bool) : IO Unit := «unless» x $ throw $ IO.userError "check failed" def inaccessible {α : Sort u} (a : α) : α := a def val {α : Sort u} (a : α) : α := a def As {α : Sort u} (v a : α) : α := a inductive Pat {α : Sort u} (a : α) : Type u | mk : Pat a inductive ArrayLit0 (α : Sort u) : Type u | mk : ArrayLit0 α inductive ArrayLit1 {α : Sort u} (a : α) : Type u | mk : ArrayLit1 a inductive ArrayLit2 {α : Sort u} (a b : α) : Type u | mk : ArrayLit2 a b inductive ArrayLit3 {α : Sort u} (a b c : α) : Type u | mk : ArrayLit3 a b c inductive ArrayLit4 {α : Sort u} (a b c d : α) : Type u | mk : ArrayLit4 a b c d private def getConstructorVal (ctorName : Name) (fn : Expr) (args : Array Expr) : MetaM (Option (ConstructorVal × Expr × Array Expr)) := do let env ← getEnv; (match env.find? ctorName with | some (ConstantInfo.ctorInfo v) => if args.size == v.nparams + v.nfields then pure $ some (v, fn, args) else pure none | _ => pure none) private def constructorApp? (e : Expr) : MetaM (Option (ConstructorVal × Expr × Array Expr)) := do let env ← getEnv; (match e with | Expr.lit (Literal.natVal n) _ => if n == 0 then getConstructorVal `Nat.zero (mkConst `Nat.zero) #[] else getConstructorVal `Nat.succ (mkConst `Nat.succ) #[mkNatLit (n-1)] | _ => let fn := e.getAppFn; match fn with | Expr.const n _ _ => getConstructorVal n fn e.getAppArgs | _ => pure none) /- Convert expression using auxiliary hints `inaccessible` and `val` into a pattern -/ partial def mkPattern : Expr → MetaM Pattern | e => if e.isAppOfArity `val 2 then pure $ Pattern.val e.appArg! else if e.isAppOfArity `inaccessible 2 then pure $ Pattern.inaccessible e.appArg! else if e.isFVar then pure $ Pattern.var e.fvarId! else if e.isAppOfArity `As 3 && (e.getArg! 1).isFVar then do let v := e.getArg! 1; let p := e.getArg! 2; let p ← mkPattern p; pure $ Pattern.as v.fvarId! p else if e.isAppOfArity `ArrayLit0 1 || e.isAppOfArity `ArrayLit1 2 || e.isAppOfArity `ArrayLit2 3 || e.isAppOfArity `ArrayLit3 4 || e.isAppOfArity `ArrayLit4 5 then do let args := e.getAppArgs; let type := args[0]; let ps := args.extract 1 args.size; let ps ← ps.toList.mapM mkPattern; pure $ Pattern.arrayLit type ps else match e.arrayLit? with | some (_, es) => do let pats ← es.mapM mkPattern; let type ← inferType e; let type ← whnfD type; let elemType := type.appArg!; pure $ Pattern.arrayLit elemType pats | none => do let e ← whnfD e; let r? ← constructorApp? e; (match r? with | none => throwError "unexpected pattern" | some (cval, fn, args) => do let params := args.extract 0 cval.nparams; let fields := args.extract cval.nparams args.size; let pats ← fields.toList.mapM mkPattern; pure $ Pattern.ctor cval.name fn.constLevels! params.toList pats) partial def decodePats : Expr → MetaM (List Pattern) | e => match e.app2? `Pat with | some (_, pat) => do let pat ← mkPattern pat; pure [pat] | none => match e.prod? with | none => throwError "unexpected pattern" | some (pat, pats) => do let pat ← decodePats pat; let pats ← decodePats pats; pure (pat ++ pats) partial def decodeAltLHS (e : Expr) : MetaM AltLHS := forallTelescopeReducing e fun args body => do let decls ← args.toList.mapM (fun arg => getLocalDecl arg.fvarId!); let pats ← decodePats body; pure { ref := Syntax.missing, fvarDecls := decls, patterns := pats } partial def decodeAltLHSs : Expr → MetaM (List AltLHS) | e => match e.app2? `LHS with | some (_, lhs) => do let lhs ← decodeAltLHS lhs; pure [lhs] | none => match e.prod? with | none => throwError "unexpected LHS" | some (lhs, lhss) => do let lhs ← decodeAltLHSs lhs; let lhss ← decodeAltLHSs lhss; pure (lhs ++ lhss) def withDepElimFrom {α} (declName : Name) (numPats : Nat) (k : List FVarId → List AltLHS → MetaM α) : MetaM α := do let cinfo ← getConstInfo declName; forallTelescopeReducing cinfo.type fun args body => if args.size < numPats then throwError "insufficient number of parameters" else do let xs := (args.extract (args.size - numPats) args.size).toList.map $ Expr.fvarId!; let alts ← decodeAltLHSs body; k xs alts inductive LHS {α : Sort u} (a : α) : Type u | mk : LHS a instance LHS.inhabited {α} (a : α) : Inhabited (LHS a) := ⟨LHS.mk⟩ -- set_option trace.Meta.debug true -- set_option trace.Meta.Tactic.cases true -- set_option trace.Meta.Tactic.subst true @[init] def register : IO Unit := registerTraceClass `Meta.mkElim /- Helper methods for testins mkElim -/ private def getUnusedLevelParam (majors : List Expr) (lhss : List AltLHS) : MetaM Level := do let s : CollectLevelParams.State := {}; let s ← majors.foldlM (fun s major => do let major ← instantiateMVars major; let majorType ← inferType major; let majorType ← instantiateMVars majorType; let s := collectLevelParams s major; pure $ collectLevelParams s majorType) s; pure s.getUnusedLevelParam /- Return `Prop` if `inProf == true` and `Sort u` otherwise, where `u` is a fresh universe level parameter. -/ private def mkElimSort (majors : List Expr) (lhss : List AltLHS) (inProp : Bool) : MetaM Expr := if inProp then pure $ mkSort $ levelZero else do let v ← getUnusedLevelParam majors lhss; pure $ mkSort $ v def mkTester (elimName : Name) (majors : List Expr) (lhss : List AltLHS) (inProp : Bool := false) : MetaM MatcherResult := do generalizeTelescope majors.toArray `_d fun majors => do let resultType := if inProp then mkConst `True /- some proposition -/ else mkConst `Nat; let matchType ← mkForallFVars majors resultType; Match.mkMatcher elimName matchType majors.size lhss def test (ex : Name) (numPats : Nat) (elimName : Name) (inProp : Bool := false) : MetaM Unit := withDepElimFrom ex numPats fun majors alts => do let majors := majors.map mkFVar; trace! `Meta.debug ("majors: " ++ majors.toArray); let r ← mkTester elimName majors alts inProp; «unless» r.counterExamples.isEmpty $ throwError ("missing cases:" ++ Format.line ++ counterExamplesToMessageData r.counterExamples); «unless» r.unusedAltIdxs.isEmpty $ throwError ("unused alternatives: " ++ toString (r.unusedAltIdxs.map fun idx => "#" ++ toString (idx+1))); let cinfo ← getConstInfo elimName; IO.println (toString cinfo.name ++ " : " ++ toString cinfo.type); pure () def testFailure (ex : Name) (numPats : Nat) (elimName : Name) (inProp : Bool := false) : MetaM Unit := do let worked ← «catch» (do test ex numPats elimName inProp; pure true) (fun ex => pure false); when worked $ throwError "unexpected success" def ex0 (x : Nat) : LHS (forall (y : Nat), Pat y) := arbitrary _ #eval test `ex0 1 `elimTest0 #print elimTest0 def ex1 (α : Type u) (β : Type v) (n : Nat) (x : List α) (y : List β) : LHS (Pat ([] : List α) × Pat ([] : List β)) × LHS (forall (a : α) (as : List α) (b : β) (bs : List β), Pat (a::as) × Pat (b::bs)) × LHS (forall (a : α) (as : List α), Pat (a::as) × Pat ([] : List β)) × LHS (forall (b : β) (bs : List β), Pat ([] : List α) × Pat (b::bs)) := arbitrary _ #eval test `ex1 2 `elimTest1 #print elimTest1 inductive Vec (α : Type u) : Nat → Type u | nil : Vec α 0 | cons {n : Nat} : α → Vec α n → Vec α (n+1) def ex2 (α : Type u) (n : Nat) (xs : Vec α n) (ys : Vec α n) : LHS (Pat (inaccessible 0) × Pat (Vec.nil : Vec α 0) × Pat (Vec.nil : Vec α 0)) × LHS (forall (n : Nat) (x : α) (xs : Vec α n) (y : α) (ys : Vec α n), Pat (inaccessible (n+1)) × Pat (Vec.cons x xs) × Pat (Vec.cons y ys)) := arbitrary _ #eval test `ex2 3 `elimTest2 #print elimTest2 def ex3 (α : Type u) (β : Type v) (n : Nat) (x : List α) (y : List β) : LHS (Pat ([] : List α) × Pat ([] : List β)) × LHS (forall (a : α) (b : β), Pat [a] × Pat [b]) × LHS (forall (a₁ a₂ : α) (as : List α) (b₁ b₂ : β) (bs : List β), Pat (a₁::a₂::as) × Pat (b₁::b₂::bs)) × LHS (forall (as : List α) (bs : List β), Pat as × Pat bs) := arbitrary _ -- set_option trace.Meta.EqnCompiler.match true -- set_option trace.Meta.EqnCompiler.matchDebug true #eval test `ex3 2 `elimTest3 #print elimTest3 def ex4 (α : Type u) (n : Nat) (xs : Vec α n) : LHS (Pat (inaccessible 0) × Pat (Vec.nil : Vec α 0)) × LHS (forall (n : Nat) (xs : Vec α (n+1)), Pat (inaccessible (n+1)) × Pat xs) := arbitrary _ #eval test `ex4 2 `elimTest4 #print elimTest4 def ex5 (α : Type u) (n : Nat) (xs : Vec α n) : LHS (Pat Nat.zero × Pat (Vec.nil : Vec α 0)) × LHS (forall (n : Nat) (xs : Vec α (n+1)), Pat (Nat.succ n) × Pat xs) := arbitrary _ #eval test `ex5 2 `elimTest5 #print elimTest5 def ex6 (α : Type u) (n : Nat) (xs : Vec α n) : LHS (Pat (inaccessible Nat.zero) × Pat (Vec.nil : Vec α 0)) × LHS (forall (N : Nat) (XS : Vec α N), Pat (inaccessible N) × Pat XS) := arbitrary _ set_option trace.Meta.Match.match true set_option trace.Meta.Match.debug true #eval test `ex6 2 `elimTest6 #print elimTest6 def ex7 (α : Type u) (n : Nat) (xs : Vec α n) : LHS (forall (a : α), Pat (inaccessible 1) × Pat (Vec.cons a Vec.nil)) × LHS (forall (N : Nat) (XS : Vec α N), Pat (inaccessible N) × Pat XS) := arbitrary _ #eval test `ex7 2 `elimTest7 #check elimTest7 def isSizeOne {n : Nat} (xs : Vec Nat n) : Bool := elimTest7 _ (fun _ _ => Bool) n xs (fun _ => true) (fun _ _ => false) #eval isSizeOne Vec.nil #eval isSizeOne (Vec.cons 1 Vec.nil) #eval isSizeOne (Vec.cons 2 (Vec.cons 1 Vec.nil)) def singleton? {n : Nat} (xs : Vec Nat n) : Option Nat := elimTest7 _ (fun _ _ => Option Nat) n xs (fun a => some a) (fun _ _ => none) #eval singleton? Vec.nil #eval singleton? (Vec.cons 10 Vec.nil) #eval singleton? (Vec.cons 20 (Vec.cons 10 Vec.nil)) def ex8 (α : Type u) (n : Nat) (xs : Vec α n) : LHS (forall (a b : α), Pat (inaccessible 2) × Pat (Vec.cons a (Vec.cons b Vec.nil))) × LHS (forall (N : Nat) (XS : Vec α N), Pat (inaccessible N) × Pat XS) := arbitrary _ #eval test `ex8 2 `elimTest8 #print elimTest8 def pair? {n : Nat} (xs : Vec Nat n) : Option (Nat × Nat) := elimTest8 _ (fun _ _ => Option (Nat × Nat)) n xs (fun a b => some (a, b)) (fun _ _ => none) #eval pair? Vec.nil #eval pair? (Vec.cons 10 Vec.nil) #eval pair? (Vec.cons 20 (Vec.cons 10 Vec.nil)) inductive Op : Nat → Nat → Type | mk : ∀ n, Op n n structure Node : Type := (id₁ id₂ : Nat) (o : Op id₁ id₂) def ex9 (xs : List Node) : LHS (forall (h : Node) (t : List Node), Pat (h :: Node.mk 1 1 (Op.mk 1) :: t)) × LHS (forall (ys : List Node), Pat ys) := arbitrary _ #eval test `ex9 1 `elimTest9 #print elimTest9 def f (xs : List Node) : Bool := elimTest9 (fun _ => Bool) xs (fun _ _ => true) (fun _ => false) #eval check (f [] == false) #eval check (f [⟨0, 0, Op.mk 0⟩] == false) #eval check (f [⟨0, 0, Op.mk 0⟩, ⟨1, 1, Op.mk 1⟩]) #eval check (f [⟨0, 0, Op.mk 0⟩, ⟨2, 2, Op.mk 2⟩] == false) inductive Foo : Bool → Prop | bar : Foo false | baz : Foo false def ex10 (x : Bool) (y : Foo x) : LHS (Pat (inaccessible false) × Pat Foo.bar) × LHS (forall (x : Bool) (y : Foo x), Pat (inaccessible x) × Pat y) := arbitrary _ #eval test `ex10 2 `elimTest10 true def ex11 (xs : List Node) : LHS (forall (h : Node) (t : List Node), Pat (h :: Node.mk 1 1 (Op.mk 1) :: t)) × LHS (Pat ([] : List Node)) := arbitrary _ #eval testFailure `ex11 1 `elimTest11 -- should produce error message def ex12 (x y z : Bool) : LHS (forall (x y : Bool), Pat x × Pat y × Pat true) × LHS (forall (x z : Bool), Pat false × Pat true × Pat z) × LHS (forall (y z : Bool), Pat true × Pat false × Pat z) := arbitrary _ #eval testFailure `ex12 3 `elimTest12 -- should produce error message def ex13 (xs : List Node) : LHS (forall (h : Node) (t : List Node), Pat (h :: Node.mk 1 1 (Op.mk 1) :: t)) × LHS (forall (ys : List Node), Pat ys) × LHS (forall (ys : List Node), Pat ys) := arbitrary _ #eval testFailure `ex13 1 `elimTest13 -- should produce error message def ex14 (x y : Nat) : LHS (Pat (val 1) × Pat (val 2)) × LHS (Pat (val 2) × Pat (val 3)) × LHS (forall (x y : Nat), Pat x × Pat y) := arbitrary _ set_option trace.Meta.Match true #eval test `ex14 2 `elimTest14 #print elimTest14 def h2 (x y : Nat) : Nat := elimTest14 (fun _ _ => Nat) x y (fun _ => 0) (fun _ => 1) (fun x y => x + y) #eval check (h2 1 2 == 0) #eval check (h2 1 4 == 5) #eval check (h2 2 3 == 1) #eval check (h2 2 4 == 6) #eval check (h2 3 4 == 7) def ex15 (xs : Array (List Nat)) : LHS (forall (a : Nat), Pat (ArrayLit1 [a])) × LHS (forall (a b : Nat), Pat (ArrayLit2 [a] [b])) × LHS (forall (ys : Array (List Nat)), Pat ys) := arbitrary _ #eval test `ex15 1 `elimTest15 #check elimTest15 def h3 (xs : Array (List Nat)) : Nat := elimTest15 (fun _ => Nat) xs (fun a => a + 1) (fun a b => a + b) (fun ys => ys.size) #eval check (h3 #[[1]] == 2) #eval check (h3 #[[3], [2]] == 5) #eval check (h3 #[[1, 2]] == 1) #eval check (h3 #[[1, 2], [2, 3], [3]] == 3) def ex16 (xs : List Nat) : LHS (forall (a : Nat) (xs : List Nat) (b : Nat) (as : List Nat), Pat (a :: As xs (b :: as))) × LHS (forall (a : Nat), Pat ([a])) × LHS (Pat ([] : List Nat)) := arbitrary _ #eval test `ex16 1 `elimTest16 #check elimTest16 #print elimTest16 def h4 (xs : List Nat) : List Nat := elimTest16 (fun _ => List Nat) xs (fun a xs b ys => xs) (fun a => []) (fun _ => [1]) #eval check (h4 [1, 2, 3] == [2, 3]) #eval check (h4 [1] == []) #eval check (h4 [] == [1])
1aa1242f1917a3ed56092af6634c2dfa1b2f7e98
0ce335c3cee4b6a212935fdfd1a5270985454648
/src/algebra/big_operators.lean
6f6b34d0fdc6ad5f6137fddb6082d3bcaf1a5d7a
[ "Apache-2.0" ]
permissive
yashen32768/mathlib
191f6113ccd0ef74091c3f5951ae84c0aa85516f
f54463254784b400da2e33dfa58f94775e3de845
refs/heads/master
1,598,060,530,541
1,571,523,082,000
1,571,523,082,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
33,614
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 Some big operators for lists and finite sets. -/ import tactic.tauto data.list.basic data.finset data.nat.enat import algebra.group algebra.ordered_group algebra.group_power universes u v w variables {α : Type u} {β : Type v} {γ : Type w} theorem directed.finset_le {r : α → α → Prop} [is_trans α r] {ι} (hι : nonempty ι) {f : ι → α} (D : directed r f) (s : finset ι) : ∃ z, ∀ i ∈ s, r (f i) (f z) := show ∃ z, ∀ i ∈ s.1, r (f i) (f z), from multiset.induction_on s.1 (let ⟨z⟩ := hι in ⟨z, λ _, false.elim⟩) $ λ i s ⟨j, H⟩, let ⟨k, h₁, h₂⟩ := D i j in ⟨k, λ a h, or.cases_on (multiset.mem_cons.1 h) (λ h, h.symm ▸ h₁) (λ h, trans (H _ h) h₂)⟩ theorem finset.exists_le {α : Type u} [nonempty α] [directed_order α] (s : finset α) : ∃ M, ∀ i ∈ s, i ≤ M := directed.finset_le (by apply_instance) directed_order.directed s namespace finset variables {s s₁ s₂ : finset α} {a : α} {f g : α → β} /-- `prod s f` is the product of `f x` as `x` ranges over the elements of the finite set `s`. -/ @[to_additive] protected def prod [comm_monoid β] (s : finset α) (f : α → β) : β := (s.1.map f).prod @[to_additive] theorem prod_eq_fold [comm_monoid β] (s : finset α) (f : α → β) : s.prod f = s.fold (*) 1 f := rfl section comm_monoid variables [comm_monoid β] @[simp, to_additive] lemma prod_empty {α : Type u} {f : α → β} : (∅:finset α).prod f = 1 := rfl @[simp, to_additive] lemma prod_insert [decidable_eq α] : a ∉ s → (insert a s).prod f = f a * s.prod f := fold_insert @[simp, to_additive] lemma prod_singleton : (singleton a).prod f = f a := eq.trans fold_singleton $ mul_one _ @[simp] lemma prod_const_one : s.prod (λx, (1 : β)) = 1 := by simp only [finset.prod, multiset.map_const, multiset.prod_repeat, one_pow] @[simp] lemma sum_const_zero {β} {s : finset α} [add_comm_monoid β] : s.sum (λx, (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) → (s.image g).prod f = s.prod (λx, f (g x)) := fold_image @[simp, to_additive] lemma prod_map (s : finset α) (e : α ↪ γ) (f : γ → β) : (s.map e).prod f = s.prod (λa, f (e a)) := 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 α] : (s₁ ∪ s₂).prod f * (s₁ ∩ s₂).prod f = s₁.prod f * s₂.prod f := fold_union_inter @[to_additive] lemma prod_union [decidable_eq α] (h : disjoint s₁ s₂) : (s₁ ∪ s₂).prod f = s₁.prod f * s₂.prod f := by rw [←prod_union_inter, (disjoint_iff_inter_eq_empty.mp h)]; exact (mul_one _).symm @[to_additive] lemma prod_sdiff [decidable_eq α] (h : s₁ ⊆ s₂) : (s₂ \ s₁).prod f * s₁.prod f = s₂.prod f := by rw [←prod_union sdiff_disjoint, sdiff_union_of_subset h] @[to_additive] lemma prod_bind [decidable_eq α] {s : finset γ} {t : γ → finset α} : (∀x∈s, ∀y∈s, x ≠ y → disjoint (t x) (t y)) → (s.bind t).prod f = s.prod (λx, (t x).prod f) := by haveI := classical.dec_eq γ; exact finset.induction_on s (λ _, by simp only [bind_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.bind s t), from (disjoint_bind_right _ _ _).mpr this, by simp only [bind_insert, prod_insert hxs, prod_union this, ih hd']) @[to_additive] lemma prod_product {s : finset γ} {t : finset α} {f : γ×α → β} : (s.product t).prod f = s.prod (λx, t.prod $ λy, f (x, y)) := begin haveI := classical.dec_eq α, haveI := classical.dec_eq γ, rw [product_eq_bind, prod_bind], { congr, funext, exact prod_image (λ _ _ _ _ H, (prod.mk.inj H).2) }, simp only [disjoint_iff_ne, mem_image], rintros _ _ _ _ h ⟨_, _⟩ ⟨_, _, ⟨_, _⟩⟩ ⟨_, _⟩ ⟨_, _, ⟨_, _⟩⟩ _, apply h, cc end @[to_additive] lemma prod_sigma {σ : α → Type*} {s : finset α} {t : Πa, finset (σ a)} {f : sigma σ → β} : (s.sigma t).prod f = s.prod (λa, (t a).prod $ λs, f ⟨a, s⟩) := by haveI := classical.dec_eq α; haveI := (λ a, classical.dec_eq (σ a)); exact calc (s.sigma t).prod f = (s.bind (λa, (t a).image (λs, sigma.mk a s))).prod f : by rw sigma_eq_bind ... = s.prod (λa, ((t a).image (λs, sigma.mk a s)).prod f) : prod_bind $ assume a₁ ha a₂ ha₂ h, by simp only [disjoint_iff_ne, mem_image]; rintro ⟨_, _⟩ ⟨_, _, _⟩ ⟨_, _⟩ ⟨_, _, _⟩ ⟨_, _⟩; apply h; cc ... = (s.prod $ λa, (t a).prod $ λs, f ⟨a, s⟩) : prod_congr rfl $ λ _ _, prod_image $ λ _ _ _ _ _, by cc @[to_additive] lemma prod_image' [decidable_eq α] {s : finset γ} {g : γ → α} (h : γ → β) (eq : ∀c∈s, f (g c) = (s.filter (λc', g c' = g c)).prod h) : (s.image g).prod f = s.prod h := begin letI := classical.dec_eq γ, rw [← image_bind_filter_eq s g] {occs := occurrences.pos [2]}, rw [finset.prod_bind], { refine finset.prod_congr rfl (assume a ha, _), rcases finset.mem_image.1 ha with ⟨b, hb, rfl⟩, exact eq b hb }, assume a₀ _ a₁ _ ne, refine (disjoint_iff_ne.2 _), assume c₀ h₀ c₁ h₁, rcases mem_filter.1 h₀ with ⟨h₀, rfl⟩, rcases mem_filter.1 h₁ with ⟨h₁, rfl⟩, exact mt (congr_arg g) ne end @[to_additive] lemma prod_mul_distrib : s.prod (λx, f x * g x) = s.prod f * s.prod g := eq.trans (by rw one_mul; refl) fold_op_distrib @[to_additive] lemma prod_comm [decidable_eq γ] {s : finset γ} {t : finset α} {f : γ → α → β} : s.prod (λx, t.prod $ f x) = t.prod (λy, s.prod $ λx, f x y) := finset.induction_on s (by simp only [prod_empty, prod_const_one]) $ λ _ _ H ih, by simp only [prod_insert H, prod_mul_distrib, ih] lemma prod_hom [comm_monoid γ] (g : β → γ) [is_monoid_hom g] : s.prod (λx, g (f x)) = g (s.prod f) := eq.trans (by rw is_monoid_hom.map_one g; refl) (fold_hom $ is_monoid_hom.map_mul g) @[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 (s.prod f) (s.prod g) := begin letI := classical.dec_eq α, refine finset.induction_on s h₁ (assume a s has ih, _), rw [prod_insert has, prod_insert has], exact h₂ a (s.prod f) (s.prod g) ih, end @[to_additive] lemma prod_subset (h : s₁ ⊆ s₂) (hf : ∀x∈s₂, x ∉ s₁ → f x = 1) : s₁.prod f = s₂.prod f := by haveI := classical.dec_eq α; exact have (s₂ \ s₁).prod f = (s₂ \ s₁).prod (λx, 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 (p : α → Prop) [decidable_pred p] (f : α → β) : (s.filter p).prod f = s.prod (λa, if p a then f a else 1) := calc (s.filter p).prod f = (s.filter p).prod (λa, if p a then f a else 1) : prod_congr rfl (assume a h, by rw [if_pos (mem_filter.1 h).2]) ... = s.prod (λa, if p a then f a else 1) : begin refine prod_subset (filter_subset s) (assume x hs h, _), rw [mem_filter, not_and] at h, exact if_neg (h hs) end @[to_additive] lemma prod_eq_single {s : finset α} {f : α → β} (a : α) (h₀ : ∀b∈s, b ≠ a → f b = 1) (h₁ : a ∉ s → f a = 1) : s.prod f = f a := by haveI := classical.dec_eq α; from classical.by_cases (assume : a ∈ s, calc s.prod f = ({a} : finset α).prod f : begin refine (prod_subset _ _).symm, { intros _ H, rwa mem_singleton.1 H }, { simpa only [mem_singleton] } end ... = f a : prod_singleton) (assume : a ∉ s, (prod_congr rfl $ λ b hb, h₀ b hb $ by rintro rfl; cc).trans $ prod_const_one.trans (h₁ this).symm) @[simp, to_additive] lemma prod_ite [decidable_eq α] (s : finset α) (a : α) (b : β) : s.prod (λ x, (ite (a = x) b 1)) = ite (a ∈ s) b 1 := begin rw ←finset.prod_filter, split_ifs; simp only [filter_eq, if_true, if_false, h, prod_empty, prod_singleton, insert_empty_eq_singleton], end @[to_additive] lemma prod_attach {f : α → β} : s.attach.prod (λx, f x.val) = s.prod f := by haveI := classical.dec_eq α; exact calc s.attach.prod (λx, f x.val) = ((s.attach).image subtype.val).prod f : by rw [prod_image]; exact assume x _ y _, subtype.eq ... = _ : by rw [attach_image_val] @[to_additive] 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) : s.prod f = t.prod g := by haveI := classical.prop_decidable; exact calc s.prod f = s.attach.prod (λx, f x.val) : prod_attach.symm ... = s.attach.prod (λx, g (i x.1 x.2)) : prod_congr rfl $ assume x hx, h _ _ ... = (s.attach.image $ λx:{x // x ∈ s}, i x.1 x.2).prod g : (prod_image $ assume (a₁:{x // x ∈ s}) _ a₂ _ eq, subtype.eq $ i_inj a₁.1 a₂.1 a₁.2 a₂.2 eq).symm ... = t.prod g : prod_subset (by simp only [subset_iff, mem_image, mem_attach]; rintro _ ⟨⟨_, _⟩, _, rfl⟩; solve_by_elim) (assume b hb hb1, false.elim $ hb1 $ by rcases i_surj b hb with ⟨a, ha, rfl⟩; exact mem_image.2 ⟨⟨_, _⟩, mem_attach _ _, rfl⟩) @[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) (hi₂ : ∀a₁ a₂ h₁₁ h₁₂ h₂₁ h₂₂, i a₁ h₁₁ h₁₂ = i a₂ h₂₁ h₂₂ → a₁ = a₂) (hi₃ : ∀b∈t, g b ≠ 1 → ∃a h₁ h₂, b = i a h₁ h₂) (h : ∀a h₁ h₂, f a = g (i a h₁ h₂)) : s.prod f = t.prod g := by haveI := classical.prop_decidable; exact calc s.prod f = (s.filter $ λx, f x ≠ 1).prod f : (prod_subset (filter_subset _) $ by simp only [not_imp_comm, mem_filter]; exact λ _, and.intro).symm ... = (t.filter $ λx, g x ≠ 1).prod g : 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₂₂, hi₂ a₁ a₂ _ _ _ _) (assume b hb, (mem_filter.mp hb).elim $ λh₁ h₂, let ⟨a, ha₁, ha₂, eq⟩ := hi₃ b h₁ h₂ in ⟨a, mem_filter.mpr ⟨ha₁, ha₂⟩, eq⟩) ... = t.prod g : (prod_subset (filter_subset _) $ by simp only [not_imp_comm, mem_filter]; exact λ _, and.intro) @[to_additive] lemma exists_ne_one_of_prod_ne_one : s.prod f ≠ 1 → ∃a∈s, f a ≠ 1 := by haveI := classical.dec_eq α; exact finset.induction_on s (λ H, (H rfl).elim) (assume a s has ih h, classical.by_cases (assume ha : f a = 1, let ⟨a, ha, hfa⟩ := ih (by rwa [prod_insert has, ha, one_mul] at h) in ⟨a, mem_insert_of_mem ha, hfa⟩) (assume hna : f a ≠ 1, ⟨a, mem_insert_self _ _, hna⟩)) @[to_additive] lemma prod_range_succ (f : ℕ → β) (n : ℕ) : (range (nat.succ n)).prod f = f n * (range n).prod f := by rw [range_succ, prod_insert not_mem_range_self] lemma prod_range_succ' (f : ℕ → β) : ∀ n : ℕ, (range (nat.succ n)).prod f = (range n).prod (f ∘ nat.succ) * f 0 | 0 := (prod_range_succ _ _).trans $ mul_comm _ _ | (n + 1) := by rw [prod_range_succ (λ m, f (nat.succ m)), mul_assoc, ← prod_range_succ']; exact prod_range_succ _ _ lemma sum_Ico_add {δ : Type*} [add_comm_monoid δ] (f : ℕ → δ) (m n k : ℕ) : (Ico m n).sum (λ l, f (k + l)) = (Ico (m + k) (n + k)).sum f := Ico.image_add m n k ▸ eq.symm $ sum_image $ λ x hx y hy h, nat.add_left_cancel h @[to_additive] lemma prod_Ico_add (f : ℕ → β) (m n k : ℕ) : (Ico m n).prod (λ l, f (k + l)) = (Ico (m + k) (n + k)).prod f := Ico.image_add m n k ▸ eq.symm $ prod_image $ λ x hx y hy h, nat.add_left_cancel h @[to_additive] lemma prod_Ico_consecutive (f : ℕ → β) {m n k : ℕ} (hmn : m ≤ n) (hnk : n ≤ k) : (Ico m n).prod f * (Ico n k).prod f = (Ico m k).prod f := Ico.union_consecutive hmn hnk ▸ eq.symm $ prod_union $ Ico.disjoint_consecutive m n k @[to_additive] lemma prod_range_mul_prod_Ico (f : ℕ → β) {m n : ℕ} (h : m ≤ n) : (range m).prod f * (Ico m n).prod f = (range n).prod f := Ico.zero_bot m ▸ Ico.zero_bot n ▸ prod_Ico_consecutive f (nat.zero_le m) h @[to_additive sum_Ico_eq_add_neg] lemma prod_Ico_eq_div {δ : Type*} [comm_group δ] (f : ℕ → δ) {m n : ℕ} (h : m ≤ n) : (Ico m n).prod f = (range n).prod f * ((range m).prod f)⁻¹ := eq_mul_inv_iff_mul_eq.2 $ by rw [mul_comm]; exact prod_range_mul_prod_Ico f h lemma sum_Ico_eq_sub {δ : Type*} [add_comm_group δ] (f : ℕ → δ) {m n : ℕ} (h : m ≤ n) : (Ico m n).sum f = (range n).sum f - (range m).sum f := sum_Ico_eq_add_neg f h @[to_additive] lemma prod_Ico_eq_prod_range (f : ℕ → β) (m n : ℕ) : (Ico m n).prod f = (range (n - m)).prod (λ l, f (m + l)) := begin by_cases h : m ≤ n, { rw [← Ico.zero_bot, prod_Ico_add, zero_add, nat.sub_add_cancel h] }, { replace h : n ≤ m := le_of_not_ge h, rw [Ico.eq_empty_of_le h, nat.sub_eq_zero_of_le h, range_zero, prod_empty, prod_empty] } end @[to_additive] lemma prod_range_zero (f : ℕ → β) : (range 0).prod f = 1 := by rw [range_zero, prod_empty] lemma prod_range_one (f : ℕ → β) : (range 1).prod f = f 0 := by { rw [range_one], apply @prod_singleton ℕ β 0 f } lemma sum_range_one {δ : Type*} [add_comm_monoid δ] (f : ℕ → δ) : (range 1).sum f = f 0 := by { rw [range_one], apply @sum_singleton ℕ δ 0 f } attribute [to_additive finset.sum_range_one] prod_range_one @[simp] lemma prod_const (b : β) : s.prod (λ a, b) = b ^ s.card := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by rw [prod_insert has, card_insert_of_not_mem has, pow_succ, ih]) lemma prod_pow (s : finset α) (n : ℕ) (f : α → β) : s.prod (λ x, f x ^ n) = s.prod f ^ n := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (by simp [_root_.mul_pow] {contextual := tt}) lemma prod_nat_pow (s : finset α) (n : ℕ) (f : α → ℕ) : s.prod (λ x, f x ^ n) = s.prod f ^ n := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (by simp [nat.mul_pow] {contextual := tt}) @[to_additive] lemma prod_involution {s : finset α} {f : α → β} : ∀ (g : Π a ∈ s, α) (h₁ : ∀ a ha, f a * f (g a ha) = 1) (h₂ : ∀ a ha, f a ≠ 1 → g a ha ≠ a) (h₃ : ∀ a ha, g a ha ∈ s) (h₄ : ∀ a ha, g (g a ha) (h₃ a ha) = a), s.prod f = 1 := by haveI := classical.dec_eq α; haveI := classical.dec_eq β; exact finset.strong_induction_on s (λ s ih g h₁ h₂ h₃ h₄, if hs : s = ∅ then hs.symm ▸ rfl else let ⟨x, hx⟩ := exists_mem_of_ne_empty hs in 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 [← h₄ x hx, ← h₄ y hy]; simp [h], have ih': (erase (erase s x) (g x hx)).prod f = (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 (h₃ x hx))⟩ (λ y hy, g y (hmem y hy)) (λ y hy, h₁ y (hmem y hy)) (λ y hy, h₂ 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 h₄ y (hmem y hy) ▸ by simp [h], by simpa [this] using hy, h₃ y (hmem y hy)⟩⟩) (λ y hy, h₄ 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 (λ h, h.symm ▸ hx1) (λ h, h₁ x hx ▸ h ▸ hx1.symm ▸ (one_mul _).symm))) else by rw [← insert_erase hx, prod_insert (not_mem_erase _ _), ← insert_erase (mem_erase.2 ⟨h₂ x hx hx1, h₃ x hx⟩), prod_insert (not_mem_erase _ _), ih', mul_one, h₁ x hx]) @[to_additive] lemma prod_eq_one {f : α → β} {s : finset α} (h : ∀x∈s, f x = 1) : s.prod f = 1 := calc s.prod f = s.prod (λx, 1) : finset.prod_congr rfl h ... = 1 : finset.prod_const_one end comm_monoid attribute [to_additive] prod_hom lemma sum_smul [add_comm_monoid β] (s : finset α) (n : ℕ) (f : α → β) : s.sum (λ x, add_monoid.smul n (f x)) = add_monoid.smul n (s.sum f) := @prod_pow _ (multiplicative β) _ _ _ _ attribute [to_additive sum_smul] prod_pow @[simp] lemma sum_const [add_comm_monoid β] (b : β) : s.sum (λ a, b) = add_monoid.smul s.card b := @prod_const _ (multiplicative β) _ _ _ attribute [to_additive] prod_const lemma sum_range_succ' [add_comm_monoid β] (f : ℕ → β) : ∀ n : ℕ, (range (nat.succ n)).sum f = (range n).sum (f ∘ nat.succ) + f 0 := @prod_range_succ' (multiplicative β) _ _ attribute [to_additive] prod_range_succ' lemma sum_nat_cast [add_comm_monoid β] [has_one β] (s : finset α) (f : α → ℕ) : ↑(s.sum f) = s.sum (λa, f a : α → β) := (sum_hom _).symm lemma prod_nat_cast [comm_semiring β] (s : finset α) (f : α → ℕ) : ↑(s.prod f) = s.prod (λa, f a : α → β) := (prod_hom _).symm protected lemma sum_nat_coe_enat [decidable_eq α] (s : finset α) (f : α → ℕ) : s.sum (λ x, (f x : enat)) = (s.sum f : ℕ) := begin induction s using finset.induction with a s has ih h, { simp }, { simp [has, ih] } end lemma le_sum_of_subadditive [add_comm_monoid α] [ordered_comm_monoid β] (f : α → β) (h_zero : f 0 = 0) (h_add : ∀x y, f (x + y) ≤ f x + f y) (s : finset γ) (g : γ → α) : f (s.sum g) ≤ s.sum (λc, f (g c)) := begin refine le_trans (multiset.le_sum_of_subadditive f h_zero h_add _) _, rw [multiset.map_map], refl end lemma abs_sum_le_sum_abs [discrete_linear_ordered_field α] {f : β → α} {s : finset β} : abs (s.sum f) ≤ s.sum (λa, abs (f a)) := le_sum_of_subadditive _ abs_zero abs_add s f section comm_group variables [comm_group β] @[simp, to_additive] lemma prod_inv_distrib : s.prod (λx, (f x)⁻¹) = (s.prod f)⁻¹ := prod_hom has_inv.inv end comm_group @[simp] theorem card_sigma {σ : α → Type*} (s : finset α) (t : Π a, finset (σ a)) : card (s.sigma t) = s.sum (λ a, card (t a)) := multiset.card_sigma _ _ lemma card_bind [decidable_eq β] {s : finset α} {t : α → finset β} (h : ∀ x ∈ s, ∀ y ∈ s, x ≠ y → disjoint (t x) (t y)) : (s.bind t).card = s.sum (λ u, card (t u)) := calc (s.bind t).card = (s.bind t).sum (λ _, 1) : by simp ... = s.sum (λ a, (t a).sum (λ _, 1)) : finset.sum_bind h ... = s.sum (λ u, card (t u)) : by simp lemma card_bind_le [decidable_eq β] {s : finset α} {t : α → finset β} : (s.bind t).card ≤ s.sum (λ a, (t a).card) := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (λ a s has ih, calc ((insert a s).bind t).card ≤ (t a).card + (s.bind t).card : by rw bind_insert; exact finset.card_union_le _ _ ... ≤ (insert a s).sum (λ a, card (t a)) : by rw sum_insert has; exact add_le_add_left ih _) theorem card_eq_sum_card_image [decidable_eq β] (f : α → β) (s : finset α) : s.card = (s.image f).sum (λ a, (s.filter (λ x, f x = a)).card) := by letI := classical.dec_eq α; exact calc s.card = ((s.image f).bind (λ a, s.filter (λ x, f x = a))).card : congr_arg _ (finset.ext.2 $ λ x, ⟨λ hs, mem_bind.2 ⟨f x, mem_image_of_mem _ hs, mem_filter.2 ⟨hs, rfl⟩⟩, λ h, let ⟨a, ha₁, ha₂⟩ := mem_bind.1 h in by convert filter_subset s ha₂⟩) ... = (s.image f).sum (λ a, (s.filter (λ x, f x = a)).card) : card_bind (by simp [disjoint_left, finset.ext] {contextual := tt}) lemma gsmul_sum [add_comm_group β] {f : α → β} {s : finset α} (z : ℤ) : gsmul z (s.sum f) = s.sum (λa, gsmul z (f a)) := (finset.sum_hom (gsmul z)).symm end finset namespace finset variables {s s₁ s₂ : finset α} {f g : α → β} {b : β} {a : α} @[simp] lemma sum_sub_distrib [add_comm_group β] : s.sum (λx, f x - g x) = s.sum f - s.sum g := sum_add_distrib.trans $ congr_arg _ sum_neg_distrib section semiring variables [semiring β] lemma sum_mul : s.sum f * b = s.sum (λx, f x * b) := (sum_hom (λx, x * b)).symm lemma mul_sum : b * s.sum f = s.sum (λx, b * f x) := (sum_hom (λx, b * x)).symm @[simp] lemma sum_mul_boole [decidable_eq α] (s : finset α) (f : α → β) (a : α) : s.sum (λ x, (f x * ite (a = x) 1 0)) = ite (a ∈ s) (f a) 0 := begin convert sum_ite s a (f a), funext, split_ifs with h; simp [h], end @[simp] lemma sum_boole_mul [decidable_eq α] (s : finset α) (f : α → β) (a : α) : s.sum (λ x, (ite (a = x) 1 0) * f x) = ite (a ∈ s) (f a) 0 := begin convert sum_ite s a (f a), funext, split_ifs with h; simp [h], end end semiring section comm_semiring variables [decidable_eq α] [comm_semiring β] lemma prod_eq_zero (ha : a ∈ s) (h : f a = 0) : s.prod f = 0 := calc s.prod f = (insert a (erase s a)).prod f : by rw insert_erase ha ... = 0 : by rw [prod_insert (not_mem_erase _ _), h, zero_mul] lemma prod_sum {δ : α → Type*} [∀a, decidable_eq (δ a)] {s : finset α} {t : Πa, finset (δ a)} {f : Πa, δ a → β} : s.prod (λa, (t a).sum (λb, f a b)) = (s.pi t).sum (λp, s.attach.prod (λx, f x.1 (p x.1 x.2))) := begin induction s using finset.induction with a s ha ih, { rw [pi_empty, sum_singleton], refl }, { have h₁ : ∀x ∈ t a, ∀y ∈ t a, ∀h : x ≠ y, disjoint (image (pi.cons s a x) (pi s t)) (image (pi.cons s a y) (pi s t)), { assume x hx y hy h, simp only [disjoint_iff_ne, mem_image], rintros _ ⟨p₂, hp, eq₂⟩ _ ⟨p₃, hp₃, eq₃⟩ eq, have : pi.cons s a x p₂ a (mem_insert_self _ _) = pi.cons s a y p₃ a (mem_insert_self _ _), { rw [eq₂, eq₃, eq] }, rw [pi.cons_same, pi.cons_same] at this, exact h this }, rw [prod_insert ha, pi_insert ha, ih, sum_mul, sum_bind h₁], refine sum_congr rfl (λ b _, _), have h₂ : ∀p₁∈pi s t, ∀p₂∈pi s t, pi.cons s a b p₁ = pi.cons s a b p₂ → p₁ = p₂, from assume p₁ h₁ p₂ h₂ eq, injective_pi_cons ha eq, rw [sum_image h₂, mul_sum], refine sum_congr rfl (λ g _, _), rw [attach_insert, prod_insert, prod_image], { simp only [pi.cons_same], congr', ext ⟨v, hv⟩, congr', exact (pi.cons_ne (by rintro rfl; exact ha hv)).symm }, { exact λ _ _ _ _, subtype.eq ∘ subtype.mk.inj }, { simp only [mem_image], rintro ⟨⟨_, hm⟩, _, rfl⟩, exact ha hm } } end end comm_semiring section integral_domain /- add integral_semi_domain to support nat and ennreal -/ variables [decidable_eq α] [integral_domain β] lemma prod_eq_zero_iff : s.prod f = 0 ↔ (∃a∈s, f a = 0) := finset.induction_on s ⟨not.elim one_ne_zero, λ ⟨_, H, _⟩, H.elim⟩ $ λ a s ha ih, by rw [prod_insert ha, mul_eq_zero_iff_eq_zero_or_eq_zero, bex_def, exists_mem_insert, ih, ← bex_def] end integral_domain section ordered_comm_monoid variables [decidable_eq α] [ordered_comm_monoid β] lemma sum_le_sum : (∀x∈s, f x ≤ g x) → s.sum f ≤ s.sum g := finset.induction_on s (λ _, le_refl _) $ assume a s ha ih h, have f a + s.sum f ≤ g a + s.sum g, from add_le_add' (h _ (mem_insert_self _ _)) (ih $ assume x hx, h _ $ mem_insert_of_mem hx), by simpa only [sum_insert ha] lemma sum_nonneg (h : ∀x∈s, 0 ≤ f x) : 0 ≤ s.sum f := le_trans (by rw [sum_const_zero]) (sum_le_sum h) lemma sum_nonpos (h : ∀x∈s, f x ≤ 0) : s.sum f ≤ 0 := le_trans (sum_le_sum h) (by rw [sum_const_zero]) lemma sum_le_sum_of_subset_of_nonneg (h : s₁ ⊆ s₂) (hf : ∀x∈s₂, x ∉ s₁ → 0 ≤ f x) : s₁.sum f ≤ s₂.sum f := calc s₁.sum f ≤ (s₂ \ s₁).sum f + s₁.sum f : le_add_of_nonneg_left' $ sum_nonneg $ by simpa only [mem_sdiff, and_imp] ... = (s₂ \ s₁ ∪ s₁).sum f : (sum_union sdiff_disjoint).symm ... = s₂.sum f : by rw [sdiff_union_of_subset h] lemma sum_eq_zero_iff_of_nonneg : (∀x∈s, 0 ≤ f x) → (s.sum f = 0 ↔ ∀x∈s, f x = 0) := finset.induction_on s (λ _, ⟨λ _ _, false.elim, λ _, rfl⟩) $ λ a s ha ih H, have ∀ x ∈ s, 0 ≤ f x, from λ _, H _ ∘ mem_insert_of_mem, by rw [sum_insert ha, add_eq_zero_iff' (H _ $ mem_insert_self _ _) (sum_nonneg this), forall_mem_insert, ih this] lemma sum_eq_zero_iff_of_nonpos : (∀x∈s, f x ≤ 0) → (s.sum f = 0 ↔ ∀x∈s, f x = 0) := @sum_eq_zero_iff_of_nonneg _ (order_dual β) _ _ _ _ lemma single_le_sum (hf : ∀x∈s, 0 ≤ f x) {a} (h : a ∈ s) : f a ≤ s.sum f := have (singleton a).sum f ≤ s.sum f, from sum_le_sum_of_subset_of_nonneg (λ x e, (mem_singleton.1 e).symm ▸ h) (λ x h _, hf x h), by rwa sum_singleton at this end ordered_comm_monoid section canonically_ordered_monoid variables [decidable_eq α] [canonically_ordered_monoid β] lemma sum_le_sum_of_subset (h : s₁ ⊆ s₂) : s₁.sum f ≤ s₂.sum f := sum_le_sum_of_subset_of_nonneg h $ assume x h₁ h₂, zero_le _ lemma sum_le_sum_of_ne_zero [@decidable_rel β (≤)] (h : ∀x∈s₁, f x ≠ 0 → x ∈ s₂) : s₁.sum f ≤ s₂.sum f := calc s₁.sum f = (s₁.filter (λx, f x = 0)).sum f + (s₁.filter (λx, f x ≠ 0)).sum f : by rw [←sum_union, filter_union_filter_neg_eq]; exact disjoint_filter (assume _ h n_h, n_h h) ... ≤ s₂.sum f : add_le_of_nonpos_of_le' (sum_nonpos $ by simp only [mem_filter, and_imp]; exact λ _ _, le_of_eq) (sum_le_sum_of_subset $ by simpa only [subset_iff, mem_filter, and_imp]) end canonically_ordered_monoid section linear_ordered_comm_ring variables [decidable_eq α] [linear_ordered_comm_ring β] /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_nonneg {s : finset α} {f : α → β} (h0 : ∀(x ∈ s), 0 ≤ f x) : 0 ≤ s.prod f := begin induction s using finset.induction with a s has ih h, { simp [zero_le_one] }, { simp [has], apply mul_nonneg, apply h0 a (mem_insert_self a s), exact ih (λ x H, h0 x (mem_insert_of_mem H)) } end /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_pos {s : finset α} {f : α → β} (h0 : ∀(x ∈ s), 0 < f x) : 0 < s.prod f := begin induction s using finset.induction with a s has ih h, { simp [zero_lt_one] }, { simp [has], apply mul_pos, apply h0 a (mem_insert_self a s), exact ih (λ x H, h0 x (mem_insert_of_mem H)) } end /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_le_prod {s : finset α} {f g : α → β} (h0 : ∀(x ∈ s), 0 ≤ f x) (h1 : ∀(x ∈ s), f x ≤ g x) : s.prod f ≤ s.prod g := begin induction s using finset.induction with a s has ih h, { simp }, { simp [has], apply mul_le_mul, exact h1 a (mem_insert_self a s), apply ih (λ x H, h0 _ _) (λ x H, h1 _ _); exact (mem_insert_of_mem H), apply prod_nonneg (λ x H, h0 x (mem_insert_of_mem H)), apply le_trans (h0 a (mem_insert_self a s)) (h1 a (mem_insert_self a s)) } end end linear_ordered_comm_ring @[simp] lemma card_pi [decidable_eq α] {δ : α → Type*} (s : finset α) (t : Π a, finset (δ a)) : (s.pi t).card = s.prod (λ a, card (t a)) := multiset.card_pi _ _ theorem card_le_mul_card_image [decidable_eq β] {f : α → β} (s : finset α) (n : ℕ) (hn : ∀ a ∈ s.image f, (s.filter (λ x, f x = a)).card ≤ n) : s.card ≤ n * (s.image f).card := calc s.card = (s.image f).sum (λ a, (s.filter (λ x, f x = a)).card) : card_eq_sum_card_image _ _ ... ≤ (s.image f).sum (λ _, n) : sum_le_sum hn ... = _ : by simp [mul_comm] @[simp] lemma prod_range_id_eq_fact (n : ℕ) : ((range n.succ).erase 0).prod (λ x, x) = nat.fact n := calc ((range n.succ).erase 0).prod (λ x, x) = (range n).prod nat.succ : eq.symm (prod_bij (λ x _, nat.succ x) (λ a h₁, mem_erase.2 ⟨nat.succ_ne_zero _, mem_range.2 $ nat.succ_lt_succ $ by simpa using h₁⟩) (by simp) (λ _ _ _ _, nat.succ_inj) (λ b h, have b.pred.succ = b, from nat.succ_pred_eq_of_pos $ by simp [nat.pos_iff_ne_zero] at *; tauto, ⟨nat.pred b, mem_range.2 $ nat.lt_of_succ_lt_succ (by simp [*] at *), this.symm⟩)) ... = nat.fact n : by induction n; simp [*, range_succ] end finset namespace finset section gauss_sum /-- Gauss' summation formula -/ lemma sum_range_id_mul_two : ∀(n : ℕ), (finset.range n).sum (λi, i) * 2 = n * (n - 1) | 0 := rfl | 1 := rfl | ((n + 1) + 1) := begin rw [sum_range_succ, add_mul, sum_range_id_mul_two (n + 1), mul_comm, two_mul, nat.add_sub_cancel, nat.add_sub_cancel, mul_comm _ n], simp only [add_mul, one_mul, add_comm, add_assoc, add_left_comm] end /-- Gauss' summation formula -/ lemma sum_range_id (n : ℕ) : (finset.range n).sum (λi, i) = (n * (n - 1)) / 2 := by rw [← sum_range_id_mul_two n, nat.mul_div_cancel]; exact dec_trivial end gauss_sum lemma card_eq_sum_ones (s : finset α) : s.card = s.sum (λ _, 1) := by simp end finset section group open list variables [group α] [group β] @[to_additive] theorem is_group_hom.map_prod (f : α → β) [is_group_hom f] (l : list α) : f (prod l) = prod (map f l) := by induction l; simp only [*, is_mul_hom.map_mul f, is_group_hom.map_one f, prod_nil, prod_cons, map] theorem is_group_anti_hom.map_prod (f : α → β) [is_group_anti_hom f] (l : list α) : f (prod l) = prod (map f (reverse l)) := by induction l with hd tl ih; [exact is_group_anti_hom.map_one f, simp only [prod_cons, is_group_anti_hom.map_mul f, ih, reverse_cons, map_append, prod_append, map_singleton, prod_cons, prod_nil, mul_one]] theorem inv_prod : ∀ l : list α, (prod l)⁻¹ = prod (map (λ x, x⁻¹) (reverse l)) := λ l, @is_group_anti_hom.map_prod _ _ _ _ _ inv_is_group_anti_hom l -- TODO there is probably a cleaner proof of this end group section comm_group variables [comm_group α] [comm_group β] (f : α → β) [is_group_hom f] @[to_additive] lemma is_group_hom.map_multiset_prod (m : multiset α) : f m.prod = (m.map f).prod := quotient.induction_on m $ assume l, by simp [is_group_hom.map_prod f l] @[to_additive] lemma is_group_hom.map_finset_prod (g : γ → α) (s : finset γ) : f (s.prod g) = s.prod (f ∘ g) := show f (s.val.map g).prod = (s.val.map (f ∘ g)).prod, by rw [is_group_hom.map_multiset_prod f]; simp end comm_group @[to_additive is_add_group_hom_finset_sum] lemma is_group_hom_finset_prod {α β γ} [group α] [comm_group β] (s : finset γ) (f : γ → α → β) [∀c, is_group_hom (f c)] : is_group_hom (λa, s.prod (λc, f c a)) := { map_mul := assume a b, by simp only [λc, is_mul_hom.map_mul (f c), finset.prod_mul_distrib] } attribute [instance] is_group_hom_finset_prod is_add_group_hom_finset_sum namespace multiset variables [decidable_eq α] @[simp] lemma to_finset_sum_count_eq (s : multiset α) : s.to_finset.sum (λa, s.count a) = s.card := multiset.induction_on s rfl (assume a s ih, calc (to_finset (a :: s)).sum (λx, count x (a :: s)) = (to_finset (a :: s)).sum (λx, (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 : (to_finset s).sum (λx, ite (x = a) 1 0) = (finset.singleton a).sum (λx, ite (x = a) 1 0), { apply (finset.sum_subset _ _).symm, { intros _ H, rwa mem_singleton.1 H }, { exact λ _ _ H, if_neg (mt finset.mem_singleton.2 H) } }, 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 : (to_finset s).sum (λx, ite (x = a) 1 0) = (to_finset s).sum (λx, 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) end multiset
2d43690874464002a159ea149eefe3f1f5fa0f8a
92e157ec9825b5e4597a6d715a8928703bc8e3b2
/src/mywork/hw4.lean
3f6058d21c4dcac845bdb2fcf52db6eb7f6d9429
[]
no_license
exb3dg/cs2120f21
9e566bc508762573c023d3e70f83cb839c199ec8
319b8bf0d63bf96437bf17970ce0198d0b3525cd
refs/heads/main
1,692,970,909,568
1,634,584,540,000
1,634,584,540,000
399,947,025
0
0
null
null
null
null
UTF-8
Lean
false
false
4,827
lean
/- chameleon exb3dg; https://github.com/exb3dg/cs2120f21.git -/ -- 1 example : 0 ≠ 1 := begin -- ¬ (0 = 1) -- (0 = 1) → false assume h, cases h, end -- 2 example : 0 ≠ 0 → 2 = 3 := begin assume h, have f : false := h (eq.refl 0), exact false.elim (f), end -- 3 example : ∀ (P : Prop), P → ¬¬P := begin assume P, assume (p : P), -- ¬¬P -- ¬P → false -- (P → false) → false assume h, have f := h p, exact f, end -- We might need classical (vs constructive) reasoning #check classical.em open classical #check em /- axiom em : ∀ (p : Prop), p ∨ ¬p This is the famous and historically controversial "law" (now axiom) of the excluded middle. It's is a key to proving many intuitive theorems in logic and mathematics. But it also leads to giving up on having evidence *why* something is either true or not true, in that you no longer need a proof of either P or of ¬P to have a proof of P ∨ ¬P. -/ -- 4 theorem neg_elim : ∀ (P : Prop), ¬¬P → P := begin assume P, assume h, have pornp := classical.em P, cases pornp with p pn, assumption, contradiction, end -- 5 theorem demorgan_1 : ∀ (P Q : Prop), ¬ (P ∧ Q) ↔ ¬ P ∨ ¬ Q := begin assume P Q, apply iff.intro _ _, assume npandnq, have pornp := classical.em P, apply or.elim (or.swap pornp), assume np, have qornq := classical.em Q, apply or.elim (or.swap qornq), assume nq, apply or.intro_right, exact nq, assume q, apply or.intro_left, assume p, have f := np p, exact f, assume p, apply or.intro_right, assume q, --***incomplete*** end -- 6 theorem demorgan_2 : ∀ (P Q : Prop), ¬ (P ∨ Q) → ¬P ∧ ¬Q := begin assume P, assume Q, have qornq := classical.em Q, cases qornq with q nq, have pornp := classical.em P, cases pornp with p np, --***incomplete*** end -- 7 theorem disappearing_opposite : ∀ (P Q : Prop), P ∨ ¬P ∧ Q ↔ P ∨ Q := begin assume P Q, apply iff.intro _ _, have pornp := classical.em P, have p : P := or.intro_right pornp, cases pornp with p np, have qornq := classical.em Q, --cases qornq with q nq, apply or.elim qornq, assume q, have pornpandq : P ∨ ¬P ∧ Q := and.intro (or.intro p np) q, --***incomplete*** end -- 8 theorem distrib_and_or : ∀ (P Q R: Prop), (P ∨ Q) ∧ (P ∨ R) ↔ P ∨ (Q ∧ R) := begin assume P Q R, apply iff.intro _ _, have pornp := classical.em P, cases pornp with p np, have qornq := classical.em Q, cases qornq with q nq, have rornr := classical.em R, cases rornr with r nr, --apply or.intro p q, --have porq : P ∨ Q := ?, --***incomplete*** end -- remember or is right associative -- you need this to know what the lefts and rights are -- 9 theorem distrib_and_or_foil : ∀ (P Q R S : Prop), (P ∨ Q) ∧ (R ∨ S) ↔ (P ∧ R) ∨ (P ∧ S) ∨ (Q ∧ R) ∨ (Q ∧ S) := begin intros P Q R S, apply iff.intro _ _, intros h, apply and.elim h, assume pOq rOs, cases pOq, exact p q, cases rOs with r s, have pAr : P ∧ R := and.intro p r, have pAs : P ∧ S := and.intro p s, --apply or.elim pOq, --assume p, --apply or.elim pOq, --apply or.elim rOs, --assume r, --apply or.intro_left _ _, --apply and.intro p r, --assume s, --apply or.intro_left _ _, --have pOq : P ∨ Q := and.elim_left h, --have p : P := or.assoc pOq, /- have pornp := classical.em P, cases pornp with p np, have qornq := classical.em Q, cases qornq with q nq, have rornr := classical.em R, cases rornr with r nr, have sorns := classical.em S, cases sorns with s ns, have porq : P ∨ Q := or.intro p q, have rors : R ∨ S := or.intro r s, -/ --***incomplete*** end /- 10 Formally state and prove the proposition that not every natural number is equal to zero. -/ lemma not_all_nats_are_zero : ¬ (∀ n : ℕ, n = 0) := begin assume n, contradiction, end -- 11. equivalence of P→Q and (¬P∨Q) example : ∀ (P Q : Prop), (P → Q) ↔ (¬P ∨ Q) := begin assume P Q, apply iff.intro _ _, assume pimq, sorry, assume p, sorry, end -- 12 example : ∀ (P Q : Prop), (P → Q) → (¬ Q → ¬ P) := begin assume (P Q : Prop), assume pimq, assume nq, assume p, sorry, end -- 13 example : ∀ (P Q : Prop), ( ¬P → ¬Q) → (Q → P) := begin assume P Q, assume npimnq, assume q, sorry, end example : ∀ (P Q : Prop), ( ¬P → ¬Q) → (Q → P) := begin assume P Q h, cases (em P) with p np, assume q, assumption, assume q, have nq := h np, contradiction, end
3e67e2dac44908080cdf0dd3886ca2ea2ca92046
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/topology/uniform_space/separation.lean
c531658045213d23516e39cd3d74550ce364a0fa
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
21,551
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Patrick Massot -/ import topology.uniform_space.basic import tactic.apply_fun /-! # Hausdorff properties of uniform spaces. Separation quotient. This file studies uniform spaces whose underlying topological spaces are separated (also known as Hausdorff or T₂). This turns out to be equivalent to asking that the intersection of all entourages is the diagonal only. This condition actually implies the stronger separation property that the space is regular (T₃), hence those conditions are equivalent for topologies coming from a uniform structure. More generally, the intersection `𝓢 X` of all entourages of `X`, which has type `set (X × X)` is an equivalence relation on `X`. Points which are equivalent under the relation are basically undistinguishable from the point of view of the uniform structure. For instance any uniformly continuous function will send equivalent points to the same value. The quotient `separation_quotient X` of `X` by `𝓢 X` has a natural uniform structure which is separated, and satisfies a universal property: every uniformly continuous function from `X` to a separated uniform space uniquely factors through `separation_quotient X`. As usual, this allows to turn `separation_quotient` into a functor (but we don't use the category theory library in this file). These notions admit relative versions, one can ask that `s : set X` is separated, this is equivalent to asking that the uniform structure induced on `s` is separated. ## Main definitions * `separation_relation X : set (X × X)`: the separation relation * `separated_space X`: a predicate class asserting that `X` is separated * `is_separated s`: a predicate asserting that `s : set X` is separated * `separation_quotient X`: the maximal separated quotient of `X`. * `separation_quotient.lift f`: factors a map `f : X → Y` through the separation quotient of `X`. * `separation_quotient.map f`: turns a map `f : X → Y` into a map between the separation quotients of `X` and `Y`. ## Main results * `separated_iff_t2`: the equivalence between being separated and being Hausdorff for uniform spaces. * `separation_quotient.uniform_continuous_lift`: factoring a uniformly continuous map through the separation quotient gives a uniformly continuous map. * `separation_quotient.uniform_continuous_map`: maps induced between separation quotients are uniformly continuous. ## Notations Localized in `uniformity`, we have the notation `𝓢 X` for the separation relation on a uniform space `X`, ## Implementation notes The separation setoid `separation_setoid` is not declared as a global instance. It is made a local instance while building the theory of `separation_quotient`. The factored map `separation_quotient.lift f` is defined without imposing any condition on `f`, but returns junk if `f` is not uniformly continuous (constant junk hence it is always uniformly continuous). -/ open filter topological_space set classical function uniform_space open_locale classical topological_space uniformity filter noncomputable theory set_option eqn_compiler.zeta true universes u v w variables {α : Type u} {β : Type v} {γ : Type w} variables [uniform_space α] [uniform_space β] [uniform_space γ] /-! ### Separated uniform spaces -/ /-- The separation relation is the intersection of all entourages. Two points which are related by the separation relation are "indistinguishable" according to the uniform structure. -/ protected def separation_rel (α : Type u) [u : uniform_space α] := ⋂₀ (𝓤 α).sets localized "notation `𝓢` := separation_rel" in uniformity lemma separated_equiv : equivalence (λx y, (x, y) ∈ 𝓢 α) := ⟨assume x, assume s, refl_mem_uniformity, assume x y, assume h (s : set (α×α)) hs, have preimage prod.swap s ∈ 𝓤 α, from symm_le_uniformity hs, h _ this, assume x y z (hxy : (x, y) ∈ 𝓢 α) (hyz : (y, z) ∈ 𝓢 α) s (hs : s ∈ 𝓤 α), let ⟨t, ht, (h_ts : comp_rel t t ⊆ s)⟩ := comp_mem_uniformity_sets hs in h_ts $ show (x, z) ∈ comp_rel t t, from ⟨y, hxy t ht, hyz t ht⟩⟩ /-- A uniform space is separated if its separation relation is trivial (each point is related only to itself). -/ @[class] def separated_space (α : Type u) [uniform_space α] := 𝓢 α = id_rel theorem separated_def {α : Type u} [uniform_space α] : separated_space α ↔ ∀ x y, (∀ r ∈ 𝓤 α, (x, y) ∈ r) → x = y := by simp [separated_space, id_rel_subset.2 separated_equiv.1, subset.antisymm_iff]; simp [subset_def, separation_rel] theorem separated_def' {α : Type u} [uniform_space α] : separated_space α ↔ ∀ x y, x ≠ y → ∃ r ∈ 𝓤 α, (x, y) ∉ r := separated_def.trans $ forall_congr $ λ x, forall_congr $ λ y, by rw ← not_imp_not; simp [classical.not_forall] lemma id_rel_sub_separation_relation (α : Type*) [uniform_space α] : id_rel ⊆ 𝓢 α := begin unfold separation_rel, rw id_rel_subset, intros x, suffices : ∀ t ∈ 𝓤 α, (x, x) ∈ t, by simpa only [refl_mem_uniformity], exact λ t, refl_mem_uniformity, end lemma separation_rel_comap {f : α → β} (h : ‹uniform_space α› = uniform_space.comap f ‹uniform_space β›) : 𝓢 α = (prod.map f f) ⁻¹' 𝓢 β := begin dsimp [separation_rel], rw [uniformity_comap h, (filter.comap_has_basis (prod.map f f) (𝓤 β)).sInter_sets, ← preimage_bInter, sInter_eq_bInter], refl, end protected lemma filter.has_basis.separation_rel {ι : Type*} {p : ι → Prop} {s : ι → set (α × α)} (h : has_basis (𝓤 α) p s) : 𝓢 α = ⋂ i ∈ set_of p, s i := by { unfold separation_rel, rw h.sInter_sets } lemma separation_rel_eq_inter_closure : 𝓢 α = ⋂₀ (closure '' (𝓤 α).sets) := by simpa [uniformity_has_basis_closure.separation_rel] lemma is_closed_separation_rel : is_closed (𝓢 α) := begin rw separation_rel_eq_inter_closure, apply is_closed_sInter, rintros _ ⟨t, t_in, rfl⟩, exact is_closed_closure, end lemma separated_iff_t2 : separated_space α ↔ t2_space α := begin classical, split ; intro h, { rw [t2_iff_is_closed_diagonal, ← show 𝓢 α = diagonal α, from h], exact is_closed_separation_rel }, { rw separated_def', intros x y hxy, have : 𝓝 x ⊓ 𝓝 y = ⊥, { rw t2_iff_nhds at h, by_contra H, exact hxy (h H) }, rcases inf_eq_bot_iff.mp this with ⟨U, V, U_in, V_in, H⟩, rcases mem_nhds_iff_symm.mp U_in with ⟨S, S_in, S_symm, S_sub⟩, use [S, S_in], change y ∉ ball x S, intro y_in, have : y ∈ U ∩ V := ⟨S_sub y_in, mem_of_nhds V_in⟩, rwa H at this }, end @[priority 100] -- see Note [lower instance priority] instance separated_regular [separated_space α] : regular_space α := { regular := λs a hs ha, have sᶜ ∈ 𝓝 a, from mem_nhds_sets hs ha, have {p : α × α | p.1 = a → p.2 ∈ sᶜ} ∈ 𝓤 α, from mem_nhds_uniformity_iff_right.mp this, let ⟨d, hd, h⟩ := comp_mem_uniformity_sets this in let e := {y:α| (a, y) ∈ d} in have hae : a ∈ closure e, from subset_closure $ refl_mem_uniformity hd, have set.prod (closure e) (closure e) ⊆ comp_rel d (comp_rel (set.prod e e) d), begin rw [←closure_prod_eq, closure_eq_inter_uniformity], change (⨅d' ∈ 𝓤 α, _) ≤ comp_rel d (comp_rel _ d), exact (infi_le_of_le d $ infi_le_of_le hd $ le_refl _) end, have e_subset : closure e ⊆ sᶜ, from assume a' ha', let ⟨x, (hx : (a, x) ∈ d), y, ⟨hx₁, hx₂⟩, (hy : (y, _) ∈ d)⟩ := @this ⟨a, a'⟩ ⟨hae, ha'⟩ in have (a, a') ∈ comp_rel d d, from ⟨y, hx₂, hy⟩, h this rfl, have closure e ∈ 𝓝 a, from (𝓝 a).sets_of_superset (mem_nhds_left a hd) subset_closure, have 𝓝 a ⊓ 𝓟 (closure e)ᶜ = ⊥, from (@inf_eq_bot_iff_le_compl _ _ _ (𝓟 (closure e)ᶜ) (𝓟 (closure e)) (by simp [principal_univ, union_comm]) (by simp)).mpr (by simp [this]), ⟨(closure e)ᶜ, is_closed_closure, assume x h₁ h₂, @e_subset x h₂ h₁, this⟩, ..@t2_space.t1_space _ _ (separated_iff_t2.mp ‹_›) } /-! ### Separated sets -/ /-- A set `s` in a uniform space `α` is separated if the separation relation `𝓢 α` induces the trivial relation on `s`. -/ def is_separated (s : set α) : Prop := ∀ x y ∈ s, (x, y) ∈ 𝓢 α → x = y lemma is_separated_def (s : set α) : is_separated s ↔ ∀ x y ∈ s, (x, y) ∈ 𝓢 α → x = y := iff.rfl lemma is_separated_def' (s : set α) : is_separated s ↔ (s.prod s) ∩ 𝓢 α ⊆ id_rel := begin rw is_separated_def, split, { rintros h ⟨x, y⟩ ⟨⟨x_in, y_in⟩, H⟩, simp [h x y x_in y_in H] }, { intros h x y x_in y_in xy_in, rw ← mem_id_rel, exact h ⟨mk_mem_prod x_in y_in, xy_in⟩ } end lemma univ_separated_iff : is_separated (univ : set α) ↔ separated_space α := begin simp only [is_separated, mem_univ, true_implies_iff, separated_space], split, { intro h, exact subset.antisymm (λ ⟨x, y⟩ xy_in, h x y xy_in) (id_rel_sub_separation_relation α), }, { intros h x y xy_in, rwa h at xy_in }, end lemma is_separated_of_separated_space [separated_space α] (s : set α) : is_separated s := begin rw [is_separated, show 𝓢 α = diagonal α, from ‹separated_space α›], tauto, end lemma is_separated_iff_induced {s : set α} : is_separated s ↔ separated_space s := begin change _ ↔ 𝓢 ({x // x ∈ s}) = _, rw [separation_rel_comap rfl, is_separated_def'], split; intro h, { ext ⟨⟨x, x_in⟩, ⟨y, y_in⟩⟩, suffices : (x, y) ∈ 𝓢 α ↔ x = y, by simpa only [mem_id_rel], refine ⟨λ H, h ⟨mk_mem_prod x_in y_in, H⟩, _⟩, rintro rfl, apply id_rel_sub_separation_relation α, rw mem_id_rel }, { -- For legibility purpose, let's have explicit coercion C s : ↥s → α for every α and s : set α let C : Π {β : Type*} (s : set β) (x : s), β := λ _ _, subtype.val, let Δ := diagonal, change _ ⊆ Δ _, change (prod.map (C s) (C s)) ⁻¹' (𝓢 α) = Δ _ at h, rw [inter_comm, ← subtype.image_preimage_coe, image_subset_iff], change (C _) ⁻¹' _ ⊆ (C _) ⁻¹' _, let φ : ↥s × ↥s → (s.prod s) := (λ x : s × s, ⟨(x.1.1, x.2.1), mk_mem_prod x.1.2 x.2.2⟩), have φ_surj : surjective φ := λ ⟨⟨x, y⟩, ⟨x_in, y_in⟩⟩, ⟨(⟨x, x_in⟩, ⟨y, y_in⟩), rfl⟩, have CCCφ: prod.map (C s) (C s) = C (s.prod s) ∘ φ, by ext ; refl, have ΔΔ: (prod.map (C s) (C s)) ⁻¹' (Δ α) = Δ s := set.preimage_coe_coe_diagonal s, apply_fun (image φ) at h, rw [ ← ΔΔ, CCCφ, preimage_comp, preimage_comp, image_preimage_eq φ_surj, image_preimage_eq φ_surj] at h, rw h }, end lemma eq_of_uniformity_inf_nhds_of_is_separated {s : set α} (hs : is_separated s) : ∀ {x y : α}, x ∈ s → y ∈ s → cluster_pt (x, y) (𝓤 α) → x = y := begin intros x y x_in y_in H, have : ∀ V ∈ 𝓤 α, (x, y) ∈ closure V, { intros V V_in, rw mem_closure_iff_cluster_pt, have : 𝓤 α ≤ 𝓟 V, by rwa le_principal_iff, exact H.mono this }, apply hs x y x_in y_in, simpa [separation_rel_eq_inter_closure], end lemma eq_of_uniformity_inf_nhds [separated_space α] : ∀ {x y : α}, cluster_pt (x, y) (𝓤 α) → x = y := begin have : is_separated (univ : set α), { rw univ_separated_iff, assumption }, introv, simpa using eq_of_uniformity_inf_nhds_of_is_separated this, end /-! ### Separation quotient -/ namespace uniform_space /-- The separation relation of a uniform space seen as a setoid. -/ def separation_setoid (α : Type u) [uniform_space α] : setoid α := ⟨λx y, (x, y) ∈ 𝓢 α, separated_equiv⟩ local attribute [instance] separation_setoid instance separation_setoid.uniform_space {α : Type u} [u : uniform_space α] : uniform_space (quotient (separation_setoid α)) := { to_topological_space := u.to_topological_space.coinduced (λx, ⟦x⟧), uniformity := map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) u.uniformity, refl := le_trans (by simp [quotient.exists_rep]) (filter.map_mono refl_le_uniformity), symm := tendsto_map' $ by simp [prod.swap, (∘)]; exact tendsto_map.comp tendsto_swap_uniformity, comp := calc (map (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) u.uniformity).lift' (λs, comp_rel s s) = u.uniformity.lift' ((λs, comp_rel s s) ∘ image (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧))) : map_lift'_eq2 $ monotone_comp_rel monotone_id monotone_id ... ≤ u.uniformity.lift' (image (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) ∘ (λs:set (α×α), comp_rel s (comp_rel s s))) : lift'_mono' $ assume s hs ⟨a, b⟩ ⟨c, ⟨⟨a₁, a₂⟩, ha, a_eq⟩, ⟨⟨b₁, b₂⟩, hb, b_eq⟩⟩, begin simp at a_eq, simp at b_eq, have h : ⟦a₂⟧ = ⟦b₁⟧, { rw [a_eq.right, b_eq.left] }, have h : (a₂, b₁) ∈ 𝓢 α := quotient.exact h, simp [function.comp, set.image, comp_rel, and.comm, and.left_comm, and.assoc], exact ⟨a₁, a_eq.left, b₂, b_eq.right, a₂, ha, b₁, h s hs, hb⟩ end ... = map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) (u.uniformity.lift' (λs:set (α×α), comp_rel s (comp_rel s s))) : by rw [map_lift'_eq]; exact monotone_comp_rel monotone_id (monotone_comp_rel monotone_id monotone_id) ... ≤ map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) u.uniformity : map_mono comp_le_uniformity3, is_open_uniformity := assume s, have ∀a, ⟦a⟧ ∈ s → ({p:α×α | p.1 = a → ⟦p.2⟧ ∈ s} ∈ 𝓤 α ↔ {p:α×α | p.1 ≈ a → ⟦p.2⟧ ∈ s} ∈ 𝓤 α), from assume a ha, ⟨assume h, let ⟨t, ht, hts⟩ := comp_mem_uniformity_sets h in have hts : ∀{a₁ a₂}, (a, a₁) ∈ t → (a₁, a₂) ∈ t → ⟦a₂⟧ ∈ s, from assume a₁ a₂ ha₁ ha₂, @hts (a, a₂) ⟨a₁, ha₁, ha₂⟩ rfl, have ht' : ∀{a₁ a₂}, a₁ ≈ a₂ → (a₁, a₂) ∈ t, from assume a₁ a₂ h, sInter_subset_of_mem ht h, u.uniformity.sets_of_superset ht $ assume ⟨a₁, a₂⟩ h₁ h₂, hts (ht' $ setoid.symm h₂) h₁, assume h, u.uniformity.sets_of_superset h $ by simp {contextual := tt}⟩, begin simp [topological_space.coinduced, u.is_open_uniformity, uniformity, forall_quotient_iff], exact ⟨λh a ha, (this a ha).mp $ h a ha, λh a ha, (this a ha).mpr $ h a ha⟩ end } lemma uniformity_quotient : 𝓤 (quotient (separation_setoid α)) = (𝓤 α).map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) := rfl lemma uniform_continuous_quotient_mk : uniform_continuous (quotient.mk : α → quotient (separation_setoid α)) := le_refl _ lemma uniform_continuous_quotient {f : quotient (separation_setoid α) → β} (hf : uniform_continuous (λx, f ⟦x⟧)) : uniform_continuous f := hf lemma uniform_continuous_quotient_lift {f : α → β} {h : ∀a b, (a, b) ∈ 𝓢 α → f a = f b} (hf : uniform_continuous f) : uniform_continuous (λa, quotient.lift f h a) := uniform_continuous_quotient hf lemma uniform_continuous_quotient_lift₂ {f : α → β → γ} {h : ∀a c b d, (a, b) ∈ 𝓢 α → (c, d) ∈ 𝓢 β → f a c = f b d} (hf : uniform_continuous (λp:α×β, f p.1 p.2)) : uniform_continuous (λp:_×_, quotient.lift₂ f h p.1 p.2) := begin rw [uniform_continuous, uniformity_prod_eq_prod, uniformity_quotient, uniformity_quotient, filter.prod_map_map_eq, filter.tendsto_map'_iff, filter.tendsto_map'_iff], rwa [uniform_continuous, uniformity_prod_eq_prod, filter.tendsto_map'_iff] at hf end lemma comap_quotient_le_uniformity : (𝓤 $ quotient $ separation_setoid α).comap (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) ≤ (𝓤 α) := assume t' ht', let ⟨t, ht, tt_t'⟩ := comp_mem_uniformity_sets ht' in let ⟨s, hs, ss_t⟩ := comp_mem_uniformity_sets ht in ⟨(λp:α×α, (⟦p.1⟧, ⟦p.2⟧)) '' s, (𝓤 α).sets_of_superset hs $ assume x hx, ⟨x, hx, rfl⟩, assume ⟨a₁, a₂⟩ ⟨⟨b₁, b₂⟩, hb, ab_eq⟩, have ⟦b₁⟧ = ⟦a₁⟧ ∧ ⟦b₂⟧ = ⟦a₂⟧, from prod.mk.inj ab_eq, have b₁ ≈ a₁ ∧ b₂ ≈ a₂, from and.imp quotient.exact quotient.exact this, have ab₁ : (a₁, b₁) ∈ t, from (setoid.symm this.left) t ht, have ba₂ : (b₂, a₂) ∈ s, from this.right s hs, tt_t' ⟨b₁, show ((a₁, a₂).1, b₁) ∈ t, from ab₁, ss_t ⟨b₂, show ((b₁, a₂).1, b₂) ∈ s, from hb, ba₂⟩⟩⟩ lemma comap_quotient_eq_uniformity : (𝓤 $ quotient $ separation_setoid α).comap (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) = 𝓤 α := le_antisymm comap_quotient_le_uniformity le_comap_map instance separated_separation : separated_space (quotient (separation_setoid α)) := set.ext $ assume ⟨a, b⟩, quotient.induction_on₂ a b $ assume a b, ⟨assume h, have a ≈ b, from assume s hs, have s ∈ (𝓤 $ quotient $ separation_setoid α).comap (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)), from comap_quotient_le_uniformity hs, let ⟨t, ht, hts⟩ := this in hts begin dsimp [preimage], exact h t ht end, show ⟦a⟧ = ⟦b⟧, from quotient.sound this, assume heq : ⟦a⟧ = ⟦b⟧, assume h hs, heq ▸ refl_mem_uniformity hs⟩ lemma separated_of_uniform_continuous {f : α → β} {x y : α} (H : uniform_continuous f) (h : x ≈ y) : f x ≈ f y := assume _ h', h _ (H h') lemma eq_of_separated_of_uniform_continuous [separated_space β] {f : α → β} {x y : α} (H : uniform_continuous f) (h : x ≈ y) : f x = f y := separated_def.1 (by apply_instance) _ _ $ separated_of_uniform_continuous H h /-- The maximal separated quotient of a uniform space `α`. -/ def separation_quotient (α : Type*) [uniform_space α] := quotient (separation_setoid α) namespace separation_quotient instance : uniform_space (separation_quotient α) := by dunfold separation_quotient ; apply_instance instance : separated_space (separation_quotient α) := by dunfold separation_quotient ; apply_instance instance [inhabited α] : inhabited (separation_quotient α) := by unfold separation_quotient; apply_instance /-- Factoring functions to a separated space through the separation quotient. -/ def lift [separated_space β] (f : α → β) : (separation_quotient α → β) := if h : uniform_continuous f then quotient.lift f (λ x y, eq_of_separated_of_uniform_continuous h) else λ x, f (classical.inhabited_of_nonempty $ (nonempty_quotient_iff $ separation_setoid α).1 ⟨x⟩).default lemma lift_mk [separated_space β] {f : α → β} (h : uniform_continuous f) (a : α) : lift f ⟦a⟧ = f a := by rw [lift, dif_pos h]; refl lemma uniform_continuous_lift [separated_space β] (f : α → β) : uniform_continuous (lift f) := begin by_cases hf : uniform_continuous f, { rw [lift, dif_pos hf], exact uniform_continuous_quotient_lift hf }, { rw [lift, dif_neg hf], exact uniform_continuous_of_const (assume a b, rfl) } end /-- The separation quotient functor acting on functions. -/ def map (f : α → β) : separation_quotient α → separation_quotient β := lift (quotient.mk ∘ f) lemma map_mk {f : α → β} (h : uniform_continuous f) (a : α) : map f ⟦a⟧ = ⟦f a⟧ := by rw [map, lift_mk (uniform_continuous_quotient_mk.comp h)] lemma uniform_continuous_map (f : α → β) : uniform_continuous (map f) := uniform_continuous_lift (quotient.mk ∘ f) lemma map_unique {f : α → β} (hf : uniform_continuous f) {g : separation_quotient α → separation_quotient β} (comm : quotient.mk ∘ f = g ∘ quotient.mk) : map f = g := by ext ⟨a⟩; calc map f ⟦a⟧ = ⟦f a⟧ : map_mk hf a ... = g ⟦a⟧ : congr_fun comm a lemma map_id : map (@id α) = id := map_unique uniform_continuous_id rfl lemma map_comp {f : α → β} {g : β → γ} (hf : uniform_continuous f) (hg : uniform_continuous g) : map g ∘ map f = map (g ∘ f) := (map_unique (hg.comp hf) $ by simp only [(∘), map_mk, hf, hg]).symm end separation_quotient lemma separation_prod {a₁ a₂ : α} {b₁ b₂ : β} : (a₁, b₁) ≈ (a₂, b₂) ↔ a₁ ≈ a₂ ∧ b₁ ≈ b₂ := begin split, { assume h, exact ⟨separated_of_uniform_continuous uniform_continuous_fst h, separated_of_uniform_continuous uniform_continuous_snd h⟩ }, { rintros ⟨eqv_α, eqv_β⟩ r r_in, rw uniformity_prod at r_in, rcases r_in with ⟨t_α, ⟨r_α, r_α_in, h_α⟩, t_β, ⟨r_β, r_β_in, h_β⟩, H⟩, let p_α := λ(p : (α × β) × (α × β)), (p.1.1, p.2.1), let p_β := λ(p : (α × β) × (α × β)), (p.1.2, p.2.2), have key_α : p_α ((a₁, b₁), (a₂, b₂)) ∈ r_α, { simp [p_α, eqv_α r_α r_α_in] }, have key_β : p_β ((a₁, b₁), (a₂, b₂)) ∈ r_β, { simp [p_β, eqv_β r_β r_β_in] }, exact H ⟨h_α key_α, h_β key_β⟩ }, end instance separated.prod [separated_space α] [separated_space β] : separated_space (α × β) := separated_def.2 $ assume x y H, prod.ext (eq_of_separated_of_uniform_continuous uniform_continuous_fst H) (eq_of_separated_of_uniform_continuous uniform_continuous_snd H) end uniform_space
8bd83fb56c7d81029d249d5cb2d0505e1591ae28
a7602958ab456501ff85db8cf5553f7bcab201d7
/Notes/Theorem_Proving_in_Lean/Chapter3/3.2.lean
39b5ee826033fed1185e4077801fee42b25cfc0c
[]
no_license
enlauren/math-logic
081e2e737c8afb28dbb337968df95ead47321ba0
086b6935543d1841f1db92d0e49add1124054c37
refs/heads/master
1,594,506,621,950
1,558,634,976,000
1,558,634,976,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,199
lean
-- 3.2 Working with Propositions as Types constants p q: Prop theorem t1: p → q → p := fun (hp: p), fun (hq: q), hp -- This newly-introduced theorem is the same as the constant we defined -- in the 3.1 notes, however in this case the arguments are of type Prop -- instead of type Type (?). -- Note that in the above, the function/lambda abstractions are -- equivalent to temporary assumptions: theorem t2: p → q → p := assume hp: p, assume hq: q, show p, from hp -- Lean also provides the word "lemma" as an alternate syntax to -- "theorem". Furthermore, "axiom" is interchangeable with "constant". -- It should be noted that `t1` is true for any propositions `p` and -- `q`, so it would be better to define `t1` in such a way that -- represents this quantification. We can do this the short-handed way -- or the long-handed way, or even the more-explicit way. theorem t3 (p q: Prop) (hp: p) (hq: q): p := hp theorem t4: Π (p q: Prop), p → q → p := fun (p q: Prop), fun (hp: p), fun (hq: q), hp theorem t5: ∀ (p q: Prop), p → q → p := fun (p q: Prop), fun (hp: p), fun (hq: q), hp #check t3 #check t4 #check t5 theorem t56 (h: p ∧ q): p := and.left h
77dd1f4a67f0c7c45ccefbb557fa9ee229546fe1
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/runSTBug.lean
18d1b6acdff86d9be9e8fbb6a99462f46c79df1d
[ "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
444
lean
import Lean open Lean def f (xs : List Nat) (delta : Nat) : List Nat := runST (fun ω => visit xs |>.run) where visit {ω} : List Nat → MonadCacheT Nat Nat (ST ω) (List Nat) | [] => [] | a::as => do let b ← checkCache a fun _ => return a + delta return b :: (← visit as) def tst (xs : List Nat) : IO Unit := do IO.println (f xs 10) IO.println (f xs 20) IO.println (f xs 30) #eval tst [1, 2, 3, 1, 2]
a5b4d82bd8da61a1be6b37ad77cb38991839d0c0
e791a827712b9cda7e14eb9861a152725a60f884
/main.lean
417687683f092989cde8762f31f82e1f0b229663
[]
no_license
Shamrock-Frost/FormalComplexAnalysis
29bf1d45f59b22d6553b24fe5b630464f9c2d9fa
3cac79d9b603b1edf7df1bc7e948c74eb86a2cc0
refs/heads/master
1,588,634,495,874
1,554,397,551,000
1,554,397,551,000
179,541,347
0
0
null
null
null
null
UTF-8
Lean
false
false
20,808
lean
import .complex .algebra .macros .sets theorem problem16 : ∀ (a z : ℂ), |z| = 1 → 1 - (complex.conj a)*z ≠ 0 → |z - a|/|1 - (complex.conj a) * z| = 1 := begin intros a z h1' h2, have h1 := eq_one_of_sqrt_eq_one h1', suffices : complex.norm (z - a) = complex.norm (1 - (complex.conj a) * z), { rw div_eq_one_iff_eq, assumption, revert h2, apply mt, intro h2, apply norm_zero_implies_zero, assumption, }, apply congr_arg sqrt, cases z with x y, simp [complex.norm_squared] at h1, cases a with a b, simp [complex.conj], transitivity (x - a)*(x - a) + (y - b)*(y - b), refl, transitivity (1-a*x - b*y)*(1-a*x - b*y) + (-a*y + b*x)*(-a*y + b*x), { rw ← sub_add_eq_sub_sub, rw FOIL, rw (_ : -a * y * (-a * y) = (a*a)*(y*y)), rw (_ : b*x*(b*x) = (b*b)*(x*x)), rw sub_eq_add_neg (1 : ℝ), rw FOIL, rw mul_one, rw mul_one, rw one_mul, rw neg_mul_neg, rw FOIL, rw (_ : a * x * (a * x) = a * a * (x * x)), rw (_ : b * y * (b * y) = b * b * (y * y)), rw add_assoc, rw (_ : (a * a * (x * x) + a * x * (b * y) + b * y * (a * x) + b * b * (y * y)) + (a * a * (y * y) + -a * y * (b * x) + b * x * (-a * y) + b * b * (x * x)) = ((a * a * (x * x) + a * a * (y * y)) + a * x * (b * y) + b * y * (a * x)) + (-a * y * (b * x) + b * x * (-a * y) + (b * b * (x * x) + b * b * (y * y)))), tactic.swap, { repeat { rw add_assoc }, apply congr_arg, repeat { rw ← add_left_comm ((a*a)*(y*y)) }, repeat { apply congr_arg }, repeat { rw add_left_comm ((b*b)*(y*y)) }, repeat { apply congr_arg }, apply add_comm }, rw [← left_distrib (a*a) (x*x) (y*y), ← left_distrib (b*b) (x*x) (y*y)], rw [h1, mul_one, mul_one], rw [add_assoc, add_assoc, add_assoc, add_assoc, add_assoc], repeat { rw ← add_left_comm (a*a) }, rw add_comm _ (b*b), repeat { rw ← add_left_comm (b*b) }, rw [← add_assoc, ← add_assoc], rw [FOIL_neg_square, FOIL_neg_square], transitivity b * b + a * a + (x * x + y*y) + ((-(x * a) + -(x * a)) + (-(y * b) + -(y * b))), { generalize : -(x * a) = u, generalize : -(y * b) = v, ac_refl }, apply congr, { congr, assumption }, rw neg_add, rw mul_comm a x, rw mul_comm b y, generalize hu : -(x * a) = u, generalize hv : -(y * b) = v, rw add_assoc, rw add_assoc, rw add_assoc, rw add_left_comm u v v, transitivity u + (v + (u + (v + 0))), rw add_zero, congr, transitivity a * b * x * y + (a * b * x * y + (-(a * b * x * y) + -(a * b * x * y))), rw [← add_assoc, ← neg_add, add_neg_self], apply congr, { apply congr_arg, ac_refl }, apply congr, { apply congr_arg, ac_refl }, apply congr, { apply congr_arg, tactic.unwrap_neg, ac_refl }, { tactic.unwrap_neg, ac_refl }, ac_refl, ac_refl, ac_refl, rw [mul_left_comm, mul_assoc, ← mul_assoc, neg_mul_neg] }, { rw (_ : 1 = complex.mk 1 0), simp, simp [complex.norm_squared], refl }, end -- a set of complex numbers is a circle if it is a set of points -- a fixed distance from some other point def mk_circle (center : ℂ) (radius : ℝ) := { z : ℂ | |z - center| = radius } def is_circle (S : set ℂ) := ∃ center radius, S = mk_circle center radius lemma shift_sends_circles_to_circles : ∀ r z₀ c, fun.im (λ z, z - c) (mk_circle z₀ r) = mk_circle (z₀ - c) r := begin intros, funext, apply propext, suffices : (∃w, |w - z₀| = r ∧ b = w - c) ↔ |b - (z₀ - c)| = r, exact this, constructor; intro h, { cases h with w h, cases h with hdist hb, rw hb, rw [sub_eq_add_neg _ c, sub_eq_add_neg _ c], rw add_sub_add_right_eq_sub, assumption }, { rw [sub_eq_add_neg, neg_sub, ← add_sub_assoc] at h, existsi b + c, constructor, assumption, rw add_sub_cancel } end noncomputable def center_of_inverted_circle (r : ℝ) (z₀ : ℂ) : ℂ := complex.conj (complex.scalar_mul (1 / (complex.norm_squared z₀ - r * r)) z₀) noncomputable def radius_of_inverted_circle (r : ℝ) (z₀ : ℂ) : ℝ := √(complex.norm_squared (center_of_inverted_circle r z₀) - 1 / (complex.norm_squared z₀ - r * r)) lemma random_inversion_inequality (z₀ : ℂ) (r : ℝ) (h1 : r ≠ |z₀| ) (h2 : 0 < r) : 1 / (complex.norm_squared z₀ - r * r) ≤ complex.norm_squared (complex.conj (complex.scalar_mul (1 / (complex.norm_squared z₀ - r * r)) z₀)) := begin rw (_ : complex.norm_squared (complex.conj (complex.scalar_mul (1 / (complex.norm_squared z₀ - r * r)) z₀)) = complex.norm_squared z₀/(abs(complex.norm_squared z₀ - r*r)*abs(complex.norm_squared z₀ - r*r))), apply le_div_of_mul_le, have h2 : abs (complex.norm_squared z₀ - r * r) > 0, { apply lt_of_le_of_ne, apply abs_nonneg, apply ne.symm, apply mt eq_zero_of_abs_eq_zero, apply mt eq_of_sub_eq_zero, rw ← squared_norm_eq_norm_squared, apply mt (eq_of_nonneg_and_sq_eq _ _), apply ne.symm, assumption, apply complex.norm_nonneg, apply le_of_lt, assumption, }, apply mul_pos h2 h2, rw ← mul_assoc, rw mul_comm (1 / (complex.norm_squared z₀ - r * r)) (abs (complex.norm_squared z₀ - r * r)), rw ← div_eq_mul_one_div, rw abs_div_self_eq_sgn, rw sgn_mul_abs_eq_self, apply sub_le_self, apply mul_self_nonneg, rw ← norm_squared_eq_norm_squared_of_conj, rw norm_squared_of_scale, rw [mul_comm, ← mul_assoc], rw [← div_eq_mul_one_div, ← div_eq_mul_one_div], rw div_div_eq_div_mul, rw abs_mul_abs_eq_self_mul_self, end lemma inverted_radius_eq_iverted_center_implies_center_eq_radius (z₀ : ℂ) (r : ℝ) (r_pos : r > 0) : |center_of_inverted_circle r z₀| = radius_of_inverted_circle r z₀ → |z₀| = r := begin intro h, by_cases h' : |z₀| = r, assumption, have := eq_of_sqrt_eq _ _ h, have := eq_sub_implies_sub_zero _ _ this, have : complex.norm_squared z₀ - r * r = 0, apply classical.by_contradiction, intro h, apply inv_ne_zero h, rw inv_eq_one_div, assumption, have := eq_of_sub_eq_zero this, transitivity √ (r*r), apply congr_arg sqrt this, symmetry, apply sqrt_unique, apply mul_self_nonneg, apply le_of_lt, assumption, refl, apply complex.norm_squared_nonneg, dunfold center_of_inverted_circle, apply sub_nonneg_of_le, apply random_inversion_inequality, apply ne.symm, assumption, assumption end lemma inversion_sends_nonzero_circles_to_circles.helper (z z₀ : ℂ) (r : ℝ) (r_pos : r > 0) (z_not_zero : z ≠ 0) (hz : r ≠ |z₀| ) : |z - z₀| = r ↔ |(1/z) - center_of_inverted_circle r z₀| = radius_of_inverted_circle r z₀ := begin dunfold center_of_inverted_circle radius_of_inverted_circle, have : |z - z₀| = r ↔ ( z₀.norm_squared - r*r)*|1/z|*|1/z| - 2 * complex.Re (z₀*(1/z)) + 1 = 0, { constructor; intro h, { have : |z - z₀|*|z - z₀| = r*r, rw h, transitivity complex.Re ((1 - z₀*(1/z))*complex.conj (1 - z₀*(1/z))) - r*r*( |1/z|*|1/z| ), { rw sub_mul, rw sub_mul, transitivity complex.norm_squared z₀ * |1 / z| * |1 / z| - 2 * (z₀ * (1 / z)).Re + 1 - r * r * |1 / z| * |1 / z|, { repeat { rw sub_eq_add_neg }, ac_refl }, rw mul_assoc (r*r), congr, rw conj_sub, rw (_ : complex.conj 1 = 1), tactic.swap, transitivity complex.conj (complex.mk 1 0), refl, dsimp [complex.conj], rw neg_zero, refl, rw FOIL_sub, rw [one_mul, one_mul, mul_one], rw [Re_additive, Re_sub, Re_sub, sub_sub, ← Re_additive], transitivity 1 - 2 * (z₀ * (1 / z)).Re + complex.norm_squared z₀ * |1 / z| * |1 / z|, { repeat { rw sub_eq_add_neg }, ac_refl }, congr, rw two_mul, rw Re_additive, apply congr_fun, apply congr_arg, apply Re_conj, rw ← squared_norm_eq_norm_squared, rw mul_right_comm ( |z₀| ), rw mul_assoc, rw ← norm_mul, rw squared_norm_eq_norm_squared, apply norm_squared_eq_mul_conj'' }, rw ← norm_squared_eq_mul_conj'', rw [← h, mul_assoc, mul_left_comm _ ( |1/z| ) _, ← mul_assoc], rw ← norm_mul, rw sub_mul, rw ← div_eq_mul_one_div z, rw div_self z_not_zero, rw squared_norm_eq_norm_squared, apply sub_self }, { have : (complex.norm_squared z₀ - r * r) * ( |1 / z| * |1 / z| ) - (2 * (z₀ * (1 / z)).Re) / ( |1 / z| * |1 / z| ) * ( |1 / z| * |1 / z| ) + 1/( |1 / z| * |1 / z| ) * ( |1 / z| * |1 / z| ) = 0, rw ← mul_assoc, rw div_eq_mul_one_div _ ( |1 / z| * |1 / z| ), rw mul_assoc _ _ ( |1 / z| * |1 / z| ), rw mul_comm _ ( |1 / z| * |1 / z| ), rw ← div_eq_mul_one_div _ ( |1 / z| * |1 / z| ), rw div_self, rw mul_one, assumption, rw ← norm_mul, apply mt (norm_zero_implies_zero _), rw ← div_mul_eq_div_mul_one_div, intro h, apply z_not_zero, apply eq_zero_of_sqr_eq_zero, have := mt (@inv_ne_zero _ _ (z*z)), rw [classical.dne, classical.dne] at this, rw inv_eq_one_div at this, apply this, assumption, rw [← sub_mul, ← right_distrib] at this, have h1 : |1/z| * |1/z| ≠ 0, { rw ← norm_mul, apply mt (norm_zero_implies_zero _), intro h, have := classical.l_or_r_eq_zero_of_mul_eq_zero h, rw or_self at this, rw ← inv_eq_one_div at this, apply mt (@inv_ne_zero _ _ z), rw classical.dne, assumption, assumption }, have := or.resolve_right (classical.l_or_r_eq_zero_of_mul_eq_zero this) h1, suffices : |z - z₀|*|z - z₀| = r*r, { transitivity √( |z - z₀|*|z - z₀| ), apply sqrt_unique, apply mul_self_nonneg, apply complex.norm_nonneg, refl, transitivity √(r*r), rw this, symmetry, apply sqrt_unique, apply mul_self_nonneg, apply le_of_lt, assumption, refl, }, rw complex.squared_dist, apply eq_of_sub_eq_zero, transitivity complex.norm_squared z₀ - r * r - 2 * (z * complex.conj z₀).Re + complex.norm_squared z, { repeat { rw sub_eq_add_neg }, ac_refl }, rw ← this, have : ∀ q, q / ( |1 / z| * |1 / z| ) = q * complex.norm_squared z, { intro q, rw div_eq_mul_one_div, congr, rw ← norm_mul, rw ← div_mul_eq_div_mul_one_div, rw ← inv_eq_one_div (z*z), rw norm_inv, rw ← inv_eq_one_div, rw division_ring.inv_inv, rw norm_mul, rw squared_norm_eq_norm_squared, rw norm_mul, apply division_ring.mul_ne_zero; apply mt (norm_zero_implies_zero _); assumption, apply division_ring.mul_ne_zero; assumption, }, apply congr, { apply congr_arg, apply congr_arg, rw this, rw mul_assoc, rw mul_comm _ (complex.norm_squared _), rw ← Re_of_scale (complex.norm_squared _), rw [Re_conj, conj_mul, conj_of_conj], congr, rw scalar_mul_comm_mul', rw mul_comm, congr, rw norm_squared_div_self, }, { rw this, rw one_mul } } }, generalize hw : 1/z = w, rw hw at this, generalize hA : complex.norm_squared z₀ - r*r = A, have hA' : A ≠ 0, { rw ← hA, apply mt eq_of_sub_eq_zero, intro h, apply hz, transitivity √(r*r), apply sqrt_unique, apply mul_self_nonneg, apply le_of_lt, assumption, refl, rw ← h }, rw mul_assoc at this, rw hA at this, have : |z - z₀| = r ↔ |w| * |w| - (2 * (z₀ * w).Re)/A + 1/A = 0, { rw this, rw (_ : |w| * |w| - 2 * (z₀ * w).Re / A + 1 / A = (A * ( |w| * |w| ) - 2 * (z₀ * w).Re + 1)/A), rw (_ : ((A * ( |w| * |w| ) - 2 * (z₀ * w).Re + 1) / A = 0) ↔ (0 = (A * ( |w| * |w| ) - 2 * (z₀ * w).Re + 1) / A)), rw eq_div_iff_mul_eq _ _ hA', rw zero_mul, apply eq_symm_iff, apply eq_symm_iff, transitivity (A/A) * ( |w| * |w| ) - 2 * (z₀ * w).Re / A + 1 / A, rw [div_self hA', one_mul], rw div_eq_mul_one_div, rw div_eq_mul_one_div (_ * _), transitivity A * (1 / A) * ( |w| * |w| ) - 2 * (z₀ * w).Re * (1 / A) + 1 * (1 / A), rw one_mul, rw mul_right_comm, rw ← sub_mul, rw ← right_distrib, rw ← div_eq_mul_one_div }, rw [mul_div_assoc, div_eq_mul_one_div] at this, rw [mul_comm _ (1/A), ← Re_of_scale] at this, rw (_ : complex.scalar_mul (1 / A) (z₀ * w) = complex.scalar_mul (1 / A) z₀ * w) at this, tactic.swap, rw mul_comm, transitivity complex.scalar_mul (1/A) (complex.mul w z₀), refl, rw scalar_mul_comm_mul, transitivity w * (complex.scalar_mul (1 / A) z₀), refl, apply mul_comm, rw ← conj_of_conj (complex.scalar_mul (1 / A) z₀) at this, rw squared_norm_eq_norm_squared at this, rw mul_comm _ w at this, have : |z - z₀| = r ↔ complex.norm_squared w - 2 * (w * complex.conj (complex.conj (complex.scalar_mul (1 / A) z₀))).Re = -(1 / A), { transitivity (complex.norm_squared w - 2 * (w * complex.conj (complex.conj (complex.scalar_mul (1 / A) z₀))).Re + (1 / A) = 0), assumption, constructor; intro h, apply eq_of_sub_eq_zero, rw sub_eq_add_neg, rw neg_neg, assumption, rw h, apply neg_add_self, }, have h1 := complex.squared_dist w (complex.conj (complex.scalar_mul (1 / A) z₀)), transitivity complex.norm_squared w - 2 * (w * complex.conj (complex.conj (complex.scalar_mul (1 / A) z₀))).Re = -(1 / A), assumption, transitivity complex.norm_squared w - 2 * (w * complex.conj (complex.conj (complex.scalar_mul (1 / A) z₀))).Re + complex.norm_squared (complex.conj (complex.scalar_mul (1 / A) z₀)) = complex.norm_squared (complex.conj (complex.scalar_mul (1 / A) z₀)) - (1 / A), { constructor; intro h, rw h, rw [add_comm, ← sub_eq_add_neg], rw sub_eq_add_neg _ (1/A) at h, rw add_comm _ (-(1/A)) at h, apply add_right_cancel, assumption, }, rw ← h1, rw squared_norm_eq_norm_squared, constructor; intro h, { apply congr_arg sqrt, assumption }, { rw ← squared_norm_eq_norm_squared, rw h, apply sqrt_sq, apply sub_nonneg_of_le, rw ← hA, apply random_inversion_inequality, assumption', } end lemma inversion_sends_nonzero_circles_to_circles : ∀ r z₀, r ≠ |z₀| → r > 0 → fun.im (λ z : ℂ, 1/z) (mk_circle z₀ r) = mk_circle (center_of_inverted_circle r z₀) (radius_of_inverted_circle r z₀) := begin intros _ _ hnon_zero hpos, funext z, apply propext, constructor; intro h', { cases h' with w hw, cases hw, have : |w - z₀| = r := hw_left, rw inversion_sends_nonzero_circles_to_circles.helper at this, have h1 : z = 1/w := hw_right, rw ← h1 at this, exact this, assumption', intro h, apply hnon_zero, rw ← this, rw h, rw norm_sub, rw sub_zero }, { have : |z - center_of_inverted_circle r z₀| = radius_of_inverted_circle r z₀ := h', have h1 : z = 1/(1/z), { rw div_of_div_eq_self, apply one_ne_zero, intro h, apply hnon_zero, rw h at this, symmetry, apply inverted_radius_eq_iverted_center_implies_center_eq_radius, assumption, rw ← this, rw norm_sub, rw sub_zero }, rw h1 at this, rw ← inversion_sends_nonzero_circles_to_circles.helper at this, existsi 1/z, constructor, assumption, simp, rw division_ring.inv_inv, { intro hz, have h1 : 1/z = 0, rw hz, rw div_zero, rw [h1, norm_sub, sub_zero] at this, apply hnon_zero, symmetry, assumption }, assumption, { intro hz, rw [hz, norm_sub, div_zero, sub_zero] at this, apply hnon_zero, symmetry, apply inverted_radius_eq_iverted_center_implies_center_eq_radius, assumption, assumption }, assumption } end lemma scale_sends_circles_to_circles : ∀ (r : ℝ) (z₀ c : ℂ), c ≠ 0 → fun.im (λ z, c * z) (mk_circle z₀ r) = mk_circle (c * z₀) ( |c| * r) := begin intros, funext, apply propext, suffices : (∃w, |w - z₀| = r ∧ b = c*w) ↔ |b - c*z₀| = |c|*r, exact this, constructor; intro h, { cases h with w h, cases h with hdist hb, rw hb, rw ← mul_sub, rw norm_mul, rw hdist }, { existsi (b/c), constructor, { rw (_ : z₀ = (z₀*c)/c), rw div_sub_div_same, rw div_eq_mul_one_div, rw norm_mul, rw ← inv_eq_one_div, rw norm_inv, rw inv_eq_one_div, rw ← div_eq_mul_one_div, apply mul_eq_of_eq_div, apply inv_ne_zero, apply mt (norm_zero_implies_zero _), assumption, rw inv_eq_one_div, rw div_eq_mul_one_div, rw div_of_div_eq_self, rw [mul_comm, mul_comm r], assumption, apply one_ne_zero, apply mt (norm_zero_implies_zero _), assumption, assumption, rw mul_div_cancel, assumption }, rw mul_comm, rw div_mul_cancel, assumption }, end theorem problem17 : ∀ (ρ : ℝ), ρ > 0 → ρ ≠ 1 → ∀ (z₀ z₁ : ℂ), z₀ ≠ z₁ → is_circle ({ z : ℂ | |z - z₀| = ρ * |z - z₁|}) := begin intros ρ h0 h1 z₀ z₁ hz, have : {z : ℂ | |z - z₀| = ρ * |z - z₁|} = {z : ℂ | |z - z₀|/|z - z₁| = ρ }, { funext, apply propext, suffices : |z - z₀| = ρ * |z - z₁| ↔ |z - z₀|/|z - z₁| = ρ, exact this, constructor; intro h, { have : z - z₁ ≠ 0, { intro hz0, rw [hz0, norm_of_zero, mul_zero] at h, apply hz, transitivity z, apply eq_of_sub_eq_zero, apply neg_inj, rw neg_zero, rw neg_sub, apply norm_zero_implies_zero, assumption, apply eq_of_sub_eq_zero, assumption, }, symmetry, rw eq_div_iff_mul_eq, symmetry, assumption, exact mt (norm_zero_implies_zero _) this }, { symmetry, rw ← eq_div_iff_mul_eq, symmetry, assumption, intro hz, rw [hz, div_zero] at h, apply ne_of_gt h0, symmetry, assumption } }, rw this, have : {z : ℂ | |z - z₀|/|z - z₁| = ρ } = {z : ℂ | |(z - z₀)/(z - z₁)| = ρ }, { funext, apply propext, suffices : |z - z₀|/|z - z₁| = ρ ↔ |(z - z₀)/(z - z₁)| = ρ, exact this, constructor; intro h, { rw norm_div, exact h, intro hz, rw hz at h, rw [norm_of_zero, div_zero] at h, rw h at h0, apply lt_irrefl ρ, exact h0 }, { rw ← norm_div, exact h, intro hz, rw hz at h, rw [div_zero, norm_of_zero] at h, rw h at h0, apply lt_irrefl ρ, exact h0 } }, rw this, have h1 : ∀ z, z - z₁ ≠ 0 → 1 + (z₁ - z₀) / (z - z₁) = (z - z₀) / (z - z₁), { intros z hz, rw ← div_self hz, rw [div_add_div_same, ← add_sub_assoc, sub_add_cancel] }, have : {z : ℂ | |(z - z₀)/(z - z₁)| = ρ } = {z : ℂ | |1 + (z₁ - z₀)/(z - z₁)| = ρ }, { funext, apply propext, suffices : |(z - z₀)/(z - z₁)| = ρ ↔ |1 + (z₁ - z₀) / (z - z₁)| = ρ, exact this, constructor; intro h, { rw h1, exact h, intro hz, rw hz at h, rw [div_zero, norm_of_zero] at h, rw h at h0, apply lt_irrefl ρ, exact h0 }, { rw ← h1, exact h, intro hz, rw hz at h, rw [div_zero, add_zero, norm_of_one] at h, refine ((_ : ρ ≠ 1) (eq.symm h)), assumption } }, rw this, let f := λ z, 1 + (z₁ - z₀)/(z - z₁), let g := λ z, (z₁ - z₀)/(z - 1) + z₁, have gf_id : ∀ z, f (g z) = z, { intros z, dsimp [f, g], by_cases z = 1, { rw h, simp, rw [div_zero, div_zero, add_zero] }, rw [add_assoc, add_neg_self, add_zero], rw [← sub_eq_add_neg, div_of_div_eq_self], rw [add_comm, add_assoc, neg_add_self, add_zero], apply mt eq_of_sub_eq_zero, apply ne.symm, assumption, rw ← sub_eq_add_neg, apply mt eq_of_sub_eq_zero, assumption }, have fg_id : ∀ z, g (f z) = z, { intros z, dsimp [f, g], by_cases z = z₁, { rw h, simp, rw [div_zero, div_zero, add_zero] }, rw [add_right_comm, add_neg_self, zero_add], rw [← sub_eq_add_neg, div_of_div_eq_self], rw [add_assoc, neg_add_self, add_zero], apply mt eq_of_sub_eq_zero, apply ne.symm, assumption, rw ← sub_eq_add_neg, intro hz, apply h, apply eq_of_sub_eq_zero hz }, have : {z : ℂ | |1 + (z₁ - z₀)/(z - z₁)| = ρ } = {z : ℂ | |f z| = ρ }, refl, rw this, have : {z : ℂ | |f z| = ρ } = fun.pre_im f (mk_circle 0 ρ), { funext, apply propext, transitivity |f z| = ρ, refl, transitivity |f z - 0| = ρ, rw sub_zero, refl }, rw this, clear this, clear this, clear this, clear this, rw fun.pre_im_of_inv_eq_im f g _ gf_id fg_id, let T0 : ℂ → ℂ := λ z, z - 1, let T1 : ℂ → ℂ := λ z, 1/z, let T2 : ℂ → ℂ := λ z, (z₁ - z₀) * z, let T3 : ℂ → ℂ := λ z, z - -z₁, have : g = T3 ∘ T2 ∘ T1 ∘ T0, { funext, simp [T0, T1, T2, T3, g, (/)], delta algebra.div, rw one_mul }, rw this, clear this, rw [im_of_comp, im_of_comp], rw im_of_comp T0 T1, rw shift_sends_circles_to_circles, simp, rw inversion_sends_nonzero_circles_to_circles, rw scale_sends_circles_to_circles, rw shift_sends_circles_to_circles, existsi ((z₁ - z₀) * center_of_inverted_circle ρ (-1) - -z₁), existsi ( |z₁ - z₀| * radius_of_inverted_circle ρ (-1)), refl, apply mt eq_of_sub_eq_zero, apply ne.symm, assumption, rw norm_neg, rw norm_of_one, assumption, assumption end
8b9104bdab9467463401fa5900317c64f14b4320
367134ba5a65885e863bdc4507601606690974c1
/src/linear_algebra/affine_space/affine_subspace.lean
951fb9a58d9ce0f6e91545d3dba3e1ac268b94ba
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
45,112
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Joseph Myers. -/ import linear_algebra.affine_space.basic import linear_algebra.tensor_product import data.set.intervals.unordered_interval /-! # Affine spaces This file defines affine subspaces (over modules) and the affine span of a set of points. ## Main definitions * `affine_subspace k P` is the type of affine subspaces. Unlike affine spaces, affine subspaces are allowed to be empty, and lemmas that do not apply to empty affine subspaces have `nonempty` hypotheses. There is a `complete_lattice` structure on affine subspaces. * `affine_subspace.direction` gives the `submodule` spanned by the pairwise differences of points in an `affine_subspace`. There are various lemmas relating to the set of vectors in the `direction`, and relating the lattice structure on affine subspaces to that on their directions. * `affine_span` gives the affine subspace spanned by a set of points, with `vector_span` giving its direction. `affine_span` is defined in terms of `span_points`, which gives an explicit description of the points contained in the affine span; `span_points` itself should generally only be used when that description is required, with `affine_span` being the main definition for other purposes. Two other descriptions of the affine span are proved equivalent: it is the `Inf` of affine subspaces containing the points, and (if `[nontrivial k]`) it contains exactly those points that are affine combinations of points in the given set. ## Implementation notes `out_param` is used in the definiton of `add_torsor V P` to make `V` an implicit argument (deduced from `P`) in most cases; `include V` is needed in many cases for `V`, and type classes using it, to be added as implicit arguments to individual lemmas. As for modules, `k` is an explicit argument rather than implied by `P` or `V`. This file only provides purely algebraic definitions and results. Those depending on analysis or topology are defined elsewhere; see `analysis.normed_space.add_torsor` and `topology.algebra.affine`. ## References * https://en.wikipedia.org/wiki/Affine_space * https://en.wikipedia.org/wiki/Principal_homogeneous_space -/ noncomputable theory open_locale big_operators classical affine open set section variables (k : Type*) {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] variables [affine_space V P] include V /-- The submodule spanning the differences of a (possibly empty) set of points. -/ def vector_span (s : set P) : submodule k V := submodule.span k (s -ᵥ s) /-- The definition of `vector_span`, for rewriting. -/ lemma vector_span_def (s : set P) : vector_span k s = submodule.span k (s -ᵥ s) := rfl /-- `vector_span` is monotone. -/ lemma vector_span_mono {s₁ s₂ : set P} (h : s₁ ⊆ s₂) : vector_span k s₁ ≤ vector_span k s₂ := submodule.span_mono (vsub_self_mono h) variables (P) /-- The `vector_span` of the empty set is `⊥`. -/ @[simp] lemma vector_span_empty : vector_span k (∅ : set P) = (⊥ : submodule k V) := by rw [vector_span_def, vsub_empty, submodule.span_empty] variables {P} /-- The `vector_span` of a single point is `⊥`. -/ @[simp] lemma vector_span_singleton (p : P) : vector_span k ({p} : set P) = ⊥ := by simp [vector_span_def] /-- The `s -ᵥ s` lies within the `vector_span k s`. -/ lemma vsub_set_subset_vector_span (s : set P) : s -ᵥ s ⊆ ↑(vector_span k s) := submodule.subset_span /-- Each pairwise difference is in the `vector_span`. -/ lemma vsub_mem_vector_span {s : set P} {p1 p2 : P} (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) : p1 -ᵥ p2 ∈ vector_span k s := vsub_set_subset_vector_span k s (vsub_mem_vsub hp1 hp2) /-- The points in the affine span of a (possibly empty) set of points. Use `affine_span` instead to get an `affine_subspace k P`. -/ def span_points (s : set P) : set P := {p | ∃ p1 ∈ s, ∃ v ∈ (vector_span k s), p = v +ᵥ p1} /-- A point in a set is in its affine span. -/ lemma mem_span_points (p : P) (s : set P) : p ∈ s → p ∈ span_points k s | hp := ⟨p, hp, 0, submodule.zero_mem _, (zero_vadd V p).symm⟩ /-- A set is contained in its `span_points`. -/ lemma subset_span_points (s : set P) : s ⊆ span_points k s := λ p, mem_span_points k p s /-- The `span_points` of a set is nonempty if and only if that set is. -/ @[simp] lemma span_points_nonempty (s : set P) : (span_points k s).nonempty ↔ s.nonempty := begin split, { contrapose, rw [set.not_nonempty_iff_eq_empty, set.not_nonempty_iff_eq_empty], intro h, simp [h, span_points] }, { exact λ h, h.mono (subset_span_points _ _) } end /-- Adding a point in the affine span and a vector in the spanning submodule produces a point in the affine span. -/ lemma vadd_mem_span_points_of_mem_span_points_of_mem_vector_span {s : set P} {p : P} {v : V} (hp : p ∈ span_points k s) (hv : v ∈ vector_span k s) : v +ᵥ p ∈ span_points k s := begin rcases hp with ⟨p2, ⟨hp2, ⟨v2, ⟨hv2, hv2p⟩⟩⟩⟩, rw [hv2p, vadd_assoc], use [p2, hp2, v + v2, (vector_span k s).add_mem hv hv2, rfl] end /-- Subtracting two points in the affine span produces a vector in the spanning submodule. -/ lemma vsub_mem_vector_span_of_mem_span_points_of_mem_span_points {s : set P} {p1 p2 : P} (hp1 : p1 ∈ span_points k s) (hp2 : p2 ∈ span_points k s) : p1 -ᵥ p2 ∈ vector_span k s := begin rcases hp1 with ⟨p1a, ⟨hp1a, ⟨v1, ⟨hv1, hv1p⟩⟩⟩⟩, rcases hp2 with ⟨p2a, ⟨hp2a, ⟨v2, ⟨hv2, hv2p⟩⟩⟩⟩, rw [hv1p, hv2p, vsub_vadd_eq_vsub_sub (v1 +ᵥ p1a), vadd_vsub_assoc, add_comm, add_sub_assoc], have hv1v2 : v1 - v2 ∈ vector_span k s, { rw sub_eq_add_neg, apply (vector_span k s).add_mem hv1, rw ←neg_one_smul k v2, exact (vector_span k s).smul_mem (-1 : k) hv2 }, refine (vector_span k s).add_mem _ hv1v2, exact vsub_mem_vector_span k hp1a hp2a end end /-- An `affine_subspace k P` is a subset of an `affine_space V P` that, if not empty, has an affine space structure induced by a corresponding subspace of the `module k V`. -/ structure affine_subspace (k : Type*) {V : Type*} (P : Type*) [ring k] [add_comm_group V] [module k V] [affine_space V P] := (carrier : set P) (smul_vsub_vadd_mem : ∀ (c : k) {p1 p2 p3 : P}, p1 ∈ carrier → p2 ∈ carrier → p3 ∈ carrier → c • (p1 -ᵥ p2 : V) +ᵥ p3 ∈ carrier) namespace submodule variables {k V : Type*} [ring k] [add_comm_group V] [module k V] /-- Reinterpret `p : submodule k V` as an `affine_subspace k V`. -/ def to_affine_subspace (p : submodule k V) : affine_subspace k V := { carrier := p, smul_vsub_vadd_mem := λ c p₁ p₂ p₃ h₁ h₂ h₃, p.add_mem (p.smul_mem _ (p.sub_mem h₁ h₂)) h₃ } end submodule namespace affine_subspace variables (k : Type*) {V : Type*} (P : Type*) [ring k] [add_comm_group V] [module k V] [affine_space V P] include V instance : has_coe (affine_subspace k P) (set P) := ⟨carrier⟩ instance : has_mem P (affine_subspace k P) := ⟨λ p s, p ∈ (s : set P)⟩ /-- A point is in an affine subspace coerced to a set if and only if it is in that affine subspace. -/ @[simp] lemma mem_coe (p : P) (s : affine_subspace k P) : p ∈ (s : set P) ↔ p ∈ s := iff.rfl variables {k P} /-- The direction of an affine subspace is the submodule spanned by the pairwise differences of points. (Except in the case of an empty affine subspace, where the direction is the zero submodule, every vector in the direction is the difference of two points in the affine subspace.) -/ def direction (s : affine_subspace k P) : submodule k V := vector_span k (s : set P) /-- The direction equals the `vector_span`. -/ lemma direction_eq_vector_span (s : affine_subspace k P) : s.direction = vector_span k (s : set P) := rfl /-- Alternative definition of the direction when the affine subspace is nonempty. This is defined so that the order on submodules (as used in the definition of `submodule.span`) can be used in the proof of `coe_direction_eq_vsub_set`, and is not intended to be used beyond that proof. -/ def direction_of_nonempty {s : affine_subspace k P} (h : (s : set P).nonempty) : submodule k V := { carrier := (s : set P) -ᵥ s, zero_mem' := begin cases h with p hp, exact (vsub_self p) ▸ vsub_mem_vsub hp hp end, add_mem' := begin intros a b ha hb, rcases ha with ⟨p1, p2, hp1, hp2, rfl⟩, rcases hb with ⟨p3, p4, hp3, hp4, rfl⟩, rw [←vadd_vsub_assoc], refine vsub_mem_vsub _ hp4, convert s.smul_vsub_vadd_mem 1 hp1 hp2 hp3, rw one_smul end, smul_mem' := begin intros c v hv, rcases hv with ⟨p1, p2, hp1, hp2, rfl⟩, rw [←vadd_vsub (c • (p1 -ᵥ p2)) p2], refine vsub_mem_vsub _ hp2, exact s.smul_vsub_vadd_mem c hp1 hp2 hp2 end } /-- `direction_of_nonempty` gives the same submodule as `direction`. -/ lemma direction_of_nonempty_eq_direction {s : affine_subspace k P} (h : (s : set P).nonempty) : direction_of_nonempty h = s.direction := le_antisymm (vsub_set_subset_vector_span k s) (submodule.span_le.2 set.subset.rfl) /-- The set of vectors in the direction of a nonempty affine subspace is given by `vsub_set`. -/ lemma coe_direction_eq_vsub_set {s : affine_subspace k P} (h : (s : set P).nonempty) : (s.direction : set V) = (s : set P) -ᵥ s := direction_of_nonempty_eq_direction h ▸ rfl /-- A vector is in the direction of a nonempty affine subspace if and only if it is the subtraction of two vectors in the subspace. -/ lemma mem_direction_iff_eq_vsub {s : affine_subspace k P} (h : (s : set P).nonempty) (v : V) : v ∈ s.direction ↔ ∃ p1 ∈ s, ∃ p2 ∈ s, v = p1 -ᵥ p2 := begin rw [←submodule.mem_coe, coe_direction_eq_vsub_set h], exact ⟨λ ⟨p1, p2, hp1, hp2, hv⟩, ⟨p1, hp1, p2, hp2, hv.symm⟩, λ ⟨p1, hp1, p2, hp2, hv⟩, ⟨p1, p2, hp1, hp2, hv.symm⟩⟩ end /-- Adding a vector in the direction to a point in the subspace produces a point in the subspace. -/ lemma vadd_mem_of_mem_direction {s : affine_subspace k P} {v : V} (hv : v ∈ s.direction) {p : P} (hp : p ∈ s) : v +ᵥ p ∈ s := begin rw mem_direction_iff_eq_vsub ⟨p, hp⟩ at hv, rcases hv with ⟨p1, hp1, p2, hp2, hv⟩, rw hv, convert s.smul_vsub_vadd_mem 1 hp1 hp2 hp, rw one_smul end /-- Subtracting two points in the subspace produces a vector in the direction. -/ lemma vsub_mem_direction {s : affine_subspace k P} {p1 p2 : P} (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) : (p1 -ᵥ p2) ∈ s.direction := vsub_mem_vector_span k hp1 hp2 /-- Adding a vector to a point in a subspace produces a point in the subspace if and only if the vector is in the direction. -/ lemma vadd_mem_iff_mem_direction {s : affine_subspace k P} (v : V) {p : P} (hp : p ∈ s) : v +ᵥ p ∈ s ↔ v ∈ s.direction := ⟨λ h, by simpa using vsub_mem_direction h hp, λ h, vadd_mem_of_mem_direction h hp⟩ /-- Given a point in an affine subspace, the set of vectors in its direction equals the set of vectors subtracting that point on the right. -/ lemma coe_direction_eq_vsub_set_right {s : affine_subspace k P} {p : P} (hp : p ∈ s) : (s.direction : set V) = (-ᵥ p) '' s := begin rw coe_direction_eq_vsub_set ⟨p, hp⟩, refine le_antisymm _ _, { rintros v ⟨p1, p2, hp1, hp2, rfl⟩, exact ⟨p1 -ᵥ p2 +ᵥ p, vadd_mem_of_mem_direction (vsub_mem_direction hp1 hp2) hp, (vadd_vsub _ _)⟩ }, { rintros v ⟨p2, hp2, rfl⟩, exact ⟨p2, p, hp2, hp, rfl⟩ } end /-- Given a point in an affine subspace, the set of vectors in its direction equals the set of vectors subtracting that point on the left. -/ lemma coe_direction_eq_vsub_set_left {s : affine_subspace k P} {p : P} (hp : p ∈ s) : (s.direction : set V) = (-ᵥ) p '' s := begin ext v, rw [submodule.mem_coe, ←submodule.neg_mem_iff, ←submodule.mem_coe, coe_direction_eq_vsub_set_right hp, set.mem_image_iff_bex, set.mem_image_iff_bex], conv_lhs { congr, funext, rw [←neg_vsub_eq_vsub_rev, neg_inj] } end /-- Given a point in an affine subspace, a vector is in its direction if and only if it results from subtracting that point on the right. -/ lemma mem_direction_iff_eq_vsub_right {s : affine_subspace k P} {p : P} (hp : p ∈ s) (v : V) : v ∈ s.direction ↔ ∃ p2 ∈ s, v = p2 -ᵥ p := begin rw [←submodule.mem_coe, coe_direction_eq_vsub_set_right hp], exact ⟨λ ⟨p2, hp2, hv⟩, ⟨p2, hp2, hv.symm⟩, λ ⟨p2, hp2, hv⟩, ⟨p2, hp2, hv.symm⟩⟩ end /-- Given a point in an affine subspace, a vector is in its direction if and only if it results from subtracting that point on the left. -/ lemma mem_direction_iff_eq_vsub_left {s : affine_subspace k P} {p : P} (hp : p ∈ s) (v : V) : v ∈ s.direction ↔ ∃ p2 ∈ s, v = p -ᵥ p2 := begin rw [←submodule.mem_coe, coe_direction_eq_vsub_set_left hp], exact ⟨λ ⟨p2, hp2, hv⟩, ⟨p2, hp2, hv.symm⟩, λ ⟨p2, hp2, hv⟩, ⟨p2, hp2, hv.symm⟩⟩ end /-- Given a point in an affine subspace, a result of subtracting that point on the right is in the direction if and only if the other point is in the subspace. -/ lemma vsub_right_mem_direction_iff_mem {s : affine_subspace k P} {p : P} (hp : p ∈ s) (p2 : P) : p2 -ᵥ p ∈ s.direction ↔ p2 ∈ s := begin rw mem_direction_iff_eq_vsub_right hp, simp end /-- Given a point in an affine subspace, a result of subtracting that point on the left is in the direction if and only if the other point is in the subspace. -/ lemma vsub_left_mem_direction_iff_mem {s : affine_subspace k P} {p : P} (hp : p ∈ s) (p2 : P) : p -ᵥ p2 ∈ s.direction ↔ p2 ∈ s := begin rw mem_direction_iff_eq_vsub_left hp, simp end /-- Two affine subspaces are equal if they have the same points. -/ @[ext] lemma ext {s1 s2 : affine_subspace k P} (h : (s1 : set P) = s2) : s1 = s2 := begin cases s1, cases s2, congr, exact h end /-- Two affine subspaces with the same direction and nonempty intersection are equal. -/ lemma ext_of_direction_eq {s1 s2 : affine_subspace k P} (hd : s1.direction = s2.direction) (hn : ((s1 : set P) ∩ s2).nonempty) : s1 = s2 := begin ext p, have hq1 := set.mem_of_mem_inter_left hn.some_mem, have hq2 := set.mem_of_mem_inter_right hn.some_mem, split, { intro hp, rw ←vsub_vadd p hn.some, refine vadd_mem_of_mem_direction _ hq2, rw ←hd, exact vsub_mem_direction hp hq1 }, { intro hp, rw ←vsub_vadd p hn.some, refine vadd_mem_of_mem_direction _ hq1, rw hd, exact vsub_mem_direction hp hq2 } end instance to_add_torsor (s : affine_subspace k P) [nonempty s] : add_torsor s.direction s := { vadd := λ a b, ⟨(a:V) +ᵥ (b:P), vadd_mem_of_mem_direction a.2 b.2⟩, zero_vadd' := by simp, vadd_assoc' := λ a b c, by { ext, apply add_torsor.vadd_assoc' }, vsub := λ a b, ⟨(a:P) -ᵥ (b:P), (vsub_left_mem_direction_iff_mem a.2 _).mpr b.2 ⟩, nonempty := by apply_instance, vsub_vadd' := λ a b, by { ext, apply add_torsor.vsub_vadd' }, vadd_vsub' := λ a b, by { ext, apply add_torsor.vadd_vsub' } } @[simp, norm_cast] lemma coe_vsub (s : affine_subspace k P) [nonempty s] (a b : s) : ↑(a -ᵥ b) = (a:P) -ᵥ (b:P) := rfl @[simp, norm_cast] lemma coe_vadd (s : affine_subspace k P) [nonempty s] (a : s.direction) (b : s) : ↑(a +ᵥ b) = (a:V) +ᵥ (b:P) := rfl /-- Two affine subspaces with nonempty intersection are equal if and only if their directions are equal. -/ lemma eq_iff_direction_eq_of_mem {s₁ s₂ : affine_subspace k P} {p : P} (h₁ : p ∈ s₁) (h₂ : p ∈ s₂) : s₁ = s₂ ↔ s₁.direction = s₂.direction := ⟨λ h, h ▸ rfl, λ h, ext_of_direction_eq h ⟨p, h₁, h₂⟩⟩ /-- Construct an affine subspace from a point and a direction. -/ def mk' (p : P) (direction : submodule k V) : affine_subspace k P := { carrier := {q | ∃ v ∈ direction, q = v +ᵥ p}, smul_vsub_vadd_mem := λ c p1 p2 p3 hp1 hp2 hp3, begin rcases hp1 with ⟨v1, hv1, hp1⟩, rcases hp2 with ⟨v2, hv2, hp2⟩, rcases hp3 with ⟨v3, hv3, hp3⟩, use [c • (v1 - v2) + v3, direction.add_mem (direction.smul_mem c (direction.sub_mem hv1 hv2)) hv3], simp [hp1, hp2, hp3, vadd_assoc] end } /-- An affine subspace constructed from a point and a direction contains that point. -/ lemma self_mem_mk' (p : P) (direction : submodule k V) : p ∈ mk' p direction := ⟨0, ⟨direction.zero_mem, (zero_vadd _ _).symm⟩⟩ /-- An affine subspace constructed from a point and a direction contains the result of adding a vector in that direction to that point. -/ lemma vadd_mem_mk' {v : V} (p : P) {direction : submodule k V} (hv : v ∈ direction) : v +ᵥ p ∈ mk' p direction := ⟨v, hv, rfl⟩ /-- An affine subspace constructed from a point and a direction is nonempty. -/ lemma mk'_nonempty (p : P) (direction : submodule k V) : (mk' p direction : set P).nonempty := ⟨p, self_mem_mk' p direction⟩ /-- The direction of an affine subspace constructed from a point and a direction. -/ @[simp] lemma direction_mk' (p : P) (direction : submodule k V) : (mk' p direction).direction = direction := begin ext v, rw mem_direction_iff_eq_vsub (mk'_nonempty _ _), split, { rintros ⟨p1, ⟨v1, hv1, hp1⟩, p2, ⟨v2, hv2, hp2⟩, hv⟩, rw [hv, hp1, hp2, vadd_vsub_vadd_cancel_right], exact direction.sub_mem hv1 hv2 }, { exact λ hv, ⟨v +ᵥ p, vadd_mem_mk' _ hv, p, self_mem_mk' _ _, (vadd_vsub _ _).symm⟩ } end /-- Constructing an affine subspace from a point in a subspace and that subspace's direction yields the original subspace. -/ @[simp] lemma mk'_eq {s : affine_subspace k P} {p : P} (hp : p ∈ s) : mk' p s.direction = s := ext_of_direction_eq (direction_mk' p s.direction) ⟨p, set.mem_inter (self_mem_mk' _ _) hp⟩ /-- If an affine subspace contains a set of points, it contains the `span_points` of that set. -/ lemma span_points_subset_coe_of_subset_coe {s : set P} {s1 : affine_subspace k P} (h : s ⊆ s1) : span_points k s ⊆ s1 := begin rintros p ⟨p1, hp1, v, hv, hp⟩, rw hp, have hp1s1 : p1 ∈ (s1 : set P) := set.mem_of_mem_of_subset hp1 h, refine vadd_mem_of_mem_direction _ hp1s1, have hs : vector_span k s ≤ s1.direction := vector_span_mono k h, rw submodule.le_def at hs, rw ←submodule.mem_coe, exact set.mem_of_mem_of_subset hv hs end end affine_subspace section affine_span variables (k : Type*) {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] [affine_space V P] include V /-- The affine span of a set of points is the smallest affine subspace containing those points. (Actually defined here in terms of spans in modules.) -/ def affine_span (s : set P) : affine_subspace k P := { carrier := span_points k s, smul_vsub_vadd_mem := λ c p1 p2 p3 hp1 hp2 hp3, vadd_mem_span_points_of_mem_span_points_of_mem_vector_span k hp3 ((vector_span k s).smul_mem c (vsub_mem_vector_span_of_mem_span_points_of_mem_span_points k hp1 hp2)) } /-- The affine span, converted to a set, is `span_points`. -/ @[simp] lemma coe_affine_span (s : set P) : (affine_span k s : set P) = span_points k s := rfl /-- A set is contained in its affine span. -/ lemma subset_affine_span (s : set P) : s ⊆ affine_span k s := subset_span_points k s /-- The direction of the affine span is the `vector_span`. -/ lemma direction_affine_span (s : set P) : (affine_span k s).direction = vector_span k s := begin apply le_antisymm, { refine submodule.span_le.2 _, rintros v ⟨p1, p3, ⟨p2, hp2, v1, hv1, hp1⟩, ⟨p4, hp4, v2, hv2, hp3⟩, rfl⟩, rw [hp1, hp3, vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, submodule.mem_coe], exact (vector_span k s).sub_mem ((vector_span k s).add_mem hv1 (vsub_mem_vector_span k hp2 hp4)) hv2 }, { exact vector_span_mono k (subset_span_points k s) } end /-- A point in a set is in its affine span. -/ lemma mem_affine_span {p : P} {s : set P} (hp : p ∈ s) : p ∈ affine_span k s := mem_span_points k p s hp end affine_span namespace affine_subspace variables {k : Type*} {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] [S : affine_space V P] include S instance : complete_lattice (affine_subspace k P) := { sup := λ s1 s2, affine_span k (s1 ∪ s2), le_sup_left := λ s1 s2, set.subset.trans (set.subset_union_left s1 s2) (subset_span_points k _), le_sup_right := λ s1 s2, set.subset.trans (set.subset_union_right s1 s2) (subset_span_points k _), sup_le := λ s1 s2 s3 hs1 hs2, span_points_subset_coe_of_subset_coe (set.union_subset hs1 hs2), inf := λ s1 s2, mk (s1 ∩ s2) (λ c p1 p2 p3 hp1 hp2 hp3, ⟨s1.smul_vsub_vadd_mem c hp1.1 hp2.1 hp3.1, s2.smul_vsub_vadd_mem c hp1.2 hp2.2 hp3.2⟩), inf_le_left := λ _ _, set.inter_subset_left _ _, inf_le_right := λ _ _, set.inter_subset_right _ _, le_inf := λ _ _ _, set.subset_inter, top := { carrier := set.univ, smul_vsub_vadd_mem := λ _ _ _ _ _ _ _, set.mem_univ _ }, le_top := λ _ _ _, set.mem_univ _, bot := { carrier := ∅, smul_vsub_vadd_mem := λ _ _ _ _, false.elim }, bot_le := λ _ _, false.elim, Sup := λ s, affine_span k (⋃ s' ∈ s, (s' : set P)), Inf := λ s, mk (⋂ s' ∈ s, (s' : set P)) (λ c p1 p2 p3 hp1 hp2 hp3, set.mem_bInter_iff.2 $ λ s2 hs2, s2.smul_vsub_vadd_mem c (set.mem_bInter_iff.1 hp1 s2 hs2) (set.mem_bInter_iff.1 hp2 s2 hs2) (set.mem_bInter_iff.1 hp3 s2 hs2)), le_Sup := λ _ _ h, set.subset.trans (set.subset_bUnion_of_mem h) (subset_span_points k _), Sup_le := λ _ _ h, span_points_subset_coe_of_subset_coe (set.bUnion_subset h), Inf_le := λ _ _, set.bInter_subset_of_mem, le_Inf := λ _ _, set.subset_bInter, .. partial_order.lift (coe : affine_subspace k P → set P) (λ _ _, ext) } instance : inhabited (affine_subspace k P) := ⟨⊤⟩ /-- The `≤` order on subspaces is the same as that on the corresponding sets. -/ lemma le_def (s1 s2 : affine_subspace k P) : s1 ≤ s2 ↔ (s1 : set P) ⊆ s2 := iff.rfl /-- One subspace is less than or equal to another if and only if all its points are in the second subspace. -/ lemma le_def' (s1 s2 : affine_subspace k P) : s1 ≤ s2 ↔ ∀ p ∈ s1, p ∈ s2 := iff.rfl /-- The `<` order on subspaces is the same as that on the corresponding sets. -/ lemma lt_def (s1 s2 : affine_subspace k P) : s1 < s2 ↔ (s1 : set P) ⊂ s2 := iff.rfl /-- One subspace is not less than or equal to another if and only if it has a point not in the second subspace. -/ lemma not_le_iff_exists (s1 s2 : affine_subspace k P) : ¬ s1 ≤ s2 ↔ ∃ p ∈ s1, p ∉ s2 := set.not_subset /-- If a subspace is less than another, there is a point only in the second. -/ lemma exists_of_lt {s1 s2 : affine_subspace k P} (h : s1 < s2) : ∃ p ∈ s2, p ∉ s1 := set.exists_of_ssubset h /-- A subspace is less than another if and only if it is less than or equal to the second subspace and there is a point only in the second. -/ lemma lt_iff_le_and_exists (s1 s2 : affine_subspace k P) : s1 < s2 ↔ s1 ≤ s2 ∧ ∃ p ∈ s2, p ∉ s1 := by rw [lt_iff_le_not_le, not_le_iff_exists] /-- If an affine subspace is nonempty and contained in another with the same direction, they are equal. -/ lemma eq_of_direction_eq_of_nonempty_of_le {s₁ s₂ : affine_subspace k P} (hd : s₁.direction = s₂.direction) (hn : (s₁ : set P).nonempty) (hle : s₁ ≤ s₂) : s₁ = s₂ := let ⟨p, hp⟩ := hn in ext_of_direction_eq hd ⟨p, hp, hle hp⟩ variables (k V) /-- The affine span is the `Inf` of subspaces containing the given points. -/ lemma affine_span_eq_Inf (s : set P) : affine_span k s = Inf {s' | s ⊆ s'} := le_antisymm (span_points_subset_coe_of_subset_coe (set.subset_bInter (λ _ h, h))) (Inf_le (subset_span_points k _)) variables (P) /-- The Galois insertion formed by `affine_span` and coercion back to a set. -/ protected def gi : galois_insertion (affine_span k) (coe : affine_subspace k P → set P) := { choice := λ s _, affine_span k s, gc := λ s1 s2, ⟨λ h, set.subset.trans (subset_span_points k s1) h, span_points_subset_coe_of_subset_coe⟩, le_l_u := λ _, subset_span_points k _, choice_eq := λ _ _, rfl } /-- The span of the empty set is `⊥`. -/ @[simp] lemma span_empty : affine_span k (∅ : set P) = ⊥ := (affine_subspace.gi k V P).gc.l_bot /-- The span of `univ` is `⊤`. -/ @[simp] lemma span_univ : affine_span k (set.univ : set P) = ⊤ := eq_top_iff.2 $ subset_span_points k _ variables {P} /-- The affine span of a single point, coerced to a set, contains just that point. -/ @[simp] lemma coe_affine_span_singleton (p : P) : (affine_span k ({p} : set P) : set P) = {p} := begin ext x, rw [mem_coe, ←vsub_right_mem_direction_iff_mem (mem_affine_span k (set.mem_singleton p)) _, direction_affine_span], simp end /-- A point is in the affine span of a single point if and only if they are equal. -/ @[simp] lemma mem_affine_span_singleton (p1 p2 : P) : p1 ∈ affine_span k ({p2} : set P) ↔ p1 = p2 := by simp [←mem_coe] /-- The span of a union of sets is the sup of their spans. -/ lemma span_union (s t : set P) : affine_span k (s ∪ t) = affine_span k s ⊔ affine_span k t := (affine_subspace.gi k V P).gc.l_sup /-- The span of a union of an indexed family of sets is the sup of their spans. -/ lemma span_Union {ι : Type*} (s : ι → set P) : affine_span k (⋃ i, s i) = ⨆ i, affine_span k (s i) := (affine_subspace.gi k V P).gc.l_supr variables (P) /-- `⊤`, coerced to a set, is the whole set of points. -/ @[simp] lemma top_coe : ((⊤ : affine_subspace k P) : set P) = set.univ := rfl variables {P} /-- All points are in `⊤`. -/ lemma mem_top (p : P) : p ∈ (⊤ : affine_subspace k P) := set.mem_univ p variables (P) /-- The direction of `⊤` is the whole module as a submodule. -/ @[simp] lemma direction_top : (⊤ : affine_subspace k P).direction = ⊤ := begin cases S.nonempty with p, ext v, refine ⟨imp_intro submodule.mem_top, λ hv, _⟩, have hpv : (v +ᵥ p -ᵥ p : V) ∈ (⊤ : affine_subspace k P).direction := vsub_mem_direction (mem_top k V _) (mem_top k V _), rwa vadd_vsub at hpv end /-- `⊥`, coerced to a set, is the empty set. -/ @[simp] lemma bot_coe : ((⊥ : affine_subspace k P) : set P) = ∅ := rfl variables {P} /-- No points are in `⊥`. -/ lemma not_mem_bot (p : P) : p ∉ (⊥ : affine_subspace k P) := set.not_mem_empty p variables (P) /-- The direction of `⊥` is the submodule `⊥`. -/ @[simp] lemma direction_bot : (⊥ : affine_subspace k P).direction = ⊥ := by rw [direction_eq_vector_span, bot_coe, vector_span_def, vsub_empty, submodule.span_empty] variables {k V P} /-- A nonempty affine subspace is `⊤` if and only if its direction is `⊤`. -/ @[simp] lemma direction_eq_top_iff_of_nonempty {s : affine_subspace k P} (h : (s : set P).nonempty) : s.direction = ⊤ ↔ s = ⊤ := begin split, { intro hd, rw ←direction_top k V P at hd, refine ext_of_direction_eq hd _, simp [h] }, { rintro rfl, simp } end /-- The inf of two affine subspaces, coerced to a set, is the intersection of the two sets of points. -/ @[simp] lemma inf_coe (s1 s2 : affine_subspace k P) : ((s1 ⊓ s2) : set P) = s1 ∩ s2 := rfl /-- A point is in the inf of two affine subspaces if and only if it is in both of them. -/ lemma mem_inf_iff (p : P) (s1 s2 : affine_subspace k P) : p ∈ s1 ⊓ s2 ↔ p ∈ s1 ∧ p ∈ s2 := iff.rfl /-- The direction of the inf of two affine subspaces is less than or equal to the inf of their directions. -/ lemma direction_inf (s1 s2 : affine_subspace k P) : (s1 ⊓ s2).direction ≤ s1.direction ⊓ s2.direction := begin repeat { rw [direction_eq_vector_span, vector_span_def] }, exact le_inf (Inf_le_Inf (λ p hp, trans (vsub_self_mono (inter_subset_left _ _)) hp)) (Inf_le_Inf (λ p hp, trans (vsub_self_mono (inter_subset_right _ _)) hp)) end /-- If two affine subspaces have a point in common, the direction of their inf equals the inf of their directions. -/ lemma direction_inf_of_mem {s₁ s₂ : affine_subspace k P} {p : P} (h₁ : p ∈ s₁) (h₂ : p ∈ s₂) : (s₁ ⊓ s₂).direction = s₁.direction ⊓ s₂.direction := begin ext v, rw [submodule.mem_inf, ←vadd_mem_iff_mem_direction v h₁, ←vadd_mem_iff_mem_direction v h₂, ←vadd_mem_iff_mem_direction v ((mem_inf_iff p s₁ s₂).2 ⟨h₁, h₂⟩), mem_inf_iff] end /-- If two affine subspaces have a point in their inf, the direction of their inf equals the inf of their directions. -/ lemma direction_inf_of_mem_inf {s₁ s₂ : affine_subspace k P} {p : P} (h : p ∈ s₁ ⊓ s₂) : (s₁ ⊓ s₂).direction = s₁.direction ⊓ s₂.direction := direction_inf_of_mem ((mem_inf_iff p s₁ s₂).1 h).1 ((mem_inf_iff p s₁ s₂).1 h).2 /-- If one affine subspace is less than or equal to another, the same applies to their directions. -/ lemma direction_le {s1 s2 : affine_subspace k P} (h : s1 ≤ s2) : s1.direction ≤ s2.direction := begin repeat { rw [direction_eq_vector_span, vector_span_def] }, exact vector_span_mono k h end /-- If one nonempty affine subspace is less than another, the same applies to their directions -/ lemma direction_lt_of_nonempty {s1 s2 : affine_subspace k P} (h : s1 < s2) (hn : (s1 : set P).nonempty) : s1.direction < s2.direction := begin cases hn with p hp, rw lt_iff_le_and_exists at h, rcases h with ⟨hle, p2, hp2, hp2s1⟩, rw submodule.lt_iff_le_and_exists, use [direction_le hle, p2 -ᵥ p, vsub_mem_direction hp2 (hle hp)], intro hm, rw vsub_right_mem_direction_iff_mem hp p2 at hm, exact hp2s1 hm end /-- The sup of the directions of two affine subspaces is less than or equal to the direction of their sup. -/ lemma sup_direction_le (s1 s2 : affine_subspace k P) : s1.direction ⊔ s2.direction ≤ (s1 ⊔ s2).direction := begin repeat { rw [direction_eq_vector_span, vector_span_def] }, exact sup_le (Inf_le_Inf (λ p hp, set.subset.trans (vsub_self_mono (le_sup_left : s1 ≤ s1 ⊔ s2)) hp)) (Inf_le_Inf (λ p hp, set.subset.trans (vsub_self_mono (le_sup_right : s2 ≤ s1 ⊔ s2)) hp)) end /-- The sup of the directions of two nonempty affine subspaces with empty intersection is less than the direction of their sup. -/ lemma sup_direction_lt_of_nonempty_of_inter_empty {s1 s2 : affine_subspace k P} (h1 : (s1 : set P).nonempty) (h2 : (s2 : set P).nonempty) (he : (s1 ∩ s2 : set P) = ∅) : s1.direction ⊔ s2.direction < (s1 ⊔ s2).direction := begin cases h1 with p1 hp1, cases h2 with p2 hp2, rw submodule.lt_iff_le_and_exists, use [sup_direction_le s1 s2, p2 -ᵥ p1, vsub_mem_direction ((le_sup_right : s2 ≤ s1 ⊔ s2) hp2) ((le_sup_left : s1 ≤ s1 ⊔ s2) hp1)], intro h, rw submodule.mem_sup at h, rcases h with ⟨v1, hv1, v2, hv2, hv1v2⟩, rw [←sub_eq_zero, sub_eq_add_neg, neg_vsub_eq_vsub_rev, add_comm v1, add_assoc, ←vadd_vsub_assoc, ←neg_neg v2, add_comm, ←sub_eq_add_neg, ←vsub_vadd_eq_vsub_sub, vsub_eq_zero_iff_eq] at hv1v2, refine set.nonempty.ne_empty _ he, use [v1 +ᵥ p1, vadd_mem_of_mem_direction hv1 hp1], rw hv1v2, exact vadd_mem_of_mem_direction (submodule.neg_mem _ hv2) hp2 end /-- If the directions of two nonempty affine subspaces span the whole module, they have nonempty intersection. -/ lemma inter_nonempty_of_nonempty_of_sup_direction_eq_top {s1 s2 : affine_subspace k P} (h1 : (s1 : set P).nonempty) (h2 : (s2 : set P).nonempty) (hd : s1.direction ⊔ s2.direction = ⊤) : ((s1 : set P) ∩ s2).nonempty := begin by_contradiction h, rw set.not_nonempty_iff_eq_empty at h, have hlt := sup_direction_lt_of_nonempty_of_inter_empty h1 h2 h, rw hd at hlt, exact not_top_lt hlt end /-- If the directions of two nonempty affine subspaces are complements of each other, they intersect in exactly one point. -/ lemma inter_eq_singleton_of_nonempty_of_is_compl {s1 s2 : affine_subspace k P} (h1 : (s1 : set P).nonempty) (h2 : (s2 : set P).nonempty) (hd : is_compl s1.direction s2.direction) : ∃ p, (s1 : set P) ∩ s2 = {p} := begin cases inter_nonempty_of_nonempty_of_sup_direction_eq_top h1 h2 hd.sup_eq_top with p hp, use p, ext q, rw set.mem_singleton_iff, split, { rintros ⟨hq1, hq2⟩, have hqp : q -ᵥ p ∈ s1.direction ⊓ s2.direction := ⟨vsub_mem_direction hq1 hp.1, vsub_mem_direction hq2 hp.2⟩, rwa [hd.inf_eq_bot, submodule.mem_bot, vsub_eq_zero_iff_eq] at hqp }, { exact λ h, h.symm ▸ hp } end /-- Coercing a subspace to a set then taking the affine span produces the original subspace. -/ @[simp] lemma affine_span_coe (s : affine_subspace k P) : affine_span k (s : set P) = s := begin refine le_antisymm _ (subset_span_points _ _), rintros p ⟨p1, hp1, v, hv, rfl⟩, exact vadd_mem_of_mem_direction hv hp1 end end affine_subspace section affine_space' variables (k : Type*) {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] [affine_space V P] variables {ι : Type*} include V open affine_subspace set /-- The `vector_span` is the span of the pairwise subtractions with a given point on the left. -/ lemma vector_span_eq_span_vsub_set_left {s : set P} {p : P} (hp : p ∈ s) : vector_span k s = submodule.span k ((-ᵥ) p '' s) := begin rw vector_span_def, refine le_antisymm _ (submodule.span_mono _), { rw submodule.span_le, rintros v ⟨p1, p2, hp1, hp2, hv⟩, rw ←vsub_sub_vsub_cancel_left p1 p2 p at hv, rw [←hv, submodule.mem_coe, submodule.mem_span], exact λ m hm, submodule.sub_mem _ (hm ⟨p2, hp2, rfl⟩) (hm ⟨p1, hp1, rfl⟩) }, { rintros v ⟨p2, hp2, hv⟩, exact ⟨p, p2, hp, hp2, hv⟩ } end /-- The `vector_span` is the span of the pairwise subtractions with a given point on the right. -/ lemma vector_span_eq_span_vsub_set_right {s : set P} {p : P} (hp : p ∈ s) : vector_span k s = submodule.span k ((-ᵥ p) '' s) := begin rw vector_span_def, refine le_antisymm _ (submodule.span_mono _), { rw submodule.span_le, rintros v ⟨p1, p2, hp1, hp2, hv⟩, rw ←vsub_sub_vsub_cancel_right p1 p2 p at hv, rw [←hv, submodule.mem_coe, submodule.mem_span], exact λ m hm, submodule.sub_mem _ (hm ⟨p1, hp1, rfl⟩) (hm ⟨p2, hp2, rfl⟩) }, { rintros v ⟨p2, hp2, hv⟩, exact ⟨p2, p, hp2, hp, hv⟩ } end /-- The `vector_span` is the span of the pairwise subtractions with a given point on the left, excluding the subtraction of that point from itself. -/ lemma vector_span_eq_span_vsub_set_left_ne {s : set P} {p : P} (hp : p ∈ s) : vector_span k s = submodule.span k ((-ᵥ) p '' (s \ {p})) := begin conv_lhs { rw [vector_span_eq_span_vsub_set_left k hp, ←set.insert_eq_of_mem hp, ←set.insert_diff_singleton, set.image_insert_eq] }, simp [submodule.span_insert_eq_span] end /-- The `vector_span` is the span of the pairwise subtractions with a given point on the right, excluding the subtraction of that point from itself. -/ lemma vector_span_eq_span_vsub_set_right_ne {s : set P} {p : P} (hp : p ∈ s) : vector_span k s = submodule.span k ((-ᵥ p) '' (s \ {p})) := begin conv_lhs { rw [vector_span_eq_span_vsub_set_right k hp, ←set.insert_eq_of_mem hp, ←set.insert_diff_singleton, set.image_insert_eq] }, simp [submodule.span_insert_eq_span] end /-- The `vector_span` of the image of a function is the span of the pairwise subtractions with a given point on the left, excluding the subtraction of that point from itself. -/ lemma vector_span_image_eq_span_vsub_set_left_ne (p : ι → P) {s : set ι} {i : ι} (hi : i ∈ s) : vector_span k (p '' s) = submodule.span k ((-ᵥ) (p i) '' (p '' (s \ {i}))) := begin conv_lhs { rw [vector_span_eq_span_vsub_set_left k (set.mem_image_of_mem p hi), ←set.insert_eq_of_mem hi, ←set.insert_diff_singleton, set.image_insert_eq, set.image_insert_eq] }, simp [submodule.span_insert_eq_span] end /-- The `vector_span` of the image of a function is the span of the pairwise subtractions with a given point on the right, excluding the subtraction of that point from itself. -/ lemma vector_span_image_eq_span_vsub_set_right_ne (p : ι → P) {s : set ι} {i : ι} (hi : i ∈ s) : vector_span k (p '' s) = submodule.span k ((-ᵥ (p i)) '' (p '' (s \ {i}))) := begin conv_lhs { rw [vector_span_eq_span_vsub_set_right k (set.mem_image_of_mem p hi), ←set.insert_eq_of_mem hi, ←set.insert_diff_singleton, set.image_insert_eq, set.image_insert_eq] }, simp [submodule.span_insert_eq_span] end /-- The `vector_span` of an indexed family is the span of the pairwise subtractions with a given point on the left. -/ lemma vector_span_range_eq_span_range_vsub_left (p : ι → P) (i0 : ι) : vector_span k (set.range p) = submodule.span k (set.range (λ (i : ι), p i0 -ᵥ p i)) := by rw [vector_span_eq_span_vsub_set_left k (set.mem_range_self i0), ←set.range_comp] /-- The `vector_span` of an indexed family is the span of the pairwise subtractions with a given point on the right. -/ lemma vector_span_range_eq_span_range_vsub_right (p : ι → P) (i0 : ι) : vector_span k (set.range p) = submodule.span k (set.range (λ (i : ι), p i -ᵥ p i0)) := by rw [vector_span_eq_span_vsub_set_right k (set.mem_range_self i0), ←set.range_comp] /-- The `vector_span` of an indexed family is the span of the pairwise subtractions with a given point on the left, excluding the subtraction of that point from itself. -/ lemma vector_span_range_eq_span_range_vsub_left_ne (p : ι → P) (i₀ : ι) : vector_span k (set.range p) = submodule.span k (set.range (λ (i : {x // x ≠ i₀}), p i₀ -ᵥ p i)) := begin rw [←set.image_univ, vector_span_image_eq_span_vsub_set_left_ne k _ (set.mem_univ i₀)], congr' with v, simp only [set.mem_range, set.mem_image, set.mem_diff, set.mem_singleton_iff, subtype.exists, subtype.coe_mk], split, { rintros ⟨x, ⟨i₁, ⟨⟨hi₁u, hi₁⟩, rfl⟩⟩, hv⟩, exact ⟨i₁, hi₁, hv⟩ }, { exact λ ⟨i₁, hi₁, hv⟩, ⟨p i₁, ⟨i₁, ⟨set.mem_univ _, hi₁⟩, rfl⟩, hv⟩ } end /-- The `vector_span` of an indexed family is the span of the pairwise subtractions with a given point on the right, excluding the subtraction of that point from itself. -/ lemma vector_span_range_eq_span_range_vsub_right_ne (p : ι → P) (i₀ : ι) : vector_span k (set.range p) = submodule.span k (set.range (λ (i : {x // x ≠ i₀}), p i -ᵥ p i₀)) := begin rw [←set.image_univ, vector_span_image_eq_span_vsub_set_right_ne k _ (set.mem_univ i₀)], congr' with v, simp only [set.mem_range, set.mem_image, set.mem_diff, set.mem_singleton_iff, subtype.exists, subtype.coe_mk], split, { rintros ⟨x, ⟨i₁, ⟨⟨hi₁u, hi₁⟩, rfl⟩⟩, hv⟩, exact ⟨i₁, hi₁, hv⟩ }, { exact λ ⟨i₁, hi₁, hv⟩, ⟨p i₁, ⟨i₁, ⟨set.mem_univ _, hi₁⟩, rfl⟩, hv⟩ } end /-- The affine span of a set is nonempty if and only if that set is. -/ lemma affine_span_nonempty (s : set P) : (affine_span k s : set P).nonempty ↔ s.nonempty := span_points_nonempty k s /-- The affine span of a nonempty set is nonempty. -/ instance {s : set P} [nonempty s] : nonempty (affine_span k s) := ((affine_span_nonempty k s).mpr (nonempty_subtype.mp ‹_›)).to_subtype variables {k} /-- Suppose a set of vectors spans `V`. Then a point `p`, together with those vectors added to `p`, spans `P`. -/ lemma affine_span_singleton_union_vadd_eq_top_of_span_eq_top {s : set V} (p : P) (h : submodule.span k (set.range (coe : s → V)) = ⊤) : affine_span k ({p} ∪ (λ v, v +ᵥ p) '' s) = ⊤ := begin convert ext_of_direction_eq _ ⟨p, mem_affine_span k (set.mem_union_left _ (set.mem_singleton _)), mem_top k V p⟩, rw [direction_affine_span, direction_top, vector_span_eq_span_vsub_set_right k ((set.mem_union_left _ (set.mem_singleton _)) : p ∈ _), eq_top_iff, ←h], apply submodule.span_mono, rintros v ⟨v', rfl⟩, use (v' : V) +ᵥ p, simp end variables (k) /-- `affine_span` is monotone. -/ lemma affine_span_mono {s₁ s₂ : set P} (h : s₁ ⊆ s₂) : affine_span k s₁ ≤ affine_span k s₂ := span_points_subset_coe_of_subset_coe (set.subset.trans h (subset_affine_span k _)) /-- Taking the affine span of a set, adding a point and taking the span again produces the same results as adding the point to the set and taking the span. -/ lemma affine_span_insert_affine_span (p : P) (ps : set P) : affine_span k (insert p (affine_span k ps : set P)) = affine_span k (insert p ps) := by rw [set.insert_eq, set.insert_eq, span_union, span_union, affine_span_coe] /-- If a point is in the affine span of a set, adding it to that set does not change the affine span. -/ lemma affine_span_insert_eq_affine_span {p : P} {ps : set P} (h : p ∈ affine_span k ps) : affine_span k (insert p ps) = affine_span k ps := begin rw ←mem_coe at h, rw [←affine_span_insert_affine_span, set.insert_eq_of_mem h, affine_span_coe] end end affine_space' namespace affine_subspace variables {k : Type*} {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] [affine_space V P] include V /-- The direction of the sup of two nonempty affine subspaces is the sup of the two directions and of any one difference between points in the two subspaces. -/ lemma direction_sup {s1 s2 : affine_subspace k P} {p1 p2 : P} (hp1 : p1 ∈ s1) (hp2 : p2 ∈ s2) : (s1 ⊔ s2).direction = s1.direction ⊔ s2.direction ⊔ k ∙ (p2 -ᵥ p1) := begin refine le_antisymm _ _, { change (affine_span k ((s1 : set P) ∪ s2)).direction ≤ _, rw ←mem_coe at hp1, rw [direction_affine_span, vector_span_eq_span_vsub_set_right k (set.mem_union_left _ hp1), submodule.span_le], rintros v ⟨p3, hp3, rfl⟩, cases hp3, { rw [sup_assoc, sup_comm, submodule.mem_coe, submodule.mem_sup], use [0, submodule.zero_mem _, p3 -ᵥ p1, vsub_mem_direction hp3 hp1], rw zero_add }, { rw [sup_assoc, submodule.mem_coe, submodule.mem_sup], use [0, submodule.zero_mem _, p3 -ᵥ p1], rw [and_comm, zero_add], use rfl, rw [←vsub_add_vsub_cancel p3 p2 p1, submodule.mem_sup], use [p3 -ᵥ p2, vsub_mem_direction hp3 hp2, p2 -ᵥ p1, submodule.mem_span_singleton_self _] } }, { refine sup_le (sup_direction_le _ _) _, rw [direction_eq_vector_span, vector_span_def], exact Inf_le_Inf (λ p hp, set.subset.trans (set.singleton_subset_iff.2 (vsub_mem_vsub (mem_span_points k p2 _ (set.mem_union_right _ hp2)) (mem_span_points k p1 _ (set.mem_union_left _ hp1)))) hp) } end /-- The direction of the span of the result of adding a point to a nonempty affine subspace is the sup of the direction of that subspace and of any one difference between that point and a point in the subspace. -/ lemma direction_affine_span_insert {s : affine_subspace k P} {p1 p2 : P} (hp1 : p1 ∈ s) : (affine_span k (insert p2 (s : set P))).direction = submodule.span k {p2 -ᵥ p1} ⊔ s.direction := begin rw [sup_comm, ←set.union_singleton, ←coe_affine_span_singleton k V p2], change (s ⊔ affine_span k {p2}).direction = _, rw [direction_sup hp1 (mem_affine_span k (set.mem_singleton _)), direction_affine_span], simp end /-- Given a point `p1` in an affine subspace `s`, and a point `p2`, a point `p` is in the span of `s` with `p2` added if and only if it is a multiple of `p2 -ᵥ p1` added to a point in `s`. -/ lemma mem_affine_span_insert_iff {s : affine_subspace k P} {p1 : P} (hp1 : p1 ∈ s) (p2 p : P) : p ∈ affine_span k (insert p2 (s : set P)) ↔ ∃ (r : k) (p0 : P) (hp0 : p0 ∈ s), p = r • (p2 -ᵥ p1 : V) +ᵥ p0 := begin rw ←mem_coe at hp1, rw [←vsub_right_mem_direction_iff_mem (mem_affine_span k (set.mem_insert_of_mem _ hp1)), direction_affine_span_insert hp1, submodule.mem_sup], split, { rintros ⟨v1, hv1, v2, hv2, hp⟩, rw submodule.mem_span_singleton at hv1, rcases hv1 with ⟨r, rfl⟩, use [r, v2 +ᵥ p1, vadd_mem_of_mem_direction hv2 hp1], symmetry' at hp, rw [←sub_eq_zero_iff_eq, ←vsub_vadd_eq_vsub_sub, vsub_eq_zero_iff_eq] at hp, rw [hp, vadd_assoc] }, { rintros ⟨r, p3, hp3, rfl⟩, use [r • (p2 -ᵥ p1), submodule.mem_span_singleton.2 ⟨r, rfl⟩, p3 -ᵥ p1, vsub_mem_direction hp3 hp1], rw [vadd_vsub_assoc, add_comm] } end end affine_subspace
b0d941d3752b33e1da489a0cc157bbe0cec3b8ba
be5348f86d661459153802318209304b793c0e2a
/src/del_root.lean
5fb885ae06332bbf734ecff6c5838c9d04135787
[]
no_license
reglayass/lean-avl
6b758c7708bdb3316b1b97ada3e3f259b49da58a
c7bffa75d7548e5ff8cdd7d69f5a58499f883df1
refs/heads/master
1,692,297,536,477
1,633,946,864,000
1,633,946,864,000
340,881,572
4
0
null
null
null
null
UTF-8
Lean
false
false
3,810
lean
import definitions rotations shrink forall_keys tactic.linarith tactic.induction set_option pp.generalized_field_notation false universe u namespace del_root_lemmas open btree rotation_lemmas shrink_lemmas forall_keys_lemmas variables {α : Type u} lemma del_root_del_root_view (t : btree α) : del_root_view t (del_root t) := begin cases t, case empty { exact del_root_view.empty, }, case node : l k a r { dsimp [del_root], cases h : shrink l, case none { dsimp [del_root._match_1], apply del_root_view.nonempty_empty; assumption, }, case some { rcases val with ⟨x, a', sh⟩, dsimp only [del_root._match_1], by_cases h' : height r > height sh + 1, { simp only [if_pos h'], apply del_root_view.nonempty_nonempty₁; assumption, }, { simp only [if_neg h'], apply del_root_view.nonempty_nonempty₂; try { assumption, }, linarith, }, }, }, end /- Auxiliary del_root lemma for forall_delete -/ lemma forall_del_root (t : btree α) (k : nat) (p : nat → nat → Prop) : forall_keys p k t → forall_keys p k (del_root t) := begin intro h₁, cases t, case empty { simp [del_root], exact h₁, }, case node : l x v r { cases' del_root_del_root_view (node l x v r), case nonempty_empty { unfold forall_keys at h₁ ⊢, intros k' h₂, apply h₁, simp [bound], tauto, }, case nonempty_nonempty₁ { apply forall_rotate_left, rw ← forall_keys_char, repeat { split }, { rw ← forall_keys_char at h₁, cases_matching* (_ ∧ _), apply forall_shrink_aux_1 (and.intro h₁_left h), }, { rw ← forall_keys_char at h₁, cases_matching* (_ ∧ _), apply forall_shrink_aux_2 (and.intro h₁_left h), }, { unfold forall_keys at h₁ ⊢, intros k' h₂, apply h₁, simp [bound], tauto, }, }, case nonempty_nonempty₂ { rw ← forall_keys_char, repeat { split }, { rw ← forall_keys_char at h₁, cases_matching* (_ ∧ _), apply forall_shrink_aux_1 (and.intro h₁_left h), }, { rw ← forall_keys_char at h₁, cases_matching* (_ ∧ _), apply forall_shrink_aux_2 (and.intro h₁_left h), }, { unfold forall_keys at h₁ ⊢, intros k' h₂, apply h₁, simp [bound], tauto, }, }, }, end /- Deleting a root of a tree preserves the tree order -/ lemma del_root_ordered (t : btree α) : ordered t → ordered (del_root t) := begin intro h₁, cases t, case empty { simp [del_root, ordered], }, case node : tl tk ta tr { simp [ordered] at h₁, cases_matching* (_ ∧ _), cases' del_root_del_root_view (node tl tk ta tr), case nonempty_empty { assumption, }, case nonempty_nonempty₁ { apply rotate_left_ordered, rw ordered, repeat { split }, { apply shrink_ordered_aux_1 (and.intro h₁_left h), }, { assumption, }, { apply shrink_ordered_aux_2 (and.intro h₁_left h), }, { apply forall_keys_trans _ (<) k, { apply forall_shrink_aux_2 (and.intro h₁_right_right_left h), }, { apply trans, }, { assumption, }, }, }, case nonempty_nonempty₂ { rw ordered, repeat { split }, { apply shrink_ordered_aux_1 (and.intro h₁_left h), }, { assumption, }, { apply shrink_ordered_aux_2 (and.intro h₁_left h), }, { apply forall_keys_trans _ (<) k, { apply forall_shrink_aux_2 (and.intro h₁_right_right_left h), }, { apply trans, }, { assumption, }, }, }, }, end end del_root_lemmas
8b11514fefe60758f49a5c606bc56658652c981e
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/fieldNamesWithMinus.lean
391cecdeac1cc9eef0e9b64c57190fe3737c3f95
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
210
lean
structure Minus where «i-love-lisp» : Bool #check Minus.«i-love-lisp» #check { «i-love-lisp» := true : Minus } #check fun (x : Minus) => x.«i-love-lisp» #check fun (x : Minus) => (x).«i-love-lisp»
8205732f54addaee32cdd7b195452785f43287bd
367134ba5a65885e863bdc4507601606690974c1
/src/data/complex/exponential_bounds.lean
1978875b8f5d958a2ac6b9b25b3ece5b98075abe
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
1,744
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Joseph Myers -/ import data.complex.exponential /-! # Bounds on specific values of the exponential -/ namespace real local notation `abs'` := _root_.abs open is_absolute_value finset cau_seq complex lemma exp_one_near_10 : abs' (exp 1 - 2244083/825552) ≤ 1/10^10 := begin apply exp_approx_start, iterate 13 { refine exp_1_approx_succ_eq (by norm_num1; refl) (by norm_cast; refl) _ }, norm_num1, refine exp_approx_end' _ (by norm_num1; refl) _ (by norm_cast; refl) (by simp) _, rw [_root_.abs_one, abs_of_pos]; norm_num1, end lemma exp_one_near_20 : abs' (exp 1 - 363916618873/133877442384) ≤ 1/10^20 := begin apply exp_approx_start, iterate 21 { refine exp_1_approx_succ_eq (by norm_num1; refl) (by norm_cast; refl) _ }, norm_num1, refine exp_approx_end' _ (by norm_num1; refl) _ (by norm_cast; refl) (by simp) _, rw [_root_.abs_one, abs_of_pos]; norm_num1, end lemma exp_one_gt_271828182 : 2.71828182 < exp 1 := lt_of_lt_of_le (by norm_num) (sub_le.1 (abs_sub_le_iff.1 exp_one_near_10).2) lemma exp_one_lt_271828183 : exp 1 < 2.71828183 := lt_of_le_of_lt (sub_le_iff_le_add.1 (abs_sub_le_iff.1 exp_one_near_10).1) (by norm_num) lemma exp_neg_one_gt_0367879441 : 0.367879441 < exp (-1) := begin rw [exp_neg, lt_inv _ (exp_pos _)], refine lt_of_le_of_lt (sub_le_iff_le_add.1 (abs_sub_le_iff.1 exp_one_near_10).1) _, all_goals {norm_num}, end lemma exp_neg_one_lt_0367879442 : exp (-1) < 0.367879442 := begin rw [exp_neg, inv_lt (exp_pos _)], refine lt_of_lt_of_le _ (sub_le.1 (abs_sub_le_iff.1 exp_one_near_10).2), all_goals {norm_num}, end end real
16fff35acc1666b7c1e66aee0475ae7384ee7caf
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/library/data/list/sort.lean
c41838c026896a7016115a4d225d6905782083c7
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,604
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 Naive sort for lists -/ import data.list.comb data.list.set data.list.perm data.list.sorted logic.connectives algebra.order namespace list open decidable nat variable {A : Type} variable (R : A → A → Prop) variable [decR : decidable_rel R] include decR definition min_core : list A → A → A | [] a := a | (b::l) a := if R b a then min_core l b else min_core l a definition min : Π (l : list A), l ≠ nil → A | [] h := absurd rfl h | (a::l) h := min_core R l a variable [decA : decidable_eq A] include decA variable {R} variables (to : total R) (tr : transitive R) (rf : reflexive R) lemma min_core_lemma : ∀ {b l} a, b ∈ l ∨ b = a → R (min_core R l a) b | b [] a h := or.elim h (suppose b ∈ [], absurd this !not_mem_nil) (suppose b = a, assert R a a, from rf a, begin subst b, unfold min_core, assumption end) | b (c::l) a h := or.elim h (suppose b ∈ c :: l, or.elim (eq_or_mem_of_mem_cons this) (suppose b = c, or.elim (em (R c a)) (suppose R c a, assert R (min_core R l b) b, from min_core_lemma _ (or.inr rfl), begin unfold min_core, rewrite [if_pos `R c a`], subst c, assumption end) (suppose ¬ R c a, assert R a c, from or_resolve_right (to c a) this, assert R (min_core R l a) a, from min_core_lemma _ (or.inr rfl), assert R (min_core R l a) c, from tr this `R a c`, begin unfold min_core, rewrite [if_neg `¬ R c a`], subst b, exact `R (min_core R l a) c` end)) (suppose b ∈ l, or.elim (em (R c a)) (suppose R c a, assert R (min_core R l c) b, from min_core_lemma _ (or.inl `b ∈ l`), begin unfold min_core, rewrite [if_pos `R c a`], assumption end) (suppose ¬ R c a, assert R (min_core R l a) b, from min_core_lemma _ (or.inl `b ∈ l`), begin unfold min_core, rewrite [if_neg `¬ R c a`], assumption end))) (suppose b = a, assert R (min_core R l a) b, from min_core_lemma _ (or.inr this), or.elim (em (R c a)) (suppose R c a, assert R (min_core R l c) c, from min_core_lemma _ (or.inr rfl), assert R (min_core R l c) a, from tr this `R c a`, begin unfold min_core, rewrite [if_pos `R c a`], subst b, exact `R (min_core R l c) a` end) (suppose ¬ R c a, begin unfold min_core, rewrite [if_neg `¬ R c a`], assumption end)) lemma min_core_le_of_mem {b : A} {l : list A} (a : A) : b ∈ l → R (min_core R l a) b := assume h : b ∈ l, min_core_lemma to tr rf a (or.inl h) lemma min_core_le {l : list A} (a : A) : R (min_core R l a) a := min_core_lemma to tr rf a (or.inr rfl) lemma min_lemma : ∀ {l} (h : l ≠ nil), all l (R (min R l h)) | [] h := absurd rfl h | (b::l) h := all_of_forall (take x, suppose x ∈ b::l, or.elim (eq_or_mem_of_mem_cons this) (suppose x = b, assert R (min_core R l b) b, from min_core_le to tr rf b, begin subst x, unfold min, assumption end) (suppose x ∈ l, assert R (min_core R l b) x, from min_core_le_of_mem to tr rf _ this, begin unfold min, assumption end)) variable (R) lemma min_core_mem : ∀ l a, min_core R l a ∈ l ∨ min_core R l a = a | [] a := or.inr rfl | (b::l) a := or.elim (em (R b a)) (suppose R b a, begin unfold min_core, rewrite [if_pos `R b a`], apply or.elim (min_core_mem l b), suppose min_core R l b ∈ l, or.inl (mem_cons_of_mem _ this), suppose min_core R l b = b, by rewrite this; exact or.inl !mem_cons end) (suppose ¬ R b a, begin unfold min_core, rewrite [if_neg `¬ R b a`], apply or.elim (min_core_mem l a), suppose min_core R l a ∈ l, or.inl (mem_cons_of_mem _ this), suppose min_core R l a = a, or.inr this end) lemma min_mem : ∀ (l : list A) (h : l ≠ nil), min R l h ∈ l | [] h := absurd rfl h | (a::l) h := begin unfold min, apply or.elim (min_core_mem R l a), suppose min_core R l a ∈ l, mem_cons_of_mem _ this, suppose min_core R l a = a, by rewrite this; apply mem_cons end omit decR private lemma ne_nil {l : list A} {n : nat} : length l = succ n → l ≠ nil := assume h₁ h₂, by rewrite h₂ at h₁; contradiction include decR lemma sort_aux_lemma {l n} (h : length l = succ n) : length (erase (min R l (ne_nil h)) l) = n := have min R l _ ∈ l, from min_mem R l (ne_nil h), assert length (erase (min R l _) l) = pred (length l), from length_erase_of_mem this, by rewrite h at this; exact this definition sort_aux : Π (n : nat) (l : list A), length l = n → list A | 0 l h := [] | (succ n) l h := let m := min R l (ne_nil h) in let l₁ := erase m l in m :: sort_aux n l₁ (sort_aux_lemma R h) definition sort (l : list A) : list A := sort_aux R (length l) l rfl open perm lemma sort_aux_perm : ∀ {n : nat} {l : list A} (h : length l = n), sort_aux R n l h ~ l | 0 l h := by rewrite [↑sort_aux, eq_nil_of_length_eq_zero h] | (succ n) l h := let m := min R l (ne_nil h) in assert leq : length (erase m l) = n, from sort_aux_lemma R h, calc m :: sort_aux R n (erase m l) leq ~ m :: erase m l : perm.skip m (sort_aux_perm leq) ... ~ l : perm_erase (min_mem _ _ _) lemma sort_perm (l : list A) : sort R l ~ l := sort_aux_perm R rfl lemma strongly_sorted_sort_aux : ∀ {n : nat} {l : list A} (h : length l = n), strongly_sorted R (sort_aux R n l h) | 0 l h := !strongly_sorted.base | (succ n) l h := let m := min R l (ne_nil h) in assert leq : length (erase m l) = n, from sort_aux_lemma R h, assert ss : strongly_sorted R (sort_aux R n (erase m l) leq), from strongly_sorted_sort_aux leq, assert all l (R m), from min_lemma to tr rf (ne_nil h), assert hall : all (sort_aux R n (erase m l) leq) (R m), from all_of_forall (take x, suppose x ∈ sort_aux R n (erase m l) leq, have x ∈ erase m l, from mem_perm (sort_aux_perm R leq) this, have x ∈ l, from mem_of_mem_erase this, show R m x, from of_mem_of_all this `all l (R m)`), strongly_sorted.step hall ss variable {R} lemma strongly_sorted_sort_core (to : total R) (tr : transitive R) (rf : reflexive R) (l : list A) : strongly_sorted R (sort R l) := @strongly_sorted_sort_aux _ _ _ _ to tr rf (length l) l rfl lemma sort_eq_of_perm_core {l₁ l₂ : list A} (to : total R) (tr : transitive R) (rf : reflexive R) (asy : anti_symmetric R) (h : l₁ ~ l₂) : sort R l₁ = sort R l₂ := have s₁ : sorted R (sort R l₁), from sorted_of_strongly_sorted (strongly_sorted_sort_core to tr rf l₁), have s₂ : sorted R (sort R l₂), from sorted_of_strongly_sorted (strongly_sorted_sort_core to tr rf l₂), have p : sort R l₁ ~ sort R l₂, from calc sort R l₁ ~ l₁ : sort_perm ... ~ l₂ : h ... ~ sort R l₂ : sort_perm, eq_of_sorted_of_perm tr asy p s₁ s₂ section open algebra omit decR lemma strongly_sorted_sort [ord : decidable_linear_order A] (l : list A) : strongly_sorted le (sort le l) := strongly_sorted_sort_core le.total (@le.trans A _) le.refl l lemma sort_eq_of_perm {l₁ l₂ : list A} [ord : decidable_linear_order A] (h : l₁ ~ l₂) : sort le l₁ = sort le l₂ := sort_eq_of_perm_core le.total (@le.trans A _) le.refl (@le.antisymm A _) h end end list
5b186642ce28e709be62d241aac0c3e908276763
9028d228ac200bbefe3a711342514dd4e4458bff
/src/analysis/normed_space/operator_norm.lean
9d976fc58c16837d3c357988bd19efdab5bbe04f
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
41,446
lean
/- Copyright (c) 2019 Jan-David Salchow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jan-David Salchow, Sébastien Gouëzel, Jean Lo -/ import linear_algebra.finite_dimensional import analysis.normed_space.riesz_lemma import analysis.asymptotics /-! # Operator norm on the space of continuous linear maps Define the operator norm on the space of continuous linear maps between normed spaces, and prove its basic properties. In particular, show that this space is itself a normed space. -/ noncomputable theory open_locale classical variables {𝕜 : Type*} {E : Type*} {F : Type*} {G : Type*} [normed_group E] [normed_group F] [normed_group G] open metric continuous_linear_map lemma exists_pos_bound_of_bound {f : E → F} (M : ℝ) (h : ∀x, ∥f x∥ ≤ M * ∥x∥) : ∃ N, 0 < N ∧ ∀x, ∥f x∥ ≤ N * ∥x∥ := ⟨max M 1, lt_of_lt_of_le zero_lt_one (le_max_right _ _), λx, calc ∥f x∥ ≤ M * ∥x∥ : h x ... ≤ max M 1 * ∥x∥ : mul_le_mul_of_nonneg_right (le_max_left _ _) (norm_nonneg _) ⟩ section normed_field /- Most statements in this file require the field to be non-discrete, as this is necessary to deduce an inequality `∥f x∥ ≤ C ∥x∥` from the continuity of f. However, the other direction always holds. In this section, we just assume that `𝕜` is a normed field. In the remainder of the file, it will be non-discrete. -/ variables [normed_field 𝕜] [normed_space 𝕜 E] [normed_space 𝕜 F] (f : E →ₗ[𝕜] F) lemma linear_map.lipschitz_of_bound (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : lipschitz_with (nnreal.of_real C) f := lipschitz_with.of_dist_le' $ λ x y, by simpa only [dist_eq_norm, f.map_sub] using h (x - y) theorem linear_map.antilipschitz_of_bound {K : nnreal} (h : ∀ x, ∥x∥ ≤ K * ∥f x∥) : antilipschitz_with K f := antilipschitz_with.of_le_mul_dist $ λ x y, by simpa only [dist_eq_norm, f.map_sub] using h (x - y) lemma linear_map.uniform_continuous_of_bound (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : uniform_continuous f := (f.lipschitz_of_bound C h).uniform_continuous lemma linear_map.continuous_of_bound (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : continuous f := (f.lipschitz_of_bound C h).continuous /-- Construct a continuous linear map from a linear map and a bound on this linear map. The fact that the norm of the continuous linear map is then controlled is given in `linear_map.mk_continuous_norm_le`. -/ def linear_map.mk_continuous (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : E →L[𝕜] F := ⟨f, linear_map.continuous_of_bound f C h⟩ /-- Reinterpret a linear map `𝕜 →ₗ[𝕜] E` as a continuous linear map. This construction is generalized to the case of any finite dimensional domain in `linear_map.to_continuous_linear_map`. -/ def linear_map.to_continuous_linear_map₁ (f : 𝕜 →ₗ[𝕜] E) : 𝕜 →L[𝕜] E := f.mk_continuous (∥f 1∥) $ λ x, le_of_eq $ by { conv_lhs { rw ← mul_one x }, rw [← smul_eq_mul, f.map_smul, norm_smul, mul_comm] } /-- Construct a continuous linear map from a linear map and the existence of a bound on this linear map. If you have an explicit bound, use `linear_map.mk_continuous` instead, as a norm estimate will follow automatically in `linear_map.mk_continuous_norm_le`. -/ def linear_map.mk_continuous_of_exists_bound (h : ∃C, ∀x, ∥f x∥ ≤ C * ∥x∥) : E →L[𝕜] F := ⟨f, let ⟨C, hC⟩ := h in linear_map.continuous_of_bound f C hC⟩ lemma continuous_of_linear_of_bound {f : E → F} (h_add : ∀ x y, f (x + y) = f x + f y) (h_smul : ∀ (c : 𝕜) x, f (c • x) = c • f x) {C : ℝ} (h_bound : ∀ x, ∥f x∥ ≤ C*∥x∥) : continuous f := let φ : E →ₗ[𝕜] F := ⟨f, h_add, h_smul⟩ in φ.continuous_of_bound C h_bound @[simp, norm_cast] lemma linear_map.mk_continuous_coe (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : ((f.mk_continuous C h) : E →ₗ[𝕜] F) = f := rfl @[simp] lemma linear_map.mk_continuous_apply (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) (x : E) : f.mk_continuous C h x = f x := rfl @[simp, norm_cast] lemma linear_map.mk_continuous_of_exists_bound_coe (h : ∃C, ∀x, ∥f x∥ ≤ C * ∥x∥) : ((f.mk_continuous_of_exists_bound h) : E →ₗ[𝕜] F) = f := rfl @[simp] lemma linear_map.mk_continuous_of_exists_bound_apply (h : ∃C, ∀x, ∥f x∥ ≤ C * ∥x∥) (x : E) : f.mk_continuous_of_exists_bound h x = f x := rfl @[simp] lemma linear_map.to_continuous_linear_map₁_coe (f : 𝕜 →ₗ[𝕜] E) : (f.to_continuous_linear_map₁ : 𝕜 →ₗ[𝕜] E) = f := rfl @[simp] lemma linear_map.to_continuous_linear_map₁_apply (f : 𝕜 →ₗ[𝕜] E) (x) : f.to_continuous_linear_map₁ x = f x := rfl lemma linear_map.continuous_iff_is_closed_ker {f : E →ₗ[𝕜] 𝕜} : continuous f ↔ is_closed (f.ker : set E) := begin -- the continuity of f obviously implies that its kernel is closed refine ⟨λh, (continuous_iff_is_closed.1 h) {0} (t1_space.t1 0), λh, _⟩, -- for the other direction, we assume that the kernel is closed by_cases hf : ∀x, x ∈ f.ker, { -- if `f = 0`, its continuity is obvious have : (f : E → 𝕜) = (λx, 0), by { ext x, simpa using hf x }, rw this, exact continuous_const }, { /- if `f` is not zero, we use an element `x₀ ∉ ker f` such that `∥x₀∥ ≤ 2 ∥x₀ - y∥` for all `y ∈ ker f`, given by Riesz's lemma, and prove that `2 ∥f x₀∥ / ∥x₀∥` gives a bound on the operator norm of `f`. For this, start from an arbitrary `x` and note that `y = x₀ - (f x₀ / f x) x` belongs to the kernel of `f`. Applying the above inequality to `x₀` and `y` readily gives the conclusion. -/ push_neg at hf, let r : ℝ := (2 : ℝ)⁻¹, have : 0 ≤ r, by norm_num [r], have : r < 1, by norm_num [r], obtain ⟨x₀, x₀ker, h₀⟩ : ∃ (x₀ : E), x₀ ∉ f.ker ∧ ∀ y ∈ linear_map.ker f, r * ∥x₀∥ ≤ ∥x₀ - y∥, from riesz_lemma h hf this, have : x₀ ≠ 0, { assume h, have : x₀ ∈ f.ker, by { rw h, exact (linear_map.ker f).zero_mem }, exact x₀ker this }, have rx₀_ne_zero : r * ∥x₀∥ ≠ 0, by { simp [norm_eq_zero, this], norm_num }, have : ∀x, ∥f x∥ ≤ (((r * ∥x₀∥)⁻¹) * ∥f x₀∥) * ∥x∥, { assume x, by_cases hx : f x = 0, { rw [hx, norm_zero], apply_rules [mul_nonneg, norm_nonneg, inv_nonneg.2] }, { let y := x₀ - (f x₀ * (f x)⁻¹ ) • x, have fy_zero : f y = 0, by calc f y = f x₀ - (f x₀ * (f x)⁻¹ ) * f x : by simp [y] ... = 0 : by { rw [mul_assoc, inv_mul_cancel hx, mul_one, sub_eq_zero_of_eq], refl }, have A : r * ∥x₀∥ ≤ ∥f x₀∥ * ∥f x∥⁻¹ * ∥x∥, from calc r * ∥x₀∥ ≤ ∥x₀ - y∥ : h₀ _ (linear_map.mem_ker.2 fy_zero) ... = ∥(f x₀ * (f x)⁻¹ ) • x∥ : by { dsimp [y], congr, abel } ... = ∥f x₀∥ * ∥f x∥⁻¹ * ∥x∥ : by rw [norm_smul, normed_field.norm_mul, normed_field.norm_inv], calc ∥f x∥ = (r * ∥x₀∥)⁻¹ * (r * ∥x₀∥) * ∥f x∥ : by rwa [inv_mul_cancel, one_mul] ... ≤ (r * ∥x₀∥)⁻¹ * (∥f x₀∥ * ∥f x∥⁻¹ * ∥x∥) * ∥f x∥ : begin apply mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_left A _) (norm_nonneg _), exact inv_nonneg.2 (mul_nonneg (by norm_num) (norm_nonneg _)) end ... = (∥f x∥ ⁻¹ * ∥f x∥) * (((r * ∥x₀∥)⁻¹) * ∥f x₀∥) * ∥x∥ : by ring ... = (((r * ∥x₀∥)⁻¹) * ∥f x₀∥) * ∥x∥ : by { rw [inv_mul_cancel, one_mul], simp [norm_eq_zero, hx] } } }, exact linear_map.continuous_of_bound f _ this } end end normed_field variables [nondiscrete_normed_field 𝕜] [normed_space 𝕜 E] [normed_space 𝕜 F] [normed_space 𝕜 G] (c : 𝕜) (f g : E →L[𝕜] F) (h : F →L[𝕜] G) (x y z : E) include 𝕜 /-- A continuous linear map between normed spaces is bounded when the field is nondiscrete. The continuity ensures boundedness on a ball of some radius `δ`. The nondiscreteness is then used to rescale any element into an element of norm in `[δ/C, δ]`, whose image has a controlled norm. The norm control for the original element follows by rescaling. -/ lemma linear_map.bound_of_continuous (f : E →ₗ[𝕜] F) (hf : continuous f) : ∃ C, 0 < C ∧ (∀ x : E, ∥f x∥ ≤ C * ∥x∥) := begin have : continuous_at f 0 := continuous_iff_continuous_at.1 hf _, rcases metric.tendsto_nhds_nhds.1 this 1 zero_lt_one with ⟨ε, ε_pos, hε⟩, let δ := ε/2, have δ_pos : δ > 0 := half_pos ε_pos, have H : ∀{a}, ∥a∥ ≤ δ → ∥f a∥ ≤ 1, { assume a ha, have : dist (f a) (f 0) ≤ 1, { apply le_of_lt (hε _), rw [dist_eq_norm, sub_zero], exact lt_of_le_of_lt ha (half_lt_self ε_pos) }, simpa using this }, rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩, refine ⟨δ⁻¹ * ∥c∥, mul_pos (inv_pos.2 δ_pos) (lt_trans zero_lt_one hc), (λx, _)⟩, by_cases h : x = 0, { simp only [h, norm_zero, mul_zero, linear_map.map_zero] }, { rcases rescale_to_shell hc δ_pos h with ⟨d, hd, dxle, ledx, dinv⟩, calc ∥f x∥ = ∥f ((d⁻¹ * d) • x)∥ : by rwa [inv_mul_cancel, one_smul] ... = ∥d∥⁻¹ * ∥f (d • x)∥ : by rw [mul_smul, linear_map.map_smul, norm_smul, normed_field.norm_inv] ... ≤ ∥d∥⁻¹ * 1 : mul_le_mul_of_nonneg_left (H dxle) (by { rw ← normed_field.norm_inv, exact norm_nonneg _ }) ... ≤ δ⁻¹ * ∥c∥ * ∥x∥ : by { rw mul_one, exact dinv } } end namespace continuous_linear_map theorem bound : ∃ C, 0 < C ∧ (∀ x : E, ∥f x∥ ≤ C * ∥x∥) := f.to_linear_map.bound_of_continuous f.2 section open asymptotics filter theorem is_O_id (l : filter E) : is_O f (λ x, x) l := let ⟨M, hMp, hM⟩ := f.bound in is_O_of_le' l hM theorem is_O_comp {α : Type*} (g : F →L[𝕜] G) (f : α → F) (l : filter α) : is_O (λ x', g (f x')) f l := (g.is_O_id ⊤).comp_tendsto le_top theorem is_O_sub (f : E →L[𝕜] F) (l : filter E) (x : E) : is_O (λ x', f (x' - x)) (λ x', x' - x) l := f.is_O_comp _ l /-- A linear map which is a homothety is a continuous linear map. Since the field `𝕜` need not have `ℝ` as a subfield, this theorem is not directly deducible from the corresponding theorem about isometries plus a theorem about scalar multiplication. Likewise for the other theorems about homotheties in this file. -/ def of_homothety (f : E →ₗ[𝕜] F) (a : ℝ) (hf : ∀x, ∥f x∥ = a * ∥x∥) : E →L[𝕜] F := f.mk_continuous a (λ x, le_of_eq (hf x)) variable (𝕜) lemma to_span_singleton_homothety (x : E) (c : 𝕜) : ∥linear_map.to_span_singleton 𝕜 E x c∥ = ∥x∥ * ∥c∥ := by {rw mul_comm, exact norm_smul _ _} /-- Given an element `x` of a normed space `E` over a field `𝕜`, the natural continuous linear map from `E` to the span of `x`.-/ def to_span_singleton (x : E) : 𝕜 →L[𝕜] E := of_homothety (linear_map.to_span_singleton 𝕜 E x) ∥x∥ (to_span_singleton_homothety 𝕜 x) end section op_norm open set real /-- The operator norm of a continuous linear map is the inf of all its bounds. -/ def op_norm := Inf {c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥} instance has_op_norm : has_norm (E →L[𝕜] F) := ⟨op_norm⟩ lemma norm_def : ∥f∥ = Inf {c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥} := rfl -- So that invocations of `real.Inf_le` make sense: we show that the set of -- bounds is nonempty and bounded below. lemma bounds_nonempty {f : E →L[𝕜] F} : ∃ c, c ∈ { c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥ } := let ⟨M, hMp, hMb⟩ := f.bound in ⟨M, le_of_lt hMp, hMb⟩ lemma bounds_bdd_below {f : E →L[𝕜] F} : bdd_below { c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥ } := ⟨0, λ _ ⟨hn, _⟩, hn⟩ lemma op_norm_nonneg : 0 ≤ ∥f∥ := lb_le_Inf _ bounds_nonempty (λ _ ⟨hx, _⟩, hx) /-- The fundamental property of the operator norm: `∥f x∥ ≤ ∥f∥ * ∥x∥`. -/ theorem le_op_norm : ∥f x∥ ≤ ∥f∥ * ∥x∥ := classical.by_cases (λ heq : x = 0, by { rw heq, simp }) (λ hne, have hlt : 0 < ∥x∥, from norm_pos_iff.2 hne, (div_le_iff hlt).mp ((le_Inf _ bounds_nonempty bounds_bdd_below).2 (λ c ⟨_, hc⟩, (div_le_iff hlt).mpr $ by { apply hc }))) theorem le_op_norm_of_le {c : ℝ} {x} (h : ∥x∥ ≤ c) : ∥f x∥ ≤ ∥f∥ * c := le_trans (f.le_op_norm x) (mul_le_mul_of_nonneg_left h f.op_norm_nonneg) /-- continuous linear maps are Lipschitz continuous. -/ theorem lipschitz : lipschitz_with ⟨∥f∥, op_norm_nonneg f⟩ f := lipschitz_with.of_dist_le_mul $ λ x y, by { rw [dist_eq_norm, dist_eq_norm, ←map_sub], apply le_op_norm } lemma ratio_le_op_norm : ∥f x∥ / ∥x∥ ≤ ∥f∥ := div_le_iff_of_nonneg_of_le (norm_nonneg _) f.op_norm_nonneg (le_op_norm _ _) /-- The image of the unit ball under a continuous linear map is bounded. -/ lemma unit_le_op_norm : ∥x∥ ≤ 1 → ∥f x∥ ≤ ∥f∥ := mul_one ∥f∥ ▸ f.le_op_norm_of_le /-- If one controls the norm of every `A x`, then one controls the norm of `A`. -/ lemma op_norm_le_bound {M : ℝ} (hMp: 0 ≤ M) (hM : ∀ x, ∥f x∥ ≤ M * ∥x∥) : ∥f∥ ≤ M := Inf_le _ bounds_bdd_below ⟨hMp, hM⟩ theorem op_norm_le_of_lipschitz {f : E →L[𝕜] F} {K : nnreal} (hf : lipschitz_with K f) : ∥f∥ ≤ K := f.op_norm_le_bound K.2 $ λ x, by simpa only [dist_zero_right, f.map_zero] using hf.dist_le_mul x 0 lemma op_norm_le_of_ball {f : E →L[𝕜] F} {ε : ℝ} {C : ℝ} (ε_pos : 0 < ε) (hC : 0 ≤ C) (hf : ∀ x ∈ ball (0 : E) ε, ∥f x∥ ≤ C * ∥x∥) : ∥f∥ ≤ C := begin apply f.op_norm_le_bound hC, intros x, rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩, by_cases hx : x = 0, { simp [hx] }, rcases rescale_to_shell hc (half_pos ε_pos) hx with ⟨δ, hδ, δxle, leδx, δinv⟩, have δx_in : δ • x ∈ ball (0 : E) ε, { rw [mem_ball, dist_eq_norm, sub_zero], linarith }, calc ∥f x∥ = ∥f ((1/δ) • δ • x)∥ : by simp [hδ, smul_smul] ... = ∥1/δ∥ * ∥f (δ • x)∥ : by simp [norm_smul] ... ≤ ∥1/δ∥ * (C*∥δ • x∥) : mul_le_mul_of_nonneg_left _ (norm_nonneg _) ... = C * ∥x∥ : by { rw norm_smul, field_simp [hδ], ring }, exact hf _ δx_in end lemma op_norm_eq_of_bounds {φ : E →L[𝕜] F} {M : ℝ} (M_nonneg : 0 ≤ M) (h_above : ∀ x, ∥φ x∥ ≤ M*∥x∥) (h_below : ∀ N ≥ 0, (∀ x, ∥φ x∥ ≤ N*∥x∥) → M ≤ N) : ∥φ∥ = M := le_antisymm (φ.op_norm_le_bound M_nonneg h_above) ((le_cInf_iff continuous_linear_map.bounds_bdd_below ⟨M, M_nonneg, h_above⟩).mpr $ λ N ⟨N_nonneg, hN⟩, h_below N N_nonneg hN) /-- The operator norm satisfies the triangle inequality. -/ theorem op_norm_add_le : ∥f + g∥ ≤ ∥f∥ + ∥g∥ := show ∥f + g∥ ≤ (coe : nnreal → ℝ) (⟨_, f.op_norm_nonneg⟩ + ⟨_, g.op_norm_nonneg⟩), from op_norm_le_of_lipschitz (f.lipschitz.add g.lipschitz) /-- An operator is zero iff its norm vanishes. -/ theorem op_norm_zero_iff : ∥f∥ = 0 ↔ f = 0 := iff.intro (λ hn, continuous_linear_map.ext (λ x, norm_le_zero_iff.1 (calc _ ≤ ∥f∥ * ∥x∥ : le_op_norm _ _ ... = _ : by rw [hn, zero_mul]))) (λ hf, le_antisymm (Inf_le _ bounds_bdd_below ⟨ge_of_eq rfl, λ _, le_of_eq (by { rw [zero_mul, hf], exact norm_zero })⟩) (op_norm_nonneg _)) /-- The norm of the identity is at most `1`. It is in fact `1`, except when the space is trivial where it is `0`. It means that one can not do better than an inequality in general. -/ lemma norm_id_le : ∥id 𝕜 E∥ ≤ 1 := op_norm_le_bound _ zero_le_one (λx, by simp) /-- If a space is non-trivial, then the norm of the identity equals `1`. -/ lemma norm_id [nontrivial E] : ∥id 𝕜 E∥ = 1 := le_antisymm norm_id_le $ let ⟨x, hx⟩ := exists_ne (0 : E) in have _ := (id 𝕜 E).ratio_le_op_norm x, by rwa [id_apply, div_self (ne_of_gt $ norm_pos_iff.2 hx)] at this @[simp] lemma norm_id_field : ∥id 𝕜 𝕜∥ = 1 := norm_id @[simp] lemma norm_id_field' : ∥(1 : 𝕜 →L[𝕜] 𝕜)∥ = 1 := norm_id_field lemma op_norm_smul_le : ∥c • f∥ ≤ ∥c∥ * ∥f∥ := ((c • f).op_norm_le_bound (mul_nonneg (norm_nonneg _) (op_norm_nonneg _)) (λ _, begin erw [norm_smul, mul_assoc], exact mul_le_mul_of_nonneg_left (le_op_norm _ _) (norm_nonneg _) end)) lemma op_norm_neg : ∥-f∥ = ∥f∥ := by { rw norm_def, apply congr_arg, ext, simp } /-- Continuous linear maps themselves form a normed space with respect to the operator norm. -/ instance to_normed_group : normed_group (E →L[𝕜] F) := normed_group.of_core _ ⟨op_norm_zero_iff, op_norm_add_le, op_norm_neg⟩ instance to_normed_space : normed_space 𝕜 (E →L[𝕜] F) := ⟨op_norm_smul_le⟩ /-- The operator norm is submultiplicative. -/ lemma op_norm_comp_le (f : E →L[𝕜] F) : ∥h.comp f∥ ≤ ∥h∥ * ∥f∥ := (Inf_le _ bounds_bdd_below ⟨mul_nonneg (op_norm_nonneg _) (op_norm_nonneg _), λ x, by { rw mul_assoc, exact h.le_op_norm_of_le (f.le_op_norm x) } ⟩) /-- Continuous linear maps form a normed ring with respect to the operator norm. -/ instance to_normed_ring : normed_ring (E →L[𝕜] E) := { norm_mul := op_norm_comp_le, .. continuous_linear_map.to_normed_group } /-- For a nonzero normed space `E`, continuous linear endomorphisms form a normed algebra with respect to the operator norm. -/ instance to_normed_algebra [nontrivial E] : normed_algebra 𝕜 (E →L[𝕜] E) := { norm_algebra_map_eq := λ c, show ∥c • id 𝕜 E∥ = ∥c∥, by {rw [norm_smul, norm_id], simp}, .. continuous_linear_map.algebra } /-- A continuous linear map is automatically uniformly continuous. -/ protected theorem uniform_continuous : uniform_continuous f := f.lipschitz.uniform_continuous variable {f} /-- A continuous linear map is an isometry if and only if it preserves the norm. -/ lemma isometry_iff_norm_image_eq_norm : isometry f ↔ ∀x, ∥f x∥ = ∥x∥ := begin rw isometry_emetric_iff_metric, split, { assume H x, have := H x 0, rwa [dist_eq_norm, dist_eq_norm, f.map_zero, sub_zero, sub_zero] at this }, { assume H x y, rw [dist_eq_norm, dist_eq_norm, ← f.map_sub, H] } end lemma homothety_norm [nontrivial E] (f : E →L[𝕜] F) {a : ℝ} (hf : ∀x, ∥f x∥ = a * ∥x∥) : ∥f∥ = a := begin obtain ⟨x, hx⟩ : ∃ (x : E), x ≠ 0 := exists_ne 0, have ha : 0 ≤ a, { apply nonneg_of_mul_nonneg_right, rw ← hf x, apply norm_nonneg, exact norm_pos_iff.mpr hx }, refine le_antisymm_iff.mpr ⟨_, _⟩, { exact continuous_linear_map.op_norm_le_bound f ha (λ y, le_of_eq (hf y)) }, { rw continuous_linear_map.norm_def, apply real.lb_le_Inf _ continuous_linear_map.bounds_nonempty, intros c h, rw mem_set_of_eq at h, apply (mul_le_mul_right (norm_pos_iff.mpr hx)).mp, rw ← hf x, exact h.2 x } end lemma to_span_singleton_norm (x : E) : ∥to_span_singleton 𝕜 x∥ = ∥x∥ := homothety_norm _ (to_span_singleton_homothety 𝕜 x) variable (f) theorem uniform_embedding_of_bound {K : nnreal} (hf : ∀ x, ∥x∥ ≤ K * ∥f x∥) : uniform_embedding f := (f.to_linear_map.antilipschitz_of_bound hf).uniform_embedding f.uniform_continuous /-- If a continuous linear map is a uniform embedding, then it is expands the distances by a positive factor.-/ theorem antilipschitz_of_uniform_embedding (hf : uniform_embedding f) : ∃ K, antilipschitz_with K f := begin obtain ⟨ε, εpos, hε⟩ : ∃ (ε : ℝ) (H : ε > 0), ∀ {x y : E}, dist (f x) (f y) < ε → dist x y < 1, from (uniform_embedding_iff.1 hf).2.2 1 zero_lt_one, let δ := ε/2, have δ_pos : δ > 0 := half_pos εpos, have H : ∀{x}, ∥f x∥ ≤ δ → ∥x∥ ≤ 1, { assume x hx, have : dist x 0 ≤ 1, { apply le_of_lt, apply hε, simp [dist_eq_norm], exact lt_of_le_of_lt hx (half_lt_self εpos) }, simpa using this }, rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩, refine ⟨⟨δ⁻¹, _⟩ * nnnorm c, f.to_linear_map.antilipschitz_of_bound $ λx, _⟩, exact inv_nonneg.2 (le_of_lt δ_pos), by_cases hx : f x = 0, { have : f x = f 0, by { simp [hx] }, have : x = 0 := (uniform_embedding_iff.1 hf).1 this, simp [this] }, { rcases rescale_to_shell hc δ_pos hx with ⟨d, hd, dxle, ledx, dinv⟩, have : ∥f (d • x)∥ ≤ δ, by simpa, have : ∥d • x∥ ≤ 1 := H this, calc ∥x∥ = ∥d∥⁻¹ * ∥d • x∥ : by rwa [← normed_field.norm_inv, ← norm_smul, ← mul_smul, inv_mul_cancel, one_smul] ... ≤ ∥d∥⁻¹ * 1 : mul_le_mul_of_nonneg_left this (inv_nonneg.2 (norm_nonneg _)) ... ≤ δ⁻¹ * ∥c∥ * ∥f x∥ : by rwa [mul_one] } end section completeness open_locale topological_space open filter /-- If the target space is complete, the space of continuous linear maps with its norm is also complete. -/ instance [complete_space F] : complete_space (E →L[𝕜] F) := begin -- We show that every Cauchy sequence converges. refine metric.complete_of_cauchy_seq_tendsto (λ f hf, _), -- We now expand out the definition of a Cauchy sequence, rcases cauchy_seq_iff_le_tendsto_0.1 hf with ⟨b, b0, b_bound, b_lim⟩, clear hf, -- and establish that the evaluation at any point `v : E` is Cauchy. have cau : ∀ v, cauchy_seq (λ n, f n v), { assume v, apply cauchy_seq_iff_le_tendsto_0.2 ⟨λ n, b n * ∥v∥, λ n, _, _, _⟩, { exact mul_nonneg (b0 n) (norm_nonneg _) }, { assume n m N hn hm, rw dist_eq_norm, apply le_trans ((f n - f m).le_op_norm v) _, exact mul_le_mul_of_nonneg_right (b_bound n m N hn hm) (norm_nonneg v) }, { simpa using b_lim.mul tendsto_const_nhds } }, -- We assemble the limits points of those Cauchy sequences -- (which exist as `F` is complete) -- into a function which we call `G`. choose G hG using λv, cauchy_seq_tendsto_of_complete (cau v), -- Next, we show that this `G` is linear, let Glin : E →ₗ[𝕜] F := { to_fun := G, map_add' := λ v w, begin have A := hG (v + w), have B := (hG v).add (hG w), simp only [map_add] at A B, exact tendsto_nhds_unique A B, end, map_smul' := λ c v, begin have A := hG (c • v), have B := filter.tendsto.smul (@tendsto_const_nhds _ ℕ _ c _) (hG v), simp only [map_smul] at A B, exact tendsto_nhds_unique A B end }, -- and that `G` has norm at most `(b 0 + ∥f 0∥)`. have Gnorm : ∀ v, ∥G v∥ ≤ (b 0 + ∥f 0∥) * ∥v∥, { assume v, have A : ∀ n, ∥f n v∥ ≤ (b 0 + ∥f 0∥) * ∥v∥, { assume n, apply le_trans ((f n).le_op_norm _) _, apply mul_le_mul_of_nonneg_right _ (norm_nonneg v), calc ∥f n∥ = ∥(f n - f 0) + f 0∥ : by { congr' 1, abel } ... ≤ ∥f n - f 0∥ + ∥f 0∥ : norm_add_le _ _ ... ≤ b 0 + ∥f 0∥ : begin apply add_le_add_right, simpa [dist_eq_norm] using b_bound n 0 0 (zero_le _) (zero_le _) end }, exact le_of_tendsto (hG v).norm (eventually_of_forall A) }, -- Thus `G` is continuous, and we propose that as the limit point of our original Cauchy sequence. let Gcont := Glin.mk_continuous _ Gnorm, use Gcont, -- Our last task is to establish convergence to `G` in norm. have : ∀ n, ∥f n - Gcont∥ ≤ b n, { assume n, apply op_norm_le_bound _ (b0 n) (λ v, _), have A : ∀ᶠ m in at_top, ∥(f n - f m) v∥ ≤ b n * ∥v∥, { refine eventually_at_top.2 ⟨n, λ m hm, _⟩, apply le_trans ((f n - f m).le_op_norm _) _, exact mul_le_mul_of_nonneg_right (b_bound n m n (le_refl _) hm) (norm_nonneg v) }, have B : tendsto (λ m, ∥(f n - f m) v∥) at_top (𝓝 (∥(f n - Gcont) v∥)) := tendsto.norm (tendsto_const_nhds.sub (hG v)), exact le_of_tendsto B A }, erw tendsto_iff_norm_tendsto_zero, exact squeeze_zero (λ n, norm_nonneg _) this b_lim, end end completeness section uniformly_extend variables [complete_space F] (e : E →L[𝕜] G) (h_dense : dense_range e) section variables (h_e : uniform_inducing e) /-- Extension of a continuous linear map `f : E →L[𝕜] F`, with `E` a normed space and `F` a complete normed space, along a uniform and dense embedding `e : E →L[𝕜] G`. -/ def extend : G →L[𝕜] F := /- extension of `f` is continuous -/ have cont : _ := (uniform_continuous_uniformly_extend h_e h_dense f.uniform_continuous).continuous, /- extension of `f` agrees with `f` on the domain of the embedding `e` -/ have eq : _ := uniformly_extend_of_ind h_e h_dense f.uniform_continuous, { to_fun := (h_e.dense_inducing h_dense).extend f, map_add' := begin refine h_dense.induction_on₂ _ _, { exact is_closed_eq (cont.comp continuous_add) ((cont.comp continuous_fst).add (cont.comp continuous_snd)) }, { assume x y, simp only [eq, ← e.map_add], exact f.map_add _ _ }, end, map_smul' := λk, begin refine (λ b, h_dense.induction_on b _ _), { exact is_closed_eq (cont.comp (continuous_const.smul continuous_id)) ((continuous_const.smul continuous_id).comp cont) }, { assume x, rw ← map_smul, simp only [eq], exact map_smul _ _ _ }, end, cont := cont } lemma extend_unique (g : G →L[𝕜] F) (H : g.comp e = f) : extend f e h_dense h_e = g := continuous_linear_map.coe_fn_injective $ uniformly_extend_unique h_e h_dense (continuous_linear_map.ext_iff.1 H) g.continuous @[simp] lemma extend_zero : extend (0 : E →L[𝕜] F) e h_dense h_e = 0 := extend_unique _ _ _ _ _ (zero_comp _) end section variables {N : nnreal} (h_e : ∀x, ∥x∥ ≤ N * ∥e x∥) local notation `ψ` := f.extend e h_dense (uniform_embedding_of_bound _ h_e).to_uniform_inducing /-- If a dense embedding `e : E →L[𝕜] G` expands the norm by a constant factor `N⁻¹`, then the norm of the extension of `f` along `e` is bounded by `N * ∥f∥`. -/ lemma op_norm_extend_le : ∥ψ∥ ≤ N * ∥f∥ := begin have uni : uniform_inducing e := (uniform_embedding_of_bound _ h_e).to_uniform_inducing, have eq : ∀x, ψ (e x) = f x := uniformly_extend_of_ind uni h_dense f.uniform_continuous, by_cases N0 : 0 ≤ N, { refine op_norm_le_bound ψ _ (is_closed_property h_dense (is_closed_le _ _) _), { exact mul_nonneg N0 (norm_nonneg _) }, { exact continuous_norm.comp (cont ψ) }, { exact continuous_const.mul continuous_norm }, { assume x, rw eq, calc ∥f x∥ ≤ ∥f∥ * ∥x∥ : le_op_norm _ _ ... ≤ ∥f∥ * (N * ∥e x∥) : mul_le_mul_of_nonneg_left (h_e x) (norm_nonneg _) ... ≤ N * ∥f∥ * ∥e x∥ : by rw [mul_comm ↑N ∥f∥, mul_assoc] } }, { have he : ∀ x : E, x = 0, { assume x, have N0 : N ≤ 0 := le_of_lt (lt_of_not_ge N0), rw ← norm_le_zero_iff, exact le_trans (h_e x) (mul_nonpos_of_nonpos_of_nonneg N0 (norm_nonneg _)) }, have hf : f = 0, { ext, simp only [he x, zero_apply, map_zero] }, have hψ : ψ = 0, { rw hf, apply extend_zero }, rw [hψ, hf, norm_zero, norm_zero, mul_zero] } end end end uniformly_extend end op_norm end continuous_linear_map /-- If a continuous linear map is constructed from a linear map via the constructor `mk_continuous`, then its norm is bounded by the bound given to the constructor if it is nonnegative. -/ lemma linear_map.mk_continuous_norm_le (f : E →ₗ[𝕜] F) {C : ℝ} (hC : 0 ≤ C) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : ∥f.mk_continuous C h∥ ≤ C := continuous_linear_map.op_norm_le_bound _ hC h namespace continuous_linear_map /-- The norm of the tensor product of a scalar linear map and of an element of a normed space is the product of the norms. -/ @[simp] lemma norm_smul_right_apply (c : E →L[𝕜] 𝕜) (f : F) : ∥smul_right c f∥ = ∥c∥ * ∥f∥ := begin refine le_antisymm _ _, { apply op_norm_le_bound _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) (λx, _), calc ∥(c x) • f∥ = ∥c x∥ * ∥f∥ : norm_smul _ _ ... ≤ (∥c∥ * ∥x∥) * ∥f∥ : mul_le_mul_of_nonneg_right (le_op_norm _ _) (norm_nonneg _) ... = ∥c∥ * ∥f∥ * ∥x∥ : by ring }, { by_cases h : ∥f∥ = 0, { rw h, simp [norm_nonneg] }, { have : 0 < ∥f∥ := lt_of_le_of_ne (norm_nonneg _) (ne.symm h), rw ← le_div_iff this, apply op_norm_le_bound _ (div_nonneg (norm_nonneg _) (norm_nonneg f)) (λx, _), rw [div_mul_eq_mul_div, le_div_iff this], calc ∥c x∥ * ∥f∥ = ∥c x • f∥ : (norm_smul _ _).symm ... = ∥((smul_right c f) : E → F) x∥ : rfl ... ≤ ∥smul_right c f∥ * ∥x∥ : le_op_norm _ _ } }, end /-- Given `c : c : E →L[𝕜] 𝕜`, `c.smul_rightL` is the continuous linear map from `F` to `E →L[𝕜] F` sending `f` to `λ e, c e • f`. -/ def smul_rightL (c : E →L[𝕜] 𝕜) : F →L[𝕜] (E →L[𝕜] F) := (c.smul_rightₗ : F →ₗ[𝕜] (E →L[𝕜] F)).mk_continuous _ (λ f, le_of_eq $ c.norm_smul_right_apply f) @[simp] lemma norm_smul_rightL_apply (c : E →L[𝕜] 𝕜) (f : F) : ∥c.smul_rightL f∥ = ∥c∥ * ∥f∥ := by simp [continuous_linear_map.smul_rightL, continuous_linear_map.smul_rightₗ] @[simp] lemma norm_smul_rightL (c : E →L[𝕜] 𝕜) [nontrivial F] : ∥(c.smul_rightL : F →L[𝕜] (E →L[𝕜] F))∥ = ∥c∥ := continuous_linear_map.homothety_norm _ c.norm_smul_right_apply variables (𝕜 F) /-- The linear map obtained by applying a continuous linear map at a given vector. -/ def applyₗ (v : E) : (E →L[𝕜] F) →ₗ[𝕜] F := { to_fun := λ f, f v, map_add' := λ f g, f.add_apply g v, map_smul' := λ x f, f.smul_apply x v } lemma continuous_applyₗ (v : E) : continuous (continuous_linear_map.applyₗ 𝕜 F v) := begin apply (continuous_linear_map.applyₗ 𝕜 F v).continuous_of_bound, intro f, rw mul_comm, exact f.le_op_norm v, end /-- The continuous linear map obtained by applying a continuous linear map at a given vector. -/ def apply (v : E) : (E →L[𝕜] F) →L[𝕜] F := ⟨continuous_linear_map.applyₗ 𝕜 F v, continuous_linear_map.continuous_applyₗ _ _ _⟩ variables {𝕜 F} section multiplication_linear variables (𝕜) (𝕜' : Type*) [normed_ring 𝕜'] [normed_algebra 𝕜 𝕜'] /-- Left-multiplication in a normed algebra, considered as a continuous linear map. -/ def lmul_left : 𝕜' → (𝕜' →L[𝕜] 𝕜') := λ x, (algebra.lmul_left 𝕜 𝕜' x).mk_continuous ∥x∥ (λ y, by {rw algebra.lmul_left_apply, exact norm_mul_le x y}) /-- Right-multiplication in a normed algebra, considered as a continuous linear map. -/ def lmul_right : 𝕜' → (𝕜' →L[𝕜] 𝕜') := λ x, (algebra.lmul_right 𝕜 𝕜' x).mk_continuous ∥x∥ (λ y, by {rw [algebra.lmul_right_apply, mul_comm], exact norm_mul_le y x}) /-- Simultaneous left- and right-multiplication in a normed algebra, considered as a continuous linear map. -/ def lmul_left_right (vw : 𝕜' × 𝕜') : 𝕜' →L[𝕜] 𝕜' := (lmul_right 𝕜 𝕜' vw.2).comp (lmul_left 𝕜 𝕜' vw.1) @[simp] lemma lmul_left_apply (x y : 𝕜') : lmul_left 𝕜 𝕜' x y = x * y := rfl @[simp] lemma lmul_right_apply (x y : 𝕜') : lmul_right 𝕜 𝕜' x y = y * x := rfl @[simp] lemma lmul_left_right_apply (vw : 𝕜' × 𝕜') (x : 𝕜') : lmul_left_right 𝕜 𝕜' vw x = vw.1 * x * vw.2 := rfl end multiplication_linear section restrict_scalars variable (𝕜) variables {𝕜' : Type*} [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] {E' : Type*} [normed_group E'] [normed_space 𝕜' E'] {F' : Type*} [normed_group F'] [normed_space 𝕜' F'] /-- `𝕜`-linear continuous function induced by a `𝕜'`-linear continuous function when `𝕜'` is a normed algebra over `𝕜`. -/ def restrict_scalars (f : E' →L[𝕜'] F') : (semimodule.restrict_scalars 𝕜 𝕜' E') →L[𝕜] (semimodule.restrict_scalars 𝕜 𝕜' F') := { cont := f.cont, ..linear_map.restrict_scalars 𝕜 (f.to_linear_map) } @[simp, norm_cast] lemma restrict_scalars_coe_eq_coe (f : E' →L[𝕜'] F') : (f.restrict_scalars 𝕜 : (semimodule.restrict_scalars 𝕜 𝕜' E') →ₗ[𝕜] (semimodule.restrict_scalars 𝕜 𝕜' F')) = (f : E' →ₗ[𝕜'] F').restrict_scalars 𝕜 := rfl @[simp, norm_cast squash] lemma restrict_scalars_coe_eq_coe' (f : E' →L[𝕜'] F') : (f.restrict_scalars 𝕜 : E' → F') = f := rfl end restrict_scalars section extend_scalars variables {𝕜' : Type*} [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] {F' : Type*} [normed_group F'] [normed_space 𝕜' F'] instance has_scalar_extend_scalars : has_scalar 𝕜' (E →L[𝕜] (semimodule.restrict_scalars 𝕜 𝕜' F')) := { smul := λ c f, (c • f.to_linear_map).mk_continuous (∥c∥ * ∥f∥) begin assume x, calc ∥c • (f x)∥ = ∥c∥ * ∥f x∥ : norm_smul c _ ... ≤ ∥c∥ * (∥f∥ * ∥x∥) : mul_le_mul_of_nonneg_left (le_op_norm f x) (norm_nonneg _) ... = ∥c∥ * ∥f∥ * ∥x∥ : (mul_assoc _ _ _).symm end } instance module_extend_scalars : module 𝕜' (E →L[𝕜] (semimodule.restrict_scalars 𝕜 𝕜' F')) := { smul_zero := λ _, ext $ λ _, smul_zero _, zero_smul := λ _, ext $ λ _, zero_smul _ _, one_smul := λ _, ext $ λ _, one_smul _ _, mul_smul := λ _ _ _, ext $ λ _, mul_smul _ _ _, add_smul := λ _ _ _, ext $ λ _, add_smul _ _ _, smul_add := λ _ _ _, ext $ λ _, smul_add _ _ _ } instance normed_space_extend_scalars : normed_space 𝕜' (E →L[𝕜] (semimodule.restrict_scalars 𝕜 𝕜' F')) := { norm_smul_le := λ c f, linear_map.mk_continuous_norm_le _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) _ } /-- When `f` is a continuous linear map taking values in `S`, then `λb, f b • x` is a continuous linear map. -/ def smul_algebra_right (f : E →L[𝕜] 𝕜') (x : semimodule.restrict_scalars 𝕜 𝕜' F') : E →L[𝕜] (semimodule.restrict_scalars 𝕜 𝕜' F') := { cont := by continuity!, .. smul_algebra_right f.to_linear_map x } @[simp] theorem smul_algebra_right_apply (f : E →L[𝕜] 𝕜') (x : semimodule.restrict_scalars 𝕜 𝕜' F') (c : E) : smul_algebra_right f x c = f c • x := rfl end extend_scalars section has_sum variables {ι : Type*} /-- Applying a continuous linear map commutes with taking an (infinite) sum. -/ protected lemma has_sum {f : ι → E} (φ : E →L[𝕜] F) {x : E} (hf : has_sum f x) : has_sum (λ (b:ι), φ (f b)) (φ x) := begin unfold has_sum, convert φ.continuous.continuous_at.tendsto.comp hf, ext s, rw [function.comp_app, finset.sum_hom s φ], end lemma has_sum_of_summable {f : ι → E} (φ : E →L[𝕜] F) (hf : summable f) : has_sum (λ (b:ι), φ (f b)) (φ (∑'b, f b)) := φ.has_sum hf.has_sum end has_sum end continuous_linear_map namespace continuous_linear_equiv variable (e : E ≃L[𝕜] F) protected lemma lipschitz : lipschitz_with (nnnorm (e : E →L[𝕜] F)) e := (e : E →L[𝕜] F).lipschitz protected lemma antilipschitz : antilipschitz_with (nnnorm (e.symm : F →L[𝕜] E)) e := e.symm.lipschitz.to_right_inverse e.left_inv theorem is_O_comp {α : Type*} (f : α → E) (l : filter α) : asymptotics.is_O (λ x', e (f x')) f l := (e : E →L[𝕜] F).is_O_comp f l theorem is_O_sub (l : filter E) (x : E) : asymptotics.is_O (λ x', e (x' - x)) (λ x', x' - x) l := (e : E →L[𝕜] F).is_O_sub l x theorem is_O_comp_rev {α : Type*} (f : α → E) (l : filter α) : asymptotics.is_O f (λ x', e (f x')) l := (e.symm.is_O_comp _ l).congr_left $ λ _, e.symm_apply_apply _ theorem is_O_sub_rev (l : filter E) (x : E) : asymptotics.is_O (λ x', x' - x) (λ x', e (x' - x)) l := e.is_O_comp_rev _ _ /-- A continuous linear equiv is a uniform embedding. -/ lemma uniform_embedding : uniform_embedding e := e.antilipschitz.uniform_embedding e.lipschitz.uniform_continuous lemma one_le_norm_mul_norm_symm [nontrivial E] : 1 ≤ ∥(e : E →L[𝕜] F)∥ * ∥(e.symm : F →L[𝕜] E)∥ := begin rw [mul_comm], convert (e.symm : F →L[𝕜] E).op_norm_comp_le (e : E →L[𝕜] F), rw [e.coe_symm_comp_coe, continuous_linear_map.norm_id] end lemma norm_pos [nontrivial E] : 0 < ∥(e : E →L[𝕜] F)∥ := pos_of_mul_pos_right (lt_of_lt_of_le zero_lt_one e.one_le_norm_mul_norm_symm) (norm_nonneg _) lemma norm_symm_pos [nontrivial E] : 0 < ∥(e.symm : F →L[𝕜] E)∥ := pos_of_mul_pos_left (lt_of_lt_of_le zero_lt_one e.one_le_norm_mul_norm_symm) (norm_nonneg _) lemma subsingleton_or_norm_symm_pos : subsingleton E ∨ 0 < ∥(e.symm : F →L[𝕜] E)∥ := begin rcases subsingleton_or_nontrivial E with _i|_i; resetI, { left, apply_instance }, { right, exact e.norm_symm_pos } end lemma subsingleton_or_nnnorm_symm_pos : subsingleton E ∨ 0 < (nnnorm $ (e.symm : F →L[𝕜] E)) := subsingleton_or_norm_symm_pos e lemma homothety_inverse (a : ℝ) (ha : 0 < a) (f : E ≃ₗ[𝕜] F) : (∀ (x : E), ∥f x∥ = a * ∥x∥) → (∀ (y : F), ∥f.symm y∥ = a⁻¹ * ∥y∥) := begin intros hf y, calc ∥(f.symm) y∥ = a⁻¹ * (a * ∥ (f.symm) y∥) : _ ... = a⁻¹ * ∥f ((f.symm) y)∥ : by rw hf ... = a⁻¹ * ∥y∥ : by simp, rw [← mul_assoc, inv_mul_cancel (ne_of_lt ha).symm, one_mul], end variable (𝕜) /-- A linear equivalence which is a homothety is a continuous linear equivalence. -/ def of_homothety (f : E ≃ₗ[𝕜] F) (a : ℝ) (ha : 0 < a) (hf : ∀x, ∥f x∥ = a * ∥x∥) : E ≃L[𝕜] F := { to_linear_equiv := f, continuous_to_fun := f.to_linear_map.continuous_of_bound a (λ x, le_of_eq (hf x)), continuous_inv_fun := f.symm.to_linear_map.continuous_of_bound a⁻¹ (λ x, le_of_eq (homothety_inverse a ha f hf x)) } lemma to_span_nonzero_singleton_homothety (x : E) (h : x ≠ 0) (c : 𝕜) : ∥linear_equiv.to_span_nonzero_singleton 𝕜 E x h c∥ = ∥x∥ * ∥c∥ := continuous_linear_map.to_span_singleton_homothety _ _ _ /-- Given a nonzero element `x` of a normed space `E` over a field `𝕜`, the natural continuous linear equivalence from `E` to the span of `x`.-/ def to_span_nonzero_singleton (x : E) (h : x ≠ 0) : 𝕜 ≃L[𝕜] (submodule.span 𝕜 ({x} : set E)) := of_homothety 𝕜 (linear_equiv.to_span_nonzero_singleton 𝕜 E x h) ∥x∥ (norm_pos_iff.mpr h) (to_span_nonzero_singleton_homothety 𝕜 x h) /-- Given a nonzero element `x` of a normed space `E` over a field `𝕜`, the natural continuous linear map from the span of `x` to `𝕜`.-/ abbreviation coord (x : E) (h : x ≠ 0) : (submodule.span 𝕜 ({x} : set E)) →L[𝕜] 𝕜 := (to_span_nonzero_singleton 𝕜 x h).symm lemma coord_norm (x : E) (h : x ≠ 0) : ∥coord 𝕜 x h∥ = ∥x∥⁻¹ := begin have hx : 0 < ∥x∥ := (norm_pos_iff.mpr h), haveI : nontrivial (submodule.span 𝕜 ({x} : set E)) := submodule.nontrivial_span_singleton h, exact continuous_linear_map.homothety_norm _ (λ y, homothety_inverse _ hx _ (to_span_nonzero_singleton_homothety 𝕜 x h) _) end lemma coord_self (x : E) (h : x ≠ 0) : (coord 𝕜 x h) (⟨x, submodule.mem_span_singleton_self x⟩ : submodule.span 𝕜 ({x} : set E)) = 1 := linear_equiv.coord_self 𝕜 E x h end continuous_linear_equiv lemma linear_equiv.uniform_embedding (e : E ≃ₗ[𝕜] F) (h₁ : continuous e) (h₂ : continuous e.symm) : uniform_embedding e := continuous_linear_equiv.uniform_embedding { continuous_to_fun := h₁, continuous_inv_fun := h₂, .. e } /-- Construct a continuous linear equivalence from a linear equivalence together with bounds in both directions. -/ def linear_equiv.to_continuous_linear_equiv_of_bounds (e : E ≃ₗ[𝕜] F) (C_to C_inv : ℝ) (h_to : ∀ x, ∥e x∥ ≤ C_to * ∥x∥) (h_inv : ∀ x : F, ∥e.symm x∥ ≤ C_inv * ∥x∥) : E ≃L[𝕜] F := { to_linear_equiv := e, continuous_to_fun := e.to_linear_map.continuous_of_bound C_to h_to, continuous_inv_fun := e.symm.to_linear_map.continuous_of_bound C_inv h_inv } namespace continuous_linear_map variables (𝕜) (𝕜' : Type*) [normed_ring 𝕜'] [normed_algebra 𝕜 𝕜'] @[simp] lemma lmul_left_norm (v : 𝕜') : ∥lmul_left 𝕜 𝕜' v∥ = ∥v∥ := begin refine le_antisymm _ _, { exact linear_map.mk_continuous_norm_le _ (norm_nonneg v) _ }, { simpa [@normed_algebra.norm_one 𝕜 _ 𝕜' _ _] using le_op_norm (lmul_left 𝕜 𝕜' v) (1:𝕜') } end @[simp] lemma lmul_right_norm (v : 𝕜') : ∥lmul_right 𝕜 𝕜' v∥ = ∥v∥ := begin refine le_antisymm _ _, { exact linear_map.mk_continuous_norm_le _ (norm_nonneg v) _ }, { simpa [@normed_algebra.norm_one 𝕜 _ 𝕜' _ _] using le_op_norm (lmul_right 𝕜 𝕜' v) (1:𝕜') } end lemma lmul_left_right_norm_le (vw : 𝕜' × 𝕜') : ∥lmul_left_right 𝕜 𝕜' vw∥ ≤ ∥vw.1∥ * ∥vw.2∥ := by simpa [mul_comm] using op_norm_comp_le (lmul_right 𝕜 𝕜' vw.2) (lmul_left 𝕜 𝕜' vw.1) end continuous_linear_map
11cfae09c24cdb15123c1fc139ac61efe0ec393f
4727251e0cd73359b15b664c3170e5d754078599
/src/data/finset/fin.lean
4fb4f1955eb3709155bc1ee64ec2c4bb6204578b
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
1,755
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Scott Morrison, Johan Commelin -/ import data.finset.card /-! # Finsets in `fin n` A few constructions for finsets in `fin n`. ## Main declarations * `finset.fin_range`: `{0, 1, ..., n - 1}` as a `finset (fin n)`. * `finset.attach_fin`: Turns a finset of naturals strictly less than `n` into a `finset (fin n)`. -/ variables {n : ℕ} namespace finset /-- `finset.fin_range n` is the finset `{0, 1, ..., n - 1}`, as a `finset (fin n)`. -/ def fin_range (n : ℕ) : finset (fin n) := ⟨list.fin_range n, list.nodup_fin_range n⟩ @[simp] lemma fin_range_card : (fin_range n).card = n := by simp [fin_range] @[simp] lemma mem_fin_range (m : fin n) : m ∈ fin_range n := list.mem_fin_range m @[simp] lemma coe_fin_range (n : ℕ) : (fin_range n : set (fin n)) = set.univ := set.eq_univ_of_forall mem_fin_range /-- Given a finset `s` of `ℕ` contained in `{0,..., n-1}`, the corresponding finset in `fin n` is `s.attach_fin h` where `h` is a proof that all elements of `s` are less than `n`. -/ def attach_fin (s : finset ℕ) {n : ℕ} (h : ∀ m ∈ s, m < n) : finset (fin n) := ⟨s.1.pmap (λ a ha, ⟨a, ha⟩) h, s.nodup.pmap $ λ _ _ _ _, fin.veq_of_eq⟩ @[simp] lemma mem_attach_fin {n : ℕ} {s : finset ℕ} (h : ∀ m ∈ s, m < n) {a : fin n} : a ∈ s.attach_fin h ↔ (a : ℕ) ∈ s := ⟨λ h, let ⟨b, hb₁, hb₂⟩ := multiset.mem_pmap.1 h in hb₂ ▸ hb₁, λ h, multiset.mem_pmap.2 ⟨a, h, fin.eta _ _⟩⟩ @[simp] lemma card_attach_fin {n : ℕ} (s : finset ℕ) (h : ∀ m ∈ s, m < n) : (s.attach_fin h).card = s.card := multiset.card_pmap _ _ _ end finset
2b09f95485cc60fb8097d6aa2a213676bbe9b98c
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/lean/run/structure.lean
dd8206c3339e40eb6a6ced968cef06eaa939f803
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
1,208
lean
import Init.Lean open Lean structure S1 := (x y : Nat) structure S2 extends S1 := (z : Nat) structure S3 := (w : Nat) structure S4 extends S2, S3 := (s : Nat) def check (b : Bool) : MetaIO Unit := unless b $ throw $ IO.userError "check failed" class S5 := (x y : Nat) inductive D | mk (x y z : Nat) : D def tst : MetaIO Unit := do env ← MetaIO.getEnv; IO.println (getStructureFields env `Lean.Environment); check $ getStructureFields env `S4 == #[`toS2, `toS3, `s]; check $ getStructureFields env `S1 == #[`x, `y]; check $ isSubobjectField? env `S4 `toS2 == some `S2; check $ getParentStructures env `S4 == #[`S2, `S3]; check $ findField? env `S4 `x == some `S1; check $ findField? env `S4 `x1 == none; check $ isStructure env `S1; check $ isStructure env `S2; check $ isStructure env `S3; check $ isStructure env `S4; check $ isStructure env `S5; check $ !isStructure env `Nat; check $ !isStructure env `D; IO.println (getStructureFieldsFlattened env `S4); IO.println (getStructureFields env `D); IO.println (getPathToBaseStructure? env `S1 `S4); check $ getPathToBaseStructure? env `S1 `S4 == some [`S4.toS2, `S2.toS1]; pure () #eval tst
696f0c49d0f517e1b2ffd28deba63f7ee1d07b76
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/buffer/parser/basic.lean
bb48257c8e22958886bf465ef8397c3601bd81d9
[ "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
110,086
lean
/- Copyright (c) 2020 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky -/ import data.string.basic import data.buffer.basic import data.nat.digits /-! # Parsers `parser α` is the type that describes a computation that can ingest a `char_buffer` and output, if successful, a term of type `α`. This file expands on the definitions in the core library, proving that all the core library parsers are `mono`. There are also lemmas on the composability of parsers. ## Main definitions * `parse_result.pos` : The position of a `char_buffer` at which a `parser α` has finished. * `parser.mono` : The property that a parser only moves forward within a buffer, in both cases of success or failure. ## Implementation details Lemmas about how parsers are mono are in the `mono` namespace. That allows using projection notation for shorter term proofs that are parallel to the definitions of the parsers in structure. -/ open parser parse_result /-- For some `parse_result α`, give the position at which the result was provided, in either the `done` or the `fail` case. -/ @[simp] def parse_result.pos {α} : parse_result α → ℕ | (done n _) := n | (fail n _) := n namespace parser section defn_lemmas variables {α β : Type} (msgs : thunk (list string)) (msg : thunk string) variables (p q : parser α) (cb : char_buffer) (n n' : ℕ) {err : dlist string} variables {a : α} {b : β} /-- A `p : parser α` is defined to be `mono` if the result `p cb n` it gives, for some `cb : char_buffer` and `n : ℕ`, (whether `done` or `fail`), is always at a `parse_result.pos` that is at least `n`. The `mono` property is used mainly for proper `orelse` behavior. -/ class mono : Prop := (le' : ∀ (cb : char_buffer) (n : ℕ), n ≤ (p cb n).pos) lemma mono.le [p.mono] : n ≤ (p cb n).pos := mono.le' cb n /-- A `parser α` is defined to be `static` if it does not move on success. -/ class static : Prop := (of_done : ∀ {cb : char_buffer} {n n' : ℕ} {a : α}, p cb n = done n' a → n = n') /-- A `parser α` is defined to be `err_static` if it does not move on error. -/ class err_static : Prop := (of_fail : ∀ {cb : char_buffer} {n n' : ℕ} {err : dlist string}, p cb n = fail n' err → n = n') /-- A `parser α` is defined to be `step` if it always moves exactly one char forward on success. -/ class step : Prop := (of_done : ∀ {cb : char_buffer} {n n' : ℕ} {a : α}, p cb n = done n' a → n' = n + 1) /-- A `parser α` is defined to be `prog` if it always moves forward on success. -/ class prog : Prop := (of_done : ∀ {cb : char_buffer} {n n' : ℕ} {a : α}, p cb n = done n' a → n < n') /-- A `parser a` is defined to be `bounded` if it produces a `fail` `parse_result` when it is parsing outside the provided `char_buffer`. -/ class bounded : Prop := (ex' : ∀ {cb : char_buffer} {n : ℕ}, cb.size ≤ n → ∃ (n' : ℕ) (err : dlist string), p cb n = fail n' err) lemma bounded.exists (p : parser α) [p.bounded] {cb : char_buffer} {n : ℕ} (h : cb.size ≤ n) : ∃ (n' : ℕ) (err : dlist string), p cb n = fail n' err := bounded.ex' h /-- A `parser a` is defined to be `unfailing` if it always produces a `done` `parse_result`. -/ class unfailing : Prop := (ex' : ∀ (cb : char_buffer) (n : ℕ), ∃ (n' : ℕ) (a : α), p cb n = done n' a) /-- A `parser a` is defined to be `conditionally_unfailing` if it produces a `done` `parse_result` as long as it is parsing within the provided `char_buffer`. -/ class conditionally_unfailing : Prop := (ex' : ∀ {cb : char_buffer} {n : ℕ}, n < cb.size → ∃ (n' : ℕ) (a : α), p cb n = done n' a) lemma fail_iff : (∀ pos' result, p cb n ≠ done pos' result) ↔ ∃ (pos' : ℕ) (err : dlist string), p cb n = fail pos' err := by cases p cb n; simp lemma success_iff : (∀ pos' err, p cb n ≠ fail pos' err) ↔ ∃ (pos' : ℕ) (result : α), p cb n = done pos' result := by cases p cb n; simp variables {p q cb n n' msgs msg} lemma mono.of_done [p.mono] (h : p cb n = done n' a) : n ≤ n' := by simpa [h] using mono.le p cb n lemma mono.of_fail [p.mono] (h : p cb n = fail n' err) : n ≤ n' := by simpa [h] using mono.le p cb n lemma bounded.of_done [p.bounded] (h : p cb n = done n' a) : n < cb.size := begin contrapose! h, obtain ⟨np, err, hp⟩ := bounded.exists p h, simp [hp] end lemma static.iff : static p ↔ (∀ (cb : char_buffer) (n n' : ℕ) (a : α), p cb n = done n' a → n = n') := ⟨λ h _ _ _ _ hp, by { haveI := h, exact static.of_done hp}, λ h, ⟨h⟩⟩ lemma exists_done (p : parser α) [p.unfailing] (cb : char_buffer) (n : ℕ) : ∃ (n' : ℕ) (a : α), p cb n = done n' a := unfailing.ex' cb n lemma unfailing.of_fail [p.unfailing] (h : p cb n = fail n' err) : false := begin obtain ⟨np, a, hp⟩ := p.exists_done cb n, simpa [hp] using h end @[priority 100] -- see Note [lower instance priority] instance conditionally_unfailing_of_unfailing [p.unfailing] : conditionally_unfailing p := ⟨λ _ _ _, p.exists_done _ _⟩ lemma exists_done_in_bounds (p : parser α) [p.conditionally_unfailing] {cb : char_buffer} {n : ℕ} (h : n < cb.size) : ∃ (n' : ℕ) (a : α), p cb n = done n' a := conditionally_unfailing.ex' h lemma conditionally_unfailing.of_fail [p.conditionally_unfailing] (h : p cb n = fail n' err) (hn : n < cb.size) : false := begin obtain ⟨np, a, hp⟩ := p.exists_done_in_bounds hn, simpa [hp] using h end lemma decorate_errors_fail (h : p cb n = fail n' err) : @decorate_errors α msgs p cb n = fail n ((dlist.lazy_of_list (msgs ()))) := by simp [decorate_errors, h] lemma decorate_errors_success (h : p cb n = done n' a) : @decorate_errors α msgs p cb n = done n' a := by simp [decorate_errors, h] lemma decorate_error_fail (h : p cb n = fail n' err) : @decorate_error α msg p cb n = fail n ((dlist.lazy_of_list ([msg ()]))) := decorate_errors_fail h lemma decorate_error_success (h : p cb n = done n' a) : @decorate_error α msg p cb n = done n' a := decorate_errors_success h @[simp] lemma decorate_errors_eq_done : @decorate_errors α msgs p cb n = done n' a ↔ p cb n = done n' a := by cases h : p cb n; simp [decorate_errors, h] @[simp] lemma decorate_error_eq_done : @decorate_error α msg p cb n = done n' a ↔ p cb n = done n' a := decorate_errors_eq_done @[simp] lemma decorate_errors_eq_fail : @decorate_errors α msgs p cb n = fail n' err ↔ n = n' ∧ err = dlist.lazy_of_list (msgs ()) ∧ ∃ np err', p cb n = fail np err' := by cases h : p cb n; simp [decorate_errors, h, eq_comm] @[simp] lemma decorate_error_eq_fail : @decorate_error α msg p cb n = fail n' err ↔ n = n' ∧ err = dlist.lazy_of_list ([msg ()]) ∧ ∃ np err', p cb n = fail np err' := decorate_errors_eq_fail @[simp] lemma return_eq_pure : (@return parser _ _ a) = pure a := rfl lemma pure_eq_done : (@pure parser _ _ a) = λ _ n, done n a := rfl @[simp] lemma pure_ne_fail : (pure a : parser α) cb n ≠ fail n' err := by simp [pure_eq_done] section bind variable (f : α → parser β) @[simp] lemma bind_eq_bind : p.bind f = p >>= f := rfl variable {f} @[simp] lemma bind_eq_done : (p >>= f) cb n = done n' b ↔ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ f a cb np = done n' b := by cases hp : p cb n; simp [hp, ←bind_eq_bind, parser.bind, and_assoc] @[simp] lemma bind_eq_fail : (p >>= f) cb n = fail n' err ↔ (p cb n = fail n' err) ∨ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ f a cb np = fail n' err) := by cases hp : p cb n; simp [hp, ←bind_eq_bind, parser.bind, and_assoc] @[simp] lemma and_then_eq_bind {α β : Type} {m : Type → Type} [monad m] (a : m α) (b : m β) : a >> b = a >>= (λ _, b) := rfl lemma and_then_fail : (p >> return ()) cb n = parse_result.fail n' err ↔ p cb n = fail n' err := by simp [pure_eq_done] lemma and_then_success : (p >> return ()) cb n = parse_result.done n' () ↔ ∃ a, p cb n = done n' a:= by simp [pure_eq_done] end bind section map variable {f : α → β} @[simp] lemma map_eq_done : (f <$> p) cb n = done n' b ↔ ∃ (a : α), p cb n = done n' a ∧ f a = b := by cases hp : p cb n; simp [←is_lawful_monad.bind_pure_comp_eq_map, hp, and_assoc, pure_eq_done] @[simp] lemma map_eq_fail : (f <$> p) cb n = fail n' err ↔ p cb n = fail n' err := by simp [←bind_pure_comp_eq_map, pure_eq_done] @[simp] lemma map_const_eq_done {b'} : (b <$ p) cb n = done n' b' ↔ ∃ (a : α), p cb n = done n' a ∧ b = b' := by simp [map_const_eq] @[simp] lemma map_const_eq_fail : (b <$ p) cb n = fail n' err ↔ p cb n = fail n' err := by simp only [map_const_eq, map_eq_fail] lemma map_const_rev_eq_done {b'} : (p $> b) cb n = done n' b' ↔ ∃ (a : α), p cb n = done n' a ∧ b = b' := map_const_eq_done lemma map_rev_const_eq_fail : (p $> b) cb n = fail n' err ↔ p cb n = fail n' err := map_const_eq_fail end map @[simp] lemma orelse_eq_orelse : p.orelse q = (p <|> q) := rfl @[simp] lemma orelse_eq_done : (p <|> q) cb n = done n' a ↔ (p cb n = done n' a ∨ (q cb n = done n' a ∧ ∃ err, p cb n = fail n err)) := begin cases hp : p cb n with np resp np errp, { simp [hp, ←orelse_eq_orelse, parser.orelse] }, { by_cases hn : np = n, { cases hq : q cb n with nq resq nq errq, { simp [hp, hn, hq, ←orelse_eq_orelse, parser.orelse] }, { rcases lt_trichotomy nq n with H|rfl|H; simp [hp, hn, hq, H, not_lt_of_lt H, lt_irrefl, ←orelse_eq_orelse, parser.orelse] <|> simp [hp, hn, hq, lt_irrefl, ←orelse_eq_orelse, parser.orelse] } }, { simp [hp, hn, ←orelse_eq_orelse, parser.orelse] } } end @[simp] lemma orelse_eq_fail_eq : (p <|> q) cb n = fail n err ↔ (p cb n = fail n err ∧ ∃ (nq errq), n < nq ∧ q cb n = fail nq errq) ∨ (∃ (errp errq), p cb n = fail n errp ∧ q cb n = fail n errq ∧ errp ++ errq = err) := begin cases hp : p cb n with np resp np errp, { simp [hp, ←orelse_eq_orelse, parser.orelse] }, { by_cases hn : np = n, { cases hq : q cb n with nq resq nq errq, { simp [hp, hn, hq, ←orelse_eq_orelse, parser.orelse] }, { rcases lt_trichotomy nq n with H|rfl|H; simp [hp, hq, hn, ←orelse_eq_orelse, parser.orelse, H, ne_of_gt H, ne_of_lt H, not_lt_of_lt H] <|> simp [hp, hq, hn, ←orelse_eq_orelse, parser.orelse, lt_irrefl] } }, { simp [hp, hn, ←orelse_eq_orelse, parser.orelse] } } end lemma orelse_eq_fail_not_mono_lt (hn : n' < n) : (p <|> q) cb n = fail n' err ↔ (p cb n = fail n' err) ∨ (q cb n = fail n' err ∧ (∃ (errp), p cb n = fail n errp)) := begin cases hp : p cb n with np resp np errp, { simp [hp, ←orelse_eq_orelse, parser.orelse] }, { by_cases h : np = n, { cases hq : q cb n with nq resq nq errq, { simp [hp, h, hn, hq, ne_of_gt hn, ←orelse_eq_orelse, parser.orelse] }, { rcases lt_trichotomy nq n with H|H|H, { simp [hp, hq, h, H, ne_of_gt hn, not_lt_of_lt H, ←orelse_eq_orelse, parser.orelse] }, { simp [hp, hq, h, H, ne_of_gt hn, lt_irrefl, ←orelse_eq_orelse, parser.orelse] }, { simp [hp, hq, h, H, ne_of_gt (hn.trans H), ←orelse_eq_orelse, parser.orelse] } } }, { simp [hp, h, ←orelse_eq_orelse, parser.orelse] } } end lemma orelse_eq_fail_of_mono_ne [q.mono] (hn : n ≠ n') : (p <|> q) cb n = fail n' err ↔ p cb n = fail n' err := begin cases hp : p cb n with np resp np errp, { simp [hp, ←orelse_eq_orelse, parser.orelse] }, { by_cases h : np = n, { cases hq : q cb n with nq resq nq errq, { simp [hp, h, hn, hq, hn, ←orelse_eq_orelse, parser.orelse] }, { have : n ≤ nq := mono.of_fail hq, rcases eq_or_lt_of_le this with rfl|H, { simp [hp, hq, h, hn, lt_irrefl, ←orelse_eq_orelse, parser.orelse] }, { simp [hp, hq, h, hn, H, ←orelse_eq_orelse, parser.orelse] } } }, { simp [hp, h, ←orelse_eq_orelse, parser.orelse] } }, end @[simp] lemma failure_eq_failure : @parser.failure α = failure := rfl @[simp] lemma failure_def : (failure : parser α) cb n = fail n dlist.empty := rfl lemma not_failure_eq_done : ¬ (failure : parser α) cb n = done n' a := by simp lemma failure_eq_fail : (failure : parser α) cb n = fail n' err ↔ n = n' ∧ err = dlist.empty := by simp [eq_comm] lemma seq_eq_done {f : parser (α → β)} {p : parser α} : (f <*> p) cb n = done n' b ↔ ∃ (nf : ℕ) (f' : α → β) (a : α), f cb n = done nf f' ∧ p cb nf = done n' a ∧ f' a = b := by simp [seq_eq_bind_map] lemma seq_eq_fail {f : parser (α → β)} {p : parser α} : (f <*> p) cb n = fail n' err ↔ (f cb n = fail n' err) ∨ (∃ (nf : ℕ) (f' : α → β), f cb n = done nf f' ∧ p cb nf = fail n' err) := by simp [seq_eq_bind_map] lemma seq_left_eq_done {p : parser α} {q : parser β} : (p <* q) cb n = done n' a ↔ ∃ (np : ℕ) (b : β), p cb n = done np a ∧ q cb np = done n' b := begin have : ∀ (p q : ℕ → α → Prop), (∃ (np : ℕ) (x : α), p np x ∧ q np x ∧ x = a) ↔ ∃ (np : ℕ), p np a ∧ q np a := λ _ _, ⟨λ ⟨np, x, hp, hq, rfl⟩, ⟨np, hp, hq⟩, λ ⟨np, hp, hq⟩, ⟨np, a, hp, hq, rfl⟩⟩, simp [seq_left_eq, seq_eq_done, map_eq_done, this] end lemma seq_left_eq_fail {p : parser α} {q : parser β} : (p <* q) cb n = fail n' err ↔ (p cb n = fail n' err) ∨ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ q cb np = fail n' err) := by simp [seq_left_eq, seq_eq_fail] lemma seq_right_eq_done {p : parser α} {q : parser β} : (p *> q) cb n = done n' b ↔ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ q cb np = done n' b := by simp [seq_right_eq, seq_eq_done, map_eq_done, and.comm, and.assoc] lemma seq_right_eq_fail {p : parser α} {q : parser β} : (p *> q) cb n = fail n' err ↔ (p cb n = fail n' err) ∨ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ q cb np = fail n' err) := by simp [seq_right_eq, seq_eq_fail] lemma mmap_eq_done {f : α → parser β} {a : α} {l : list α} {b : β} {l' : list β} : (a :: l).mmap f cb n = done n' (b :: l') ↔ ∃ (np : ℕ), f a cb n = done np b ∧ l.mmap f cb np = done n' l' := by simp [mmap, and.comm, and.assoc, and.left_comm, pure_eq_done] lemma mmap'_eq_done {f : α → parser β} {a : α} {l : list α} : (a :: l).mmap' f cb n = done n' () ↔ ∃ (np : ℕ) (b : β), f a cb n = done np b ∧ l.mmap' f cb np = done n' () := by simp [mmap'] lemma guard_eq_done {p : Prop} [decidable p] {u : unit} : @guard parser _ p _ cb n = done n' u ↔ p ∧ n = n' := by { by_cases hp : p; simp [guard, hp, pure_eq_done] } lemma guard_eq_fail {p : Prop} [decidable p] : @guard parser _ p _ cb n = fail n' err ↔ (¬ p) ∧ n = n' ∧ err = dlist.empty := by { by_cases hp : p; simp [guard, hp, eq_comm, pure_eq_done] } namespace mono variables {sep : parser unit} instance pure : mono (pure a) := ⟨λ _ _, by simp [pure_eq_done]⟩ instance bind {f : α → parser β} [p.mono] [∀ a, (f a).mono] : (p >>= f).mono := begin constructor, intros cb n, cases hx : (p >>= f) cb n, { obtain ⟨n', a, h, h'⟩ := bind_eq_done.mp hx, refine le_trans (of_done h) _, simpa [h'] using of_done h' }, { obtain h | ⟨n', a, h, h'⟩ := bind_eq_fail.mp hx, { simpa [h] using of_fail h }, { refine le_trans (of_done h) _, simpa [h'] using of_fail h' } } end instance and_then {q : parser β} [p.mono] [q.mono] : (p >> q).mono := mono.bind instance map [p.mono] {f : α → β} : (f <$> p).mono := mono.bind instance seq {f : parser (α → β)} [f.mono] [p.mono] : (f <*> p).mono := mono.bind instance mmap : Π {l : list α} {f : α → parser β} [∀ a ∈ l, (f a).mono], (l.mmap f).mono | [] _ _ := mono.pure | (a :: l) f h := begin convert mono.bind, { exact h _ (list.mem_cons_self _ _) }, { intro, convert mono.map, convert mmap, exact (λ _ ha, h _ (list.mem_cons_of_mem _ ha)) } end instance mmap' : Π {l : list α} {f : α → parser β} [∀ a ∈ l, (f a).mono], (l.mmap' f).mono | [] _ _ := mono.pure | (a :: l) f h := begin convert mono.and_then, { exact h _ (list.mem_cons_self _ _) }, { convert mmap', exact (λ _ ha, h _ (list.mem_cons_of_mem _ ha)) } end instance failure : (failure : parser α).mono := ⟨by simp [le_refl]⟩ instance guard {p : Prop} [decidable p] : mono (guard p) := ⟨by { by_cases h : p; simp [h, pure_eq_done, le_refl] }⟩ instance orelse [p.mono] [q.mono] : (p <|> q).mono := begin constructor, intros cb n, cases hx : (p <|> q) cb n with posx resx posx errx, { obtain h | ⟨h, -, -⟩ := orelse_eq_done.mp hx; simpa [h] using of_done h }, { by_cases h : n = posx, { simp [hx, h] }, { simp only [orelse_eq_fail_of_mono_ne h] at hx, exact of_fail hx } } end instance decorate_errors [p.mono] : (@decorate_errors α msgs p).mono := begin constructor, intros cb n, cases h : p cb n, { simpa [decorate_errors, h] using of_done h }, { simp [decorate_errors, h] } end instance decorate_error [p.mono] : (@decorate_error α msg p).mono := mono.decorate_errors instance any_char : mono any_char := begin constructor, intros cb n, by_cases h : n < cb.size; simp [any_char, h], end instance sat {p : char → Prop} [decidable_pred p] : mono (sat p) := begin constructor, intros cb n, simp only [sat], split_ifs; simp end instance eps : mono eps := mono.pure instance ch {c : char} : mono (ch c) := mono.decorate_error instance char_buf {s : char_buffer} : mono (char_buf s) := mono.decorate_error instance one_of {cs : list char} : (one_of cs).mono := mono.decorate_errors instance one_of' {cs : list char} : (one_of' cs).mono := mono.and_then instance str {s : string} : (str s).mono := mono.decorate_error instance remaining : remaining.mono := ⟨λ _ _, le_refl _⟩ instance eof : eof.mono := mono.decorate_error instance foldr_core {f : α → β → β} {b : β} [p.mono] : ∀ {reps : ℕ}, (foldr_core f p b reps).mono | 0 := mono.failure | (reps + 1) := begin convert mono.orelse, { convert mono.bind, { apply_instance }, { exact λ _, @mono.bind _ _ _ _ foldr_core _ } }, { exact mono.pure } end instance foldr {f : α → β → β} [p.mono] : mono (foldr f p b) := ⟨λ _ _, by { convert mono.le (foldr_core f p b _) _ _, exact mono.foldr_core }⟩ instance foldl_core {f : α → β → α} {p : parser β} [p.mono] : ∀ {a : α} {reps : ℕ}, (foldl_core f a p reps).mono | _ 0 := mono.failure | _ (reps + 1) := begin convert mono.orelse, { convert mono.bind, { apply_instance }, { exact λ _, foldl_core } }, { exact mono.pure } end instance foldl {f : α → β → α} {p : parser β} [p.mono] : mono (foldl f a p) := ⟨λ _ _, by { convert mono.le (foldl_core f a p _) _ _, exact mono.foldl_core }⟩ instance many [p.mono] : p.many.mono := mono.foldr instance many_char {p : parser char} [p.mono] : p.many_char.mono := mono.map instance many' [p.mono] : p.many'.mono := mono.and_then instance many1 [p.mono] : p.many1.mono := mono.seq instance many_char1 {p : parser char} [p.mono] : p.many_char1.mono := mono.map instance sep_by1 [p.mono] [sep.mono] : mono (sep_by1 sep p) := mono.seq instance sep_by [p.mono] [hs : sep.mono] : mono (sep_by sep p) := mono.orelse lemma fix_core {F : parser α → parser α} (hF : ∀ (p : parser α), p.mono → (F p).mono) : ∀ (max_depth : ℕ), mono (fix_core F max_depth) | 0 := mono.failure | (max_depth + 1) := hF _ (fix_core _) instance digit : digit.mono := mono.decorate_error instance nat : nat.mono := mono.decorate_error lemma fix {F : parser α → parser α} (hF : ∀ (p : parser α), p.mono → (F p).mono) : mono (fix F) := ⟨λ _ _, by { convert mono.le (parser.fix_core F _) _ _, exact fix_core hF _ }⟩ end mono @[simp] lemma orelse_pure_eq_fail : (p <|> pure a) cb n = fail n' err ↔ p cb n = fail n' err ∧ n ≠ n' := begin by_cases hn : n = n', { simp [hn, pure_eq_done] }, { simp [orelse_eq_fail_of_mono_ne, hn] } end end defn_lemmas section done variables {α β : Type} {cb : char_buffer} {n n' : ℕ} {a a' : α} {b : β} {c : char} {u : unit} {err : dlist string} lemma any_char_eq_done : any_char cb n = done n' c ↔ ∃ (hn : n < cb.size), n' = n + 1 ∧ cb.read ⟨n, hn⟩ = c := begin simp_rw [any_char], split_ifs with h; simp [h, eq_comm] end lemma any_char_eq_fail : any_char cb n = fail n' err ↔ n = n' ∧ err = dlist.empty ∧ cb.size ≤ n := begin simp_rw [any_char], split_ifs with h; simp [←not_lt, h, eq_comm] end lemma sat_eq_done {p : char → Prop} [decidable_pred p] : sat p cb n = done n' c ↔ ∃ (hn : n < cb.size), p c ∧ n' = n + 1 ∧ cb.read ⟨n, hn⟩ = c := begin by_cases hn : n < cb.size, { by_cases hp : p (cb.read ⟨n, hn⟩), { simp only [sat, hn, hp, dif_pos, if_true, exists_prop_of_true], split, { rintro ⟨rfl, rfl⟩, simp [hp] }, { rintro ⟨-, rfl, rfl⟩, simp } }, { simp only [sat, hn, hp, dif_pos, false_iff, not_and, exists_prop_of_true, if_false], rintro H - rfl, exact hp H } }, { simp [sat, hn] } end lemma sat_eq_fail {p : char → Prop} [decidable_pred p] : sat p cb n = fail n' err ↔ n = n' ∧ err = dlist.empty ∧ ∀ (h : n < cb.size), ¬ p (cb.read ⟨n, h⟩) := begin dsimp only [sat], split_ifs; simp [*, eq_comm] end lemma eps_eq_done : eps cb n = done n' u ↔ n = n' := by simp [eps, pure_eq_done] lemma ch_eq_done : ch c cb n = done n' u ↔ ∃ (hn : n < cb.size), n' = n + 1 ∧ cb.read ⟨n, hn⟩ = c := by simp [ch, eps_eq_done, sat_eq_done, and.comm, @eq_comm _ n'] lemma char_buf_eq_done {cb' : char_buffer} : char_buf cb' cb n = done n' u ↔ n + cb'.size = n' ∧ cb'.to_list <+: (cb.to_list.drop n) := begin simp only [char_buf, decorate_error_eq_done, ne.def, ←buffer.length_to_list], induction cb'.to_list with hd tl hl generalizing cb n n', { simp [pure_eq_done, mmap'_eq_done, -buffer.length_to_list, list.nil_prefix] }, { simp only [ch_eq_done, and.comm, and.assoc, and.left_comm, hl, mmap', and_then_eq_bind, bind_eq_done, list.length, exists_and_distrib_left, exists_const], split, { rintro ⟨np, h, rfl, rfl, hn, rfl⟩, simp only [add_comm, add_left_comm, h, true_and, eq_self_iff_true, and_true], have : n < cb.to_list.length := by simpa using hn, rwa [←buffer.nth_le_to_list _ this, ←list.cons_nth_le_drop_succ this, list.prefix_cons_inj] }, { rintro ⟨h, rfl⟩, by_cases hn : n < cb.size, { have : n < cb.to_list.length := by simpa using hn, rw [←list.cons_nth_le_drop_succ this, list.cons_prefix_iff] at h, use [n + 1, h.right], simpa [buffer.nth_le_to_list, add_comm, add_left_comm, add_assoc, hn] using h.left.symm }, { have : cb.to_list.length ≤ n := by simpa using hn, rw list.drop_eq_nil_of_le this at h, simpa using h } } } end lemma one_of_eq_done {cs : list char} : one_of cs cb n = done n' c ↔ ∃ (hn : n < cb.size), c ∈ cs ∧ n' = n + 1 ∧ cb.read ⟨n, hn⟩ = c := by simp [one_of, sat_eq_done] lemma one_of'_eq_done {cs : list char} : one_of' cs cb n = done n' u ↔ ∃ (hn : n < cb.size), cb.read ⟨n, hn⟩ ∈ cs ∧ n' = n + 1 := begin simp only [one_of', one_of_eq_done, eps_eq_done, and.comm, and_then_eq_bind, bind_eq_done, exists_eq_left, exists_and_distrib_left], split, { rintro ⟨c, hc, rfl, hn, rfl⟩, exact ⟨rfl, hn, hc⟩ }, { rintro ⟨rfl, hn, hc⟩, exact ⟨cb.read ⟨n, hn⟩, hc, rfl, hn, rfl⟩ } end lemma str_eq_char_buf (s : string) : str s = char_buf s.to_list.to_buffer := begin ext cb n, rw [str, char_buf], congr, { simp [buffer.to_string, string.as_string_inv_to_list] }, { simp } end lemma str_eq_done {s : string} : str s cb n = done n' u ↔ n + s.length = n' ∧ s.to_list <+: (cb.to_list.drop n) := by simp [str_eq_char_buf, char_buf_eq_done] lemma remaining_eq_done {r : ℕ} : remaining cb n = done n' r ↔ n = n' ∧ cb.size - n = r := by simp [remaining] lemma remaining_ne_fail : remaining cb n ≠ fail n' err := by simp [remaining] lemma eof_eq_done {u : unit} : eof cb n = done n' u ↔ n = n' ∧ cb.size ≤ n := by simp [eof, guard_eq_done, remaining_eq_done, tsub_eq_zero_iff_le, and_comm, and_assoc] @[simp] lemma foldr_core_zero_eq_done {f : α → β → β} {p : parser α} {b' : β} : foldr_core f p b 0 cb n ≠ done n' b' := by simp [foldr_core] lemma foldr_core_eq_done {f : α → β → β} {p : parser α} {reps : ℕ} {b' : β} : foldr_core f p b (reps + 1) cb n = done n' b' ↔ (∃ (np : ℕ) (a : α) (xs : β), p cb n = done np a ∧ foldr_core f p b reps cb np = done n' xs ∧ f a xs = b') ∨ (n = n' ∧ b = b' ∧ ∃ (err), (p cb n = fail n err) ∨ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldr_core f p b reps cb np = fail n err)) := by simp [foldr_core, and.comm, and.assoc, pure_eq_done] @[simp] lemma foldr_core_zero_eq_fail {f : α → β → β} {p : parser α} {err : dlist string} : foldr_core f p b 0 cb n = fail n' err ↔ n = n' ∧ err = dlist.empty := by simp [foldr_core, eq_comm] lemma foldr_core_succ_eq_fail {f : α → β → β} {p : parser α} {reps : ℕ} {err : dlist string} : foldr_core f p b (reps + 1) cb n = fail n' err ↔ n ≠ n' ∧ (p cb n = fail n' err ∨ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldr_core f p b reps cb np = fail n' err) := by simp [foldr_core, and_comm] lemma foldr_eq_done {f : α → β → β} {p : parser α} {b' : β} : foldr f p b cb n = done n' b' ↔ ((∃ (np : ℕ) (a : α) (x : β), p cb n = done np a ∧ foldr_core f p b (cb.size - n) cb np = done n' x ∧ f a x = b') ∨ (n = n' ∧ b = b' ∧ (∃ (err), p cb n = parse_result.fail n err ∨ ∃ (np : ℕ) (x : α), p cb n = done np x ∧ foldr_core f p b (cb.size - n) cb np = fail n err))) := by simp [foldr, foldr_core_eq_done] lemma foldr_eq_fail_iff_mono_at_end {f : α → β → β} {p : parser α} {err : dlist string} [p.mono] (hc : cb.size ≤ n) : foldr f p b cb n = fail n' err ↔ n < n' ∧ (p cb n = fail n' err ∨ ∃ (a : α), p cb n = done n' a ∧ err = dlist.empty) := begin have : cb.size - n = 0 := tsub_eq_zero_iff_le.mpr hc, simp only [foldr, foldr_core_succ_eq_fail, this, and.left_comm, foldr_core_zero_eq_fail, ne_iff_lt_iff_le, exists_and_distrib_right, exists_eq_left, and.congr_left_iff, exists_and_distrib_left], rintro (h | ⟨⟨a, h⟩, rfl⟩), { exact mono.of_fail h }, { exact mono.of_done h } end lemma foldr_eq_fail {f : α → β → β} {p : parser α} {err : dlist string} : foldr f p b cb n = fail n' err ↔ n ≠ n' ∧ (p cb n = fail n' err ∨ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldr_core f p b (cb.size - n) cb np = fail n' err) := by simp [foldr, foldr_core_succ_eq_fail] @[simp] lemma foldl_core_zero_eq_done {f : β → α → β} {p : parser α} {b' : β} : foldl_core f b p 0 cb n = done n' b' ↔ false := by simp [foldl_core] lemma foldl_core_eq_done {f : β → α → β} {p : parser α} {reps : ℕ} {b' : β} : foldl_core f b p (reps + 1) cb n = done n' b' ↔ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldl_core f (f b a) p reps cb np = done n' b') ∨ (n = n' ∧ b = b' ∧ ∃ (err), (p cb n = fail n err) ∨ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldl_core f (f b a) p reps cb np = fail n err)) := by simp [foldl_core, and.assoc, pure_eq_done] @[simp] lemma foldl_core_zero_eq_fail {f : β → α → β} {p : parser α} {err : dlist string} : foldl_core f b p 0 cb n = fail n' err ↔ n = n' ∧ err = dlist.empty := by simp [foldl_core, eq_comm] lemma foldl_core_succ_eq_fail {f : β → α → β} {p : parser α} {reps : ℕ} {err : dlist string} : foldl_core f b p (reps + 1) cb n = fail n' err ↔ n ≠ n' ∧ (p cb n = fail n' err ∨ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldl_core f (f b a) p reps cb np = fail n' err) := by simp [foldl_core, and_comm] lemma foldl_eq_done {f : β → α → β} {p : parser α} {b' : β} : foldl f b p cb n = done n' b' ↔ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldl_core f (f b a) p (cb.size - n) cb np = done n' b') ∨ (n = n' ∧ b = b' ∧ ∃ (err), (p cb n = fail n err) ∨ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldl_core f (f b a) p (cb.size - n) cb np = fail n err)) := by simp [foldl, foldl_core_eq_done] lemma foldl_eq_fail {f : β → α → β} {p : parser α} {err : dlist string} : foldl f b p cb n = fail n' err ↔ n ≠ n' ∧ (p cb n = fail n' err ∨ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldl_core f (f b a) p (cb.size - n) cb np = fail n' err) := by simp [foldl, foldl_core_succ_eq_fail] lemma foldl_eq_fail_iff_mono_at_end {f : β → α → β} {p : parser α} {err : dlist string} [p.mono] (hc : cb.size ≤ n) : foldl f b p cb n = fail n' err ↔ n < n' ∧ (p cb n = fail n' err ∨ ∃ (a : α), p cb n = done n' a ∧ err = dlist.empty) := begin have : cb.size - n = 0 := tsub_eq_zero_iff_le.mpr hc, simp only [foldl, foldl_core_succ_eq_fail, this, and.left_comm, ne_iff_lt_iff_le, exists_eq_left, exists_and_distrib_right, and.congr_left_iff, exists_and_distrib_left, foldl_core_zero_eq_fail], rintro (h | ⟨⟨a, h⟩, rfl⟩), { exact mono.of_fail h }, { exact mono.of_done h } end lemma many_eq_done_nil {p : parser α} : many p cb n = done n' (@list.nil α) ↔ n = n' ∧ ∃ (err), p cb n = fail n err ∨ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldr_core list.cons p [] (cb.size - n) cb np = fail n err := by simp [many, foldr_eq_done] lemma many_eq_done {p : parser α} {x : α} {xs : list α} : many p cb n = done n' (x :: xs) ↔ ∃ (np : ℕ), p cb n = done np x ∧ foldr_core list.cons p [] (cb.size - n) cb np = done n' xs := by simp [many, foldr_eq_done, and.comm, and.assoc, and.left_comm] lemma many_eq_fail {p : parser α} {err : dlist string} : many p cb n = fail n' err ↔ n ≠ n' ∧ (p cb n = fail n' err ∨ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldr_core list.cons p [] (cb.size - n) cb np = fail n' err) := by simp [many, foldr_eq_fail] lemma many_char_eq_done_empty {p : parser char} : many_char p cb n = done n' string.empty ↔ n = n' ∧ ∃ (err), p cb n = fail n err ∨ ∃ (np : ℕ) (c : char), p cb n = done np c ∧ foldr_core list.cons p [] (cb.size - n) cb np = fail n err := by simp [many_char, many_eq_done_nil, map_eq_done, list.as_string_eq] lemma many_char_eq_done_not_empty {p : parser char} {s : string} (h : s ≠ "") : many_char p cb n = done n' s ↔ ∃ (np : ℕ), p cb n = done np s.head ∧ foldr_core list.cons p list.nil (buffer.size cb - n) cb np = done n' (s.popn 1).to_list := by simp [many_char, list.as_string_eq, string.to_list_nonempty h, many_eq_done] lemma many_char_eq_many_of_to_list {p : parser char} {s : string} : many_char p cb n = done n' s ↔ many p cb n = done n' s.to_list := by simp [many_char, list.as_string_eq] lemma many'_eq_done {p : parser α} : many' p cb n = done n' u ↔ many p cb n = done n' [] ∨ ∃ (np : ℕ) (a : α) (l : list α), many p cb n = done n' (a :: l) ∧ p cb n = done np a ∧ foldr_core list.cons p [] (buffer.size cb - n) cb np = done n' l := begin simp only [many', eps_eq_done, many, foldr, and_then_eq_bind, exists_and_distrib_right, bind_eq_done, exists_eq_right], split, { rintro ⟨_ | ⟨hd, tl⟩, hl⟩, { exact or.inl hl }, { have hl2 := hl, simp only [foldr_core_eq_done, or_false, exists_and_distrib_left, and_false, false_and, exists_eq_right_right] at hl, obtain ⟨np, hp, h⟩ := hl, refine or.inr ⟨np, _, _, hl2, hp, h⟩ } }, { rintro (h | ⟨np, a, l, hp, h⟩), { exact ⟨[], h⟩ }, { refine ⟨a :: l, hp⟩ } } end @[simp] lemma many1_ne_done_nil {p : parser α} : many1 p cb n ≠ done n' [] := by simp [many1, seq_eq_done] lemma many1_eq_done {p : parser α} {l : list α} : many1 p cb n = done n' (a :: l) ↔ ∃ (np : ℕ), p cb n = done np a ∧ many p cb np = done n' l := by simp [many1, seq_eq_done, map_eq_done] lemma many1_eq_fail {p : parser α} {err : dlist string} : many1 p cb n = fail n' err ↔ p cb n = fail n' err ∨ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ many p cb np = fail n' err) := by simp [many1, seq_eq_fail] @[simp] lemma many_char1_ne_empty {p : parser char} : many_char1 p cb n ≠ done n' "" := by simp [many_char1, ←string.nil_as_string_eq_empty] lemma many_char1_eq_done {p : parser char} {s : string} (h : s ≠ "") : many_char1 p cb n = done n' s ↔ ∃ (np : ℕ), p cb n = done np s.head ∧ many_char p cb np = done n' (s.popn 1) := by simp [many_char1, list.as_string_eq, string.to_list_nonempty h, many1_eq_done, many_char_eq_many_of_to_list] @[simp] lemma sep_by1_ne_done_nil {sep : parser unit} {p : parser α} : sep_by1 sep p cb n ≠ done n' [] := by simp [sep_by1, seq_eq_done] lemma sep_by1_eq_done {sep : parser unit} {p : parser α} {l : list α} : sep_by1 sep p cb n = done n' (a :: l) ↔ ∃ (np : ℕ), p cb n = done np a ∧ (sep >> p).many cb np = done n' l := by simp [sep_by1, seq_eq_done] lemma sep_by_eq_done_nil {sep : parser unit} {p : parser α} : sep_by sep p cb n = done n' [] ↔ n = n' ∧ ∃ (err), sep_by1 sep p cb n = fail n err := by simp [sep_by, pure_eq_done] @[simp] lemma fix_core_ne_done_zero {F : parser α → parser α} : fix_core F 0 cb n ≠ done n' a := by simp [fix_core] lemma fix_core_eq_done {F : parser α → parser α} {max_depth : ℕ} : fix_core F (max_depth + 1) cb n = done n' a ↔ F (fix_core F max_depth) cb n = done n' a := by simp [fix_core] lemma digit_eq_done {k : ℕ} : digit cb n = done n' k ↔ ∃ (hn : n < cb.size), n' = n + 1 ∧ k ≤ 9 ∧ (cb.read ⟨n, hn⟩).to_nat - '0'.to_nat = k ∧ '0' ≤ cb.read ⟨n, hn⟩ ∧ cb.read ⟨n, hn⟩ ≤ '9' := begin have c9 : '9'.to_nat - '0'.to_nat = 9 := rfl, have l09 : '0'.to_nat ≤ '9'.to_nat := dec_trivial, have le_iff_le : ∀ {c c' : char}, c ≤ c' ↔ c.to_nat ≤ c'.to_nat := λ _ _, iff.rfl, split, { simp only [digit, sat_eq_done, pure_eq_done, decorate_error_eq_done, bind_eq_done, ←c9], rintro ⟨np, c, ⟨hn, ⟨ge0, le9⟩, rfl, rfl⟩, rfl, rfl⟩, simpa [hn, ge0, le9, true_and, and_true, eq_self_iff_true, exists_prop_of_true, tsub_le_tsub_iff_right, l09] using (le_iff_le.mp le9) }, { simp only [digit, sat_eq_done, pure_eq_done, decorate_error_eq_done, bind_eq_done, ←c9, le_iff_le], rintro ⟨hn, rfl, -, rfl, ge0, le9⟩, use [n + 1, cb.read ⟨n, hn⟩], simp [hn, ge0, le9] } end lemma digit_eq_fail : digit cb n = fail n' err ↔ n = n' ∧ err = dlist.of_list ["<digit>"] ∧ ∀ (h : n < cb.size), ¬ ((λ c, '0' ≤ c ∧ c ≤ '9') (cb.read ⟨n, h⟩)) := by simp [digit, sat_eq_fail] end done namespace static variables {α β : Type} {p q : parser α} {msgs : thunk (list string)} {msg : thunk string} {cb : char_buffer} {n' n : ℕ} {err : dlist string} {a : α} {b : β} {sep : parser unit} lemma not_of_ne (h : p cb n = done n' a) (hne : n ≠ n') : ¬ static p := by { introI, exact hne (of_done h) } instance pure : static (pure a) := ⟨λ _ _ _ _, by { simp_rw pure_eq_done, rw [and.comm], simp }⟩ instance bind {f : α → parser β} [p.static] [∀ a, (f a).static] : (p >>= f).static := ⟨λ _ _ _ _, by { rw bind_eq_done, rintro ⟨_, _, hp, hf⟩, exact trans (of_done hp) (of_done hf) }⟩ instance and_then {q : parser β} [p.static] [q.static] : (p >> q).static := static.bind instance map [p.static] {f : α → β} : (f <$> p).static := ⟨λ _ _ _ _, by { simp_rw map_eq_done, rintro ⟨_, hp, _⟩, exact of_done hp }⟩ instance seq {f : parser (α → β)} [f.static] [p.static] : (f <*> p).static := static.bind instance mmap : Π {l : list α} {f : α → parser β} [∀ a, (f a).static], (l.mmap f).static | [] _ _ := static.pure | (a :: l) _ h := begin convert static.bind, { exact h _ }, { intro, convert static.bind, { convert mmap, exact h }, { exact λ _, static.pure } } end instance mmap' : Π {l : list α} {f : α → parser β} [∀ a, (f a).static], (l.mmap' f).static | [] _ _ := static.pure | (a :: l) _ h := begin convert static.and_then, { exact h _ }, { convert mmap', exact h } end instance failure : @parser.static α failure := ⟨λ _ _ _ _, by simp⟩ instance guard {p : Prop} [decidable p] : static (guard p) := ⟨λ _ _ _ _, by simp [guard_eq_done]⟩ instance orelse [p.static] [q.static] : (p <|> q).static := ⟨λ _ _ _ _, by { simp_rw orelse_eq_done, rintro (h | ⟨h, -⟩); exact of_done h }⟩ instance decorate_errors [p.static] : (@decorate_errors α msgs p).static := ⟨λ _ _ _ _, by { rw decorate_errors_eq_done, exact of_done }⟩ instance decorate_error [p.static] : (@decorate_error α msg p).static := static.decorate_errors lemma any_char : ¬ static any_char := begin have : any_char "s".to_char_buffer 0 = done 1 's', { have : 0 < "s".to_char_buffer.size := dec_trivial, simpa [any_char_eq_done, this] }, exact not_of_ne this zero_ne_one end lemma sat_iff {p : char → Prop} [decidable_pred p] : static (sat p) ↔ ∀ c, ¬ p c := begin split, { introI, intros c hc, have : sat p [c].to_buffer 0 = done 1 c := by simp [sat_eq_done, hc], exact zero_ne_one (of_done this) }, { contrapose!, simp only [iff, sat_eq_done, and_imp, exists_prop, exists_and_distrib_right, exists_and_distrib_left, exists_imp_distrib, not_forall], rintros _ _ _ a h hne rfl hp -, exact ⟨a, hp⟩ } end instance sat : static (sat (λ _, false)) := by { apply sat_iff.mpr, simp } instance eps : static eps := static.pure lemma ch (c : char) : ¬ static (ch c) := begin have : ch c [c].to_buffer 0 = done 1 (), { have : 0 < [c].to_buffer.size := dec_trivial, simp [ch_eq_done, this] }, exact not_of_ne this zero_ne_one end lemma char_buf_iff {cb' : char_buffer} : static (char_buf cb') ↔ cb' = buffer.nil := begin rw ←buffer.size_eq_zero_iff, have : char_buf cb' cb' 0 = done cb'.size () := by simp [char_buf_eq_done], cases hc : cb'.size with n, { simp only [eq_self_iff_true, iff_true], exact ⟨λ _ _ _ _ h, by simpa [hc] using (char_buf_eq_done.mp h).left⟩ }, { rw hc at this, simpa [nat.succ_ne_zero] using not_of_ne this (nat.succ_ne_zero n).symm } end lemma one_of_iff {cs : list char} : static (one_of cs) ↔ cs = [] := begin cases cs with hd tl, { simp [one_of, static.decorate_errors] }, { have : one_of (hd :: tl) (hd :: tl).to_buffer 0 = done 1 hd, { simp [one_of_eq_done] }, simpa using not_of_ne this zero_ne_one } end instance one_of : static (one_of []) := by { apply one_of_iff.mpr, refl } lemma one_of'_iff {cs : list char} : static (one_of' cs) ↔ cs = [] := begin cases cs with hd tl, { simp [one_of', static.bind], }, { have : one_of' (hd :: tl) (hd :: tl).to_buffer 0 = done 1 (), { simp [one_of'_eq_done] }, simpa using not_of_ne this zero_ne_one } end instance one_of' : static (one_of []) := by { apply one_of_iff.mpr, refl } lemma str_iff {s : string} : static (str s) ↔ s = "" := by simp [str_eq_char_buf, char_buf_iff, ←string.to_list_inj, buffer.ext_iff] instance remaining : remaining.static := ⟨λ _ _ _ _ h, (remaining_eq_done.mp h).left⟩ instance eof : eof.static := static.decorate_error instance foldr_core {f : α → β → β} [p.static] : ∀ {b : β} {reps : ℕ}, (foldr_core f p b reps).static | _ 0 := static.failure | _ (reps + 1) := begin simp_rw parser.foldr_core, convert static.orelse, { convert static.bind, { apply_instance }, { intro, convert static.bind, { exact foldr_core }, { apply_instance } } }, { exact static.pure } end instance foldr {f : α → β → β} [p.static] : static (foldr f p b) := ⟨λ _ _ _ _, by { dsimp [foldr], exact of_done }⟩ instance foldl_core {f : α → β → α} {p : parser β} [p.static] : ∀ {a : α} {reps : ℕ}, (foldl_core f a p reps).static | _ 0 := static.failure | _ (reps + 1) := begin convert static.orelse, { convert static.bind, { apply_instance }, { exact λ _, foldl_core } }, { exact static.pure } end instance foldl {f : α → β → α} {p : parser β} [p.static] : static (foldl f a p) := ⟨λ _ _ _ _, by { dsimp [foldl], exact of_done }⟩ instance many [p.static] : p.many.static := static.foldr instance many_char {p : parser char} [p.static] : p.many_char.static := static.map instance many' [p.static] : p.many'.static := static.and_then instance many1 [p.static] : p.many1.static := static.seq instance many_char1 {p : parser char} [p.static] : p.many_char1.static := static.map instance sep_by1 [p.static] [sep.static] : static (sep_by1 sep p) := static.seq instance sep_by [p.static] [sep.static] : static (sep_by sep p) := static.orelse lemma fix_core {F : parser α → parser α} (hF : ∀ (p : parser α), p.static → (F p).static) : ∀ (max_depth : ℕ), static (fix_core F max_depth) | 0 := static.failure | (max_depth + 1) := hF _ (fix_core _) lemma digit : ¬ digit.static := begin have : digit "1".to_char_buffer 0 = done 1 1, { have : 0 < "s".to_char_buffer.size := dec_trivial, simpa [this] }, exact not_of_ne this zero_ne_one end lemma nat : ¬ nat.static := begin have : nat "1".to_char_buffer 0 = done 1 1, { have : 0 < "s".to_char_buffer.size := dec_trivial, simpa [this] }, exact not_of_ne this zero_ne_one end lemma fix {F : parser α → parser α} (hF : ∀ (p : parser α), p.static → (F p).static) : static (fix F) := ⟨λ cb n _ _ h, by { haveI := fix_core hF (cb.size - n + 1), dsimp [fix] at h, exact static.of_done h }⟩ end static namespace bounded variables {α β : Type} {msgs : thunk (list string)} {msg : thunk string} variables {p q : parser α} {cb : char_buffer} {n n' : ℕ} {err : dlist string} variables {a : α} {b : β} lemma done_of_unbounded (h : ¬p.bounded) : ∃ (cb : char_buffer) (n n' : ℕ) (a : α), p cb n = done n' a ∧ cb.size ≤ n := begin contrapose! h, constructor, intros cb n hn, cases hp : p cb n, { exact absurd hn (h _ _ _ _ hp).not_le }, { simp [hp] } end lemma pure : ¬ bounded (pure a) := begin introI, have : (pure a : parser α) buffer.nil 0 = done 0 a := by simp [pure_eq_done], exact absurd (bounded.of_done this) (lt_irrefl _) end instance bind {f : α → parser β} [p.bounded] : (p >>= f).bounded := begin constructor, intros cb n hn, obtain ⟨_, _, hp⟩ := bounded.exists p hn, simp [hp] end instance and_then {q : parser β} [p.bounded] : (p >> q).bounded := bounded.bind instance map [p.bounded] {f : α → β} : (f <$> p).bounded := bounded.bind instance seq {f : parser (α → β)} [f.bounded] : (f <*> p).bounded := bounded.bind instance mmap {a : α} {l : list α} {f : α → parser β} [∀ a, (f a).bounded] : ((a :: l).mmap f).bounded := bounded.bind instance mmap' {a : α} {l : list α} {f : α → parser β} [∀ a, (f a).bounded] : ((a :: l).mmap' f).bounded := bounded.and_then instance failure : @parser.bounded α failure := ⟨by simp⟩ lemma guard_iff {p : Prop} [decidable p] : bounded (guard p) ↔ ¬ p := by simpa [guard, apply_ite bounded, pure, failure] using λ _, bounded.failure instance orelse [p.bounded] [q.bounded] : (p <|> q).bounded := begin constructor, intros cb n hn, cases hx : (p <|> q) cb n with posx resx posx errx, { obtain h | ⟨h, -, -⟩ := orelse_eq_done.mp hx; exact absurd hn (of_done h).not_le }, { simp } end instance decorate_errors [p.bounded] : (@decorate_errors α msgs p).bounded := begin constructor, intros _ _, simpa using bounded.exists p end lemma decorate_errors_iff : (@parser.decorate_errors α msgs p).bounded ↔ p.bounded := begin split, { introI, constructor, intros _ _ hn, obtain ⟨_, _, h⟩ := bounded.exists (@parser.decorate_errors α msgs p) hn, simp [decorate_errors_eq_fail] at h, exact h.right.right }, { introI, constructor, intros _ _ hn, obtain ⟨_, _, h⟩ := bounded.exists p hn, simp [h] } end instance decorate_error [p.bounded] : (@decorate_error α msg p).bounded := bounded.decorate_errors lemma decorate_error_iff : (@parser.decorate_error α msg p).bounded ↔ p.bounded := decorate_errors_iff instance any_char : bounded any_char := ⟨λ cb n hn, by simp [any_char, hn]⟩ instance sat {p : char → Prop} [decidable_pred p] : bounded (sat p) := ⟨λ cb n hn, by simp [sat, hn]⟩ lemma eps : ¬ bounded eps := pure instance ch {c : char} : bounded (ch c) := bounded.decorate_error lemma char_buf_iff {cb' : char_buffer} : bounded (char_buf cb') ↔ cb' ≠ buffer.nil := begin have : cb' ≠ buffer.nil ↔ cb'.to_list ≠ [] := not_iff_not_of_iff ⟨λ h, by simp [h], λ h, by simpa using congr_arg list.to_buffer h⟩, rw [char_buf, decorate_error_iff, this], cases cb'.to_list, { simp [pure, ch] }, { simp only [iff_true, ne.def, not_false_iff], apply_instance } end instance one_of {cs : list char} : (one_of cs).bounded := bounded.decorate_errors instance one_of' {cs : list char} : (one_of' cs).bounded := bounded.and_then lemma str_iff {s : string} : (str s).bounded ↔ s ≠ "" := begin rw [str, decorate_error_iff], cases hs : s.to_list, { have : s = "", { cases s, rw [string.to_list] at hs, simpa [hs] }, simp [pure, this] }, { have : s ≠ "", { intro H, simpa [H] using hs }, simp only [this, iff_true, ne.def, not_false_iff], apply_instance } end lemma remaining : ¬ remaining.bounded := begin introI, have : remaining buffer.nil 0 = done 0 0 := by simp [remaining_eq_done], exact absurd (bounded.of_done this) (lt_irrefl _) end lemma eof : ¬ eof.bounded := begin introI, have : eof buffer.nil 0 = done 0 () := by simp [eof_eq_done], exact absurd (bounded.of_done this) (lt_irrefl _) end section fold instance foldr_core_zero {f : α → β → β} : (foldr_core f p b 0).bounded := bounded.failure instance foldl_core_zero {f : β → α → β} {b : β} : (foldl_core f b p 0).bounded := bounded.failure variables {reps : ℕ} [hpb : p.bounded] (he : ∀ cb n n' err, p cb n = fail n' err → n ≠ n') include hpb he lemma foldr_core {f : α → β → β} : (foldr_core f p b reps).bounded := begin cases reps, { exact bounded.foldr_core_zero }, constructor, intros cb n hn, obtain ⟨np, errp, hp⟩ := bounded.exists p hn, simpa [foldr_core_succ_eq_fail, hp] using he cb n np errp, end lemma foldr {f : α → β → β} : bounded (foldr f p b) := begin constructor, intros cb n hn, haveI : (parser.foldr_core f p b (cb.size - n + 1)).bounded := foldr_core he, obtain ⟨np, errp, hp⟩ := bounded.exists (parser.foldr_core f p b (cb.size - n + 1)) hn, simp [foldr, hp] end lemma foldl_core {f : β → α → β} : (foldl_core f b p reps).bounded := begin cases reps, { exact bounded.foldl_core_zero }, constructor, intros cb n hn, obtain ⟨np, errp, hp⟩ := bounded.exists p hn, simpa [foldl_core_succ_eq_fail, hp] using he cb n np errp, end lemma foldl {f : β → α → β} : bounded (foldl f b p) := begin constructor, intros cb n hn, haveI : (parser.foldl_core f b p (cb.size - n + 1)).bounded := foldl_core he, obtain ⟨np, errp, hp⟩ := bounded.exists (parser.foldl_core f b p (cb.size - n + 1)) hn, simp [foldl, hp] end lemma many : p.many.bounded := foldr he omit hpb lemma many_char {pc : parser char} [pc.bounded] (he : ∀ cb n n' err, pc cb n = fail n' err → n ≠ n'): pc.many_char.bounded := by { convert bounded.map, exact many he } include hpb lemma many' : p.many'.bounded := by { convert bounded.and_then, exact many he } end fold instance many1 [p.bounded] : p.many1.bounded := bounded.seq instance many_char1 {p : parser char} [p.bounded] : p.many_char1.bounded := bounded.map instance sep_by1 {sep : parser unit} [p.bounded] : bounded (sep_by1 sep p) := bounded.seq lemma fix_core {F : parser α → parser α} (hF : ∀ (p : parser α), p.bounded → (F p).bounded) : ∀ (max_depth : ℕ), bounded (fix_core F max_depth) | 0 := bounded.failure | (max_depth + 1) := hF _ (fix_core _) instance digit : digit.bounded := bounded.decorate_error instance nat : nat.bounded := bounded.decorate_error lemma fix {F : parser α → parser α} (hF : ∀ (p : parser α), p.bounded → (F p).bounded) : bounded (fix F) := begin constructor, intros cb n hn, haveI : (parser.fix_core F (cb.size - n + 1)).bounded := fix_core hF _, obtain ⟨np, errp, hp⟩ := bounded.exists (parser.fix_core F (cb.size - n + 1)) hn, simp [fix, hp] end end bounded namespace unfailing variables {α β : Type} {p q : parser α} {msgs : thunk (list string)} {msg : thunk string} {cb : char_buffer} {n' n : ℕ} {err : dlist string} {a : α} {b : β} {sep : parser unit} lemma of_bounded [p.bounded] : ¬ unfailing p := begin introI, cases h : p buffer.nil 0, { simpa [lt_irrefl] using bounded.of_done h }, { exact of_fail h } end instance pure : unfailing (pure a) := ⟨λ _ _, by simp [pure_eq_done]⟩ instance bind {f : α → parser β} [p.unfailing] [∀ a, (f a).unfailing] : (p >>= f).unfailing := ⟨λ cb n, begin obtain ⟨np, a, hp⟩ := exists_done p cb n, simpa [hp, and.comm, and.left_comm, and.assoc] using exists_done (f a) cb np end⟩ instance and_then {q : parser β} [p.unfailing] [q.unfailing] : (p >> q).unfailing := unfailing.bind instance map [p.unfailing] {f : α → β} : (f <$> p).unfailing := unfailing.bind instance seq {f : parser (α → β)} [f.unfailing] [p.unfailing] : (f <*> p).unfailing := unfailing.bind instance mmap {l : list α} {f : α → parser β} [∀ a, (f a).unfailing] : (l.mmap f).unfailing := begin constructor, induction l with hd tl hl, { intros, simp [pure_eq_done] }, { intros, obtain ⟨np, a, hp⟩ := exists_done (f hd) cb n, obtain ⟨n', b, hf⟩ := hl cb np, simp [hp, hf, and.comm, and.left_comm, and.assoc, pure_eq_done] } end instance mmap' {l : list α} {f : α → parser β} [∀ a, (f a).unfailing] : (l.mmap' f).unfailing := begin constructor, induction l with hd tl hl, { intros, simp [pure_eq_done] }, { intros, obtain ⟨np, a, hp⟩ := exists_done (f hd) cb n, obtain ⟨n', b, hf⟩ := hl cb np, simp [hp, hf, and.comm, and.left_comm, and.assoc, pure_eq_done] } end lemma failure : ¬ @parser.unfailing α failure := begin introI h, have : (failure : parser α) buffer.nil 0 = fail 0 dlist.empty := by simp, exact of_fail this end instance guard_true : unfailing (guard true) := unfailing.pure lemma guard : ¬ unfailing (guard false) := unfailing.failure instance orelse [p.unfailing] : (p <|> q).unfailing := ⟨λ cb n, by { obtain ⟨_, _, h⟩ := p.exists_done cb n, simp [success_iff, h] }⟩ instance decorate_errors [p.unfailing] : (@decorate_errors α msgs p).unfailing := ⟨λ cb n, by { obtain ⟨_, _, h⟩ := p.exists_done cb n, simp [success_iff, h] }⟩ instance decorate_error [p.unfailing] : (@decorate_error α msg p).unfailing := unfailing.decorate_errors instance any_char : conditionally_unfailing any_char := ⟨λ _ _ hn, by simp [success_iff, any_char_eq_done, hn]⟩ lemma sat : conditionally_unfailing (sat (λ _, true)) := ⟨λ _ _ hn, by simp [success_iff, sat_eq_done, hn]⟩ instance eps : unfailing eps := unfailing.pure instance remaining : remaining.unfailing := ⟨λ _ _, by simp [success_iff, remaining_eq_done]⟩ lemma foldr_core_zero {f : α → β → β} {b : β} : ¬ (foldr_core f p b 0).unfailing := unfailing.failure instance foldr_core_of_static {f : α → β → β} {b : β} {reps : ℕ} [p.static] [p.unfailing] : (foldr_core f p b (reps + 1)).unfailing := begin induction reps with reps hr, { constructor, intros cb n, obtain ⟨np, a, h⟩ := p.exists_done cb n, simpa [foldr_core_eq_done, h] using (static.of_done h).symm }, { constructor, haveI := hr, intros cb n, obtain ⟨np, a, h⟩ := p.exists_done cb n, have : n = np := static.of_done h, subst this, obtain ⟨np, b', hf⟩ := exists_done (foldr_core f p b (reps + 1)) cb n, have : n = np := static.of_done hf, subst this, refine ⟨n, f a b', _⟩, rw foldr_core_eq_done, simp [h, hf, and.comm, and.left_comm, and.assoc] } end instance foldr_core_one_of_err_static {f : α → β → β} {b : β} [p.static] [p.err_static] : (foldr_core f p b 1).unfailing := begin constructor, intros cb n, cases h : p cb n, { simpa [foldr_core_eq_done, h] using (static.of_done h).symm }, { simpa [foldr_core_eq_done, h] using (err_static.of_fail h).symm } end -- TODO: add foldr and foldl, many, etc, fix_core lemma digit : ¬ digit.unfailing := of_bounded lemma nat : ¬ nat.unfailing := of_bounded end unfailing namespace err_static variables {α β : Type} {p q : parser α} {msgs : thunk (list string)} {msg : thunk string} {cb : char_buffer} {n' n : ℕ} {err : dlist string} {a : α} {b : β} {sep : parser unit} lemma not_of_ne (h : p cb n = fail n' err) (hne : n ≠ n') : ¬ err_static p := by { introI, exact hne (of_fail h) } instance pure : err_static (pure a) := ⟨λ _ _ _ _, by { simp [pure_eq_done] }⟩ instance bind {f : α → parser β} [p.static] [p.err_static] [∀ a, (f a).err_static] : (p >>= f).err_static := ⟨λ cb n n' err, begin rw bind_eq_fail, rintro (hp | ⟨_, _, hp, hf⟩), { exact of_fail hp }, { exact trans (static.of_done hp) (of_fail hf) } end⟩ instance bind_of_unfailing {f : α → parser β} [p.err_static] [∀ a, (f a).unfailing] : (p >>= f).err_static := ⟨λ cb n n' err, begin rw bind_eq_fail, rintro (hp | ⟨_, _, hp, hf⟩), { exact of_fail hp }, { exact false.elim (unfailing.of_fail hf) } end⟩ instance and_then {q : parser β} [p.static] [p.err_static] [q.err_static] : (p >> q).err_static := err_static.bind instance and_then_of_unfailing {q : parser β} [p.err_static] [q.unfailing] : (p >> q).err_static := err_static.bind_of_unfailing instance map [p.err_static] {f : α → β} : (f <$> p).err_static := ⟨λ _ _ _ _, by { rw map_eq_fail, exact of_fail }⟩ instance seq {f : parser (α → β)} [f.static] [f.err_static] [p.err_static] : (f <*> p).err_static := err_static.bind instance seq_of_unfailing {f : parser (α → β)} [f.err_static] [p.unfailing] : (f <*> p).err_static := err_static.bind_of_unfailing instance mmap : Π {l : list α} {f : α → parser β} [∀ a, (f a).static] [∀ a, (f a).err_static], (l.mmap f).err_static | [] _ _ _ := err_static.pure | (a :: l) _ h h' := begin convert err_static.bind, { exact h _ }, { exact h' _ }, { intro, convert err_static.bind, { convert static.mmap, exact h }, { apply mmap, { exact h }, { exact h' } }, { exact λ _, err_static.pure } } end instance mmap_of_unfailing : Π {l : list α} {f : α → parser β} [∀ a, (f a).unfailing] [∀ a, (f a).err_static], (l.mmap f).err_static | [] _ _ _ := err_static.pure | (a :: l) _ h h' := begin convert err_static.bind_of_unfailing, { exact h' _ }, { intro, convert unfailing.bind, { convert unfailing.mmap, exact h }, { exact λ _, unfailing.pure } } end instance mmap' : Π {l : list α} {f : α → parser β} [∀ a, (f a).static] [∀ a, (f a).err_static], (l.mmap' f).err_static | [] _ _ _ := err_static.pure | (a :: l) _ h h' := begin convert err_static.and_then, { exact h _ }, { exact h' _ }, { convert mmap', { exact h }, { exact h' } } end instance mmap'_of_unfailing : Π {l : list α} {f : α → parser β} [∀ a, (f a).unfailing] [∀ a, (f a).err_static], (l.mmap' f).err_static | [] _ _ _ := err_static.pure | (a :: l) _ h h' := begin convert err_static.and_then_of_unfailing, { exact h' _ }, { convert unfailing.mmap', exact h } end instance failure : @parser.err_static α failure := ⟨λ _ _ _ _ h, (failure_eq_fail.mp h).left⟩ instance guard {p : Prop} [decidable p] : err_static (guard p) := ⟨λ _ _ _ _ h, (guard_eq_fail.mp h).right.left⟩ instance orelse [p.err_static] [q.mono] : (p <|> q).err_static := ⟨λ _ n n' _, begin by_cases hn : n = n', { exact λ _, hn }, { rw orelse_eq_fail_of_mono_ne hn, { exact of_fail }, { apply_instance } } end⟩ instance decorate_errors : (@decorate_errors α msgs p).err_static := ⟨λ _ _ _ _ h, (decorate_errors_eq_fail.mp h).left⟩ instance decorate_error : (@decorate_error α msg p).err_static := err_static.decorate_errors instance any_char : err_static any_char := ⟨λ _ _ _ _, by { rw [any_char_eq_fail, and.comm], simp }⟩ instance sat_iff {p : char → Prop} [decidable_pred p] : err_static (sat p) := ⟨λ _ _ _ _ h, (sat_eq_fail.mp h).left⟩ instance eps : err_static eps := err_static.pure instance ch (c : char) : err_static (ch c) := err_static.decorate_error instance char_buf {cb' : char_buffer} : err_static (char_buf cb') := err_static.decorate_error instance one_of {cs : list char} : err_static (one_of cs) := err_static.decorate_errors instance one_of' {cs : list char} : err_static (one_of' cs) := err_static.and_then_of_unfailing instance str {s : string} : err_static (str s) := err_static.decorate_error instance remaining : remaining.err_static := ⟨λ _ _ _ _, by simp [remaining_ne_fail]⟩ instance eof : eof.err_static := err_static.decorate_error -- TODO: add foldr and foldl, many, etc, fix_core lemma fix_core {F : parser α → parser α} (hF : ∀ (p : parser α), p.err_static → (F p).err_static) : ∀ (max_depth : ℕ), err_static (fix_core F max_depth) | 0 := err_static.failure | (max_depth + 1) := hF _ (fix_core _) instance digit : digit.err_static := err_static.decorate_error instance nat : nat.err_static := err_static.decorate_error lemma fix {F : parser α → parser α} (hF : ∀ (p : parser α), p.err_static → (F p).err_static) : err_static (fix F) := ⟨λ cb n _ _ h, by { haveI := fix_core hF (cb.size - n + 1), dsimp [fix] at h, exact err_static.of_fail h }⟩ end err_static namespace step variables {α β : Type} {p q : parser α} {msgs : thunk (list string)} {msg : thunk string} {cb : char_buffer} {n' n : ℕ} {err : dlist string} {a : α} {b : β} {sep : parser unit} lemma not_step_of_static_done [static p] (h : ∃ cb n n' a, p cb n = done n' a) : ¬ step p := begin introI, rcases h with ⟨cb, n, n', a, h⟩, have hs := static.of_done h, simpa [←hs] using of_done h end lemma pure (a : α) : ¬ step (pure a) := begin apply not_step_of_static_done, simp [pure_eq_done] end instance bind {f : α → parser β} [p.step] [∀ a, (f a).static] : (p >>= f).step := ⟨λ _ _ _ _, by { simp_rw bind_eq_done, rintro ⟨_, _, hp, hf⟩, exact (static.of_done hf) ▸ (of_done hp) }⟩ instance bind' {f : α → parser β} [p.static] [∀ a, (f a).step] : (p >>= f).step := ⟨λ _ _ _ _, by { simp_rw bind_eq_done, rintro ⟨_, _, hp, hf⟩, rw static.of_done hp, exact of_done hf }⟩ instance and_then {q : parser β} [p.step] [q.static] : (p >> q).step := step.bind instance and_then' {q : parser β} [p.static] [q.step] : (p >> q).step := step.bind' instance map [p.step] {f : α → β} : (f <$> p).step := ⟨λ _ _ _ _, by { simp_rw map_eq_done, rintro ⟨_, hp, _⟩, exact of_done hp }⟩ instance seq {f : parser (α → β)} [f.step] [p.static] : (f <*> p).step := step.bind instance seq' {f : parser (α → β)} [f.static] [p.step] : (f <*> p).step := step.bind' instance mmap {f : α → parser β} [(f a).step] : ([a].mmap f).step := begin convert step.bind, { apply_instance }, { intro, convert static.bind, { exact static.pure }, { exact λ _, static.pure } } end instance mmap' {f : α → parser β} [(f a).step] : ([a].mmap' f).step := begin convert step.and_then, { apply_instance }, { exact static.pure } end instance failure : @parser.step α failure := ⟨λ _ _ _ _, by simp⟩ lemma guard_true : ¬ step (guard true) := pure _ instance guard : step (guard false) := step.failure instance orelse [p.step] [q.step] : (p <|> q).step := ⟨λ _ _ _ _, by { simp_rw orelse_eq_done, rintro (h | ⟨h, -⟩); exact of_done h }⟩ lemma decorate_errors_iff : (@parser.decorate_errors α msgs p).step ↔ p.step := begin split, { introI, constructor, intros cb n n' a h, have : (@parser.decorate_errors α msgs p) cb n = done n' a := by simpa using h, exact of_done this }, { introI, constructor, intros _ _ _ _ h, rw decorate_errors_eq_done at h, exact of_done h } end instance decorate_errors [p.step] : (@decorate_errors α msgs p).step := ⟨λ _ _ _ _, by { rw decorate_errors_eq_done, exact of_done }⟩ lemma decorate_error_iff : (@parser.decorate_error α msg p).step ↔ p.step := decorate_errors_iff instance decorate_error [p.step] : (@decorate_error α msg p).step := step.decorate_errors instance any_char : step any_char := begin constructor, intros cb n, simp_rw [any_char_eq_done], rintro _ _ ⟨_, rfl, -⟩, simp end instance sat {p : char → Prop} [decidable_pred p] : step (sat p) := begin constructor, intros cb n, simp_rw [sat_eq_done], rintro _ _ ⟨_, _, rfl, -⟩, simp end lemma eps : ¬ step eps := step.pure () instance ch {c : char} : step (ch c) := step.decorate_error lemma char_buf_iff {cb' : char_buffer} : (char_buf cb').step ↔ cb'.size = 1 := begin have : char_buf cb' cb' 0 = done cb'.size () := by simp [char_buf_eq_done], split, { introI, simpa using of_done this }, { intro h, constructor, intros cb n n' _, rw [char_buf_eq_done, h], rintro ⟨rfl, -⟩, refl } end instance one_of {cs : list char} : (one_of cs).step := step.decorate_errors instance one_of' {cs : list char} : (one_of' cs).step := step.and_then lemma str_iff {s : string} : (str s).step ↔ s.length = 1 := by simp [str_eq_char_buf, char_buf_iff, ←string.to_list_inj, buffer.ext_iff] lemma remaining : ¬ remaining.step := begin apply not_step_of_static_done, simp [remaining_eq_done] end lemma eof : ¬ eof.step := begin apply not_step_of_static_done, simp only [eof_eq_done, exists_eq_left', exists_const], use [buffer.nil, 0], simp end -- TODO: add foldr and foldl, many, etc, fix_core lemma fix_core {F : parser α → parser α} (hF : ∀ (p : parser α), p.step → (F p).step) : ∀ (max_depth : ℕ), step (fix_core F max_depth) | 0 := step.failure | (max_depth + 1) := hF _ (fix_core _) instance digit : digit.step := step.decorate_error lemma fix {F : parser α → parser α} (hF : ∀ (p : parser α), p.step → (F p).step) : step (fix F) := ⟨λ cb n _ _ h, by { haveI := fix_core hF (cb.size - n + 1), dsimp [fix] at h, exact of_done h }⟩ end step section step variables {α β : Type} {p q : parser α} {msgs : thunk (list string)} {msg : thunk string} {cb : char_buffer} {n' n : ℕ} {err : dlist string} {a : α} {b : β} {sep : parser unit} lemma many1_eq_done_iff_many_eq_done [p.step] [p.bounded] {x : α} {xs : list α} : many1 p cb n = done n' (x :: xs) ↔ many p cb n = done n' (x :: xs) := begin induction hx : (x :: xs) with hd tl IH generalizing x xs n n', { simpa using hx }, split, { simp only [many1_eq_done, and_imp, exists_imp_distrib], intros np hp hm, have : np = n + 1 := step.of_done hp, have hn : n < cb.size := bounded.of_done hp, subst this, obtain ⟨k, hk⟩ : ∃ k, cb.size - n = k + 1 := nat.exists_eq_succ_of_ne_zero (ne_of_gt (tsub_pos_of_lt hn)), cases k, { cases tl; simpa [many_eq_done_nil, nat.sub_succ, hk, many_eq_done, hp, foldr_core_eq_done] using hm }, cases tl with hd' tl', { simpa [many_eq_done_nil, nat.sub_succ, hk, many_eq_done, hp, foldr_core_eq_done] using hm }, { rw ←@IH hd' tl' at hm, swap, refl, simp only [many1_eq_done, many, foldr] at hm, obtain ⟨np, hp', hf⟩ := hm, have : np = n + 1 + 1 := step.of_done hp', subst this, simpa [nat.sub_succ, many_eq_done, hp, hk, foldr_core_eq_done, hp'] using hf } }, { simp only [many_eq_done, many1_eq_done, and_imp, exists_imp_distrib], intros np hp hm, have : np = n + 1 := step.of_done hp, have hn : n < cb.size := bounded.of_done hp, subst this, obtain ⟨k, hk⟩ : ∃ k, cb.size - n = k + 1 := nat.exists_eq_succ_of_ne_zero (ne_of_gt (tsub_pos_of_lt hn)), cases k, { cases tl; simpa [many_eq_done_nil, nat.sub_succ, hk, many_eq_done, hp, foldr_core_eq_done] using hm }, cases tl with hd' tl', { simpa [many_eq_done_nil, nat.sub_succ, hk, many_eq_done, hp, foldr_core_eq_done] using hm }, { simp [hp], rw ←@IH hd' tl' (n + 1) n', swap, refl, rw [hk, foldr_core_eq_done, or.comm] at hm, obtain (hm | ⟨np, hd', tl', hp', hf, hm⟩) := hm, { simpa using hm }, simp only at hm, obtain ⟨rfl, rfl⟩ := hm, have : np = n + 1 + 1 := step.of_done hp', subst this, simp [nat.sub_succ, many, many1_eq_done, hp, hk, foldr_core_eq_done, hp', ←hf, foldr] } } end end step namespace prog variables {α β : Type} {p q : parser α} {msgs : thunk (list string)} {msg : thunk string} {cb : char_buffer} {n' n : ℕ} {err : dlist string} {a : α} {b : β} {sep : parser unit} @[priority 100] -- see Note [lower instance priority] instance of_step [step p] : prog p := ⟨λ _ _ _ _ h, by { rw step.of_done h, exact nat.lt_succ_self _ }⟩ lemma pure (a : α) : ¬ prog (pure a) := begin introI h, have : (pure a : parser α) buffer.nil 0 = done 0 a := by simp [pure_eq_done], replace this : 0 < 0 := prog.of_done this, exact (lt_irrefl _) this end instance bind {f : α → parser β} [p.prog] [∀ a, (f a).mono] : (p >>= f).prog := ⟨λ _ _ _ _, by { simp_rw bind_eq_done, rintro ⟨_, _, hp, hf⟩, exact lt_of_lt_of_le (of_done hp) (mono.of_done hf) }⟩ instance and_then {q : parser β} [p.prog] [q.mono] : (p >> q).prog := prog.bind instance map [p.prog] {f : α → β} : (f <$> p).prog := ⟨λ _ _ _ _, by { simp_rw map_eq_done, rintro ⟨_, hp, _⟩, exact of_done hp }⟩ instance seq {f : parser (α → β)} [f.prog] [p.mono] : (f <*> p).prog := prog.bind instance mmap {l : list α} {f : α → parser β} [(f a).prog] [∀ a, (f a).mono] : ((a :: l).mmap f).prog := begin constructor, simp only [and_imp, bind_eq_done, return_eq_pure, mmap, exists_imp_distrib, pure_eq_done], rintro _ _ _ _ _ _ h _ _ hp rfl rfl, exact lt_of_lt_of_le (of_done h) (mono.of_done hp) end instance mmap' {l : list α} {f : α → parser β} [(f a).prog] [∀ a, (f a).mono] : ((a :: l).mmap' f).prog := begin constructor, simp only [and_imp, bind_eq_done, mmap', exists_imp_distrib, and_then_eq_bind], intros _ _ _ _ _ _ h hm, exact lt_of_lt_of_le (of_done h) (mono.of_done hm) end instance failure : @parser.prog α failure := prog.of_step lemma guard_true : ¬ prog (guard true) := pure _ instance guard : prog (guard false) := prog.failure instance orelse [p.prog] [q.prog] : (p <|> q).prog := ⟨λ _ _ _ _, by { simp_rw orelse_eq_done, rintro (h | ⟨h, -⟩); exact of_done h }⟩ lemma decorate_errors_iff : (@parser.decorate_errors α msgs p).prog ↔ p.prog := begin split, { introI, constructor, intros cb n n' a h, have : (@parser.decorate_errors α msgs p) cb n = done n' a := by simpa using h, exact of_done this }, { introI, constructor, intros _ _ _ _ h, rw decorate_errors_eq_done at h, exact of_done h } end instance decorate_errors [p.prog] : (@decorate_errors α msgs p).prog := ⟨λ _ _ _ _, by { rw decorate_errors_eq_done, exact of_done }⟩ lemma decorate_error_iff : (@parser.decorate_error α msg p).prog ↔ p.prog := decorate_errors_iff instance decorate_error [p.prog] : (@decorate_error α msg p).prog := prog.decorate_errors instance any_char : prog any_char := prog.of_step instance sat {p : char → Prop} [decidable_pred p] : prog (sat p) := prog.of_step lemma eps : ¬ prog eps := prog.pure () instance ch {c : char} : prog (ch c) := prog.of_step lemma char_buf_iff {cb' : char_buffer} : (char_buf cb').prog ↔ cb' ≠ buffer.nil := begin have : cb' ≠ buffer.nil ↔ cb'.to_list ≠ [] := not_iff_not_of_iff ⟨λ h, by simp [h], λ h, by simpa using congr_arg list.to_buffer h⟩, rw [char_buf, this, decorate_error_iff], cases cb'.to_list, { simp [pure] }, { simp only [iff_true, ne.def, not_false_iff], apply_instance } end instance one_of {cs : list char} : (one_of cs).prog := prog.decorate_errors instance one_of' {cs : list char} : (one_of' cs).prog := prog.and_then lemma str_iff {s : string} : (str s).prog ↔ s ≠ "" := by simp [str_eq_char_buf, char_buf_iff, ←string.to_list_inj, buffer.ext_iff] lemma remaining : ¬ remaining.prog := begin introI h, have : remaining buffer.nil 0 = done 0 0 := by simp [remaining_eq_done], replace this : 0 < 0 := prog.of_done this, exact (lt_irrefl _) this end lemma eof : ¬ eof.prog := begin introI h, have : eof buffer.nil 0 = done 0 () := by simpa [remaining_eq_done], replace this : 0 < 0 := prog.of_done this, exact (lt_irrefl _) this end -- TODO: add foldr and foldl, many, etc, fix_core instance many1 [p.mono] [p.prog] : p.many1.prog := begin constructor, rintro cb n n' (_ | ⟨hd, tl⟩), { simp }, { rw many1_eq_done, rintro ⟨np, hp, h⟩, exact (of_done hp).trans_le (mono.of_done h) } end lemma fix_core {F : parser α → parser α} (hF : ∀ (p : parser α), p.prog → (F p).prog) : ∀ (max_depth : ℕ), prog (fix_core F max_depth) | 0 := prog.failure | (max_depth + 1) := hF _ (fix_core _) instance digit : digit.prog := prog.of_step instance nat : nat.prog := prog.decorate_error lemma fix {F : parser α → parser α} (hF : ∀ (p : parser α), p.prog → (F p).prog) : prog (fix F) := ⟨λ cb n _ _ h, by { haveI := fix_core hF (cb.size - n + 1), dsimp [fix] at h, exact of_done h }⟩ end prog variables {α β : Type} {msgs : thunk (list string)} {msg : thunk string} variables {p q : parser α} {cb : char_buffer} {n n' : ℕ} {err : dlist string} variables {a : α} {b : β} section many -- TODO: generalize to p.prog instead of p.step lemma many_sublist_of_done [p.step] [p.bounded] {l : list α} (h : p.many cb n = done n' l) : ∀ k < n' - n, p.many cb (n + k) = done n' (l.drop k) := begin induction l with hd tl hl generalizing n, { rw many_eq_done_nil at h, simp [h.left] }, intros m hm, cases m, { exact h }, rw [list.drop, nat.add_succ, ←nat.succ_add], apply hl, { rw [←many1_eq_done_iff_many_eq_done, many1_eq_done] at h, obtain ⟨_, hp, h⟩ := h, convert h, exact (step.of_done hp).symm }, { exact nat.lt_pred_iff.mpr hm }, end lemma many_eq_nil_of_done [p.step] [p.bounded] {l : list α} (h : p.many cb n = done n' l) : p.many cb n' = done n' [] := begin induction l with hd tl hl generalizing n, { convert h, rw many_eq_done_nil at h, exact h.left.symm }, { rw [←many1_eq_done_iff_many_eq_done, many1_eq_done] at h, obtain ⟨_, -, h⟩ := h, exact hl h } end lemma many_eq_nil_of_out_of_bound [p.bounded] {l : list α} (h : p.many cb n = done n' l) (hn : cb.size < n) : n' = n ∧ l = [] := begin cases l, { rw many_eq_done_nil at h, exact ⟨h.left.symm, rfl⟩ }, { rw many_eq_done at h, obtain ⟨np, hp, -⟩ := h, exact absurd (bounded.of_done hp) hn.not_lt } end lemma many1_length_of_done [p.mono] [p.step] [p.bounded] {l : list α} (h : many1 p cb n = done n' l) : l.length = n' - n := begin induction l with hd tl hl generalizing n n', { simpa using h }, { obtain ⟨k, hk⟩ : ∃ k, n' = n + k + 1 := nat.exists_eq_add_of_lt (prog.of_done h), subst hk, simp only [many1_eq_done] at h, obtain ⟨_, hp, h⟩ := h, have := step.of_done hp, subst this, cases tl, { simp only [many_eq_done_nil, add_left_inj, exists_and_distrib_right, self_eq_add_right] at h, rcases h with ⟨rfl, -⟩, simp }, rw ←many1_eq_done_iff_many_eq_done at h, specialize hl h, simp [hl, add_comm, add_assoc, nat.sub_succ] } end lemma many1_bounded_of_done [p.step] [p.bounded] {l : list α} (h : many1 p cb n = done n' l) : n' ≤ cb.size := begin induction l with hd tl hl generalizing n n', { simpa using h }, { simp only [many1_eq_done] at h, obtain ⟨np, hp, h⟩ := h, have := step.of_done hp, subst this, cases tl, { simp only [many_eq_done_nil, exists_and_distrib_right] at h, simpa [←h.left] using bounded.of_done hp }, { rw ←many1_eq_done_iff_many_eq_done at h, exact hl h } } end end many section nat /-- The `val : ℕ` produced by a successful parse of a `cb : char_buffer` is the numerical value represented by the string of decimal digits (possibly padded with 0s on the left) starting from the parsing position `n` and ending at position `n'`. The number of characters parsed in is necessarily `n' - n`. This is one of the directions of `nat_eq_done`. -/ lemma nat_of_done {val : ℕ} (h : nat cb n = done n' val) : val = (nat.of_digits 10 ((((cb.to_list.drop n).take (n' - n)).reverse.map (λ c, c.to_nat - '0'.to_nat)))) := begin /- The parser `parser.nat` that generates a decimal number from a string of digit characters does several things. First it ingests in as many digits as it can with `many1 digit`. Then, it folds over the resulting `list ℕ` using a helper function that keeps track of both the running sum an and the magnitude so far, using a `(sum, magnitude) : (ℕ × ℕ)` pair. The final sum is extracted using a `prod.fst`. To prove that the value that `parser.nat` produces, after moving precisely `n' - n` steps, is precisely what `nat.of_digits` would give, if supplied the string that is in the ingested `char_buffer` (modulo conversion from `char` to `ℕ ), we need to induct over the length `n' - n` of `cb : char_buffer` ingested, and prove that the parser must have terminated due to hitting either the end of the `char_buffer` or a non-digit character. The statement of the lemma is phrased using a combination of `list.drop` and `list.map` because there is no currently better way to extract an "interval" from a `char_buffer`. Additionally, the statement uses a `list.reverse` because `nat.of_digits` is little-endian. We try to stop referring to the `cb : char_buffer` as soon as possible, so that we can instead regard a `list char` instead, which lends itself better to proofs via induction. -/ /- We first prove some helper lemmas about the definition of `parser.nat`. Since it is defined in core, we have to work with how it is defined instead of changing its definition. In its definition, the function that folds over the parsed in digits is defined internally, as a lambda with anonymous destructor syntax, which leads to an unpleasant `nat._match_1` term when rewriting the definition of `parser.nat` away. Since we know exactly what the function is, we have a `rfl`-like lemma here to rewrite it back into a readable form. -/ have natm : nat._match_1 = (λ (d : ℕ) p, ⟨p.1 + d * p.2, p.2 * 10⟩), { ext1, ext1 ⟨⟩, refl }, -- We also have to prove what is the `prod.snd` of the result of the fold of a `list (ℕ × ℕ)` with -- the function above. We use this lemma later when we finish our inductive case. have hpow : ∀ l, (list.foldr (λ (digit : ℕ) (x : ℕ × ℕ), (x.fst + digit * x.snd, x.snd * 10)) (0, 1) l).snd = 10 ^ l.length, { intro l, induction l with hd tl hl, { simp }, { simp [hl, pow_succ, mul_comm] } }, -- We convert the hypothesis that `parser.nat` has succeeded into an existential that there is -- some list of digits that it has parsed in, and that those digits, when folded over by the -- function above, give the value at hand. simp only [nat, pure_eq_done, natm, decorate_error_eq_done, bind_eq_done] at h, obtain ⟨n', l, hp, rfl, rfl⟩ := h, -- We now want to stop working with the `cb : char_buffer` and parse positions `n` and `n'`, -- and just deal with the parsed digit list `l : list ℕ`. To do so, we have to show that -- this is precisely the list that could have been parsed in, no smaller and no greater. induction l with lhd ltl IH generalizing n n' cb, { -- Base case: we parsed in no digits whatsoever. But this is impossible because `parser.many1` -- must produce a list that is not `list.nil`, by `many1_ne_done_nil`. simpa using hp }, -- Inductive case: -- We must prove that the first digit parsed in `lhd : ℕ` is precisely the digit that is -- represented by the character at position `n` in `cb : char_buffer`. -- We will also prove the correspondence between the subsequent digits `ltl : list ℕ` and the -- remaining characters past position `n` up to position `n'`. cases hx : (list.drop n (buffer.to_list cb)) with chd ctl, { -- Are there even characters left to parse, at position `n` in the `cb : char_buffer`? In other -- words, are we already out of bounds, and thus could not have parsed in any value -- successfully. But this must be a contradiction because `parser.digit` is a `bounded` parser, -- (due to its being defined via `parser.decorate_error`), which means it only succeeds -- in-bounds, and the `many1` parser combinator retains that property. have : cb.size ≤ n := by simpa using list.drop_eq_nil_iff_le.mp hx, exact absurd (bounded.of_done hp) this.not_lt }, -- We prove that the first digit parsed in is precisely the digit that is represented by the -- character at position `n`, which we now call `chd : char`. have chdh : chd.to_nat - '0'.to_nat = lhd, { simp only [many1_eq_done] at hp, -- We know that `parser.digit` succeeded, so it has moved to a possibly different position. -- In fact, we know that this new position is `n + 1`, by the `step` property of -- `parser.digit`. obtain ⟨_, hp, -⟩ := hp, have := step.of_done hp, subst this, -- We now unfold what it means for `parser.digit` to succeed, which means that the character -- parsed in was "numeric" (for some definition of that property), and, more importantly, -- that the `n`th character of `cb`, let's say `c`, when converted to a `ℕ` via -- `char.to_nat c - '0'.to_nat`, must be equal to the resulting value, `lhd` in our case. simp only [digit_eq_done, buffer.read_eq_nth_le_to_list, hx, buffer.length_to_list, true_and, add_left_inj, list.length, list.nth_le, eq_self_iff_true, exists_and_distrib_left, fin.coe_mk] at hp, rcases hp with ⟨_, hn, rfl, _, _⟩, -- But we already know the list corresponding to `cb : char_buffer` from position `n` and on -- is equal to `(chd :: ctl) : list char`, so our `c` above must satisfy `c = chd`. have hn' : n < cb.to_list.length := by simpa using hn, rw ←list.cons_nth_le_drop_succ hn' at hx, -- We can ignore proving any correspondence of `ctl : list char` to the other portions of the -- `cb : char_buffer`. simp only at hx, simp [hx] }, -- We know that we parsed in more than one character because of the `prog` property of -- `parser.digit`, which the `many1` parser combinator retains. In other words, we know that -- `n < n'`, and so, the list of digits `ltl` must correspond to the list of digits that -- `digit.many1 cb (n + 1)` would produce. We know that the shift of `1` in `n ↦ n + 1` holds -- due to the `step` property of `parser.digit`. -- We also get here `k : ℕ` which will indicate how many characters we parsed in past position -- `n`. We will prove later that this must be the number of digits we produced as well in `ltl`. obtain ⟨k, hk⟩ : ∃ k, n' = n + k + 1 := nat.exists_eq_add_of_lt (prog.of_done hp), have hdm : ltl = [] ∨ digit.many1 cb (n + 1) = done n' ltl, { cases ltl, { simp }, { rw many1_eq_done at hp, obtain ⟨_, hp, hp'⟩ := hp, simpa [step.of_done hp, many1_eq_done_iff_many_eq_done] using hp' } }, -- Now we case on the two possibilities, that there was only a single digit parsed in, and -- `ltl = []`, or, had we started parsing at `n + 1` instead, we'd parse in the value associated -- with `ltl`. -- We prove that the LHS, which is a fold over a `list ℕ` is equal to the RHS, which is that -- the `val : ℕ` that `nat.of_digits` produces when supplied a `list ℕ that has been produced -- via mapping a `list char` using `char.to_nat`. Specifically, that `list char` are the -- characters in the `cb : char_buffer`, from position `n` to position `n'` (excluding `n'`), -- in reverse. rcases hdm with rfl|hdm, { -- Case that `ltl = []`. simp only [many1_eq_done, many_eq_done_nil, exists_and_distrib_right] at hp, -- This means we must have failed parsing with `parser.digit` at some other position, -- which we prove must be `n + 1` via the `step` property. obtain ⟨_, hp, rfl, hp'⟩ := hp, have := step.of_done hp, subst this, -- Now we rely on the simplifier, which simplfies the LHS, which is a fold over a singleton -- list. On the RHS, `list.take (n + 1 - n)` also produces a singleton list, which, when -- reversed, is the same list. `nat.of_digits` of a singleton list is precisely the value in -- the list. And we already have that `chd.to_nat - '0'.to_nat = lhd`. simp [chdh] }, -- We now have to deal with the case where we parsed in more than one digit, and thus -- `n + 1 < n'`, which means `ctl` has one or more elements. Similarly, `ltl` has one or more -- elements. -- We finish ridding ourselves of references to `cb : char_buffer`, by relying on the fact that -- our `ctl : list char` must be the appropriate portion of `cb` once enough elements have been -- dropped and taken. have rearr : list.take (n + (k + 1) - (n + 1)) (list.drop (n + 1) (buffer.to_list cb)) = ctl.take k, { simp [←list.tail_drop, hx, nat.sub_succ, hk] }, -- We have to prove that the number of digits produced (given by `ltl`) is equal to the number -- of characters parsed in, as given by `ctl.take k`, and that this is precisely `k`. We phrase it -- in the statement using `min`, because lemmas about `list.length (list.take ...)` simplify to -- a statement that uses `min`. The `list.length` term appears from the reduction of the folding -- function, as proven above. have ltll : min k ctl.length = ltl.length, { -- Here is an example of how statements about the `list.length` of `list.take` simplify. have : (ctl.take k).length = min k ctl.length := by simp, -- We bring back the underlying definition of `ctl` as the result of a sequence of `list.take` -- and `list.drop`, so that lemmas about `list.length` of those can fire. rw [←this, ←rearr, many1_length_of_done hdm], -- Likewise, we rid ourselves of the `k` we generated earlier. have : k = n' - n - 1, { simp [hk, add_assoc] }, subst this, simp only [nat.sub_succ, add_comm, ←nat.pred_sub, buffer.length_to_list, nat.pred_one_add, min_eq_left_iff, list.length_drop, add_tsub_cancel_left, list.length_take, tsub_zero], -- We now have a goal of proving an inequality dealing with `nat` subtraction and `nat.pred`, -- both of which require special care to provide positivity hypotheses. rw [tsub_le_tsub_iff_right, nat.pred_le_iff], { -- We know that `n' ≤ cb.size` because of the `bounded` property, that a parser will not -- produce a `done` result at a position farther than the size of the underlying -- `char_buffer`. convert many1_bounded_of_done hp, -- What is now left to prove is that `0 < cb.size`, which can be rephrased -- as proving that it is nonempty. cases hc : cb.size, { -- Proof by contradiction. Let's say that `cb.size = 0`. But we know that we succeeded -- parsing in at position `n` using a `bounded` parser, so we must have that -- `n < cb.size`. have := bounded.of_done hp, rw hc at this, -- But then `n < 0`, a contradiction. exact absurd n.zero_le this.not_le }, { simp } }, { -- Here, we use the same result as above, that `n < cb.size`, and relate it to -- `n ≤ cb.size.pred`. exact nat.le_pred_of_lt (bounded.of_done hp) } }, -- Finally, we simplify. On the LHS, we have a fold over `lhd :: ltl`, which simplifies to -- the operation of the summing folding function on `lhd` and the fold over `ltl`. To that we can -- apply the induction hypothesis, because we know that our parser would have succeeded had we -- started at position `n + 1`. We replace mentions of `cb : char_buffer` with the appropriate -- `chd :: ctl`, replace `lhd` with the appropriate statement of how it is calculated from `chd`, -- and use the lemmas describing the length of `ltl` and how it is associated with `k`. We also -- remove mentions of `n'` and replace with an expression using solely `n + k + 1`. -- We use the lemma we proved above about how the folding function produces the -- `prod.snd` value, which is `10` to the power of the length of the list provided to the fold. -- Finally, we rely on `nat.of_digits_append` for the related statement of how digits given -- are used in the `nat.of_digits` calculation, which also involves `10 ^ list.length ...`. -- The `list.append` operation appears due to the `list.reverse (chd :: ctl)`. -- We include some addition and multiplication lemmas to help the simplifier rearrange terms. simp [IH _ hdm, hx, hk, rearr, ←chdh, ←ltll, hpow, add_assoc, nat.of_digits_append, mul_comm] end /-- If we know that `parser.nat` was successful, starting at position `n` and ending at position `n'`, then it must be the case that for all `k : ℕ`, `n ≤ k`, `k < n'`, the character at the `k`th position in `cb : char_buffer` is "numeric", that is, is between `'0'` and `'9'` inclusive. This is a necessary part of proving one of the directions of `nat_eq_done`. -/ lemma nat_of_done_as_digit {val : ℕ} (h : nat cb n = done n' val) : ∀ (hn : n' ≤ cb.size) k (hk : k < n'), n ≤ k → '0' ≤ cb.read ⟨k, hk.trans_le hn⟩ ∧ cb.read ⟨k, hk.trans_le hn⟩ ≤ '9' := begin -- The properties to be shown for the characters involved rely solely on the success of -- `parser.digit` at the relevant positions, and not on the actual value `parser.nat` produced. -- We break done the success of `parser.nat` into the `parser.digit` success and throw away -- the resulting value given by `parser.nat`, and focus solely on the `list ℕ` generated by -- `parser.digit.many1`. simp only [nat, pure_eq_done, and.left_comm, decorate_error_eq_done, bind_eq_done, exists_eq_left, exists_and_distrib_left] at h, obtain ⟨xs, h, -⟩ := h, -- We want to avoid having to make statements about the `cb : char_buffer` itself. Instead, we -- induct on the `xs : list ℕ` that `parser.digit.many1` produced. induction xs with hd tl hl generalizing n n', { -- Base case: `xs` is empty. But this is a contradiction because `many1` always produces a -- nonempty list, as proven by `many1_ne_done_nil`. simpa using h }, -- Inductive case: we prove that the `parser.digit.many1` produced a valid `(hd :: tl) : list ℕ`, -- by showing that is the case for the character at position `n`, which gave `hd`, and use the -- induction hypothesis on the remaining `tl`. -- We break apart a `many1` success into a success of the underlying `parser.digit` to give `hd` -- and a `parser.digit.many` which gives `tl`. We first deal with the `hd`. rw many1_eq_done at h, -- Right away, we can throw away the information about the "new" position that `parser.digit` -- ended on because we will soon prove that it must have been `n + 1`. obtain ⟨_, hp, h⟩ := h, -- The main lemma here is `digit_eq_done`, which already proves the necessary conditions about -- the character at hand. What is left to do is properly unpack the information. simp only [digit_eq_done, and.comm, and.left_comm, digit_eq_fail, true_and, exists_eq_left, eq_self_iff_true, exists_and_distrib_left, exists_and_distrib_left] at hp, obtain ⟨rfl, -, hn, ge0, le9, rfl⟩ := hp, -- Let's now consider a position `k` between `n` and `n'`, excluding `n'`. intros hn k hk hk', -- What if we are at `n`? What if we are past `n`? We case on the `n ≤ k`. rcases hk'.eq_or_lt with rfl|hk', { -- The `n = k` case. But this is exactly what we know already, so we provide the -- relevant hypotheses. exact ⟨ge0, le9⟩ }, -- The `n < k` case. First, we check if there would have even been digits parsed in. So, we -- case on `tl : list ℕ` cases tl, { -- Case where `tl = []`. But that means `many` gave us a `[]` so either the character at -- position `k` was not "numeric" or we are out of bounds. More importantly, when `many` -- successfully produces a `[]`, it does not progress the parser head, so we have that -- `n + 1 = n'`. This will lead to a contradiction because now we have `n < k` and `k < n + 1`. simp only [many_eq_done_nil, exists_and_distrib_right] at h, -- Extract out just the `n + 1 = n'`. obtain ⟨rfl, -⟩ := h, -- Form the contradictory hypothesis, and discharge the goal. have : k < k := hk.trans_le (nat.succ_le_of_lt hk'), exact absurd this (lt_irrefl _) }, { -- Case where `tl ≠ []`. But that means that `many` produced a nonempty list as a result, so -- `many1` would have successfully parsed at this position too. We use this statement to -- rewrite our hypothesis into something that works with the induction hypothesis, and apply it. rw ←many1_eq_done_iff_many_eq_done at h, apply hl h, -- All that is left to prove is that our `k` is at least our new "lower bound" `n + 1`, which -- we have from our original split of the `n ≤ k`, since we are now on the `n < k` case. exact nat.succ_le_of_lt hk' } end /-- If we know that `parser.nat` was successful, starting at position `n` and ending at position `n'`, then it must be the case that for the ending position `n'`, either it is beyond the end of the `cb : char_buffer`, or the character at that position is not "numeric", that is, between `'0'` and `'9'` inclusive. This is a necessary part of proving one of the directions of `nat_eq_done`. -/ lemma nat_of_done_bounded {val : ℕ} (h : nat cb n = done n' val) : ∀ (hn : n' < cb.size), '0' ≤ cb.read ⟨n', hn⟩ → '9' < cb.read ⟨n', hn⟩ := begin -- The properties to be shown for the characters involved rely solely on the success of -- `parser.digit` at the relevant positions, and not on the actual value `parser.nat` produced. -- We break done the success of `parser.nat` into the `parser.digit` success and throw away -- the resulting value given by `parser.nat`, and focus solely on the `list ℕ` generated by -- `parser.digit.many1`. -- We deal with the case of `n'` is "out-of-bounds" right away by requiring that -- `∀ (hn : n' < cb.size)`. Thus we only have to prove the lemma for the cases where `n'` is still -- "in-bounds". simp only [nat, pure_eq_done, and.left_comm, decorate_error_eq_done, bind_eq_done, exists_eq_left, exists_and_distrib_left] at h, obtain ⟨xs, h, -⟩ := h, -- We want to avoid having to make statements about the `cb : char_buffer` itself. Instead, we -- induct on the `xs : list ℕ` that `parser.digit.many1` produced. induction xs with hd tl hl generalizing n n', { -- Base case: `xs` is empty. But this is a contradiction because `many1` always produces a -- nonempty list, as proven by `many1_ne_done_nil`. simpa using h }, -- Inductive case: at least one character has been parsed in, starting at position `n`. -- We know that the size of `cb : char_buffer` must be at least `n + 1` because -- `parser.digit.many1` is `bounded` (`n < cb.size`). -- We show that either we parsed in just that one character, or we use the inductive hypothesis. obtain ⟨k, hk⟩ : ∃ k, cb.size = n + k + 1 := nat.exists_eq_add_of_lt (bounded.of_done h), cases tl, { -- Case where `tl = []`, so we parsed in only `hd`. That must mean that `parser.digit` failed -- at `n + 1`. simp only [many1_eq_done, many_eq_done_nil, and.left_comm, exists_and_distrib_right, exists_eq_left] at h, -- We throw away the success information of what happened at position `n`, and we do not need -- the "error" value that the failure produced. obtain ⟨-, _, h⟩ := h, -- If `parser.digit` failed at `n + 1`, then either we hit a non-numeric character, or -- we are out of bounds. `digit_eq_fail` provides us with those two cases. simp only [digit_eq_done, and.comm, and.left_comm, digit_eq_fail, true_and, exists_eq_left, eq_self_iff_true, exists_and_distrib_left] at h, obtain (⟨rfl, h⟩ | ⟨h, -⟩) := h, { -- First case: we are still in bounds, but the character is not numeric. We must prove -- that we are still in bounds. But we know that from our initial requirement. intro hn, simpa using h hn }, { -- Second case: we are out of bounds, and somehow the fold that `many1` relied on failed. -- But we know that `parser.digit` is mono, that is, it never goes backward in position, -- in neither success nor in failure. We also have that `foldr_core` respects `mono`. -- But in this case, `foldr_core` is starting at position `n' + 1` but failing at -- position `n'`, which is a contradiction, because otherwise we would have `n' + 1 ≤ n'`. simpa using mono.of_fail h } }, { -- Case where `tl ≠ []`. But that means that `many` produced a nonempty list as a result, so -- `many1` would have successfully parsed at this position too. We use this statement to -- rewrite our hypothesis into something that works with the induction hypothesis, and apply it. rw many1_eq_done at h, obtain ⟨_, -, h⟩ := h, rw ←many1_eq_done_iff_many_eq_done at h, exact hl h } end /-- The `val : ℕ` produced by a successful parse of a `cb : char_buffer` is the numerical value represented by the string of decimal digits (possibly padded with 0s on the left) starting from the parsing position `n` and ending at position `n'`, where `n < n'`. The number of characters parsed in is necessarily `n' - n`. Additionally, all of the characters in the `cb` starting at position `n` (inclusive) up to position `n'` (exclusive) are "numeric", in that they are between `'0'` and `'9'` inclusive. Such a `char_buffer` would produce the `ℕ` value encoded by its decimal characters. -/ lemma nat_eq_done {val : ℕ} : nat cb n = done n' val ↔ ∃ (hn : n < n'), val = (nat.of_digits 10 ((((cb.to_list.drop n).take (n' - n)).reverse.map (λ c, c.to_nat - '0'.to_nat)))) ∧ (∀ (hn' : n' < cb.size), ('0' ≤ cb.read ⟨n', hn'⟩ → '9' < cb.read ⟨n', hn'⟩)) ∧ ∃ (hn'' : n' ≤ cb.size), (∀ k (hk : k < n'), n ≤ k → '0' ≤ cb.read ⟨k, hk.trans_le hn''⟩ ∧ cb.read ⟨k, hk.trans_le hn''⟩ ≤ '9') := begin -- To prove this iff, we have most of the way in the forward direction, using the lemmas proven -- above. First, we must use that `parser.nat` is `prog`, which means that on success, it must -- move forward. We also have to prove the statement that a success means the parsed in -- characters were properly "numeric". It involves first generating ane existential witness -- that the parse was completely "in-bounds". -- For the reverse direction, we first discharge the goals that deal with proving that our parser -- succeeded because it encountered characters with the proper "numeric" properties, was -- "in-bounds" and hit a nonnumeric character. The more difficult portion is proving that the -- list of characters from positions `n` to `n'`, when folded over by the function defined inside -- `parser.nat` gives exactly the same value as `nat.of_digits` when supplied with the same -- (modulo rearrangement) list. To reach this goal, we try to remove any reliance on the -- underlying `cb : char_buffer` or parsers as soon as possible, via a cased-induction. refine ⟨λ h, ⟨prog.of_done h, nat_of_done h, nat_of_done_bounded h, _⟩, _⟩, { -- To provide the existential witness that `n'` is within the bounds of the `cb : char_buffer`, -- we rely on the fact that `parser.nat` is primarily a `parser.digit.many1`, and that `many1`, -- must finish with the bounds of the `cb`, as long as the underlying parser is `step` and -- `bounded`, which `digit` is. We do not prove this as a separate lemma about `parser.nat` -- because it would almost always be only relevant in this larger theorem. -- We clone the success hypothesis `h` so that we can supply it back later. have H := h, -- We unwrap the `parser.nat` success down to the `many1` success, throwing away other info. rw [nat] at h, simp only [decorate_error_eq_done, bind_eq_done, pure_eq_done, and.left_comm, exists_eq_left, exists_and_distrib_left] at h, obtain ⟨_, h, -⟩ := h, -- Now we get our existential witness that `n' ≤ cb.size`. replace h := many1_bounded_of_done h, -- With that, we can use the lemma proved above that our characters are "numeric" exact ⟨h, nat_of_done_as_digit H h⟩ }, -- We now prove that given the `cb : char_buffer` with characters within the `n ≤ k < n'` interval -- properly "numeric" and such that their `nat.of_digits` generates the `val : ℕ`, `parser.nat` -- of that `cb`, when starting at `n`, will finish at `n'` and produce the same `val`. -- We first introduce the relevant hypotheses, including the fact that we have a valid interval -- where `n < n'` and that characters at `n'` and beyond are no longer numeric. rintro ⟨hn, hv, hb, hn', ho⟩, -- We first unwrap the `parser.nat` definition to the underlying `parser.digit.many1` success -- and the fold function of the digits. rw nat, simp only [and.left_comm, pure_eq_done, hv, decorate_error_eq_done, list.map_reverse, bind_eq_done, exists_eq_left, exists_and_distrib_left], -- We won't actually need the `val : ℕ` itself, since it is entirely characterized by the -- underlying characters. Instead, we will induct over the `list char` of characters from -- position `n` onwards, showing that if we could have provided a list at `n`, we could have -- provided a valid list of characters at `n + 1` too. clear hv val, /- We first prove some helper lemmas about the definition of `parser.nat`. Since it is defined in core, we have to work with how it is defined instead of changing its definition. In its definition, the function that folds over the parsed in digits is defined internally, as a lambda with anonymous destructor syntax, which leads to an unpleasant `nat._match_1` term when rewriting the definition of `parser.nat` away. Since we know exactly what the function is, we have a `rfl`-like lemma here to rewrite it back into a readable form. -/ have natm : nat._match_1 = (λ (d : ℕ) p, ⟨p.1 + d * p.2, p.2 * 10⟩), { ext1, ext1 ⟨⟩, refl }, -- We induct over the characters available at position `n` and onwards. Because `cb` is used -- in other expressions, we utilize the `induction H : ...` tactic to induct separately from -- destructing `cb` itself. induction H : (cb.to_list.drop n) with hd tl IH generalizing n, { -- Base case: there are no characters at position `n` or onwards, which means that -- `cb.size ≤ n`. But this is a contradiction, since we have `n < n' ≤ cb.size`. rw list.drop_eq_nil_iff_le at H, refine absurd ((lt_of_le_of_lt H hn).trans_le hn') _, simp }, { -- Inductive case: we prove that if we could have parsed from `n + 1`, we could have also parsed -- from `n`, if there was a valid numerical character at `n`. Most of the body -- of this inductive case is generating the appropriate conditions for use of the inductive -- hypothesis. specialize @IH (n + 1), -- We have, by the inductive case, that there is at least one character `hd` at position `n`, -- with the rest at `tl`. We rearrange our inductive case to make `tl` be expressed as -- list.drop (n + 1), which fits out induction hypothesis conditions better. To use the -- rearranging lemma, we must prove that we are "dropping" in bounds, which we supply on-the-fly simp only [←list.cons_nth_le_drop_succ (show n < cb.to_list.length, by simpa using hn.trans_le hn')] at H, -- We prove that parsing our `n`th character, `hd`, would have resulted in a success from -- `parser.digit`, with the appropriate `ℕ` success value. We use this later to simplify the -- unwrapped fold, since `hd` is our head character. have hdigit : digit cb n = done (n + 1) (hd.to_nat - '0'.to_nat), { -- By our necessary condition, we know that `n` is in bounds, and that the `n`th character -- has the necessary "numeric" properties. specialize ho n hn (le_refl _), -- We prove an additional result that the conversion of `hd : char` to a `ℕ` would give a -- value `x ≤ 9`, since that is part of the iff statement in the `digit_eq_done` lemma. have : (buffer.read cb ⟨n, hn.trans_le hn'⟩).to_nat - '0'.to_nat ≤ 9, { -- We rewrite the statement to be a statement about characters instead, and split the -- inequality into the case that our hypotheses prove, and that `'0' ≤ '9'`, which -- is true by computation, handled by `dec_trivial`. rw [show 9 = '9'.to_nat - '0'.to_nat, from dec_trivial, tsub_le_tsub_iff_right], { exact ho.right }, { dec_trivial } }, -- We rely on the simplifier, mostly powered by `digit_eq_done`, and supply all the -- necessary conditions of bounds and identities about `hd`. simp [digit_eq_done, this, ←H.left, buffer.nth_le_to_list, hn.trans_le hn', ho] }, -- We now case on whether we've moved to the end of our parse or not. We phrase this as -- casing on either `n + 1 < n` or `n ≤ n + 1`. The more difficult goal comes first. cases lt_or_ge (n + 1) n' with hn'' hn'', { -- Case `n + 1 < n'`. We can directly supply this to our induction hypothesis. -- We now have to prove, for the induction hypothesis, that the characters at positions `k`, -- `n + 1 ≤ k < n'` are "numeric". We already had this for `n ≤ k < n`, so we just rearrange -- the hypotheses we already have. specialize IH hn'' _ H.right, { intros k hk hk', apply ho, exact nat.le_of_succ_le hk' }, -- With the induction hypothesis conditions satisfier, we can extract out a list that -- `parser.digit.many1` would have generated from position `n + 1`, as well as the associated -- property of the list, that it folds into what `nat.of_digits` generates from the -- characters in `cb : char_buffer`, now known as `hd :: tl`. obtain ⟨l, hdl, hvl⟩ := IH, -- Of course, the parsed in list from position `n` would be `l` prepended with the result -- of parsing in `hd`, which is provided explicitly. use (hd.to_nat - '0'.to_nat) :: l, -- We case on `l : list ℕ` so that we can make statements about the fold on `l` cases l with lhd ltl, { -- As before, if `l = []` then `many1` produced a `[]` success, which is a contradiction. simpa using hdl }, -- Case `l = lhd :: ltl`. We can rewrite the fold of the function inside `parser.nat` on -- `lhd :: ltl`, which will be used to rewrite in the goal. simp only [natm, list.foldr] at hvl, -- We also expand the fold in the goal, using the expanded fold from our hypothesis, powered -- by `many1_eq_done` to proceed in the parsing. We know exactly what the next `many` will -- produce from `many1_eq_done_iff_many_eq_done.mp` of our `hdl` hypothesis. Finally, -- we also use `hdigit` to express what the single `parser.digit` result would be at `n`. simp only [natm, hvl, many1_eq_done, hdigit, many1_eq_done_iff_many_eq_done.mp hdl, true_and, and_true, eq_self_iff_true, list.foldr, exists_eq_left'], -- Now our goal is solely about the equality of two different folding functions, one from the -- function defined inside `parser.nat` and the other as `nat.of_digits`, when applied to -- similar list inputs. -- First, we rid ourselves of `n'` by replacing with `n + m + 1`, which allows us to -- simplify the term of how many elements we are keeping using a `list.take`. obtain ⟨m, rfl⟩ : ∃ m, n' = n + m + 1 := nat.exists_eq_add_of_lt hn, -- The following rearrangement lemma is to simplify the `list.take (n' - n)` expression we had have : n + m + 1 - n = m + 1, { rw [add_assoc, tsub_eq_iff_eq_add_of_le, add_comm], exact nat.le_add_right _ _ }, -- We also have to prove what is the `prod.snd` of the result of the fold of a `list (ℕ × ℕ)` -- with the function above. We use this lemma to finish our inductive case. have hpow : ∀ l, (list.foldr (λ (digit : ℕ) (x : ℕ × ℕ), (x.fst + digit * x.snd, x.snd * 10)) (0, 1) l).snd = 10 ^ l.length, { intro l, induction l with hd tl hl, { simp }, { simp [hl, pow_succ, mul_comm] } }, -- We prove that the parsed list of digits `(lhd :: ltl) : list ℕ` must be of length `m` -- which is used later when the `parser.nat` fold places `ltl.length` in the exponent. have hml : ltl.length + 1 = m := by simpa using many1_length_of_done hdl, -- A simplified `list.length (list.take ...)` expression refers to the minimum of the -- underlying length and the amount of elements taken. We know that `m ≤ tl.length`, so -- we provide this auxiliary lemma so that the simplified "take-length" can simplify further have ltll : min m tl.length = m, { -- On the way to proving this, we have to actually show that `m ≤ tl.length`, by showing -- that since `tl` was a subsequence in `cb`, and was retrieved from `n + 1` to `n + m + 1`, -- then since `n + m + 1 ≤ cb.size`, we have that `tl` must be at least `m` in length. simpa [←H.right, le_tsub_iff_right (hn''.trans_le hn').le, add_comm, add_assoc, add_left_comm] using hn' }, -- Finally, we rely on the simplifier. We already expressions of `nat.of_digits` on both -- the LHS and RHS. All that is left to do is to prove that the summand on the LHS is produced -- by the fold of `nat.of_digits` on the RHS of `hd :: tl`. The `nat.of_digits_append` is used -- because of the append that forms from the included `list.reverse`. The lengths of the lists -- are placed in the exponents with `10` as a base, and are combined using `←pow_succ 10`. -- Any complicated expression about list lengths is further simplified by the auxiliary -- lemmas we just proved. Finally, we assist the simplifier by rearranging terms with our -- `n + m + 1 - n = m + 1` proof and `mul_comm`. simp [this, hpow, nat.of_digits_append, mul_comm, ←pow_succ 10, hml, ltll] }, { -- Consider the case that `n' ≤ n + 1`. But then since `n < n' ≤ n + 1`, `n' = n + 1`. have : n' = n + 1 := le_antisymm hn'' (nat.succ_le_of_lt hn), subst this, -- This means we have only parsed in a single character, so the resulting parsed in list -- is explicitly formed from an expression we can construct from `hd`. use [[hd.to_nat - '0'.to_nat]], -- Our list expression simplifies nicely because it is a fold over a singleton, so we -- do not have to supply any auxiliary lemmas for it, other than what we already know about -- `hd` and the function defined in `parser.nat`. However, we will have to prove that our -- parse ended because of a good reason: either we are out of bounds or we hit a nonnumeric -- character. simp only [many1_eq_done, many_eq_done_nil, digit_eq_fail, natm, and.comm, and.left_comm, hdigit, true_and, mul_one, nat.of_digits_singleton, list.take, exists_eq_left, exists_and_distrib_right, add_tsub_cancel_left, eq_self_iff_true, list.reverse_singleton, zero_add, list.foldr, list.map], -- We take the route of proving that we hit a nonnumeric character, since we already have -- a hypothesis that says that characters at `n'` and past it are nonnumeric. (Note, by now -- we have substituted `n + 1` for `n'. -- We are also asked to provide the error value that our failed parse would report. But -- `digit_eq_fail` already knows what it is, so we can discharge that with an inline `rfl`. refine ⟨_, or.inl ⟨rfl, _⟩⟩, -- The nonnumeric condition looks almost exactly like the hypothesis we already have, so -- we let the simplifier align them for us simpa using hb } } end end nat end parser
c618c3ffc38629ebc12bf9f466eee32487a6aefa
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/algebra/group/type_tags.lean
17c13d3ea634f1d2abb80fe2563e80931e460e4f
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
7,273
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import algebra.group.hom /-! # Type tags that turn additive structures into multiplicative, and vice versa We define two type tags: * `additive α`: turns any multiplicative structure on `α` into the corresponding additive structure on `additive α`; * `multiplicative α`: turns any additive structure on `α` into the corresponding multiplicative structure on `multiplicative α`. We also define instances `additive.*` and `multiplicative.*` that actually transfer the structures. -/ universes u v variables {α : Type u} {β : Type v} /-- If `α` carries some multiplicative structure, then `additive α` carries the corresponding additive structure. -/ def additive (α : Type*) := α /-- If `α` carries some additive structure, then `multiplicative α` carries the corresponding multiplicative structure. -/ def multiplicative (α : Type*) := α /-- Reinterpret `x : α` as an element of `additive α`. -/ def additive.of_mul (x : α) : additive α := x /-- Reinterpret `x : additive α` as an element of `α`. -/ def additive.to_mul (x : additive α) : α := x lemma of_mul_injective : function.injective (@additive.of_mul α) := λ _ _, id lemma to_mul_injective : function.injective (@additive.to_mul α) := λ _ _, id /-- Reinterpret `x : α` as an element of `multiplicative α`. -/ def multiplicative.of_add (x : α) : multiplicative α := x /-- Reinterpret `x : multiplicative α` as an element of `α`. -/ def multiplicative.to_add (x : multiplicative α) : α := x lemma of_add_injective : function.injective (@multiplicative.of_add α) := λ _ _, id lemma to_add_injective : function.injective (@multiplicative.to_add α) := λ _ _, id @[simp] lemma to_add_of_add (x : α) : (multiplicative.of_add x).to_add = x := rfl @[simp] lemma of_add_to_add (x : multiplicative α) : multiplicative.of_add x.to_add = x := rfl @[simp] lemma to_mul_of_mul (x : α) : (additive.of_mul x).to_mul = x := rfl @[simp] lemma of_mul_to_mul (x : additive α) : additive.of_mul x.to_mul = x := rfl instance [inhabited α] : inhabited (additive α) := ⟨additive.of_mul (default α)⟩ instance [inhabited α] : inhabited (multiplicative α) := ⟨multiplicative.of_add (default α)⟩ instance additive.has_add [has_mul α] : has_add (additive α) := { add := λ x y, additive.of_mul (x.to_mul * y.to_mul) } instance [has_add α] : has_mul (multiplicative α) := { mul := λ x y, multiplicative.of_add (x.to_add + y.to_add) } @[simp] lemma of_add_add [has_add α] (x y : α) : multiplicative.of_add (x + y) = multiplicative.of_add x * multiplicative.of_add y := rfl @[simp] lemma to_add_mul [has_add α] (x y : multiplicative α) : (x * y).to_add = x.to_add + y.to_add := rfl @[simp] lemma of_mul_mul [has_mul α] (x y : α) : additive.of_mul (x * y) = additive.of_mul x + additive.of_mul y := rfl @[simp] lemma to_mul_add [has_mul α] (x y : additive α) : (x + y).to_mul = x.to_mul * y.to_mul := rfl instance [semigroup α] : add_semigroup (additive α) := { add_assoc := @mul_assoc α _, ..additive.has_add } instance [add_semigroup α] : semigroup (multiplicative α) := { mul_assoc := @add_assoc α _, ..multiplicative.has_mul } instance [comm_semigroup α] : add_comm_semigroup (additive α) := { add_comm := @mul_comm _ _, ..additive.add_semigroup } instance [add_comm_semigroup α] : comm_semigroup (multiplicative α) := { mul_comm := @add_comm _ _, ..multiplicative.semigroup } instance [left_cancel_semigroup α] : add_left_cancel_semigroup (additive α) := { add_left_cancel := @mul_left_cancel _ _, ..additive.add_semigroup } instance [add_left_cancel_semigroup α] : left_cancel_semigroup (multiplicative α) := { mul_left_cancel := @add_left_cancel _ _, ..multiplicative.semigroup } instance [right_cancel_semigroup α] : add_right_cancel_semigroup (additive α) := { add_right_cancel := @mul_right_cancel _ _, ..additive.add_semigroup } instance [add_right_cancel_semigroup α] : right_cancel_semigroup (multiplicative α) := { mul_right_cancel := @add_right_cancel _ _, ..multiplicative.semigroup } instance [has_one α] : has_zero (additive α) := ⟨additive.of_mul 1⟩ @[simp] lemma of_mul_one [has_one α] : @additive.of_mul α 1 = 0 := rfl @[simp] lemma to_mul_zero [has_one α] : (0 : additive α).to_mul = 1 := rfl instance [has_zero α] : has_one (multiplicative α) := ⟨multiplicative.of_add 0⟩ @[simp] lemma of_add_zero [has_zero α] : @multiplicative.of_add α 0 = 1 := rfl @[simp] lemma to_add_one [has_zero α] : (1 : multiplicative α).to_add = 0 := rfl instance [monoid α] : add_monoid (additive α) := { zero := 0, zero_add := @one_mul _ _, add_zero := @mul_one _ _, ..additive.add_semigroup } instance [add_monoid α] : monoid (multiplicative α) := { one := 1, one_mul := @zero_add _ _, mul_one := @add_zero _ _, ..multiplicative.semigroup } instance [comm_monoid α] : add_comm_monoid (additive α) := { .. additive.add_monoid, .. additive.add_comm_semigroup } instance [add_comm_monoid α] : comm_monoid (multiplicative α) := { ..multiplicative.monoid, .. multiplicative.comm_semigroup } instance [has_inv α] : has_neg (additive α) := ⟨λ x, multiplicative.of_add x.to_mul⁻¹⟩ @[simp] lemma of_mul_inv [has_inv α] (x : α) : additive.of_mul x⁻¹ = -(additive.of_mul x) := rfl @[simp] lemma to_mul_neg [has_inv α] (x : additive α) : (-x).to_mul = x.to_mul⁻¹ := rfl instance [has_neg α] : has_inv (multiplicative α) := ⟨λ x, additive.of_mul (-x.to_add)⟩ @[simp] lemma of_add_neg [has_neg α] (x : α) : multiplicative.of_add (-x) = (multiplicative.of_add x)⁻¹ := rfl @[simp] lemma to_add_inv [has_neg α] (x : multiplicative α) : (x⁻¹).to_add = -x.to_add := rfl instance [group α] : add_group (additive α) := { add_left_neg := @mul_left_inv α _, .. additive.has_neg, .. additive.add_monoid } instance [add_group α] : group (multiplicative α) := { mul_left_inv := @add_left_neg α _, .. multiplicative.has_inv, ..multiplicative.monoid } instance [comm_group α] : add_comm_group (additive α) := { .. additive.add_group, .. additive.add_comm_monoid } instance [add_comm_group α] : comm_group (multiplicative α) := { .. multiplicative.group, .. multiplicative.comm_monoid } /-- Reinterpret `f : α →+ β` as `multiplicative α →* multiplicative β`. -/ def add_monoid_hom.to_multiplicative [add_monoid α] [add_monoid β] (f : α →+ β) : multiplicative α →* multiplicative β := ⟨f.1, f.2, f.3⟩ /-- Reinterpret `f : α →* β` as `additive α →+ additive β`. -/ def monoid_hom.to_additive [monoid α] [monoid β] (f : α →* β) : additive α →+ additive β := ⟨f.1, f.2, f.3⟩ /-- Reinterpret `f : additive α →+ β` as `α →* multiplicative β`. -/ def add_monoid_hom.to_multiplicative' [monoid α] [add_monoid β] (f : additive α →+ β) : α →* multiplicative β := ⟨f.1, f.2, f.3⟩ /-- Reinterpret `f : α →* multiplicative β` as `additive α →+ β`. -/ def monoid_hom.to_additive' [monoid α] [add_monoid β] (f : α →* multiplicative β) : additive α →+ β := ⟨f.1, f.2, f.3⟩
72c53a3166687ac354dd98f32cf973ed62f17973
94e33a31faa76775069b071adea97e86e218a8ee
/src/analysis/normed_space/riesz_lemma.lean
a6fd90c3a5b2a72b82cc48626885641074553cec
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
5,355
lean
/- Copyright (c) 2019 Jean Lo. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jean Lo, Yury Kudryashov -/ import analysis.normed_space.basic import topology.metric_space.hausdorff_distance /-! # Applications of the Hausdorff distance in normed spaces Riesz's lemma, stated for a normed space over a normed field: for any closed proper subspace `F` of `E`, there is a nonzero `x` such that `∥x - F∥` is at least `r * ∥x∥` for any `r < 1`. This is `riesz_lemma`. In a nondiscrete normed field (with an element `c` of norm `> 1`) and any `R > ∥c∥`, one can guarantee `∥x∥ ≤ R` and `∥x - y∥ ≥ 1` for any `y` in `F`. This is `riesz_lemma_of_norm_lt`. A further lemma, `metric.closed_ball_inf_dist_compl_subset_closure`, finds a *closed* ball within the closure of a set `s` of optimal distance from a point in `x` to the frontier of `s`. -/ open set metric open_locale topological_space variables {𝕜 : Type*} [normed_field 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] variables {F : Type*} [semi_normed_group F] [normed_space ℝ F] /-- Riesz's lemma, which usually states that it is possible to find a vector with norm 1 whose distance to a closed proper subspace is arbitrarily close to 1. The statement here is in terms of multiples of norms, since in general the existence of an element of norm exactly 1 is not guaranteed. For a variant giving an element with norm in `[1, R]`, see `riesz_lemma_of_norm_lt`. -/ lemma riesz_lemma {F : subspace 𝕜 E} (hFc : is_closed (F : set E)) (hF : ∃ x : E, x ∉ F) {r : ℝ} (hr : r < 1) : ∃ x₀ : E, x₀ ∉ F ∧ ∀ y ∈ F, r * ∥x₀∥ ≤ ∥x₀ - y∥ := begin classical, obtain ⟨x, hx⟩ : ∃ x : E, x ∉ F := hF, let d := metric.inf_dist x F, have hFn : (F : set E).nonempty, from ⟨_, F.zero_mem⟩, have hdp : 0 < d, from lt_of_le_of_ne metric.inf_dist_nonneg (λ heq, hx ((hFc.mem_iff_inf_dist_zero hFn).2 heq.symm)), let r' := max r 2⁻¹, have hr' : r' < 1, by { simp [r', hr], norm_num }, have hlt : 0 < r' := lt_of_lt_of_le (by norm_num) (le_max_right r 2⁻¹), have hdlt : d < d / r', from (lt_div_iff hlt).mpr ((mul_lt_iff_lt_one_right hdp).2 hr'), obtain ⟨y₀, hy₀F, hxy₀⟩ : ∃ y ∈ F, dist x y < d / r' := (metric.inf_dist_lt_iff hFn).mp hdlt, have x_ne_y₀ : x - y₀ ∉ F, { by_contradiction h, have : (x - y₀) + y₀ ∈ F, from F.add_mem h hy₀F, simp only [neg_add_cancel_right, sub_eq_add_neg] at this, exact hx this }, refine ⟨x - y₀, x_ne_y₀, λy hy, le_of_lt _⟩, have hy₀y : y₀ + y ∈ F, from F.add_mem hy₀F hy, calc r * ∥x - y₀∥ ≤ r' * ∥x - y₀∥ : mul_le_mul_of_nonneg_right (le_max_left _ _) (norm_nonneg _) ... < d : by { rw ←dist_eq_norm, exact (lt_div_iff' hlt).1 hxy₀ } ... ≤ dist x (y₀ + y) : metric.inf_dist_le_dist_of_mem hy₀y ... = ∥x - y₀ - y∥ : by { rw [sub_sub, dist_eq_norm] } end /-- A version of Riesz lemma: given a strict closed subspace `F`, one may find an element of norm `≤ R` which is at distance at least `1` of every element of `F`. Here, `R` is any given constant strictly larger than the norm of an element of norm `> 1`. For a version without an `R`, see `riesz_lemma`. Since we are considering a general nondiscrete normed field, there may be a gap in possible norms (for instance no element of norm in `(1,2)`). Hence, we can not allow `R` arbitrarily close to `1`, and require `R > ∥c∥` for some `c : 𝕜` with norm `> 1`. -/ lemma riesz_lemma_of_norm_lt {c : 𝕜} (hc : 1 < ∥c∥) {R : ℝ} (hR : ∥c∥ < R) {F : subspace 𝕜 E} (hFc : is_closed (F : set E)) (hF : ∃ x : E, x ∉ F) : ∃ x₀ : E, ∥x₀∥ ≤ R ∧ ∀ y ∈ F, 1 ≤ ∥x₀ - y∥ := begin have Rpos : 0 < R := (norm_nonneg _).trans_lt hR, have : ∥c∥ / R < 1, by { rw div_lt_iff Rpos, simpa using hR }, rcases riesz_lemma hFc hF this with ⟨x, xF, hx⟩, have x0 : x ≠ 0 := λ H, by simpa [H] using xF, obtain ⟨d, d0, dxlt, ledx, -⟩ : ∃ (d : 𝕜), d ≠ 0 ∧ ∥d • x∥ < R ∧ R / ∥c∥ ≤ ∥d • x∥ ∧ ∥d∥⁻¹ ≤ R⁻¹ * ∥c∥ * ∥x∥ := rescale_to_shell hc Rpos x0, refine ⟨d • x, dxlt.le, λ y hy, _⟩, set y' := d⁻¹ • y with hy', have y'F : y' ∈ F, by simp [hy', submodule.smul_mem _ _ hy], have yy' : y = d • y', by simp [hy', smul_smul, mul_inv_cancel d0], calc 1 = (∥c∥/R) * (R/∥c∥) : by field_simp [Rpos.ne', (zero_lt_one.trans hc).ne'] ... ≤ (∥c∥/R) * (∥d • x∥) : mul_le_mul_of_nonneg_left ledx (div_nonneg (norm_nonneg _) Rpos.le) ... = ∥d∥ * (∥c∥/R * ∥x∥) : by { simp [norm_smul], ring } ... ≤ ∥d∥ * ∥x - y'∥ : mul_le_mul_of_nonneg_left (hx y' (by simp [hy', submodule.smul_mem _ _ hy])) (norm_nonneg _) ... = ∥d • x - y∥ : by simp [yy', ← smul_sub, norm_smul], end lemma metric.closed_ball_inf_dist_compl_subset_closure {x : F} {s : set F} (hx : x ∈ s) : closed_ball x (inf_dist x sᶜ) ⊆ closure s := begin cases eq_or_ne (inf_dist x sᶜ) 0 with h₀ h₀, { rw [h₀, closed_ball_zero'], exact closure_mono (singleton_subset_iff.2 hx) }, { rw ← closure_ball x h₀, exact closure_mono ball_inf_dist_compl_subset } end
1e451fb6d8bd21db2985a7da55839510dca5852f
271e26e338b0c14544a889c31c30b39c989f2e0f
/tests/lean/run/float_cases_bug.lean
aef21a2a2e5b7bd0b6f415e619026f12a48f858f
[ "Apache-2.0" ]
permissive
dgorokho/lean4
805f99b0b60c545b64ac34ab8237a8504f89d7d4
e949a052bad59b1c7b54a82d24d516a656487d8a
refs/heads/master
1,607,061,363,851
1,578,006,086,000
1,578,006,086,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
67
lean
def foo (xs : List Nat) := xs.span (fun n => coe (decide (n = 1)))
7a01fbc6416c58c043fa6c378efd8d5057635a89
3dc4623269159d02a444fe898d33e8c7e7e9461b
/.github/workflows/geo/src/pfin/ops.lean
a56dbb2e47c34783f0cca26f5531f29cbfa5553c
[]
no_license
Or7ando/lean
cc003e6c41048eae7c34aa6bada51c9e9add9e66
d41169cf4e416a0d42092fb6bdc14131cee9dd15
refs/heads/master
1,650,600,589,722
1,587,262,906,000
1,587,262,906,000
255,387,160
0
0
null
null
null
null
UTF-8
Lean
false
false
3,203
lean
import pfin.basic namespace pfin open nat variable {n : nat} protected def succ : pfin n → pfin (succ n) | ⟨a, h⟩ := ⟨nat.succ a, succ_lt_succ h⟩ def of_nat {n : nat} (a : nat) : pfin (succ n) := ⟨a % succ n, nat.mod_lt _ (nat.zero_lt_succ _)⟩ private lemma mlt {n b : nat} : ∀ {a}, n > a → b % n < n | 0 h := nat.mod_lt _ h | (a+1) h := have n > 0, from lt.trans (nat.zero_lt_succ _) h, nat.mod_lt _ this protected def add : pfin n → pfin n → pfin n | ⟨a, h⟩ ⟨b, _⟩ := ⟨(a + b) % n, mlt h⟩ protected def mul : pfin n → pfin n → pfin n | ⟨a, h⟩ ⟨b, _⟩ := ⟨(a * b) % n, mlt h⟩ private lemma sublt {a b n : nat} (h : a < n) : a - b < n := lt_of_le_of_lt (nat.sub_le a b) h protected def sub : pfin n → pfin n → pfin n | ⟨a, h⟩ ⟨b, _⟩ := ⟨a - b, sublt h⟩ private lemma modlt {a b n : nat} (h₁ : a < n) (h₂ : b < n) : a % b < n := begin cases b with b, {simp [mod_zero], assumption}, {have h : a % (succ b) < succ b, apply nat.mod_lt _ (nat.zero_lt_succ _), exact lt.trans h h₂} end protected def mod : pfin n → pfin n → pfin n | ⟨a, h₁⟩ ⟨b, h₂⟩ := ⟨a % b, modlt h₁ h₂⟩ private lemma divlt {a b n : nat} (h : a < n) : a / b < n := lt_of_le_of_lt (nat.div_le_self a b) h protected def div : pfin n → pfin n → pfin n | ⟨a, h⟩ ⟨b, _⟩ := ⟨a / b, divlt h⟩ instance : has_zero (pfin (succ n)) := ⟨⟨0, succ_pos n⟩⟩ instance : has_one (pfin (succ n)) := ⟨of_nat 1⟩ instance : has_add (pfin n) := ⟨pfin.add⟩ instance : has_sub (pfin n) := ⟨pfin.sub⟩ instance : has_mul (pfin n) := ⟨pfin.mul⟩ instance : has_mod (pfin n) := ⟨pfin.mod⟩ instance : has_div (pfin n) := ⟨pfin.div⟩ lemma of_nat_zero : @of_nat n 0 = 0 := rfl lemma add_def (a b : pfin n) : (a + b).val = (a.val + b.val) % n := show (pfin.add a b).val = (a.val + b.val) % n, from by cases a; cases b; simp [pfin.add] lemma mul_def (a b : pfin n) : (a * b).val = (a.val * b.val) % n := show (pfin.mul a b).val = (a.val * b.val) % n, from by cases a; cases b; simp [pfin.mul] lemma sub_def (a b : pfin n) : (a - b).val = a.val - b.val := show (pfin.sub a b).val = a.val - b.val, from by cases a; cases b; simp [pfin.sub] lemma mod_def (a b : pfin n) : (a % b).val = a.val % b.val := show (pfin.mod a b).val = a.val % b.val, from by cases a; cases b; simp [pfin.mod] lemma div_def (a b : pfin n) : (a / b).val = a.val / b.val := show (pfin.div a b).val = a.val / b.val, from by cases a; cases b; simp [pfin.div] lemma lt_def (a b : pfin n) : (a < b) = (a.val < b.val) := show (pfin.lt a b) = (a.val < b.val), from by cases a; cases b; simp [pfin.lt] lemma le_def (a b : pfin n) : (a ≤ b) = (a.val ≤ b.val) := show (pfin.le a b) = (a.val ≤ b.val), from by cases a; cases b; simp [pfin.le] lemma val_zero : (0 : pfin (succ n)).val = 0 := rfl def pred {n : nat} : ∀ i : pfin (succ n), i ≠ 0 → pfin n | ⟨a, h₁⟩ h₂ := ⟨a.pred, begin have this : a ≠ 0, { have aux₁ := vne_of_ne h₂, dsimp at aux₁, rw val_zero at aux₁, exact aux₁ }, exact nat.pred_lt_pred this h₁ end⟩ end pfin
a4390c5906fe68c94f8fd52dfb0fd1b5def8c622
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/ring_theory/ideal/quotient.lean
ca8c7d82c5b75b41e4109898c568c0b9d94a5aaf
[ "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
15,496
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Chris Hughes, Mario Carneiro, Anne Baanen -/ import linear_algebra.quotient import ring_theory.ideal.basic /-! # Ideal quotients This file defines ideal quotients as a special case of submodule quotients and proves some basic results about these quotients. See `algebra.ring_quot` for quotients of non-commutative rings. ## Main definitions - `ideal.quotient`: the quotient of a commutative ring `R` by an ideal `I : ideal R` ## Main results - `ideal.quotient_inf_ring_equiv_pi_quotient`: the **Chinese Remainder Theorem** -/ universes u v w namespace ideal open set open_locale big_operators variables {R : Type u} [comm_ring R] (I : ideal R) {a b : R} variables {S : Type v} /-- The quotient `R/I` of a ring `R` by an ideal `I`. The ideal quotient of `I` is defined to equal the quotient of `I` as an `R`-submodule of `R`. This definition is marked `reducible` so that typeclass instances can be shared between `ideal.quotient I` and `submodule.quotient I`. -/ -- Note that at present `ideal` means a left-ideal, -- so this quotient is only useful in a commutative ring. -- We should develop quotients by two-sided ideals as well. @[reducible] def quotient (I : ideal R) := I.quotient namespace quotient variables {I} {x y : R} instance (I : ideal R) : has_one I.quotient := ⟨submodule.quotient.mk 1⟩ instance (I : ideal R) : has_mul I.quotient := ⟨λ a b, quotient.lift_on₂' a b (λ a b, submodule.quotient.mk (a * b)) $ λ a₁ a₂ b₁ b₂ h₁ h₂, quot.sound $ begin have F := I.add_mem (I.mul_mem_left a₂ h₁) (I.mul_mem_right b₁ h₂), have : a₁ * a₂ - b₁ * b₂ = a₂ * (a₁ - b₁) + (a₂ - b₂) * b₁, { rw [mul_sub, sub_mul, sub_add_sub_cancel, mul_comm, mul_comm b₁] }, rw ← this at F, change _ ∈ _, convert F, end⟩ instance (I : ideal R) : comm_ring I.quotient := { mul := (*), one := 1, mul_assoc := λ a b c, quotient.induction_on₃' a b c $ λ a b c, congr_arg submodule.quotient.mk (mul_assoc a b c), mul_comm := λ a b, quotient.induction_on₂' a b $ λ a b, congr_arg submodule.quotient.mk (mul_comm a b), one_mul := λ a, quotient.induction_on' a $ λ a, congr_arg submodule.quotient.mk (one_mul a), mul_one := λ a, quotient.induction_on' a $ λ a, congr_arg submodule.quotient.mk (mul_one a), left_distrib := λ a b c, quotient.induction_on₃' a b c $ λ a b c, congr_arg submodule.quotient.mk (left_distrib a b c), right_distrib := λ a b c, quotient.induction_on₃' a b c $ λ a b c, congr_arg submodule.quotient.mk (right_distrib a b c), ..submodule.quotient.add_comm_group I } /-- The ring homomorphism from a ring `R` to a quotient ring `R/I`. -/ def mk (I : ideal R) : R →+* I.quotient := ⟨λ a, submodule.quotient.mk a, rfl, λ _ _, rfl, rfl, λ _ _, rfl⟩ /- Two `ring_homs`s from the quotient by an ideal are equal if their compositions with `ideal.quotient.mk'` are equal. See note [partially-applied ext lemmas]. -/ @[ext] lemma ring_hom_ext [non_assoc_semiring S] ⦃f g : I.quotient →+* S⦄ (h : f.comp (mk I) = g.comp (mk I)) : f = g := ring_hom.ext $ λ x, quotient.induction_on' x $ (ring_hom.congr_fun h : _) instance : inhabited (quotient I) := ⟨mk I 37⟩ protected theorem eq : mk I x = mk I y ↔ x - y ∈ I := submodule.quotient.eq I @[simp] theorem mk_eq_mk (x : R) : (submodule.quotient.mk x : quotient I) = mk I x := rfl lemma eq_zero_iff_mem {I : ideal R} : mk I a = 0 ↔ a ∈ I := by conv {to_rhs, rw ← sub_zero a }; exact quotient.eq' theorem zero_eq_one_iff {I : ideal R} : (0 : I.quotient) = 1 ↔ I = ⊤ := eq_comm.trans $ eq_zero_iff_mem.trans (eq_top_iff_one _).symm theorem zero_ne_one_iff {I : ideal R} : (0 : I.quotient) ≠ 1 ↔ I ≠ ⊤ := not_congr zero_eq_one_iff protected theorem nontrivial {I : ideal R} (hI : I ≠ ⊤) : nontrivial I.quotient := ⟨⟨0, 1, zero_ne_one_iff.2 hI⟩⟩ lemma mk_surjective : function.surjective (mk I) := λ y, quotient.induction_on' y (λ x, exists.intro x rfl) /-- If `I` is an ideal of a commutative ring `R`, if `q : R → R/I` is the quotient map, and if `s ⊆ R` is a subset, then `q⁻¹(q(s)) = ⋃ᵢ(i + s)`, the union running over all `i ∈ I`. -/ lemma quotient_ring_saturate (I : ideal R) (s : set R) : mk I ⁻¹' (mk I '' s) = (⋃ x : I, (λ y, x.1 + y) '' s) := begin ext x, simp only [mem_preimage, mem_image, mem_Union, ideal.quotient.eq], exact ⟨λ ⟨a, a_in, h⟩, ⟨⟨_, I.neg_mem h⟩, a, a_in, by simp⟩, λ ⟨⟨i, hi⟩, a, ha, eq⟩, ⟨a, ha, by rw [← eq, sub_add_eq_sub_sub_swap, sub_self, zero_sub]; exact I.neg_mem hi⟩⟩ end instance (I : ideal R) [hI : I.is_prime] : is_domain I.quotient := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b, quotient.induction_on₂' a b $ λ a b hab, (hI.mem_or_mem (eq_zero_iff_mem.1 hab)).elim (or.inl ∘ eq_zero_iff_mem.2) (or.inr ∘ eq_zero_iff_mem.2), .. quotient.nontrivial hI.1 } lemma is_domain_iff_prime (I : ideal R) : is_domain I.quotient ↔ I.is_prime := ⟨ λ ⟨h1, h2⟩, ⟨zero_ne_one_iff.1 $ @zero_ne_one _ _ ⟨h2⟩, λ x y h, by { simp only [←eq_zero_iff_mem, (mk I).map_mul] at ⊢ h, exact h1 h}⟩, λ h, by { resetI, apply_instance }⟩ lemma exists_inv {I : ideal R} [hI : I.is_maximal] : ∀ {a : I.quotient}, a ≠ 0 → ∃ b : I.quotient, a * b = 1 := begin rintro ⟨a⟩ h, rcases hI.exists_inv (mt eq_zero_iff_mem.2 h) with ⟨b, c, hc, abc⟩, rw [mul_comm] at abc, refine ⟨mk _ b, quot.sound _⟩, --quot.sound hb rw ← eq_sub_iff_add_eq' at abc, rw [abc, ← neg_mem_iff, neg_sub] at hc, convert hc, end open_locale classical /-- quotient by maximal ideal is a field. def rather than instance, since users will have computable inverses in some applications. See note [reducible non-instances]. -/ @[reducible] protected noncomputable def field (I : ideal R) [hI : I.is_maximal] : field I.quotient := { inv := λ a, if ha : a = 0 then 0 else classical.some (exists_inv ha), mul_inv_cancel := λ a (ha : a ≠ 0), show a * dite _ _ _ = _, by rw dif_neg ha; exact classical.some_spec (exists_inv ha), inv_zero := dif_pos rfl, ..quotient.comm_ring I, ..quotient.is_domain I } /-- If the quotient by an ideal is a field, then the ideal is maximal. -/ theorem maximal_of_is_field (I : ideal R) (hqf : is_field I.quotient) : I.is_maximal := begin apply ideal.is_maximal_iff.2, split, { intro h, rcases hqf.exists_pair_ne with ⟨⟨x⟩, ⟨y⟩, hxy⟩, exact hxy (ideal.quotient.eq.2 (mul_one (x - y) ▸ I.mul_mem_left _ h)) }, { intros J x hIJ hxnI hxJ, rcases hqf.mul_inv_cancel (mt ideal.quotient.eq_zero_iff_mem.1 hxnI) with ⟨⟨y⟩, hy⟩, rw [← zero_add (1 : R), ← sub_self (x * y), sub_add], refine J.sub_mem (J.mul_mem_right _ hxJ) (hIJ (ideal.quotient.eq.1 hy)) } end /-- The quotient of a ring by an ideal is a field iff the ideal is maximal. -/ theorem maximal_ideal_iff_is_field_quotient (I : ideal R) : I.is_maximal ↔ is_field I.quotient := ⟨λ h, @field.to_is_field I.quotient (@ideal.quotient.field _ _ I h), λ h, maximal_of_is_field I h⟩ variable [comm_ring S] /-- Given a ring homomorphism `f : R →+* S` sending all elements of an ideal to zero, lift it to the quotient by this ideal. -/ def lift (I : ideal R) (f : R →+* S) (H : ∀ (a : R), a ∈ I → f a = 0) : quotient I →+* S := { to_fun := λ x, quotient.lift_on' x f $ λ (a b) (h : _ ∈ _), eq_of_sub_eq_zero $ by rw [← f.map_sub, H _ h], map_one' := f.map_one, map_zero' := f.map_zero, map_add' := λ a₁ a₂, quotient.induction_on₂' a₁ a₂ f.map_add, map_mul' := λ a₁ a₂, quotient.induction_on₂' a₁ a₂ f.map_mul } @[simp] lemma lift_mk (I : ideal R) (f : R →+* S) (H : ∀ (a : R), a ∈ I → f a = 0) : lift I f H (mk I a) = f a := rfl /-- The ring homomorphism from the quotient by a smaller ideal to the quotient by a larger ideal. This is the `ideal.quotient` version of `quot.factor` -/ def factor (S T : ideal R) (H : S ≤ T) : S.quotient →+* T.quotient := ideal.quotient.lift S (T^.quotient.mk) (λ x hx, eq_zero_iff_mem.2 (H hx)) @[simp] lemma factor_mk (S T : ideal R) (H : S ≤ T) (x : R) : factor S T H (mk S x) = mk T x := rfl @[simp] lemma factor_comp_mk (S T : ideal R) (H : S ≤ T) : (factor S T H).comp (mk S) = mk T := by { ext x, rw [ring_hom.comp_apply, factor_mk] } end quotient /-- Quotienting by equal ideals gives equivalent rings. See also `submodule.quot_equiv_of_eq`. -/ def quot_equiv_of_eq {R : Type*} [comm_ring R] {I J : ideal R} (h : I = J) : I.quotient ≃+* J.quotient := { map_mul' := by { rintro ⟨x⟩ ⟨y⟩, refl }, .. submodule.quot_equiv_of_eq I J h } @[simp] lemma quot_equiv_of_eq_mk {R : Type*} [comm_ring R] {I J : ideal R} (h : I = J) (x : R) : quot_equiv_of_eq h (ideal.quotient.mk I x) = ideal.quotient.mk J x := rfl section pi variables (ι : Type v) /-- `R^n/I^n` is a `R/I`-module. -/ instance module_pi : module (I.quotient) (I.pi ι).quotient := { smul := λ c m, quotient.lift_on₂' c m (λ r m, submodule.quotient.mk $ r • m) begin intros c₁ m₁ c₂ m₂ hc hm, apply ideal.quotient.eq.2, intro i, exact I.mul_sub_mul_mem hc (hm i), end, one_smul := begin rintro ⟨a⟩, change ideal.quotient.mk _ _ = ideal.quotient.mk _ _, congr' with i, exact one_mul (a i), end, mul_smul := begin rintro ⟨a⟩ ⟨b⟩ ⟨c⟩, change ideal.quotient.mk _ _ = ideal.quotient.mk _ _, simp only [(•)], congr' with i, exact mul_assoc a b (c i), end, smul_add := begin rintro ⟨a⟩ ⟨b⟩ ⟨c⟩, change ideal.quotient.mk _ _ = ideal.quotient.mk _ _, congr' with i, exact mul_add a (b i) (c i), end, smul_zero := begin rintro ⟨a⟩, change ideal.quotient.mk _ _ = ideal.quotient.mk _ _, congr' with i, exact mul_zero a, end, add_smul := begin rintro ⟨a⟩ ⟨b⟩ ⟨c⟩, change ideal.quotient.mk _ _ = ideal.quotient.mk _ _, congr' with i, exact add_mul a b (c i), end, zero_smul := begin rintro ⟨a⟩, change ideal.quotient.mk _ _ = ideal.quotient.mk _ _, congr' with i, exact zero_mul (a i), end, } /-- `R^n/I^n` is isomorphic to `(R/I)^n` as an `R/I`-module. -/ noncomputable def pi_quot_equiv : (I.pi ι).quotient ≃ₗ[I.quotient] (ι → I.quotient) := { to_fun := λ x, quotient.lift_on' x (λ f i, ideal.quotient.mk I (f i)) $ λ a b hab, funext (λ i, ideal.quotient.eq.2 (hab i)), map_add' := by { rintros ⟨_⟩ ⟨_⟩, refl }, map_smul' := by { rintros ⟨_⟩ ⟨_⟩, refl }, inv_fun := λ x, ideal.quotient.mk (I.pi ι) $ λ i, quotient.out' (x i), left_inv := begin rintro ⟨x⟩, exact ideal.quotient.eq.2 (λ i, ideal.quotient.eq.1 (quotient.out_eq' _)) end, right_inv := begin intro x, ext i, obtain ⟨r, hr⟩ := @quot.exists_rep _ _ (x i), simp_rw ←hr, convert quotient.out_eq' _ end } /-- If `f : R^n → R^m` is an `R`-linear map and `I ⊆ R` is an ideal, then the image of `I^n` is contained in `I^m`. -/ lemma map_pi {ι} [fintype ι] {ι' : Type w} (x : ι → R) (hi : ∀ i, x i ∈ I) (f : (ι → R) →ₗ[R] (ι' → R)) (i : ι') : f x i ∈ I := begin rw pi_eq_sum_univ x, simp only [finset.sum_apply, smul_eq_mul, linear_map.map_sum, pi.smul_apply, linear_map.map_smul], exact I.sum_mem (λ j hj, I.mul_mem_right _ (hi j)) end end pi section chinese_remainder variables {ι : Type v} theorem exists_sub_one_mem_and_mem (s : finset ι) {f : ι → ideal R} (hf : ∀ i ∈ s, ∀ j ∈ s, i ≠ j → f i ⊔ f j = ⊤) (i : ι) (his : i ∈ s) : ∃ r : R, r - 1 ∈ f i ∧ ∀ j ∈ s, j ≠ i → r ∈ f j := begin have : ∀ j ∈ s, j ≠ i → ∃ r : R, ∃ H : r - 1 ∈ f i, r ∈ f j, { intros j hjs hji, specialize hf i his j hjs hji.symm, rw [eq_top_iff_one, submodule.mem_sup] at hf, rcases hf with ⟨r, hri, s, hsj, hrs⟩, refine ⟨1 - r, _, _⟩, { rw [sub_right_comm, sub_self, zero_sub], exact (f i).neg_mem hri }, { rw [← hrs, add_sub_cancel'], exact hsj } }, classical, have : ∃ g : ι → R, (∀ j, g j - 1 ∈ f i) ∧ ∀ j ∈ s, j ≠ i → g j ∈ f j, { choose g hg1 hg2, refine ⟨λ j, if H : j ∈ s ∧ j ≠ i then g j H.1 H.2 else 1, λ j, _, λ j, _⟩, { split_ifs with h, { apply hg1 }, rw sub_self, exact (f i).zero_mem }, { intros hjs hji, rw dif_pos, { apply hg2 }, exact ⟨hjs, hji⟩ } }, rcases this with ⟨g, hgi, hgj⟩, use (∏ x in s.erase i, g x), split, { rw [← quotient.eq, ring_hom.map_one, ring_hom.map_prod], apply finset.prod_eq_one, intros, rw [← ring_hom.map_one, quotient.eq], apply hgi }, intros j hjs hji, rw [← quotient.eq_zero_iff_mem, ring_hom.map_prod], refine finset.prod_eq_zero (finset.mem_erase_of_ne_of_mem hji hjs) _, rw quotient.eq_zero_iff_mem, exact hgj j hjs hji end theorem exists_sub_mem [fintype ι] {f : ι → ideal R} (hf : ∀ i j, i ≠ j → f i ⊔ f j = ⊤) (g : ι → R) : ∃ r : R, ∀ i, r - g i ∈ f i := begin have : ∃ φ : ι → R, (∀ i, φ i - 1 ∈ f i) ∧ (∀ i j, i ≠ j → φ i ∈ f j), { have := exists_sub_one_mem_and_mem (finset.univ : finset ι) (λ i _ j _ hij, hf i j hij), choose φ hφ, existsi λ i, φ i (finset.mem_univ i), exact ⟨λ i, (hφ i _).1, λ i j hij, (hφ i _).2 j (finset.mem_univ j) hij.symm⟩ }, rcases this with ⟨φ, hφ1, hφ2⟩, use ∑ i, g i * φ i, intros i, rw [← quotient.eq, ring_hom.map_sum], refine eq.trans (finset.sum_eq_single i _ _) _, { intros j _ hji, rw quotient.eq_zero_iff_mem, exact (f i).mul_mem_left _ (hφ2 j i hji) }, { intros hi, exact (hi $ finset.mem_univ i).elim }, specialize hφ1 i, rw [← quotient.eq, ring_hom.map_one] at hφ1, rw [ring_hom.map_mul, hφ1, mul_one] end /-- The homomorphism from `R/(⋂ i, f i)` to `∏ i, (R / f i)` featured in the Chinese Remainder Theorem. It is bijective if the ideals `f i` are comaximal. -/ def quotient_inf_to_pi_quotient (f : ι → ideal R) : (⨅ i, f i).quotient →+* Π i, (f i).quotient := quotient.lift (⨅ i, f i) (pi.ring_hom (λ i : ι, (quotient.mk (f i) : _))) $ λ r hr, begin rw submodule.mem_infi at hr, ext i, exact quotient.eq_zero_iff_mem.2 (hr i) end theorem quotient_inf_to_pi_quotient_bijective [fintype ι] {f : ι → ideal R} (hf : ∀ i j, i ≠ j → f i ⊔ f j = ⊤) : function.bijective (quotient_inf_to_pi_quotient f) := ⟨λ x y, quotient.induction_on₂' x y $ λ r s hrs, quotient.eq.2 $ (submodule.mem_infi _).2 $ λ i, quotient.eq.1 $ show quotient_inf_to_pi_quotient f (quotient.mk' r) i = _, by rw hrs; refl, λ g, let ⟨r, hr⟩ := exists_sub_mem hf (λ i, quotient.out' (g i)) in ⟨quotient.mk _ r, funext $ λ i, quotient.out_eq' (g i) ▸ quotient.eq.2 (hr i)⟩⟩ /-- Chinese Remainder Theorem. Eisenbud Ex.2.6. Similar to Atiyah-Macdonald 1.10 and Stacks 00DT -/ noncomputable def quotient_inf_ring_equiv_pi_quotient [fintype ι] (f : ι → ideal R) (hf : ∀ i j, i ≠ j → f i ⊔ f j = ⊤) : (⨅ i, f i).quotient ≃+* Π i, (f i).quotient := { .. equiv.of_bijective _ (quotient_inf_to_pi_quotient_bijective hf), .. quotient_inf_to_pi_quotient f } end chinese_remainder end ideal
7d26e44b5b846543e8f1493f3f1ec01f7f93ab61
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Meta/Tactic/Cleanup.lean
a6031aec2bc7d149060faca6a8af495aceeef45d
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
2,765
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.CollectFVars import Lean.Meta.Tactic.Clear namespace Lean.Meta private partial def cleanupCore (mvarId : MVarId) : MetaM MVarId := do mvarId.withContext do mvarId.checkNotAssigned `cleanup let used ← collectUsed |>.run' (false, {}) let mut lctx ← getLCtx for localDecl in lctx do unless used.contains localDecl.fvarId do lctx := lctx.erase localDecl.fvarId let localInsts := (← getLocalInstances).filter fun inst => used.contains inst.fvar.fvarId! let mvarNew ← mkFreshExprMVarAt lctx localInsts (← instantiateMVars (← mvarId.getType)) .syntheticOpaque (← mvarId.getTag) mvarId.assign mvarNew return mvarNew.mvarId! where addUsedFVars (e : Expr) : StateRefT (Bool × FVarIdSet) MetaM Unit := do let (_, s) ← (← instantiateMVars e).collectFVars |>.run {} for fvarId in s.fvarSet do addUsedFVar fvarId addDeps (fvarId : FVarId) : StateRefT (Bool × FVarIdSet) MetaM Unit := do let localDecl ← fvarId.getDecl addUsedFVars localDecl.type if let some val := localDecl.value? then addUsedFVars val addUsedFVar (fvarId : FVarId) : StateRefT (Bool × FVarIdSet) MetaM Unit := do unless (← get).2.contains fvarId do modify fun (_, s) => (true, s.insert fvarId) addDeps fvarId /-- We include `p` in the used-set, if `p` is a proposition that contains a `x` that is in the used-set. -/ collectPropsStep : StateRefT (Bool × FVarIdSet) MetaM Unit := do let usedSet := (← get).2 for localDecl in (← getLCtx) do if (← isProp localDecl.type) then if (← dependsOnPred localDecl.type usedSet.contains) then addUsedFVar localDecl.fvarId collectProps : StateRefT (Bool × FVarIdSet) MetaM Unit := do modify fun s => (false, s.2) collectPropsStep if (← get).1 then collectProps collectUsed : StateRefT (Bool × FVarIdSet) MetaM FVarIdSet := do addUsedFVars (← instantiateMVars (← mvarId.getType)) collectProps return (← get).2 /-- Auxiliary tactic for cleaning the local context. It removes local declarations (aka hypotheses) that are *not* relevant. We say a variable `x` is "relevant" if - It occurs in the target type, or - There is a relevant variable `y` that depends on `x`, or - The type of `x` is a proposition and it depends on a relevant variable `y`. -/ abbrev _root_.Lean.MVarId.cleanup (mvarId : MVarId) : MetaM MVarId := do cleanupCore mvarId @[deprecated MVarId.cleanup] abbrev cleanup (mvarId : MVarId) : MetaM MVarId := do mvarId.cleanup end Lean.Meta
a902928601c245bcde2fd0c0e1e4f9e10153b20a
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/test/set.lean
ecd1abd0def11c06cbc36295d592ad735da9fe6b
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
1,055
lean
import data.matrix.notation example (x : ℕ) (h : x = 3) : x + x + x = 9 := begin set y := x with ←h_xy, guard_hyp y := ℕ, guard_hyp h_xy := x = y, guard_hyp h := y = 3, guard_target y + y + y = 9, set! z : ℕ := y, guard_target y + y + y = 9, simp [h] end example : true := let X1 := (![![1, 0], ![0, 0]] : matrix (fin 2) (fin 2) ℕ), -- X1 : fin 1.succ → fin 2 → ℕ X2 : matrix (fin 2) (fin 2) ℕ := ![![1, 0], ![0, 0]] in -- X2 : matrix (fin 2) (fin 2) ℕ begin set Y1 := (![![1, 0], ![0, 0]] : matrix (fin 2) (fin 2) ℕ), set Y2 : matrix (fin 2) (fin 2) ℕ := ![![1, 0], ![0, 0]], let Z1 := (![![1, 0], ![0, 0]] : matrix (fin 2) (fin 2) ℕ), let Z2 : matrix (fin 2) (fin 2) ℕ := ![![1, 0], ![0, 0]], guard_hyp Y2 := matrix (fin 2) (fin 2) ℕ, trivial end def T {α : Type} := ℕ def v : @T ℕ := nat.zero def S := @T ℕ def u : S := nat.zero def p : true := begin set a : T := v, set b : T := u, -- the type `T` can't be fully elaborated without the body but this is fine trivial end
32440af260ee76e26f845a909aa3427c578ef9d6
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/measure_theory/function/conditional_expectation/condexp_L2.lean
b099139680fd1e566c7fd0e9d6c39e3e1bf754c1
[ "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
25,788
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 analysis.inner_product_space.projection import measure_theory.function.conditional_expectation.unique /-! # Conditional expectation in L2 > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file contains one step of the construction of the conditional expectation, which is completed in `measure_theory.function.conditional_expectation.basic`. See that file for a description of the full process. We build the conditional expectation of an `L²` function, as an element of `L²`. This is the orthogonal projection on the subspace of almost everywhere `m`-measurable functions. ## Main definitions * `condexp_L2`: Conditional expectation of a function in L2 with respect to a sigma-algebra: it is the orthogonal projection on the subspace `Lp_meas`. ## Implementation notes Most of the results in this file are valid for a complete real normed space `F`. However, some lemmas also use `𝕜 : is_R_or_C`: * `condexp_L2` is defined only for an `inner_product_space` for now, and we use `𝕜` for its field. * results about scalar multiplication are stated not only for `ℝ` but also for `𝕜` if we happen to have `normed_space 𝕜 F`. -/ open topological_space filter continuous_linear_map open_locale ennreal topology measure_theory namespace measure_theory variables {α E E' F G G' 𝕜 : Type*} {p : ℝ≥0∞} [is_R_or_C 𝕜] -- 𝕜 for ℝ or ℂ -- E for an inner product space [normed_add_comm_group E] [inner_product_space 𝕜 E] [complete_space E] -- E' for an inner product space on which we compute integrals [normed_add_comm_group E'] [inner_product_space 𝕜 E'] [complete_space E'] [normed_space ℝ E'] -- F for a Lp submodule [normed_add_comm_group F] [normed_space 𝕜 F] -- G for a Lp add_subgroup [normed_add_comm_group G] -- G' for integrals on a Lp add_subgroup [normed_add_comm_group G'] [normed_space ℝ G'] [complete_space G'] variables {m m0 : measurable_space α} {μ : measure α} {s t : set α} local notation `⟪`x`, `y`⟫` := @inner 𝕜 E _ x y local notation `⟪`x`, `y`⟫₂` := @inner 𝕜 (α →₂[μ] E) _ x y variables (𝕜) /-- Conditional expectation of a function in L2 with respect to a sigma-algebra -/ noncomputable def condexp_L2 (hm : m ≤ m0) : (α →₂[μ] E) →L[𝕜] (Lp_meas E 𝕜 m 2 μ) := @orthogonal_projection 𝕜 (α →₂[μ] E) _ _ _ (Lp_meas E 𝕜 m 2 μ) (by { haveI : fact (m ≤ m0) := ⟨hm⟩, exact infer_instance, }) variables {𝕜} lemma ae_strongly_measurable'_condexp_L2 (hm : m ≤ m0) (f : α →₂[μ] E) : ae_strongly_measurable' m (condexp_L2 𝕜 hm f) μ := Lp_meas.ae_strongly_measurable' _ lemma integrable_on_condexp_L2_of_measure_ne_top (hm : m ≤ m0) (hμs : μ s ≠ ∞) (f : α →₂[μ] E) : integrable_on (condexp_L2 𝕜 hm f) s μ := integrable_on_Lp_of_measure_ne_top ((condexp_L2 𝕜 hm f) : α →₂[μ] E) fact_one_le_two_ennreal.elim hμs lemma integrable_condexp_L2_of_is_finite_measure (hm : m ≤ m0) [is_finite_measure μ] {f : α →₂[μ] E} : integrable (condexp_L2 𝕜 hm f) μ := integrable_on_univ.mp $ integrable_on_condexp_L2_of_measure_ne_top hm (measure_ne_top _ _) f lemma norm_condexp_L2_le_one (hm : m ≤ m0) : ‖@condexp_L2 α E 𝕜 _ _ _ _ _ _ μ hm‖ ≤ 1 := by { haveI : fact (m ≤ m0) := ⟨hm⟩, exact orthogonal_projection_norm_le _, } lemma norm_condexp_L2_le (hm : m ≤ m0) (f : α →₂[μ] E) : ‖condexp_L2 𝕜 hm f‖ ≤ ‖f‖ := ((@condexp_L2 _ E 𝕜 _ _ _ _ _ _ μ hm).le_op_norm f).trans (mul_le_of_le_one_left (norm_nonneg _) (norm_condexp_L2_le_one hm)) lemma snorm_condexp_L2_le (hm : m ≤ m0) (f : α →₂[μ] E) : snorm (condexp_L2 𝕜 hm f) 2 μ ≤ snorm f 2 μ := begin rw [Lp_meas_coe, ← ennreal.to_real_le_to_real (Lp.snorm_ne_top _) (Lp.snorm_ne_top _), ← Lp.norm_def, ← Lp.norm_def, submodule.norm_coe], exact norm_condexp_L2_le hm f, end lemma norm_condexp_L2_coe_le (hm : m ≤ m0) (f : α →₂[μ] E) : ‖(condexp_L2 𝕜 hm f : α →₂[μ] E)‖ ≤ ‖f‖ := begin rw [Lp.norm_def, Lp.norm_def, ← Lp_meas_coe], refine (ennreal.to_real_le_to_real _ (Lp.snorm_ne_top _)).mpr (snorm_condexp_L2_le hm f), exact Lp.snorm_ne_top _, end lemma inner_condexp_L2_left_eq_right (hm : m ≤ m0) {f g : α →₂[μ] E} : ⟪(condexp_L2 𝕜 hm f : α →₂[μ] E), g⟫₂ = ⟪f, (condexp_L2 𝕜 hm g : α →₂[μ] E)⟫₂ := by { haveI : fact (m ≤ m0) := ⟨hm⟩, exact inner_orthogonal_projection_left_eq_right _ f g, } lemma condexp_L2_indicator_of_measurable (hm : m ≤ m0) (hs : measurable_set[m] s) (hμs : μ s ≠ ∞) (c : E) : (condexp_L2 𝕜 hm (indicator_const_Lp 2 (hm s hs) hμs c) : α →₂[μ] E) = indicator_const_Lp 2 (hm s hs) hμs c := begin rw condexp_L2, haveI : fact (m ≤ m0) := ⟨hm⟩, have h_mem : indicator_const_Lp 2 (hm s hs) hμs c ∈ Lp_meas E 𝕜 m 2 μ, from mem_Lp_meas_indicator_const_Lp hm hs hμs, let ind := (⟨indicator_const_Lp 2 (hm s hs) hμs c, h_mem⟩ : Lp_meas E 𝕜 m 2 μ), have h_coe_ind : (ind : α →₂[μ] E) = indicator_const_Lp 2 (hm s hs) hμs c, by refl, have h_orth_mem := orthogonal_projection_mem_subspace_eq_self ind, rw [← h_coe_ind, h_orth_mem], end lemma inner_condexp_L2_eq_inner_fun (hm : m ≤ m0) (f g : α →₂[μ] E) (hg : ae_strongly_measurable' m g μ) : ⟪(condexp_L2 𝕜 hm f : α →₂[μ] E), g⟫₂ = ⟪f, g⟫₂ := begin symmetry, rw [← sub_eq_zero, ← inner_sub_left, condexp_L2], simp only [mem_Lp_meas_iff_ae_strongly_measurable'.mpr hg, orthogonal_projection_inner_eq_zero], end section real variables {hm : m ≤ m0} lemma integral_condexp_L2_eq_of_fin_meas_real (f : Lp 𝕜 2 μ) (hs : measurable_set[m] s) (hμs : μ s ≠ ∞) : ∫ x in s, condexp_L2 𝕜 hm f x ∂μ = ∫ x in s, f x ∂μ := begin rw ← L2.inner_indicator_const_Lp_one (hm s hs) hμs, have h_eq_inner : ∫ x in s, condexp_L2 𝕜 hm f x ∂μ = inner (indicator_const_Lp 2 (hm s hs) hμs (1 : 𝕜)) (condexp_L2 𝕜 hm f), { rw L2.inner_indicator_const_Lp_one (hm s hs) hμs, congr, }, rw [h_eq_inner, ← inner_condexp_L2_left_eq_right, condexp_L2_indicator_of_measurable hm hs hμs], end lemma lintegral_nnnorm_condexp_L2_le (hs : measurable_set[m] s) (hμs : μ s ≠ ∞) (f : Lp ℝ 2 μ) : ∫⁻ x in s, ‖condexp_L2 ℝ hm f x‖₊ ∂μ ≤ ∫⁻ x in s, ‖f x‖₊ ∂μ := begin let h_meas := Lp_meas.ae_strongly_measurable' (condexp_L2 ℝ hm f), let g := h_meas.some, have hg_meas : strongly_measurable[m] g, from h_meas.some_spec.1, have hg_eq : g =ᵐ[μ] condexp_L2 ℝ hm f, from h_meas.some_spec.2.symm, have hg_eq_restrict : g =ᵐ[μ.restrict s] condexp_L2 ℝ hm f, from ae_restrict_of_ae hg_eq, have hg_nnnorm_eq : (λ x, (‖g x‖₊ : ℝ≥0∞)) =ᵐ[μ.restrict s] (λ x, (‖condexp_L2 ℝ hm f x‖₊ : ℝ≥0∞)), { refine hg_eq_restrict.mono (λ x hx, _), dsimp only, rw hx, }, rw lintegral_congr_ae hg_nnnorm_eq.symm, refine lintegral_nnnorm_le_of_forall_fin_meas_integral_eq hm (Lp.strongly_measurable f) _ _ _ _ hs hμs, { exact integrable_on_Lp_of_measure_ne_top f fact_one_le_two_ennreal.elim hμs, }, { exact hg_meas, }, { rw [integrable_on, integrable_congr hg_eq_restrict], exact integrable_on_condexp_L2_of_measure_ne_top hm hμs f, }, { intros t ht hμt, rw ← integral_condexp_L2_eq_of_fin_meas_real f ht hμt.ne, exact set_integral_congr_ae (hm t ht) (hg_eq.mono (λ x hx _, hx)), }, end lemma condexp_L2_ae_eq_zero_of_ae_eq_zero (hs : measurable_set[m] s) (hμs : μ s ≠ ∞) {f : Lp ℝ 2 μ} (hf : f =ᵐ[μ.restrict s] 0) : condexp_L2 ℝ hm f =ᵐ[μ.restrict s] 0 := begin suffices h_nnnorm_eq_zero : ∫⁻ x in s, ‖condexp_L2 ℝ hm f x‖₊ ∂μ = 0, { rw lintegral_eq_zero_iff at h_nnnorm_eq_zero, refine h_nnnorm_eq_zero.mono (λ x hx, _), dsimp only at hx, rw pi.zero_apply at hx ⊢, { rwa [ennreal.coe_eq_zero, nnnorm_eq_zero] at hx, }, { refine measurable.coe_nnreal_ennreal (measurable.nnnorm _), rw Lp_meas_coe, exact (Lp.strongly_measurable _).measurable }, }, refine le_antisymm _ (zero_le _), refine (lintegral_nnnorm_condexp_L2_le hs hμs f).trans (le_of_eq _), rw lintegral_eq_zero_iff, { refine hf.mono (λ x hx, _), dsimp only, rw hx, simp, }, { exact (Lp.strongly_measurable _).ennnorm, }, end lemma lintegral_nnnorm_condexp_L2_indicator_le_real (hs : measurable_set s) (hμs : μ s ≠ ∞) (ht : measurable_set[m] t) (hμt : μ t ≠ ∞) : ∫⁻ a in t, ‖condexp_L2 ℝ hm (indicator_const_Lp 2 hs hμs (1 : ℝ)) a‖₊ ∂μ ≤ μ (s ∩ t) := begin refine (lintegral_nnnorm_condexp_L2_le ht hμt _).trans (le_of_eq _), have h_eq : ∫⁻ x in t, ‖(indicator_const_Lp 2 hs hμs (1 : ℝ)) x‖₊ ∂μ = ∫⁻ x in t, s.indicator (λ x, (1 : ℝ≥0∞)) x ∂μ, { refine lintegral_congr_ae (ae_restrict_of_ae _), refine (@indicator_const_Lp_coe_fn _ _ _ 2 _ _ _ hs hμs (1 : ℝ)).mono (λ x hx, _), rw hx, classical, simp_rw set.indicator_apply, split_ifs; simp, }, rw [h_eq, lintegral_indicator _ hs, lintegral_const, measure.restrict_restrict hs], simp only [one_mul, set.univ_inter, measurable_set.univ, measure.restrict_apply], end end real /-- `condexp_L2` commutes with taking inner products with constants. See the lemma `condexp_L2_comp_continuous_linear_map` for a more general result about commuting with continuous linear maps. -/ lemma condexp_L2_const_inner (hm : m ≤ m0) (f : Lp E 2 μ) (c : E) : condexp_L2 𝕜 hm (((Lp.mem_ℒp f).const_inner c).to_Lp (λ a, ⟪c, f a⟫)) =ᵐ[μ] λ a, ⟪c, condexp_L2 𝕜 hm f a⟫ := begin rw Lp_meas_coe, have h_mem_Lp : mem_ℒp (λ a, ⟪c, condexp_L2 𝕜 hm f a⟫) 2 μ, { refine mem_ℒp.const_inner _ _, rw Lp_meas_coe, exact Lp.mem_ℒp _, }, have h_eq : h_mem_Lp.to_Lp _ =ᵐ[μ] λ a, ⟪c, condexp_L2 𝕜 hm f a⟫, from h_mem_Lp.coe_fn_to_Lp, refine eventually_eq.trans _ h_eq, refine Lp.ae_eq_of_forall_set_integral_eq' 𝕜 hm _ _ two_ne_zero ennreal.coe_ne_top (λ s hs hμs, integrable_on_condexp_L2_of_measure_ne_top hm hμs.ne _) _ _ _ _, { intros s hs hμs, rw [integrable_on, integrable_congr (ae_restrict_of_ae h_eq)], exact (integrable_on_condexp_L2_of_measure_ne_top hm hμs.ne _).const_inner _, }, { intros s hs hμs, rw [← Lp_meas_coe, integral_condexp_L2_eq_of_fin_meas_real _ hs hμs.ne, integral_congr_ae (ae_restrict_of_ae h_eq), Lp_meas_coe, ← L2.inner_indicator_const_Lp_eq_set_integral_inner 𝕜 ↑(condexp_L2 𝕜 hm f) (hm s hs) c hμs.ne, ← inner_condexp_L2_left_eq_right, condexp_L2_indicator_of_measurable, L2.inner_indicator_const_Lp_eq_set_integral_inner 𝕜 f (hm s hs) c hμs.ne, set_integral_congr_ae (hm s hs) ((mem_ℒp.coe_fn_to_Lp ((Lp.mem_ℒp f).const_inner c)).mono (λ x hx hxs, hx))], }, { rw ← Lp_meas_coe, exact Lp_meas.ae_strongly_measurable' _, }, { refine ae_strongly_measurable'.congr _ h_eq.symm, exact (Lp_meas.ae_strongly_measurable' _).const_inner _, }, end /-- `condexp_L2` verifies the equality of integrals defining the conditional expectation. -/ lemma integral_condexp_L2_eq (hm : m ≤ m0) (f : Lp E' 2 μ) (hs : measurable_set[m] s) (hμs : μ s ≠ ∞) : ∫ x in s, condexp_L2 𝕜 hm f x ∂μ = ∫ x in s, f x ∂μ := begin rw [← sub_eq_zero, Lp_meas_coe, ← integral_sub' (integrable_on_Lp_of_measure_ne_top _ fact_one_le_two_ennreal.elim hμs) (integrable_on_Lp_of_measure_ne_top _ fact_one_le_two_ennreal.elim hμs)], refine integral_eq_zero_of_forall_integral_inner_eq_zero 𝕜 _ _ _, { rw integrable_congr (ae_restrict_of_ae (Lp.coe_fn_sub ↑(condexp_L2 𝕜 hm f) f).symm), exact integrable_on_Lp_of_measure_ne_top _ fact_one_le_two_ennreal.elim hμs, }, intro c, simp_rw [pi.sub_apply, inner_sub_right], rw integral_sub ((integrable_on_Lp_of_measure_ne_top _ fact_one_le_two_ennreal.elim hμs).const_inner c) ((integrable_on_Lp_of_measure_ne_top _ fact_one_le_two_ennreal.elim hμs).const_inner c), have h_ae_eq_f := mem_ℒp.coe_fn_to_Lp ((Lp.mem_ℒp f).const_inner c), rw [← Lp_meas_coe, sub_eq_zero, ← set_integral_congr_ae (hm s hs) ((condexp_L2_const_inner hm f c).mono (λ x hx _, hx)), ← set_integral_congr_ae (hm s hs) (h_ae_eq_f.mono (λ x hx _, hx))], exact integral_condexp_L2_eq_of_fin_meas_real _ hs hμs, end variables {E'' 𝕜' : Type*} [is_R_or_C 𝕜'] [normed_add_comm_group E''] [inner_product_space 𝕜' E''] [complete_space E''] [normed_space ℝ E''] variables (𝕜 𝕜') lemma condexp_L2_comp_continuous_linear_map (hm : m ≤ m0) (T : E' →L[ℝ] E'') (f : α →₂[μ] E') : (condexp_L2 𝕜' hm (T.comp_Lp f) : α →₂[μ] E'') =ᵐ[μ] T.comp_Lp (condexp_L2 𝕜 hm f : α →₂[μ] E') := begin refine Lp.ae_eq_of_forall_set_integral_eq' 𝕜' hm _ _ two_ne_zero ennreal.coe_ne_top (λ s hs hμs, integrable_on_condexp_L2_of_measure_ne_top hm hμs.ne _) (λ s hs hμs, integrable_on_Lp_of_measure_ne_top _ fact_one_le_two_ennreal.elim hμs.ne) _ _ _, { intros s hs hμs, rw [T.set_integral_comp_Lp _ (hm s hs), T.integral_comp_comm (integrable_on_Lp_of_measure_ne_top _ fact_one_le_two_ennreal.elim hμs.ne), ← Lp_meas_coe, ← Lp_meas_coe, integral_condexp_L2_eq hm f hs hμs.ne, integral_condexp_L2_eq hm (T.comp_Lp f) hs hμs.ne, T.set_integral_comp_Lp _ (hm s hs), T.integral_comp_comm (integrable_on_Lp_of_measure_ne_top f fact_one_le_two_ennreal.elim hμs.ne)], }, { rw ← Lp_meas_coe, exact Lp_meas.ae_strongly_measurable' _, }, { have h_coe := T.coe_fn_comp_Lp (condexp_L2 𝕜 hm f : α →₂[μ] E'), rw ← eventually_eq at h_coe, refine ae_strongly_measurable'.congr _ h_coe.symm, exact (Lp_meas.ae_strongly_measurable' (condexp_L2 𝕜 hm f)).continuous_comp T.continuous, }, end variables {𝕜 𝕜'} section condexp_L2_indicator variables (𝕜) lemma condexp_L2_indicator_ae_eq_smul (hm : m ≤ m0) (hs : measurable_set s) (hμs : μ s ≠ ∞) (x : E') : condexp_L2 𝕜 hm (indicator_const_Lp 2 hs hμs x) =ᵐ[μ] λ a, (condexp_L2 ℝ hm (indicator_const_Lp 2 hs hμs (1 : ℝ)) a) • x := begin rw indicator_const_Lp_eq_to_span_singleton_comp_Lp hs hμs x, have h_comp := condexp_L2_comp_continuous_linear_map ℝ 𝕜 hm (to_span_singleton ℝ x) (indicator_const_Lp 2 hs hμs (1 : ℝ)), rw ← Lp_meas_coe at h_comp, refine h_comp.trans _, exact (to_span_singleton ℝ x).coe_fn_comp_Lp _, end lemma condexp_L2_indicator_eq_to_span_singleton_comp (hm : m ≤ m0) (hs : measurable_set s) (hμs : μ s ≠ ∞) (x : E') : (condexp_L2 𝕜 hm (indicator_const_Lp 2 hs hμs x) : α →₂[μ] E') = (to_span_singleton ℝ x).comp_Lp (condexp_L2 ℝ hm (indicator_const_Lp 2 hs hμs (1 : ℝ))) := begin ext1, rw ← Lp_meas_coe, refine (condexp_L2_indicator_ae_eq_smul 𝕜 hm hs hμs x).trans _, have h_comp := (to_span_singleton ℝ x).coe_fn_comp_Lp (condexp_L2 ℝ hm (indicator_const_Lp 2 hs hμs (1 : ℝ)) : α →₂[μ] ℝ), rw ← eventually_eq at h_comp, refine eventually_eq.trans _ h_comp.symm, refine eventually_of_forall (λ y, _), refl, end variables {𝕜} lemma set_lintegral_nnnorm_condexp_L2_indicator_le (hm : m ≤ m0) (hs : measurable_set s) (hμs : μ s ≠ ∞) (x : E') {t : set α} (ht : measurable_set[m] t) (hμt : μ t ≠ ∞) : ∫⁻ a in t, ‖condexp_L2 𝕜 hm (indicator_const_Lp 2 hs hμs x) a‖₊ ∂μ ≤ μ (s ∩ t) * ‖x‖₊ := calc ∫⁻ a in t, ‖condexp_L2 𝕜 hm (indicator_const_Lp 2 hs hμs x) a‖₊ ∂μ = ∫⁻ a in t, ‖(condexp_L2 ℝ hm (indicator_const_Lp 2 hs hμs (1 : ℝ)) a) • x‖₊ ∂μ : set_lintegral_congr_fun (hm t ht) ((condexp_L2_indicator_ae_eq_smul 𝕜 hm hs hμs x).mono (λ a ha hat, by rw ha)) ... = ∫⁻ a in t, ‖condexp_L2 ℝ hm (indicator_const_Lp 2 hs hμs (1 : ℝ)) a‖₊ ∂μ * ‖x‖₊ : begin simp_rw [nnnorm_smul, ennreal.coe_mul], rw [lintegral_mul_const, Lp_meas_coe], exact (Lp.strongly_measurable _).ennnorm end ... ≤ μ (s ∩ t) * ‖x‖₊ : mul_le_mul_right' (lintegral_nnnorm_condexp_L2_indicator_le_real hs hμs ht hμt) _ lemma lintegral_nnnorm_condexp_L2_indicator_le (hm : m ≤ m0) (hs : measurable_set s) (hμs : μ s ≠ ∞) (x : E') [sigma_finite (μ.trim hm)] : ∫⁻ a, ‖condexp_L2 𝕜 hm (indicator_const_Lp 2 hs hμs x) a‖₊ ∂μ ≤ μ s * ‖x‖₊ := begin refine lintegral_le_of_forall_fin_meas_le' hm (μ s * ‖x‖₊) _ (λ t ht hμt, _), { rw Lp_meas_coe, exact (Lp.ae_strongly_measurable _).ennnorm }, refine (set_lintegral_nnnorm_condexp_L2_indicator_le hm hs hμs x ht hμt).trans _, exact mul_le_mul_right' (measure_mono (set.inter_subset_left _ _)) _ end /-- If the measure `μ.trim hm` is sigma-finite, then the conditional expectation of a measurable set with finite measure is integrable. -/ lemma integrable_condexp_L2_indicator (hm : m ≤ m0) [sigma_finite (μ.trim hm)] (hs : measurable_set s) (hμs : μ s ≠ ∞) (x : E') : integrable (condexp_L2 𝕜 hm (indicator_const_Lp 2 hs hμs x)) μ := begin refine integrable_of_forall_fin_meas_le' hm (μ s * ‖x‖₊) (ennreal.mul_lt_top hμs ennreal.coe_ne_top) _ _, { rw Lp_meas_coe, exact Lp.ae_strongly_measurable _, }, { refine λ t ht hμt, (set_lintegral_nnnorm_condexp_L2_indicator_le hm hs hμs x ht hμt).trans _, exact mul_le_mul_right' (measure_mono (set.inter_subset_left _ _)) _, }, end end condexp_L2_indicator section condexp_ind_smul variables [normed_space ℝ G] {hm : m ≤ m0} /-- Conditional expectation of the indicator of a measurable set with finite measure, in L2. -/ noncomputable def condexp_ind_smul (hm : m ≤ m0) (hs : measurable_set s) (hμs : μ s ≠ ∞) (x : G) : Lp G 2 μ := (to_span_singleton ℝ x).comp_LpL 2 μ (condexp_L2 ℝ hm (indicator_const_Lp 2 hs hμs (1 : ℝ))) lemma ae_strongly_measurable'_condexp_ind_smul (hm : m ≤ m0) (hs : measurable_set s) (hμs : μ s ≠ ∞) (x : G) : ae_strongly_measurable' m (condexp_ind_smul hm hs hμs x) μ := begin have h : ae_strongly_measurable' m (condexp_L2 ℝ hm (indicator_const_Lp 2 hs hμs (1 : ℝ))) μ, from ae_strongly_measurable'_condexp_L2 _ _, rw condexp_ind_smul, suffices : ae_strongly_measurable' m ((to_span_singleton ℝ x) ∘ (condexp_L2 ℝ hm (indicator_const_Lp 2 hs hμs (1 : ℝ)))) μ, { refine ae_strongly_measurable'.congr this _, refine eventually_eq.trans _ (coe_fn_comp_LpL _ _).symm, rw Lp_meas_coe, }, exact ae_strongly_measurable'.continuous_comp (to_span_singleton ℝ x).continuous h, end lemma condexp_ind_smul_add (hs : measurable_set s) (hμs : μ s ≠ ∞) (x y : G) : condexp_ind_smul hm hs hμs (x + y) = condexp_ind_smul hm hs hμs x + condexp_ind_smul hm hs hμs y := by { simp_rw [condexp_ind_smul], rw [to_span_singleton_add, add_comp_LpL, add_apply], } lemma condexp_ind_smul_smul (hs : measurable_set s) (hμs : μ s ≠ ∞) (c : ℝ) (x : G) : condexp_ind_smul hm hs hμs (c • x) = c • condexp_ind_smul hm hs hμs x := by { simp_rw [condexp_ind_smul], rw [to_span_singleton_smul, smul_comp_LpL, smul_apply], } lemma condexp_ind_smul_smul' [normed_space ℝ F] [smul_comm_class ℝ 𝕜 F] (hs : measurable_set s) (hμs : μ s ≠ ∞) (c : 𝕜) (x : F) : condexp_ind_smul hm hs hμs (c • x) = c • condexp_ind_smul hm hs hμs x := by rw [condexp_ind_smul, condexp_ind_smul, to_span_singleton_smul', (to_span_singleton ℝ x).smul_comp_LpL c, smul_apply] lemma condexp_ind_smul_ae_eq_smul (hm : m ≤ m0) (hs : measurable_set s) (hμs : μ s ≠ ∞) (x : G) : condexp_ind_smul hm hs hμs x =ᵐ[μ] λ a, (condexp_L2 ℝ hm (indicator_const_Lp 2 hs hμs (1 : ℝ)) a) • x := (to_span_singleton ℝ x).coe_fn_comp_LpL _ lemma set_lintegral_nnnorm_condexp_ind_smul_le (hm : m ≤ m0) (hs : measurable_set s) (hμs : μ s ≠ ∞) (x : G) {t : set α} (ht : measurable_set[m] t) (hμt : μ t ≠ ∞) : ∫⁻ a in t, ‖condexp_ind_smul hm hs hμs x a‖₊ ∂μ ≤ μ (s ∩ t) * ‖x‖₊ := calc ∫⁻ a in t, ‖condexp_ind_smul hm hs hμs x a‖₊ ∂μ = ∫⁻ a in t, ‖condexp_L2 ℝ hm (indicator_const_Lp 2 hs hμs (1 : ℝ)) a • x‖₊ ∂μ : set_lintegral_congr_fun (hm t ht) ((condexp_ind_smul_ae_eq_smul hm hs hμs x).mono (λ a ha hat, by rw ha )) ... = ∫⁻ a in t, ‖condexp_L2 ℝ hm (indicator_const_Lp 2 hs hμs (1 : ℝ)) a‖₊ ∂μ * ‖x‖₊ : begin simp_rw [nnnorm_smul, ennreal.coe_mul], rw [lintegral_mul_const, Lp_meas_coe], exact (Lp.strongly_measurable _).ennnorm end ... ≤ μ (s ∩ t) * ‖x‖₊ : mul_le_mul_right' (lintegral_nnnorm_condexp_L2_indicator_le_real hs hμs ht hμt) _ lemma lintegral_nnnorm_condexp_ind_smul_le (hm : m ≤ m0) (hs : measurable_set s) (hμs : μ s ≠ ∞) (x : G) [sigma_finite (μ.trim hm)] : ∫⁻ a, ‖condexp_ind_smul hm hs hμs x a‖₊ ∂μ ≤ μ s * ‖x‖₊ := begin refine lintegral_le_of_forall_fin_meas_le' hm (μ s * ‖x‖₊) _ (λ t ht hμt, _), { exact (Lp.ae_strongly_measurable _).ennnorm }, refine (set_lintegral_nnnorm_condexp_ind_smul_le hm hs hμs x ht hμt).trans _, exact mul_le_mul_right' (measure_mono (set.inter_subset_left _ _)) _ end /-- If the measure `μ.trim hm` is sigma-finite, then the conditional expectation of a measurable set with finite measure is integrable. -/ lemma integrable_condexp_ind_smul (hm : m ≤ m0) [sigma_finite (μ.trim hm)] (hs : measurable_set s) (hμs : μ s ≠ ∞) (x : G) : integrable (condexp_ind_smul hm hs hμs x) μ := begin refine integrable_of_forall_fin_meas_le' hm (μ s * ‖x‖₊) (ennreal.mul_lt_top hμs ennreal.coe_ne_top) _ _, { exact Lp.ae_strongly_measurable _, }, { refine λ t ht hμt, (set_lintegral_nnnorm_condexp_ind_smul_le hm hs hμs x ht hμt).trans _, exact mul_le_mul_right' (measure_mono (set.inter_subset_left _ _)) _, }, end lemma condexp_ind_smul_empty {x : G} : condexp_ind_smul hm measurable_set.empty ((@measure_empty _ _ μ).le.trans_lt ennreal.coe_lt_top).ne x = 0 := begin rw [condexp_ind_smul, indicator_const_empty], simp only [coe_fn_coe_base, submodule.coe_zero, continuous_linear_map.map_zero], end lemma set_integral_condexp_L2_indicator (hs : measurable_set[m] s) (ht : measurable_set t) (hμs : μ s ≠ ∞) (hμt : μ t ≠ ∞) : ∫ x in s, (condexp_L2 ℝ hm (indicator_const_Lp 2 ht hμt (1 : ℝ))) x ∂μ = (μ (t ∩ s)).to_real := calc ∫ x in s, (condexp_L2 ℝ hm (indicator_const_Lp 2 ht hμt (1 : ℝ))) x ∂μ = ∫ x in s, indicator_const_Lp 2 ht hμt (1 : ℝ) x ∂μ : @integral_condexp_L2_eq α _ ℝ _ _ _ _ _ _ _ _ _ hm (indicator_const_Lp 2 ht hμt (1 : ℝ)) hs hμs ... = (μ (t ∩ s)).to_real • 1 : set_integral_indicator_const_Lp (hm s hs) ht hμt (1 : ℝ) ... = (μ (t ∩ s)).to_real : by rw [smul_eq_mul, mul_one] lemma set_integral_condexp_ind_smul (hs : measurable_set[m] s) (ht : measurable_set t) (hμs : μ s ≠ ∞) (hμt : μ t ≠ ∞) (x : G') : ∫ a in s, (condexp_ind_smul hm ht hμt x) a ∂μ = (μ (t ∩ s)).to_real • x := calc ∫ a in s, (condexp_ind_smul hm ht hμt x) a ∂μ = (∫ a in s, (condexp_L2 ℝ hm (indicator_const_Lp 2 ht hμt (1 : ℝ)) a • x) ∂μ) : set_integral_congr_ae (hm s hs) ((condexp_ind_smul_ae_eq_smul hm ht hμt x).mono (λ x hx hxs, hx)) ... = (∫ a in s, condexp_L2 ℝ hm (indicator_const_Lp 2 ht hμt (1 : ℝ)) a ∂μ) • x : integral_smul_const _ x ... = (μ (t ∩ s)).to_real • x : by rw set_integral_condexp_L2_indicator hs ht hμs hμt lemma condexp_L2_indicator_nonneg (hm : m ≤ m0) (hs : measurable_set s) (hμs : μ s ≠ ∞) [sigma_finite (μ.trim hm)] : 0 ≤ᵐ[μ] condexp_L2 ℝ hm (indicator_const_Lp 2 hs hμs (1 : ℝ)) := begin have h : ae_strongly_measurable' m (condexp_L2 ℝ hm (indicator_const_Lp 2 hs hμs (1 : ℝ))) μ, from ae_strongly_measurable'_condexp_L2 _ _, refine eventually_le.trans_eq _ h.ae_eq_mk.symm, refine @ae_le_of_ae_le_trim _ _ _ _ _ _ hm _ _ _, refine ae_nonneg_of_forall_set_integral_nonneg_of_sigma_finite _ _, { intros t ht hμt, refine @integrable.integrable_on _ _ m _ _ _ _ _, refine integrable.trim hm _ _, { rw integrable_congr h.ae_eq_mk.symm, exact integrable_condexp_L2_indicator hm hs hμs _, }, { exact h.strongly_measurable_mk, }, }, { intros t ht hμt, rw ← set_integral_trim hm h.strongly_measurable_mk ht, have h_ae : ∀ᵐ x ∂μ, x ∈ t → h.mk _ x = condexp_L2 ℝ hm (indicator_const_Lp 2 hs hμs (1 : ℝ)) x, { filter_upwards [h.ae_eq_mk] with x hx, exact λ _, hx.symm, }, rw [set_integral_congr_ae (hm t ht) h_ae, set_integral_condexp_L2_indicator ht hs ((le_trim hm).trans_lt hμt).ne hμs], exact ennreal.to_real_nonneg, }, end lemma condexp_ind_smul_nonneg {E} [normed_lattice_add_comm_group E] [normed_space ℝ E] [ordered_smul ℝ E] [sigma_finite (μ.trim hm)] (hs : measurable_set s) (hμs : μ s ≠ ∞) (x : E) (hx : 0 ≤ x) : 0 ≤ᵐ[μ] condexp_ind_smul hm hs hμs x := begin refine eventually_le.trans_eq _ (condexp_ind_smul_ae_eq_smul hm hs hμs x).symm, filter_upwards [condexp_L2_indicator_nonneg hm hs hμs] with a ha, exact smul_nonneg ha hx, end end condexp_ind_smul end measure_theory
b949e7297f3b291bcc40135f4e62156a871bdfe0
a4673261e60b025e2c8c825dfa4ab9108246c32e
/src/Lean/Parser/Command.lean
9a29d49b4eba2f46233808388eaa9a2dc7305dab
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,552
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Parser.Term import Lean.Parser.Do namespace Lean namespace Parser /-- Syntax quotation for terms and (lists of) commands. We prefer terms, so ambiguous quotations like `($x $y) will be parsed as an application, not two commands. Use `($x:command $y:command) instead. Multiple command will be put in a `null node, but a single command will not (so that you can directly match against a quotation in a command kind's elaborator). -/ -- TODO: use two separate quotation parsers with parser priorities instead @[builtinTermParser] def Term.quot := parser! "`(" >> toggleInsideQuot (termParser <|> many1Unbox commandParser) >> ")" namespace Command def commentBody : Parser := { fn := rawFn (finishCommentBlock 1) true } @[combinatorParenthesizer Lean.Parser.Command.commentBody] def commentBody.parenthesizer := PrettyPrinter.Parenthesizer.visitToken @[combinatorFormatter Lean.Parser.Command.commentBody] def commentBody.formatter := PrettyPrinter.Formatter.visitAtom Name.anonymous def docComment := parser! ppDedent $ "/--" >> commentBody >> ppLine def «private» := parser! "private " def «protected» := parser! "protected " def visibility := «private» <|> «protected» def «noncomputable» := parser! "noncomputable " def «unsafe» := parser! "unsafe " def «partial» := parser! "partial " def declModifiers (inline : Bool) := parser! optional docComment >> optional (Term.«attributes» >> if inline then skip else ppDedent ppLine) >> optional visibility >> optional «noncomputable» >> optional «unsafe» >> optional «partial» def declId := parser! ident >> optional (".{" >> sepBy1 ident ", " >> "}") def declSig := parser! many (ppSpace >> (Term.simpleBinderWithoutType <|> Term.bracketedBinder)) >> Term.typeSpec def optDeclSig := parser! many (ppSpace >> (Term.simpleBinderWithoutType <|> Term.bracketedBinder)) >> Term.optType def declValSimple := parser! " :=\n" >> termParser >> optional Term.whereDecls def declValEqns := parser! Term.matchAltsWhereDecls def declVal := declValSimple <|> declValEqns <|> Term.whereDecls def «abbrev» := parser! "abbrev " >> declId >> optDeclSig >> declVal def «def» := parser! "def " >> declId >> optDeclSig >> declVal def «theorem» := parser! "theorem " >> declId >> declSig >> declVal def «constant» := parser! "constant " >> declId >> declSig >> optional declValSimple def «instance» := parser! "instance " >> optional declId >> declSig >> declVal def «axiom» := parser! "axiom " >> declId >> declSig def «example» := parser! "example " >> declSig >> declVal def inferMod := parser! atomic ("{" >> "}") def ctor := parser! "\n| " >> declModifiers true >> ident >> optional inferMod >> optDeclSig def «inductive» := parser! "inductive " >> declId >> optDeclSig >> optional (":=" <|> "where") >> many ctor def classInductive := parser! atomic (group ("class " >> "inductive ")) >> declId >> optDeclSig >> optional (":=" <|> "where") >> many ctor def structExplicitBinder := parser! atomic (declModifiers true >> "(") >> many1 ident >> optional inferMod >> optDeclSig >> optional Term.binderDefault >> ")" def structImplicitBinder := parser! atomic (declModifiers true >> "{") >> many1 ident >> optional inferMod >> declSig >> "}" def structInstBinder := parser! atomic (declModifiers true >> "[") >> many1 ident >> optional inferMod >> declSig >> "]" def structSimpleBinder := parser! atomic (declModifiers true >> many1 ident) >> optional inferMod >> optDeclSig >> optional Term.binderDefault def structFields := parser! manyIndent (ppLine >> checkColGe >>(structExplicitBinder <|> structImplicitBinder <|> structInstBinder <|> structSimpleBinder)) def structCtor := parser! atomic (declModifiers true >> ident >> optional inferMod >> " :: ") def structureTk := parser! "structure " def classTk := parser! "class " def «extends» := parser! " extends " >> sepBy1 termParser ", " def «structure» := parser! (structureTk <|> classTk) >> declId >> many Term.bracketedBinder >> optional «extends» >> Term.optType >> optional ((" := " <|> " where ") >> optional structCtor >> structFields) @[builtinCommandParser] def declaration := parser! declModifiers false >> («abbrev» <|> «def» <|> «theorem» <|> «constant» <|> «instance» <|> «axiom» <|> «example» <|> «inductive» <|> classInductive <|> «structure») @[builtinCommandParser] def «section» := parser! "section " >> optional ident @[builtinCommandParser] def «namespace» := parser! "namespace " >> ident @[builtinCommandParser] def «end» := parser! "end " >> optional ident @[builtinCommandParser] def «variable» := parser! "variable" >> Term.bracketedBinder @[builtinCommandParser] def «variables» := parser! "variables" >> many1 Term.bracketedBinder @[builtinCommandParser] def «universe» := parser! "universe " >> ident @[builtinCommandParser] def «universes» := parser! "universes " >> many1 ident @[builtinCommandParser] def check := parser! "#check " >> termParser @[builtinCommandParser] def check_failure := parser! "#check_failure " >> termParser -- Like `#check`, but succeeds only if term does not type check @[builtinCommandParser] def eval := parser! "#eval " >> termParser @[builtinCommandParser] def synth := parser! "#synth " >> termParser @[builtinCommandParser] def exit := parser! "#exit" @[builtinCommandParser] def print := parser! "#print " >> (ident <|> strLit) @[builtinCommandParser] def printAxioms := parser! "#print " >> nonReservedSymbol "axioms " >> ident @[builtinCommandParser] def «resolve_name» := parser! "#resolve_name " >> ident @[builtinCommandParser] def «init_quot» := parser! "init_quot" @[builtinCommandParser] def «set_option» := parser! "set_option " >> ident >> (nonReservedSymbol "true" <|> nonReservedSymbol "false" <|> strLit <|> numLit) @[builtinCommandParser] def «attribute» := parser! optional "local " >> "attribute " >> "[" >> sepBy1 Term.attrInstance ", " >> "] " >> many1 ident @[builtinCommandParser] def «export» := parser! "export " >> ident >> "(" >> many1 ident >> ")" def openHiding := parser! atomic (ident >> "hiding") >> many1 ident def openRenamingItem := parser! ident >> unicodeSymbol "→" "->" >> ident def openRenaming := parser! atomic (ident >> "renaming") >> sepBy1 openRenamingItem ", " def openOnly := parser! atomic (ident >> "(") >> many1 ident >> ")" def openSimple := parser! many1 ident @[builtinCommandParser] def «open» := parser! "open " >> (openHiding <|> openRenaming <|> openOnly <|> openSimple) @[builtinCommandParser] def «mutual» := parser! "mutual " >> many1 (notSymbol "end" >> commandParser) >> "end" @[builtinCommandParser] def «initialize» := parser! "initialize " >> optional (atomic (ident >> Term.typeSpec >> Term.leftArrow)) >> Term.doSeq @[builtinCommandParser] def «builtin_initialize» := parser! "builtin_initialize " >> optional (atomic (ident >> Term.typeSpec >> Term.leftArrow)) >> Term.doSeq @[builtinCommandParser] def «in» := tparser! " in " >> commandParser end Command end Parser end Lean
b2b3865c99cc226e551e438c7f851c4e1618231c
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/linear_ordered_comm_group_with_zero.lean
236ed476f8f1cefcd7c888901e265b4c6864d11c
[ "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
9,153
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Johan Commelin, Patrick Massot -/ import algebra.ordered_group import algebra.group_with_zero import algebra.group_with_zero.power import tactic.abel /-! # Linearly ordered commutative groups and monoids with a zero element adjoined This file sets up a special class of linearly ordered commutative monoids that show up as the target of so-called “valuations” in algebraic number theory. Usually, in the informal literature, these objects are constructed by taking a linearly ordered commutative group Γ and formally adjoining a zero element: Γ ∪ {0}. The disadvantage is that a type such as `nnreal` is not of that form, whereas it is a very common target for valuations. The solutions is to use a typeclass, and that is exactly what we do in this file. Note that to avoid issues with import cycles, `linear_ordered_comm_monoid_with_zero` is defined in another file. However, the lemmas about it are stated here. -/ set_option old_structure_cmd true /-- A linearly ordered commutative group with a zero element. -/ class linear_ordered_comm_group_with_zero (α : Type*) extends linear_ordered_comm_monoid_with_zero α, comm_group_with_zero α variables {α : Type*} variables {a b c d x y z : α} instance [linear_ordered_add_comm_monoid_with_top α] : linear_ordered_comm_monoid_with_zero (multiplicative (order_dual α)) := { zero := multiplicative.of_add (⊤ : α), zero_mul := top_add, mul_zero := add_top, zero_le_one := (le_top : (0 : α) ≤ ⊤), ..multiplicative.ordered_comm_monoid, ..multiplicative.linear_order } instance [linear_ordered_add_comm_group_with_top α] : linear_ordered_comm_group_with_zero (multiplicative (order_dual α)) := { inv_zero := linear_ordered_add_comm_group_with_top.neg_top, mul_inv_cancel := linear_ordered_add_comm_group_with_top.add_neg_cancel, ..multiplicative.div_inv_monoid, ..multiplicative.linear_ordered_comm_monoid_with_zero, ..multiplicative.nontrivial } section linear_ordered_comm_monoid variables [linear_ordered_comm_monoid_with_zero α] /- The following facts are true more generally in a (linearly) ordered commutative monoid. -/ /-- Pullback a `linear_ordered_comm_monoid_with_zero` under an injective map. See note [reducible non-instances]. -/ @[reducible] def function.injective.linear_ordered_comm_monoid_with_zero {β : Type*} [has_zero β] [has_one β] [has_mul β] (f : β → α) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) : linear_ordered_comm_monoid_with_zero β := { zero_le_one := show f 0 ≤ f 1, by simp only [zero, one, linear_ordered_comm_monoid_with_zero.zero_le_one], ..linear_order.lift f hf, ..hf.ordered_comm_monoid f one mul, ..hf.comm_monoid_with_zero f zero one mul } lemma one_le_pow_of_one_le' {n : ℕ} (H : 1 ≤ x) : 1 ≤ x^n := begin induction n with n ih, { rw pow_zero }, { rw pow_succ, exact one_le_mul H ih } end lemma pow_le_one_of_le_one {n : ℕ} (H : x ≤ 1) : x^n ≤ 1 := begin induction n with n ih, { rw pow_zero }, { rw pow_succ, exact mul_le_one' H ih } end lemma eq_one_of_pow_eq_one {n : ℕ} (hn : n ≠ 0) (H : x ^ n = 1) : x = 1 := begin rcases nat.exists_eq_succ_of_ne_zero hn with ⟨n, rfl⟩, clear hn, induction n with n ih, { simpa using H }, { cases le_total x 1 with h, all_goals { have h1 := mul_le_mul_right' h (x ^ (n + 1)), rw pow_succ at H, rw [H, one_mul] at h1 }, { have h2 := pow_le_one_of_le_one h, exact ih (le_antisymm h2 h1) }, { have h2 := one_le_pow_of_one_le' h, exact ih (le_antisymm h1 h2) } } end lemma pow_eq_one_iff {n : ℕ} (hn : n ≠ 0) : x ^ n = 1 ↔ x = 1 := ⟨eq_one_of_pow_eq_one hn, by { rintro rfl, exact one_pow _ }⟩ lemma one_le_pow_iff {n : ℕ} (hn : n ≠ 0) : 1 ≤ x^n ↔ 1 ≤ x := begin refine ⟨_, one_le_pow_of_one_le'⟩, contrapose!, intro h, apply lt_of_le_of_ne (pow_le_one_of_le_one (le_of_lt h)), rw [ne.def, pow_eq_one_iff hn], exact ne_of_lt h, end lemma pow_le_one_iff {n : ℕ} (hn : n ≠ 0) : x^n ≤ 1 ↔ x ≤ 1 := begin refine ⟨_, pow_le_one_of_le_one⟩, contrapose!, intro h, apply lt_of_le_of_ne (one_le_pow_of_one_le' (le_of_lt h)), rw [ne.def, eq_comm, pow_eq_one_iff hn], exact ne_of_gt h, end lemma zero_le_one' : (0 : α) ≤ 1 := linear_ordered_comm_monoid_with_zero.zero_le_one @[simp] lemma zero_le' : 0 ≤ a := by simpa only [mul_zero, mul_one] using mul_le_mul_left' (@zero_le_one' α _) a @[simp] lemma not_lt_zero' : ¬a < 0 := not_lt_of_le zero_le' @[simp] lemma le_zero_iff : a ≤ 0 ↔ a = 0 := ⟨λ h, le_antisymm h zero_le', λ h, h ▸ le_refl _⟩ lemma zero_lt_iff : 0 < a ↔ a ≠ 0 := ⟨ne_of_gt, λ h, lt_of_le_of_ne zero_le' h.symm⟩ lemma ne_zero_of_lt (h : b < a) : a ≠ 0 := λ h1, not_lt_zero' $ show b < 0, from h1 ▸ h lemma pow_pos_iff [no_zero_divisors α] {n : ℕ} (hn : 0 < n) : 0 < a ^ n ↔ 0 < a := by simp_rw [zero_lt_iff, pow_ne_zero_iff hn] instance : linear_ordered_add_comm_monoid_with_top (additive (order_dual α)) := { top := (0 : α), top_add' := λ a, (zero_mul a : (0 : α) * a = 0), le_top := λ _, zero_le', ..additive.ordered_add_comm_monoid, ..additive.linear_order } end linear_ordered_comm_monoid variables [linear_ordered_comm_group_with_zero α] lemma zero_lt_one'' : (0 : α) < 1 := lt_of_le_of_ne zero_le_one' zero_ne_one lemma le_of_le_mul_right (h : c ≠ 0) (hab : a * c ≤ b * c) : a ≤ b := by simpa only [mul_inv_cancel_right' h] using (mul_le_mul_right' hab c⁻¹) lemma le_mul_inv_of_mul_le (h : c ≠ 0) (hab : a * c ≤ b) : a ≤ b * c⁻¹ := le_of_le_mul_right h (by simpa [h] using hab) lemma mul_inv_le_of_le_mul (h : c ≠ 0) (hab : a ≤ b * c) : a * c⁻¹ ≤ b := le_of_le_mul_right h (by simpa [h] using hab) lemma div_le_div' (a b c d : α) (hb : b ≠ 0) (hd : d ≠ 0) : a * b⁻¹ ≤ c * d⁻¹ ↔ a * d ≤ c * b := if ha : a = 0 then by simp [ha] else if hc : c = 0 then by simp [inv_ne_zero hb, hc, hd] else show (units.mk0 a ha) * (units.mk0 b hb)⁻¹ ≤ (units.mk0 c hc) * (units.mk0 d hd)⁻¹ ↔ (units.mk0 a ha) * (units.mk0 d hd) ≤ (units.mk0 c hc) * (units.mk0 b hb), from mul_inv_le_mul_inv_iff' @[simp] lemma units.zero_lt (u : units α) : (0 : α) < u := zero_lt_iff.2 $ u.ne_zero lemma mul_lt_mul'''' (hab : a < b) (hcd : c < d) : a * c < b * d := have hb : b ≠ 0 := ne_zero_of_lt hab, have hd : d ≠ 0 := ne_zero_of_lt hcd, if ha : a = 0 then by { rw [ha, zero_mul, zero_lt_iff], exact mul_ne_zero hb hd } else if hc : c = 0 then by { rw [hc, mul_zero, zero_lt_iff], exact mul_ne_zero hb hd } else show (units.mk0 a ha) * (units.mk0 c hc) < (units.mk0 b hb) * (units.mk0 d hd), from mul_lt_mul''' hab hcd lemma mul_inv_lt_of_lt_mul' (h : x < y * z) : x * z⁻¹ < y := have hz : z ≠ 0 := (mul_ne_zero_iff.1 $ ne_zero_of_lt h).2, by { contrapose! h, simpa only [inv_inv'] using mul_inv_le_of_le_mul (inv_ne_zero hz) h } lemma mul_lt_right' (c : α) (h : a < b) (hc : c ≠ 0) : a * c < b * c := by { contrapose! h, exact le_of_le_mul_right hc h } lemma pow_lt_pow_succ {x : α} {n : ℕ} (hx : 1 < x) : x ^ n < x ^ n.succ := by { rw [← one_mul (x ^ n), pow_succ], exact mul_lt_right' _ hx (pow_ne_zero _ $ ne_of_gt (lt_trans zero_lt_one'' hx)) } lemma pow_lt_pow' {x : α} {m n : ℕ} (hx : 1 < x) (hmn : m < n) : x ^ m < x ^ n := by { induction hmn with n hmn ih, exacts [pow_lt_pow_succ hx, lt_trans ih (pow_lt_pow_succ hx)] } lemma inv_lt_inv'' (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ < b⁻¹ ↔ b < a := show (units.mk0 a ha)⁻¹ < (units.mk0 b hb)⁻¹ ↔ (units.mk0 b hb) < (units.mk0 a ha), from inv_lt_inv_iff lemma inv_le_inv'' (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := show (units.mk0 a ha)⁻¹ ≤ (units.mk0 b hb)⁻¹ ↔ (units.mk0 b hb) ≤ (units.mk0 a ha), from inv_le_inv_iff instance : linear_ordered_add_comm_group_with_top (additive (order_dual α)) := { neg_top := inv_zero, add_neg_cancel := λ a ha, mul_inv_cancel ha, ..additive.sub_neg_monoid, ..additive.linear_ordered_add_comm_monoid_with_top, ..additive.nontrivial } namespace monoid_hom variables {R : Type*} [ring R] (f : R →* α) theorem map_neg_one : f (-1) = 1 := eq_one_of_pow_eq_one (nat.succ_ne_zero 1) $ calc f (-1) ^ 2 = f (-1) * f(-1) : sq _ ... = f ((-1) * - 1) : (f.map_mul _ _).symm ... = f ( - - 1) : congr_arg _ (neg_one_mul _) ... = f 1 : congr_arg _ (neg_neg _) ... = 1 : map_one f @[simp] lemma map_neg (x : R) : f (-x) = f x := calc f (-x) = f (-1 * x) : congr_arg _ (neg_one_mul _).symm ... = f (-1) * f x : map_mul _ _ _ ... = 1 * f x : _root_.congr_arg (λ g, g * (f x)) (map_neg_one f) ... = f x : one_mul _ lemma map_sub_swap (x y : R) : f (x - y) = f (y - x) := calc f (x - y) = f (-(y - x)) : congr_arg _ (neg_sub _ _).symm ... = _ : map_neg _ _ end monoid_hom
09fc8c0414879df08a160063eb62cd3c15180427
cb1829c15cd3d28210f93507f96dfb1f56ec0128
/theorem_proving/02-dependent_types_part1.lean
f3f2dc13cd900be3e60fc5bf92299002ae8f07dd
[]
no_license
williamdemeo/LEAN_wjd
69f9f76e35092b89e4479a320be2fa3c18aed6fe
13826c75c06ef435166a26a72e76fe984c15bad7
refs/heads/master
1,609,516,630,137
1,518,123,893,000
1,518,123,893,000
97,740,278
2
0
null
null
null
null
UTF-8
Lean
false
false
19,183
lean
-- Chapter 2. Dependent Type Theory #print "------------------------------------------------" #print "Section 2.1 Simple Type Theory" -- page 10 ------------------------------------------ /- declare some constants -/ constant m : nat -- m is a natural number constant n : nat -- page 11 ------------------------------------------ constants b1 b2 : bool -- declare two constants at once (notice the plural) /- check their types -/ #check m -- m : ℕ #check n #check n + 0 #check m * (n+0) #check b1 #check b1 && b2 -- b1 && b2 : bool #check b1 || b2 #check tt -- tt : bool (i.e., boolean true) -- #check b1 + tt -- b1 + tt : bool (actually it's a type error) constant f : nat → nat -- type the arrow using `\to` or `\r` constant f' : nat -> nat -- alternative ASCII notation constant f'' : ℕ → ℕ -- `\nat` is alternative notation for `nat` constant p : ℕ × ℕ -- type the product using `\times` constant q : prod nat nat -- alternative notation constant g : ℕ → ℕ → ℕ constant g' : nat -> (nat -> nat) -- has the same type as g! constant g'' : nat × nat -> nat -- not the same type as g constant F : (nat -> nat) -> nat -- a "functional" #check f #check f n #check g m #check g m n #check (m, n) #check F #check F f #check p.1 #check p.1 #check (m, n).1 #check (p, n) #check (p.1, n) #check (n, f) #check F (n, f).2 -- (output) F((n, f).snd) : ℕ /- Section 2.1 output of type-check results m : ℕ n : ℕ n + 0 : ℕ m * (n + 0) : ℕ b1 : bool b1 && b2 : bool b1 || b2 : bool tt : bool f : ℕ → ℕ f n : ℕ g m : ℕ → ℕ g m n : ℕ (m, n) : ℕ × ℕ F : (ℕ → ℕ) → ℕ F f : ℕ p.fst : ℕ p.fst : ℕ (m, n).fst : ℕ (p, n) : (ℕ × ℕ) × ℕ (p.fst, n) : ℕ × ℕ (n, f) : ℕ × (ℕ → ℕ) F ((n, f).snd) : ℕ -/ #print "------------------------------------------------" #print "Section 2.2 Types as Objects" -- page 12 #check nat -- ℕ : Type #check bool -- bool : Type #check nat -> bool #check nat -> (nat -> nat) #check list -- list : Type u_1 → Type u_1 #check prod -- prod : Type u_1 → Type u_2 → Type(max u_1 u_2) -- page 13 constants α β : Type constant H : Type → Type constants G : Type → Type → Type #check α #check H α #check H nat #check G α #check G α β #check G α nat #check list α -- Types of types #check Type -- Type : Type 1 #check Type 0 -- Type : Type 1 #check Type 1 -- Type 1 : Type 2 #check Type 2 -- Type 2 : Type 3 #check Type 3 -- etc. #check Type 4 namespace page14 #check Prop -- Prop : Type -- Polymorphism /- To define polymorphic constants and variables, Lean allows us to declare universe variables explicitly: -/ universe u constant γ : Type u #check γ end page14 -- (page 8 of new edition) /- The ability to treat type constructors as instances of ordinary mathematical functions is a powerful feature of dependent type theory. -/ /- Section 2.2 output of type-check results ℕ : Type bool : Type ℕ → bool : Type ℕ → ℕ → ℕ : Type list : Type u_1 → Type u_1 prod : Type u_1 → Type u_2 → Type (max u_1 u_2) α : Type H α : Type H ℕ : Type G α : Type → Type G α β : Type G α ℕ : Type list α : Type Type : Type 1 Type : Type 1 Type 1 : Type 2 Type 2 : Type 3 Type 3 : Type 4 Type 4 : Type 5 Prop : Type γ : Type u_1 -/ #print "------------------------------------------------" #print "Section 2.3. Function Abstraction and Evaluation" -- page 15 (lambda abstraction) (page 8 in new edition) namespace page15 #check fun x : nat, x + 5 #check λ x : ℕ, x + 5 constants α β : Type constants a1 a2 : α constants b1 b2 : β constant f : α → α constant g : α → β constant h : α → β → α constant p : α → α → bool #check fun x : α, f x #check λ x : α, f x #check λ x : α, f (f x) end page15 namespace page16 -- (page 9 in new edition) constants α β γ : Type constant f : α → β constant g : β → γ constant b : β #check λ x : α, x #check λ x : α, b #check λ x : α, g (f x) #check λ x, g (f x) -- We can abstract over any of the constants in the previous definitions. #check λ b : β, λ x : α, x -- β → α → α #check λ (b : β) (x : α), x -- β → α → α (same as previous line) #check λ (g : α → β) (f : β → γ) (x : α), f (g x) -- We can even abstract over the type. #check λ (α β : Type) (b : β) (x : α), x #check λ (α β γ : Type) (g: α → β) (f: β → γ) (x: α), f (g x) /- the last expression has "pi-type" Π (α β γ : Type) (α → β) → (β → γ) → α → γ which is the type that, for all types α, β, γ, takes maps of types α → β and β → γ, and returns their composition (a map of type α → γ) -/ end page16 namespace page17 -- (page 10 of new edition) constants α β γ : Type constant f : α → β constant g : β → γ constant h : α → α constants (a : α) (b : β) #check (λ x : α, x) a -- α #check (λ x : α, b) a -- β #check (λ x : α, b) (h a) -- β #check (λ x : α, g (f x)) (h (h a)) -- γ #check (λ (v : β → γ) (u : α → β) x, v (u x)) g f a -- γ #check (λ (Q R S : Type) (v : R → S) (u: Q → R) (x : Q), v (u x)) α β γ g f a -- γ -- `#reduce` tells Lean to evaluate an expression by reducing to normal form. #reduce (λ x : α, x) a -- a #reduce (λ x : α, b) a -- b #reduce (λ x : α, b) (h a) -- b #reduce (λ x : α, g (f x)) (h (h a)) -- g (f (h (h a))) #reduce (λ (v : β → γ) (u : α → β) x, v (u x)) g f a -- g (f a) #reduce (λ (Q R S : Type) (v : R → S) (u: Q → R) (x : Q), v (u x)) α β γ g f a -- g (f a) -- `#reduce` carries out more than just β reductions. constants m n : nat constant s : bool #print "reducing pairs" #reduce (m, n).1 -- m #reduce (m, n).2 -- n #print "reducing boolean expressions" #reduce tt && ff -- ff #reduce s && ff -- bool.rec ff ff s #reduce ff && s -- ff #print "reducing arithmetic expressions" #reduce n + 0 #reduce n + 2 #reduce 2 + 3 end page17 /- This is an important feature of dependent type theory: every term has a computational behavior, and supports a notion of reduction, or normalization. In principle, two terms that reduce to the same value are called definitionally equal. -/ /- It is the computational behavior illustrated above that makes it possible to use Lean as a programming language as well as a proof assistant. Lean extracts bytecode from terms in a computationally pure fragment of the logical framework, and can evaluate them quite efficiently. -/ #eval 12345 * 54321 /- In contrast, the #reduce command relies on Lean's trusted kernel, the part of Lean that is responsible for checking and verifying the correctness of expressions and proofs. As such, the `#reduce` command is more trustworthy, but far less efficient. -/ /- Section 2.3 output λ (x : ℕ), x + 5 : ℕ → ℕ λ (x : ℕ), x + 5 : ℕ → ℕ λ (x : α), f x : α → α λ (x : α), f x : α → α λ (x : α), f (f x) : α → α λ (x : α), x : α → α λ (x : α), b : α → β λ (x : α), g (f x) : α → γ λ (x : α), g (f x) : α → γ λ (b : β) (x : α), x : β → α → α λ (b : β) (x : α), x : β → α → α λ (g : α → β) (f : β → γ) (x : α), f (g x) : (α → β) → (β → γ) → α → γ λ (α β : Type) (b : β) (x : α), x : Π (α β : Type), β → α → α λ (α β γ : Type) (g : α → β) (f : β → γ) (x : α), f (g x) : Π (α β γ : Type), (α → β) → (β → γ) → α → γ (λ (x : α), x) a : α (λ (x : α), b) a : β (λ (x : α), b) (h a) : β (λ (x : α), g (f x)) (h (h a)) : γ (λ (v : β → γ) (u : α → β) (x : α), v (u x)) g f a : γ (λ (Q R S : Type) (v : R → S) (u : Q → R) (x : Q), v (u x)) α β γ g f a : γ a b b g (f (h (h a))) g (f a) g (f a) reducing pairs m n reducing boolean expressions ff bool.rec ff ff s ff reducing arithmetic expressions n nat.succ (nat.succ n) 5 670592745 -/ #print "------------------------------------------------" #print "Section 2.4. Introducing Definitions" /- Declaring constants is a good way to postulate new objects to experiment with. But most of the time we want to define objects in Lean and prove things about them. The definition command provides one important way of defining new objects. -/ namespace page18 definition foo : (ℕ → ℕ) → ℕ := λ f, f 0 #check foo #print foo #reduce foo (λ x : ℕ, x * 2) end page18 /- We can use a shorthand `def` and an alternative format that puts the abstracted variables before the colon and odmits the lambda. -/ namespace page19 def double (x : ℕ) : ℕ := x + x #check double -- ℕ → ℕ #print double #reduce double 3 -- 6 def square (x : ℕ) := x*x #check square -- ℕ → ℕ #print square #reduce square 3 -- 9 def do_twice (f : ℕ → ℕ) (x : ℕ) := f (f x) #reduce do_twice double 2 -- 8 -- we could have defined the last three terms thus: def double_alt : ℕ → ℕ := λ x, x + x def square_alt : ℕ → ℕ := λ x, x*x def do_twice_alt : (ℕ → ℕ) → ℕ → ℕ := λ (f: ℕ → ℕ) (x: ℕ), f (f x) #check do_twice_alt #print do_twice_alt #reduce do_twice_alt double_alt 2 /- As an exercise, we encourage you to use do_twice and double to define functions that quadruple their input, and multiply the input by 8. -/ def quadruple : ℕ → ℕ := do_twice double #check quadruple #reduce quadruple 2 def mult_by_eight := λ x, (do_twice double 2) * x #check mult_by_eight #reduce mult_by_eight 4 /- As a further exercise, we encourage you to try defining a function Do_Twice : ((N → N) → (N → N)) → (N → N) → (N → N) which applies its argument twice, so that `Do_Twice do_twice` is a function that iterates its input four times. -/ def Do_Twice : ((ℕ → ℕ) → (ℕ → ℕ)) → (ℕ → ℕ) → (ℕ → ℕ) := λ (F : (ℕ → ℕ) → (ℕ → ℕ)) (f: ℕ → ℕ), F (F f) def Four_Times : (ℕ → ℕ) → ℕ → ℕ := Do_Twice do_twice -- Finally, evaluate `Do_Twice do_twice double 2`. #reduce Four_Times double 2 -- 32 /- As another exercise, we encourage you to complete the following definitions, which "curry" and "uncurry" a function. -/ def curry (α β γ : Type) (f : α × β → γ) : α → β → γ := λ (x : α) (y : β), f (x, y) def uncurry (α β γ : Type) (f : α → β → γ) : α × β → γ := λ (p : α × β), f p.1 p.2 end page19 /- Section 2.4. output: foo : (ℕ → ℕ) → ℕ def page18.foo : (ℕ → ℕ) → ℕ := λ (f : ℕ → ℕ), f 0 0 double : ℕ → ℕ def page19.double : ℕ → ℕ := λ (x : ℕ), x + x 6 square : ℕ → ℕ def page19.square : ℕ → ℕ := λ (x : ℕ), x * x 9 8 do_twice_alt : (ℕ → ℕ) → ℕ → ℕ def page19.do_twice_alt : (ℕ → ℕ) → ℕ → ℕ := λ (f : ℕ → ℕ) (x : ℕ), f (f x) 8 quadruple : ℕ → ℕ 8 mult_by_eight : ℕ → ℕ 32 32 -/ #print "------------------------------------------------" #print "Section 2.5. Local Definitions" -- Lean allows you to introduce "local" definitions using the let construct. /- The expression let `a := t1 in t2` is definitionally equal to the result of replacing every occurrence of `a` in `t2` by `t1`. -/ namespace page20 #check let y := 2 + 2 in y * y -- ℕ #reduce let y := 2 + 2 in y * y -- 16 def t (x : ℕ) : ℕ := let y := x + x in y * y #reduce t 2 -- 16 end page20 #print "------------------------------------------------" #print "Section 2.6. Variables and Sections" -- some organizational features of Lean (not part of axiomatic framework per se) /- Recall, the `constant` command allows us to declare new objects, which then become part of the global context. This can be somewhat dangerous since declaring a new constant is tantamount to declaring an axiomatic extension of our foundational system, and may result in inconsistency. This can be avoided, using implicit or explicit lambda abstraction in our definitions to declare such objects "locally". -/ namespace page21 -- (page 13 in new edition) def compose (α β γ : Type) (g : β → γ) (f : α → β) (x : α) : γ := g (f x) def do_twice (α : Type) (h : α → α) (x : α) : α := h (h x) /- Repeating declarations in this way can be tedious, however. Lean provides us with the `variable` and `variables` commands to make such declarations look global: -/ variables (α β γ : Type) def compose_alt (g : β → γ) (f : α → β) (x : α) : γ := g (f x) end page21 /- The variable and variables commands look like the constant and constants commands, but there is an important difference. Rather than creating permanent entities, the `variables` command simply instructs Lean to insert the declared variables as bound variables in definitions that refer to them. -/ /- A variable stays in scope until the end of the file we are working on, and we cannot declare another variable with the same name. To limit the scope of a variable, Lean provides the notion of a section: -/ section useful variables (α β γ : Type) variables (g : β → γ) (f : α → β) (h: α → α) variable x : α def compose := g (f x) def do_twice := h (h x) end useful #print "------------------------------------------------" #print "Section 2.7 Namespaces" /- Lean provides us with the ability to group definitions, notation, and other information into nested, hierarchical namespaces. -/ namespace fu def a : ℕ :=5 def f (x : ℕ) : ℕ := x+7 def fa : ℕ := f a def ffa : ℕ := f (f a) #print "inside fu" #check a #check f #check fa #check ffa #check fu.fa end fu #print "outside the fu namespace" -- #check a -- error -- #check f -- error #check fu.a #check fu.ffa open fu #print "opened fu" #check a -- #check f -- still an error because ambiguous (f was also defined above) #check fu.f #check ffa /- The `open` command brings the shorter names into the current context. Often, when we import a theory file, we will want to open one or more of the namespaces it contains, to have access to the short identifiers, notations, and so on. But sometimes we will want to leave this information hidden, for example, when they conflict with identifiers and notations in another namespace we want to use. Thus namespaces give us a way to manage our working environment. -/ -- Lean groups definitions and theorems involving lists into a namespace `list`. #check list.nil #check list.cons #check list.append open list #check nil #check cons #check append -- like sections, namespaces can be nested namespace page24 namespace pre def a : ℕ := 5 def f (x : ℕ) : ℕ := x+7 end pre namespace top def fa : ℕ := pre.f a namespace bar def ffa : ℕ := pre.f (pre.f a) #check fa #check ffa end bar #check fa #check bar.ffa end top end page24 -- Namespaces that have been closed can later be reopened, even in another file. namespace page24 def b : ℕ := 5 end page24 /- Namespaces and sections serve different purposes: namespaces organize data and sections declare variables for insertion in theorems. -/ /- Section 2.7. output: inside fu a : ℕ f : ℕ → ℕ fa : ℕ ffa : ℕ fa : ℕ outside the fu namespace fu.a : ℕ fu.ffa : ℕ opened fu a : ℕ f : ℕ → ℕ ffa : ℕ list.nil : list ?M_1 list.cons : ?M_1 → list ?M_1 → list ?M_1 list.append : list ?M_1 → list ?M_1 → list ?M_1 nil : list ?M_1 cons : ?M_1 → list ?M_1 → list ?M_1 append : ?M_1 → ?M_1 → ?M_1 fa : ℕ ffa : ℕ fa : ℕ bar.ffa : ℕ -/
e3fe9df8b3291f9cf730249ad19197ae6fa23925
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/matrix/basic.lean
649ceb76e903c592fbbdac9cac4a51c4e10c0685
[ "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
80,273
lean
/- Copyright (c) 2018 Ellen Arlt. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ellen Arlt, Blair Shi, Sean Leather, Mario Carneiro, Johan Commelin, Lu-Ming Zhang -/ import algebra.algebra.basic import algebra.big_operators.pi import algebra.big_operators.ring import algebra.big_operators.ring_equiv import algebra.module.linear_map import algebra.module.pi import algebra.star.big_operators import algebra.star.module import algebra.star.pi import data.fintype.big_operators /-! # Matrices This file defines basic properties of matrices. Matrices with rows indexed by `m`, columns indexed by `n`, and entries of type `α` are represented with `matrix m n α`. For the typical approach of counting rows and columns, `matrix (fin m) (fin n) α` can be used. ## Notation The locale `matrix` gives the following notation: * `⬝ᵥ` for `matrix.dot_product` * `⬝` for `matrix.mul` * `ᵀ` for `matrix.transpose` * `ᴴ` for `matrix.conj_transpose` ## Implementation notes For convenience, `matrix m n α` is defined as `m → n → α`, as this allows elements of the matrix to be accessed with `A i j`. However, it is not advisable to _construct_ matrices using terms of the form `λ i j, _` or even `(λ i j, _ : matrix m n α)`, as these are not recognized by lean as having the right type. Instead, `matrix.of` should be used. ## TODO Under various conditions, multiplication of infinite matrices makes sense. These have not yet been implemented. -/ universes u u' v w open_locale big_operators /-- `matrix m n R` is the type of matrices with entries in `R`, whose rows are indexed by `m` and whose columns are indexed by `n`. -/ def matrix (m : Type u) (n : Type u') (α : Type v) : Type (max u u' v) := m → n → α variables {l m n o : Type*} {m' : o → Type*} {n' : o → Type*} variables {R : Type*} {S : Type*} {α : Type v} {β : Type w} {γ : Type*} namespace matrix section ext variables {M N : matrix m n α} theorem ext_iff : (∀ i j, M i j = N i j) ↔ M = N := ⟨λ h, funext $ λ i, funext $ h i, λ h, by simp [h]⟩ @[ext] theorem ext : (∀ i j, M i j = N i j) → M = N := ext_iff.mp end ext /-- Cast a function into a matrix. The two sides of the equivalence are definitionally equal types. We want to use an explicit cast to distinguish the types because `matrix` has different instances to pi types (such as `pi.has_mul`, which performs elementwise multiplication, vs `matrix.has_mul`). If you are defining a matrix, in terms of its entries, either use `of (λ i j, _)`, or use pattern matching in a definition as `| i j := _` (which can only be unfolded when fully-applied). The purpose of this approach is to ensure that terms of the form `(λ i j, _) * (λ i j, _)` do not appear, as the type of `*` can be misleading. -/ def of : (m → n → α) ≃ matrix m n α := equiv.refl _ @[simp] lemma of_apply (f : m → n → α) (i j) : of f i j = f i j := rfl @[simp] lemma of_symm_apply (f : matrix m n α) (i j) : of.symm f i j = f i j := rfl /-- `M.map f` is the matrix obtained by applying `f` to each entry of the matrix `M`. This is available in bundled forms as: * `add_monoid_hom.map_matrix` * `linear_map.map_matrix` * `ring_hom.map_matrix` * `alg_hom.map_matrix` * `equiv.map_matrix` * `add_equiv.map_matrix` * `linear_equiv.map_matrix` * `ring_equiv.map_matrix` * `alg_equiv.map_matrix` -/ def map (M : matrix m n α) (f : α → β) : matrix m n β := of (λ i j, f (M i j)) @[simp] lemma map_apply {M : matrix m n α} {f : α → β} {i : m} {j : n} : M.map f i j = f (M i j) := rfl @[simp] lemma map_id (M : matrix m n α) : M.map id = M := by { ext, refl, } @[simp] lemma map_map {M : matrix m n α} {β γ : Type*} {f : α → β} {g : β → γ} : (M.map f).map g = M.map (g ∘ f) := by { ext, refl, } lemma map_injective {f : α → β} (hf : function.injective f) : function.injective (λ M : matrix m n α, M.map f) := λ M N h, ext $ λ i j, hf $ ext_iff.mpr h i j /-- The transpose of a matrix. -/ def transpose (M : matrix m n α) : matrix n m α | x y := M y x localized "postfix (name := matrix.transpose) `ᵀ`:1500 := matrix.transpose" in matrix /-- The conjugate transpose of a matrix defined in term of `star`. -/ def conj_transpose [has_star α] (M : matrix m n α) : matrix n m α := M.transpose.map star localized "postfix (name := matrix.conj_transpose) `ᴴ`:1500 := matrix.conj_transpose" in matrix /-- `matrix.col u` is the column matrix whose entries are given by `u`. -/ def col (w : m → α) : matrix m unit α | x y := w x /-- `matrix.row u` is the row matrix whose entries are given by `u`. -/ def row (v : n → α) : matrix unit n α | x y := v y instance [inhabited α] : inhabited (matrix m n α) := pi.inhabited _ instance [has_add α] : has_add (matrix m n α) := pi.has_add instance [add_semigroup α] : add_semigroup (matrix m n α) := pi.add_semigroup instance [add_comm_semigroup α] : add_comm_semigroup (matrix m n α) := pi.add_comm_semigroup instance [has_zero α] : has_zero (matrix m n α) := pi.has_zero instance [add_zero_class α] : add_zero_class (matrix m n α) := pi.add_zero_class instance [add_monoid α] : add_monoid (matrix m n α) := pi.add_monoid instance [add_comm_monoid α] : add_comm_monoid (matrix m n α) := pi.add_comm_monoid instance [has_neg α] : has_neg (matrix m n α) := pi.has_neg instance [has_sub α] : has_sub (matrix m n α) := pi.has_sub instance [add_group α] : add_group (matrix m n α) := pi.add_group instance [add_comm_group α] : add_comm_group (matrix m n α) := pi.add_comm_group instance [unique α] : unique (matrix m n α) := pi.unique instance [subsingleton α] : subsingleton (matrix m n α) := pi.subsingleton instance [nonempty m] [nonempty n] [nontrivial α] : nontrivial (matrix m n α) := function.nontrivial instance [has_smul R α] : has_smul R (matrix m n α) := pi.has_smul instance [has_smul R α] [has_smul S α] [smul_comm_class R S α] : smul_comm_class R S (matrix m n α) := pi.smul_comm_class instance [has_smul R S] [has_smul R α] [has_smul S α] [is_scalar_tower R S α] : is_scalar_tower R S (matrix m n α) := pi.is_scalar_tower instance [has_smul R α] [has_smul Rᵐᵒᵖ α] [is_central_scalar R α] : is_central_scalar R (matrix m n α) := pi.is_central_scalar instance [monoid R] [mul_action R α] : mul_action R (matrix m n α) := pi.mul_action _ instance [monoid R] [add_monoid α] [distrib_mul_action R α] : distrib_mul_action R (matrix m n α) := pi.distrib_mul_action _ instance [semiring R] [add_comm_monoid α] [module R α] : module R (matrix m n α) := pi.module _ _ _ /-! simp-normal form pulls `of` to the outside. -/ @[simp] lemma of_zero [has_zero α] : of (0 : m → n → α) = 0 := rfl @[simp] lemma of_add_of [has_add α] (f g : m → n → α) : of f + of g = of (f + g) := rfl @[simp] lemma of_sub_of [has_sub α] (f g : m → n → α) : of f - of g = of (f - g) := rfl @[simp] lemma neg_of [has_neg α] (f : m → n → α) : -of f = of (-f) := rfl @[simp] lemma smul_of [has_smul R α] (r : R) (f : m → n → α) : r • of f = of (r • f) := rfl @[simp] protected lemma map_zero [has_zero α] [has_zero β] (f : α → β) (h : f 0 = 0) : (0 : matrix m n α).map f = 0 := by { ext, simp [h], } protected lemma map_add [has_add α] [has_add β] (f : α → β) (hf : ∀ a₁ a₂, f (a₁ + a₂) = f a₁ + f a₂) (M N : matrix m n α) : (M + N).map f = M.map f + N.map f := ext $ λ _ _, hf _ _ protected lemma map_sub [has_sub α] [has_sub β] (f : α → β) (hf : ∀ a₁ a₂, f (a₁ - a₂) = f a₁ - f a₂) (M N : matrix m n α) : (M - N).map f = M.map f - N.map f := ext $ λ _ _, hf _ _ lemma map_smul [has_smul R α] [has_smul R β] (f : α → β) (r : R) (hf : ∀ a, f (r • a) = r • f a) (M : matrix m n α) : (r • M).map f = r • (M.map f) := ext $ λ _ _, hf _ /-- The scalar action via `has_mul.to_has_smul` is transformed by the same map as the elements of the matrix, when `f` preserves multiplication. -/ lemma map_smul' [has_mul α] [has_mul β] (f : α → β) (r : α) (A : matrix n n α) (hf : ∀ a₁ a₂, f (a₁ * a₂) = f a₁ * f a₂) : (r • A).map f = f r • A.map f := ext $ λ _ _, hf _ _ /-- The scalar action via `has_mul.to_has_opposite_smul` is transformed by the same map as the elements of the matrix, when `f` preserves multiplication. -/ lemma map_op_smul' [has_mul α] [has_mul β] (f : α → β) (r : α) (A : matrix n n α) (hf : ∀ a₁ a₂, f (a₁ * a₂) = f a₁ * f a₂) : (mul_opposite.op r • A).map f = mul_opposite.op (f r) • A.map f := ext $ λ _ _, hf _ _ lemma _root_.is_smul_regular.matrix [has_smul R S] {k : R} (hk : is_smul_regular S k) : is_smul_regular (matrix m n S) k := is_smul_regular.pi $ λ _, is_smul_regular.pi $ λ _, hk lemma _root_.is_left_regular.matrix [has_mul α] {k : α} (hk : is_left_regular k) : is_smul_regular (matrix m n α) k := hk.is_smul_regular.matrix instance subsingleton_of_empty_left [is_empty m] : subsingleton (matrix m n α) := ⟨λ M N, by { ext, exact is_empty_elim i }⟩ instance subsingleton_of_empty_right [is_empty n] : subsingleton (matrix m n α) := ⟨λ M N, by { ext, exact is_empty_elim j }⟩ end matrix open_locale matrix namespace matrix section diagonal variables [decidable_eq n] /-- `diagonal d` is the square matrix such that `(diagonal d) i i = d i` and `(diagonal d) i j = 0` if `i ≠ j`. Note that bundled versions exist as: * `matrix.diagonal_add_monoid_hom` * `matrix.diagonal_linear_map` * `matrix.diagonal_ring_hom` * `matrix.diagonal_alg_hom` -/ def diagonal [has_zero α] (d : n → α) : matrix n n α | i j := if i = j then d i else 0 @[simp] theorem diagonal_apply_eq [has_zero α] (d : n → α) (i : n) : (diagonal d) i i = d i := by simp [diagonal] @[simp] theorem diagonal_apply_ne [has_zero α] (d : n → α) {i j : n} (h : i ≠ j) : (diagonal d) i j = 0 := by simp [diagonal, h] theorem diagonal_apply_ne' [has_zero α] (d : n → α) {i j : n} (h : j ≠ i) : (diagonal d) i j = 0 := diagonal_apply_ne d h.symm @[simp] theorem diagonal_eq_diagonal_iff [has_zero α] {d₁ d₂ : n → α} : diagonal d₁ = diagonal d₂ ↔ ∀ i, d₁ i = d₂ i := ⟨λ h i, by simpa using congr_arg (λ m : matrix n n α, m i i) h, λ h, by rw show d₁ = d₂, from funext h⟩ lemma diagonal_injective [has_zero α] : function.injective (diagonal : (n → α) → matrix n n α) := λ d₁ d₂ h, funext $ λ i, by simpa using matrix.ext_iff.mpr h i i @[simp] theorem diagonal_zero [has_zero α] : (diagonal (λ _, 0) : matrix n n α) = 0 := by { ext, simp [diagonal] } @[simp] lemma diagonal_transpose [has_zero α] (v : n → α) : (diagonal v)ᵀ = diagonal v := begin ext i j, by_cases h : i = j, { simp [h, transpose] }, { simp [h, transpose, diagonal_apply_ne' _ h] } end @[simp] theorem diagonal_add [add_zero_class α] (d₁ d₂ : n → α) : diagonal d₁ + diagonal d₂ = diagonal (λ i, d₁ i + d₂ i) := by ext i j; by_cases h : i = j; simp [h] @[simp] theorem diagonal_smul [monoid R] [add_monoid α] [distrib_mul_action R α] (r : R) (d : n → α) : diagonal (r • d) = r • diagonal d := by ext i j; by_cases h : i = j; simp [h] variables (n α) /-- `matrix.diagonal` as an `add_monoid_hom`. -/ @[simps] def diagonal_add_monoid_hom [add_zero_class α] : (n → α) →+ matrix n n α := { to_fun := diagonal, map_zero' := diagonal_zero, map_add' := λ x y, (diagonal_add x y).symm,} variables (R) /-- `matrix.diagonal` as a `linear_map`. -/ @[simps] def diagonal_linear_map [semiring R] [add_comm_monoid α] [module R α] : (n → α) →ₗ[R] matrix n n α := { map_smul' := diagonal_smul, .. diagonal_add_monoid_hom n α,} variables {n α R} @[simp] lemma diagonal_map [has_zero α] [has_zero β] {f : α → β} (h : f 0 = 0) {d : n → α} : (diagonal d).map f = diagonal (λ m, f (d m)) := by { ext, simp only [diagonal, map_apply], split_ifs; simp [h], } @[simp] lemma diagonal_conj_transpose [add_monoid α] [star_add_monoid α] (v : n → α) : (diagonal v)ᴴ = diagonal (star v) := begin rw [conj_transpose, diagonal_transpose, diagonal_map (star_zero _)], refl, end section one variables [has_zero α] [has_one α] instance : has_one (matrix n n α) := ⟨diagonal (λ _, 1)⟩ @[simp] theorem diagonal_one : (diagonal (λ _, 1) : matrix n n α) = 1 := rfl theorem one_apply {i j} : (1 : matrix n n α) i j = if i = j then 1 else 0 := rfl @[simp] theorem one_apply_eq (i) : (1 : matrix n n α) i i = 1 := diagonal_apply_eq _ i @[simp] theorem one_apply_ne {i j} : i ≠ j → (1 : matrix n n α) i j = 0 := diagonal_apply_ne _ theorem one_apply_ne' {i j} : j ≠ i → (1 : matrix n n α) i j = 0 := diagonal_apply_ne' _ @[simp] lemma map_one [has_zero β] [has_one β] (f : α → β) (h₀ : f 0 = 0) (h₁ : f 1 = 1) : (1 : matrix n n α).map f = (1 : matrix n n β) := by { ext, simp only [one_apply, map_apply], split_ifs; simp [h₀, h₁], } lemma one_eq_pi_single {i j} : (1 : matrix n n α) i j = pi.single i 1 j := by simp only [one_apply, pi.single_apply, eq_comm]; congr -- deal with decidable_eq end one section numeral @[simp] lemma bit0_apply [has_add α] (M : matrix m m α) (i : m) (j : m) : (bit0 M) i j = bit0 (M i j) := rfl variables [add_zero_class α] [has_one α] lemma bit1_apply (M : matrix n n α) (i : n) (j : n) : (bit1 M) i j = if i = j then bit1 (M i j) else bit0 (M i j) := by dsimp [bit1]; by_cases h : i = j; simp [h] @[simp] lemma bit1_apply_eq (M : matrix n n α) (i : n) : (bit1 M) i i = bit1 (M i i) := by simp [bit1_apply] @[simp] lemma bit1_apply_ne (M : matrix n n α) {i j : n} (h : i ≠ j) : (bit1 M) i j = bit0 (M i j) := by simp [bit1_apply, h] end numeral end diagonal section diag /-- The diagonal of a square matrix. -/ @[simp] def diag (A : matrix n n α) (i : n) : α := A i i @[simp] lemma diag_diagonal [decidable_eq n] [has_zero α] (a : n → α) : diag (diagonal a) = a := funext $ @diagonal_apply_eq _ _ _ _ a @[simp] lemma diag_transpose (A : matrix n n α) : diag Aᵀ = diag A := rfl @[simp] theorem diag_zero [has_zero α] : diag (0 : matrix n n α) = 0 := rfl @[simp] theorem diag_add [has_add α] (A B : matrix n n α) : diag (A + B) = diag A + diag B := rfl @[simp] theorem diag_sub [has_sub α] (A B : matrix n n α) : diag (A - B) = diag A - diag B := rfl @[simp] theorem diag_neg [has_neg α] (A : matrix n n α) : diag (-A) = -diag A := rfl @[simp] theorem diag_smul [has_smul R α] (r : R) (A : matrix n n α) : diag (r • A) = r • diag A := rfl @[simp] theorem diag_one [decidable_eq n] [has_zero α] [has_one α] : diag (1 : matrix n n α) = 1 := diag_diagonal _ variables (n α) /-- `matrix.diag` as an `add_monoid_hom`. -/ @[simps] def diag_add_monoid_hom [add_zero_class α] : matrix n n α →+ (n → α) := { to_fun := diag, map_zero' := diag_zero, map_add' := diag_add,} variables (R) /-- `matrix.diag` as a `linear_map`. -/ @[simps] def diag_linear_map [semiring R] [add_comm_monoid α] [module R α] : matrix n n α →ₗ[R] (n → α) := { map_smul' := diag_smul, .. diag_add_monoid_hom n α,} variables {n α R} lemma diag_map {f : α → β} {A : matrix n n α} : diag (A.map f) = f ∘ diag A := rfl @[simp] lemma diag_conj_transpose [add_monoid α] [star_add_monoid α] (A : matrix n n α) : diag Aᴴ = star (diag A) := rfl @[simp] lemma diag_list_sum [add_monoid α] (l : list (matrix n n α)) : diag l.sum = (l.map diag).sum := map_list_sum (diag_add_monoid_hom n α) l @[simp] lemma diag_multiset_sum [add_comm_monoid α] (s : multiset (matrix n n α)) : diag s.sum = (s.map diag).sum := map_multiset_sum (diag_add_monoid_hom n α) s @[simp] lemma diag_sum {ι} [add_comm_monoid α] (s : finset ι) (f : ι → matrix n n α) : diag (∑ i in s, f i) = ∑ i in s, diag (f i) := map_sum (diag_add_monoid_hom n α) f s end diag section dot_product variables [fintype m] [fintype n] /-- `dot_product v w` is the sum of the entrywise products `v i * w i` -/ def dot_product [has_mul α] [add_comm_monoid α] (v w : m → α) : α := ∑ i, v i * w i /- The precedence of 72 comes immediately after ` • ` for `has_smul.smul`, so that `r₁ • a ⬝ᵥ r₂ • b` is parsed as `(r₁ • a) ⬝ᵥ (r₂ • b)` here. -/ localized "infix (name := matrix.dot_product) ` ⬝ᵥ `:72 := matrix.dot_product" in matrix lemma dot_product_assoc [non_unital_semiring α] (u : m → α) (w : n → α) (v : matrix m n α) : (λ j, u ⬝ᵥ (λ i, v i j)) ⬝ᵥ w = u ⬝ᵥ (λ i, (v i) ⬝ᵥ w) := by simpa [dot_product, finset.mul_sum, finset.sum_mul, mul_assoc] using finset.sum_comm lemma dot_product_comm [add_comm_monoid α] [comm_semigroup α] (v w : m → α) : v ⬝ᵥ w = w ⬝ᵥ v := by simp_rw [dot_product, mul_comm] @[simp] lemma dot_product_punit [add_comm_monoid α] [has_mul α] (v w : punit → α) : v ⬝ᵥ w = v ⟨⟩ * w ⟨⟩ := by simp [dot_product] section non_unital_non_assoc_semiring variables [non_unital_non_assoc_semiring α] (u v w : m → α) (x y : n → α) @[simp] lemma dot_product_zero : v ⬝ᵥ 0 = 0 := by simp [dot_product] @[simp] lemma dot_product_zero' : v ⬝ᵥ (λ _, 0) = 0 := dot_product_zero v @[simp] lemma zero_dot_product : 0 ⬝ᵥ v = 0 := by simp [dot_product] @[simp] lemma zero_dot_product' : (λ _, (0 : α)) ⬝ᵥ v = 0 := zero_dot_product v @[simp] lemma add_dot_product : (u + v) ⬝ᵥ w = u ⬝ᵥ w + v ⬝ᵥ w := by simp [dot_product, add_mul, finset.sum_add_distrib] @[simp] lemma dot_product_add : u ⬝ᵥ (v + w) = u ⬝ᵥ v + u ⬝ᵥ w := by simp [dot_product, mul_add, finset.sum_add_distrib] @[simp] lemma sum_elim_dot_product_sum_elim : (sum.elim u x) ⬝ᵥ (sum.elim v y) = u ⬝ᵥ v + x ⬝ᵥ y := by simp [dot_product] end non_unital_non_assoc_semiring section non_unital_non_assoc_semiring_decidable variables [decidable_eq m] [non_unital_non_assoc_semiring α] (u v w : m → α) @[simp] lemma diagonal_dot_product (i : m) : diagonal v i ⬝ᵥ w = v i * w i := have ∀ j ≠ i, diagonal v i j * w j = 0 := λ j hij, by simp [diagonal_apply_ne' _ hij], by convert finset.sum_eq_single i (λ j _, this j) _ using 1; simp @[simp] lemma dot_product_diagonal (i : m) : v ⬝ᵥ diagonal w i = v i * w i := have ∀ j ≠ i, v j * diagonal w i j = 0 := λ j hij, by simp [diagonal_apply_ne' _ hij], by convert finset.sum_eq_single i (λ j _, this j) _ using 1; simp @[simp] lemma dot_product_diagonal' (i : m) : v ⬝ᵥ (λ j, diagonal w j i) = v i * w i := have ∀ j ≠ i, v j * diagonal w j i = 0 := λ j hij, by simp [diagonal_apply_ne _ hij], by convert finset.sum_eq_single i (λ j _, this j) _ using 1; simp @[simp] lemma single_dot_product (x : α) (i : m) : pi.single i x ⬝ᵥ v = x * v i := have ∀ j ≠ i, pi.single i x j * v j = 0 := λ j hij, by simp [pi.single_eq_of_ne hij], by convert finset.sum_eq_single i (λ j _, this j) _ using 1; simp @[simp] lemma dot_product_single (x : α) (i : m) : v ⬝ᵥ pi.single i x = v i * x := have ∀ j ≠ i, v j * pi.single i x j = 0 := λ j hij, by simp [pi.single_eq_of_ne hij], by convert finset.sum_eq_single i (λ j _, this j) _ using 1; simp end non_unital_non_assoc_semiring_decidable section non_unital_non_assoc_ring variables [non_unital_non_assoc_ring α] (u v w : m → α) @[simp] lemma neg_dot_product : -v ⬝ᵥ w = - (v ⬝ᵥ w) := by simp [dot_product] @[simp] lemma dot_product_neg : v ⬝ᵥ -w = - (v ⬝ᵥ w) := by simp [dot_product] @[simp] lemma sub_dot_product : (u - v) ⬝ᵥ w = u ⬝ᵥ w - v ⬝ᵥ w := by simp [sub_eq_add_neg] @[simp] lemma dot_product_sub : u ⬝ᵥ (v - w) = u ⬝ᵥ v - u ⬝ᵥ w := by simp [sub_eq_add_neg] end non_unital_non_assoc_ring section distrib_mul_action variables [monoid R] [has_mul α] [add_comm_monoid α] [distrib_mul_action R α] @[simp] lemma smul_dot_product [is_scalar_tower R α α] (x : R) (v w : m → α) : (x • v) ⬝ᵥ w = x • (v ⬝ᵥ w) := by simp [dot_product, finset.smul_sum, smul_mul_assoc] @[simp] lemma dot_product_smul [smul_comm_class R α α] (x : R) (v w : m → α) : v ⬝ᵥ (x • w) = x • (v ⬝ᵥ w) := by simp [dot_product, finset.smul_sum, mul_smul_comm] end distrib_mul_action section star_ring variables [non_unital_semiring α] [star_ring α] (v w : m → α) lemma star_dot_product_star : star v ⬝ᵥ star w = star (w ⬝ᵥ v) := by simp [dot_product] lemma star_dot_product : star v ⬝ᵥ w = star (star w ⬝ᵥ v) := by simp [dot_product] lemma dot_product_star : v ⬝ᵥ star w = star (w ⬝ᵥ star v) := by simp [dot_product] end star_ring end dot_product open_locale matrix /-- `M ⬝ N` is the usual product of matrices `M` and `N`, i.e. we have that `(M ⬝ N) i k` is the dot product of the `i`-th row of `M` by the `k`-th column of `N`. This is currently only defined when `m` is finite. -/ protected def mul [fintype m] [has_mul α] [add_comm_monoid α] (M : matrix l m α) (N : matrix m n α) : matrix l n α := λ i k, (λ j, M i j) ⬝ᵥ (λ j, N j k) localized "infixl (name := matrix.mul) ` ⬝ `:75 := matrix.mul" in matrix theorem mul_apply [fintype m] [has_mul α] [add_comm_monoid α] {M : matrix l m α} {N : matrix m n α} {i k} : (M ⬝ N) i k = ∑ j, M i j * N j k := rfl instance [fintype n] [has_mul α] [add_comm_monoid α] : has_mul (matrix n n α) := ⟨matrix.mul⟩ @[simp] theorem mul_eq_mul [fintype n] [has_mul α] [add_comm_monoid α] (M N : matrix n n α) : M * N = M ⬝ N := rfl theorem mul_apply' [fintype m] [has_mul α] [add_comm_monoid α] {M : matrix l m α} {N : matrix m n α} {i k} : (M ⬝ N) i k = (λ j, M i j) ⬝ᵥ (λ j, N j k) := rfl @[simp] theorem diagonal_neg [decidable_eq n] [add_group α] (d : n → α) : -diagonal d = diagonal (λ i, -d i) := ((diagonal_add_monoid_hom n α).map_neg d).symm lemma sum_apply [add_comm_monoid α] (i : m) (j : n) (s : finset β) (g : β → matrix m n α) : (∑ c in s, g c) i j = ∑ c in s, g c i j := (congr_fun (s.sum_apply i g) j).trans (s.sum_apply j _) lemma two_mul_expl {R : Type*} [comm_ring R] (A B : matrix (fin 2) (fin 2) R) : (A * B) 0 0 = A 0 0 * B 0 0 + A 0 1 * B 1 0 ∧ (A * B) 0 1 = A 0 0 * B 0 1 + A 0 1 * B 1 1 ∧ (A * B) 1 0 = A 1 0 * B 0 0 + A 1 1 * B 1 0 ∧ (A * B) 1 1 = A 1 0 * B 0 1 + A 1 1 * B 1 1 := begin split, work_on_goal 2 {split}, work_on_goal 3 {split}, all_goals {simp only [matrix.mul_eq_mul], rw [matrix.mul_apply, finset.sum_fin_eq_sum_range, finset.sum_range_succ, finset.sum_range_succ], simp}, end section add_comm_monoid variables [add_comm_monoid α] [has_mul α] @[simp] lemma smul_mul [fintype n] [monoid R] [distrib_mul_action R α] [is_scalar_tower R α α] (a : R) (M : matrix m n α) (N : matrix n l α) : (a • M) ⬝ N = a • M ⬝ N := by { ext, apply smul_dot_product } @[simp] lemma mul_smul [fintype n] [monoid R] [distrib_mul_action R α] [smul_comm_class R α α] (M : matrix m n α) (a : R) (N : matrix n l α) : M ⬝ (a • N) = a • M ⬝ N := by { ext, apply dot_product_smul } end add_comm_monoid section non_unital_non_assoc_semiring variables [non_unital_non_assoc_semiring α] @[simp] protected theorem mul_zero [fintype n] (M : matrix m n α) : M ⬝ (0 : matrix n o α) = 0 := by { ext i j, apply dot_product_zero } @[simp] protected theorem zero_mul [fintype m] (M : matrix m n α) : (0 : matrix l m α) ⬝ M = 0 := by { ext i j, apply zero_dot_product } protected theorem mul_add [fintype n] (L : matrix m n α) (M N : matrix n o α) : L ⬝ (M + N) = L ⬝ M + L ⬝ N := by { ext i j, apply dot_product_add } protected theorem add_mul [fintype m] (L M : matrix l m α) (N : matrix m n α) : (L + M) ⬝ N = L ⬝ N + M ⬝ N := by { ext i j, apply add_dot_product } instance [fintype n] : non_unital_non_assoc_semiring (matrix n n α) := { mul := (*), add := (+), zero := 0, mul_zero := matrix.mul_zero, zero_mul := matrix.zero_mul, left_distrib := matrix.mul_add, right_distrib := matrix.add_mul, .. matrix.add_comm_monoid} @[simp] theorem diagonal_mul [fintype m] [decidable_eq m] (d : m → α) (M : matrix m n α) (i j) : (diagonal d).mul M i j = d i * M i j := diagonal_dot_product _ _ _ @[simp] theorem mul_diagonal [fintype n] [decidable_eq n] (d : n → α) (M : matrix m n α) (i j) : (M ⬝ diagonal d) i j = M i j * d j := by { rw ← diagonal_transpose, apply dot_product_diagonal } @[simp] theorem diagonal_mul_diagonal [fintype n] [decidable_eq n] (d₁ d₂ : n → α) : (diagonal d₁) ⬝ (diagonal d₂) = diagonal (λ i, d₁ i * d₂ i) := by ext i j; by_cases i = j; simp [h] theorem diagonal_mul_diagonal' [fintype n] [decidable_eq n] (d₁ d₂ : n → α) : diagonal d₁ * diagonal d₂ = diagonal (λ i, d₁ i * d₂ i) := diagonal_mul_diagonal _ _ lemma smul_eq_diagonal_mul [fintype m] [decidable_eq m] (M : matrix m n α) (a : α) : a • M = diagonal (λ _, a) ⬝ M := by { ext, simp } @[simp] lemma diag_col_mul_row (a b : n → α) : diag (col a ⬝ row b) = a * b := by { ext, simp [matrix.mul_apply, col, row] } /-- Left multiplication by a matrix, as an `add_monoid_hom` from matrices to matrices. -/ @[simps] def add_monoid_hom_mul_left [fintype m] (M : matrix l m α) : matrix m n α →+ matrix l n α := { to_fun := λ x, M ⬝ x, map_zero' := matrix.mul_zero _, map_add' := matrix.mul_add _ } /-- Right multiplication by a matrix, as an `add_monoid_hom` from matrices to matrices. -/ @[simps] def add_monoid_hom_mul_right [fintype m] (M : matrix m n α) : matrix l m α →+ matrix l n α := { to_fun := λ x, x ⬝ M, map_zero' := matrix.zero_mul _, map_add' := λ _ _, matrix.add_mul _ _ _ } protected lemma sum_mul [fintype m] (s : finset β) (f : β → matrix l m α) (M : matrix m n α) : (∑ a in s, f a) ⬝ M = ∑ a in s, f a ⬝ M := (add_monoid_hom_mul_right M : matrix l m α →+ _).map_sum f s protected lemma mul_sum [fintype m] (s : finset β) (f : β → matrix m n α) (M : matrix l m α) : M ⬝ ∑ a in s, f a = ∑ a in s, M ⬝ f a := (add_monoid_hom_mul_left M : matrix m n α →+ _).map_sum f s /-- This instance enables use with `smul_mul_assoc`. -/ instance semiring.is_scalar_tower [fintype n] [monoid R] [distrib_mul_action R α] [is_scalar_tower R α α] : is_scalar_tower R (matrix n n α) (matrix n n α) := ⟨λ r m n, matrix.smul_mul r m n⟩ /-- This instance enables use with `mul_smul_comm`. -/ instance semiring.smul_comm_class [fintype n] [monoid R] [distrib_mul_action R α] [smul_comm_class R α α] : smul_comm_class R (matrix n n α) (matrix n n α) := ⟨λ r m n, (matrix.mul_smul m r n).symm⟩ end non_unital_non_assoc_semiring section non_assoc_semiring variables [non_assoc_semiring α] @[simp] protected theorem one_mul [fintype m] [decidable_eq m] (M : matrix m n α) : (1 : matrix m m α) ⬝ M = M := by ext i j; rw [← diagonal_one, diagonal_mul, one_mul] @[simp] protected theorem mul_one [fintype n] [decidable_eq n] (M : matrix m n α) : M ⬝ (1 : matrix n n α) = M := by ext i j; rw [← diagonal_one, mul_diagonal, mul_one] instance [fintype n] [decidable_eq n] : non_assoc_semiring (matrix n n α) := { one := 1, one_mul := matrix.one_mul, mul_one := matrix.mul_one, nat_cast := λ n, diagonal (λ _, n), nat_cast_zero := by ext; simp [nat.cast], nat_cast_succ := λ n, by ext; by_cases i = j; simp [nat.cast, *], .. matrix.non_unital_non_assoc_semiring } @[simp] lemma map_mul [fintype n] {L : matrix m n α} {M : matrix n o α} [non_assoc_semiring β] {f : α →+* β} : (L ⬝ M).map f = L.map f ⬝ M.map f := by { ext, simp [mul_apply, ring_hom.map_sum], } variables (α n) /-- `matrix.diagonal` as a `ring_hom`. -/ @[simps] def diagonal_ring_hom [fintype n] [decidable_eq n] : (n → α) →+* matrix n n α := { to_fun := diagonal, map_one' := diagonal_one, map_mul' := λ _ _, (diagonal_mul_diagonal' _ _).symm, .. diagonal_add_monoid_hom n α } end non_assoc_semiring section non_unital_semiring variables [non_unital_semiring α] [fintype m] [fintype n] protected theorem mul_assoc (L : matrix l m α) (M : matrix m n α) (N : matrix n o α) : (L ⬝ M) ⬝ N = L ⬝ (M ⬝ N) := by { ext, apply dot_product_assoc } instance : non_unital_semiring (matrix n n α) := { mul_assoc := matrix.mul_assoc, ..matrix.non_unital_non_assoc_semiring } end non_unital_semiring section semiring variables [semiring α] instance [fintype n] [decidable_eq n] : semiring (matrix n n α) := { ..matrix.non_unital_semiring, ..matrix.non_assoc_semiring } end semiring section non_unital_non_assoc_ring variables [non_unital_non_assoc_ring α] [fintype n] @[simp] protected theorem neg_mul (M : matrix m n α) (N : matrix n o α) : (-M) ⬝ N = -(M ⬝ N) := by { ext, apply neg_dot_product } @[simp] protected theorem mul_neg (M : matrix m n α) (N : matrix n o α) : M ⬝ (-N) = -(M ⬝ N) := by { ext, apply dot_product_neg } protected theorem sub_mul (M M' : matrix m n α) (N : matrix n o α) : (M - M') ⬝ N = M ⬝ N - M' ⬝ N := by rw [sub_eq_add_neg, matrix.add_mul, matrix.neg_mul, sub_eq_add_neg] protected theorem mul_sub (M : matrix m n α) (N N' : matrix n o α) : M ⬝ (N - N') = M ⬝ N - M ⬝ N' := by rw [sub_eq_add_neg, matrix.mul_add, matrix.mul_neg, sub_eq_add_neg] instance : non_unital_non_assoc_ring (matrix n n α) := { ..matrix.non_unital_non_assoc_semiring, ..matrix.add_comm_group } end non_unital_non_assoc_ring instance [fintype n] [non_unital_ring α] : non_unital_ring (matrix n n α) := { ..matrix.non_unital_semiring, ..matrix.add_comm_group } instance [fintype n] [decidable_eq n] [non_assoc_ring α] : non_assoc_ring (matrix n n α) := { ..matrix.non_assoc_semiring, ..matrix.add_comm_group } instance [fintype n] [decidable_eq n] [ring α] : ring (matrix n n α) := { ..matrix.semiring, ..matrix.add_comm_group } section semiring variables [semiring α] lemma diagonal_pow [fintype n] [decidable_eq n] (v : n → α) (k : ℕ) : diagonal v ^ k = diagonal (v ^ k) := (map_pow (diagonal_ring_hom n α) v k).symm @[simp] lemma mul_mul_left [fintype n] (M : matrix m n α) (N : matrix n o α) (a : α) : of (λ i j, a * M i j) ⬝ N = a • (M ⬝ N) := smul_mul a M N /-- The ring homomorphism `α →+* matrix n n α` sending `a` to the diagonal matrix with `a` on the diagonal. -/ def scalar (n : Type u) [decidable_eq n] [fintype n] : α →+* matrix n n α := { to_fun := λ a, a • 1, map_one' := by simp, map_mul' := by { intros, ext, simp [mul_assoc], }, .. (smul_add_hom α _).flip (1 : matrix n n α) } section scalar variables [decidable_eq n] [fintype n] @[simp] lemma coe_scalar : (scalar n : α → matrix n n α) = λ a, a • 1 := rfl lemma scalar_apply_eq (a : α) (i : n) : scalar n a i i = a := by simp only [coe_scalar, smul_eq_mul, mul_one, one_apply_eq, pi.smul_apply] lemma scalar_apply_ne (a : α) (i j : n) (h : i ≠ j) : scalar n a i j = 0 := by simp only [h, coe_scalar, one_apply_ne, ne.def, not_false_iff, pi.smul_apply, smul_zero] lemma scalar_inj [nonempty n] {r s : α} : scalar n r = scalar n s ↔ r = s := begin split, { intro h, inhabit n, rw [← scalar_apply_eq r (arbitrary n), ← scalar_apply_eq s (arbitrary n), h] }, { rintro rfl, refl } end end scalar end semiring section comm_semiring variables [comm_semiring α] [fintype n] lemma smul_eq_mul_diagonal [decidable_eq n] (M : matrix m n α) (a : α) : a • M = M ⬝ diagonal (λ _, a) := by { ext, simp [mul_comm] } @[simp] lemma mul_mul_right (M : matrix m n α) (N : matrix n o α) (a : α) : M ⬝ of (λ i j, a * N i j) = a • (M ⬝ N) := mul_smul M a N lemma scalar.commute [decidable_eq n] (r : α) (M : matrix n n α) : commute (scalar n r) M := by simp [commute, semiconj_by] end comm_semiring section algebra variables [fintype n] [decidable_eq n] variables [comm_semiring R] [semiring α] [semiring β] [algebra R α] [algebra R β] instance : algebra R (matrix n n α) := { commutes' := λ r x, begin ext, simp [matrix.scalar, matrix.mul_apply, matrix.one_apply, algebra.commutes, smul_ite], end, smul_def' := λ r x, begin ext, simp [matrix.scalar, algebra.smul_def r], end, ..((matrix.scalar n).comp (algebra_map R α)) } lemma algebra_map_matrix_apply {r : R} {i j : n} : algebra_map R (matrix n n α) r i j = if i = j then algebra_map R α r else 0 := begin dsimp [algebra_map, algebra.to_ring_hom, matrix.scalar], split_ifs with h; simp [h, matrix.one_apply_ne], end lemma algebra_map_eq_diagonal (r : R) : algebra_map R (matrix n n α) r = diagonal (algebra_map R (n → α) r) := matrix.ext $ λ i j, algebra_map_matrix_apply @[simp] lemma algebra_map_eq_smul (r : R) : algebra_map R (matrix n n R) r = r • (1 : matrix n n R) := rfl lemma algebra_map_eq_diagonal_ring_hom : algebra_map R (matrix n n α) = (diagonal_ring_hom n α).comp (algebra_map R _) := ring_hom.ext algebra_map_eq_diagonal @[simp] lemma map_algebra_map (r : R) (f : α → β) (hf : f 0 = 0) (hf₂ : f (algebra_map R α r) = algebra_map R β r) : (algebra_map R (matrix n n α) r).map f = algebra_map R (matrix n n β) r := begin rw [algebra_map_eq_diagonal, algebra_map_eq_diagonal, diagonal_map hf], congr' 1 with x, simp only [hf₂, pi.algebra_map_apply] end variables (R) /-- `matrix.diagonal` as an `alg_hom`. -/ @[simps] def diagonal_alg_hom : (n → α) →ₐ[R] matrix n n α := { to_fun := diagonal, commutes' := λ r, (algebra_map_eq_diagonal r).symm, .. diagonal_ring_hom n α } end algebra end matrix /-! ### Bundled versions of `matrix.map` -/ namespace equiv /-- The `equiv` between spaces of matrices induced by an `equiv` between their coefficients. This is `matrix.map` as an `equiv`. -/ @[simps apply] def map_matrix (f : α ≃ β) : matrix m n α ≃ matrix m n β := { to_fun := λ M, M.map f, inv_fun := λ M, M.map f.symm, left_inv := λ M, matrix.ext $ λ _ _, f.symm_apply_apply _, right_inv := λ M, matrix.ext $ λ _ _, f.apply_symm_apply _, } @[simp] lemma map_matrix_refl : (equiv.refl α).map_matrix = equiv.refl (matrix m n α) := rfl @[simp] lemma map_matrix_symm (f : α ≃ β) : f.map_matrix.symm = (f.symm.map_matrix : matrix m n β ≃ _) := rfl @[simp] lemma map_matrix_trans (f : α ≃ β) (g : β ≃ γ) : f.map_matrix.trans g.map_matrix = ((f.trans g).map_matrix : matrix m n α ≃ _) := rfl end equiv namespace add_monoid_hom variables [add_zero_class α] [add_zero_class β] [add_zero_class γ] /-- The `add_monoid_hom` between spaces of matrices induced by an `add_monoid_hom` between their coefficients. This is `matrix.map` as an `add_monoid_hom`. -/ @[simps] def map_matrix (f : α →+ β) : matrix m n α →+ matrix m n β := { to_fun := λ M, M.map f, map_zero' := matrix.map_zero f f.map_zero, map_add' := matrix.map_add f f.map_add } @[simp] lemma map_matrix_id : (add_monoid_hom.id α).map_matrix = add_monoid_hom.id (matrix m n α) := rfl @[simp] lemma map_matrix_comp (f : β →+ γ) (g : α →+ β) : f.map_matrix.comp g.map_matrix = ((f.comp g).map_matrix : matrix m n α →+ _) := rfl end add_monoid_hom namespace add_equiv variables [has_add α] [has_add β] [has_add γ] /-- The `add_equiv` between spaces of matrices induced by an `add_equiv` between their coefficients. This is `matrix.map` as an `add_equiv`. -/ @[simps apply] def map_matrix (f : α ≃+ β) : matrix m n α ≃+ matrix m n β := { to_fun := λ M, M.map f, inv_fun := λ M, M.map f.symm, map_add' := matrix.map_add f f.map_add, .. f.to_equiv.map_matrix } @[simp] lemma map_matrix_refl : (add_equiv.refl α).map_matrix = add_equiv.refl (matrix m n α) := rfl @[simp] lemma map_matrix_symm (f : α ≃+ β) : f.map_matrix.symm = (f.symm.map_matrix : matrix m n β ≃+ _) := rfl @[simp] lemma map_matrix_trans (f : α ≃+ β) (g : β ≃+ γ) : f.map_matrix.trans g.map_matrix = ((f.trans g).map_matrix : matrix m n α ≃+ _) := rfl end add_equiv namespace linear_map variables [semiring R] [add_comm_monoid α] [add_comm_monoid β] [add_comm_monoid γ] variables [module R α] [module R β] [module R γ] /-- The `linear_map` between spaces of matrices induced by a `linear_map` between their coefficients. This is `matrix.map` as a `linear_map`. -/ @[simps] def map_matrix (f : α →ₗ[R] β) : matrix m n α →ₗ[R] matrix m n β := { to_fun := λ M, M.map f, map_add' := matrix.map_add f f.map_add, map_smul' := λ r, matrix.map_smul f r (f.map_smul r), } @[simp] lemma map_matrix_id : linear_map.id.map_matrix = (linear_map.id : matrix m n α →ₗ[R] _) := rfl @[simp] lemma map_matrix_comp (f : β →ₗ[R] γ) (g : α →ₗ[R] β) : f.map_matrix.comp g.map_matrix = ((f.comp g).map_matrix : matrix m n α →ₗ[R] _) := rfl end linear_map namespace linear_equiv variables [semiring R] [add_comm_monoid α] [add_comm_monoid β] [add_comm_monoid γ] variables [module R α] [module R β] [module R γ] /-- The `linear_equiv` between spaces of matrices induced by an `linear_equiv` between their coefficients. This is `matrix.map` as an `linear_equiv`. -/ @[simps apply] def map_matrix (f : α ≃ₗ[R] β) : matrix m n α ≃ₗ[R] matrix m n β := { to_fun := λ M, M.map f, inv_fun := λ M, M.map f.symm, .. f.to_equiv.map_matrix, .. f.to_linear_map.map_matrix } @[simp] lemma map_matrix_refl : (linear_equiv.refl R α).map_matrix = linear_equiv.refl R (matrix m n α) := rfl @[simp] lemma map_matrix_symm (f : α ≃ₗ[R] β) : f.map_matrix.symm = (f.symm.map_matrix : matrix m n β ≃ₗ[R] _) := rfl @[simp] lemma map_matrix_trans (f : α ≃ₗ[R] β) (g : β ≃ₗ[R] γ) : f.map_matrix.trans g.map_matrix = ((f.trans g).map_matrix : matrix m n α ≃ₗ[R] _) := rfl end linear_equiv namespace ring_hom variables [fintype m] [decidable_eq m] variables [non_assoc_semiring α] [non_assoc_semiring β] [non_assoc_semiring γ] /-- The `ring_hom` between spaces of square matrices induced by a `ring_hom` between their coefficients. This is `matrix.map` as a `ring_hom`. -/ @[simps] def map_matrix (f : α →+* β) : matrix m m α →+* matrix m m β := { to_fun := λ M, M.map f, map_one' := by simp, map_mul' := λ L M, matrix.map_mul, .. f.to_add_monoid_hom.map_matrix } @[simp] lemma map_matrix_id : (ring_hom.id α).map_matrix = ring_hom.id (matrix m m α) := rfl @[simp] lemma map_matrix_comp (f : β →+* γ) (g : α →+* β) : f.map_matrix.comp g.map_matrix = ((f.comp g).map_matrix : matrix m m α →+* _) := rfl end ring_hom namespace ring_equiv variables [fintype m] [decidable_eq m] variables [non_assoc_semiring α] [non_assoc_semiring β] [non_assoc_semiring γ] /-- The `ring_equiv` between spaces of square matrices induced by a `ring_equiv` between their coefficients. This is `matrix.map` as a `ring_equiv`. -/ @[simps apply] def map_matrix (f : α ≃+* β) : matrix m m α ≃+* matrix m m β := { to_fun := λ M, M.map f, inv_fun := λ M, M.map f.symm, .. f.to_ring_hom.map_matrix, .. f.to_add_equiv.map_matrix } @[simp] lemma map_matrix_refl : (ring_equiv.refl α).map_matrix = ring_equiv.refl (matrix m m α) := rfl @[simp] lemma map_matrix_symm (f : α ≃+* β) : f.map_matrix.symm = (f.symm.map_matrix : matrix m m β ≃+* _) := rfl @[simp] lemma map_matrix_trans (f : α ≃+* β) (g : β ≃+* γ) : f.map_matrix.trans g.map_matrix = ((f.trans g).map_matrix : matrix m m α ≃+* _) := rfl end ring_equiv namespace alg_hom variables [fintype m] [decidable_eq m] variables [comm_semiring R] [semiring α] [semiring β] [semiring γ] variables [algebra R α] [algebra R β] [algebra R γ] /-- The `alg_hom` between spaces of square matrices induced by a `alg_hom` between their coefficients. This is `matrix.map` as a `alg_hom`. -/ @[simps] def map_matrix (f : α →ₐ[R] β) : matrix m m α →ₐ[R] matrix m m β := { to_fun := λ M, M.map f, commutes' := λ r, matrix.map_algebra_map r f f.map_zero (f.commutes r), .. f.to_ring_hom.map_matrix } @[simp] lemma map_matrix_id : (alg_hom.id R α).map_matrix = alg_hom.id R (matrix m m α) := rfl @[simp] lemma map_matrix_comp (f : β →ₐ[R] γ) (g : α →ₐ[R] β) : f.map_matrix.comp g.map_matrix = ((f.comp g).map_matrix : matrix m m α →ₐ[R] _) := rfl end alg_hom namespace alg_equiv variables [fintype m] [decidable_eq m] variables [comm_semiring R] [semiring α] [semiring β] [semiring γ] variables [algebra R α] [algebra R β] [algebra R γ] /-- The `alg_equiv` between spaces of square matrices induced by a `alg_equiv` between their coefficients. This is `matrix.map` as a `alg_equiv`. -/ @[simps apply] def map_matrix (f : α ≃ₐ[R] β) : matrix m m α ≃ₐ[R] matrix m m β := { to_fun := λ M, M.map f, inv_fun := λ M, M.map f.symm, .. f.to_alg_hom.map_matrix, .. f.to_ring_equiv.map_matrix } @[simp] lemma map_matrix_refl : alg_equiv.refl.map_matrix = (alg_equiv.refl : matrix m m α ≃ₐ[R] _) := rfl @[simp] lemma map_matrix_symm (f : α ≃ₐ[R] β) : f.map_matrix.symm = (f.symm.map_matrix : matrix m m β ≃ₐ[R] _) := rfl @[simp] lemma map_matrix_trans (f : α ≃ₐ[R] β) (g : β ≃ₐ[R] γ) : f.map_matrix.trans g.map_matrix = ((f.trans g).map_matrix : matrix m m α ≃ₐ[R] _) := rfl end alg_equiv open_locale matrix namespace matrix /-- For two vectors `w` and `v`, `vec_mul_vec w v i j` is defined to be `w i * v j`. Put another way, `vec_mul_vec w v` is exactly `col w ⬝ row v`. -/ def vec_mul_vec [has_mul α] (w : m → α) (v : n → α) : matrix m n α | x y := w x * v y lemma vec_mul_vec_eq [has_mul α] [add_comm_monoid α] (w : m → α) (v : n → α) : vec_mul_vec w v = (col w) ⬝ (row v) := by { ext i j, simp only [vec_mul_vec, mul_apply, fintype.univ_punit, finset.sum_singleton], refl } section non_unital_non_assoc_semiring variables [non_unital_non_assoc_semiring α] /-- `mul_vec M v` is the matrix-vector product of `M` and `v`, where `v` is seen as a column matrix. Put another way, `mul_vec M v` is the vector whose entries are those of `M ⬝ col v` (see `col_mul_vec`). -/ def mul_vec [fintype n] (M : matrix m n α) (v : n → α) : m → α | i := (λ j, M i j) ⬝ᵥ v /-- `vec_mul v M` is the vector-matrix product of `v` and `M`, where `v` is seen as a row matrix. Put another way, `vec_mul v M` is the vector whose entries are those of `row v ⬝ M` (see `row_vec_mul`). -/ def vec_mul [fintype m] (v : m → α) (M : matrix m n α) : n → α | j := v ⬝ᵥ (λ i, M i j) /-- Left multiplication by a matrix, as an `add_monoid_hom` from vectors to vectors. -/ @[simps] def mul_vec.add_monoid_hom_left [fintype n] (v : n → α) : matrix m n α →+ m → α := { to_fun := λ M, mul_vec M v, map_zero' := by ext; simp [mul_vec]; refl, map_add' := λ x y, by { ext m, apply add_dot_product } } lemma mul_vec_diagonal [fintype m] [decidable_eq m] (v w : m → α) (x : m) : mul_vec (diagonal v) w x = v x * w x := diagonal_dot_product v w x lemma vec_mul_diagonal [fintype m] [decidable_eq m] (v w : m → α) (x : m) : vec_mul v (diagonal w) x = v x * w x := dot_product_diagonal' v w x /-- Associate the dot product of `mul_vec` to the left. -/ lemma dot_product_mul_vec [fintype n] [fintype m] [non_unital_semiring R] (v : m → R) (A : matrix m n R) (w : n → R) : v ⬝ᵥ mul_vec A w = vec_mul v A ⬝ᵥ w := by simp only [dot_product, vec_mul, mul_vec, finset.mul_sum, finset.sum_mul, mul_assoc]; exact finset.sum_comm @[simp] lemma mul_vec_zero [fintype n] (A : matrix m n α) : mul_vec A 0 = 0 := by { ext, simp [mul_vec] } @[simp] lemma zero_vec_mul [fintype m] (A : matrix m n α) : vec_mul 0 A = 0 := by { ext, simp [vec_mul] } @[simp] lemma zero_mul_vec [fintype n] (v : n → α) : mul_vec (0 : matrix m n α) v = 0 := by { ext, simp [mul_vec] } @[simp] lemma vec_mul_zero [fintype m] (v : m → α) : vec_mul v (0 : matrix m n α) = 0 := by { ext, simp [vec_mul] } lemma smul_mul_vec_assoc [fintype n] [monoid R] [distrib_mul_action R α] [is_scalar_tower R α α] (a : R) (A : matrix m n α) (b : n → α) : (a • A).mul_vec b = a • (A.mul_vec b) := by { ext, apply smul_dot_product, } lemma mul_vec_add [fintype n] (A : matrix m n α) (x y : n → α) : A.mul_vec (x + y) = A.mul_vec x + A.mul_vec y := by { ext, apply dot_product_add } lemma add_mul_vec [fintype n] (A B : matrix m n α) (x : n → α) : (A + B).mul_vec x = A.mul_vec x + B.mul_vec x := by { ext, apply add_dot_product } lemma vec_mul_add [fintype m] (A B : matrix m n α) (x : m → α) : vec_mul x (A + B) = vec_mul x A + vec_mul x B := by { ext, apply dot_product_add } lemma add_vec_mul [fintype m] (A : matrix m n α) (x y : m → α) : vec_mul (x + y) A = vec_mul x A + vec_mul y A := by { ext, apply add_dot_product } lemma vec_mul_smul [fintype n] [monoid R] [non_unital_non_assoc_semiring S] [distrib_mul_action R S] [is_scalar_tower R S S] (M : matrix n m S) (b : R) (v : n → S) : M.vec_mul (b • v) = b • M.vec_mul v := by { ext i, simp only [vec_mul, dot_product, finset.smul_sum, pi.smul_apply, smul_mul_assoc] } lemma mul_vec_smul [fintype n] [monoid R] [non_unital_non_assoc_semiring S] [distrib_mul_action R S] [smul_comm_class R S S] (M : matrix m n S) (b : R) (v : n → S) : M.mul_vec (b • v) = b • M.mul_vec v := by { ext i, simp only [mul_vec, dot_product, finset.smul_sum, pi.smul_apply, mul_smul_comm] } @[simp] lemma mul_vec_single [fintype n] [decidable_eq n] [non_unital_non_assoc_semiring R] (M : matrix m n R) (j : n) (x : R) : M.mul_vec (pi.single j x) = (λ i, M i j * x) := funext $ λ i, dot_product_single _ _ _ @[simp] lemma single_vec_mul [fintype m] [decidable_eq m] [non_unital_non_assoc_semiring R] (M : matrix m n R) (i : m) (x : R) : vec_mul (pi.single i x) M = (λ j, x * M i j) := funext $ λ i, single_dot_product _ _ _ @[simp] lemma diagonal_mul_vec_single [fintype n] [decidable_eq n] [non_unital_non_assoc_semiring R] (v : n → R) (j : n) (x : R) : (diagonal v).mul_vec (pi.single j x) = pi.single j (v j * x) := begin ext i, rw mul_vec_diagonal, exact pi.apply_single (λ i x, v i * x) (λ i, mul_zero _) j x i, end @[simp] lemma single_vec_mul_diagonal [fintype n] [decidable_eq n] [non_unital_non_assoc_semiring R] (v : n → R) (j : n) (x : R) : vec_mul (pi.single j x) (diagonal v) = pi.single j (x * v j) := begin ext i, rw vec_mul_diagonal, exact pi.apply_single (λ i x, x * v i) (λ i, zero_mul _) j x i, end end non_unital_non_assoc_semiring section non_unital_semiring variables [non_unital_semiring α] @[simp] lemma vec_mul_vec_mul [fintype n] [fintype m] (v : m → α) (M : matrix m n α) (N : matrix n o α) : vec_mul (vec_mul v M) N = vec_mul v (M ⬝ N) := by { ext, apply dot_product_assoc } @[simp] lemma mul_vec_mul_vec [fintype n] [fintype o] (v : o → α) (M : matrix m n α) (N : matrix n o α) : mul_vec M (mul_vec N v) = mul_vec (M ⬝ N) v := by { ext, symmetry, apply dot_product_assoc } lemma star_mul_vec [fintype n] [star_ring α] (M : matrix m n α) (v : n → α) : star (M.mul_vec v) = vec_mul (star v) (Mᴴ) := funext $ λ i, (star_dot_product_star _ _).symm lemma star_vec_mul [fintype m] [star_ring α] (M : matrix m n α) (v : m → α) : star (M.vec_mul v) = (Mᴴ).mul_vec (star v) := funext $ λ i, (star_dot_product_star _ _).symm lemma mul_vec_conj_transpose [fintype m] [star_ring α] (A : matrix m n α) (x : m → α) : mul_vec Aᴴ x = star (vec_mul (star x) A) := funext $ λ i, star_dot_product _ _ lemma vec_mul_conj_transpose [fintype n] [star_ring α] (A : matrix m n α) (x : n → α) : vec_mul x Aᴴ = star (mul_vec A (star x)) := funext $ λ i, dot_product_star _ _ lemma mul_mul_apply [fintype n] (A B C : matrix n n α) (i j : n) : (A ⬝ B ⬝ C) i j = A i ⬝ᵥ (B.mul_vec (Cᵀ j)) := by { rw matrix.mul_assoc, simpa only [mul_apply, dot_product, mul_vec] } end non_unital_semiring section non_assoc_semiring variables [fintype m] [decidable_eq m] [non_assoc_semiring α] @[simp] lemma one_mul_vec (v : m → α) : mul_vec 1 v = v := by { ext, rw [←diagonal_one, mul_vec_diagonal, one_mul] } @[simp] lemma vec_mul_one (v : m → α) : vec_mul v 1 = v := by { ext, rw [←diagonal_one, vec_mul_diagonal, mul_one] } end non_assoc_semiring section non_unital_non_assoc_ring variables [non_unital_non_assoc_ring α] lemma neg_vec_mul [fintype m] (v : m → α) (A : matrix m n α) : vec_mul (-v) A = - vec_mul v A := by { ext, apply neg_dot_product } lemma vec_mul_neg [fintype m] (v : m → α) (A : matrix m n α) : vec_mul v (-A) = - vec_mul v A := by { ext, apply dot_product_neg } lemma neg_mul_vec [fintype n] (v : n → α) (A : matrix m n α) : mul_vec (-A) v = - mul_vec A v := by { ext, apply neg_dot_product } lemma mul_vec_neg [fintype n] (v : n → α) (A : matrix m n α) : mul_vec A (-v) = - mul_vec A v := by { ext, apply dot_product_neg } lemma sub_mul_vec [fintype n] (A B : matrix m n α) (x : n → α) : mul_vec (A - B) x = mul_vec A x - mul_vec B x := by simp [sub_eq_add_neg, add_mul_vec, neg_mul_vec] lemma vec_mul_sub [fintype m] (A B : matrix m n α) (x : m → α) : vec_mul x (A - B) = vec_mul x A - vec_mul x B := by simp [sub_eq_add_neg, vec_mul_add, vec_mul_neg] end non_unital_non_assoc_ring section non_unital_comm_semiring variables [non_unital_comm_semiring α] lemma mul_vec_transpose [fintype m] (A : matrix m n α) (x : m → α) : mul_vec Aᵀ x = vec_mul x A := by { ext, apply dot_product_comm } lemma vec_mul_transpose [fintype n] (A : matrix m n α) (x : n → α) : vec_mul x Aᵀ = mul_vec A x := by { ext, apply dot_product_comm } lemma mul_vec_vec_mul [fintype n] [fintype o] (A : matrix m n α) (B : matrix o n α) (x : o → α) : mul_vec A (vec_mul x B) = mul_vec (A ⬝ Bᵀ) x := by rw [← mul_vec_mul_vec, mul_vec_transpose] lemma vec_mul_mul_vec [fintype m] [fintype n] (A : matrix m n α) (B : matrix m o α) (x : n → α) : vec_mul (mul_vec A x) B = vec_mul x (Aᵀ ⬝ B) := by rw [← vec_mul_vec_mul, vec_mul_transpose] end non_unital_comm_semiring section comm_semiring variables [comm_semiring α] lemma mul_vec_smul_assoc [fintype n] (A : matrix m n α) (b : n → α) (a : α) : A.mul_vec (a • b) = a • (A.mul_vec b) := by { ext, apply dot_product_smul } end comm_semiring section transpose open_locale matrix /-- Tell `simp` what the entries are in a transposed matrix. Compare with `mul_apply`, `diagonal_apply_eq`, etc. -/ @[simp] lemma transpose_apply (M : matrix m n α) (i j) : M.transpose j i = M i j := rfl @[simp] lemma transpose_transpose (M : matrix m n α) : Mᵀᵀ = M := by ext; refl @[simp] lemma transpose_zero [has_zero α] : (0 : matrix m n α)ᵀ = 0 := by ext i j; refl @[simp] lemma transpose_one [decidable_eq n] [has_zero α] [has_one α] : (1 : matrix n n α)ᵀ = 1 := begin ext i j, unfold has_one.one transpose, by_cases i = j, { simp only [h, diagonal_apply_eq] }, { simp only [diagonal_apply_ne _ h, diagonal_apply_ne' _ h] } end @[simp] lemma transpose_add [has_add α] (M : matrix m n α) (N : matrix m n α) : (M + N)ᵀ = Mᵀ + Nᵀ := by { ext i j, simp } @[simp] lemma transpose_sub [has_sub α] (M : matrix m n α) (N : matrix m n α) : (M - N)ᵀ = Mᵀ - Nᵀ := by { ext i j, simp } @[simp] lemma transpose_mul [add_comm_monoid α] [comm_semigroup α] [fintype n] (M : matrix m n α) (N : matrix n l α) : (M ⬝ N)ᵀ = Nᵀ ⬝ Mᵀ := begin ext i j, apply dot_product_comm end @[simp] lemma transpose_smul {R : Type*} [has_smul R α] (c : R) (M : matrix m n α) : (c • M)ᵀ = c • Mᵀ := by { ext i j, refl } @[simp] lemma transpose_neg [has_neg α] (M : matrix m n α) : (- M)ᵀ = - Mᵀ := by ext i j; refl lemma transpose_map {f : α → β} {M : matrix m n α} : Mᵀ.map f = (M.map f)ᵀ := by { ext, refl } variables (m n α) /-- `matrix.transpose` as an `add_equiv` -/ @[simps apply] def transpose_add_equiv [has_add α] : matrix m n α ≃+ matrix n m α := { to_fun := transpose, inv_fun := transpose, left_inv := transpose_transpose, right_inv := transpose_transpose, map_add' := transpose_add } @[simp] lemma transpose_add_equiv_symm [has_add α] : (transpose_add_equiv m n α).symm = transpose_add_equiv n m α := rfl variables {m n α} lemma transpose_list_sum [add_monoid α] (l : list (matrix m n α)) : l.sumᵀ = (l.map transpose).sum := (transpose_add_equiv m n α).to_add_monoid_hom.map_list_sum l lemma transpose_multiset_sum [add_comm_monoid α] (s : multiset (matrix m n α)) : s.sumᵀ = (s.map transpose).sum := (transpose_add_equiv m n α).to_add_monoid_hom.map_multiset_sum s lemma transpose_sum [add_comm_monoid α] {ι : Type*} (s : finset ι) (M : ι → matrix m n α) : (∑ i in s, M i)ᵀ = ∑ i in s, (M i)ᵀ := (transpose_add_equiv m n α).to_add_monoid_hom.map_sum _ s variables (m n R α) /-- `matrix.transpose` as a `linear_map` -/ @[simps apply] def transpose_linear_equiv [semiring R] [add_comm_monoid α] [module R α] : matrix m n α ≃ₗ[R] matrix n m α := { map_smul' := transpose_smul, ..transpose_add_equiv m n α} @[simp] lemma transpose_linear_equiv_symm [semiring R] [add_comm_monoid α] [module R α] : (transpose_linear_equiv m n R α).symm = transpose_linear_equiv n m R α := rfl variables {m n R α} variables (m α) /-- `matrix.transpose` as a `ring_equiv` to the opposite ring -/ @[simps] def transpose_ring_equiv [add_comm_monoid α] [comm_semigroup α] [fintype m] : matrix m m α ≃+* (matrix m m α)ᵐᵒᵖ := { to_fun := λ M, mul_opposite.op (Mᵀ), inv_fun := λ M, M.unopᵀ, map_mul' := λ M N, (congr_arg mul_opposite.op (transpose_mul M N)).trans (mul_opposite.op_mul _ _), ..(transpose_add_equiv m m α).trans mul_opposite.op_add_equiv } variables {m α} @[simp] lemma transpose_pow [comm_semiring α] [fintype m] [decidable_eq m] (M : matrix m m α) (k : ℕ) : (M ^ k)ᵀ = Mᵀ ^ k := mul_opposite.op_injective $ map_pow (transpose_ring_equiv m α) M k lemma transpose_list_prod [comm_semiring α] [fintype m] [decidable_eq m] (l : list (matrix m m α)) : l.prodᵀ = (l.map transpose).reverse.prod := (transpose_ring_equiv m α).unop_map_list_prod l variables (R m α) /-- `matrix.transpose` as an `alg_equiv` to the opposite ring -/ @[simps] def transpose_alg_equiv [comm_semiring R] [comm_semiring α] [fintype m] [decidable_eq m] [algebra R α] : matrix m m α ≃ₐ[R] (matrix m m α)ᵐᵒᵖ := { to_fun := λ M, mul_opposite.op (Mᵀ), commutes' := λ r, by simp only [algebra_map_eq_diagonal, diagonal_transpose, mul_opposite.algebra_map_apply], ..(transpose_add_equiv m m α).trans mul_opposite.op_add_equiv, ..transpose_ring_equiv m α } variables {R m α} end transpose section conj_transpose open_locale matrix /-- Tell `simp` what the entries are in a conjugate transposed matrix. Compare with `mul_apply`, `diagonal_apply_eq`, etc. -/ @[simp] lemma conj_transpose_apply [has_star α] (M : matrix m n α) (i j) : M.conj_transpose j i = star (M i j) := rfl @[simp] lemma conj_transpose_conj_transpose [has_involutive_star α] (M : matrix m n α) : Mᴴᴴ = M := matrix.ext $ by simp @[simp] lemma conj_transpose_zero [add_monoid α] [star_add_monoid α] : (0 : matrix m n α)ᴴ = 0 := matrix.ext $ by simp @[simp] lemma conj_transpose_one [decidable_eq n] [semiring α] [star_ring α]: (1 : matrix n n α)ᴴ = 1 := by simp [conj_transpose] @[simp] lemma conj_transpose_add [add_monoid α] [star_add_monoid α] (M N : matrix m n α) : (M + N)ᴴ = Mᴴ + Nᴴ := matrix.ext $ by simp @[simp] lemma conj_transpose_sub [add_group α] [star_add_monoid α] (M N : matrix m n α) : (M - N)ᴴ = Mᴴ - Nᴴ := matrix.ext $ by simp /-- Note that `star_module` is quite a strong requirement; as such we also provide the following variants which this lemma would not apply to: * `matrix.conj_transpose_smul_non_comm` * `matrix.conj_transpose_nsmul` * `matrix.conj_transpose_zsmul` * `matrix.conj_transpose_nat_cast_smul` * `matrix.conj_transpose_int_cast_smul` * `matrix.conj_transpose_inv_nat_cast_smul` * `matrix.conj_transpose_inv_int_cast_smul` * `matrix.conj_transpose_rat_smul` * `matrix.conj_transpose_rat_cast_smul` -/ @[simp] lemma conj_transpose_smul [has_star R] [has_star α] [has_smul R α] [star_module R α] (c : R) (M : matrix m n α) : (c • M)ᴴ = star c • Mᴴ := matrix.ext $ λ i j, star_smul _ _ @[simp] lemma conj_transpose_smul_non_comm [has_star R] [has_star α] [has_smul R α] [has_smul Rᵐᵒᵖ α] (c : R) (M : matrix m n α) (h : ∀ (r : R) (a : α), star (r • a) = mul_opposite.op (star r) • star a) : (c • M)ᴴ = mul_opposite.op (star c) • Mᴴ := matrix.ext $ by simp [h] @[simp] lemma conj_transpose_smul_self [semigroup α] [star_semigroup α] (c : α) (M : matrix m n α) : (c • M)ᴴ = mul_opposite.op (star c) • Mᴴ := conj_transpose_smul_non_comm c M star_mul @[simp] lemma conj_transpose_nsmul [add_monoid α] [star_add_monoid α] (c : ℕ) (M : matrix m n α) : (c • M)ᴴ = c • Mᴴ := matrix.ext $ by simp @[simp] lemma conj_transpose_zsmul [add_group α] [star_add_monoid α] (c : ℤ) (M : matrix m n α) : (c • M)ᴴ = c • Mᴴ := matrix.ext $ by simp @[simp] lemma conj_transpose_nat_cast_smul [semiring R] [add_comm_monoid α] [star_add_monoid α] [module R α] (c : ℕ) (M : matrix m n α) : ((c : R) • M)ᴴ = (c : R) • Mᴴ := matrix.ext $ by simp @[simp] lemma conj_transpose_int_cast_smul [ring R] [add_comm_group α] [star_add_monoid α] [module R α] (c : ℤ) (M : matrix m n α) : ((c : R) • M)ᴴ = (c : R) • Mᴴ := matrix.ext $ by simp @[simp] lemma conj_transpose_inv_nat_cast_smul [division_ring R] [add_comm_group α] [star_add_monoid α] [module R α] (c : ℕ) (M : matrix m n α) : ((c : R)⁻¹ • M)ᴴ = (c : R)⁻¹ • Mᴴ := matrix.ext $ by simp @[simp] lemma conj_transpose_inv_int_cast_smul [division_ring R] [add_comm_group α] [star_add_monoid α] [module R α] (c : ℤ) (M : matrix m n α) : ((c : R)⁻¹ • M)ᴴ = (c : R)⁻¹ • Mᴴ := matrix.ext $ by simp @[simp] lemma conj_transpose_rat_cast_smul [division_ring R] [add_comm_group α] [star_add_monoid α] [module R α] (c : ℚ) (M : matrix m n α) : ((c : R) • M)ᴴ = (c : R) • Mᴴ := matrix.ext $ by simp @[simp] lemma conj_transpose_rat_smul [add_comm_group α] [star_add_monoid α] [module ℚ α] (c : ℚ) (M : matrix m n α) : (c • M)ᴴ = c • Mᴴ := matrix.ext $ by simp @[simp] lemma conj_transpose_mul [fintype n] [non_unital_semiring α] [star_ring α] (M : matrix m n α) (N : matrix n l α) : (M ⬝ N)ᴴ = Nᴴ ⬝ Mᴴ := matrix.ext $ by simp [mul_apply] @[simp] lemma conj_transpose_neg [add_group α] [star_add_monoid α] (M : matrix m n α) : (- M)ᴴ = - Mᴴ := matrix.ext $ by simp lemma conj_transpose_map [has_star α] [has_star β] {A : matrix m n α} (f : α → β) (hf : function.semiconj f star star) : Aᴴ.map f = (A.map f)ᴴ := matrix.ext $ λ i j, hf _ variables (m n α) /-- `matrix.conj_transpose` as an `add_equiv` -/ @[simps apply] def conj_transpose_add_equiv [add_monoid α] [star_add_monoid α] : matrix m n α ≃+ matrix n m α := { to_fun := conj_transpose, inv_fun := conj_transpose, left_inv := conj_transpose_conj_transpose, right_inv := conj_transpose_conj_transpose, map_add' := conj_transpose_add } @[simp] lemma conj_transpose_add_equiv_symm [add_monoid α] [star_add_monoid α] : (conj_transpose_add_equiv m n α).symm = conj_transpose_add_equiv n m α := rfl variables {m n α} lemma conj_transpose_list_sum [add_monoid α] [star_add_monoid α] (l : list (matrix m n α)) : l.sumᴴ = (l.map conj_transpose).sum := (conj_transpose_add_equiv m n α).to_add_monoid_hom.map_list_sum l lemma conj_transpose_multiset_sum [add_comm_monoid α] [star_add_monoid α] (s : multiset (matrix m n α)) : s.sumᴴ = (s.map conj_transpose).sum := (conj_transpose_add_equiv m n α).to_add_monoid_hom.map_multiset_sum s lemma conj_transpose_sum [add_comm_monoid α] [star_add_monoid α] {ι : Type*} (s : finset ι) (M : ι → matrix m n α) : (∑ i in s, M i)ᴴ = ∑ i in s, (M i)ᴴ := (conj_transpose_add_equiv m n α).to_add_monoid_hom.map_sum _ s variables (m n R α) /-- `matrix.conj_transpose` as a `linear_map` -/ @[simps apply] def conj_transpose_linear_equiv [comm_semiring R] [star_ring R] [add_comm_monoid α] [star_add_monoid α] [module R α] [star_module R α] : matrix m n α ≃ₗ⋆[R] matrix n m α := { map_smul' := conj_transpose_smul, ..conj_transpose_add_equiv m n α} @[simp] lemma conj_transpose_linear_equiv_symm [comm_semiring R] [star_ring R] [add_comm_monoid α] [star_add_monoid α] [module R α] [star_module R α] : (conj_transpose_linear_equiv m n R α).symm = conj_transpose_linear_equiv n m R α := rfl variables {m n R α} variables (m α) /-- `matrix.conj_transpose` as a `ring_equiv` to the opposite ring -/ @[simps] def conj_transpose_ring_equiv [semiring α] [star_ring α] [fintype m] : matrix m m α ≃+* (matrix m m α)ᵐᵒᵖ := { to_fun := λ M, mul_opposite.op (Mᴴ), inv_fun := λ M, M.unopᴴ, map_mul' := λ M N, (congr_arg mul_opposite.op (conj_transpose_mul M N)).trans (mul_opposite.op_mul _ _), ..(conj_transpose_add_equiv m m α).trans mul_opposite.op_add_equiv } variables {m α} @[simp] lemma conj_transpose_pow [semiring α] [star_ring α] [fintype m] [decidable_eq m] (M : matrix m m α) (k : ℕ) : (M ^ k)ᴴ = Mᴴ ^ k := mul_opposite.op_injective $ map_pow (conj_transpose_ring_equiv m α) M k lemma conj_transpose_list_prod [semiring α] [star_ring α] [fintype m] [decidable_eq m] (l : list (matrix m m α)) : l.prodᴴ = (l.map conj_transpose).reverse.prod := (conj_transpose_ring_equiv m α).unop_map_list_prod l end conj_transpose section star /-- When `α` has a star operation, square matrices `matrix n n α` have a star operation equal to `matrix.conj_transpose`. -/ instance [has_star α] : has_star (matrix n n α) := {star := conj_transpose} lemma star_eq_conj_transpose [has_star α] (M : matrix m m α) : star M = Mᴴ := rfl @[simp] lemma star_apply [has_star α] (M : matrix n n α) (i j) : (star M) i j = star (M j i) := rfl instance [has_involutive_star α] : has_involutive_star (matrix n n α) := { star_involutive := conj_transpose_conj_transpose } /-- When `α` is a `*`-additive monoid, `matrix.has_star` is also a `*`-additive monoid. -/ instance [add_monoid α] [star_add_monoid α] : star_add_monoid (matrix n n α) := { star_add := conj_transpose_add } /-- When `α` is a `*`-(semi)ring, `matrix.has_star` is also a `*`-(semi)ring. -/ instance [fintype n] [semiring α] [star_ring α] : star_ring (matrix n n α) := { star_add := conj_transpose_add, star_mul := conj_transpose_mul, } /-- A version of `star_mul` for `⬝` instead of `*`. -/ lemma star_mul [fintype n] [non_unital_semiring α] [star_ring α] (M N : matrix n n α) : star (M ⬝ N) = star N ⬝ star M := conj_transpose_mul _ _ end star /-- Given maps `(r_reindex : l → m)` and `(c_reindex : o → n)` reindexing the rows and columns of a matrix `M : matrix m n α`, the matrix `M.submatrix r_reindex c_reindex : matrix l o α` is defined by `(M.submatrix r_reindex c_reindex) i j = M (r_reindex i) (c_reindex j)` for `(i,j) : l × o`. Note that the total number of row and columns does not have to be preserved. -/ def submatrix (A : matrix m n α) (r_reindex : l → m) (c_reindex : o → n) : matrix l o α := of $ λ i j, A (r_reindex i) (c_reindex j) @[simp] lemma submatrix_apply (A : matrix m n α) (r_reindex : l → m) (c_reindex : o → n) (i j) : A.submatrix r_reindex c_reindex i j = A (r_reindex i) (c_reindex j) := rfl @[simp] lemma submatrix_id_id (A : matrix m n α) : A.submatrix id id = A := ext $ λ _ _, rfl @[simp] lemma submatrix_submatrix {l₂ o₂ : Type*} (A : matrix m n α) (r₁ : l → m) (c₁ : o → n) (r₂ : l₂ → l) (c₂ : o₂ → o) : (A.submatrix r₁ c₁).submatrix r₂ c₂ = A.submatrix (r₁ ∘ r₂) (c₁ ∘ c₂) := ext $ λ _ _, rfl @[simp] lemma transpose_submatrix (A : matrix m n α) (r_reindex : l → m) (c_reindex : o → n) : (A.submatrix r_reindex c_reindex)ᵀ = Aᵀ.submatrix c_reindex r_reindex := ext $ λ _ _, rfl @[simp] lemma conj_transpose_submatrix [has_star α] (A : matrix m n α) (r_reindex : l → m) (c_reindex : o → n) : (A.submatrix r_reindex c_reindex)ᴴ = Aᴴ.submatrix c_reindex r_reindex := ext $ λ _ _, rfl lemma submatrix_add [has_add α] (A B : matrix m n α) : ((A + B).submatrix : (l → m) → (o → n) → matrix l o α) = A.submatrix + B.submatrix := rfl lemma submatrix_neg [has_neg α] (A : matrix m n α) : ((-A).submatrix : (l → m) → (o → n) → matrix l o α) = -A.submatrix := rfl lemma submatrix_sub [has_sub α] (A B : matrix m n α) : ((A - B).submatrix : (l → m) → (o → n) → matrix l o α) = A.submatrix - B.submatrix := rfl @[simp] lemma submatrix_zero [has_zero α] : ((0 : matrix m n α).submatrix : (l → m) → (o → n) → matrix l o α) = 0 := rfl lemma submatrix_smul {R : Type*} [has_smul R α] (r : R) (A : matrix m n α) : ((r • A : matrix m n α).submatrix : (l → m) → (o → n) → matrix l o α) = r • A.submatrix := rfl lemma submatrix_map (f : α → β) (e₁ : l → m) (e₂ : o → n) (A : matrix m n α) : (A.map f).submatrix e₁ e₂ = (A.submatrix e₁ e₂).map f := rfl /-- Given a `(m × m)` diagonal matrix defined by a map `d : m → α`, if the reindexing map `e` is injective, then the resulting matrix is again diagonal. -/ lemma submatrix_diagonal [has_zero α] [decidable_eq m] [decidable_eq l] (d : m → α) (e : l → m) (he : function.injective e) : (diagonal d).submatrix e e = diagonal (d ∘ e) := ext $ λ i j, begin rw submatrix_apply, by_cases h : i = j, { rw [h, diagonal_apply_eq, diagonal_apply_eq], }, { rw [diagonal_apply_ne _ h, diagonal_apply_ne _ (he.ne h)], }, end lemma submatrix_one [has_zero α] [has_one α] [decidable_eq m] [decidable_eq l] (e : l → m) (he : function.injective e) : (1 : matrix m m α).submatrix e e = 1 := submatrix_diagonal _ e he lemma submatrix_mul [fintype n] [fintype o] [has_mul α] [add_comm_monoid α] {p q : Type*} (M : matrix m n α) (N : matrix n p α) (e₁ : l → m) (e₂ : o → n) (e₃ : q → p) (he₂ : function.bijective e₂) : (M ⬝ N).submatrix e₁ e₃ = (M.submatrix e₁ e₂) ⬝ (N.submatrix e₂ e₃) := ext $ λ _ _, (he₂.sum_comp _).symm lemma diag_submatrix (A : matrix m m α) (e : l → m) : diag (A.submatrix e e) = A.diag ∘ e := rfl /-! `simp` lemmas for `matrix.submatrix`s interaction with `matrix.diagonal`, `1`, and `matrix.mul` for when the mappings are bundled. -/ @[simp] lemma submatrix_diagonal_embedding [has_zero α] [decidable_eq m] [decidable_eq l] (d : m → α) (e : l ↪ m) : (diagonal d).submatrix e e = diagonal (d ∘ e) := submatrix_diagonal d e e.injective @[simp] lemma submatrix_diagonal_equiv [has_zero α] [decidable_eq m] [decidable_eq l] (d : m → α) (e : l ≃ m) : (diagonal d).submatrix e e = diagonal (d ∘ e) := submatrix_diagonal d e e.injective @[simp] lemma submatrix_one_embedding [has_zero α] [has_one α] [decidable_eq m] [decidable_eq l] (e : l ↪ m) : (1 : matrix m m α).submatrix e e = 1 := submatrix_one e e.injective @[simp] lemma submatrix_one_equiv [has_zero α] [has_one α] [decidable_eq m] [decidable_eq l] (e : l ≃ m) : (1 : matrix m m α).submatrix e e = 1 := submatrix_one e e.injective @[simp] lemma submatrix_mul_equiv [fintype n] [fintype o] [add_comm_monoid α] [has_mul α] {p q : Type*} (M : matrix m n α) (N : matrix n p α) (e₁ : l → m) (e₂ : o ≃ n) (e₃ : q → p) : (M.submatrix e₁ e₂) ⬝ (N.submatrix e₂ e₃) = (M ⬝ N).submatrix e₁ e₃ := (submatrix_mul M N e₁ e₂ e₃ e₂.bijective).symm lemma mul_submatrix_one [fintype n] [fintype o] [non_assoc_semiring α] [decidable_eq o] (e₁ : n ≃ o) (e₂ : l → o) (M : matrix m n α) : M ⬝ (1 : matrix o o α).submatrix e₁ e₂ = submatrix M id (e₁.symm ∘ e₂) := begin let A := M.submatrix id e₁.symm, have : M = A.submatrix id e₁, { simp only [submatrix_submatrix, function.comp.right_id, submatrix_id_id, equiv.symm_comp_self], }, rw [this, submatrix_mul_equiv], simp only [matrix.mul_one, submatrix_submatrix, function.comp.right_id, submatrix_id_id, equiv.symm_comp_self], end lemma one_submatrix_mul [fintype m] [fintype o] [non_assoc_semiring α] [decidable_eq o] (e₁ : l → o) (e₂ : m ≃ o) (M : matrix m n α) : ((1 : matrix o o α).submatrix e₁ e₂).mul M = submatrix M (e₂.symm ∘ e₁) id := begin let A := M.submatrix e₂.symm id, have : M = A.submatrix e₂ id, { simp only [submatrix_submatrix, function.comp.right_id, submatrix_id_id, equiv.symm_comp_self], }, rw [this, submatrix_mul_equiv], simp only [matrix.one_mul, submatrix_submatrix, function.comp.right_id, submatrix_id_id, equiv.symm_comp_self], end /-- The natural map that reindexes a matrix's rows and columns with equivalent types is an equivalence. -/ def reindex (eₘ : m ≃ l) (eₙ : n ≃ o) : matrix m n α ≃ matrix l o α := { to_fun := λ M, M.submatrix eₘ.symm eₙ.symm, inv_fun := λ M, M.submatrix eₘ eₙ, left_inv := λ M, by simp, right_inv := λ M, by simp, } @[simp] lemma reindex_apply (eₘ : m ≃ l) (eₙ : n ≃ o) (M : matrix m n α) : reindex eₘ eₙ M = M.submatrix eₘ.symm eₙ.symm := rfl @[simp] lemma reindex_refl_refl (A : matrix m n α) : reindex (equiv.refl _) (equiv.refl _) A = A := A.submatrix_id_id @[simp] lemma reindex_symm (eₘ : m ≃ l) (eₙ : n ≃ o) : (reindex eₘ eₙ).symm = (reindex eₘ.symm eₙ.symm : matrix l o α ≃ _) := rfl @[simp] lemma reindex_trans {l₂ o₂ : Type*} (eₘ : m ≃ l) (eₙ : n ≃ o) (eₘ₂ : l ≃ l₂) (eₙ₂ : o ≃ o₂) : (reindex eₘ eₙ).trans (reindex eₘ₂ eₙ₂) = (reindex (eₘ.trans eₘ₂) (eₙ.trans eₙ₂) : matrix m n α ≃ _) := equiv.ext $ λ A, (A.submatrix_submatrix eₘ.symm eₙ.symm eₘ₂.symm eₙ₂.symm : _) lemma transpose_reindex (eₘ : m ≃ l) (eₙ : n ≃ o) (M : matrix m n α) : (reindex eₘ eₙ M)ᵀ = (reindex eₙ eₘ Mᵀ) := rfl lemma conj_transpose_reindex [has_star α] (eₘ : m ≃ l) (eₙ : n ≃ o) (M : matrix m n α) : (reindex eₘ eₙ M)ᴴ = (reindex eₙ eₘ Mᴴ) := rfl @[simp] lemma submatrix_mul_transpose_submatrix [fintype m] [fintype n] [add_comm_monoid α] [has_mul α] (e : m ≃ n) (M : matrix m n α) : (M.submatrix id e) ⬝ (Mᵀ).submatrix e id = M ⬝ Mᵀ := by rw [submatrix_mul_equiv, submatrix_id_id] /-- The left `n × l` part of a `n × (l+r)` matrix. -/ @[reducible] def sub_left {m l r : nat} (A : matrix (fin m) (fin (l + r)) α) : matrix (fin m) (fin l) α := submatrix A id (fin.cast_add r) /-- The right `n × r` part of a `n × (l+r)` matrix. -/ @[reducible] def sub_right {m l r : nat} (A : matrix (fin m) (fin (l + r)) α) : matrix (fin m) (fin r) α := submatrix A id (fin.nat_add l) /-- The top `u × n` part of a `(u+d) × n` matrix. -/ @[reducible] def sub_up {d u n : nat} (A : matrix (fin (u + d)) (fin n) α) : matrix (fin u) (fin n) α := submatrix A (fin.cast_add d) id /-- The bottom `d × n` part of a `(u+d) × n` matrix. -/ @[reducible] def sub_down {d u n : nat} (A : matrix (fin (u + d)) (fin n) α) : matrix (fin d) (fin n) α := submatrix A (fin.nat_add u) id /-- The top-right `u × r` part of a `(u+d) × (l+r)` matrix. -/ @[reducible] def sub_up_right {d u l r : nat} (A: matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin u) (fin r) α := sub_up (sub_right A) /-- The bottom-right `d × r` part of a `(u+d) × (l+r)` matrix. -/ @[reducible] def sub_down_right {d u l r : nat} (A : matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin d) (fin r) α := sub_down (sub_right A) /-- The top-left `u × l` part of a `(u+d) × (l+r)` matrix. -/ @[reducible] def sub_up_left {d u l r : nat} (A : matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin u) (fin (l)) α := sub_up (sub_left A) /-- The bottom-left `d × l` part of a `(u+d) × (l+r)` matrix. -/ @[reducible] def sub_down_left {d u l r : nat} (A: matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin d) (fin (l)) α := sub_down (sub_left A) section row_col /-! ### `row_col` section Simplification lemmas for `matrix.row` and `matrix.col`. -/ open_locale matrix @[simp] lemma col_add [has_add α] (v w : m → α) : col (v + w) = col v + col w := by { ext, refl } @[simp] lemma col_smul [has_smul R α] (x : R) (v : m → α) : col (x • v) = x • col v := by { ext, refl } @[simp] lemma row_add [has_add α] (v w : m → α) : row (v + w) = row v + row w := by { ext, refl } @[simp] lemma row_smul [has_smul R α] (x : R) (v : m → α) : row (x • v) = x • row v := by { ext, refl } @[simp] lemma col_apply (v : m → α) (i j) : matrix.col v i j = v i := rfl @[simp] lemma row_apply (v : m → α) (i j) : matrix.row v i j = v j := rfl @[simp] lemma transpose_col (v : m → α) : (matrix.col v)ᵀ = matrix.row v := by { ext, refl } @[simp] lemma transpose_row (v : m → α) : (matrix.row v)ᵀ = matrix.col v := by { ext, refl } @[simp] lemma conj_transpose_col [has_star α] (v : m → α) : (col v)ᴴ = row (star v) := by { ext, refl } @[simp] lemma conj_transpose_row [has_star α] (v : m → α) : (row v)ᴴ = col (star v) := by { ext, refl } lemma row_vec_mul [fintype m] [non_unital_non_assoc_semiring α] (M : matrix m n α) (v : m → α) : matrix.row (matrix.vec_mul v M) = matrix.row v ⬝ M := by {ext, refl} lemma col_vec_mul [fintype m] [non_unital_non_assoc_semiring α] (M : matrix m n α) (v : m → α) : matrix.col (matrix.vec_mul v M) = (matrix.row v ⬝ M)ᵀ := by {ext, refl} lemma col_mul_vec [fintype n] [non_unital_non_assoc_semiring α] (M : matrix m n α) (v : n → α) : matrix.col (matrix.mul_vec M v) = M ⬝ matrix.col v := by {ext, refl} lemma row_mul_vec [fintype n] [non_unital_non_assoc_semiring α] (M : matrix m n α) (v : n → α) : matrix.row (matrix.mul_vec M v) = (M ⬝ matrix.col v)ᵀ := by {ext, refl} @[simp] lemma row_mul_col_apply [fintype m] [has_mul α] [add_comm_monoid α] (v w : m → α) (i j) : (row v ⬝ col w) i j = v ⬝ᵥ w := rfl end row_col section update /-- Update, i.e. replace the `i`th row of matrix `A` with the values in `b`. -/ def update_row [decidable_eq m] (M : matrix m n α) (i : m) (b : n → α) : matrix m n α := function.update M i b /-- Update, i.e. replace the `j`th column of matrix `A` with the values in `b`. -/ def update_column [decidable_eq n] (M : matrix m n α) (j : n) (b : m → α) : matrix m n α := λ i, function.update (M i) j (b i) variables {M : matrix m n α} {i : m} {j : n} {b : n → α} {c : m → α} @[simp] lemma update_row_self [decidable_eq m] : update_row M i b i = b := function.update_same i b M @[simp] lemma update_column_self [decidable_eq n] : update_column M j c i j = c i := function.update_same j (c i) (M i) @[simp] lemma update_row_ne [decidable_eq m] {i' : m} (i_ne : i' ≠ i) : update_row M i b i' = M i' := function.update_noteq i_ne b M @[simp] lemma update_column_ne [decidable_eq n] {j' : n} (j_ne : j' ≠ j) : update_column M j c i j' = M i j' := function.update_noteq j_ne (c i) (M i) lemma update_row_apply [decidable_eq m] {i' : m} : update_row M i b i' j = if i' = i then b j else M i' j := begin by_cases i' = i, { rw [h, update_row_self, if_pos rfl] }, { rwa [update_row_ne h, if_neg h] } end lemma update_column_apply [decidable_eq n] {j' : n} : update_column M j c i j' = if j' = j then c i else M i j' := begin by_cases j' = j, { rw [h, update_column_self, if_pos rfl] }, { rwa [update_column_ne h, if_neg h] } end @[simp] lemma update_column_subsingleton [subsingleton n] (A : matrix m n R) (i : n) (b : m → R) : A.update_column i b = (col b).submatrix id (function.const n ()) := begin ext x y, simp [update_column_apply, subsingleton.elim i y] end @[simp] lemma update_row_subsingleton [subsingleton m] (A : matrix m n R) (i : m) (b : n → R) : A.update_row i b = (row b).submatrix (function.const m ()) id := begin ext x y, simp [update_column_apply, subsingleton.elim i x] end lemma map_update_row [decidable_eq m] (f : α → β) : map (update_row M i b) f = update_row (M.map f) i (f ∘ b) := begin ext i' j', rw [update_row_apply, map_apply, map_apply, update_row_apply], exact apply_ite f _ _ _, end lemma map_update_column [decidable_eq n] (f : α → β) : map (update_column M j c) f = update_column (M.map f) j (f ∘ c) := begin ext i' j', rw [update_column_apply, map_apply, map_apply, update_column_apply], exact apply_ite f _ _ _, end lemma update_row_transpose [decidable_eq n] : update_row Mᵀ j c = (update_column M j c)ᵀ := begin ext i' j, rw [transpose_apply, update_row_apply, update_column_apply], refl end lemma update_column_transpose [decidable_eq m] : update_column Mᵀ i b = (update_row M i b)ᵀ := begin ext i' j, rw [transpose_apply, update_row_apply, update_column_apply], refl end lemma update_row_conj_transpose [decidable_eq n] [has_star α] : update_row Mᴴ j (star c) = (update_column M j c)ᴴ := begin rw [conj_transpose, conj_transpose, transpose_map, transpose_map, update_row_transpose, map_update_column], refl, end lemma update_column_conj_transpose [decidable_eq m] [has_star α] : update_column Mᴴ i (star b) = (update_row M i b)ᴴ := begin rw [conj_transpose, conj_transpose, transpose_map, transpose_map, update_column_transpose, map_update_row], refl, end @[simp] lemma update_row_eq_self [decidable_eq m] (A : matrix m n α) (i : m) : A.update_row i (A i) = A := function.update_eq_self i A @[simp] lemma update_column_eq_self [decidable_eq n] (A : matrix m n α) (i : n) : A.update_column i (λ j, A j i) = A := funext $ λ j, function.update_eq_self i (A j) lemma diagonal_update_column_single [decidable_eq n] [has_zero α] (v : n → α) (i : n) (x : α): (diagonal v).update_column i (pi.single i x) = diagonal (function.update v i x) := begin ext j k, obtain rfl | hjk := eq_or_ne j k, { rw [diagonal_apply_eq], obtain rfl | hji := eq_or_ne j i, { rw [update_column_self, pi.single_eq_same, function.update_same], }, { rw [update_column_ne hji, diagonal_apply_eq, function.update_noteq hji], } }, { rw [diagonal_apply_ne _ hjk], obtain rfl | hki := eq_or_ne k i, { rw [update_column_self, pi.single_eq_of_ne hjk] }, { rw [update_column_ne hki, diagonal_apply_ne _ hjk] } } end lemma diagonal_update_row_single [decidable_eq n] [has_zero α] (v : n → α) (i : n) (x : α): (diagonal v).update_row i (pi.single i x) = diagonal (function.update v i x) := by rw [←diagonal_transpose, update_row_transpose, diagonal_update_column_single, diagonal_transpose] end update end matrix namespace ring_hom variables [fintype n] [non_assoc_semiring α] [non_assoc_semiring β] lemma map_matrix_mul (M : matrix m n α) (N : matrix n o α) (i : m) (j : o) (f : α →+* β) : f (matrix.mul M N i j) = matrix.mul (M.map f) (N.map f) i j := by simp [matrix.mul_apply, ring_hom.map_sum] lemma map_dot_product [non_assoc_semiring R] [non_assoc_semiring S] (f : R →+* S) (v w : n → R) : f (v ⬝ᵥ w) = (f ∘ v) ⬝ᵥ (f ∘ w) := by simp only [matrix.dot_product, f.map_sum, f.map_mul] lemma map_vec_mul [non_assoc_semiring R] [non_assoc_semiring S] (f : R →+* S) (M : matrix n m R) (v : n → R) (i : m) : f (M.vec_mul v i) = ((M.map f).vec_mul (f ∘ v) i) := by simp only [matrix.vec_mul, matrix.map_apply, ring_hom.map_dot_product] lemma map_mul_vec [non_assoc_semiring R] [non_assoc_semiring S] (f : R →+* S) (M : matrix m n R) (v : n → R) (i : m) : f (M.mul_vec v i) = ((M.map f).mul_vec (f ∘ v) i) := by simp only [matrix.mul_vec, matrix.map_apply, ring_hom.map_dot_product] end ring_hom
ccf2fd2922dad4690d0384a24ea08195b7ad4fc6
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/abelian/opposite.lean
745571ee4c297c20f5c6bc4d2ff6b73cfe1242a5
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
1,004
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 category_theory.abelian.basic import category_theory.preadditive.opposite import category_theory.limits.opposites import category_theory.limits.constructions.limits_of_products_and_equalizers /-! # The opposite of an abelian category is abelian. -/ namespace category_theory open category_theory.limits variables (C : Type*) [category C] [abelian C] local attribute [instance] finite_limits_from_equalizers_and_finite_products finite_colimits_from_coequalizers_and_finite_coproducts has_finite_limits_opposite has_finite_colimits_opposite has_finite_products_opposite instance : abelian Cᵒᵖ := { normal_mono := λ X Y f m, by exactI normal_mono_of_normal_epi_unop _ (abelian.normal_epi f.unop), normal_epi := λ X Y f m, by exactI normal_epi_of_normal_mono_unop _ (abelian.normal_mono f.unop), } end category_theory
44b1e48ad85e642900c9f2fd9c6daede2cc51cba
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/interactive/haveInfo.lean
9f83f27bc0c2915967574bcc1714afe5d9a02d7a
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
391
lean
example : False := by have : True := by skip --^ $/lean/plainGoal skip admit example : False := by have : True := by --^ $/lean/plainGoal skip skip admit example : False := by have : True := by --^ $/lean/plainGoal skip skip admit example : False := by have : True := by skip --^ $/lean/plainGoal skip admit
7abfd9bade45fae446a1fbd17be1ea94c843687f
d406927ab5617694ec9ea7001f101b7c9e3d9702
/test/localized/localized.lean
07fad09ff60b7905ee6301121127e83e71482174
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
1,484
lean
import tactic.localized import algebra.group_power open tactic local infix ` ⊹ `:59 := nat.mul local infix ` ↓ `:59 := pow local infix ` ⊖ `:59 := pow example : 2 ⊹ 3 = 6 := rfl example : 2 ↓ 3 = 8 := rfl example : 2 ⊖ 3 = 8 := rfl example {n m : ℕ} (h : n < m) : n ≤ m := by { success_if_fail { simp [h] }, exact le_of_lt h } section localized "infix (name := plus) ` ⊹ `:59 := nat.add" in nat localized "infix (name := down) ` ↓ `:59 := nat.mul" in nat localized "infix (name := minus) ` ⊖ `:59 := nat.mul" in nat.mul localized "attribute [simp] le_of_lt" in le example : 2 ⊹ 3 = 5 := rfl example : 2 ↓ 3 = 6 := rfl example : 2 ⊖ 3 = 6 := rfl example {n m : ℕ} (h : n < m) : n ≤ m := by { simp [h] } end section example : 2 ⊹ 3 = 6 := rfl example : 2 ↓ 3 = 8 := rfl example : 2 ⊖ 3 = 8 := rfl example {n m : ℕ} (h : n < m) : n ≤ m := by { success_if_fail { simp [h] }, exact le_of_lt h } -- test that `open_locale` will fail when given a nonexistent locale run_cmd success_if_fail $ get_localized [`ceci_nest_pas_une_locale] open_locale nat example : 2 ⊹ 3 = 5 := rfl example : 2 ↓ 3 = 6 := rfl example : 2 ⊖ 3 = 8 := rfl open_locale nat.mul example : 2 ⊹ 3 = 5 := rfl example : 2 ↓ 3 = 6 := rfl example : 2 ⊖ 3 = 6 := rfl end section open_locale nat.mul nat nat.mul le example : 2 ⊹ 3 = 5 := rfl example : 2 ↓ 3 = 6 := rfl example : 2 ⊖ 3 = 6 := rfl example {n m : ℕ} (h : n < m) : n ≤ m := by { simp [h] } end
8bed1649afed8df8bd395ee148bc40545cad1963
88fb7558b0636ec6b181f2a548ac11ad3919f8a5
/library/tools/super/utils.lean
7455e6197353c8f07c39e2c074648fe34190764c
[ "Apache-2.0" ]
permissive
moritayasuaki/lean
9f666c323cb6fa1f31ac597d777914aed41e3b7a
ae96ebf6ee953088c235ff7ae0e8c95066ba8001
refs/heads/master
1,611,135,440,814
1,493,852,869,000
1,493,852,869,000
90,269,903
0
0
null
1,493,906,291,000
1,493,906,291,000
null
UTF-8
Lean
false
false
5,044
lean
/- Copyright (c) 2016 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ open tactic expr list meta def get_metas : expr → list expr | (var _) := [] | (sort _) := [] | (const _ _) := [] | (mvar n t) := expr.mvar n t :: get_metas t | (local_const _ _ _ t) := get_metas t | (app a b) := get_metas a ++ get_metas b | (lam _ _ d b) := get_metas d ++ get_metas b | (pi _ _ d b) := get_metas d ++ get_metas b | (elet _ t v b) := get_metas t ++ get_metas v ++ get_metas b | (macro _ _ _) := [] meta def get_meta_type : expr → expr | (mvar _ t) := t | _ := mk_var 0 -- TODO(gabriel): think about how to handle the avalanche of implicit arguments meta def expr_size : expr → nat | (var _) := 1 | (sort _) := 1 | (const _ _) := 1 | (mvar n t) := 1 | (local_const _ _ _ _) := 1 | (app a b) := expr_size a + expr_size b | (lam _ _ d b) := 1 + expr_size b | (pi _ _ d b) := 1 + expr_size b | (elet _ t v b) := 1 + expr_size v + expr_size b | (macro _ _ _) := 1 namespace ordering def is_lt {A} [has_ordering A] (x y : A) : bool := match has_ordering.cmp x y with ordering.lt := tt | _ := ff end end ordering namespace list meta def nub {A} [has_ordering A] (l : list A) : list A := rb_map.keys (rb_map.set_of_list l) meta def nub_on {A B} [has_ordering B] (f : A → B) (l : list A) : list A := rb_map.values (rb_map.of_list (map (λx, (f x, x)) l)) def nub_on' {A B} [decidable_eq B] (f : A → B) : list A → list A | [] := [] | (x::xs) := x :: filter (λy, f x ≠ f y) (nub_on' xs) def for_all {A} (l : list A) (p : A → Prop) [decidable_pred p] : bool := list.all l (λx, to_bool (p x)) def exists_ {A} (l : list A) (p : A → Prop) [decidable_pred p] : bool := list.any l (λx, to_bool (p x)) def subset_of {A} [decidable_eq A] (xs ys : list A) := xs.for_all (λx, x ∈ ys) def filter_maximal {A} (gt : A → A → bool) (l : list A) : list A := filter (λx, l.for_all (λy, ¬gt y x)) l private def zip_with_index' {A} : ℕ → list A → list (A × ℕ) | _ nil := nil | i (x::xs) := (x,i) :: zip_with_index' (i+1) xs def zip_with_index {A} : list A → list (A × ℕ) := zip_with_index' 0 def partition {A} (pred : A → Prop) [decidable_pred pred] : list A → list A × list A | (x::xs) := match partition xs with (ts,fs) := if pred x then (x::ts, fs) else (ts, x::fs) end | [] := ([],[]) meta def merge_sorted {A} [has_ordering A] : list A → list A → list A | [] ys := ys | xs [] := xs | (x::xs) (y::ys) := if ordering.is_lt x y then x :: merge_sorted xs (y::ys) else y :: merge_sorted (x::xs) ys meta def sort {A} [has_ordering A] : list A → list A | (x::xs) := let (smaller, greater_eq) := partition (λy, ordering.is_lt y x) xs in merge_sorted (sort smaller) (x :: sort greater_eq) | [] := [] meta def sort_on {A B} (f : A → B) [has_ordering B] : list A → list A := @sort _ ⟨λx y, has_ordering.cmp (f x) (f y)⟩ end list meta def name_of_funsym : expr → name | (local_const uniq _ _ _) := uniq | (const n _) := n | _ := name.anonymous private meta def contained_funsyms' : expr → rb_map name expr → rb_map name expr | (var _) m := m | (sort _) m := m | (const n ls) m := rb_map.insert m n (const n ls) | (mvar _ t) m := contained_funsyms' t m | (local_const uniq pp bi t) m := rb_map.insert m uniq (local_const uniq pp bi t) | (app a b) m := contained_funsyms' a (contained_funsyms' b m) | (lam _ _ d b) m := contained_funsyms' d (contained_funsyms' b m) | (pi _ _ d b) m := contained_funsyms' d (contained_funsyms' b m) | (elet _ t v b) m := contained_funsyms' t (contained_funsyms' v (contained_funsyms' b m)) | (macro _ _ _) m := m meta def contained_funsyms (e : expr) : rb_map name expr := contained_funsyms' e (rb_map.mk name expr) private meta def contained_lconsts' : expr → rb_map name expr → rb_map name expr | (var _) m := m | (sort _) m := m | (const _ _) m := m | (mvar _ t) m := contained_lconsts' t m | (local_const uniq pp bi t) m := contained_lconsts' t (rb_map.insert m uniq (local_const uniq pp bi t)) | (app a b) m := contained_lconsts' a (contained_lconsts' b m) | (lam _ _ d b) m := contained_lconsts' d (contained_lconsts' b m) | (pi _ _ d b) m := contained_lconsts' d (contained_lconsts' b m) | (elet _ t v b) m := contained_lconsts' t (contained_lconsts' v (contained_lconsts' b m)) | (macro _ _ _) m := m meta def contained_lconsts (e : expr) : rb_map name expr := contained_lconsts' e (rb_map.mk name expr) meta def contained_lconsts_list (es : list expr) : rb_map name expr := es.foldl (λlcs e, contained_lconsts' e lcs) (rb_map.mk name expr) namespace tactic meta def infer_univ (type : expr) : tactic level := do sort_of_type ← infer_type type >>= whnf, match sort_of_type with | sort lvl := return lvl | not_sort := do fmt ← pp not_sort, fail $ to_fmt "cannot get universe level of sort: " ++ fmt end end tactic namespace nat def min (m n : ℕ) := if m < n then m else n def max (m n : ℕ) := if m > n then m else n end nat
aef05637032225bec3bc0030104433120e847c53
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/03_Propositions_and_Proofs.org.13.lean
3cbb34f140b11a4bda0a0c36eebd7ad12eb508bb
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
350
lean
/- page 37 -/ import standard theorem t1 (p q : Prop) (Hp : p) (Hq : q) : p := Hp variables p q r s : Prop check t1 p q -- p → q → p check t1 r s -- r → s → r check t1 (r → s) (s → r) -- (r → s) → (s → r) → r → s variable H : r → s check t1 (r → s) (s → r) H -- (s → r) → r → s